just_getopt

Struct OptSpecs

Source
pub struct OptSpecs { /* private fields */ }
Expand description

Specification for program’s valid command-line options.

An instance of this struct is needed before command-line options can be parsed. Instances are created with function OptSpecs::new and they are modified with methods option and flag.

The struct instance is used when parsing the command line given by program’s user. The parser methods is getopt.

Implementations§

Source§

impl OptSpecs

Source

pub fn new() -> Self

Create and return a new instance of OptSpecs struct.

The created instance is “empty” and does not contain any specifications for command-line options. Apply methods option and flag to make it useful for parsing command-line.

Examples found in repository?
examples/basic.rs (line 17)
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
fn main() -> ExitCode {
    // The `OptSpecs::new()` function below creates a new option
    // specification struct `OptSpecs`. Its `option()` methods configure
    // three different options for logical meanings "help", "file" and
    // "verbose". All three options can be written in command-line with
    // a short variant (like "-h") and a long variant (like "--help").
    // Some options accept or require a value.
    //
    // Flag OptionsEverywhere changes parser's behavior. This flag means
    // that options and other arguments (non-options) can be mixed in
    // their order in the command line. Without the flag the option
    // parsing stops at the first non-option argument and the rest of
    // the command-line is parsed as non-options.
    let specs = OptSpecs::new()
        .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
        .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
        .option("help", "help", OptValueType::None)
        .option("file", "f", OptValueType::Required)
        .option("file", "file", OptValueType::Required)
        .option("verbose", "v", OptValueType::Optional)
        .option("verbose", "verbose", OptValueType::Optional);

    // Parse program's command-line with the given specification `specs`.
    let mut args = std::env::args(); // Get arguments iterator from operating system.
    args.next(); // Consume the first item which is this program's name.
    let parsed = specs.getopt(args);

    // With this you can see the parsed output which is an `Args`
    // struct.
    eprintln!("{:#?}", parsed);

    // Report user about unknown options.
    for u in &parsed.unknown {
        eprintln!("Unknown option: {}", u);
    }

    // Report user about missing values for options that require them
    // (i.e. "file"). Exit the program with error code.
    for o in &parsed.required_value_missing() {
        eprintln!("Value is required for option '{}'.", o.name);
        return ExitCode::FAILURE;
    }

    // Print help and exit because "-h" or "--help" was given. We use
    // option's identifier string "help" here to find if the correct
    // option was present in the command line. See the `id` argument of
    // `option()` methods above.
    if let Some(_) = parsed.options_first("help") {
        println!("Print friendly help about program's usage.");
        return ExitCode::from(2);
    }

    // Collect all (required) values for "-f" and "--file". We use
    // option's identifier (id) string "file" to find the option.
    for f in &parsed.options_value_all("file") {
        println!("File name: {:?}", f);
    }

    // Notice if "-v" or "--verbose" was given (even without a value).
    // Then collect all its (optional) values. We use option's
    // identifier (id) string "verbose".
    if let Some(_) = parsed.options_first("verbose") {
        println!("Option 'verbose' was given.");

        for v in &parsed.options_value_all("verbose") {
            println!("Verbose level: {:?}", v);
        }
    }

    // Collect all other (non-option) arguments.
    for o in &parsed.other {
        println!("Other argument: {:?}", o);
    }

    // Try to run this program with various command-line options to see
    // the output.
    ExitCode::SUCCESS
}
Source

pub fn option(self, id: &str, name: &str, value_type: OptValueType) -> Self

Add an option specification for OptSpecs.

The method requires three arguments:

  1. id: Programmer’s identifier string for the option. Later, after parsing the command line, the identifier is used to match if this particular option was present in the command-line.

    Several options may have the same identifier string. This makes sense when different option names in the command line represent the same meaning, like -h and --help for printing program’s help message.

  2. name: Option’s name string in the command line (without prefix). If the string is a single character (like h) it defines a short option which is entered as -h in the command line. If there are more than one character in the string it defines a long option name (like help) which is entered as --help in the command line.

    All options must have a unique name string. This method will panic if the same name is added twice. The method will also panic if the name string contains illegal characters. Space characters are not accepted. A short option name can’t be - and long option names can’t have any = characters nor - as their first character.

  3. value_type: A variant of enum OptValueType which defines if this option accepts a value. If not, use OptValueType::None as method’s argument. If an optional value is accepted, use OptValueType::Optional. If the option requires a value, use OptValueType::Required.

Method returns the same OptSpecs struct instance which was modified.

