qrsimple_cli/
config.rs

1use crate::error::MyResult;
2use clap_builder::{Arg, ArgAction, ArgMatches, Command};
3
4pub struct Config {
5    pub text: Option<String>,
6}
7
8impl Config {
9    pub fn new(name: String, args: Vec<String>) -> MyResult<Config> {
10        let mut command = Self::create_command(name);
11        let matches = Self::create_matches(&mut command, args)?;
12        let config = Self::create_config(matches)?;
13        Ok(config)
14    }
15
16    fn create_command(name: String) -> Command {
17        let mut index = 0;
18        let command = Command::new(name)
19            .version(clap::crate_version!())
20            .about(clap::crate_description!())
21            .author(clap::crate_authors!());
22        let command = command.arg(Self::create_arg("text", &mut index)
23            .action(ArgAction::Set)
24            .help("File to read, or text to import, for QR code"));
25        command
26    }
27
28    fn create_arg(name: &'static str, index: &mut usize) -> Arg {
29        *index += 1;
30        Arg::new(name).display_order(*index)
31    }
32
33    fn create_matches(command: &mut Command, args: Vec<String>) -> MyResult<ArgMatches> {
34        let matches = command.try_get_matches_from_mut(args)?;
35        Ok(matches)
36    }
37
38    fn create_config(matches: ArgMatches) -> MyResult<Config> {
39        let text = matches.get_one("text").map(String::clone);
40        let config = Self { text };
41        Ok(config)
42    }
43}