1pub(crate) mod hooks;
8pub(crate) mod progress_options;
9
10use std::{
11 collections::BTreeMap,
12 fmt::{self, Display, Formatter},
13 path::PathBuf,
14};
15
16use abscissa_core::{FrameworkError, FrameworkErrorKind, config::Config, path::AbsPathBuf};
17use anyhow::{Result, anyhow};
18use clap::{Parser, ValueHint};
19use conflate::Merge;
20use directories::ProjectDirs;
21use itertools::Itertools;
22use log::Level;
23use reqwest::Url;
24use rustic_core::SnapshotGroupCriterion;
25use serde::{Deserialize, Serialize};
26use serde_with::{DisplayFromStr, serde_as};
27#[cfg(not(all(feature = "mount", feature = "webdav")))]
28use toml::Value;
29
30#[cfg(feature = "mount")]
31use crate::commands::mount::MountCmd;
32#[cfg(feature = "webdav")]
33use crate::commands::webdav::WebDavCmd;
34
35use crate::{
36 commands::{backup::BackupCmd, copy::CopyCmd, forget::ForgetOptions},
37 config::{hooks::Hooks, progress_options::ProgressOptions},
38 filtering::SnapshotFilter,
39 repository::AllRepositoryOptions,
40};
41
42#[derive(Clone, Default, Debug, Parser, Deserialize, Serialize, Merge)]
49#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
50pub struct RusticConfig {
51 #[clap(flatten, next_help_heading = "Global options")]
53 pub global: GlobalOptions,
54
55 #[clap(flatten, next_help_heading = "Repository options")]
57 pub repository: AllRepositoryOptions,
58
59 #[clap(flatten, next_help_heading = "Snapshot filter options")]
61 pub snapshot_filter: SnapshotFilter,
62
63 #[clap(skip)]
65 pub backup: BackupCmd,
66
67 #[clap(skip)]
69 pub copy: CopyCmd,
70
71 #[clap(skip)]
73 pub forget: ForgetOptions,
74
75 #[cfg(feature = "mount")]
77 #[clap(skip)]
78 pub mount: MountCmd,
79 #[cfg(not(feature = "mount"))]
80 #[clap(skip)]
81 #[merge(skip)]
82 pub mount: Option<Value>,
83
84 #[cfg(feature = "webdav")]
86 #[clap(skip)]
87 pub webdav: WebDavCmd,
88 #[cfg(not(feature = "webdav"))]
89 #[clap(skip)]
90 #[merge(skip)]
91 pub webdav: Option<Value>,
92}
93
94impl Display for RusticConfig {
95 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
96 let config = toml::to_string_pretty(self)
97 .unwrap_or_else(|_| "<Error serializing config>".to_string());
98
99 write!(f, "{config}",)
100 }
101}
102
103impl RusticConfig {
104 pub fn merge_profile(
113 &mut self,
114 profile: &str,
115 merge_logs: &mut Vec<(Level, String)>,
116 level_missing: Level,
117 ) -> Result<(), FrameworkError> {
118 let profile_filename = profile.to_string() + ".toml";
119 let paths = get_config_paths(&profile_filename);
120
121 if let Some(path) = paths.iter().find(|path| path.exists()) {
122 merge_logs.push((Level::Info, format!("using config {}", path.display())));
123 let config_content = subst::substitute(
124 &std::fs::read_to_string(AbsPathBuf::canonicalize(path)?)?,
125 &subst::Env,
126 )
127 .map_err(|e| {
128 abscissa_core::error::context::Context::new(
129 FrameworkErrorKind::ParseError,
130 Some(Box::new(e)),
131 )
132 })?;
133 let mut config = Self::load_toml(config_content)?;
134 for profile in &config.global.use_profiles.clone() {
136 config.merge_profile(profile, merge_logs, Level::Warn)?;
137 }
138 self.merge(config);
139 } else {
140 let paths_string = paths.iter().map(|path| path.display()).join(", ");
141 merge_logs.push((
142 level_missing,
143 format!(
144 "using no config file, none of these exist: {}",
145 &paths_string
146 ),
147 ));
148 };
149 Ok(())
150 }
151}
152
153#[serde_as]
157#[derive(Default, Debug, Parser, Clone, Deserialize, Serialize, Merge)]
158#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
159pub struct GlobalOptions {
160 #[clap(
163 short = 'P',
164 long = "use-profile",
165 global = true,
166 value_name = "PROFILE",
167 env = "RUSTIC_USE_PROFILE"
168 )]
169 #[merge(strategy=conflate::vec::append)]
170 pub use_profiles: Vec<String>,
171
172 #[clap(
174 long,
175 short = 'g',
176 global = true,
177 value_name = "CRITERION",
178 env = "RUSTIC_GROUP_BY"
179 )]
180 #[serde_as(as = "Option<DisplayFromStr>")]
181 #[merge(strategy=conflate::option::overwrite_none)]
182 pub group_by: Option<SnapshotGroupCriterion>,
183
184 #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
186 #[merge(strategy=conflate::bool::overwrite_false)]
187 pub dry_run: bool,
188
189 #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
191 #[merge(strategy=conflate::bool::overwrite_false)]
192 pub check_index: bool,
193
194 #[clap(long, global = true, env = "RUSTIC_LOG_LEVEL")]
196 #[merge(strategy=conflate::option::overwrite_none)]
197 pub log_level: Option<String>,
198
199 #[clap(long, global = true, env = "RUSTIC_LOG_FILE", value_name = "LOGFILE", value_hint = ValueHint::FilePath)]
205 #[merge(strategy=conflate::option::overwrite_none)]
206 pub log_file: Option<PathBuf>,
207
208 #[clap(flatten)]
210 #[serde(flatten)]
211 pub progress_options: ProgressOptions,
212
213 #[clap(skip)]
215 pub hooks: Hooks,
216
217 #[clap(skip)]
219 #[merge(strategy = conflate::btreemap::append_or_ignore)]
220 pub env: BTreeMap<String, String>,
221
222 #[serde_as(as = "Option<DisplayFromStr>")]
224 #[clap(long, global = true, env = "RUSTIC_PROMETHEUS", value_name = "PUSHGATEWAY_URL", value_hint = ValueHint::Url)]
225 #[merge(strategy=conflate::option::overwrite_none)]
226 pub prometheus: Option<Url>,
227
228 #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
230 #[merge(strategy=conflate::option::overwrite_none)]
231 pub prometheus_user: Option<String>,
232
233 #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
235 #[merge(strategy=conflate::option::overwrite_none)]
236 pub prometheus_pass: Option<String>,
237
238 #[clap(skip)]
240 #[merge(strategy=conflate::btreemap::append_or_ignore)]
241 pub metrics_labels: BTreeMap<String, String>,
242
243 #[serde_as(as = "Option<DisplayFromStr>")]
245 #[clap(long, global = true, env = "RUSTIC_OTEL", value_name = "ENDPOINT_URL", value_hint = ValueHint::Url)]
246 #[merge(strategy=conflate::option::overwrite_none)]
247 pub opentelemetry: Option<Url>,
248}
249
250pub fn parse_labels(s: &str) -> Result<BTreeMap<String, String>> {
251 s.split(',')
252 .filter_map(|s| {
253 let s = s.trim();
254 (!s.is_empty()).then_some(s)
255 })
256 .map(|s| -> Result<_> {
257 let pos = s.find('=').ok_or_else(|| {
258 anyhow!("invalid prometheus label definition: no `=` found in `{s}`")
259 })?;
260 Ok((s[..pos].to_owned(), s[pos + 1..].to_owned()))
261 })
262 .try_collect()
263}
264
265impl GlobalOptions {
266 pub fn is_metrics_configured(&self) -> bool {
267 self.prometheus.is_some() || self.opentelemetry.is_some()
268 }
269}
270
271fn get_config_paths(filename: &str) -> Vec<PathBuf> {
281 [
282 ProjectDirs::from("", "", "rustic")
283 .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
284 get_global_config_path(),
285 Some(PathBuf::from(".")),
286 ]
287 .into_iter()
288 .filter_map(|path| {
289 path.map(|mut p| {
290 p.push(filename);
291 p
292 })
293 })
294 .collect()
295}
296
297#[cfg(target_os = "windows")]
304fn get_global_config_path() -> Option<PathBuf> {
305 std::env::var_os("PROGRAMDATA").map(|program_data| {
306 let mut path = PathBuf::from(program_data);
307 path.push(r"rustic\config");
308 path
309 })
310}
311
312#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
318fn get_global_config_path() -> Option<PathBuf> {
319 None
320}
321
322#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
329fn get_global_config_path() -> Option<PathBuf> {
330 Some(PathBuf::from("/etc/rustic"))
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use insta::{assert_debug_snapshot, assert_snapshot};
337
338 #[test]
339 fn test_default_config_passes() {
340 let config = RusticConfig::default();
341
342 assert_debug_snapshot!(config);
343 }
344
345 #[test]
346 fn test_default_config_display_passes() {
347 let config = RusticConfig::default();
348
349 assert_snapshot!(config);
350 }
351
352 #[test]
353 fn test_global_env_roundtrip_passes() {
354 let mut config = RusticConfig::default();
355
356 for i in 0..10 {
357 let _ = config
358 .global
359 .env
360 .insert(format!("KEY{i}"), format!("VALUE{i}"));
361 }
362
363 let serialized = toml::to_string(&config).unwrap();
364
365 assert_snapshot!(serialized);
367
368 let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
369 assert_snapshot!(deserialized);
371
372 assert_debug_snapshot!(deserialized);
374 }
375}