Skip to main content

OptionParser

Struct OptionParser 

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

The main option parser.

This parser handles the low-level parsing of command-line arguments. It supports both short and long options, with various actions like store, append, and count.

§Example

use click::parser::{OptionParser, OptionAction, ParsedValue};

let mut parser = OptionParser::new();
parser.add_option(&["-n", "--name"], "name", OptionAction::Store, 1, None);
parser.add_option(&["-v", "--verbose"], "verbose", OptionAction::Count, 0, None);
parser.add_argument("file", 1);

let args = vec!["-v", "-v", "--name", "test", "input.txt"]
    .into_iter().map(String::from).collect();
let (opts, remaining, order) = parser.parse_args(args).unwrap();

assert_eq!(opts.get("verbose"), Some(&ParsedValue::Count(2)));
assert_eq!(opts.get("name"), Some(&ParsedValue::Single("test".to_string())));

Implementations§

Source§

impl OptionParser

Source

pub fn new() -> Self

Create a new option parser with default settings.

Source

pub fn allow_interspersed_args(self, allow: bool) -> Self

Set whether to allow interspersed positional arguments.

When true (default), positional args can appear between options. When false, the parser stops on the first non-option.

Source

pub fn ignore_unknown_options(self, ignore: bool) -> Self

Set whether to ignore unknown options.

When true, unknown options are passed through as positional args. When false (default), unknown options cause an error.

Source

pub fn token_normalize_func<F>(self, func: F) -> Self
where F: Fn(&str) -> String + Send + Sync + 'static,

Set a token normalization function.

This function is applied to option names for matching. Useful for case-insensitive option matching.

Source

pub fn add_option( &mut self, opts: &[&str], dest: &str, action: OptionAction, nargs: i32, const_value: Option<&str>, )

Add an option to the parser.

§Arguments
  • opts - Option strings (e.g., ["-n", "--name"])
  • dest - Destination key in the results
  • action - Action to perform when option is encountered
  • nargs - Number of arguments (1 = single, -1 = variadic, 0 = flag, -2 = optional)
  • const_value - Constant value for StoreConst/AppendConst actions
Source

pub fn add_option_ex( &mut self, opts: &[&str], dest: &str, action: OptionAction, nargs: i32, const_value: Option<&str>, flag_needs_value: bool, )

Add an option to the parser with extended options.

§Arguments
  • opts - Option strings (e.g., ["-n", "--name"])
  • dest - Destination key in the results
  • action - Action to perform when option is encountered
  • nargs - Number of arguments (1 = single, -1 = variadic, 0 = flag, -2 = optional)
  • const_value - Constant value for StoreConst/AppendConst actions
  • flag_needs_value - If true, value is optional: if next arg looks like an option, returns FlagNeedsValue instead of consuming it
Source

pub fn add_argument(&mut self, dest: &str, nargs: i32)

Add a positional argument to the parser.

§Arguments
  • dest - Destination key in the results
  • nargs - Number of values (1 = single, -1 = variadic)
Source

pub fn parse_args(&self, args: Vec<String>) -> ParseResult

Parse command-line arguments.

§Returns

A tuple of:

  • Parsed option values (dest -> value)
  • Remaining unparsed arguments
  • Order of parameters as they were seen
§Errors

Returns a ClickError if parsing fails (e.g., unknown option, missing value).

Trait Implementations§

Source§

impl Debug for OptionParser

Source§

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

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

impl Default for OptionParser

Source§

fn default() -> Self

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

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