pub struct Parser<'a> { /* private fields */ }Expand description
Parses raw argument slices against a slice of registered Commands.
Create a Parser with Parser::new, then call Parser::parse for
each invocation. The parser borrows the command slice for lifetime 'a;
the returned ParsedCommand also carries that lifetime.
§Examples
let cmds = vec![Command::builder("status").build().unwrap()];
let parser = Parser::new(&cmds);
let parsed = parser.parse(&["status"]).unwrap();
assert_eq!(parsed.command.canonical, "status");Implementations§
Source§impl<'a> Parser<'a>
impl<'a> Parser<'a>
Sourcepub fn new(commands: &'a [Command]) -> Self
pub fn new(commands: &'a [Command]) -> Self
Create a new Parser over the given command slice.
§Arguments
commands— Top-level commands to parse against. The lifetime'ais propagated to theParsedCommandreturned byParser::parse.
Sourcepub fn parse(&self, argv: &[&str]) -> Result<ParsedCommand<'a>, ParseError>
pub fn parse(&self, argv: &[&str]) -> Result<ParsedCommand<'a>, ParseError>
Parse argv (the full argument list including the command name) into a
ParsedCommand that borrows from the registered command tree.
The first element of argv must be a word token naming the top-level
command. Subsequent tokens are processed as described in the
module documentation.
§Arguments
argv— The argument slice to parse. Should not include the program name (argv[0]instd::env::args); the first element must be the command name.
§Errors
ParseError::NoCommand—argvis empty.ParseError::Resolve— the command or subcommand token could not be resolved (wrapsResolveError::UnknownorResolveError::Ambiguous).ParseError::MissingArgument— a required positional argument was absent.ParseError::UnexpectedArgument— more positional arguments were provided than the command declares.ParseError::MissingFlag— a required flag was absent.ParseError::FlagMissingValue— a value-taking flag had no following value.ParseError::UnknownFlag— an unrecognized flag was encountered.
§Examples
let cmd = Command::builder("build")
.flag(
Flag::builder("target")
.takes_value()
.default_value("debug")
.build()
.unwrap(),
)
.build()
.unwrap();
let cmds = vec![cmd];
let parser = Parser::new(&cmds);
let parsed = parser.parse(&["build", "--target=release"]).unwrap();
assert_eq!(parsed.flags["target"], "release");
// Default is applied when flag is absent
let parsed2 = parser.parse(&["build"]).unwrap();
assert_eq!(parsed2.flags["target"], "debug");Auto Trait Implementations§
impl<'a> Freeze for Parser<'a>
impl<'a> !RefUnwindSafe for Parser<'a>
impl<'a> Send for Parser<'a>
impl<'a> Sync for Parser<'a>
impl<'a> Unpin for Parser<'a>
impl<'a> UnsafeUnpin for Parser<'a>
impl<'a> !UnwindSafe for Parser<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more