Struct Command

Source
pub struct Command { /* private fields */ }
Expand description

A command-line command.

Implementations§

Source§

impl Command

Source

pub fn new<S: Into<String>>(name: S) -> Self

Constructs a new Command.

§Panics

Panics if the command name is blank or empty.

§Example
use clapi::Command;

let command = Command::new("My App");
assert_eq!(command.get_name(), "My App");
Source

pub fn root() -> Self

Constructs a new Command named after the running executable.

Source

pub fn with_options<S: Into<String>>(name: S, options: OptionList) -> Self

Constructs a new Command with the specified Options.

§Panics

Panics if the command name is empty or contains whitespaces.

§Example
use clapi::{OptionList, CommandOption, Command};

let mut options = OptionList::new();
options.add(CommandOption::new("enable")).unwrap();

let command = Command::with_options("My App", options);
assert!(command.get_options().contains("enable"));
Source

pub fn get_name(&self) -> &str

Returns the name of the command.

Source

pub fn get_description(&self) -> Option<&str>

Returns a short description of the command, or None if is not set.

Source

pub fn get_usage(&self) -> Option<&str>

Returns information about the usage of this command.

Source

pub fn get_help(&self) -> Option<&str>

Returns the help information of the command.

Source

pub fn get_version(&self) -> Option<&str>

Returns the version of this command.

Source

pub fn get_subcommands(&self) -> Iter<'_>

Returns an iterator over the subcommands of this command.

Source

pub fn get_subcommands_mut(&mut self) -> IterMut<'_>

Returns an ExactSizeIterator over the children of this command.

Source

pub fn get_options(&self) -> &OptionList

Returns the Options of this command.

Source

pub fn get_arg(&self) -> Option<&Argument>

Returns the Argument this option takes or None if have more than 1 argument.

Source

pub fn get_args(&self) -> &ArgumentList

Returns the Arguments of this command.

Source

pub fn take_args(&self) -> bool

Returns true if this command take args.

Source

pub fn is_hidden(&self) -> bool

Returns true if this command is no visible for help.

Source

pub fn get_handler( &self, ) -> Option<RefMut<'_, dyn FnMut(&OptionList, &ArgumentList) -> Result<()> + 'static>>

Returns the handler of this command, or None if not set.

Source

pub fn find_subcommand<S: AsRef<str>>(&self, name: S) -> Option<&Command>

Returns the child with the given name, or None if not child if found.

Source

pub fn description<S: Into<String>>(self, description: S) -> Self

Sets a short description of this command.

§Example
use clapi::Command;

let command = Command::root().description("My application");
assert_eq!(command.get_description(), Some("My application"));
Source

pub fn usage<S: Into<String>>(self, usage: S) -> Self

Sets information about the usage of this command.

§Example
use clapi::Command;
let command = Command::new("app")
    .usage("app [VALUES]\napp [OPTIONS] [VALUES]");

assert_eq!(command.get_usage(), Some("app [VALUES]\napp [OPTIONS] [VALUES]"));
Source

pub fn help<S: Into<String>>(self, help: S) -> Self

Sets help information about this command.

