Args

Struct Args 

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

§Arguments

§Examples

use dia_args;

let mut args = dia_args::parse_strings(["run", "--debug", "--port=99"])?;
assert_eq!(args.take(&["--debug"])?, Some(true));
assert_eq!(args.take::<u16>(&["--port"])?.unwrap(), 99);

Implementations§

Source§

impl Args

Source

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

§Gets the command
Source

pub fn sub_args(&self) -> &[String]

§Sub arguments
Source

pub fn is_empty(&self) -> bool

§Checks if there are no arguments/options/sub arguments
Source

pub fn try_into_sub_cmd(self) -> Result<(Option<String>, Self)>

§Transforms into sub command

For example:

  • Command line:

    ~> program help version 1
  • Parsed as:

    help version 1
  • After calling this function:

    version 1
use dia_args;

const CMD_VERSION: &str = "version";

let (cmd, args) = dia_args::parse()?.try_into_sub_cmd()?;
match cmd.as_ref().map(|s| s.as_str()) {
    Some(CMD_VERSION) => if args.is_empty() {
        println!("Version: ...");
    } else {
        eprintln!("{:?} command doesn't take arguments", CMD_VERSION);
    },
    Some(other) => eprintln!("Command {:?} not supported", other),
    None => eprintln!("Missing command"),
};
Source

pub fn take<T>(&mut self, keys: &[&str]) -> Result<Option<T>>
where T: FromStr + 'static, <T as FromStr>::Err: Debug,

§Takes an option using given keys
§Examples
use dia_args;

let mut args = dia_args::parse_strings(["--type", "rs"])?;
assert_eq!(args.take::<String>(&["--type"])?.unwrap(), "rs");
assert!(args.take::<String>(&["--type"])?.is_none());
Source

pub fn take_vec<T>(&mut self, keys: &[&str]) -> Result<Option<Vec<T>>>
where T: FromStr, <T as FromStr>::Err: Debug,

§Takes an option using given keys
§Examples
use dia_args;

let mut args = dia_args::parse_strings(["-l", "c", "-l", "c++"])?;
let mut languages = args.take_vec::<String>(&["-l"])?.unwrap();
languages.sort();
assert_eq!(languages, &["c", "c++"]);
assert!(args.is_empty());
Source

pub fn take_args(&mut self) -> Result<Vec<String>>

§Takes arguments out
§Notes

This function might return an error if:

  • There is at least one option left.
  • And an argument is not owned.
§Examples
use dia_args;

let mut args = dia_args::parse_strings(["do", "this", "--debug"])?;
assert_eq!(args.take_args()?, &["do", "this"]);
Source

pub fn take_sub_args(&mut self) -> Vec<String>

§Takes sub arguments out
§Examples
use dia_args;

let mut args = dia_args::parse_strings(
    ["eat", "chicken", "--", "with", "ronnie-coleman"]
)?;
assert_eq!(args.take_sub_args(), &["with", "ronnie-coleman"]);
Source

pub fn merge_options( &mut self, other: &mut Self, filter: &[&[&str]], merge_option: MergeOption, ) -> Result<usize>

§Merges options with other
  • This function works on options, not commands/sub arguments…
  • Other’s options will be taken out, if conditions are met.
  • Result is number of items merged.
§Parameters
  • filter:

    • If you provide some sets of keys, only those (from other) are accepted.
    • If you provide an empty slice, or any of its items is empty, an error is returned.
§Examples

Your program allows the user to set options from file. Later you want to give the user new ability to set options via command line, overwriting the ones from file. Then this function can help.

use dia_args::MergeOption;

const OPTION_DEBUG: &[&str] = &["-d", "--debug"];
const OPTION_PORT: &[&str] = &["--port"];

// Here in test, we're parsing from strings.
// In real code, you might want to use dia_args::parse_file()
let mut args_from_file = dia_args::parse_strings(
    ["--debug=false", "--port=6789"]
)?;

// Command line arguments
let mut cmd_line_args = dia_args::parse_strings(
    ["-d=true", "--address", "localhost"]
)?;

// Merge
let count = cmd_line_args.merge_options(
    &mut args_from_file, &[OPTION_DEBUG, OPTION_PORT], MergeOption::IgnoreExisting,
)?;
assert_eq!(count, 1);

// Verify
assert_eq!(cmd_line_args.take(OPTION_DEBUG)?, Some(true));
assert_eq!(cmd_line_args.take::<String>(&["--address"])?.unwrap(), "localhost");
assert_eq!(cmd_line_args.take::<u16>(OPTION_PORT)?, Some(6789));

Trait Implementations§

Source§

impl Debug for Args

Source§

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

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

impl Default for Args

Source§

fn default() -> Args

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Args

§

impl RefUnwindSafe for Args

§

impl Send for Args

§

impl Sync for Args

§

impl Unpin for Args

§

impl UnwindSafe for Args

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

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.