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 = std::fs::read_to_string(AbsPathBuf::canonicalize(path)?)?;
124 let config_content = if self.global.profile_substitute_env {
125 subst::substitute(&config_content, &subst::Env).map_err(|e| {
126 abscissa_core::error::context::Context::new(
127 FrameworkErrorKind::ParseError,
128 Some(Box::new(e)),
129 )
130 })?
131 } else {
132 config_content
133 };
134 let mut config = Self::load_toml(config_content)?;
135 for profile in &config.global.use_profiles.clone() {
137 config.merge_profile(profile, merge_logs, Level::Warn)?;
138 }
139 self.merge(config);
140 } else {
141 let paths_string = paths.iter().map(|path| path.display()).join(", ");
142 merge_logs.push((
143 level_missing,
144 format!(
145 "using no config file, none of these exist: {}",
146 &paths_string
147 ),
148 ));
149 };
150 Ok(())
151 }
152}
153
154#[serde_as]
158#[derive(Default, Debug, Parser, Clone, Deserialize, Serialize, Merge)]
159#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
160pub struct GlobalOptions {
161 #[clap(long, global = true, env = "RUSTIC_PROFILE_SUBSTITUTE_ENV")]
163 #[merge(strategy=conflate::bool::overwrite_false)]
164 pub profile_substitute_env: bool,
165
166 #[clap(
169 short = 'P',
170 long = "use-profile",
171 global = true,
172 value_name = "PROFILE",
173 env = "RUSTIC_USE_PROFILE"
174 )]
175 #[merge(strategy=conflate::vec::append)]
176 pub use_profiles: Vec<String>,
177
178 #[clap(
180 long,
181 short = 'g',
182 global = true,
183 value_name = "CRITERION",
184 env = "RUSTIC_GROUP_BY"
185 )]
186 #[serde_as(as = "Option<DisplayFromStr>")]
187 #[merge(strategy=conflate::option::overwrite_none)]
188 pub group_by: Option<SnapshotGroupCriterion>,
189
190 #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
192 #[merge(strategy=conflate::bool::overwrite_false)]
193 pub dry_run: bool,
194
195 #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
197 #[merge(strategy=conflate::bool::overwrite_false)]
198 pub check_index: bool,
199
200 #[clap(long, global = true, env = "RUSTIC_LOG_LEVEL")]
202 #[merge(strategy=conflate::option::overwrite_none)]
203 pub log_level: Option<String>,
204
205 #[clap(long, global = true, env = "RUSTIC_LOG_FILE", value_name = "LOGFILE", value_hint = ValueHint::FilePath)]
211 #[merge(strategy=conflate::option::overwrite_none)]
212 pub log_file: Option<PathBuf>,
213
214 #[clap(flatten)]
216 #[serde(flatten)]
217 pub progress_options: ProgressOptions,
218
219 #[clap(skip)]
221 pub hooks: Hooks,
222
223 #[clap(skip)]
225 #[merge(strategy = conflate::btreemap::append_or_ignore)]
226 pub env: BTreeMap<String, String>,
227
228 #[serde_as(as = "Option<DisplayFromStr>")]
230 #[clap(long, global = true, env = "RUSTIC_PROMETHEUS", value_name = "PUSHGATEWAY_URL", value_hint = ValueHint::Url)]
231 #[merge(strategy=conflate::option::overwrite_none)]
232 pub prometheus: Option<Url>,
233
234 #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
236 #[merge(strategy=conflate::option::overwrite_none)]
237 pub prometheus_user: Option<String>,
238
239 #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
241 #[merge(strategy=conflate::option::overwrite_none)]
242 pub prometheus_pass: Option<String>,
243
244 #[clap(skip)]
246 #[merge(strategy=conflate::btreemap::append_or_ignore)]
247 pub metrics_labels: BTreeMap<String, String>,
248
249 #[serde_as(as = "Option<DisplayFromStr>")]
251 #[clap(long, global = true, env = "RUSTIC_OTEL", value_name = "ENDPOINT_URL", value_hint = ValueHint::Url)]
252 #[merge(strategy=conflate::option::overwrite_none)]
253 pub opentelemetry: Option<Url>,
254}
255
256pub fn parse_labels(s: &str) -> Result<BTreeMap<String, String>> {
257 s.split(',')
258 .filter_map(|s| {
259 let s = s.trim();
260 (!s.is_empty()).then_some(s)
261 })
262 .map(|s| -> Result<_> {
263 let pos = s.find('=').ok_or_else(|| {
264 anyhow!("invalid prometheus label definition: no `=` found in `{s}`")
265 })?;
266 Ok((s[..pos].to_owned(), s[pos + 1..].to_owned()))
267 })
268 .try_collect()
269}
270
271impl GlobalOptions {
272 pub fn is_metrics_configured(&self) -> bool {
273 self.prometheus.is_some() || self.opentelemetry.is_some()
274 }
275}
276
277fn get_config_paths(filename: &str) -> Vec<PathBuf> {
287 [
288 ProjectDirs::from("", "", "rustic")
289 .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
290 get_global_config_path(),
291 Some(PathBuf::from(".")),
292 ]
293 .into_iter()
294 .filter_map(|path| {
295 path.map(|mut p| {
296 p.push(filename);
297 p
298 })
299 })
300 .collect()
301}
302
303#[cfg(target_os = "windows")]
310fn get_global_config_path() -> Option<PathBuf> {
311 std::env::var_os("PROGRAMDATA").map(|program_data| {
312 let mut path = PathBuf::from(program_data);
313 path.push(r"rustic\config");
314 path
315 })
316}
317
318#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
324fn get_global_config_path() -> Option<PathBuf> {
325 None
326}
327
328#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
335fn get_global_config_path() -> Option<PathBuf> {
336 Some(PathBuf::from("/etc/rustic"))
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use insta::{assert_debug_snapshot, assert_snapshot};
343
344 #[test]
345 fn test_default_config_passes() {
346 let config = RusticConfig::default();
347
348 assert_debug_snapshot!(config);
349 }
350
351 #[test]
352 fn test_default_config_display_passes() {
353 let config = RusticConfig::default();
354
355 assert_snapshot!(config);
356 }
357
358 #[test]
359 fn test_global_env_roundtrip_passes() {
360 let mut config = RusticConfig::default();
361
362 for i in 0..10 {
363 let _ = config
364 .global
365 .env
366 .insert(format!("KEY{i}"), format!("VALUE{i}"));
367 }
368
369 let serialized = toml::to_string(&config).unwrap();
370
371 assert_snapshot!(serialized);
373
374 let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
375 assert_snapshot!(deserialized);
377
378 assert_debug_snapshot!(deserialized);
380 }
381}