pub struct Args {
pub options: Vec<Opt>,
pub other: Vec<String>,
pub unknown: Vec<String>,
}Expand description
Parsed command line in organized form.
Instances of this struct are usually created with
OptSpecs::getopt method and an instance represents the parsed
output in organized form. See each field’s documentation for more
information.
Programmers can use the parsed output (Args struct) any way they
like. There are some methods for convenience.
Fields§
§options: Vec<Opt>A vector of valid command-line options.
Elements of this vector are Opt structs which each
represents a single command-line option. Elements are in the
same order as given (by program’s user) in the command line. The
vector is empty if the parser didn’t find any valid command-line
options.
other: Vec<String>A vector of other arguments (non-options).
Each element of the vector is a single non-option argument string in the same order as given (by program’s user) in the command line. The vector is empty if the parser didn’t find any non-option arguments.
unknown: Vec<String>Unknown options.
Command-line arguments that look like options but were not part
of OptSpecs specification are classified as unknown. They
are listed in this vector. Possible duplicate unknown options
have been filtered out.
Each element is the name string for the option (without - or
-- prefix). For unknown short options the element is a
single-character string. For unknown long options the string has
more than one character. The whole vector is empty if there were
no unknown options.
If a long option does not accept a value (that is, its value
type is OptValue::None) but user gives it a value with
equal sign notation (--foo=), that option is classified as
unknown and it will be in this field’s vector with name foo=.
Implementations§
Source§impl Args
impl Args
Sourcepub fn required_value_missing(&self) -> impl DoubleEndedIterator<Item = &Opt>
pub fn required_value_missing(&self) -> impl DoubleEndedIterator<Item = &Opt>
Find options with missing required value.
This method finds all (otherwise valid) options which require a
value but the value is missing. That is, OptSpecs struct
specification defined that an option requires a value but
program’s user didn’t give one in the command line. Such thing
can happen if an option like --file is the last argument in
the command line and that option requires a value.
If option’s value type is OptValue::Required the empty
string "" is not classified as missing value because it can be
valid user input in many situations. If option’s value type is
OptValue::RequiredNonEmpty the empty string that was given
in the command line will be classified as missing value.
The return value implements the DoubleEndedIterator trait
(possibly empty, if no matches) and each item is a reference to
Opt struct in the original Args::options field. Items
are in the same order as in the parsed command line. You can
collect the iterator to a vector by applying method
collect::<Vec<&Opt>>().
Examples found in repository?
8fn main() {
9 // The `OptSpecs::new()` function below creates a new option
10 // specification struct `OptSpecs`. Its `option()` methods configure
11 // three different options for logical meanings "help", "file" and
12 // "verbose". All three options can be written in command-line with
13 // a short variant (like "-h") and a long variant (like "--help").
14 // Some options accept or require a value.
15 //
16 // Flag OptionsEverywhere changes parser's behavior. This flag means
17 // that options and other arguments (non-options) can be mixed in
18 // their order in the command line. Without the flag the option
19 // parsing stops at the first non-option argument and the rest of
20 // the command-line is parsed as non-options.
21 let specs = OptSpecs::new()
22 .option("help", "h", OptValue::None) // Arguments: (id, name, value_type)
23 .option("help", "help", OptValue::None)
24 .option("file", "f", OptValue::RequiredNonEmpty)
25 .option("file", "file", OptValue::RequiredNonEmpty)
26 .option("verbose", "v", OptValue::OptionalNonEmpty)
27 .option("verbose", "verbose", OptValue::OptionalNonEmpty)
28 .flag(OptFlags::OptionsEverywhere);
29
30 // Get arguments iterator from operating system and skip the first item
31 let args = std::env::args().skip(1); // which is this program's file path.
32
33 // Parse program's command-line with the given specification `specs`.
34 let parsed = specs.getopt(args);
35
36 // With this you can see the parsed output which is an `Args`
37 // struct.
38 eprintln!("{:#?}", parsed);
39
40 // Create a condition variable for possible exit on error.
41 let mut error_exit = false;
42
43 // Report user about unknown options.
44 for u in &parsed.unknown {
45 eprintln!("Unknown option: {u}");
46 error_exit = true;
47 }
48
49 // Report user about missing values for options that require them
50 // (i.e. "file").
51 for o in parsed.required_value_missing() {
52 eprintln!("Value is required for option '{}'.", o.name);
53 error_exit = true;
54 }
55
56 // Exit if there were bad command-line arguments.
57 if error_exit {
58 eprintln!("Use '-h' for help.");
59 std::process::exit(1);
60 }
61
62 // Print help and exit because "-h" or "--help" was given. We use
63 // option's identifier string "help" here to find if the correct
64 // option was present in the command line. See the `id` argument of
65 // `option()` methods above.
66 if parsed.option_exists("help") {
67 println!("Print friendly help about program's usage.");
68 std::process::exit(0);
69 }
70
71 // Collect all (required) values for "-f" and "--file". We use
72 // option's identifier (id) string "file" to find the option.
73 for f in parsed.options_value_all("file") {
74 println!("File name: {:?}", f);
75 }
76
77 // Notice if "-v" or "--verbose" was given (even without a value).
78 // Then collect all its (optional) values. We use option's
79 // identifier (id) string "verbose".
80 if parsed.option_exists("verbose") {
81 println!("Option 'verbose' was given.");
82 for v in parsed.options_value_all("verbose") {
83 println!("Verbose level: {:?}", v);
84 }
85 }
86
87 // Collect all other (non-option) arguments.
88 for o in &parsed.other {
89 println!("Other argument: {:?}", o);
90 }
91}Sourcepub fn option_exists(&self, id: &str) -> bool
pub fn option_exists(&self, id: &str) -> bool
Return boolean whether option with the given id exists.
This is functionally the same as
options_first(id).is_some().
Examples found in repository?
8fn main() {
9 // The `OptSpecs::new()` function below creates a new option
10 // specification struct `OptSpecs`. Its `option()` methods configure
11 // three different options for logical meanings "help", "file" and
12 // "verbose". All three options can be written in command-line with
13 // a short variant (like "-h") and a long variant (like "--help").
14 // Some options accept or require a value.
15 //
16 // Flag OptionsEverywhere changes parser's behavior. This flag means
17 // that options and other arguments (non-options) can be mixed in
18 // their order in the command line. Without the flag the option
19 // parsing stops at the first non-option argument and the rest of
20 // the command-line is parsed as non-options.
21 let specs = OptSpecs::new()
22 .option("help", "h", OptValue::None) // Arguments: (id, name, value_type)
23 .option("help", "help", OptValue::None)
24 .option("file", "f", OptValue::RequiredNonEmpty)
25 .option("file", "file", OptValue::RequiredNonEmpty)
26 .option("verbose", "v", OptValue::OptionalNonEmpty)
27 .option("verbose", "verbose", OptValue::OptionalNonEmpty)
28 .flag(OptFlags::OptionsEverywhere);
29
30 // Get arguments iterator from operating system and skip the first item
31 let args = std::env::args().skip(1); // which is this program's file path.
32
33 // Parse program's command-line with the given specification `specs`.
34 let parsed = specs.getopt(args);
35
36 // With this you can see the parsed output which is an `Args`
37 // struct.
38 eprintln!("{:#?}", parsed);
39
40 // Create a condition variable for possible exit on error.
41 let mut error_exit = false;
42
43 // Report user about unknown options.
44 for u in &parsed.unknown {
45 eprintln!("Unknown option: {u}");
46 error_exit = true;
47 }
48
49 // Report user about missing values for options that require them
50 // (i.e. "file").
51 for o in parsed.required_value_missing() {
52 eprintln!("Value is required for option '{}'.", o.name);
53 error_exit = true;
54 }
55
56 // Exit if there were bad command-line arguments.
57 if error_exit {
58 eprintln!("Use '-h' for help.");
59 std::process::exit(1);
60 }
61
62 // Print help and exit because "-h" or "--help" was given. We use
63 // option's identifier string "help" here to find if the correct
64 // option was present in the command line. See the `id` argument of
65 // `option()` methods above.
66 if parsed.option_exists("help") {
67 println!("Print friendly help about program's usage.");
68 std::process::exit(0);
69 }
70
71 // Collect all (required) values for "-f" and "--file". We use
72 // option's identifier (id) string "file" to find the option.
73 for f in parsed.options_value_all("file") {
74 println!("File name: {:?}", f);
75 }
76
77 // Notice if "-v" or "--verbose" was given (even without a value).
78 // Then collect all its (optional) values. We use option's
79 // identifier (id) string "verbose".
80 if parsed.option_exists("verbose") {
81 println!("Option 'verbose' was given.");
82 for v in parsed.options_value_all("verbose") {
83 println!("Verbose level: {:?}", v);
84 }
85 }
86
87 // Collect all other (non-option) arguments.
88 for o in &parsed.other {
89 println!("Other argument: {:?}", o);
90 }
91}Sourcepub fn options_all<'a>(
&'a self,
id: &'a str,
) -> impl DoubleEndedIterator<Item = &'a Opt>
pub fn options_all<'a>( &'a self, id: &'a str, ) -> impl DoubleEndedIterator<Item = &'a Opt>
Find all options with the given id.
Find all options which have the identifier id. (Option
identifiers have been defined in OptSpecs struct before
parsing.)
The return value implements the DoubleEndedIterator trait
(possibly empty, if no matches) and each item is a reference to
Opt struct in the original Args::options field. Items
are in the same order as in the parsed command line. You can
collect the iterator to a vector by applying method
collect::<Vec<&Opt>>().
Sourcepub fn options_first(&self, id: &str) -> Option<&Opt>
pub fn options_first(&self, id: &str) -> Option<&Opt>
Find the first option with the given id.
Find and return the first match for option id in command-line
arguments’ order. (Options’ identifiers have been defined in
OptSpecs struct before parsing.)
The return value is a variant of enum Option. Their
meanings:
-
None: No options found with the givenid. -
Some(&Opt): An option was found with the givenidand a reference is provided to itsOptstruct in the originalArgs::optionsfield.
Sourcepub fn options_last(&self, id: &str) -> Option<&Opt>
pub fn options_last(&self, id: &str) -> Option<&Opt>
Find the last option with the given id.
This is similar to options_first method
but this returns the last match in command-line arguments’
order.
Sourcepub fn options_value_all<'a>(
&'a self,
id: &'a str,
) -> impl DoubleEndedIterator<Item = &'a String>
pub fn options_value_all<'a>( &'a self, id: &'a str, ) -> impl DoubleEndedIterator<Item = &'a String>
Find all values for options with the given id.
Find all options which match the identifier id and which also
have a value assigned. (Options’ identifiers have been defined
in OptSpecs struct before parsing.)
The return value implements the DoubleEndedIterator trait
(possibly empty, if no matches) and each item is a reference to
string in Opt::value field in the original Args::options
field. Items are in the same order as in the parsed command
line. You can collect the iterator to a vector by applying
method
collect::<Vec<&String>>().
Examples found in repository?
8fn main() {
9 // The `OptSpecs::new()` function below creates a new option
10 // specification struct `OptSpecs`. Its `option()` methods configure
11 // three different options for logical meanings "help", "file" and
12 // "verbose". All three options can be written in command-line with
13 // a short variant (like "-h") and a long variant (like "--help").
14 // Some options accept or require a value.
15 //
16 // Flag OptionsEverywhere changes parser's behavior. This flag means
17 // that options and other arguments (non-options) can be mixed in
18 // their order in the command line. Without the flag the option
19 // parsing stops at the first non-option argument and the rest of
20 // the command-line is parsed as non-options.
21 let specs = OptSpecs::new()
22 .option("help", "h", OptValue::None) // Arguments: (id, name, value_type)
23 .option("help", "help", OptValue::None)
24 .option("file", "f", OptValue::RequiredNonEmpty)
25 .option("file", "file", OptValue::RequiredNonEmpty)
26 .option("verbose", "v", OptValue::OptionalNonEmpty)
27 .option("verbose", "verbose", OptValue::OptionalNonEmpty)
28 .flag(OptFlags::OptionsEverywhere);
29
30 // Get arguments iterator from operating system and skip the first item
31 let args = std::env::args().skip(1); // which is this program's file path.
32
33 // Parse program's command-line with the given specification `specs`.
34 let parsed = specs.getopt(args);
35
36 // With this you can see the parsed output which is an `Args`
37 // struct.
38 eprintln!("{:#?}", parsed);
39
40 // Create a condition variable for possible exit on error.
41 let mut error_exit = false;
42
43 // Report user about unknown options.
44 for u in &parsed.unknown {
45 eprintln!("Unknown option: {u}");
46 error_exit = true;
47 }
48
49 // Report user about missing values for options that require them
50 // (i.e. "file").
51 for o in parsed.required_value_missing() {
52 eprintln!("Value is required for option '{}'.", o.name);
53 error_exit = true;
54 }
55
56 // Exit if there were bad command-line arguments.
57 if error_exit {
58 eprintln!("Use '-h' for help.");
59 std::process::exit(1);
60 }
61
62 // Print help and exit because "-h" or "--help" was given. We use
63 // option's identifier string "help" here to find if the correct
64 // option was present in the command line. See the `id` argument of
65 // `option()` methods above.
66 if parsed.option_exists("help") {
67 println!("Print friendly help about program's usage.");
68 std::process::exit(0);
69 }
70
71 // Collect all (required) values for "-f" and "--file". We use
72 // option's identifier (id) string "file" to find the option.
73 for f in parsed.options_value_all("file") {
74 println!("File name: {:?}", f);
75 }
76
77 // Notice if "-v" or "--verbose" was given (even without a value).
78 // Then collect all its (optional) values. We use option's
79 // identifier (id) string "verbose".
80 if parsed.option_exists("verbose") {
81 println!("Option 'verbose' was given.");
82 for v in parsed.options_value_all("verbose") {
83 println!("Verbose level: {:?}", v);
84 }
85 }
86
87 // Collect all other (non-option) arguments.
88 for o in &parsed.other {
89 println!("Other argument: {:?}", o);
90 }
91}Sourcepub fn options_value_first(&self, id: &str) -> Option<&String>
pub fn options_value_first(&self, id: &str) -> Option<&String>
Find the first option with a value for given option id.
Find the first option with the identifier id and which has a
value assigned. (Options’ identifiers have been defined in
OptSpecs struct before parsing.) Method’s return value is a
variant of enum Option which are:
-
None: No options found with the givenidand a value assigned. Note that there could be options for the sameidbut they don’t have a value. -
Some(&String): An option was found with the givenidand the option has a value assigned. A reference is provided to the string value in theOpt::valuefield in the originalArgs::optionsfield.
Sourcepub fn options_value_last(&self, id: &str) -> Option<&String>
pub fn options_value_last(&self, id: &str) -> Option<&String>
Find the last option with a value for given option id.
This is similar to
options_value_first method but
this method finds and returns the last option’s value.
Note: Program’s user may give the same option several times in the command line. If the option accepts a value it may be suitable to consider only the last value relevant. (Or the first, or maybe print an error message for providing several, possibly conflicting, values.)