1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/// ## Initialize command line parsing

/// ### Example
/// ```rust
/// use ace::App;
///
/// let app = App::new("app", env!("CARGO_PKG_VERSION"))
///     .cmd("start", "Start now")
///     .cmd("help", "Display help information")
///     .cmd("version", "Display version information")
///     .opt("--config", "Use configuration file");
///
/// if let Some(cmd) = app.command() {
///     match cmd.as_str() {
///         "start" => {
///             dbg!(app.value("--config"));
///         }
///         "help" => {
///             app.help();
///         }
///         "version" => {
///             app.version();
///         }
///         _ => {
///             app.error_try("help");
///         }
///     }
/// }
/// ```

#[derive(Debug, Clone)]
pub struct App<'a> {
    name: &'a str,
    version: &'a str,
    args: Vec<String>,
    command: Vec<(&'a str, &'a str)>,
    option: Vec<(&'a str, &'a str)>,
}

impl<'a> App<'a> {
    /// Create
    pub fn new(name: &'a str, version: &'a str) -> App<'a> {
        let args = std::env::args().collect::<Vec<String>>();
        App {
            name,
            version,
            args,
            command: vec![],
            option: vec![],
        }
    }

    /// Add a command
    pub fn cmd(mut self, cmd: &'a str, desc: &'a str) -> App<'a> {
        self.command.push((cmd, desc));
        App { ..self }
    }

    /// Add a option
    pub fn opt(mut self, opt: &'a str, desc: &'a str) -> App<'a> {
        self.option.push((opt, desc));
        App { ..self }
    }

    /// Get the current command
    pub fn command(&self) -> Option<&String> {
        if let Some(cur) = self.args.get(1) {
            let all = self.option.iter().all(|(item, _)| item != cur);
            if all {
                return Some(cur);
            }
        }
        None
    }

    /// Match the current command
    pub fn is(&mut self, arg: &str) -> bool {
        self.args.len() > 1 && arg == self.args[1]
    }

    // Get all values
    pub fn values(&self) -> &[String] {
        &self.args[1..]
    }

    /// Get the value of option
    pub fn value(&self, option: &str) -> Option<Vec<&String>> {
        let mut values = vec![];
        let mut find = false;
        for item in self.args[1..].iter() {
            if find {
                let all = self.option.iter().all(|(arg, _)| item != arg);
                if all {
                    values.push(item);
                } else {
                    break;
                }
            }
            if item == option {
                find = true;
            }
        }
        if find {
            Some(values)
        } else {
            None
        }
    }

    /// Print version information
    pub fn version(&self) {
        println!("{0} version {1}", self.name, self.version)
    }

    fn print_help(name: &'static str, data: &Vec<(&str, &str)>) {
        println!("{}", name);
        let mut n = 0;
        data.iter().for_each(|(d, _)| {
            if d.len() > n {
                n = d.len();
            }
        });
        for (arg, desc) in data {
            println!("    {:arg$}    {}", arg, desc, arg = n);
        }
    }

    /// Print help information
    pub fn help(&self) {
        println!(
            "\
{0} version {1}

Usage:
    {0} [COMMAND] [OPTION]
            ",
            self.name, self.version
        );

        if self.command.len() > 0 {
            Self::print_help("Command:", &self.command);
        }

        if self.command.len() > 0 && self.option.len() > 0 {
            println!();
        }

        if self.option.len() > 0 {
            Self::print_help("Option:", &self.option);
        }
    }

    /// Print error information
    pub fn error(&self) {
        eprint!("\x1B[1;31m{}\x1B[0m", "error: ");
        eprintln!(
            "'{}' is not a valid command",
            self.args.get(1).unwrap_or(&String::new())
        );
    }

    /// Print an error message and add an attempt
    pub fn error_try(&self, command: &str) {
        self.error();
        eprintln!("try:\n    '{} {}'", self.name, command);
    }
}