Struct Cmd

Source
pub struct Cmd<'a> { /* 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.

Implementations§

Source§

impl<'b, '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

pub fn parse_until_sub_cmd(&mut self) -> Result<Option<Cmd<'b>>, InvalidOption>

Parses command line arguments without configurations but stops parsing when encountering first command argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd::parse method, except that it only parses the command line arguments before the first command argument.

use cliargs::Cmd;
use cliargs::errors::InvalidOption;

let mut cmd = Cmd::with_strings(vec![ /* ... */ ]);

match cmd.parse_until_sub_cmd() {
    Ok(Some(mut sub_cmd)) => {
        let sub_cmd_name = sub_cmd.name();
        match sub_cmd.parse() {
            Ok(_) => { /* ... */ },
            Err(err) => panic!("Invalid option: {}", err.option()),
        }
    },
    Ok(None) => { /* ... */ },
    Err(InvalidOption::OptionContainsInvalidChar { option }) => {
        panic!("Option contains invalid character: {option}");
    },
    Err(err) => panic!("Invalid option: {}", err.option()),
}
Source§

impl<'b, '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.

When an option matches one of the names in the option configurations, the option is registered into Cmd with store_key. If both has_arg and is_array is false, the optioin can have only one option argument, otherwise the option cannot have option arguments. If defaults field is specified and no option value is given in command line arguments, the value of defaults is set as the option arguments.

If options not declared in option configurations are given in command line arguments, this method basicaly returns InvalidOption::UnconfiguredOption error. However, if you want to allow other options, add an option configuration of which store_key or the first element of names is “*”.

The ownership of the vector of option configurations which is passed as an argument of this method is moved to this method and set into this Cmd instance. It can be retrieved with its method: Cmd::opt_cfgs.

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

pub fn parse_until_sub_cmd_with( &mut self, opt_cfgs: Vec<OptCfg>, ) -> Result<Option<Cmd<'b>>, InvalidOption>

Parses command line arguments with option configurations but stops parsing when encountering first command argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd::parse_with method, except that it only parses the command line arguments before the first command argument.

The ownership of the vector of option configurations which is passed as an argument of this method is moved to this method and set into this Cmd instance. It can be retrieved with its method: Cmd::opt_cfgs.

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_until_sub_cmd_with(opt_cfgs) {
    Ok(Some(mut sub_cmd)) => {
        let sub_cmd_name = sub_cmd.name();
        match sub_cmd.parse() {
            Ok(_) => { /* ... */ },
            Err(err) => panic!("Invalid option: {}", err.option()),
        }
    },
    Ok(None) => { /* ... */ },
    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<'b> 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 fields of the option store which is passed as the argument of this method.

This method divides command line arguments to command arguments and options, then sets each option value to a corresponding 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 into this Cmd instance. If you want to access this option configurations, get them by opt_cfgs method.

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 character 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 cfgs = cmd.opt_cfgs();
Source

pub fn parse_until_sub_cmd_for<T: OptStore>( &mut self, opt_store: &mut T, ) -> Result<Option<Cmd<'b>>, InvalidOption>

Parses command line arguments until the first command argument and set their option values to the option store which is passed as an argument.

This method creates and returns a new Cmd instance that holds the command line arguments starting from the first command argument.

This method parses command line arguments in the same way as the Cmd::parse_for method, except that it only parses the command line arguments before the first command argument.

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_until_sub_cmd_for(&mut my_options) {
    Ok(Some(mut sub_cmd)) => {
        let sub_cmd_name = sub_cmd.name();
        match sub_cmd.parse() {
            Ok(_) => { /* ... */ },
            Err(err) => panic!("Invalid option: {}", err.option()),
        }
    },
    Ok(None) => { /* ... */ },
    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 cfgs = cmd.opt_cfgs();
Source§

impl<'b, '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. If the option is a boolean flag, this method returns None. If the option is not specified in the command line arguments, the return value of this method is 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. If the option is a boolean flag, this method returns an empty vector. If the option is not specified in the command line arguments, the return value of this method is None.

Source

pub fn opt_cfgs(&'a self) -> &[OptCfg]

Retrieves the option configurations which was used to parse command line arguments.

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T