Skip to main content

ParsedCommand

Struct ParsedCommand 

Source
pub struct ParsedCommand<'a> {
    pub command: &'a Command,
    pub args: HashMap<String, String>,
    pub flags: HashMap<String, String>,
}
Expand description

The result of successfully parsing an invocation against a Command.

ParsedCommand borrows the matched Command from the registry (lifetime 'a) and owns the resolved argument and flag value maps. Keys in both maps are the canonical names of the argument/flag definitions.

§Examples

let cmd = Command::builder("get")
    .argument(
        Argument::builder("id")
            .required()
            .build()
            .unwrap(),
    )
    .build()
    .unwrap();

let cmds = vec![cmd];
let parser = Parser::new(&cmds);
let parsed = parser.parse(&["get", "42"]).unwrap();

assert_eq!(parsed.command.canonical, "get");
assert_eq!(parsed.args["id"], "42");

Fields§

§command: &'a Command

The matched Command definition, borrowed from the registry.

§args: HashMap<String, String>

Resolved positional argument values, keyed by argument name.

§flags: HashMap<String, String>

Resolved flag values, keyed by flag name.

Boolean flags (those without takes_value) are stored as "true". Flags that were not provided but have a default value are included with that default.

Implementations§

Source§

impl<'a> ParsedCommand<'a>

Source

pub fn arg(&self, name: &str) -> Option<&str>

Return a positional argument value by name, or None if absent.

§Examples
let cmd = Command::builder("get")
    .argument(Argument::builder("id").required().build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["get", "42"]).unwrap();
assert_eq!(parsed.arg("id"), Some("42"));
assert_eq!(parsed.arg("missing"), None);
Source

pub fn flag(&self, name: &str) -> Option<&str>

Return a flag value by name, or None if absent.

§Examples
let cmd = Command::builder("run")
    .flag(Flag::builder("output").takes_value().default_value("text").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["run", "--output=json"]).unwrap();
assert_eq!(parsed.flag("output"), Some("json"));
Source

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

Return true if a boolean flag is present and set to "true", false otherwise.

§Examples
let cmd = Command::builder("build")
    .flag(Flag::builder("release").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["build", "--release"]).unwrap();
assert!(parsed.flag_bool("release"));
assert!(!parsed.flag_bool("missing"));
Source

pub fn flag_count(&self, name: &str) -> u64

Return the occurrence count for a repeatable boolean flag (stored as a numeric string). Returns 0 if the flag was not provided.

For flags stored as "true" (non-repeatable), returns 1.

§Examples
// With a repeatable flag (see Flag::repeatable), -v -v -v → flag_count("verbose") == 3
// With a normal flag, --verbose → flag_count("verbose") == 1 (stored as "true")
let cmd = Command::builder("run")
    .flag(Flag::builder("verbose").short('v').build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["run", "-v"]).unwrap();
// Non-repeatable flag stores "true"; flag_count returns 1
assert_eq!(parsed.flag_count("verbose"), 1);
assert_eq!(parsed.flag_count("missing"), 0);
Source

pub fn flag_values(&self, name: &str) -> Vec<String>

Return all values for a repeatable value-taking flag as a Vec<String>.

  • If the flag was provided multiple times (repeatable), the stored JSON array is deserialized into a Vec.
  • If the flag was provided once (non-repeatable), returns a single-element Vec.
  • If the flag was not provided, returns an empty Vec.
§Examples
let cmd = Command::builder("run")
    .flag(Flag::builder("output").takes_value().default_value("text").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["run", "--output=json"]).unwrap();
assert_eq!(parsed.flag_values("output"), vec!["json"]);
assert!(parsed.flag_values("missing").is_empty());
Source

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

Return true if name is present in the parsed flag map.

A flag is present when it was explicitly provided on the command line or when the parser inserted a default or env-var value. To distinguish explicit from default, use ParsedCommand::flag and compare with the flag definition’s default.

§Examples
let cmd = Command::builder("run")
    .flag(Flag::builder("verbose").build().unwrap())
    .flag(Flag::builder("output").takes_value().default_value("text").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["run", "--verbose"]).unwrap();
assert!(parsed.has_flag("verbose"));
assert!(parsed.has_flag("output"));  // present via default
assert!(!parsed.has_flag("missing"));
Source

pub fn arg_as<T: FromStr>(&self, name: &str) -> Option<Result<T, T::Err>>

Parse a positional argument as type T using std::str::FromStr.

Returns:

  • None if the argument was not provided (absent from the map)
  • Some(Ok(value)) if parsing succeeded
  • Some(Err(e)) if the string was present but could not be parsed
§Examples
let cmd = Command::builder("resize")
    .argument(Argument::builder("width").required().build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["resize", "1920"]).unwrap();

let width: u32 = parsed.arg_as("width").unwrap().unwrap();
assert_eq!(width, 1920u32);

assert!(parsed.arg_as::<u32>("missing").is_none());
Source

pub fn flag_as<T: FromStr>(&self, name: &str) -> Option<Result<T, T::Err>>

Parse a flag value as type T using std::str::FromStr.

Returns:

  • None if the flag was not set (and has no default)
  • Some(Ok(value)) if parsing succeeded
  • Some(Err(e)) if the string was present but could not be parsed
§Examples
let cmd = Command::builder("serve")
    .flag(Flag::builder("port").takes_value().default_value("8080").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["serve"]).unwrap();

let port: u16 = parsed.flag_as("port").unwrap().unwrap();
assert_eq!(port, 8080u16);
Source

pub fn arg_as_or<T: FromStr>(&self, name: &str, default: T) -> T

Parse a positional argument as type T, returning a default if absent or unparseable.

§Examples
let cmd = Command::builder("run")
    .argument(Argument::builder("count").build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["run"]).unwrap();

assert_eq!(parsed.arg_as_or("count", 1u32), 1u32);
Source

pub fn flag_as_or<T: FromStr>(&self, name: &str, default: T) -> T

Parse a flag value as type T, returning a default if absent or unparseable.

§Examples
let cmd = Command::builder("serve")
    .flag(Flag::builder("workers").takes_value().build().unwrap())
    .build().unwrap();
let cmds = vec![cmd];
let parsed = Parser::new(&cmds).parse(&["serve"]).unwrap();

assert_eq!(parsed.flag_as_or("workers", 4u32), 4u32);

Trait Implementations§

Source§

impl<'a> Debug for ParsedCommand<'a>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for ParsedCommand<'a>

§

impl<'a> !RefUnwindSafe for ParsedCommand<'a>

§

impl<'a> Send for ParsedCommand<'a>

§

impl<'a> Sync for ParsedCommand<'a>

§

impl<'a> Unpin for ParsedCommand<'a>

§

impl<'a> UnsafeUnpin for ParsedCommand<'a>

§

impl<'a> !UnwindSafe for ParsedCommand<'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>,

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.