Struct Command

Source
pub struct Command {
    pub argv: Vec<String>,
    pub argc: usize,
    pub executable: String,
    pub options: Vec<String>,
    pub definitions: HashMap<String, String>,
    pub first_arg: Option<String>,
    pub last_arg: Option<String>,
    pub double_hyphen_argv: Option<Vec<String>>,
}
Expand description

A command line argument object

The Command struct defines fields that hold parsed command line argument data and provides methods that can be used to define the logic of a command line interface application.

§Examples

§Instantiation

extern crate commandlines;

use commandlines::Command;

def main() {
    let c = Command::new();
}

§Debugging

The Command struct supports pretty-printed display of all parsed data fields to the standard output stream with the {:#?} formatting idiom:

use commandlines::Command;

println!("{:#?}", Command::new());

§Remarks

The Vector of command line arguments presented to the executable in std::env::args().collect() is used to define the Command struct fields.

See the documentation for the Command struct methods and fields to learn how to use the parsed data in your command line interface application logic.

Fields§

§argv: Vec<String>

Vector of ordered command line arguments

§argc: usize

number of strings in Command.argv

§executable: String

The executable path at index position 0 of Command.argv

§options: Vec<String>

Vector of command line options in Command.argv

§definitions: HashMap<String, String>

HashMap of command line option definitions mapped as key=option:value=definition

§first_arg: Option<String>

Option<String> of first positional argument to the executable. None if there are no arguments to the executable.

§last_arg: Option<String>

Option<String> of last positional argument to the executable. None if there are no arguments to the executable.

§double_hyphen_argv: Option<Vec<String>>

Option<Vec<String>> of ordered arguments that follow a double hyphen command line idiom. None if a double hyphen argument is not present or there are no arguments after the double hyphen argument.

Implementations§

Source§

impl Command

Source

pub fn new() -> Self

Instantiates and returns a new Command struct with the command line argument data in std::env::args().collect()

§Remarks

Instantiate a Command struct in the main() method of the main.rs file of your Rust executable project.

§Examples
extern crate commandlines;

use commandlines::Command;

def main() {
    let c = Command::new();
}
Source

pub fn has_args(&self) -> bool

Returns a boolean for the question “Does the command include any arguments to the executable?”

§Remarks

This method defines an argument as a command line string that occurs after the executable path string located at index position 0 of Command.argv. Please note that the executable path at index position 0 in the Vec<String> returned by std::env::args().collect() will always be present and is intentionally not part of this definition.

§Examples
let c = commandlines::Command::new();

if !c.has_args() {
   eprintln!("Missing arguments");
}
Source

pub fn has_definitions(&self) -> bool

Returns a boolean for the question “Does the command include any definition options?”

§Remarks

A definition option is defined as a command line string that takes a short or long option format with an equal symbol character that is used to indicate that an option definition string follows. This library supports the following formats:

  • --option=def
  • -o=def

The long format with two hyphens is specified in the GNU command line argument conventions. The short format with a single hyphen is not specified in the POSIX or GNU guidelines.

§Examples
let c = commandlines::Command::new();

if c.has_definitions() {
   // definitions were parsed in the command
}
Source

pub fn has_double_hyphen_args(&self) -> bool

Returns a boolean for the question “Does the command include any arguments following the double hyphen (–) idiom?”

§Examples
let c = commandlines::Command::new();

if c.has_double_hyphen_args() {
    // arguments were identified following a double hyphen idiom
}
Source

pub fn has_mops(&self) -> bool

Returns a boolean for the question “Does the command include any multi-option short syntax style option arguments?”

§Remarks

POSIX defines a short option style that uses a single hyphen delimiter with more than one option indicated by the individual characters defined in the argument string (e.g., -hij means that the command has the options -h -i -j). This method provides support for determining whether a mops style option is present in the command string.

§Examples
let c = commandlines::Command::new();

if c.has_mops() {
    // at least one multi-option short syntax style argument was parsed in the command
}
Source

pub fn has_options(&self) -> bool

Returns a boolean for the question “Does the command include any options?”

§Remarks

An option is defined as a command line argument that starts with one or two hyphen characters. This definition includes standard long (e.g., --longoption) and short (e.g., -s) command line options.

If you use POSIX multi-option short syntax style arguments (e.g., “-lmn” is used to indicate “-l -m -n”) in your application, see the Command::contains_mops() method. This method does not test against mops style command line arguments.

§Examples
let c = commandlines::Command::new();

if c.has_options() {
   // start application-specific option parsing logic
}
Source

pub fn contains_arg(&self, needle: &str) -> bool

Returns a boolean for the question “Does the command include the argument string needle?” at any index

§Examples
let c = commandlines::Command::new();

if c.contains_arg("spam") {
    // a `spam` argument was in the command
}
Source

pub fn contains_definition(&self, needle: &str) -> bool

Returns a boolean for the question “Does the command include the definition option needle?”

§Examples
let c = commandlines::Command::new();

if c.contains_definition("--spam") {
    // command included a `--spam=[definition]` option
}
Source

pub fn contains_mops(&self, needle: &str) -> bool

Returns a boolean for the question “Does the command include the option needle when the POSIX multi-option short syntax option style is used?”

§Remarks

The mops style defined by POSIX includes a single hyphen character followed by one or more alphanumeric characters in the Unicode Basic Latin set. Each character represents a unique option switch. For example, “-lmn” is used to indicate “-l -m -n”. This method tests against any short option formatted argument included in the command irrespective of the number of alphanumeric characters that are included. The method does not test against long options (i.e., those that begin with two hyphens).

If you do not use the mops option syntax in your application, use the Command::contains_option() method instead.

§Examples
let c = commandlines::Command::new();

if c.contains_mops("-j") {
    // the `j` switch was identified in a short format option on the command line
}
Source

pub fn contains_option(&self, needle: &str) -> bool

Returns a boolean for the question “Does the command include the option string needle at any index?”

§Examples
let c = commandlines::Command::new();

if c.contains_option("--help") {
    // you have a standard request for help documentation
}
Source

pub fn contains_all_mops(&self, needle_vec: Vec<&str>) -> bool

Returns a boolean for the question “Does the command include the option needle when the POSIX multi-option short syntax option style is used?”

§Remarks

The mops style defined by POSIX includes a single hyphen character followed by one or more alphanumeric characters in the Unicode Basic Latin set. Each character represents a unique option switch. For example, “-lmn” is used to indicate “-l -m -n”. This method tests against any short option formatted argument included in the command irrespective of the number of alphanumeric characters that are included. The method does not test against long options (i.e., those that begin with two hyphens).

If you do not use the mops option syntax in your application, use the Command::contains_all_options() method instead.

§Examples
let c = commandlines::Command::new();

if c.contains_all_mops(vec!["-j", "-k", "-l"]) {
    // the `j`, `k` and `l` switches were identified in short format options on the command line
}
Source

pub fn contains_all_options(&self, needle_vec: Vec<&str>) -> bool

Returns a boolean for the question “Does the command include all of the option strings in needle_vec Vector?”

§Examples
let c = commandlines::Command::new();

if c.contains_all_options(vec!["--some", "--things"]) {
    // implement whatever requires `some` && `things` condition
}
Source

pub fn contains_any_mops(&self, needle_vec: Vec<&str>) -> bool

Returns a boolean for the question “Does the command include the option needle when the POSIX multi-option short syntax option style is used?”

§Remarks

The mops style defined by POSIX includes a single hyphen character followed by one or more alphanumeric characters in the Unicode Basic Latin set. Each character represents a unique option switch. For example, “-lmn” is used to indicate “-l -m -n”. This method tests against any short option formatted argument included in the command irrespective of the number of alphanumeric characters that are included. The method does not test against long options (i.e., those that begin with two hyphens).

If you do not use the mops option syntax in your application, use the Command::contains_any_options() method instead.

§Examples
let c = commandlines::Command::new();

if c.contains_any_mops(vec!["-j", "-k", "-l"]) {
    // the `j` or `k` or `l` switch was identified in short format options on the command line
}
Source

pub fn contains_any_option(&self, needle_vec: Vec<&str>) -> bool

Returns a boolean for the question “Does the command include any of the option strings in the needle_vec Vector?”

§Examples
let c = commandlines::Command::new();

if c.contains_any_option(vec!["-h", "--help"]) {
    // received a help request with `-h` || `--help` condition
}
Source

pub fn contains_sequence(&self, needle_vec: Vec<&str>) -> bool

Returns boolean for the question “Do the command arguments to the executable match the argument strings and sequence in needle_vec Vector?”

§Examples
let c = commandlines::Command::new();

if c.contains_sequence(vec!["filter", "help"]) {
    // the command sequence was identified as "[executable] filter help"
}
Source

pub fn get_definition_for(&self, needle: &str) -> Option<Cow<'_, str>>

Returns Option<Cow<str>> definition for a key defined by needle

Returns None if the option was not used in the command

§Examples

The following example demonstrates how to get the definition string for a command line option with the format --name=[definition]:

let c = commandlines::Command::new();

match c.get_definition_for("--name") {
    Some(x) => println!("The definition for --name is {}", x),
    None => eprintln!("Missing")
};
Source

pub fn get_argument_after(&self, needle: &str) -> Option<Cow<'_, str>>

Returns Option<Cow<str>> for argument at index position i+1 for needle at index position i

Returns None if needle is the last positional argument in the command

§Remarks

This method can be used to obtain space-delimited definition arguments that follow an option (e.g., -o [filepath]).

§Examples

For a command with the syntax test -o [filepath] the following can be used to get the filepath definition after the -o option:

let c = commandlines::Command::new();

match c.get_argument_after("-o") {
    Some(x) => println!("The filepath definition after -o is {}", x),
    None => eprintln!("-o is the last positional argument in the command")
}
Source

pub fn get_arguments_after(&self, needle: &str) -> Option<Vec<Cow<'_, str>>>

Returns Option<Vec<Cow<str>>> for the one or more ordered arguments that follow the needle argument

Returns None if needle is not in the command or there are no arguments after the needle argument

§Examples
let c = commandlines::Command::new();

match c.get_arguments_after("-o") {
    Some(x) => println!("The arguments after the -o option are {:?}", x),
    None => eprintln!("-o not found or there were no arguments after -o")
}
Source

pub fn get_argument_at(&self, needle: usize) -> Option<Cow<'_, str>>

Returns Option<Cow<str>> for the argument at index position needle

Returns None if needle is outside of the bounds of valid index values

§Examples
// example command = "test subcmd --option"
let c = commandlines::Command::new();

match c.get_argument_at(0) {
    Some(x) => println!("The executable is {}", x),
    None => eprintln!("Error")
}

match c.get_argument_at(1) {
    Some(x) => println!("The first positional argument is {}", x),
    None => eprintln!("There is no first positional argument")
}
Source

pub fn get_arguments_after_double_hyphen(&self) -> Option<Vec<Cow<'_, str>>>

Returns Option<Vec<Cow<str>>> for the arguments in sequence that follow a double hyphen -- command line idiom

Returns None if there is no double hyphen idiom or there are no arguments that follow the idiom

§Examples
let c = commandlines::Command::new();

match c.get_arguments_after_double_hyphen() {
    Some(x) => println!("Args following double hyphen: {:?}", x),
    None => eprintln!("There are no arguments that follow a double hyphen idiom")
}
Source

pub fn get_argument_first(&self) -> Option<Cow<'_, str>>

Returns Option<Cow<str>> for the first positional argument to the executable

Returns None if there are no arguments to the executable

§Examples
let c = commandlines::Command::new();

match c.get_argument_first() {
    Some(x) => println!("The first positional argument is {}", x),
    None => eprintln!("There are no arguments to the executable")
}
Source

pub fn get_argument_last(&self) -> Option<Cow<'_, str>>

Returns Option<Cow<str>> for the last positional argument to the executable

Returns None if there are no arguments to the executable

§Examples
let c = commandlines::Command::new();

match c.get_argument_last() {
    Some(x) => println!("The last positional argument is {}", x),
    None => eprintln!("There are no arguments to the executable")
}
Source

pub fn get_executable(&self) -> Cow<'_, str>

Returns Cow<str> for the executable

§Examples
let c = commandlines::Command::new();

println!("{} v1.0.0", c.get_executable())
Source

pub fn get_index_of(&self, needle: &str) -> Option<usize>

Returns Option<usize> for index position of the argument needle in the Command.argv Vector

Returns None if needle does not match a string in the Vector

§Examples

In the following example, the command is test -o [filepath]:

let c = commandlines::Command::new();

match c.get_index_of("-o") {
    Some(x) => println!("The index position of -o is {}", x), // prints 1
    None => eprintln!("The requested argument was not found")
}
Source

pub fn is_help_request(&self) -> bool

Returns boolean for the question “Is the command a help request with a -h or --help flag?”

§Examples
let c = commandlines::Command::new();

if c.is_help_request() {
    // handle help request
}
Source

pub fn is_version_request(&self) -> bool

Returns boolean for the question “Is the command a version request with a -v or --version flag?”

§Examples
let c = commandlines::Command::new();

if c.is_version_request() {
    // handle version request
}
Source

pub fn is_usage_request(&self) -> bool

Returns boolean for the question “Is the command a usage request with a --usage flag?”

§Examples
let c = commandlines::Command::new();

if c.is_usage_request() {
    // handle usage request
}

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 Display for Command

Source§

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

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

impl PartialEq for Command

Source§

fn eq(&self, other: &Command) -> 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 StructuralPartialEq for Command

Auto Trait Implementations§

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.