pub struct Cmd<'a> {
pub cfgs: Vec<OptCfg>,
/* private fields */
}Expand description
Parses command line arguments and stores them.
The results of parsing are stored by separating into command name, command arguments, options, and option arguments.
These values are retrieved as string slices with the same lifetime as this Cmd instance.
Therefore, if you want to use those values for a longer period, it is needed to convert them
to Strings.
Fields§
§cfgs: Vec<OptCfg>The option configurations which is used to parse command line arguments.
Implementations§
source§impl<'a> Cmd<'a>
impl<'a> Cmd<'a>
sourcepub fn parse(&mut self) -> Result<(), InvalidOption>
pub fn parse(&mut self) -> Result<(), InvalidOption>
Parses command line arguments without configurations.
This method divides command line arguments into options and command arguments based on
simple rules that are almost the same as POSIX & GNU:
arguments staring with - or -- are treated as options, and others are treated as command
arguments.
If an = is found within an option, the part before the = is treated as the option name,
and the part after the = is treated as the option argument.
Options starting with -- are long options and option starting with - are short options.
Multiple short options can be concatenated into a single command line argument.
If an argument is exactly --, all subsequent arguments are treated as command arguments.
Since the results of parsing are stored into this Cmd instance, this method returns a
Result which contains an unit value (()) if succeeding, or a errors::InvalidOption
if failing.
use cliargs::Cmd;
use cliargs::errors::InvalidOption;
let mut cmd = Cmd::with_strings(vec![ /* ... */ ]);
match cmd.parse() {
Ok(_) => { /* ... */ },
Err(InvalidOption::OptionContainsInvalidChar { option }) => {
panic!("Option contains invalid character: {option}");
},
Err(err) => panic!("Invalid option: {}", err.option()),
}source§impl<'a> Cmd<'a>
impl<'a> Cmd<'a>
sourcepub fn parse_with(&mut self, opt_cfgs: Vec<OptCfg>) -> Result<(), InvalidOption>
pub fn parse_with(&mut self, opt_cfgs: Vec<OptCfg>) -> Result<(), InvalidOption>
Parses command line arguments with option configurations.
This method divides command line arguments to command arguments and options.
And an option consists of a name and an option argument.
Options are divided to long format options and short format options.
About long/short format options, since they are same with parse method, see the comment
of that method.
This method allows only options declared in option configurations, basically.
An option configuration has fields: store_key, names, has_arg, is_array,
defaults, desc, arg_in_help, and validator.
The ownership of the vector of option configurations which is passed as an argument of
this method is moved to this method and set to the public field cfgs of Cmd instance.
If you want to access the option configurations after parsing, get them from this field.
use cliargs::{Cmd, OptCfg};
use cliargs::OptCfgParam::{names, has_arg, defaults, validator, desc, arg_in_help};
use cliargs::validators::validate_number;
use cliargs::errors::InvalidOption;
let mut cmd = Cmd::with_strings(vec![ /* ... */ ]);
let opt_cfgs = vec![
OptCfg::with(&[
names(&["foo-bar"]),
desc("This is description of foo-bar."),
]),
OptCfg::with(&[
names(&["baz", "z"]),
has_arg(true),
defaults(&["1"]),
desc("This is description of baz."),
arg_in_help("<num>"),
validator(validate_number::<u32>),
]),
];
match cmd.parse_with(opt_cfgs) {
Ok(_) => { /* ... */ },
Err(InvalidOption::OptionContainsInvalidChar { option }) => { /* ... */ },
Err(InvalidOption::UnconfiguredOption { option }) => { /* ... */ },
Err(InvalidOption::OptionNeedsArg { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionTakesNoArg { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionIsNotArray { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionArgIsInvalid { option, opt_arg, details, .. }) => { /* ... */ },
Err(err) => panic!("Invalid option: {}", err.option()),
}source§impl Cmd<'_>
impl Cmd<'_>
sourcepub fn parse_for<T: OptStore>(
&mut self,
opt_store: &mut T,
) -> Result<(), InvalidOption>
pub fn parse_for<T: OptStore>( &mut self, opt_store: &mut T, ) -> Result<(), InvalidOption>
Parses command line arguments and set their option values to the option store which is passed as an argument.
This method divides command line arguments to command arguments and options, then sets each option value to a curresponding field of the option store.
Within this method, a vector of OptCfg is made from the fields of the option store.
This OptCfg vector is set to the public field cfgs of the Cmd instance.
If you want to access this option configurations, get them from this field.
An option configuration corresponding to each field of an option store is determined by
its type and opt field attribute.
If the type is bool, the option takes no argument.
If the type is integer, floating point number or string, the option can takes single option
argument, therefore it can appear once in command line arguments.
If the type is a vector, the option can takes multiple option arguments, therefore it can
appear multiple times in command line arguments.
A opt field attribute can have the following pairs of name and value: one is cfg to
specify names and defaults fields of OptCfg struct, another is desc to specify
desc field, and yet another is arg to specify arg_in_help field.
The format of cfg is like cfg="f,foo=123".
The left side of the equal sign is the option name(s), and the right side is the default
value(s).
If there is no equal sign, it is determined that only the option name is specified.
If you want to specify multiple option names, separate them with commas.
If you want to specify multiple default values, separate them with commas and round them
with square brackets, like [1,2,3].
If you want to use your favorite carachter as a separator, you can use it by putting it on
the left side of the open square bracket, like /[1/2/3].
NOTE: A default value of empty string array option in a field attribute is [], like
#[opt(cfg="=[]")], but it doesn’t represent an array which contains only one empty
string.
If you want to specify an array which contains only one emtpy string, write nothing after
= symbol, like #[opt(cfg="=")].
use cliargs::Cmd;
use cliargs::errors::InvalidOption;
#[derive(cliargs::OptStore)]
struct MyOptions {
#[opt(cfg = "f,foo-bar", desc="The description of foo_bar.")]
foo_bar: bool,
#[opt(cfg = "b,baz", desc="The description of baz.", arg="<s>")]
baz: String,
}
let mut my_options = MyOptions::with_defaults();
let mut cmd = Cmd::with_strings(vec![ /* ... */ ]);
match cmd.parse_for(&mut my_options) {
Ok(_) => { /* ... */ },
Err(InvalidOption::OptionContainsInvalidChar { option }) => { /* ... */ },
Err(InvalidOption::UnconfiguredOption { option }) => { /* ... */ },
Err(InvalidOption::OptionNeedsArg { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionTakesNoArg { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionIsNotArray { option, .. }) => { /* ... */ },
Err(InvalidOption::OptionArgIsInvalid { option, opt_arg, details, .. }) => { /* ... */ },
Err(err) => panic!("Invalid option: {}", err.option()),
}
let opt_cfgs = &cmd.cfgs;source§impl<'a> Cmd<'a>
impl<'a> Cmd<'a>
sourcepub fn new() -> Result<Cmd<'a>, InvalidOsArg>
pub fn new() -> Result<Cmd<'a>, InvalidOsArg>
Creates a Cmd instance with command line arguments obtained from std::env::args_os.
Since std::env::args_os returns a vector of OsString and they can contain invalid
unicode data, the return value of this funciton is Result of Cmd or
errors::InvalidOsArg.
sourcepub fn with_os_strings(
osargs: impl IntoIterator<Item = OsString>,
) -> Result<Cmd<'a>, InvalidOsArg>
pub fn with_os_strings( osargs: impl IntoIterator<Item = OsString>, ) -> Result<Cmd<'a>, InvalidOsArg>
sourcepub fn with_strings(args: impl IntoIterator<Item = String>) -> Cmd<'a>
pub fn with_strings(args: impl IntoIterator<Item = String>) -> Cmd<'a>
Creates a Cmd instance with the specified iterator of Strings.
sourcepub fn name(&'a self) -> &'a str
pub fn name(&'a self) -> &'a str
Returns the command name.
This name is base name extracted from the command path string slice, which is the first element of the command line arguments.
sourcepub fn args(&'a self) -> &'a [&'a str]
pub fn args(&'a self) -> &'a [&'a str]
Returns the command arguments.
These arguments are retrieved as string slices in an array.
sourcepub fn has_opt(&self, name: &str) -> bool
pub fn has_opt(&self, name: &str) -> bool
Checks whether an option with the specified name exists.