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
//! This crate is using for `commander_rust`.
//!
//! Only `Application`, `Cli`, `Raw` you will use.
//!
//! `Application` will be returned by macro `run!()`.
//! It's readonly. You can get application information through it.
//! `Application` contains all information you defined using `#[option]` ,`#[command]` and `#[entry]`.
//! See `Application` for more details.
//!
//! `Cli` is an interface of CLI. You can get all argument of options through it.
//! `Cli` offered two convenient method to get argument of options.
//! They are `get(idx: &str) -> Raw` and `get_or<T: From<Raw>>(&self, idx: &str, d: T) -> T`.
//! See `Cli` for more details.
//!
//!
//! `Raw` is encapsulation of something. It a sequence of String.
//! You can regard it as `Raw(<Vec<String>>)`. In fact, it is.
//! `Raw` is using for types convert.
//! Any type implemented `From<Raw>` can be types of command processing functions' parameter.
//! For example, `Vec<i32>` implemented `From<Raw>`. So you can use it like `fn method(v: Vec<i32>)`.
//! But `slice` is not implemented `From<Raw>`, so you can not use it like `fn method(s: [i32])`.
//! Once type implemented `From<Raw>`, you can covert it's type using `let right: bool = raw.into()`.
//!


mod raw;
mod fmt;

use std::ops::Index;
use regex::Regex;
use std::collections::HashMap;

pub use raw::Raw;

/// The type of argument.
///
/// they are:
/// - <rs>    -- RequiredSingle
/// - [os]    -- OptionalSingle
/// - <rm...> -- RequiredMultiple
/// - [om...] -- OptionalMultiple
///
///
/// For most of the times, you will not use it.
///
///
#[doc(hidden)]
#[derive(PartialEq, Eq)]
#[derive(Debug, Clone)]
pub enum ArgumentType {
    RequiredSingle,
    OptionalSingle,
    RequiredMultiple,
    OptionalMultiple,
}

/// Represents a parameter.
///
/// For example, `<dir>` will represents as
/// ```ignore
/// Argument {
///     name: "dir",
///     ty: ArgumentType::RequiredSingle,
/// }
/// ```
///
/// For most of the time, you will not use it.
#[doc(hidden)]
#[derive(PartialEq, Eq)]
#[derive(Clone)]
pub struct Argument {
    pub name: String,
    pub ty: ArgumentType,
}

/// Represents an application.
///
/// Application is what? Application is generated from your code.
/// If you use `#[command]`, application will get a `Command`.
/// If you use `#[options]`, application will get a `Options`.
/// If you write descriptions in your `Cargo.toml`, application will get a `desc`.
/// If you write version in your `Cargo.toml`, application will get a `ver`.
///
/// For most of the time, you will use all of them.
///
/// And we offer a way to get the only application of your CLI.
/// Using `commander_rust::run!()`(instead of `commander_rust::run()`, it's a proc_macro) to get it.
///
/// # Note
/// It's generated by `commander_rust`, and it should be readonly.
///
pub struct Application {
    pub name: String,
    pub desc: String,
    pub cmds: Vec<Command>,
    pub opts: Vec<Options>,
}

/// Represents a instance defined by `#[command]`.
///
/// For example, `#[command(rmir <dir> [others...], "remove files")]` will generate a instance like:
/// ```ignore
/// Command {
///     name: "rmdir",
///     args: [
///         Argument {
///             name: "dir",
///             ty: ArgumentType::RequiredSingle,
///         },
///         Argument {
///             name: "others",
///             ty: ArgumentType::OptionalMultiple,
///         }
///     ],
///     desc: Some("remove files"),
///     opts: ...
/// }
/// ```
///
/// `opts` is determined by `#[option]` before `#[command]`.
///
/// # Note
/// `#[command]` should be and only should be defined after all `#[option]`.
/// It means:
/// ```ignore
/// // correct
/// #[option(...)]
/// #[command(test ...)]
/// fn test(...) {}
///
/// // fault
/// #[command(test ...)]
/// #[option(...)]
/// fn test(...) {}
/// ```
/// And the name in `#[command]` have to be same as the name of corresponding functions.
/// In this example, they are `test`.
/// For most of the time, you will not use it.
///
#[doc(hidden)]
pub struct Command {
    pub name: String,
    pub args: Vec<Argument>,
    pub desc: Option<String>,
    pub opts: Vec<Options>,
}

