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 option and other
methods
The struct instance is used when parsing the command line given by
program’s user. The parser methods is getopt.
Implementations§
Source§impl OptSpecs
impl OptSpecs
Sourcepub fn new() -> Self
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
option or other methods to make it useful
for parsing command-line.
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(self, id: &str, name: &str, value_type: OptValue) -> Self
pub fn option(self, id: &str, name: &str, value_type: OptValue) -> Self
Add an option specification for OptSpecs.
The method requires three arguments:
-
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
-hand--helpfor printing program’s help message. -
name: Option’s name string in the command line (without prefix). If the string is a single character (likeh) it defines a short option which is entered as-hin the command line. If there are more than one character in the string it defines a long option name (likehelp) which is entered as--helpin the command line.All options must have a unique
namestring. This method will panic if the samenameis added twice. The method will also panic if thenamestring 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. -
value_type: The argument is a variant of enumOptValueand it defines if and how this option accepts a value. See the enum’s documentation for more information.
The return value is the same struct instance which was modified.
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 flag(self, flag: OptFlags) -> Self
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
and it is a configuration flag that changes parser’s general
behavior. See the enum’s documentation for more information.
The return value is the same struct instance which was modified.
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 limit_options(self, limit: u32) -> Self
pub fn limit_options(self, limit: u32) -> Self
Maximum number of valid options.
Method’s argument limit sets the maximum number of valid
options to collect from the command line. The rest is ignored.
This doesn’t include unknown options (see
limit_unknown_options).
The return value is the same struct instance which was modified.
Sourcepub fn limit_other_args(self, limit: u32) -> Self
pub fn limit_other_args(self, limit: u32) -> Self
Maximum number of other command-line arguments.
Method’s argument limit sets the maximum number of other
(non-option) arguments to collect from the command line. The
rest is ignored.
Note: If your program accepts n number of command-line argument (apart from options) you could set this limit to n + 1. This way you know if there were more arguments than needed and can inform program’s user about that. There is no need to collect more arguments.
The return value is the same struct instance which was modified.
Sourcepub fn limit_unknown_options(self, limit: u32) -> Self
pub fn limit_unknown_options(self, limit: u32) -> Self
Maximum number of unknown options.
Method’s argument limit sets the maximum number of unique
unknown options to collect from the command line. Duplicates are
not collected.
Note: If you want to stop your program if it notices just one unknown option you can set this limit to 1. There is probably no need to collect more of them.
The return value is the same struct instance which was modified.
Sourcepub fn getopt<I, S>(&self, args: I) -> Argswhere
I: IntoIterator<Item = S>,
S: ToString,
pub fn getopt<I, S>(&self, args: I) -> Argswhere
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?
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}