Struct cliargs::Cmd

source ·
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>

source

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>

source

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<'_>

source

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>

source

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.

source

pub fn with_os_strings( osargs: impl IntoIterator<Item = OsString>, ) -> Result<Cmd<'a>, InvalidOsArg>

Creates a Cmd instance with the specified iterator of OsStrings.

OsStrings can contain invalid unicode data, the return value of this function is Result of Cmd or errors::InvalidOsArg.

source

pub fn with_strings(args: impl IntoIterator<Item = String>) -> Cmd<'a>

Creates a Cmd instance with the specified iterator of Strings.

source

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.

source

pub fn args(&'a self) -> &'a [&'a str]

Returns the command arguments.

These arguments are retrieved as string slices in an array.

source

pub fn has_opt(&self, name: &str) -> bool

Checks whether an option with the specified name exists.

source

pub fn opt_arg(&'a self, name: &str) -> Option<&'a str>

Returns the option argument with the specified name.

If the option has multiple arguments, this method returns the first argument.

Since the option may not be specified in the command line arguments, the return value of this method is an Option of an option argument or None.

source

pub fn opt_args(&'a self, name: &str) -> Option<&'a [&'a str]>

Returns the option arguments with the specified name.

If the option has one or multiple arguments, this method returns an array of the arguments.

Since the option may not be specified in the command line arguments, the return value of this method is an Option of option arguments or None.

Trait Implementations§

source§

impl Debug for Cmd<'_>

source§

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

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

impl<'a> Drop for Cmd<'a>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Cmd<'a>

§

impl<'a> RefUnwindSafe for Cmd<'a>

§

impl<'a> Send for Cmd<'a>

§

impl<'a> Sync for Cmd<'a>

§

impl<'a> Unpin for Cmd<'a>

§

impl<'a> UnwindSafe for Cmd<'a>

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>,

§

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>,

§

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.