/// Represents a instance defined by `#[option]`.
///
/// # Note
/// `#[option]` only accepts up to one argument. And one `#[command]` can accept many `#[option]`.
/// It's similar with `Command`. See `Command` for more detail.
/// For most of the time, you will not use it.
#[derive(Debug)]
#[doc(hidden)]
pub struct Options {
    pub short: String,
    pub long: String,
    pub arg: Option<Argument>,
    pub desc: Option<String>,
}

/// A divided set of user's inputs.
///
///
/// For example, when you input `[pkg-name] rmdir /test/ -rf`, `commander_rust` will generate something like
/// ```ignore
/// [
///     Instance {
///         name: "rmdir",
///         args: ["/test/"],
///     },
///     Instance {
///         name: "r",
///         args: vec![],
///     },
///     Instance {
///         name: "f",
///         args: vec![],
///     }
/// ]
/// ```
/// For most of the time, you will not use it.
#[derive(Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct Instance {
    pub name: String,
    pub args: Vec<String>,
}

/// `Cmd` is not `Command`. It's defined by the user's input.
///
/// `name` is the first elements of inputs if the first element is one of the name of any `Command`.
/// `raws` is followed element after the first element, until something like `-rf`,`--simple=yes` appears.
/// `raws` is `Vec<Raw>`, because we one command maybe has more than one arguments.
/// See `Raw` for more details.
/// `opt_raws` is a `HashMap`. It stores elements user input that `Options` might use.
/// It's hard to understand what `Cmd' is for. Many people get confused.
/// But fortunately, for most of the time(even forever), you will not use it.
#[derive(Debug)]
#[doc(hidden)]
pub struct Cmd {
    pub name: String,
    pub raws: Vec<Raw>,
    pub opt_raws: HashMap<String, Raw>,
}


/// Something like `Cmd`.
///
/// But unfortunately, you will use it frequently.
///
/// `commander_rust` will generate a instance of `Application` according your code. It happens in compile-time.
/// `commander_rust` will generate a instance of `Cli` according user's input. It happens in run-time.

/// What' the difference?
/// Content in `Application` will be replaced by something concrete through user's input.
/// For example, If your code is like this:
/// ```ignore
/// #[option(-r, --recursive [dir...], "recursively")]
/// #[command(rmdir <dir> [otherDirs...], "remove files and directories")]
/// fn rmdir(dir: i32, other_dirs: Option<Vec<bool>>, cli: Cli) {
///     let r: bool = cli.get("recursive").into();
/// }
/// ```
/// Let's see. The last argument of function is `Cli` type(you can miss it).
/// So when we want to do something if `--recursive` is offered by user, how can we?
/// You just need to code like `let r: ? = cli.get("recursive").into()`,
/// then you can get contents of `recursive` options if user has inputted it.
///
/// That's why `Cli` will be used frequently.
///
#[derive(Debug)]
pub struct Cli {
    pub cmd: Option<Cmd>,
    pub global_raws: HashMap<String, Raw>,
}

impl Application {
    /// Deriving `#[option(-h, --help, "output usage information")]`
    /// and `#[option(-V, --version, "output the version number")]` for all `Command` and `Application`.
    /// Dont use it!
    #[doc(hidden)]
    pub fn derive(&mut self) {
        self.opts.push(Options {
            short: String::from("h"),
            long: String::from("help"),
            arg: None,
            desc: Some(String::from("output usage information")),
        });
        self.opts.push(Options {
            short: String::from("V"),
            long: String::from("version"),
            arg: None,
            desc: Some(String::from("output the version number")),
        });
        self.derive_cmds();
    }

    /// Deriving `#[option(-h, --help, "output usage information")]`
    /// and `#[option(-V, --version, "output the version number")]` for all `Command`.
    /// Dont use it!
    #[doc(hidden)]
    fn derive_cmds(&mut self) {
        for cmd in &mut self.cmds {
            cmd.derive();
        }
    }
}

impl Command {
    /// Deriving `#[option(-h, --help, "output usage information")]`
    /// and `#[option(-V, --version, "output the version number")]` for `Command`.
    /// Dont use it!
    #[doc(hidden)]
    pub fn derive(&mut self) {
        self.opts.push(Options {
            short: String::from("h"),
            long: String::from("help"),
            arg: None,
            desc: Some(String::from("output usage information")),
        });
    }
}

