cmder 1.0.0-beta-1

A simple, lightweight, command line argument parser for rust codebases
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
#![allow(unused)]
use std::{env, fmt::Debug, path::PathBuf, rc::Rc};

use crate::{
    core::errors::CmderError,
    parse::{matches::ParserMatches, parser::Parser, Argument},
    ui::formatter::FormatGenerator,
    utils::{self, HelpWriter},
    Event, Pattern, PredefinedThemes, Theme,
};

use super::events::EventListener;
use super::{
    super::parse::flags::{CmderFlag, CmderOption},
    events::{EventConfig, EventEmitter},
    settings::{ProgramSettings, Setting},
};

type Callback = fn(ParserMatches) -> ();

/// Similar to the Command struct except commands created via the `Program::new()` method are marked as the root command and also contain the version flag automatically.
/// Exists due to maintain some familiarity with earlier versions of the crate
pub struct Program {}

impl Program {
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> Command<'static> {
        Command {
            flags: vec![
                CmderFlag::new("-v", "--version", "Print out version information"),
                CmderFlag::new("-h", "--help", "Print out help information"),
            ],
            is_root: true,
            emitter: Some(EventEmitter::default()),
            ..Command::new("")
        }
    }
}

/// The gist of the crate. Create instances of the program struct to chain to them all available methods. Event the program created is itself a command.
#[derive(Clone)]
pub struct Command<'p> {
    name: String,
    theme: Theme,
    is_root: bool,
    pattern: Pattern,
    alias: Option<&'p str>,
    author: Option<&'p str>,
    version: Option<&'p str>,
    arguments: Vec<Argument>,
    flags: Vec<CmderFlag<'p>>,
    options: Vec<CmderOption<'p>>,
    description: Option<&'p str>,
    more_info: Option<&'p str>,
    usage_str: Option<&'p str>,
    settings: ProgramSettings,
    emitter: Option<EventEmitter>,
    subcommands: Vec<Command<'p>>,
    callback: Option<Callback>, // (cb_function, index_of_execution)
    parent: Option<Rc<Command<'p>>>,
}

impl<'d> Debug for Command<'d> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "
            name: {},
            alias: {},
            args: {:#?},
            flags: {:#?},
            options: {:#?},
            subcmds: {:#?},
            ",
            self.name,
            self.alias.unwrap_or(""),
            self.arguments,
            self.flags,
            self.options,
            self.subcommands,
        ))
    }
}

impl<'p> Command<'p> {
    /// Simply creates a new instance of a command with the help flag added to it
    pub fn new(name: &'p str) -> Self {
        Self {
            name: name.to_string(),
            alias: None,
            arguments: vec![],
            description: None,
            flags: vec![CmderFlag::new("-h", "--help", "Print out help information")],
            options: vec![],
            subcommands: vec![],
            callback: None,
            parent: None,
            more_info: None,
            version: None,
            author: None,
            theme: Theme::default(),
            pattern: Pattern::Legacy,
            emitter: None,
            settings: ProgramSettings::default(),
            is_root: false,
            usage_str: None,
        }
    }

    // Root command options

    /// Sets the author of the program
    pub fn author(&mut self, author: &'p str) -> &mut Self {
        self.author = Some(author);
        self
    }

    /// Simply sets the version of the program
    pub fn version(&mut self, val: &'p str) -> &mut Self {
        self.version = Some(val);
        self
    }

    /// Sets the command name but only for the root command(program)
    pub fn bin_name(&mut self, val: &'p str) -> &mut Self {
        if self.is_root {
            self.name = val.into();
        }
        self
    }

    // Getters

    /// Returns the author of the program or empty value if none is set
    pub fn get_author(&self) -> &str {
        self.author.unwrap_or("")
    }

    /// Returns the provided version of the program or empty string slice
    pub fn get_version(&self) -> &str {
        self.version.unwrap_or("")
    }

    /// Returns configured theme of the program
    pub fn get_theme(&self) -> &Theme {
        &self.theme
    }

    /// Returns configured program pattern
    pub fn get_pattern(&self) -> &Pattern {
        &self.pattern
    }