Examples found in repository?
examples/basic.rs (line 19)
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
fn main() -> ExitCode {
    // The `OptSpecs::new()` function below creates a new option
    // specification struct `OptSpecs`. Its `option()` methods configure
    // three different options for logical meanings "help", "file" and
    // "verbose". All three options can be written in command-line with
    // a short variant (like "-h") and a long variant (like "--help").
    // Some options accept or require a value.
    //
    // Flag OptionsEverywhere changes parser's behavior. This flag means
    // that options and other arguments (non-options) can be mixed in
    // their order in the command line. Without the flag the option
    // parsing stops at the first non-option argument and the rest of
    // the command-line is parsed as non-options.
    let specs = OptSpecs::new()
        .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
        .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
        .option("help", "help", OptValueType::None)
        .option("file", "f", OptValueType::Required)
        .option("file", "file", OptValueType::Required)
        .option("verbose", "v", OptValueType::Optional)
        .option("verbose", "verbose", OptValueType::Optional);

    // Parse program's command-line with the given specification `specs`.
    let mut args = std::env::args(); // Get arguments iterator from operating system.
    args.next(); // Consume the first item which is this program's name.
    let parsed = specs.getopt(args);

    // With this you can see the parsed output which is an `Args`
    // struct.
    eprintln!("{:#?}", parsed);

    // Report user about unknown options.
    for u in &parsed.unknown {
        eprintln!("Unknown option: {}", u);
    }

    // Report user about missing values for options that require them
    // (i.e. "file"). Exit the program with error code.
    for o in &parsed.required_value_missing() {
        eprintln!("Value is required for option '{}'.", o.name);
        return ExitCode::FAILURE;
    }

    // Print help and exit because "-h" or "--help" was given. We use
    // option's identifier string "help" here to find if the correct
    // option was present in the command line. See the `id` argument of
    // `option()` methods above.
    if let Some(_) = parsed.options_first("help") {
        println!("Print friendly help about program's usage.");
        return ExitCode::from(2);
    }

    // Collect all (required) values for "-f" and "--file". We use
    // option's identifier (id) string "file" to find the option.
    for f in &parsed.options_value_all("file") {
        println!("File name: {:?}", f);
    }

    // Notice if "-v" or "--verbose" was given (even without a value).
    // Then collect all its (optional) values. We use option's
    // identifier (id) string "verbose".
    if let Some(_) = parsed.options_first("verbose") {
        println!("Option 'verbose' was given.");

        for v in &parsed.options_value_all("verbose") {
            println!("Verbose level: {:?}", v);
        }
    }

    // Collect all other (non-option) arguments.
    for o in &parsed.other {
        println!("Other argument: {:?}", o);
    }

    // Try to run this program with various command-line options to see
    // the output.
    ExitCode::SUCCESS
}
Source

pub fn flag(self, flag: OptFlags) -> Self

Add a flag that changes parser’s behavior.

Method’s only argument flag is a variant of enum OptFlags. Their names and meanings are:

  • OptFlags::OptionsEverywhere: Accept command-line options and other arguments in mixed order in the command line. That is, options can come after non-option arguments.

    This is not the default behavior. By default the first non-option argument in the command line stops option parsing and the rest of the command line is parsed as non-options (other arguments), even if they look like options.

  • OptFlags::PrefixMatchLongOptions: With this flag long options don’t need to be written in full in the command line. They can be shortened as long as there are enough characters to find a unique prefix match. If there are more than one match the option given in the command line is classified as unknown.

Method returns the same OptSpecs struct instance which was modified.

Examples found in repository?
examples/basic.rs (line 18)
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
fn main() -> ExitCode {
    // The `OptSpecs::new()` function below creates a new option
    // specification struct `OptSpecs`. Its `option()` methods configure
    // three different options for logical meanings "help", "file" and
    // "verbose". All three options can be written in command-line with
    // a short variant (like "-h") and a long variant (like "--help").
    // Some options accept or require a value.
    //
    // Flag OptionsEverywhere changes parser's behavior. This flag means
    // that options and other arguments (non-options) can be mixed in
    // their order in the command line. Without the flag the option
    // parsing stops at the first non-option argument and the rest of
    // the command-line is parsed as non-options.
    let specs = OptSpecs::new()
        .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
        .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
        .option("help", "help", OptValueType::None)
        .option("file", "f", OptValueType::Required)
        .option("file", "file", OptValueType::Required)
        .option("verbose", "v", OptValueType::Optional)
        .option("verbose", "verbose", OptValueType::Optional);

    // Parse program's command-line with the given specification `specs`.
    let mut args = std::env::args(); // Get arguments iterator from operating system.
    args.next(); // Consume the first item which is this program's name.
    let parsed = specs.getopt(args);

    // With this you can see the parsed output which is an `Args`
    // struct.
    eprintln!("{:#?}", parsed);

    // Report user about unknown options.
    for u in &parsed.unknown {
        eprintln!("Unknown option: {}", u);
    }

    // Report user about missing values for options that require them
    // (i.e. "file"). Exit the program with error code.
    for o in &parsed.required_value_missing() {
        eprintln!("Value is required for option '{}'.", o.name);
        return ExitCode::FAILURE;
    }

    // Print help and exit because "-h" or "--help" was given. We use
    // option's identifier string "help" here to find if the correct
    // option was present in the command line. See the `id` argument of
    // `option()` methods above.
    if let Some(_) = parsed.options_first("help") {
        println!("Print friendly help about program's usage.");
        return ExitCode::from(2);
    }

    // Collect all (required) values for "-f" and "--file". We use
    // option's identifier (id) string "file" to find the option.
    for f in &parsed.options_value_all("file") {
        println!("File name: {:?}", f);
    }

    // Notice if "-v" or "--verbose" was given (even without a value).
    // Then collect all its (optional) values. We use option's
    // identifier (id) string "verbose".
    if let Some(_) = parsed.options_first("verbose") {
        println!("Option 'verbose' was given.");

        for v in &parsed.options_value_all("verbose") {
            println!("Verbose level: {:?}", v);
        }
    }

    // Collect all other (non-option) arguments.
    for o in &parsed.other {
        println!("Other argument: {:?}", o);
    }

    // Try to run this program with various command-line options to see
    // the output.
    ExitCode::SUCCESS
}
Source

