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 OptValueType::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) -> Vec<&Opt>
pub fn required_value_missing(&self) -> Vec<&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. Empty string
"" is not classified as missing value because it can be valid
user input in many situations.
This method returns a vector (possibly empty) and each element
is a reference to an Opt struct in the original
Args::options field contents.
Examples found in repository?
4fn main() -> ExitCode {
5 // The `OptSpecs::new()` function below creates a new option
6 // specification struct `OptSpecs`. Its `option()` methods configure
7 // three different options for logical meanings "help", "file" and
8 // "verbose". All three options can be written in command-line with
9 // a short variant (like "-h") and a long variant (like "--help").
10 // Some options accept or require a value.
11 //
12 // Flag OptionsEverywhere changes parser's behavior. This flag means
13 // that options and other arguments (non-options) can be mixed in
14 // their order in the command line. Without the flag the option
15 // parsing stops at the first non-option argument and the rest of
16 // the command-line is parsed as non-options.
17 let specs = OptSpecs::new()
18 .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
19 .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
20 .option("help", "help", OptValueType::None)
21 .option("file", "f", OptValueType::Required)
22 .option("file", "file", OptValueType::Required)
23 .option("verbose", "v", OptValueType::Optional)
24 .option("verbose", "verbose", OptValueType::Optional);
25
26 // Get arguments iterator from operating system and skip the first item
27 let args = std::env::args().skip(1); // which is this program's file path.
28
29 // Parse program's command-line with the given specification `specs`.
30 let parsed = specs.getopt(args);
31
32 // With this you can see the parsed output which is an `Args`
33 // struct.
34 eprintln!("{:#?}", parsed);
35
36 // Report user about unknown options.
37 for u in &parsed.unknown {
38 eprintln!("Unknown option: {}", u);
39 }
40
41 // Report user about missing values for options that require them
42 // (i.e. "file"). Exit the program with error code.
43 for o in &parsed.required_value_missing() {
44 eprintln!("Value is required for option '{}'.", o.name);
45 return ExitCode::FAILURE;
46 }
47
48 // Print help and exit because "-h" or "--help" was given. We use
49 // option's identifier string "help" here to find if the correct
50 // option was present in the command line. See the `id` argument of
51 // `option()` methods above.
52 if parsed.option_exists("help") {
53 println!("Print friendly help about program's usage.");
54 return ExitCode::from(2);
55 }
56
57 // Collect all (required) values for "-f" and "--file". We use
58 // option's identifier (id) string "file" to find the option.
59 for f in &parsed.options_value_all("file") {
60 println!("File name: {:?}", f);
61 }
62
63 // Notice if "-v" or "--verbose" was given (even without a value).
64 // Then collect all its (optional) values. We use option's
65 // identifier (id) string "verbose".
66 if parsed.option_exists("verbose") {
67 println!("Option 'verbose' was given.");
68
69 for v in &parsed.options_value_all("verbose") {
70 println!("Verbose level: {:?}", v);
71 }
72 }
73
74 // Collect all other (non-option) arguments.
75 for o in &parsed.other {
76 println!("Other argument: {:?}", o);
77 }
78
79 // Try to run this program with various command-line options to see
80 // the output.
81 ExitCode::SUCCESS
82}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?
4fn main() -> ExitCode {
5 // The `OptSpecs::new()` function below creates a new option
6 // specification struct `OptSpecs`. Its `option()` methods configure
7 // three different options for logical meanings "help", "file" and
8 // "verbose". All three options can be written in command-line with
9 // a short variant (like "-h") and a long variant (like "--help").
10 // Some options accept or require a value.
11 //
12 // Flag OptionsEverywhere changes parser's behavior. This flag means
13 // that options and other arguments (non-options) can be mixed in
14 // their order in the command line. Without the flag the option
15 // parsing stops at the first non-option argument and the rest of
16 // the command-line is parsed as non-options.
17 let specs = OptSpecs::new()
18 .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
19 .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
20 .option("help", "help", OptValueType::None)
21 .option("file", "f", OptValueType::Required)
22 .option("file", "file", OptValueType::Required)
23 .option("verbose", "v", OptValueType::Optional)
24 .option("verbose", "verbose", OptValueType::Optional);
25
26 // Get arguments iterator from operating system and skip the first item
27 let args = std::env::args().skip(1); // which is this program's file path.
28
29 // Parse program's command-line with the given specification `specs`.
30 let parsed = specs.getopt(args);
31
32 // With this you can see the parsed output which is an `Args`
33 // struct.
34 eprintln!("{:#?}", parsed);
35
36 // Report user about unknown options.
37 for u in &parsed.unknown {
38 eprintln!("Unknown option: {}", u);
39 }
40
41 // Report user about missing values for options that require them
42 // (i.e. "file"). Exit the program with error code.
43 for o in &parsed.required_value_missing() {
44 eprintln!("Value is required for option '{}'.", o.name);
45 return ExitCode::FAILURE;
46 }
47
48 // Print help and exit because "-h" or "--help" was given. We use
49 // option's identifier string "help" here to find if the correct
50 // option was present in the command line. See the `id` argument of
51 // `option()` methods above.
52 if parsed.option_exists("help") {
53 println!("Print friendly help about program's usage.");
54 return ExitCode::from(2);
55 }
56
57 // Collect all (required) values for "-f" and "--file". We use
58 // option's identifier (id) string "file" to find the option.
59 for f in &parsed.options_value_all("file") {
60 println!("File name: {:?}", f);
61 }
62
63 // Notice if "-v" or "--verbose" was given (even without a value).
64 // Then collect all its (optional) values. We use option's
65 // identifier (id) string "verbose".
66 if parsed.option_exists("verbose") {
67 println!("Option 'verbose' was given.");
68
69 for v in &parsed.options_value_all("verbose") {
70 println!("Verbose level: {:?}", v);
71 }
72 }
73
74 // Collect all other (non-option) arguments.
75 for o in &parsed.other {
76 println!("Other argument: {:?}", o);
77 }
78
79 // Try to run this program with various command-line options to see
80 // the output.
81 ExitCode::SUCCESS
82}Sourcepub fn options_all(&self, id: &str) -> Vec<&Opt>
pub fn options_all(&self, id: &str) -> Vec<&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 is a vector (possibly empty, if no
matches) and each element is a reference to Opt struct in
the original Args struct. Elements in the vector are in the
same order as in the parsed command line.
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(&self, id: &str) -> Vec<&String>
pub fn options_value_all(&self, id: &str) -> Vec<&String>
Find and return 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.) Collect options’ values
into a new vector in the same order as they were given in the
command line. Vector’s elements are references to the value
strings in the original Args struct. The returned vector is
empty if there were no matches.
Examples found in repository?
4fn main() -> ExitCode {
5 // The `OptSpecs::new()` function below creates a new option
6 // specification struct `OptSpecs`. Its `option()` methods configure
7 // three different options for logical meanings "help", "file" and
8 // "verbose". All three options can be written in command-line with
9 // a short variant (like "-h") and a long variant (like "--help").
10 // Some options accept or require a value.
11 //
12 // Flag OptionsEverywhere changes parser's behavior. This flag means
13 // that options and other arguments (non-options) can be mixed in
14 // their order in the command line. Without the flag the option
15 // parsing stops at the first non-option argument and the rest of
16 // the command-line is parsed as non-options.
17 let specs = OptSpecs::new()
18 .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
19 .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
20 .option("help", "help", OptValueType::None)
21 .option("file", "f", OptValueType::Required)
22 .option("file", "file", OptValueType::Required)
23 .option("verbose", "v", OptValueType::Optional)
24 .option("verbose", "verbose", OptValueType::Optional);
25
26 // Get arguments iterator from operating system and skip the first item
27 let args = std::env::args().skip(1); // which is this program's file path.
28
29 // Parse program's command-line with the given specification `specs`.
30 let parsed = specs.getopt(args);
31
32 // With this you can see the parsed output which is an `Args`
33 // struct.
34 eprintln!("{:#?}", parsed);
35
36 // Report user about unknown options.
37 for u in &parsed.unknown {
38 eprintln!("Unknown option: {}", u);
39 }
40
41 // Report user about missing values for options that require them
42 // (i.e. "file"). Exit the program with error code.
43 for o in &parsed.required_value_missing() {
44 eprintln!("Value is required for option '{}'.", o.name);
45 return ExitCode::FAILURE;
46 }
47
48 // Print help and exit because "-h" or "--help" was given. We use
49 // option's identifier string "help" here to find if the correct
50 // option was present in the command line. See the `id` argument of
51 // `option()` methods above.
52 if parsed.option_exists("help") {
53 println!("Print friendly help about program's usage.");
54 return ExitCode::from(2);
55 }
56
57 // Collect all (required) values for "-f" and "--file". We use
58 // option's identifier (id) string "file" to find the option.
59 for f in &parsed.options_value_all("file") {
60 println!("File name: {:?}", f);
61 }
62
63 // Notice if "-v" or "--verbose" was given (even without a value).
64 // Then collect all its (optional) values. We use option's
65 // identifier (id) string "verbose".
66 if parsed.option_exists("verbose") {
67 println!("Option 'verbose' was given.");
68
69 for v in &parsed.options_value_all("verbose") {
70 println!("Verbose level: {:?}", v);
71 }
72 }
73
74 // Collect all other (non-option) arguments.
75 for o in &parsed.other {
76 println!("Other argument: {:?}", o);
77 }
78
79 // Try to run this program with various command-line options to see
80 // the output.
81 ExitCode::SUCCESS
82}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.)