tiny-args 0.2.0

Tiny command line argument parser
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*!
 A tiny command line argument parser with automatic help generation, and argument validation.

- Inputs are categorized as `commands`, `options`, and `va args`.
- Commands and va args have no prefixes. First argument of such kind is stored as the command, and the rest into a va_args "bucket", which can be retrived with `get_va_args()`.
- Options/flags are defined with the `-` or `--` prefixes.
- These can hold values representing booleans, numbers and text values, (stored internally as bool, f64 and Strings).
- Arguments with values are strictly defined with the equal sign `=` like: `--arg=value`.
- Help sections such as description, usage, and examples can be redefined if needed using the
   provided functions: `define_help_...()`.
 - The help call is hard coded.


 ## Example
 ```
use std::process::ExitCode;
use tiny_args::*;

fn main() -> ExitCode {
    let mut args = TinyArgs::new();

    // Optional help definitions:
    args.define_help_program_name("demo");
    args.define_help_description("A demo program for TinyArgs");
    args.define_help_usage("[OPTIONS] [COMMAND] [ARGS]...");
    args.define_help_example("--name=test some/path/  - Sets some values");

    let list = args.define_command("list", "List vargs");
    let version = args.define_command("version", "Display version");

    let name = args.define_option_txt("name", "", "test", "A name of something");
    let context = args.define_option_num("context", "c", 4, "Context lines");
    let verbose = args.define_option_bool("verbose", "v", false, "Verbose mode");

    if let Err(e) = args.parse_arguments() {
        eprintln!("Error: {e}");
        return ExitCode::FAILURE;
    }

    println!("name: {}", args.get_option(name));
    println!("context: {}", args.get_option(context));
    println!("verbose: {}", args.get_option(verbose));

    if args.command() == version {
        println!("Version: 1.2.3.4");
    }

    if args.command() == list {
        for arg in args.get_va_args() {
            println!("{arg}");
        }
    }

    ExitCode::SUCCESS
}
 }
 ```
## Generated Help

```none
>demo_program --help

A demo program for TinyArgs

Help:

  Usage: demo [OPTIONS] [COMMAND] [ARGS]...

  Commands:

      list                     List args
      version                  Display version

  Options:

    -c, --context=<context>    Context lines [Default: 4]
    -h, --help                 Display this help message
        --name=<name>          A name of something [Default: test]
    -v, --verbose              Verbose mode

Examples:

  demo --name=test some/path/  - Sets some values
```
*/

use std::any::type_name;
use std::collections::HashMap;
use std::fmt::Display;
use std::marker::PhantomData;
use std::num::ParseFloatError;
use std::str::ParseBoolError;

#[derive(Clone, Debug)]
pub enum Error {
    ParseValue { value: String, arg: String },
    UnknownOpt(String),
    UnknownCmd(String),
    Parse(String),
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::ParseValue { value, arg } => {
                write!(f, "Cannot parse value: {} for argument: {}", value, arg)
            }
            Error::UnknownOpt(s) => write!(f, "Unknown option: {}", s),
            Error::UnknownCmd(s) => write!(f, "Unknown command: {}", s),
            Error::Parse(s) => f.write_str(s),
        }
    }
}

impl std::error::Error for Error {}

/// Possible argument values
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Bool(bool),
    Num(f64),
    Txt(String),
}

impl Value {
    /// Parse str as bool Val
    pub fn parse_as_bool(input_val: &str) -> Result<Self, ParseBoolError> {
        let b = input_val.parse::<bool>()?;
        Ok(Value::Bool(b))
    }

    /// Parse str as num Val
    pub fn parse_as_num(input_val: &str) -> Result<Self, ParseFloatError> {
        let num = input_val.parse::<f64>()?;
        Ok(Value::Num(num))
    }
}

pub trait FromValue: Sized {
    fn from_value(v: &Value) -> Option<Self>;
}

impl FromValue for bool {
    fn from_value(v: &Value) -> Option<Self> {
        if let Value::Bool(b) = v {
            Some(*b)
        } else {
            None
        }
    }
}

impl FromValue for f64 {
    fn from_value(v: &Value) -> Option<Self> {
        if let Value::Num(n) = v {
            Some(*n)
        } else {
            None
        }
    }
}