§Example
use clapi::Command;
let command = Command::new("MyApp")
    .version("1.0")
    .help(
"MyApp - An app for sum numbers

USAGE:
    MyApp [left] [right]

OPTIONS:
    - times [TIMES]     Number of times to multiply the numbers
    - version           Shows the version of the app
");

assert!(command.get_help().is_some());
Source

pub fn version<S: Into<String>>(self, version: S) -> Self

Sets the version of this command.

§Example
use clapi::Command;

let command = Command::new("MyApp").version("1.0.2");
assert_eq!(command.get_version(), Some("1.0.2"));
Source

pub fn option(self, option: CommandOption) -> Self

Adds an CommandOption to this command.

§Panics:

Panics it the command contains an CommandOption with the same name or alias.

§Example
use clapi::{Command, CommandOption, Argument};
use clapi::validator::validate_type;

let command = Command::new("MyApp")
    .option(CommandOption::new("enable"))
    .option(CommandOption::new("times")
        .arg(Argument::new()
            .validator(validate_type::<i64>())));

assert!(command.get_options().contains("enable"));
assert!(command.get_options().contains("times"));
Source

pub fn options(self, options: OptionList) -> Self

Replaces the options of this command with the specified.

§Example
use clapi::{OptionList, CommandOption, Argument, Command};
use clapi::validator::validate_type;

let mut options = OptionList::new();
options.add(CommandOption::new("enable")).unwrap();
options.add(CommandOption::new("times")
    .arg(Argument::new()
        .validator(validate_type::<i64>()))).unwrap();

let command = Command::new("MyApp").options(options);
assert!(command.get_options().contains("enable"));
assert!(command.get_options().contains("times"));
Source

pub fn arg(self, arg: Argument) -> Self

Adds a new Argument to this command.

§Panics:

Panic if the command contains an Argument with the same name.

§Example
use clapi::{Command, Argument};

let command = Command::new("MyApp").arg(Argument::with_name("values"));
assert_eq!(command.get_arg().unwrap().get_name(), "values");
Source

pub fn args(self, args: ArgumentList) -> Self

Sets the Arguments of this command.

§Example
use clapi::{ArgumentList, Argument, Command};

let mut args = ArgumentList::new();
args.add(Argument::with_name("values")).unwrap();

let command = Command::new("MyApp").args(args);
assert_eq!(command.get_arg().unwrap().get_name(), "values");
Source

pub fn hidden(self, is_hidden: bool) -> Self

Specify if this command is hidden for the help, this property may be ignore if is the root command.

What will be hidden or not about the command is up to the implementor of the Help trait.

§Example
use clapi::Command;

let command = Command::new("MyApp").hidden(true);
assert!(command.is_hidden());
Source

pub fn handler<F>(self, f: F) -> Self
where F: FnMut(&OptionList, &ArgumentList) -> Result<()> + 'static,

Sets the handler of this command.

§Example
use clapi::{Command, CommandLine};

let command = Command::new("test")
    .handler(|_options, _args| {
        println!("This is a test");
        Ok(())
});

let mut cli = CommandLine::new(command);
cli.run();
Source

pub fn subcommand(self, command: Command) -> Self

Adds a new child Command.

§Example
use clapi::Command;

let command = Command::new("MyApp")
    .subcommand(Command::new("test"));

assert!(command.find_subcommand("test").is_some());
Source

pub fn parse_args(self) -> Result<ParseResult>

Parse the arguments from std::env::args using this command and returns the ParseResult.

§Example:
use clapi::{Command, CommandOption, Argument};
use clapi::validator::validate_type;

let result = Command::root()
    .option(CommandOption::new("negate")
        .arg(Argument::new().validator(validate_type::<bool>())))
    .arg(Argument::one_or_more("values").validator(validate_type::<i64>()))
    .parse_args()
    .unwrap();
Source

pub fn parse_from<I, S>(self, args: I) -> Result<ParseResult>
where I: IntoIterator<Item = S>, S: Borrow<str>,

Parse the arguments using this command and returns the ParseResult.

§Example:
use clapi::{Command, CommandOption, Argument};
use clapi::validator::validate_type;

let result = Command::root()
    .option(CommandOption::new("negate")
        .arg(Argument::new().validator(validate_type::<bool>())))
    .arg(Argument::one_or_more("values").validator(validate_type::<i64>()))
    .parse_from(vec!["--negate=true", "1", "2", "3"])
    .unwrap();

assert!(result.options().contains("negate"));
assert_eq!(result.arg().unwrap().convert_all::<i64>().ok(), Some(vec![1, 2, 3]));

Trait Implementations§

Source§

impl Clone for Command

Source§

fn clone(&self) -> Command

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Command

Source§

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

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

impl<'de> Deserialize<'de> for Command

Source§

fn deserialize<D>( deserializer: D, ) -> Result<Self, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Hash for Command

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> IntoIterator for &'a Command

Source§

type Item = &'a Command

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Command

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Command

Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Command

Auto Trait Implementations§

§

impl Freeze for Command

§

impl !RefUnwindSafe for Command

§

impl !Send for Command

§

impl !Sync for Command

§

impl Unpin for Command

§

impl !UnwindSafe for Command

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,