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
//! # Immediate Arguments
//!
//! _No-hassle, on-the-spot, command line argument parser_
//!
//! Highlights:
//!
//! * Straightforward declaration of arguments with proc-macro.
//! * Supports POSIX/GNU argument syntax conventions.
//! * Supports arguments of any type that implements [`FromStr`](core::str::FromStr) + [`Debug`](core::fmt::Debug).
//! * Supports (sub)commands, with aliases.
//! * Supports declaration of conflicting arguments.
//! * Supports automatic `--version` and `--help` handling, with possibility to opt-out.
//! * Tested on Linux, macOS and Windows.
//! * No run-time dependencies.
//!
//! # Basic Example
//!
//! ```no_run
//! use immargs::immargs_from_env;
//!
//! let args = immargs_from_env! {
//! --force "overwrite destination",
//! -l --log <level> u8 "set log level",
//! -h --help "print help message",
//! <src>... String "source(s)",
//! <dest> String "destination",
//! };
//!
//! // Assuming this program was executed with "myprog -l 3 Src0 Src1 Dest"
//! assert!(!args.force);
//! assert!(args.log == Some(3));
//! assert!(args.src.len() == 2);
//! assert!(args.src[0] == "Src0");
//! assert!(args.src[1] == "Src1");
//! assert!(args.dest == "Dest");
//! ```
//!
//! [`immargs_from_env!`] returns a `struct` with fields derived from to the arguments
//! specification. The fields are populated with the corresponding values from the command
//! line. For the example above, the returned `struct` looks like this:
//! ```
//! pub struct ImmArgs {
//! pub force: bool,
//! pub log: Option<u8>,
//! pub src: Vec<String>,
//! pub dest: String,
//! }
//! ```
//!
//! A help message will also be derived from the arguments specification, and is printed if the
//! `-h` or `--help` option is used. For the above example, the help message looks like this:
//!
//! ```no_rust
//! usage: myprog [options] <src>... <dest>
//!
//! options:
//! --force overwrite destination
//! -l, --log <level> set log level
//! -h, --help print help message
//!
//! arguments:
//! <src>... source(s)
//! <dest> desination
//!
//! ```
//!
//! # Advanced Example
//!
//! In this example, the main program takes a command as its last argument. Any arguments
//! following the command will be returned as an [`Args`] for further processing by the
//! command's use of [`immargs!`]. A non-option argument enclosed by `[ ]` means that its an
//! optional argument.
//!
//! ```no_run
//! use immargs::immargs;
//!
//! // The last argument is a command, with available commands (and their aliases) enclosed
//! // by braces. An `enum` with variants matching the commands will be generated. We declare
//! // these arguments outside of the main function to be the MainArgs type visible
//! // to the command functions.
//! immargs! {
//! MainArgs, // The argument struct will be called "MainArgs"
//! -v --verbose "Enable verbose logging", // An option
//! -h --help "Print help message", // --help enables automatic help generation
//! <command> Command "The command to run" { // The command enum will be named "Command"
//! add "Add file(s)", // "add" has not aliases
//! remove rm "Remove file(s)", // "rm" is an alias for "remove"
//! commit co c "Commit changes", // "co" and "c" are aliases for "commit"
//! }
//! }
//!
//! // The "!" indicates that these are conflicting arguments, i.e. they can't be
//! // used at the same time.
//! immargs! {
//! AddArgs,
//! -a --all ! "Add all files", // Conflicts with [file...]
//! --force "Overwrite destination",
//! -h --help "Print help message",
//! [<file>...] String ! "File(s) to add", // Conflicts with -a, --all
//! }
//!
//! immargs! {
//! RemoveArgs,
//! -r --recursive "Recursively remove files",
//! -h --help "Print help message",
//! <file>... String "File(s) to remove", // The "..." means it's a variadic argument
//! }
//!
//! immargs!(
//! CommitArgs,
//! -a --amend "Amend latest commit",
//! -h --help "Print help message",
//! [<message>] String "Commit message", // The "[ ]" means it's an optional argument
//! );
//!
//! fn main() {
//! let main_args = MainArgs::from_env();
//!
//! let verbose = main_args.verbose;
//!
//! match main_args.command {
//! Command::Add(args) => add(verbose, args.into()),
//! Command::Remove(args) => remove(verbose, args.into()),
//! Command::Commit(args) => commit(verbose, args.into()),
//! }
//! }
//!
//! fn add(verbose: bool, args: AddArgs) {
//! // ...
//! }
//!
//! fn remove(verbose: bool, args: RemoveArgs) {
//! // ...
//! }
//!
//! fn commit(verbose: bool, args: CommitArgs) {
//! // ...
//! }
//! ```
//!
//! # Terminology
//!
//! [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap12.html
//! [GNU]: https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
//!
//! Terms and definitions used by `immargs` (mostly derived from [POSIX] and [GNU] definitions):
//!
//! * __Arguments__ - The umbrella term for all kinds strings that appear on the command line.
//! _Arguments_ are further divided into _options_ and _non-options_.
//!
//! * __Options__ - The subset of _arguments_ that start with `-` or `--`, e.g. `-v` or
//! `--verbose`. The order in which _options_ appear on the command line carries no meaning,
//! i.e. `-a -b` has the same meaning as `-b -a`. _Options_ are, as the name implies, always
//! optional and never required. _Options_ are further divided into _short_ and _long_ options.
//!
//! * __Short options__ - The subset of _options_ that start with `-` followed by a single
//! character, e.g. `-v`.
//!
//! * __Long options__ - The subset of _options_ that start with `--` followed by two or more
//! characters, e.g. `--verbose`.
//!
//! * __Value__ - An additional piece of information associated with an _option_, e.g.
//! `--speed 100`, where `100` is the _value_. Value-less _options_ implicitly hold a binary
//! value (`true` or `false`) through their presence or absence on the command line.
//!
//! * __Non-options__ - The subset of _arguments_ that don't start with `-` or `--`, e.g.
//! `commit` or `file.txt`. The order in which _non-options_ appear on the command line
//! carries meaning, i.e. `commit file.txt` doesn't have the same meaning as `file.txt commit`.
//! _Non-optons_ are further divided into _required_ and _optional_ non-options.
//!
//! * __Required non-option__ - A _non-option_ that must be present on the command line.
//! In text, _required non-options_ are represented by enclosing `<` `>`, e.g. `<file>`.
//!
//! * __Optional non-option__ - A _non-options_ that doesn't have to be present on the command
//! line. In text, _optional non-options_ are represented by enclosing `[` `]`, e.g. `[file]`.
//!
//! * __Variadic option__ - An _option_ that is materialized from multiple separate instances
//! of the option, as opposed to the last instance taking precedence.
//! E.g. `--file hello.txt --file world.txt` results in the option _file_ holding two values,
//! `hello.txt` and `world.txt`. A value-less _option_ can also be _variadic_, in which case
//! the value held by the option is an unsigned integer representing the number of times the
//! option appeared on the command line. E.g. `--verbose --verbose --verbose` results in the
//! option _verbose_ holding the value `3`. In text, _variadic options_ are represented by
//! trailing `...`, e.g. `--file... <path>` or `--verbose...`.
//!
//! * __Variadic non-option__ - A _non-option_ that is materialized from multiple separate
//! command line arguments of the same type. In text, _variadic non-options_ are represented
//! by trailing `...`, e.g. `<file>...` or `[<file>...]`.
//!
//! # Command Line Argument Syntax
//!
//! The following [POSIX]/[GNU] argument syntax conventions are supported:
//!
//! * Short option, `-` followed by a single character, e.g. `-f`.
//! * Long option, `--` followed by two or more characters, e.g. `--foo`.
//! * Short/Long option with separate value, e.g. `-f 100` or `--foo 100`.
//! * Short/Long option with attached value delimited by `=`, e.g. `-f=100` or `--foo=100`.
//! * Short option with attached value without delimiter, e.g. `-f100`.
//! * Combined short options, e.g. `-abc` is equivalent to `-a -b -c`.
//! * Short/Long options may appear in any order, but before any non-option arguments.
//! * Short/Long options may appear multiple times, the last appearance takes precedence unless
//! it's a _variadic_ (repeatable) option, where the number of times the option appears has
//! meaning, e.g. `-vvv` where each `-v` increases the verbosity level.
//! * The order of non-option arguments carries meaning.
//! * A standalone `-` argument is treated as a non-option argument.
//! * A standalone `--` argument marks the end of options. Any following arguments are treated
//! as non-option arguments.
//!
//! # The Returned `struct`
//!
//! #### Field Names
//!
//! The field names of the `struct` returned by [`immargs!()`](immargs!) are derived as follows:
//!
//! | Argument Type | Field Name | Example |
//! | - | - | - |
//! | Option | Field name is direved from the first long-option (or the first short-option if no long-option exists) | `--foo` uses field name `foo` |
//! | Non-Option | Field name is derived from the non--option name | `<bar> T` uses field name `bar` |
//!
//! Note that the specified option and non-option names must be valid Rust identifiers, as they
//! will become the names of the `struct` fields. However, the names visible to the user of the
//! program will be transformed as follows, to allow use of names that aren't valid Rust `struct`
//! field names (keywords, words starting with a number, etc).
//!
//! * Any starting and trailing `_` will be stripped.
//! * Any other `_` will be replaced by `-`.
//! * Letters will be converted to lower case (does not apply to short-options).
//!
//! Examples:
//!
//! | Specified Argument | `struct` Field Name | User Visibale Name |
//! | - | - | - |
//! | `-_1` | _1 | `-1` |
//! | `--move_` | move_ | `--move` |
//! | `--_1_to_1` | _1_to_1 | `--1-to-1` |
//! | `--Report_Error` | `Report_Error` | `--report-error` |
//! | `--log <Log_Level> u8` | `log` | `--log <log-level>` |
//! | `<number_of_items>` | `number_or_items` | `<number-of-items>` |
//! | `[_4th]` | `_4th` | `[4th]` |
//!
//! #### Field Types
//!
//! The field types of the `struct` returned by [`immargs!()`](immargs!) are derived as follows:
//!
//! | Argument Type | Example | Field Type |
//! | - | - | - |
//! | Option | `--foo` | bool |
//! | Option with Value | `--foo <bar> T` | `Option<T>` |
//! | Variadic Option | `--foo...` | `usize` |
//! | Variadic Option with Value | `--foo... <bar> T` | `Vec<T>` |
//! | Required Argument (non-option) | `<foo> T` | `T` |
//! | Optional Argument (non-option) | `[foo] T` | `Option<T>` |
//! | Required Variadic Argument (non-option) | `<foo>... T` | `Vec<T>` (with lenth > 0) |
//! | Optional Variadic Argument (non-option) | `[<foo>...] T` | `Vec<T>` (with lenth >= 0) |
//! | Required Command Argument (non-option) | `<foo> [...]` | `(&'static str, immargs::Args)` |
//! | Optional Command Argument (non-option) | `[foo] [...]` | `Option<(&'static str, immargs::Args)>` |
//!
//! # Conflicting Arguments
//!
//! An argument can be declared to be in conflict with one or more other arguments. This is
//! useful when two or more arguments are incompatible or otherwise mutually exclusive. A
//! conflict is declared using an `!` or `?` optionally followed by a _conflict-id_. The
//! _conflict-id_ is an identitier used if there are more than one group of conflicting options.
//! `!` means that zero or one of the options in the group is allowed to be present on the commane
//! line, while `?` means that exactly one of the options in the group is must be present on the
//! command line.
//!
//! Example with one group of conflicting arguments, without an explicit _conflict-id_:
//!
//! ```
//! use immargs::immargs;
//!
//! immargs! {
//! --verbose, // Doesn't conflict with any other argument
//! --all !, // Conflicts with [names...]
//! [<names>...] String !, // Conflicts with --all
//! }
//! ```
//!
//! Example with two groups of conflicting arguments, where one argument is part of both groups:
//!
//! ```
//! use immargs::immargs;
//!
//! immargs! {
//! --feature_a, // Doesn't conflict with any other argument
//! --feature_b ?B_C, // Conflicts with --feature-c
//! --feature_c ?B_C !C_D_E, // Conflicts with --feature-b, --feature-d and --feature-e
//! --feature_d !C_D_E, // Conflicts with --feature-c and --feature-e
//! --feature_e !C_D_E, // Conflicts with --feature-c and --feature-d
//! }
//! ```
//!
//! # Help and Version
//!
//! Options with long-option names `--help` and `--version` are special. These options are
//! intercepted during arguments parsing and will not be visible, or have a corresponding field,
//! in the arguments `struct` generated by [`immargs!`]. Instead these options will cause an
//! [`Help`](Error::Help) or [`Version`](Error::Version) error to be generated. When parsing
//! arguments using `from_env()` or `from()`, these errors never reach the application.
//!
//! An application that wants to do display a custom help message or version information would
//! instead use `try_from_env()` or `try_from()` to catch these errors display an appropriate
//! message.
//!
//! # Unicode
//!
//! Non-unicode command line arguments will be converted to unicode using
//! [`to_string_lossy()`](std::ffi::OsStr::to_string_lossy).
//!
//! # `immargs!()` Syntax
//!
//! ## Specification
//!
//! `immargs! {`
//! \[ ___StructName___ `,` \]
//! \[ ___Option___ `,` \]*
//! \[ ___NonOption___ `,` \]*
//! `}`
//!
//! ___Option___ := \[ `-` ___Short___ \]*
//! \[`--` ___Long___ \]*
//! \[ `...` \]
//! \[ `<` ___Value___ `>` ___Type___ \]
//! \[ `!` \[ ___ConflictId___ \] \]*
//! \[ `?` \[ ___ChoiceId___ \] \]*
//! \[ ___Help___ \]
//! `,`
//!
//! ___NonOption___ := \( ___RequiredNonOption___ | ___OptionalNonOption___ \)*
//!
//! ___RequiredNonOption___ := `<` ___Name___ `>`
//! \[ `...` \]
//! ___Type___
//! \[ `!` \[ ___ConflictId___ \] \]*
//! \[ `?` \[ ___ChoiceId___ \] \]*
//! \[ ___Help___ \]
//! \[ ___Commands___ \]
//! `,`
//!
//! ___OptionalNonOption___ := `[<` ___Name___ `>` \[ `...` \] `]`
//! ___Type___
//! \[ `!` \[ ___ConflictId___ \] \]*
//! \[ `?` \[ ___ChoiceId___ \] \]*
//! \[ ___Help___ \]
//! \[ ___Commands___ \]
//! `,`
//!
//! ___Commands___ := `{` \[ ___Command___ `,` \]* `}`
//!
//! ___Command___ := ___Name___ \[ ___Alias___ \]* \[ ___Help___ \]
//!
//! ___StructName___ /
//! ___Short___ /
//! ___Long___ /
//! ___Value___ /
//! ___Name___ /
//! ___Alias___ /
//! ___ConflictId___ /
//! ___ChoiceId___ := A Rust [non-keyword identifier](https://doc.rust-lang.org/reference/identifiers.html)
//!
//! ___Type___ := A Rust type that implements [`FromStr`](std::str::FromStr) + [`Debug`](std::fmt::Debug)
//!
//! ___Help___ := A Rust [string literal](https://doc.rust-lang.org/reference/tokens.html#r-lex.token.literal.str)
//!
//! ## Examples
//!
//! Options:
//!
//! ```no_rust
//! -f, // Short-option
//! --foo, // Long-option
//! -f --foo, // Short-option + long-option
//! -f -F --foo, // Multiple short-options + long-option
//!
//! -f <bar> u64, // With u64 value named "bar"
//! --foo <bar> u64, // With u64 value named "bar"
//! -f --foo <bar> String, // With String value named "bar"
//! -f -F --foo <bar> Ipv4Addr, // With Ipv4Addr value named "bar"
//!
//! -f "Help text", // With help text
//! --foo "Help text", // ...
//! -f --foo "Help text", // ...
//! -f --foo <bar> u64 "Help text", // ...
//!
//! -f ! "Help text", // With default conflict-id
//! --foo ! "Help text", // ...
//! -f --foo ! "Help text", // ...
//! -f --foo <bar> u64 ! "Help text", // ...
//! -f --foo <bar> String !A !B "Help text", // With conflict-ids "A" and "B"
//!
//! -f... "Help text", // Variadic (repeatable) option
//! --foo... "Help text", // ...
//! -f --foo... "Help text", // ...
//! -f --foo... <bar> u64 "Help text", // ...
//! -f --foo... <bar> String "Help text", // ...
//! ```
//!
//! Non-options:
//!
//! ```no_rust
//! <foo> u64, // Required argument named "foo" of type u64
//! <foo> String, // Required argument named "foo" of type String
//! <foo>... String, // Required variadic argument named "foo" of type String
//! <foo>... String "Help text", // With help text
//! <foo>... String ! "Help text", // With default conflict-id
//! <foo>... String !A !B "Help text", // With conflict-ids "A" and "B"
//!
//! [<foo>] u64, // Optional argument name "foo" of type u64
//! [<foo>] String, // Optional argument name "foo" of type String
//! [<foo>...] String, // Optional variadic argument name "foo" of type String
//! [<foo>...] String "Help text", // With help text
//! [<foo>...] String ! "Help text", // With default conflict-id
//! [<foo>...] String !0 !1 "Help text", // With conflict-ids 0 and 1
//!
//! <command> [...] { // Required command argument
//! add, // Command "add"
//! remove rm, // Command "remove" with alias "rm"
//! list ls l, // Command "list" with alieses "ls" and "l"
//! }
//!
//! [<command>] [...] { // Optional command
//! add,
//! remove rm,
//! list ls l,
//! }
//!
//! <command> [...] "Help text" { // With help texts
//! add "Help text for add",
//! remove rm "Help text for remove",
//! list ls l "Help text for list",
//! }
//!
//! <command> [...] ! "Help text" { // With default conflict-id
//! add "Help text for add",
//! remove rm "Help text for remove",
//! list ls l "Help text for list",
//! }
//!
//! <command> [...] !0 !1 "Help text" { // With conflict-ids 0 and 1
//! add "Help text for add",
//! remove rm "Help text for remove",
//! list ls l "Help text for list",
//! }
//! ```
pub use Error;
pub use immargs;
use VecDeque;
use IntoIter;
use from_args;
use try_from_args;
/// Result returned by argument parser.
pub type Result<T> = Result;
/// A trait implemented by all arguments `struct`s generated by [`immargs!`].
///
/// Users of `immargs` never explicitly call methods on this trait. This trait is public
/// soley to enable [`Args::into()`] and [`Args::try_into()`] to seamelessly convert
/// (sub)command arguments into an arguments `struct`.
/// Command line arguments in raw form, i.e. not yet parsed.
;