pub fn getopt<I, S>(&self, args: I) -> Args
where I: IntoIterator<Item = S>, S: ToString,

Getopt-parse an iterable item as command line arguments.

This method’s argument args is of any type that implements trait IntoIterator and that has items of type that implements trait ToString. For example, argument args can be a vector or an iterator such as command-line arguments returned by std::env::args.

The return value is an Args struct which represents the command-line information in organized form.

Examples found in repository?
examples/basic.rs (line 29)
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
fn main() -> ExitCode {
    // The `OptSpecs::new()` function below creates a new option
    // specification struct `OptSpecs`. Its `option()` methods configure
    // three different options for logical meanings "help", "file" and
    // "verbose". All three options can be written in command-line with
    // a short variant (like "-h") and a long variant (like "--help").
    // Some options accept or require a value.
    //
    // Flag OptionsEverywhere changes parser's behavior. This flag means
    // that options and other arguments (non-options) can be mixed in
    // their order in the command line. Without the flag the option
    // parsing stops at the first non-option argument and the rest of
    // the command-line is parsed as non-options.
    let specs = OptSpecs::new()
        .flag(OptFlags::OptionsEverywhere) // Argument: (flag)
        .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
        .option("help", "help", OptValueType::None)
        .option("file", "f", OptValueType::Required)
        .option("file", "file", OptValueType::Required)
        .option("verbose", "v", OptValueType::Optional)
        .option("verbose", "verbose", OptValueType::Optional);

    // Parse program's command-line with the given specification `specs`.
    let mut args = std::env::args(); // Get arguments iterator from operating system.
    args.next(); // Consume the first item which is this program's name.
    let parsed = specs.getopt(args);

    // With this you can see the parsed output which is an `Args`
    // struct.
    eprintln!("{:#?}", parsed);

    // Report user about unknown options.
    for u in &parsed.unknown {
        eprintln!("Unknown option: {}", u);
    }

    // Report user about missing values for options that require them
    // (i.e. "file"). Exit the program with error code.
    for o in &parsed.required_value_missing() {
        eprintln!("Value is required for option '{}'.", o.name);
        return ExitCode::FAILURE;
    }

    // Print help and exit because "-h" or "--help" was given. We use
    // option's identifier string "help" here to find if the correct
    // option was present in the command line. See the `id` argument of
    // `option()` methods above.
    if let Some(_) = parsed.options_first("help") {
        println!("Print friendly help about program's usage.");
        return ExitCode::from(2);
    }

    // Collect all (required) values for "-f" and "--file". We use
    // option's identifier (id) string "file" to find the option.
    for f in &parsed.options_value_all("file") {
        println!("File name: {:?}", f);
    }

    // Notice if "-v" or "--verbose" was given (even without a value).
    // Then collect all its (optional) values. We use option's
    // identifier (id) string "verbose".
    if let Some(_) = parsed.options_first("verbose") {
        println!("Option 'verbose' was given.");

        for v in &parsed.options_value_all("verbose") {
            println!("Verbose level: {:?}", v);
        }
    }

    // Collect all other (non-option) arguments.
    for o in &parsed.other {
        println!("Other argument: {:?}", o);
    }

    // Try to run this program with various command-line options to see
    // the output.
    ExitCode::SUCCESS
}

Trait Implementations§

Source§

impl Debug for OptSpecs

Source§

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

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

impl Default for OptSpecs

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl PartialEq for OptSpecs

Source§

fn eq(&self, other: &OptSpecs) -> 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 OptSpecs

Auto Trait Implementations§

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.