Skip to main content

rustic_rs/
commands.rs

1//! Rustic Subcommands
2
3pub(crate) mod backup;
4pub(crate) mod cat;
5pub(crate) mod check;
6pub(crate) mod completions;
7pub(crate) mod config;
8pub(crate) mod copy;
9pub(crate) mod diff;
10pub(crate) mod docs;
11pub(crate) mod dump;
12pub(crate) mod find;
13pub(crate) mod forget;
14pub(crate) mod init;
15pub(crate) mod key;
16pub(crate) mod list;
17pub(crate) mod ls;
18pub(crate) mod merge;
19#[cfg(feature = "mount")]
20pub(crate) mod mount;
21pub(crate) mod prune;
22pub(crate) mod repair;
23pub(crate) mod repoinfo;
24pub(crate) mod restore;
25pub(crate) mod rewrite;
26pub(crate) mod self_update;
27pub(crate) mod show_config;
28pub(crate) mod snapshots;
29pub(crate) mod tag;
30#[cfg(feature = "tui")]
31pub(crate) mod tui;
32#[cfg(feature = "webdav")]
33pub(crate) mod webdav;
34
35use std::fmt::Debug;
36use std::path::PathBuf;
37use std::sync::mpsc::channel;
38
39#[cfg(feature = "mount")]
40use crate::commands::mount::MountCmd;
41#[cfg(feature = "webdav")]
42use crate::commands::webdav::WebDavCmd;
43use crate::{
44    Application, RUSTIC_APP,
45    commands::{
46        backup::BackupCmd, cat::CatCmd, check::CheckCmd, completions::CompletionsCmd,
47        config::ConfigCmd, copy::CopyCmd, diff::DiffCmd, docs::DocsCmd, dump::DumpCmd,
48        forget::ForgetCmd, init::InitCmd, key::KeyCmd, list::ListCmd, ls::LsCmd, merge::MergeCmd,
49        prune::PruneCmd, repair::RepairCmd, repoinfo::RepoInfoCmd, restore::RestoreCmd,
50        rewrite::RewriteCmd, self_update::SelfUpdateCmd, show_config::ShowConfigCmd,
51        snapshots::SnapshotCmd, tag::TagCmd,
52    },
53    config::RusticConfig,
54};
55
56use abscissa_core::{
57    Command, Configurable, FrameworkError, FrameworkErrorKind, Runnable, Shutdown, config::Override,
58};
59use anyhow::Result;
60use clap::builder::{
61    Styles,
62    styling::{AnsiColor, Effects},
63};
64use convert_case::{Case, Casing};
65use human_panic::setup_panic;
66use log::{Level, info, log};
67use reqwest::Url;
68
69use self::find::FindCmd;
70
71/// Rustic Subcommands
72/// Subcommands need to be listed in an enum.
73#[derive(clap::Parser, Command, Debug, Runnable)]
74enum RusticCmd {
75    /// Backup to the repository
76    Backup(Box<BackupCmd>),
77
78    /// Show raw data of files and blobs in a repository
79    Cat(Box<CatCmd>),
80
81    /// Change the repository configuration
82    Config(Box<ConfigCmd>),
83
84    /// Generate shell completions
85    Completions(Box<CompletionsCmd>),
86
87    /// Check the repository
88    Check(Box<CheckCmd>),
89
90    /// Copy snapshots to other repositories
91    Copy(Box<CopyCmd>),
92
93    /// Compare two snapshots or paths
94    Diff(Box<DiffCmd>),
95
96    /// Open the documentation
97    Docs(Box<DocsCmd>),
98
99    /// Dump the contents of a file within a snapshot to stdout
100    Dump(Box<DumpCmd>),
101
102    /// Find patterns in given snapshots
103    Find(Box<FindCmd>),
104
105    /// Remove snapshots from the repository
106    Forget(Box<ForgetCmd>),
107
108    /// Initialize a new repository
109    Init(Box<InitCmd>),
110
111    /// Manage keys for a repository
112    Key(Box<KeyCmd>),
113
114    /// List repository files by file type
115    List(Box<ListCmd>),
116
117    #[cfg(feature = "mount")]
118    /// Mount a repository as read-only filesystem
119    Mount(Box<MountCmd>),
120
121    /// List file contents of a snapshot
122    Ls(Box<LsCmd>),
123
124    /// Merge snapshots
125    Merge(Box<MergeCmd>),
126
127    /// Show a detailed overview of the snapshots within the repository
128    Snapshots(Box<SnapshotCmd>),
129
130    /// Show the configuration which has been read from the config file(s)
131    ShowConfig(Box<ShowConfigCmd>),
132
133    /// Update to the latest stable rustic release
134    #[cfg_attr(not(feature = "self-update"), clap(hide = true))]
135    SelfUpdate(Box<SelfUpdateCmd>),
136
137    /// Remove unused data or repack repository pack files
138    Prune(Box<PruneCmd>),
139
140    /// Restore (a path within) a snapshot
141    Restore(Box<RestoreCmd>),
142
143    /// Rewrite existing snapshot(s)
144    Rewrite(Box<RewriteCmd>),
145
146    /// Repair a snapshot or the repository index
147    Repair(Box<RepairCmd>),
148
149    /// Show general information about the repository
150    Repoinfo(Box<RepoInfoCmd>),
151
152    /// Change tags of snapshots
153    Tag(Box<TagCmd>),
154
155    /// Start a webdav server which allows to access the repository
156    #[cfg(feature = "webdav")]
157    Webdav(Box<WebDavCmd>),
158}
159
160fn styles() -> Styles {
161    Styles::styled()
162        .header(AnsiColor::Red.on_default() | Effects::BOLD)
163        .usage(AnsiColor::Red.on_default() | Effects::BOLD)
164        .literal(AnsiColor::Blue.on_default() | Effects::BOLD)
165        .placeholder(AnsiColor::Green.on_default())
166}
167
168fn version() -> &'static str {
169    option_env!("PROJECT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"))
170}
171
172/// Entry point for the application. It needs to be a struct to allow using subcommands!
173#[derive(clap::Parser, Command, Debug)]
174#[command(author, about, name="rustic", styles=styles(), version=version())]
175pub struct EntryPoint {
176    #[command(flatten)]
177    pub config: RusticConfig,
178
179    #[command(subcommand)]
180    commands: RusticCmd,
181}
182
183impl Runnable for EntryPoint {
184    fn run(&self) {
185        // Set up panic hook for better error messages and logs
186        setup_panic!();
187
188        // Set up Ctrl-C handler
189        let (tx, rx) = channel();
190
191        ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel."))
192            .expect("Error setting Ctrl-C handler");
193
194        _ = std::thread::spawn(move || {
195            // Wait for Ctrl-C
196            rx.recv().expect("Could not receive from channel.");
197            info!("Ctrl-C received, shutting down...");
198            RUSTIC_APP.shutdown(Shutdown::Graceful)
199        });
200
201        // Run the subcommand
202        self.commands.run();
203        RUSTIC_APP.shutdown(Shutdown::Graceful)
204    }
205}
206
207/// This trait allows you to define how application configuration is loaded.
208impl Configurable<RusticConfig> for EntryPoint {
209    /// Location of the configuration file
210    fn config_path(&self) -> Option<PathBuf> {
211        // Actually abscissa itself reads a config from `config_path`, but I have now returned None,
212        // i.e. no config is read.
213        None
214    }
215
216    /// Apply changes to the config after it's been loaded, e.g. overriding
217    /// values in a config file using command-line options.
218    fn process_config(&self, _config: RusticConfig) -> Result<RusticConfig, FrameworkError> {
219        // Note: The config that is "not read" is then read here in `process_config()` by the
220        // rustic logic and merged with the CLI options.
221        // That's why it says `_config`, because it's not read at all and therefore not needed.
222        let mut config = self.config.clone();
223
224        // collect "RUSTIC_REPO_OPT*" and "OPENDAL*" env variables.
225        // also add the standardized OTEL variables manually
226        // since clap does not support multiple variables for a single arg
227        for (var, value) in std::env::vars() {
228            if let Some(var) = var.strip_prefix("RUSTIC_REPO_OPT_") {
229                let var = var.from_case(Case::UpperSnake).to_case(Case::Kebab);
230                _ = config.repository.be.options.insert(var, value);
231            } else if let Some(var) = var.strip_prefix("OPENDAL_") {
232                let var = var.from_case(Case::UpperSnake).to_case(Case::Snake);
233                _ = config.repository.be.options.insert(var, value);
234            } else if let Some(var) = var.strip_prefix("RUSTIC_REPO_OPTHOT_") {
235                let var = var.from_case(Case::UpperSnake).to_case(Case::Kebab);
236                _ = config.repository.be.options_hot.insert(var, value);
237            } else if let Some(var) = var.strip_prefix("RUSTIC_REPO_OPTCOLD_") {
238                let var = var.from_case(Case::UpperSnake).to_case(Case::Kebab);
239                _ = config.repository.be.options_cold.insert(var, value);
240            } else if let Some(var) = var.strip_prefix("OPENDALHOT_") {
241                let var = var.from_case(Case::UpperSnake).to_case(Case::Snake);
242                _ = config.repository.be.options_hot.insert(var, value);
243            } else if let Some(var) = var.strip_prefix("OPENDALCOLD_") {
244                let var = var.from_case(Case::UpperSnake).to_case(Case::Snake);
245                _ = config.repository.be.options_cold.insert(var, value);
246            } else if var == "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT" {
247                #[cfg(feature = "opentelemetry")]
248                if let Ok(url) = Url::parse(&value) {
249                    _ = config.global.opentelemetry.insert(url);
250                }
251            } else if var == "OTEL_SERVICE_NAME" && cfg!(feature = "opentelemetry") {
252                _ = config.backup.metrics_job.insert(value);
253            }
254        }
255
256        // collect logs during merging as we start the logger *after* merging
257        let mut merge_logs = Vec::new();
258
259        // get global options from command line / env and config file
260        if config.global.use_profiles.is_empty() {
261            config.merge_profile("rustic", &mut merge_logs, Level::Info)?;
262        } else {
263            for profile in &config.global.use_profiles.clone() {
264                config.merge_profile(profile, &mut merge_logs, Level::Warn)?;
265            }
266        }
267
268        // start logger
269        config
270            .global
271            .logging_options
272            .start_logger(config.global.dry_run)
273            .map_err(|e| FrameworkErrorKind::ConfigError.context(e))?;
274
275        if config.global.logging_options.log_file.is_some() {
276            info!("rustic {}", version());
277            info!("command: {:?}", std::env::args_os().collect::<Vec<_>>());
278        }
279
280        // display logs from merging
281        for (level, merge_log) in merge_logs {
282            log!(level, "{merge_log}");
283        }
284
285        match &self.commands {
286            RusticCmd::Forget(cmd) => cmd.override_config(config),
287            RusticCmd::Copy(cmd) => cmd.override_config(config),
288            #[cfg(feature = "webdav")]
289            RusticCmd::Webdav(cmd) => cmd.override_config(config),
290            #[cfg(feature = "mount")]
291            RusticCmd::Mount(cmd) => cmd.override_config(config),
292
293            // subcommands that don't need special overrides use a catch all
294            _ => Ok(config),
295        }
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use crate::commands::EntryPoint;
302    use clap::CommandFactory;
303
304    #[test]
305    fn verify_cli() {
306        EntryPoint::command().debug_assert();
307    }
308}