    /// Getter for the command name
    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }

    /// A getter for the command alias or empty value if none is found
    pub fn get_alias(&self) -> &str {
        self.alias.unwrap_or("")
    }

    /// Returns a reference to a vector containing all the flags of a given command
    pub fn get_flags(&self) -> &Vec<CmderFlag> {
        &self.flags
    }

    /// Returns the command description or empty string slice
    pub fn get_description(&self) -> &str {
        self.description.unwrap_or("")
    }

    /// Returns a ref to a vector containing all configured command options
    pub fn get_options(&self) -> &Vec<CmderOption> {
        &self.options
    }

    /// Returns borrowed vectot with command arguments
    pub fn get_arguments(&self) -> &Vec<Argument> {
        &self.arguments
    }

    /// Returns the vector of subcommands of a command
    pub fn get_subcommands(&self) -> &Vec<Self> {
        &self.subcommands
    }

    /// Returns the parent of a given command if any
    pub fn get_parent(&self) -> Option<&Rc<Self>> {
        self.parent.as_ref()
    }

    /// Returns the usage string of a command
    pub fn get_usage_str(&self) -> String {
        let mut parent = self.get_parent();

        let mut usage = vec![self.get_name()];
        let mut usage_str = String::new();

        while parent.is_some() {
            usage.push(parent.unwrap().get_name());
            parent = parent.unwrap().get_parent();
        }

        usage.reverse();

        for v in &usage {
            usage_str.push_str(v);
            usage_str.push(' ');
        }

        usage_str.trim().into()
    }

    /// A utility method used to check if a subcommand is contained within a command and returns a reference to said subcommand if found
    pub fn find_subcommand(&self, val: &str) -> Option<&Command<'_>> {
        self.subcommands
            .iter()
            .find(|c| c.get_name() == val || c.get_alias() == val)
    }

    fn _set_bin_name(&mut self, val: &str) {
        if self.name.is_empty() {
            let p_buff = PathBuf::from(val);

            if let Some(name) = p_buff.file_name() {
                self.name = name.to_str().unwrap().into();
            };
        }
    }

    // Core functionality
    fn _add_args(&mut self, args: &[&str]) {
        for p in args.iter() {
            let temp = Argument::new(p, None);
            if !self.arguments.contains(&temp) {
                self.arguments.push(temp);
            }
        }
    }

    fn _add_parent(&mut self, parent: Rc<Self>) -> &mut Self {
        self.parent = Some(parent);
        self
    }

    #[deprecated(note = "Subcmds now built automatically")]
    pub fn build(&mut self) {}

    /// Sets the alias of a given command
    pub fn alias(&mut self, val: &'p str) -> &mut Self {
        self.alias = Some(val);
        self
    }

    /// Sets the description or help string of a command
    pub fn description(&mut self, val: &'p str) -> &mut Self {
        self.description = Some(val);
        self
    }

    /// Adds a new subcommand to an instance of a command
    pub fn subcommand(&mut self, name: &'p str) -> &mut Self {
        let parent = Rc::new(self.to_owned());

        self.subcommands.push(Self::new(name));
        self.subcommands.last_mut().unwrap()._add_parent(parent)
    }

    /// Used to register a new argument, receives the name of the argument and its help string
    pub fn argument(&mut self, val: &str, help: &str) -> &mut Self {
        let arg = Argument::new(val, Some(help.to_string()));

        if !self.arguments.contains(&arg) {
            self.arguments.push(arg);
        }

        self
    }

    /// A method used to configure the function to be invoked when the command it is chained to is matched
    pub fn action(&mut self, cb: Callback) -> &mut Self {
        self.callback = Some(cb);
        self
    }

    fn _generate_option(&mut self, values: Vec<&'p str>, help: &'p str, r: bool) {
        let mut short = "";
        let mut long = "";
        let mut args = vec![];

        for v in &values {
            if v.starts_with("--") {
                long = v;
            } else if v.starts_with('-') {
                short = v;
            } else {
                args.push(*v);
            }
        }

        let option = CmderOption::new(short, long, help, &args[..]).required(r);
        if !self.options.contains(&option) {
            self.options.push(option)
        }
    }

    /// Similar to the .option() method but it is instead used to register options that are required
    pub fn required(&mut self, val: &'p str, help: &'p str) -> &mut Self {
        let values: Vec<_> = val.split_whitespace().collect();
        self._generate_option(values, help, true);

        self
    }

    /// Registers a new option or flag depending on the values passed along with the help string for the flag or option
    pub fn option(&mut self, val: &'p str, help: &'p str) -> &mut Self {
        let values: Vec<_> = val.split_whitespace().collect();

        let mut short = "";
        let mut long = "";
        let mut args = vec![];

        for v in &values {
            if v.starts_with("--") {
                long = v;
            } else if v.starts_with('-') {
                short = v;
            } else {
                args.push(*v);
            }
        }

        if args.is_empty() {
            let flag = CmderFlag::new(short, long, help);
            if !self.flags.contains(&flag) {
                self.flags.push(flag)
            };
        } else {
            self._generate_option(values, help, false);
        }

        self
    }

    // Settings

    /// A method used to register a new listener to the program. It takes in a closure that will be invoked when the given event occurs
    pub fn on(&mut self, event: Event, cb: EventListener) {
        if let Some(emitter) = &mut self.emitter {
            emitter.on(event, cb, 0)
        }
    }

    /// Used to emit events and thus trigger the callbacks
    pub(crate) fn emit(&self, cfg: EventConfig) {
        if let Some(emitter) = &self.emitter {
            emitter.emit(cfg);
        }
    }

    /// A global method used to configure all settings of the program. This settings are defined in the `Setting` enum
    pub fn set(&mut self, setting: Setting) {
        let s = &mut self.settings;

        use Setting::*;
        match setting {
            ChoosePredefinedTheme(theme) => match theme {
                PredefinedThemes::Plain => self.theme = Theme::plain(),
                PredefinedThemes::Colorful => self.theme = Theme::colorful(),
            },
            EnableCommandSuggestion(enable) => s.enable_command_suggestions = enable,
            HideCommandAliases(hide) => s.hide_command_aliases = hide,
            SeparateOptionsAndFlags(separate) => s.separate_options_and_flags = separate,
            ShowHelpOnAllErrors(show) => s.show_help_on_all_errors = show,
            ShowHelpOnEmptyArgs(show) => s.show_help_on_empty_args = show,
            DefineCustomTheme(theme) => self.theme = theme,
            SetProgramPattern(pattern) => self.pattern = pattern,
            OverrideAllDefaultListeners(val) => s.override_all_default_listeners = val,
            OverrideSpecificEventListener(event) => s.events_to_override.push(event),
            AutoIncludeHelpSubcommand(val) => s.auto_include_help_subcommand = val,
            EnableTreeViewSubcommand(val) => s.enable_tree_view_subcommand = val,
            IgnoreAllErrors(val) => s.ignore_all_errors = val,
        }
    }

    // Parser
    fn _handle_root_flags(&self, matches: &ParserMatches) {
        let cmd = matches.get_matched_cmd().unwrap();
        let program = matches.get_program();

        let cfg = EventConfig::new(program);
        if matches.contains_flag("-h") {
            self.emit(cfg.set_matched_cmd(cmd).set_event(Event::OutputHelp));
        } else if matches.contains_flag("-v") && cmd.is_root {
            self.emit(
                cfg.arg_c(1_usize)
                    .args(vec![program.get_version().to_string()])
                    .set_event(Event::OutputVersion),
            );
        }
    }

    fn __parse(&'p mut self, args: Vec<String>) {
        self._set_bin_name(&args[0]);

        // TODO: Rewrite this functionality
        self.__init(); // performance dip here

        let mut parser = Parser::new(self);

        match parser.parse(args[1..].to_vec()) {
            Ok(matches) => {
                self._handle_root_flags(&matches);

                if let Some(cmd) = matches.get_matched_cmd() {
                    if let Some(cb) = cmd.callback {
                        (cb)(matches);
                    }
                }
            }
            Err(e) => {
                // FIXME: No clones
                // TODO: Impl into eventcfg from cmdererror
                let clone = self.clone();
                let shared_cfg = EventConfig::new(&clone).error_str(e.clone().into());

                use CmderError::*;
                let event_cfg = match e {
                    MissingRequiredArgument(args) => shared_cfg
                        .arg_c(args.len())
                        .args(args)
                        .exit_code(5)
                        .set_event(Event::MissingRequiredArgument),
                    OptionMissingArgument(args) => shared_cfg
                        .arg_c(args.len())
                        .args(args)
                        .exit_code(10)
                        .set_event(Event::OptionMissingArgument),
                    UnknownCommand(cmd) => shared_cfg
                        .arg_c(1)
                        .args(vec![cmd])
                        .exit_code(15)
                        .set_event(Event::UnknownCommand),
                    UnknownOption(opt) => shared_cfg
                        .arg_c(1)
                        .args(vec![opt])
                        .exit_code(20)
                        .set_event(Event::UnknownOption),
                    UnresolvedArgument(vals) => shared_cfg
                        .arg_c(vals.len())
                        .args(vals)
                        .exit_code(25)
                        .set_event(Event::UnresolvedArgument),
                };

                self.emit(event_cfg);
            }
        }
    }

    fn __init(&mut self) {
        if !self.subcommands.is_empty() && self.settings.auto_include_help_subcommand {
            // Add help subcommand
            self.subcommand("help")
                .argument("<SUB-COMMAND>", "The subcommand to print out help info for")
                .description("A subcommand used for printing out help")
                .action(|m| {
                    let cmd = m.get_matched_cmd().unwrap();
                    let val = m.get_arg("<SUB-COMMAND>").unwrap();
                    let parent = cmd.get_parent().unwrap();

                    if let Some(cmd) = parent.find_subcommand(&val) {
                        cmd.output_help();
                    }
                });
        }

        // Means that it is the root_cmd(program)
        if let Some(emitter) = &mut self.emitter {
            let settings = &self.settings;

            use Event::*;

            emitter.on(
                OutputHelp,
                |cfg| cfg.get_matched_cmd().unwrap().output_help(),
                -4,
            );

            // Register default listeners
            if !settings.override_all_default_listeners {
                // Default behavior for errors is to print the error message
                if !settings.ignore_all_errors {
                    emitter.on_all_errors(
                        |cfg| {
                            let error = cfg.get_error_str();

                            // TODO: Improve default error handling
                            if !error.is_empty() {
                                eprintln!("Error: {error}");
                            }
                        },
                        -4,
                    );
                }

                // Register default output version listener
                emitter.on(
                    OutputVersion,
                    |cfg| {
                        let p = cfg.get_program();

                        println!("{}, v{}", p.get_name(), p.get_version());
                        println!("{}", p.get_author());
                        println!("{}", p.get_description());
                    },
                    -4,
                );

                // Remove default listeners if behavior set to override
                for event in &settings.events_to_override {
                    emitter.rm_lstnr_idx(*event, -4)
                }
            }

            // Register help listeners
            if settings.show_help_on_all_errors && !settings.ignore_all_errors {
                let _output_help_ = |cfg: EventConfig| cfg.get_matched_cmd().unwrap().output_help();

                // Output help on all error events
                emitter.insert_before_all(_output_help_);
            }

            // TODO: remove this
            // Register listener for unknown commands
            if settings.enable_command_suggestions {
                // Remove default listener to register new default one
                emitter.rm_lstnr_idx(UnknownCommand, -4);

                emitter.on(
                    UnknownCommand,
                    |cfg| {
                        println!("Error: {}\n", cfg.get_error_str());

                        // Suggest command
                        let prog = cfg.get_program();
                        let cmd = &cfg.get_args()[0];

                        if let Some(ans) = utils::suggest_cmd(cmd, prog.get_subcommands()) {
                            // output command suggestion
                            println!("       Did you mean: `{ans}` ?\n")
                        }
                    },
                    -1,
                )
            }
        }
    }

    /// Builds the command and parses the args passed to it automatically
    pub fn parse(&'p mut self) {
        let args = env::args().collect::<Vec<_>>();
        self.__parse(args);
    }

    /// Builds the command and parses from the vector of string slices passed to it
    pub fn parse_from(&'p mut self, list: Vec<&str>) {
        let args = list.iter().map(|a| a.to_string()).collect::<Vec<_>>();
        self.__parse(args);
    }

    // Others

    /// Prints out help information for a command
    pub fn output_help(&self) {
        HelpWriter::write(self, self.get_theme(), self.get_pattern());
    }

    /// Method used to register a listener before all events
    pub fn before_all(&mut self, cb: EventListener) {
        if let Some(emitter) = &mut self.emitter {
            emitter.insert_before_all(cb)
        }
    }

    /// Register a listener after all other listeners
    pub fn after_all(&mut self, cb: EventListener) {
        if let Some(emitter) = &mut self.emitter {
            emitter.insert_after_all(cb)
        }
    }

    /// Register a listener only before help is printed out
    pub fn before_help(&mut self, cb: EventListener) {
        if let Some(emitter) = &mut self.emitter {
            emitter.on(Event::OutputHelp, cb, -4)
        }
    }

    /// Register a listener to be invoked after help is printed out
    pub fn after_help(&mut self, cb: EventListener) {
        if let Some(emitter) = &mut self.emitter {
            emitter.on(Event::OutputHelp, cb, 1)
        }
    }

    // Debug utilities
    pub fn display_commands_tree(&self) {
        let mut commands = self.get_subcommands();
        let mut empty = String::new();

        let mut parent = self.get_parent();

        while parent.is_some() {
            empty.push('\t');
            empty.push('|');

            parent = parent.unwrap().get_parent();
        }

        println!("{}-> {}", &empty, self.get_name());

        for cmd in commands.iter() {
            cmd.display_commands_tree();
        }
    }

    pub fn init_dbg(&mut self) {
        self.__init();
    }
}

