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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::error::FlagError;
use crate::{Flag, FlagType, FlagValue};

/// `Context` type
///
/// This type is used only for `Action` arguments
pub struct Context {
    /// `Vec<String>` with flags and flag values ​​removed from command line arguments
    pub args: Vec<String>,
    /// `Vec` that stores flag name and flag value as tuple
    flags: Option<Vec<(String, Result<FlagValue, FlagError>)>>,
    help_text: String,
}

impl Context {
    /// Create new instance of `Context`
    /// Parse processing using `Vec<String>` command line argument and `Vec<Flag>` as arguments
    pub fn new(args: Vec<String>, flags: Option<Vec<Flag>>, help_text: String) -> Self {
        let mut v = Vec::new();
        let mut parsed_args = args;
        let flags_val = match flags {
            Some(flags) => {
                for flag in flags {
                    if let Some(index) = flag.option_index(&parsed_args) {
                        parsed_args.remove(index);

                        let val = if flag.flag_type != FlagType::Bool {
                            if parsed_args.len() <= index {
                                None
                            } else {
                                Some(parsed_args.remove(index))
                            }
                        } else {
                            None
                        };
                        v.push((flag.name.to_string(), flag.value(val)))
                    } else {
                        v.push((flag.name.to_string(), Err(FlagError::NotFound)))
                    }
                }
                Some(v)
            }
            None => None,
        };

        Self {
            args: parsed_args,
            flags: flags_val,
            help_text,
        }
    }

    /// Get flag value
    fn result_flag_value(&self, name: &str) -> Result<FlagValue, FlagError> {
        let flag = self
            .flags
            .as_ref()
            .and_then(|flags| flags.iter().find(|flag| flag.0 == name));

        match flag {
            Some(f) => match &f.1 {
                Ok(val) => Ok(val.to_owned()),
                Err(e) => Err(e.to_owned()),
            },
            None => Err(FlagError::Undefined),
        }
    }

    /// Get bool flag
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     if c.bool_flag("bool") {
    ///         println!("True!");
    ///     } else {
    ///         println!("False!");
    ///     }
    /// }
    /// ```
    pub fn bool_flag(&self, name: &str) -> bool {
        let r = self.result_flag_value(name);
        match r {
            Ok(FlagValue::Bool(val)) => val,
            _ => false,
        }
    }

    /// Get string flag
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     match c.string_flag("string") {
    ///         Ok(s) => println!("{}", s),
    ///         Err(e) => println!("{}", e)
    ///     }
    /// }
    /// ```
    pub fn string_flag(&self, name: &str) -> Result<String, FlagError> {
        let r = self.result_flag_value(name)?;
        match r {
            FlagValue::String(val) => Ok(val),
            _ => Err(FlagError::TypeError),
        }
    }

    /// Get int flag
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     match c.int_flag("int") {
    ///         Ok(i) => println!("{}", i),
    ///         Err(e) => println!("{}", e)
    ///     }
    /// }
    /// ```
    pub fn int_flag(&self, name: &str) -> Result<isize, FlagError> {
        let r = self.result_flag_value(name)?;
        match r {
            FlagValue::Int(val) => Ok(val),
            _ => Err(FlagError::TypeError),
        }
    }

    /// Get Uint flag
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     match c.uint_flag("uint") {
    ///         Ok(i) => println!("{}", i),
    ///         Err(e) => println!("{}", e)
    ///     }
    /// }
    /// ```
    pub fn uint_flag(&self, name: &str) -> Result<usize, FlagError> {
        let r = self.result_flag_value(name)?;
        match r {
            FlagValue::Uint(val) => Ok(val),
            _ => Err(FlagError::TypeError),
        }
    }

    /// Get float flag
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     match c.float_flag("float") {
    ///         Ok(f) => println!("{}", f),
    ///         Err(e) => println!("{}", e)
    ///     }
    /// }
    /// ```
    pub fn float_flag(&self, name: &str) -> Result<f64, FlagError> {
        let r = self.result_flag_value(name)?;
        match r {
            FlagValue::Float(val) => Ok(val),
            _ => Err(FlagError::TypeError),
        }
    }

    /// Display help
    ///
    /// Example
    ///
    /// ```
    /// use seahorse::Context;
    ///
    /// fn action(c: &Context) {
    ///     c.help();
    /// }
    /// ```
    pub fn help(&self) {
        println!("{}", self.help_text);
    }
}

#[cfg(test)]
mod tests {
    use crate::error::FlagError;
    use crate::{Context, Flag, FlagType};

    #[test]
    fn context_test() {
        let args = vec![
            "cli".to_string(),
            "command".to_string(),
            "args".to_string(),
            "--bool".to_string(),
            "--string".to_string(),
            "test".to_string(),
            "--int".to_string(),
            "100".to_string(),
            "--uint".to_string(),
            "1234567654321".to_string(),
            "--float".to_string(),
            "1.23".to_string(),
            "--invalid_float".to_string(),
            "invalid".to_string(),
        ];
        let flags = vec![
            Flag::new("bool", FlagType::Bool),
            Flag::new("string", FlagType::String),
            Flag::new("int", FlagType::Int),
            Flag::new("uint", FlagType::Uint),
            Flag::new("float", FlagType::Float),
            Flag::new("invalid_float", FlagType::Float),
            Flag::new("not_specified", FlagType::String),
        ];
        let context = Context::new(args, Some(flags), "".to_string());

        assert_eq!(context.bool_flag("bool"), true);
        assert_eq!(context.string_flag("string"), Ok("test".to_string()));
        assert_eq!(context.int_flag("int"), Ok(100));
        assert_eq!(context.uint_flag("uint"), Ok(1234567654321));
        assert_eq!(context.float_flag("float"), Ok(1.23));

        // string value arg, string flag, used as int
        assert_eq!(context.int_flag("string"), Err(FlagError::TypeError));
        // string value arg, string flag, used as uint
        assert_eq!(context.uint_flag("string"), Err(FlagError::TypeError));
        // string value arg, float flag, used as float
        assert_eq!(
            context.float_flag("invalid_float"),
            Err(FlagError::ValueTypeError)
        );
        // use a flag whose name is not defined as flag
        assert_eq!(
            context.string_flag("not_registered"),
            Err(FlagError::Undefined)
        );
        // use a flag but it's value not passed
        assert_eq!(
            context.string_flag("not_specified"),
            Err(FlagError::NotFound)
        );
    }
}