rustic_rs/commands/
key.rs

1//! `key` subcommand
2
3use crate::{repository::CliOpenRepo, status_err, Application, RUSTIC_APP};
4
5use std::path::PathBuf;
6
7use abscissa_core::{Command, Runnable, Shutdown};
8use anyhow::Result;
9use dialoguer::Password;
10use log::info;
11
12use rustic_core::{CommandInput, KeyOptions, RepositoryOptions};
13
14/// `key` subcommand
15#[derive(clap::Parser, Command, Debug)]
16pub(super) struct KeyCmd {
17    /// Subcommand to run
18    #[clap(subcommand)]
19    cmd: KeySubCmd,
20}
21
22#[derive(clap::Subcommand, Debug, Runnable)]
23enum KeySubCmd {
24    /// Add a new key to the repository
25    Add(AddCmd),
26}
27
28#[derive(clap::Parser, Debug)]
29pub(crate) struct AddCmd {
30    /// New password
31    #[clap(long)]
32    pub(crate) new_password: Option<String>,
33
34    /// File from which to read the new password
35    #[clap(long)]
36    pub(crate) new_password_file: Option<PathBuf>,
37
38    /// Command to get the new password from
39    #[clap(long)]
40    pub(crate) new_password_command: Option<CommandInput>,
41
42    /// Key options
43    #[clap(flatten)]
44    pub(crate) key_opts: KeyOptions,
45}
46
47impl Runnable for KeyCmd {
48    fn run(&self) {
49        self.cmd.run();
50    }
51}
52
53impl Runnable for AddCmd {
54    fn run(&self) {
55        if let Err(err) = RUSTIC_APP
56            .config()
57            .repository
58            .run_open(|repo| self.inner_run(repo))
59        {
60            status_err!("{}", err);
61            RUSTIC_APP.shutdown(Shutdown::Crash);
62        };
63    }
64}
65
66impl AddCmd {
67    fn inner_run(&self, repo: CliOpenRepo) -> Result<()> {
68        // create new Repository options which just contain password information
69        let mut pass_opts = RepositoryOptions::default();
70        pass_opts.password = self.new_password.clone();
71        pass_opts.password_file = self.new_password_file.clone();
72        pass_opts.password_command = self.new_password_command.clone();
73
74        let pass = pass_opts
75            .evaluate_password()
76            .map_err(Into::into)
77            .transpose()
78            .unwrap_or_else(|| -> Result<_> {
79                Ok(Password::new()
80                    .with_prompt("enter password for new key")
81                    .allow_empty_password(true)
82                    .with_confirmation("confirm password", "passwords do not match")
83                    .interact()?)
84            })?;
85
86        let id = repo.add_key(&pass, &self.key_opts)?;
87        info!("key {id} successfully added.");
88
89        Ok(())
90    }
91}