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
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 methods
option and flag to
make it useful for parsing command-line.
Examples found in repository?
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
}Sourcepub fn option(self, id: &str, name: &str, value_type: OptValueType) -> Self
pub fn option(self, id: &str, name: &str, value_type: OptValueType) -> 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: A variant of enumOptValueTypewhich defines if this option accepts a value. If not, useOptValueType::Noneas method’s argument. If an optional value is accepted, useOptValueType::Optional. If the option requires a value, useOptValueType::Required.
Method returns the same OptSpecs struct instance which was
modified.
Examples found in repository?
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
}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.
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?
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
}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?
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
}