Args

Struct Args 

Source
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

Source

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?
examples/basic.rs (line 51)
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}
Source

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?
examples/basic.rs (line 66)
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}
Source

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>>().

Source

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 given id.

  • Some(&Opt): An option was found with the given id and a reference is provided to its Opt struct in the original Args::options field.

Source

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.

Source

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?
examples/basic.rs (line 73)
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}
Source

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 given id and a value assigned. Note that there could be options for the same id but they don’t have a value.

  • Some(&String): An option was found with the given id and the option has a value assigned. A reference is provided to the string value in the Opt::value field in the original Args::options field.

Source

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.)

Trait Implementations§

Source§

impl Debug for Args

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Args

Source§

fn eq(&self, other: &Args) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Args

Auto Trait Implementations§

§

impl Freeze for Args

§

impl RefUnwindSafe for Args

§

impl Send for Args

§

impl Sync for Args

§

impl Unpin for Args

§

impl UnwindSafe for Args

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.