impl Cli {
    /// Create a empty `Cli`.
    #[doc(hidden)]
    pub fn empty() -> Cli {
        Cli {
            cmd: None,
            global_raws: HashMap::new(),
        }
    }

    /// Get the content of `Options`.
    /// `Options` has two types, one is private, the other is global. Of course they are same.
    /// Private means they belong to the command.
    /// Global means they belong to the global.
    ///
    /// Private is more weight than global.
    pub fn get(&self, idx: &str) -> Raw {
        if self.cmd.is_some() && self.cmd.as_ref().unwrap().has(idx) {
            self.cmd.as_ref().unwrap()[idx].clone()
        } else if self.global_raws.contains_key(idx) {
            self.global_raws[idx].clone()
        } else {
            Raw::new(vec![])
        }
    }

    /// Getting contents of `Options`. if `idx` dont exist, return `default`.
    pub fn get_or<T: From<Raw>>(&self, idx: &str, d: T) -> T {
        if self.has(idx) {
            self.get(idx).into()
        } else {
            d
        }
    }

    /// Get contents of `Options`. if `idx` dont exist, call f.
    ///
    /// f should return a value of type T.
    pub fn get_or_else<T: From<Raw>, F>(&self, idx: &str, f: F) -> T
    where F: FnOnce() -> T {
        if self.has(idx) {
            self.get(idx).into()
        } else {
            f()
        }
    }

    /// Check user input a option or not.
    pub fn has(&self, idx: &str) -> bool {
        (self.cmd.is_some() && self.cmd.as_ref().unwrap().has(idx)) || self.global_raws.contains_key(idx)
    }

    /// Inner function, dont use it.
    #[doc(hidden)]
    pub fn from(instances: &Vec<Instance>, app: &Application) -> Option<Cli> {
        if instances.is_empty() {
            None
        } else {
            let cmd = Cmd::from(instances, &app.cmds);
            let mut global_raws = HashMap::new();

            if let Some(cmd) = &cmd {
                for ins in instances.iter() {
                    let matched = app.opts.iter().find(|o| o.long == ins.name || o.short == ins.name);

                    if let Some(matched) = matched {
                        if !cmd.has(&matched.long) {
                            let raw = Raw::divide_opt(ins, &matched.arg);

                            global_raws.insert(matched.long.clone(), raw.clone());
                            global_raws.insert(matched.short.clone(), raw);
                        }
                    }
                }
            } else {
                for ins in instances.iter() {
                    let matched = app.opts.iter().find(|o| (o.long == ins.name || o.short == ins.name));

                    if let Some(matched) = matched {
                        let raw = Raw::divide_opt(ins, &matched.arg);

                        global_raws.insert(matched.long.clone(), raw.clone());
                        global_raws.insert(matched.short.clone(), raw);
                    }
                }
            }

            Some(Cli {
                cmd,
                global_raws,
            })
        }
    }

    #[doc(hidden)]
    pub fn get_raws(&self) -> Vec<Raw> {
        if let Some(cmd) = &self.cmd {
            cmd.raws.clone()
        } else {
            vec![]
        }
    }

    /// Get the name of the only command inputted by user.
    ///
    /// For Exanple, If user input `[pkg-name] rmdir -rf ./*`,
    /// then the name is `rmdir`.
    ///
    #[doc(hidden)]
    pub fn get_name(&self) -> String {
        if let Some(cmd) = &self.cmd {
            cmd.name.clone()
        } else {
            String::new()
        }
    }
}

impl Cmd {
    /// Create a `Cmd` using offered name.
    #[doc(hidden)]
    fn new(name: String) -> Cmd {
        Cmd {
            name,
            raws: vec![],
            opt_raws: HashMap::new(),
        }
    }

    #[doc(hidden)]
    fn push(&mut self, arg: Raw) {
        self.raws.push(arg);
    }

    #[doc(hidden)]
    fn insert(&mut self, key: String, arg: Raw) {
        if !self.opt_raws.contains_key(&key) {
            self.opt_raws.insert(key, arg);
        }
    }

