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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use std::env;

/**
Enum allowing to choose the type of argument.
*/
#[derive(Debug)]
pub enum ArgType
{
    Flag,
    Value,
    ValueList,
}

/**
ArgResult enum is similar to ArgType enum but contains data generated through parsing
*/
#[derive(Debug, PartialEq)]
pub enum ArgResult
{
    Flag,
    Value(String),
    ValueList(Vec<String>),
}

///

/// Argument struct allows to specify type of expected argument, its names and after parsing contains results.

///

/// # Examples

/// ```

/// use trivial_argument_parser::*;

/// let mut example_argument = Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).unwrap();

/// ```


#[derive(Debug)]
pub struct Argument
{
    short: Option<char>,
    long: Option<String>,
    arg_type: ArgType,
    pub arg_result: Option<ArgResult>,
}

impl Argument
{
    /**
    Create new Argument. You need to specify at least one name (short or long) or you can specify both. Parameter arg_type changes how the parsing will treat the argument.
    */
    pub fn new(short: Option<char>, long: Option<& str>, arg_type: ArgType) -> Result<Argument, String>
    {
        // Check if at least 1 name is specified

        match & short
        {
            None =>
            {
                match & long
                {
                    None =>
                    {
                        return Err(String::from("At least one name of argument must be specified (short or long or both)"))
                    }
                    _ => ()
                }
            }
            _ => (),
        };

        // Check if long name is defined, if so use it

        let long_owned: Option<String> = match long
        {
            Some(text) => Some(String::from(text)),
            None => None,
        };

        Ok(Argument{short, long: long_owned, arg_type, arg_result: None})
    }

    pub fn add_value(& mut self, input_iter: & mut std::slice::Iter<'_, String>) -> Result<(), String>
    {
        match self.arg_type
        {
            ArgType::Flag =>
            {
                match self.arg_result
                {
                    Some(_) => return Err(String::from("Flag already set")),
                    _ => (),
                }
                self.arg_result = Some(ArgResult::Flag);
            }
            ArgType::Value =>
            {
                match self.arg_result
                {
                    Some(_) => return Err(String::from("Value already assigned")),
                    _ => (),
                }
                match input_iter.next()
                {
                    Some(word) => self.arg_result = Some(ArgResult::Value(String::from(word))),
                    None => return Err(String::from("Expected value")),
                }

            }
            ArgType::ValueList =>
            {
                let mut new_result = false;
                match self.arg_result
                {
                    Some(_) => (),
                    None => new_result = true,
                }

                if new_result
                {
                    self.arg_result = Some(ArgResult::ValueList(Vec::new()));
                }

                match input_iter.next()
                {
                    Some(word) =>
                    {
                        match self.arg_result.as_mut().expect("as mut")
                        {
                            ArgResult::ValueList(ref mut values) => values.push(String::from(word)),
                            _ => return Err(String::from("WTF")),
                        }
                    }
                    None => return Err(String::from("Expected value")),
                }
            }
        }

        Ok(())
    }
}

///

/// Acumulates arguments into list which then can be fed to parse.

///

/// # Examples

/// ```

/// use trivial_argument_parser::*;

/// let mut args_list = ArgumentList::new();

/// args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).unwrap());

/// args_list.append_arg(Argument::new(Some('p'), None, ArgType::Value).unwrap());

/// args_list.append_arg(Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).unwrap());

/// ```

#[derive(Debug)]
pub struct ArgumentList
{
    pub dangling_values: Vec<String>,
    pub arguments: Vec<Argument>,
}

impl ArgumentList
{
    /**
    Create ArgumentList with empty vector of arguments.
    */
    pub fn new() -> ArgumentList
    {
        ArgumentList{dangling_values: Vec::new(), arguments: Vec::new()}
    }

    /**
    Append argument to the end of the list.
    */
    pub fn append_arg(& mut self, argument: Argument)
    {
        self.arguments.push(argument);
    }

    /**
    Append dangling values (dangling values)
    */
    pub fn append_dangling_value(& mut self, value: & str)
    {
        self.dangling_values.push(String::from(value));
    }