impl<'f> FormatGenerator for Command<'f> {
    fn generate(&self, ptrn: Pattern) -> (String, String) {
        match &ptrn {
            Pattern::Custom(ptrn) => {
                let base = &ptrn.sub_cmds_fmter;

                let mut leading = base.replace("{{name}}", self.get_name());
                let mut floating = String::from("");

                if let Some(alias) = self.alias {
                    leading = leading.replace("{{alias}}", alias)
                } else {
                    leading = leading.replace("{{alias}}", "")
                }

                if base.contains("{{args}}") && !self.get_arguments().is_empty() {
                    let mut value = String::new();

                    for a in self.get_arguments() {
                        value.push_str(&(a.literal));
                        value.push(' ');
                    }

                    leading = leading.replace("{{args}}", value.trim());
                }

                if base.contains("{{description}}") {
                    leading = leading.replace("{{description}}", self.get_author());
                } else {
                    floating = self.get_description().into()
                }

                (leading, floating)
            }
            _ => (self.get_name().into(), self.get_description().into()),
        }
    }
}

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

    #[test]
    fn test_prog_creation() {
        let mut program = Program::new();

        assert!(program.is_root);
        assert!(program.emitter.is_some());
        assert!(program.get_flags().len() == 2);
        assert!(program.get_parent().is_none());
        assert!(program.get_name().is_empty());
        assert!(program.get_version().is_empty());
        assert!(program.get_subcommands().is_empty());

        program
            .author("vndaba")
            .bin_name("test1")
            .version("0.1.0")
            .argument("<dummy>", "Some dummy value");

        assert_eq!(program.get_author(), "vndaba");
        assert_eq!(program.get_name(), "test1");
        assert_eq!(program.get_version(), "0.1.0");
        assert_eq!(
            program.get_arguments(),
            &vec![Argument::new("<dummy>", Some("Some dummy value".into()))]
        )
    }

    #[test]
    fn test_cmd_creation() {
        let cmd = Command::new("test2");

        assert!(!cmd.is_root);
        assert!(cmd.emitter.is_none());
        assert!(cmd.parent.is_none());
        assert_eq!(cmd.get_name(), "test2");
        assert_eq!(
            cmd.get_flags(),
            &vec![CmderFlag::new("-h", "--help", "Print out help information")]
        );
    }
}