impl FromValue for String {
    fn from_value(v: &Value) -> Option<Self> {
        if let Value::Txt(s) = v {
            Some(s.clone())
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Argument {
    pub name: &'static str,
    pub short_name: &'static str,
    pub description: &'static str,
    pub default: Value,
    pub value: Value,
    pub was_set: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Command {
    pub name: &'static str,
    pub description: &'static str,
}

#[derive(Debug, Default, Clone, PartialEq)]
pub struct TinyArgs {
    pub program_name: String,
    pub description: String,
    pub help: String,
    pub usage: String,
    pub examples: Vec<String>,
    pub cmds: HashMap<String, Command>,
    pub opts: HashMap<String, Argument>,
    pub va_args: Vec<String>,
    pub active_cmd: Option<Command>,
}

impl TinyArgs {
    /// Create a TinyArgs instance
    #[must_use]
    pub fn new() -> Self {
        let mut res = Self {
            program_name: String::new(),
            description: String::new(),
            help: String::new(),
            usage: String::new(),
            examples: vec![],
            cmds: HashMap::new(),
            opts: HashMap::new(),
            va_args: vec![],
            active_cmd: None,
        };

        let _ = res.define_option_bool("help", "h", false, "Display this help message");
        res
    }

    /// Define the program name displayed in the help section
    /// If not defined, the program name is automatically derived from the command line
    pub fn define_help_program_name(&mut self, name: &str) {
        self.program_name = name.to_owned();
    }

    /// Define the program description for the help section
    pub fn define_help_description(&mut self, description: &str) {
        self.description = description.into();
    }

    /// Define program usage for the help section
    /// The program name gets automatically prefixed,
    pub fn define_help_usage(&mut self, usage: &str) {
        self.usage = usage.into();
    }

    /// Define examples in for the help section
    /// You can this function multiple times to add more execution examples
    /// The program name gets automatically prefixed
    pub fn define_help_example(&mut self, examples: &str) {
        self.examples.push(examples.to_string());
    }

    /// Define a command
    #[must_use]
    pub fn define_command(&mut self, name: &'static str, description: &'static str) -> CmdHandle {
        let arg = Command { name, description };
        self.cmds.insert(name.to_owned(), arg);

        CmdHandle { name }
    }

    /// Define a boolean option
    #[must_use]
    pub fn define_option_bool(
        &mut self,
        name: &'static str,
        short_name: &'static str,
        default_value: bool,
        description: &'static str,
    ) -> OptHandle<bool> {
        self.define_argument(name, short_name, Value::Bool(default_value), description);

        OptHandle {
            name,
            _p: PhantomData::<bool>,
        }
    }

    /// Define a numerical option
    #[must_use]
    pub fn define_option_num(
        &mut self,
        name: &'static str,
        short_name: &'static str,
        default_value: impl Into<f64>,
        description: &'static str,
    ) -> OptHandle<f64> {
        self.define_argument(
            name,
            short_name,
            Value::Num(default_value.into()),
            description,
        );

        OptHandle {
            name,
            _p: PhantomData::<f64>,
        }
    }

    /// Define a text option
    #[must_use]
    pub fn define_option_txt(
        &mut self,
        name: &'static str,
        short_name: &'static str,
        default_value: &str,
        description: &'static str,
    ) -> OptHandle<String> {
        self.define_argument(
            name,
            short_name,
            Value::Txt(default_value.into()),
            description,
        );

        OptHandle {
            name,
            _p: PhantomData::<String>,
        }
    }

    /// Internal
    fn define_argument(
        &mut self,
        name: &'static str,
        short_name: &'static str,
        default_value: Value,
        description: &'static str,
    ) {
        let arg = Argument {
            name,
            short_name,
            description,
            value: default_value.clone(),
            default: default_value,
            was_set: false,
        };
        self.opts.insert(name.to_owned(), arg);
    }

    /// Get the option's value from the stored handle
    #[must_use]
    pub fn get_option<T: FromValue>(&self, opt_handle: OptHandle<T>) -> T {
        let val = &self.find_argument(opt_handle.name).value;

        T::from_value(&val).unwrap_or_else(|| {
            panic!(
                "type mismatch for argument {} when converting from {:?} to {}",
                opt_handle.name,
                val,
                type_name::<T>()
            )
        })
    }

    /// Get the active command handle
    /// CmdHandle::NONE is returned if no command is set
    /// Example:
    ///  ```
    ///      if args.command() == version {
    ///          println!("Version: 1.2.3.4");
    ///      }
    ///  ```
    pub fn command(&self) -> CmdHandle {
        let name = self.active_cmd.as_ref().map_or_else(|| "", |c| c.name);

        if name.is_empty() {
            return CmdHandle::NONE;
        }

        CmdHandle { name }
    }

    /// This function MUST be run for the input arguments to be processed
    /// Automatically handles the help printout if "help" or "h" is encountered
    /// Call example:
    /// ```
    ///
    ///    if let Err(e) = args.parse_arguments() {
    ///        eprintln!("Error: {e}");
    ///        return ExitCode::FAILURE;
    ///    }
    ///
    /// ```
    pub fn parse_arguments(&mut self) -> Result<(), Error> {
        let args = std::env::args().collect();
        self.parse_arguments_from_vec(args)
    }

    /// Parse arguments from a provided vector of Strings
    pub fn parse_arguments_from_vec(&mut self, args: Vec<String>) -> Result<(), Error> {
        let mut args_iter = args.iter();

        let input_name = args_iter.next().ok_or_else(|| {
            Error::Parse("Failed parsing first argument (executable path)".to_owned())
        })?;

        // We derive the program name if none was defined by the user
        if self.program_name.is_empty() {
            let split: Vec<&str> = input_name.split(|c| c == '\\' || c == '/').collect();

            self.program_name = split
                .last()
                .map_or("program_name".to_owned(), |s| s.to_string())
        }

        for input in args_iter {
            // Trimming - or -- prefixes
            let trimmed_input = input.trim_start_matches('-').to_owned();
            if trimmed_input.is_empty() {
                return Err(Error::Parse("Invalid argument starting with -".to_owned()));
            }

            // Parsing command or va_arg
            if &trimmed_input == input {
                // Argument was not prefixed with - or --
                if let Some(cmd) = self.cmds.get_mut(&trimmed_input)
                    && self.active_cmd.is_none()
                {
                    // No command was registered, and command is valid
                    self.active_cmd = Some(cmd.clone());
                    // TODO Do something about help?
                    //
                } else if self.active_cmd.is_some() || self.cmds.is_empty() {
                    // Va args
                    self.va_args.push(trimmed_input); // We add it to the va args bucket
                } else {
                    // Commands are defined, this is the first command input, but we don't recognise this specific one
                    return Err(Error::UnknownCmd(trimmed_input));
                }
                continue; // We continue to next arg
            }

            let mut input_arg = trimmed_input;
            let mut input_val = String::new();

            // Try splitting arg=value into separate parts
            //
            // If value is not present, then the value string stays empty.
            if let Some((left, right)) = input_arg.split_once('=') {
                if left.is_empty() {
                    return Err(Error::Parse(format!("Argument missing before ={}", right)));
                }

                if right.is_empty() {
                    return Err(Error::Parse(format!("Value missing after {}=", left)));
                }
                input_val = right.to_owned();
                input_arg = left.to_owned();
            }

            // We catch help option flags and display it immediately
            if input_arg == "help" || input_arg == "h" {
                self.print_help_and_exit(0);
            }

            // Find the argument against user registered ones
            let found_arg = self.opts.iter_mut().find_map(|(_, a)| {
                if input_arg == a.name || input_arg == a.short_name {
                    Some(a)
                } else {
                    None
                }
            });

            if let Some(argument) = found_arg {
                argument.was_set = true;
                // Only boolean options/flags can be set without an explicit value
                if input_val.is_empty() {
                    if matches!(argument.value, Value::Bool(_)) {
                        argument.value = Value::Bool(true)
                    }
                }
                // Options/flags with explicit value assignment arg=val
                else {
                    argument.value = match argument.value {
                        Value::Txt(_) => Value::Txt(input_val),
                        Value::Num(_) => {
                            Value::parse_as_num(&input_val).map_err(|_| Error::ParseValue {
                                value: input_val,
                                arg: input_arg,
                            })?
                        }
                        Value::Bool(_) => {
                            Value::parse_as_bool(&input_val).map_err(|_| Error::ParseValue {
                                value: input_val,
                                arg: input_arg,
                            })?
                        }
                    }
                }
            } else {
                // Argument not defined - unknown
                return Err(Error::UnknownOpt(input_arg));
            }
        }

        Ok(())
    }

    /// Internal - Acts as get, should not fail
    fn find_argument(&self, name: &str) -> &Argument {
        self.opts
            .get(name)
            .unwrap_or_else(|| panic!("Could not find argument: {name}"))
    }

    /// Find if an argument was explicitly set by the user
    pub fn was_option_set<T>(&self, arg_handle: OptHandle<T>) -> bool {
        self.find_argument(arg_handle.name).was_set
    }

    /// Retrieve the rest of input va args
    pub fn get_va_args(&self) -> std::slice::Iter<'_, String> {
        self.va_args.iter()
    }

    fn generate_help(&mut self) {
        if self.usage.is_empty() {
            self.usage = {
                let mut options = "";
                let mut commands = "";

                if !self.opts.is_empty() {
                    options = "[OPTIONS] "
                };

                if !self.cmds.is_empty() {
                    commands = "[COMMANDS] "
                };

                format!("{}{}[ARGS]...", options, commands)
            }
        }

        let examples = {
            let mut res = String::new();

            if !self.examples.is_empty() {
                res = "\nExamples:\n\n".to_owned() + &res;
                self.examples.iter().for_each(|s| {
                    res.push_str(&format!("  {program} {s}\n", program = self.program_name))
                });
            }

            res
        };

        self.help = format!(
            "
{description}

Help:

  Usage: {program} {usage}
{commands} {arguments} {examples}
",
            description = self.description,
            program = self.program_name,
            usage = self.usage,
            commands = if !self.cmds.is_empty() {
                "\n  Commands:\n\n".to_string() + &self.generate_cmds_help_list()
            } else {
                "".to_string()
            },
            arguments = if !self.opts.is_empty() {
                "\n  Options:\n\n".to_string() + &self.generate_args_help_list()
            } else {
                "".to_string()
            },
        );
    }

    fn generate_args_help_list(&self) -> String {
        let mut args_help = String::new();

        let mut keys: Vec<&String> = self.opts.keys().collect();
        keys.sort();

        for arg in keys.iter().map(|&k| self.opts.get(k).unwrap()) {
            let name = "--".to_owned() + arg.name;

            let short_name = {
                if !arg.short_name.is_empty() {
                    "-".to_owned() + arg.short_name + ", "
                } else {
                    "".to_string()
                }
            };

            let mut default = match &arg.default {
                Value::Bool(true) => "true".to_string(),
                Value::Txt(s) => {
                    if s.is_empty() {
                        "".to_string()
                    } else {
                        s.clone()
                    }
                }
                Value::Num(n) => n.to_string(),
                _ => "".to_string(),
            };

            let value = {
                match arg.default {
                    Value::Bool(_) => "".to_string(),
                    _ => format!("=<{}>", arg.name),
                }
            };

            if !default.is_empty() {
                default = format!("[Default: {}]", default);
            }

            let line = &format!(
                "{space:2}{short_name:>6}{name_and_val:23}{desc} {default}\n",
                space = "",
                name_and_val = name + &value,
                desc = arg.description
            );

            args_help.push_str(line);
        }

        args_help
    }

    fn generate_cmds_help_list(&self) -> String {
        let mut cmds_help = String::new();

        let mut keys: Vec<&String> = self.cmds.keys().collect();
        keys.sort();

        for cmd in keys.iter().map(|&k| self.cmds.get(k).unwrap()) {
            let line = &format!(
                "{space:6}{name:25}{desc}\n",
                space = "",
                name = cmd.name,
                desc = cmd.description
            );

            cmds_help.push_str(line);
        }

        cmds_help
    }

    /// Get help as str
    pub fn get_help_text(&mut self) -> &str {
        if self.help.is_empty() {
            self.generate_help();
        }

        &self.help
    }

    /// Print the program help
    pub fn print_help(&mut self) {
        println!("{}", self.get_help_text());
    }

    /// Print the program help and exit program with code
    pub fn print_help_and_exit(&mut self, exit_code: i32) {
        println!("{}", self.get_help_text());
        std::process::exit(exit_code);
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct OptHandle<T> {
    name: &'static str,
    _p: PhantomData<T>,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct CmdHandle {
    name: &'static str,
}

impl CmdHandle {
    const NONE: Self = CmdHandle { name: "" };
}