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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use std::fmt::Display;
use std::process;

use clap::{Arg, ArgAction, ArgMatches, Command};
use clap_builder::parser::ValuesRef;
use clap_complete::Shell;

use crate::error::{MyError, MyResult};

pub enum ShellKind {
    Bash,
    PowerShell,
}

pub struct Config {
    pub paths: Vec<String>,
    pub values: Vec<String>,
    pub completion: Option<ShellKind>,
}

const PATHS_SHORT: &'static str = "Values and operations from text files";
const VALUES_SHORT: &'static str = "Values and operations from command line";
const SHELL_SHORT: &'static str = "Create completion script";

const PATHS_LONG: &'static str = "\
Read values and operations from text files or stdin";
const VALUES_LONG: &'static str = "\
Read values and operations from command line";
const SHELL_LONG: &'static str = "\
Create completion script:
Use \"--completion bash\" to create script for Bash
Use \"--completion ps\" to create script for PowerShell";

impl Config {
    pub fn new(name: String, args: Vec<String>) -> MyResult<Config> {
        let mut command = Self::create_command(name.clone());
        let matches = Self::create_matches(&mut command, args)?;
        let config = Self::create_config(&mut command, matches)?;
        if let Some(completion) = config.completion {
            Self::create_completion(&mut command, name, completion);
            process::exit(1);
        }
        return Ok(config);
    }

    fn create_command(name: String) -> Command {
        let mut index = 0;
        let command = Command::new(name)
            .version(clap::crate_version!())
            .about(clap::crate_description!())
            .author(clap::crate_authors!());
        let command = command.arg(Self::create_arg("paths", &mut index)
            .action(ArgAction::Append)
            .help(PATHS_SHORT)
            .long_help(PATHS_LONG));
        let command = command.arg(Self::create_arg("command", &mut index)
            .long("command")
            .short('c')
            .action(ArgAction::Append)
            .value_name("VALUE")
            .num_args(1..)
            .allow_negative_numbers(true)
            .help(VALUES_SHORT)
            .long_help(VALUES_LONG));
        let command = command.arg(Self::create_arg("completion", &mut index)
            .long("completion")
            .action(ArgAction::Set)
            .value_name("SHELL")
            .value_parser(["bash", "ps"])
            .hide_possible_values(true)
            .help(SHELL_SHORT)
            .long_help(SHELL_LONG));
        return command;
    }

    fn create_arg(name: &'static str, index: &mut usize) -> Arg {
        *index += 1;
        return Arg::new(name).display_order(*index);
    }

    fn create_matches(command: &mut Command, args: Vec<String>) -> clap::error::Result<ArgMatches> {
        match command.try_get_matches_from_mut(args) {
            Ok(found) => Ok(found),
            Err(error) => match error.kind() {
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
                    let error = error.to_string();
                    let error = error.trim_end();
                    eprintln!("{error}");
                    process::exit(1);
                },
                _ => Err(error),
            }
        }
    }

    fn create_config(command: &mut Command, matches: ArgMatches) -> MyResult<Config> {
        let paths = Self::parse_values(matches.get_many("paths"));
        let values = Self::parse_values(matches.get_many("command"));
        let completion = Self::parse_completion(command, matches.get_one("completion"))?;
        let config = Self {
            paths,
            values,
            completion,
        };
        return Ok(config);
    }

    fn parse_values(values: Option<ValuesRef<String>>) -> Vec<String> {
        values.unwrap_or_default().map(String::to_string).collect()
    }

    fn parse_completion(command: &mut Command, value: Option<&String>) -> MyResult<Option<ShellKind>> {
        let value = value.map(String::as_ref);
        match value {
            Some("bash") => Ok(Some(ShellKind::Bash)),
            Some("ps") => Ok(Some(ShellKind::PowerShell)),
            Some(value) => Err(Self::make_error(command, "completion", value)),
            None => Ok(None),
        }
    }

    fn create_completion(command: &mut Command, name: String, value: ShellKind) {
        let mut stdout = std::io::stdout();
        let value = match value {
            ShellKind::Bash => Shell::Bash,
            ShellKind::PowerShell => Shell::PowerShell,
        };
        clap_complete::generate(value, command, name, &mut stdout);
    }

    fn make_error<T: Display>(command: &mut Command, option: &str, value: T) -> MyError {
        let message = format!("Invalid {option} option: {value}");
        let error = command.error(clap::error::ErrorKind::ValueValidation, message);
        return MyError::Clap(error);
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            paths: Vec::new(),
            values: Vec::new(),
            completion: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Display;

    use crate::config::Config;

    #[test]
    fn test_paths_are_handled() {
        let expected: Vec<String> = vec![];
        let args = vec!["rpn"];
        let config = create_config(args);
        assert_eq!(expected, config.paths);

        let expected = vec!["file1"];
        let args = vec!["rpn", "file1"];
        let config = create_config(args);
        assert_eq!(expected, config.paths);

        let expected = vec!["file1", "file2"];
        let args = vec!["rpn", "file1", "file2"];
        let config = create_config(args);
        assert_eq!(expected, config.paths);
    }

    #[test]
    fn test_values_are_handled() {
        let expected = vec!["1"];
        let args = vec!["rpn", "-c", "1"];
        let config = create_config(args);
        assert_eq!(expected, config.values);

        let expected = vec!["1", "-2", "add"];
        let args = vec!["rpn", "--command", "1", "-2", "add"];
        let config = create_config(args);
        assert_eq!(expected, config.values);
    }

    fn create_config(args: Vec<&str>) -> Config {
        let mut command = Config::create_command(String::from("rpn"));
        let args = args.into_iter().map(String::from).collect();
        let matches = Config::create_matches(&mut command, args).unwrap_or_else(handle_error);
        let config = Config::create_config(&mut command, matches).unwrap_or_else(handle_error);
        return config;
    }

    fn handle_error<T, E: Display>(err: E)-> T {
        panic!("{}", err);
    }
}