    /**
    Search arguments by short name
    */
    pub fn search_by_short_name(& mut self, name: char) -> Result<& mut Argument, String>
    {
        for x in & mut self.arguments
        {
            match x.short
            {
                Some(symbol) =>
                {
                    if symbol == name
                    {
                        return Ok(x)
                    }
                }
                None => (),
            };
        }
        Err(String::from("Argument not found"))
    }

    /**
    Search arguments by long name
    */
    pub fn search_by_long_name(& mut self, name: & str) -> Result<& mut Argument, String>
    {
        for x in & mut self.arguments
        {
            match x.long
            {
                Some(ref long_name) =>
                {
                    if long_name == name
                    {
                        return Ok(x)
                    }
                }
                None => (),
            }
        }
        Err(String::from("Argument not found"))
    }

    /// Function that does all the parsing. You need to feed user input.

    ///

    /// # Examples

    /// ```

    /// use trivial_argument_parser::*;

    ///

    /// let mut args_list = ArgumentList::new();

    /// args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).unwrap());

    /// args_list.append_arg(Argument::new(Some('p'), None, ArgType::Value).unwrap());

    /// args_list.append_arg(Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).unwrap());

    /// args_list.parse_args(args_to_string_vector(std::env::args())).unwrap();

    /// ```

    pub fn parse_args(& mut self, input: Vec<String>) -> Result<(), String>
    {
        let mut input_iter = input.iter();
        while let Some(word) = input_iter.next()
        {
            // Check if word is a short argument, long argument or dangling value

            let word_length = word.chars().count();
            let mut chars = word.chars();
            if word_length == 2
            {
                if word.chars().nth(0).expect("first letter") == '-' &&  word.chars().nth(1).expect(& format!("{}", word_length)).is_alphabetic()
                {
                    // Add value to argument identified by short name

                    match self.search_by_short_name(word.chars().nth(1).unwrap())
                    {
                        Ok(ref mut argument) =>
                        {
                            argument.add_value(& mut input_iter);
                        }
                        Err(msg) =>
                        {
                            return Err(format!("Error while parsing arguments: {}", msg))
                        }
                    };
                }
                else
                {
                    // Add as dangling value

                    self.append_dangling_value(word);
                }
            }
            else if word_length > 2
            {
                if word.chars().nth(0).unwrap() == '-' && word.chars().nth(1).unwrap() == '-' && word.chars().nth(2).unwrap().is_alphabetic()
                {
                    // Add value to argument identified by long name

                    match self.search_by_long_name(& word[2..word.len()])
                    {
                        Ok(ref mut argument) =>
                        {
                            argument.add_value(& mut input_iter);
                        }
                        Err(msg) =>
                        {
                            return Err(format!("Error while parsing arguments: {}", msg))
                        }
                    };
                }
                else
                {
                    // Add as dangling value

                    self.append_dangling_value(word);
                }
            }
            else
            {
                // Add as dangling value

                self.append_dangling_value(word);
            }
        }

        // return arguments list with filled parsed values

        Ok(())
    }
}

/**
Helper function to transform arguments given by user from Args to vector of String.
*/
pub fn args_to_string_vector(args: env::Args) -> Vec<String>
{
    let mut arguments = Vec::new();

    for x in args
    {
        arguments.push(String::from(x));
    }
    arguments
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_works()
    {
        let args = vec![String::from("-d"), String::from("-p"), String::from("/file"), String::from("--an-list"), String::from("Marcin"), String::from("-l"), String::from("Mazgaj")];
        let mut args_list = ArgumentList::new();
        args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).expect("append 1"));
        args_list.append_arg(Argument::new(Some('p'), None, ArgType::Value).expect("append 2"));
        args_list.append_arg(Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).expect("append 3"));
        args_list.parse_args(args).unwrap();
        assert_eq!(args_list.arguments[0].arg_result, Some(ArgResult::Flag));
        assert_eq!(args_list.arguments[1].arg_result, Some(ArgResult::Value(String::from("/file"))));
        assert_eq!(args_list.arguments[2].arg_result, Some(ArgResult::ValueList(vec![String::from("Marcin"), String::from("Mazgaj")])));
    }
}