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 for profile in &config.global.use_profiles.clone() {
143 config.merge_profile(profile, merge_logs, Level::Warn)?;
144 }
145 self.merge(config);
146 } else {
147 let paths_string = paths.iter().map(|path| path.display()).join(", ");
148 merge_logs.push((
149 level_missing,
150 format!(
151 "using no config file, none of these exist: {}",
152 &paths_string
153 ),
154 ));
155 };
156 Ok(())
157 }
158}
159
160#[serde_as]
164#[derive(Default, Debug, Parser, Clone, Deserialize, Serialize, Merge)]
165#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
166pub struct GlobalOptions {
167 #[clap(long, global = true, env = "RUSTIC_PROFILE_SUBSTITUTE_ENV")]
169 #[merge(strategy=conflate::bool::overwrite_false)]
170 pub profile_substitute_env: bool,
171
172 #[clap(
175 short = 'P',
176 long = "use-profile",
177 global = true,
178 value_name = "PROFILE",
179 env = "RUSTIC_USE_PROFILE"
180 )]
181 #[merge(strategy=conflate::vec::append)]
182 pub use_profiles: Vec<String>,
183
184 #[clap(
186 long,
187 short = 'g',
188 global = true,
189 value_name = "CRITERION",
190 env = "RUSTIC_GROUP_BY"
191 )]
192 #[serde_as(as = "Option<DisplayFromStr>")]
193 #[merge(strategy=conflate::option::overwrite_none)]
194 pub group_by: Option<SnapshotGroupCriterion>,
195
196 #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
198 #[merge(strategy=conflate::bool::overwrite_false)]
199 pub dry_run: bool,
200
201 #[clap(long, global = true, env = "RUSTIC_DRY_RUN_WARMUP")]
203 #[merge(strategy=conflate::bool::overwrite_false)]
204 pub dry_run_warmup: bool,
205
206 #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
208 #[merge(strategy=conflate::bool::overwrite_false)]
209 pub check_index: bool,
210
211 #[clap(flatten)]
213 #[serde(flatten)]
214 pub logging_options: LoggingOptions,
215
216 #[clap(flatten)]
218 #[serde(flatten)]
219 pub progress_options: ProgressOptions,
220
221 #[clap(skip)]
223 pub hooks: Hooks,
224
225 #[clap(skip)]
227 #[merge(strategy = conflate::btreemap::append_or_ignore)]
228 pub env: BTreeMap<String, String>,
229
230 #[serde_as(as = "Option<DisplayFromStr>")]
232 #[clap(long, global = true, env = "RUSTIC_PROMETHEUS", value_name = "PUSHGATEWAY_URL", value_hint = ValueHint::Url)]
233 #[merge(strategy=conflate::option::overwrite_none)]
234 pub prometheus: Option<Url>,
235
236 #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
238 #[merge(strategy=conflate::option::overwrite_none)]
239 pub prometheus_user: Option<String>,
240
241 #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
243 #[merge(strategy=conflate::option::overwrite_none)]
244 pub prometheus_pass: Option<String>,
245
246 #[clap(skip)]
248 #[merge(strategy=conflate::btreemap::append_or_ignore)]
249 pub metrics_labels: BTreeMap<String, String>,
250
251 #[serde_as(as = "Option<DisplayFromStr>")]
253 #[clap(long, global = true, env = "RUSTIC_OTEL", value_name = "ENDPOINT_URL", value_hint = ValueHint::Url)]
254 #[merge(strategy=conflate::option::overwrite_none)]
255 pub opentelemetry: Option<Url>,
256
257 #[clap(long, global = true, env = "RUSTIC_SHOW_TIME_OFFSET")]
259 #[merge(strategy=conflate::bool::overwrite_false)]
260 pub show_time_offset: bool,
261}
262
263pub fn parse_labels(s: &str) -> Result<BTreeMap<String, String>> {
264 s.split(',')
265 .filter_map(|s| {
266 let s = s.trim();
267 (!s.is_empty()).then_some(s)
268 })
269 .map(|s| -> Result<_> {
270 let pos = s.find('=').ok_or_else(|| {
271 anyhow!("invalid prometheus label definition: no `=` found in `{s}`")
272 })?;
273 Ok((s[..pos].to_owned(), s[pos + 1..].to_owned()))
274 })
275 .try_collect()
276}
277
278impl GlobalOptions {
279 pub fn is_metrics_configured(&self) -> bool {
280 self.prometheus.is_some() || self.opentelemetry.is_some()
281 }
282
283 pub fn format_timestamp(&self, timestamp: Timestamp) -> String {
284 self.format_time(×tamp.to_zoned(TimeZone::UTC))
285 .to_string()
286 }
287
288 pub fn format_time(&self, time: &Zoned) -> impl Display {
289 if self.show_time_offset {
290 time.strftime("%Y-%m-%d %H:%M:%S%z")
291 } else {
292 let tz = TimeZone::system();
293 if time.offset() == tz.to_offset(time.timestamp()) {
294 time.strftime("%Y-%m-%d %H:%M:%S")
295 } else {
296 time.with_time_zone(tz).strftime("%Y-%m-%d %H:%M:%S*")
297 }
298 }
299 }
300}
301
302fn get_config_paths(filename: &str) -> Vec<PathBuf> {
312 [
313 ProjectDirs::from("", "", "rustic")
314 .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
315 get_global_config_path(),
316 Some(PathBuf::from(".")),
317 ]
318 .into_iter()
319 .filter_map(|path| {
320 path.map(|mut p| {
321 p.push(filename);
322 p
323 })
324 })
325 .collect()
326}
327
328#[cfg(target_os = "windows")]
335fn get_global_config_path() -> Option<PathBuf> {
336 std::env::var_os("PROGRAMDATA").map(|program_data| {
337 let mut path = PathBuf::from(program_data);
338 path.push(r"rustic\config");
339 path
340 })
341}
342
343#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
349fn get_global_config_path() -> Option<PathBuf> {
350 None
351}
352
353#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
360fn get_global_config_path() -> Option<PathBuf> {
361 Some(PathBuf::from("/etc/rustic"))
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use insta::{assert_debug_snapshot, assert_snapshot};
368
369 #[test]
370 fn test_default_config_passes() {
371 let config = RusticConfig::default();
372
373 assert_debug_snapshot!(config);
374 }
375
376 #[test]
377 fn test_default_config_display_passes() {
378 let config = RusticConfig::default();
379
380 assert_snapshot!(config);
381 }
382
383 #[test]
384 fn test_global_env_roundtrip_passes() {
385 let mut config = RusticConfig::default();
386
387 for i in 0..10 {
388 let _ = config
389 .global
390 .env
391 .insert(format!("KEY{i}"), format!("VALUE{i}"));
392 }
393
394 let serialized = toml::to_string(&config).unwrap();
395
396 assert_snapshot!(serialized);
398
399 let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
400 assert_snapshot!(deserialized);
402
403 assert_debug_snapshot!(deserialized);
405 }
406}