Skip to main content

canic_cli/backup/options/
mod.rs

1use crate::args::{flag_arg, parse_matches, path_option, value_arg};
2
3use super::{BackupCommandError, usage};
4use clap::{ArgMatches, Command as ClapCommand};
5use std::{ffi::OsString, path::PathBuf};
6
7///
8/// BackupVerifyOptions
9///
10
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct BackupVerifyOptions {
13    pub dir: PathBuf,
14    pub out: Option<PathBuf>,
15}
16
17impl BackupVerifyOptions {
18    /// Parse backup verification options from CLI arguments.
19    pub fn parse<I>(args: I) -> Result<Self, BackupCommandError>
20    where
21        I: IntoIterator<Item = OsString>,
22    {
23        let matches = parse_backup_options(backup_verify_command(), args)?;
24
25        Ok(Self {
26            dir: required_path_option(&matches, "dir", "--dir")?,
27            out: path_option(&matches, "out"),
28        })
29    }
30}
31
32// Build the backup verify parser.
33fn backup_verify_command() -> ClapCommand {
34    backup_dir_out_command("backup-verify")
35}
36
37///
38/// BackupStatusOptions
39///
40
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct BackupStatusOptions {
43    pub dir: PathBuf,
44    pub out: Option<PathBuf>,
45    pub require_complete: bool,
46}
47
48impl BackupStatusOptions {
49    /// Parse backup status options from CLI arguments.
50    pub fn parse<I>(args: I) -> Result<Self, BackupCommandError>
51    where
52        I: IntoIterator<Item = OsString>,
53    {
54        let matches = parse_backup_options(backup_status_command(), args)?;
55
56        Ok(Self {
57            dir: required_path_option(&matches, "dir", "--dir")?,
58            out: path_option(&matches, "out"),
59            require_complete: matches.get_flag("require-complete"),
60        })
61    }
62}
63
64// Build the backup status parser.
65fn backup_status_command() -> ClapCommand {
66    backup_dir_out_command("backup-status")
67        .arg(flag_arg("require-complete").long("require-complete"))
68}
69
70// Parse one backup command option set.
71fn parse_backup_options<I>(command: ClapCommand, args: I) -> Result<ArgMatches, BackupCommandError>
72where
73    I: IntoIterator<Item = OsString>,
74{
75    parse_matches(command, args).map_err(|_| BackupCommandError::Usage(usage()))
76}
77
78// Build the common --dir/--out parser shape.
79fn backup_dir_out_command(name: &'static str) -> ClapCommand {
80    ClapCommand::new(name)
81        .disable_help_flag(true)
82        .arg(value_arg("dir").long("dir"))
83        .arg(value_arg("out").long("out"))
84}
85
86// Read one required path from Clap matches.
87fn required_path_option(
88    matches: &ArgMatches,
89    id: &str,
90    option: &'static str,
91) -> Result<PathBuf, BackupCommandError> {
92    path_option(matches, id).ok_or(BackupCommandError::MissingOption(option))
93}