1pub(crate) mod hooks;
8pub(crate) mod logging;
9pub(crate) mod progress_options;
10
11use std::{
12 collections::BTreeMap,
13 fmt::{self, Display, Formatter},
14 path::PathBuf,
15};
16
17use abscissa_core::{FrameworkError, FrameworkErrorKind, config::Config, path::AbsPathBuf};
18use anyhow::{Result, anyhow};
19use clap::{Parser, ValueHint};
20use conflate::Merge;
21use directories::ProjectDirs;
22use itertools::Itertools;
23use jiff::{Timestamp, Zoned, tz::TimeZone};
24use log::Level;
25use reqwest::Url;
26use rustic_core::SnapshotGroupCriterion;
27use serde::{Deserialize, Serialize};
28use serde_with::{DisplayFromStr, serde_as};
29#[cfg(not(all(feature = "mount", feature = "webdav")))]
30use toml::Value;
31
32#[cfg(feature = "mount")]
33use crate::commands::mount::MountCmd;
34#[cfg(feature = "webdav")]
35use crate::commands::webdav::WebDavCmd;
36
37use crate::{
38 commands::{backup::BackupCmd, copy::CopyCmd, forget::ForgetOptions},
39 config::{hooks::Hooks, logging::LoggingOptions, progress_options::ProgressOptions},
40 filtering::SnapshotFilter,
41 repository::AllRepositoryOptions,
42};
43
44#[derive(Clone, Default, Debug, Parser, Deserialize, Serialize, Merge)]
51#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
52pub struct RusticConfig {
53 #[clap(flatten, next_help_heading = "Global options")]
55 pub global: GlobalOptions,
56
57 #[clap(flatten, next_help_heading = "Repository options")]
59 pub repository: AllRepositoryOptions,
60
61 #[clap(flatten, next_help_heading = "Snapshot filter options")]
63 pub snapshot_filter: SnapshotFilter,
64
65 #[clap(skip)]
67 pub backup: BackupCmd,
68
69 #[clap(skip)]
71 pub copy: CopyCmd,
72
73 #[clap(skip)]
75 pub forget: ForgetOptions,
76
77 #[cfg(feature = "mount")]
79 #[clap(skip)]
80 pub mount: MountCmd,
81 #[cfg(not(feature = "mount"))]
82 #[clap(skip)]
83 #[merge(skip)]
84 pub mount: Option<Value>,
85
86 #[cfg(feature = "webdav")]
88 #[clap(skip)]
89 pub webdav: WebDavCmd,
90 #[cfg(not(feature = "webdav"))]
91 #[clap(skip)]
92 #[merge(skip)]
93 pub webdav: Option<Value>,
94}
95
96impl Display for RusticConfig {
97 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
98 let config = toml::to_string_pretty(self)
99 .unwrap_or_else(|_| "<Error serializing config>".to_string());
100
101 write!(f, "{config}",)
102 }
103}
104
105impl RusticConfig {
106 pub fn merge_profile(
115 &mut self,
116 profile: &str,
117 merge_logs: &mut Vec<(Level, String)>,
118 level_missing: Level,
119 ) -> Result<(), FrameworkError> {
120 let profile_filename = if profile.ends_with(".toml") {
121 profile.to_string()
122 } else {
123 profile.to_string() + ".toml"
124 };
125 let paths = get_config_paths(&profile_filename);
126
127 if let Some(path) = paths.iter().find(|path| path.exists()) {
128 merge_logs.push((Level::Info, format!("using config {}", path.display())));
129 let config_content = std::fs::read_to_string(AbsPathBuf::canonicalize(path)?)?;
130 let config_content = if self.global.profile_substitute_env {
131 subst::substitute(&config_content, &subst::Env).map_err(|e| {
132 abscissa_core::error::context::Context::new(
133 FrameworkErrorKind::ParseError,
134 Some(Box::new(e)),
135 )
136 })?
137 } else {
138 config_content
139 };
140 let mut config = Self::load_toml(config_content)?;
141 if config.global.profile_substitute_env && config.global.use_profiles.is_empty() {
143 merge_logs.push((Level::Warn, "Option `profile-substitute-env` is given without any profiles to load! Note that this option does NOT apply to the file where it is specified!".to_string()));
144 }
145 for profile in &config.global.use_profiles.clone() {
147 config.merge_profile(profile, merge_logs, Level::Warn)?;
148 }
149 self.merge(config);
150 } else {
151 let paths_string = paths.iter().map(|path| path.display()).join(", ");
152 merge_logs.push((
153 level_missing,
154 format!("using no config file, none of these exist: {paths_string}",),
155 ));
156 };
157 Ok(())
158 }
159}
160
161#[serde_as]
165#[derive(Default, Debug, Parser, Clone, Deserialize, Serialize, Merge)]
166#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
167pub struct GlobalOptions {
168 #[clap(long, global = true, env = "RUSTIC_PROFILE_SUBSTITUTE_ENV")]
170 #[merge(strategy=conflate::bool::overwrite_false)]
171 pub profile_substitute_env: bool,
172
173 #[clap(
176 short = 'P',
177 long = "use-profile",
178 global = true,
179 value_name = "PROFILE",
180 env = "RUSTIC_USE_PROFILE"
181 )]
182 #[merge(strategy=conflate::vec::append)]
183 pub use_profiles: Vec<String>,
184
185 #[clap(
187 long,
188 short = 'g',
189 global = true,
190 value_name = "CRITERION",
191 env = "RUSTIC_GROUP_BY"
192 )]
193 #[serde_as(as = "Option<DisplayFromStr>")]
194 #[merge(strategy=conflate::option::overwrite_none)]
195 pub group_by: Option<SnapshotGroupCriterion>,
196
197 #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
199 #[merge(strategy=conflate::bool::overwrite_false)]
200 pub dry_run: bool,
201
202 #[clap(long, global = true, env = "RUSTIC_DRY_RUN_WARMUP")]
204 #[merge(strategy=conflate::bool::overwrite_false)]
205 pub dry_run_warmup: bool,
206
207 #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
209 #[merge(strategy=conflate::bool::overwrite_false)]
210 pub check_index: bool,
211
212 #[clap(flatten)]
214 #[serde(flatten)]
215 pub logging_options: LoggingOptions,
216
217 #[clap(flatten)]
219 #[serde(flatten)]
220 pub progress_options: ProgressOptions,
221
222 #[clap(skip)]
224 pub hooks: Hooks,
225
226 #[clap(skip)]
228 #[merge(strategy = conflate::btreemap::append_or_ignore)]
229 pub env: BTreeMap<String, String>,
230
231 #[serde_as(as = "Option<DisplayFromStr>")]
233 #[clap(long, global = true, env = "RUSTIC_PROMETHEUS", value_name = "PUSHGATEWAY_URL", value_hint = ValueHint::Url)]
234 #[merge(strategy=conflate::option::overwrite_none)]
235 pub prometheus: Option<Url>,
236
237 #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
239 #[merge(strategy=conflate::option::overwrite_none)]
240 pub prometheus_user: Option<String>,
241
242 #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
244 #[merge(strategy=conflate::option::overwrite_none)]
245 pub prometheus_pass: Option<String>,
246
247 #[clap(skip)]
249 #[merge(strategy=conflate::btreemap::append_or_ignore)]
250 pub metrics_labels: BTreeMap<String, String>,
251
252 #[serde_as(as = "Option<DisplayFromStr>")]
254 #[clap(long, global = true, env = "RUSTIC_OTEL", value_name = "ENDPOINT_URL", value_hint = ValueHint::Url)]
255 #[merge(strategy=conflate::option::overwrite_none)]
256 pub opentelemetry: Option<Url>,
257
258 #[clap(long, global = true, env = "RUSTIC_SHOW_TIME_OFFSET")]
260 #[merge(strategy=conflate::bool::overwrite_false)]
261 pub show_time_offset: bool,
262}
263
264pub fn parse_labels(s: &str) -> Result<BTreeMap<String, String>> {
265 s.split(',')
266 .filter_map(|s| {
267 let s = s.trim();
268 (!s.is_empty()).then_some(s)
269 })
270 .map(|s| -> Result<_> {
271 let pos = s.find('=').ok_or_else(|| {
272 anyhow!("invalid prometheus label definition: no `=` found in `{s}`")
273 })?;
274 Ok((s[..pos].to_owned(), s[pos + 1..].to_owned()))
275 })
276 .try_collect()
277}
278
279impl GlobalOptions {
280 pub fn is_metrics_configured(&self) -> bool {
281 self.prometheus.is_some() || self.opentelemetry.is_some()
282 }
283
284 pub fn format_timestamp(&self, timestamp: Timestamp) -> String {
285 self.format_time(×tamp.to_zoned(TimeZone::UTC))
286 .to_string()
287 }
288
289 pub fn format_time(&self, time: &Zoned) -> impl Display {
290 if self.show_time_offset {
291 time.strftime("%Y-%m-%d %H:%M:%S%z")
292 } else {
293 let tz = TimeZone::system();
294 if time.offset() == tz.to_offset(time.timestamp()) {
295 time.strftime("%Y-%m-%d %H:%M:%S")
296 } else {
297 time.with_time_zone(tz).strftime("%Y-%m-%d %H:%M:%S*")
298 }
299 }
300 }
301}
302
303fn get_config_paths(filename: &str) -> Vec<PathBuf> {
313 [
314 ProjectDirs::from("", "", "rustic")
315 .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
316 get_global_config_path(),
317 Some(PathBuf::from(".")),
318 ]
319 .into_iter()
320 .filter_map(|path| {
321 path.map(|mut p| {
322 p.push(filename);
323 p
324 })
325 })
326 .collect()
327}
328
329#[cfg(target_os = "windows")]
336fn get_global_config_path() -> Option<PathBuf> {
337 std::env::var_os("PROGRAMDATA").map(|program_data| {
338 let mut path = PathBuf::from(program_data);
339 path.push(r"rustic\config");
340 path
341 })
342}
343
344#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
350fn get_global_config_path() -> Option<PathBuf> {
351 None
352}
353
354#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
361fn get_global_config_path() -> Option<PathBuf> {
362 Some(PathBuf::from("/etc/rustic"))
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use insta::{assert_debug_snapshot, assert_snapshot};
369
370 #[test]
371 fn test_default_config_passes() {
372 let config = RusticConfig::default();
373
374 assert_debug_snapshot!(config);
375 }
376
377 #[test]
378 fn test_default_config_display_passes() {
379 let config = RusticConfig::default();
380
381 assert_snapshot!(config);
382 }
383
384 #[test]
385 fn test_global_env_roundtrip_passes() {
386 let mut config = RusticConfig::default();
387
388 for i in 0..10 {
389 let _ = config
390 .global
391 .env
392 .insert(format!("KEY{i}"), format!("VALUE{i}"));
393 }
394
395 let serialized = toml::to_string(&config).unwrap();
396
397 assert_snapshot!(serialized);
399
400 let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
401 assert_snapshot!(deserialized);
403
404 assert_debug_snapshot!(deserialized);
406 }
407}