rustic_rs/
config.rs

1//! Rustic Config
2//!
3//! See instructions in `commands.rs` to specify the path to your
4//! application's configuration file and/or command-line options
5//! for specifying it.
6
7pub(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/// Rustic Configuration
43///
44/// Further documentation can be found [here](https://github.com/rustic-rs/rustic/blob/main/config/README.md).
45///
46/// # Example
47// TODO: add example
48#[derive(Clone, Default, Debug, Parser, Deserialize, Serialize, Merge)]
49#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
50pub struct RusticConfig {
51    /// Global options
52    #[clap(flatten, next_help_heading = "Global options")]
53    pub global: GlobalOptions,
54
55    /// Repository options
56    #[clap(flatten, next_help_heading = "Repository options")]
57    pub repository: AllRepositoryOptions,
58
59    /// Snapshot filter options
60    #[clap(flatten, next_help_heading = "Snapshot filter options")]
61    pub snapshot_filter: SnapshotFilter,
62
63    /// Backup options
64    #[clap(skip)]
65    pub backup: BackupCmd,
66
67    /// Copy options
68    #[clap(skip)]
69    pub copy: CopyCmd,
70
71    /// Forget options
72    #[clap(skip)]
73    pub forget: ForgetOptions,
74
75    /// mount options
76    #[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    /// webdav options
85    #[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    /// Merge a profile into the current config by reading the corresponding config file.
105    /// Also recursively merge all profiles given within this config file.
106    ///
107    /// # Arguments
108    ///
109    /// * `profile` - name of the profile to merge
110    /// * `merge_logs` - Vector to collect logs during merging
111    /// * `level_missing` - The log level to use if this profile is missing. Recursive calls will produce a Warning.
112    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            // if "use_profile" is defined in config file, merge the referenced profiles first
135            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/// Global options
154///
155/// These options are available for all commands.
156#[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    /// Config profile to use. This parses the file `<PROFILE>.toml` in the config directory.
161    /// [default: "rustic"]
162    #[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    /// Group snapshots by any combination of host,label,paths,tags, e.g. to find the latest snapshot [default: "host,label,paths"]
173    #[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    /// Only show what would be done without modifying anything. Does not affect read-only commands.
185    #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
186    #[merge(strategy=conflate::bool::overwrite_false)]
187    pub dry_run: bool,
188
189    /// Check if index matches pack files and read pack headers if necessary
190    #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
191    #[merge(strategy=conflate::bool::overwrite_false)]
192    pub check_index: bool,
193
194    /// Use this log level [default: info]
195    #[clap(long, global = true, env = "RUSTIC_LOG_LEVEL")]
196    #[merge(strategy=conflate::option::overwrite_none)]
197    pub log_level: Option<String>,
198
199    /// Write log messages to the given file instead of printing them.
200    ///
201    /// # Note
202    ///
203    /// Warnings and errors are still additionally printed unless they are ignored by `--log-level`
204    #[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    /// Settings to customize progress bars
209    #[clap(flatten)]
210    #[serde(flatten)]
211    pub progress_options: ProgressOptions,
212
213    /// Hooks
214    #[clap(skip)]
215    pub hooks: Hooks,
216
217    /// List of environment variables to set (only in config file)
218    #[clap(skip)]
219    #[merge(strategy = conflate::btreemap::append_or_ignore)]
220    pub env: BTreeMap<String, String>,
221
222    /// Push metrics to a Prometheus Pushgateway
223    #[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    /// Authenticate to Prometheus Pushgateway using this user
229    #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
230    #[merge(strategy=conflate::option::overwrite_none)]
231    pub prometheus_user: Option<String>,
232
233    /// Authenticate to Prometheus Pushgateway using this password
234    #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
235    #[merge(strategy=conflate::option::overwrite_none)]
236    pub prometheus_pass: Option<String>,
237
238    /// Additional labels to set to generated metrics
239    #[clap(skip)]
240    #[merge(strategy=conflate::btreemap::append_or_ignore)]
241    pub metrics_labels: BTreeMap<String, String>,
242
243    /// OpenTelemetry metrics endpoint (HTTP Protobuf)
244    #[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
271/// Get the paths to the config file
272///
273/// # Arguments
274///
275/// * `filename` - name of the config file
276///
277/// # Returns
278///
279/// A vector of [`PathBuf`]s to the config files
280fn 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/// Get the path to the global config directory on Windows.
298///
299/// # Returns
300///
301/// The path to the global config directory on Windows.
302/// If the environment variable `PROGRAMDATA` is not set, `None` is returned.
303#[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/// Get the path to the global config directory on ios and wasm targets.
313///
314/// # Returns
315///
316/// `None` is returned.
317#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
318fn get_global_config_path() -> Option<PathBuf> {
319    None
320}
321
322/// Get the path to the global config directory on non-Windows,
323/// non-iOS, non-wasm targets.
324///
325/// # Returns
326///
327/// "/etc/rustic" is returned.
328#[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        // Check Serialization
366        assert_snapshot!(serialized);
367
368        let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
369        // Check Deserialization and Display
370        assert_snapshot!(deserialized);
371
372        // Check Debug
373        assert_debug_snapshot!(deserialized);
374    }
375}