    #[doc(hidden)]
    fn append(&mut self, raws: Vec<Raw>) {
        raws.into_iter().for_each(|r| self.push(r));
    }

    /// Check user input a option or not. Used by `Cli::has`.
    ///
    /// Dont use it.
    #[doc(hidden)]
    pub fn has(&self, idx: &str) -> bool {
        self.opt_raws.contains_key(idx)
    }

    /// Inner function, dont use it.
    #[doc(hidden)]
    pub fn from(instances: &Vec<Instance>, commands: &Vec<Command>) -> Option<Cmd> {
        let mut result = Cmd::new(String::new());

        if instances.is_empty() {
            None
        } else {
            let head = instances.get(0).unwrap();
            let cmd = commands.iter().find(|c| c.name == head.name);

            // user calls sub-command or not
            if let Some(sub_cmd) = cmd {
                let raws = Raw::divide_cmd(head, &sub_cmd.args);

                result.name = sub_cmd.name.clone();
                // get raws of arguments
                result.append(raws);

                // get all raws of all options
                for ins in instances.iter().skip(1) {
                    let matched = sub_cmd.opts.iter().find(|o| (o.long == ins.name || o.short == ins.name));

                    if let Some(matched) = matched {
                        let raw = Raw::divide_opt(ins, &matched.arg);

                        result.insert(matched.long.clone(), raw.clone());
                        result.insert(matched.short.clone(), raw);

                    }
                }

                Some(result)
            } else {
                None
            }
        }
    }
}

impl Index<&str> for Cmd {
    type Output = Raw;

    fn index(&self, idx: &str) -> &Raw {
        &self.opt_raws[idx]
    }
}

impl Instance {
    /// Check instance is empty or not.
    #[doc(hidden)]
    pub fn is_empty(&self) -> bool {
        self.name.is_empty()
    }

    /// Create an empty `Instance`.
    #[doc(hidden)]
    pub fn empty() -> Instance {
        Instance {
            name: String::new(),
            args: vec![],
        }
    }

    /// Create an `Instance` using offered name.
    #[doc(hidden)]
    pub fn new(name: &str) -> Instance {
        Instance {
            name: String::from(name),
            args: vec![],
        }
    }
}

/// Using for creating Instances according user's input content.
///
/// Dont call it.
#[doc(hidden)]
pub fn normalize(args: Vec<String>) -> Vec<Instance> {
    let cmd_name = Regex::new(r"^\w+$").unwrap();
    let complex_long = Regex::new(r"^--(\w{2,})=(.+)$").unwrap();
    let short = Regex::new(r"^-(\w+)$",).unwrap();
    let long = Regex::new(r"^--(\w{2,})$").unwrap();
    let mut opt_ins = vec![];
    let mut iter = args.into_iter().skip(1).enumerate();
    let mut head = Instance::empty();

    while let Some((idx, arg)) = iter.next() {
        if short.is_match(&arg) {

            if let Some(caps) = short.captures(&arg) {
                let mut all: Vec<&str> = (&caps[1]).split("").collect();

                all.dedup_by(|a, b| a == b);

                if !head.is_empty() {
                    opt_ins.push(head);
                }

                for x in all.into_iter() {
                    if x.len() == 1 {
                        opt_ins.push(Instance::new(x));
                    }
                }

                head = opt_ins.pop().unwrap_or(Instance::empty());
            }
        } else if complex_long.is_match(&arg) {
            if !head.is_empty() {
                opt_ins.push(head);
            }

            head = Instance::empty();

            if let Some(caps) = complex_long.captures(&arg) {
                let mut all: Vec<&str> = (&caps[2]).split_terminator(" ").collect();

                all.dedup_by(|a, b| a == b);
                all.retain(|x| !x.is_empty());

                opt_ins.push(Instance {
                    name: String::from(&caps[1]),
                    args: all.into_iter().map(|x| String::from(x)).collect(),
                });
            }
        } else if long.is_match(&arg) {
            if let Some(caps) = long.captures(&arg) {
                if !head.is_empty() {
                    opt_ins.push(head);
                }

                head = Instance::new(&caps[1]);
            }
        } else if cmd_name.is_match(&arg) && idx == 0 {
            head = Instance::new(&arg);
        } else {
            head.args.push(arg);
        }
    }

    opt_ins.push(head);

    opt_ins
}