Struct Docopt

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

The main Docopt type, which is constructed with a Docopt usage string.

This can be used to match command line arguments to produce a ArgvMap.

Implementations§

Source§

impl Docopt

Source

pub fn new<S>(usage: S) -> Result<Docopt, Error>
where S: Deref<Target = str>,

Parse the Docopt usage string given.

The Docopt value returned may be used immediately to parse command line arguments with a default configuration.

If there was a problem parsing the usage string, a Usage error is returned.

Examples found in repository?
examples/cp.rs (line 22)
21fn main() {
22    let args: Args = Docopt::new(USAGE)
23        .and_then(|d| d.deserialize())
24        .unwrap_or_else(|e| e.exit());
25    println!("{:?}", args);
26}
More examples
Hide additional examples
examples/optional_command.rs (line 68)
67fn main() {
68    let args: Args = Docopt::new(USAGE)
69        .and_then(|d| d.deserialize())
70        .unwrap_or_else(|e| e.exit());
71    println!("{:?}", args);
72}
examples/verbose_multiple.rs (line 30)
29fn main() {
30    let args: Args = Docopt::new(USAGE)
31        .and_then(|d| d.deserialize())
32        .unwrap_or_else(|e| e.exit());
33    println!("{:?}", args);
34}
examples/cargo.rs (line 52)
51fn main() {
52    let args: Args = Docopt::new(USAGE)
53        .and_then(|d| d.options_first(true).deserialize())
54        .unwrap_or_else(|e| e.exit());
55    println!("{:?}", args);
56}
examples/decode.rs (line 35)
34fn main() {
35    let args: Args = Docopt::new(USAGE)
36        .and_then(|d| d.deserialize())
37        .unwrap_or_else(|e| e.exit());
38    println!("{:?}", args);
39
40    println!("\nSome values:");
41    println!("  Speed: {}", args.flag_speed);
42    println!("  Drifting? {}", args.flag_drifting);
43    println!("  Names: {:?}", args.arg_name);
44    println!("  Command 'ship' invoked? {:?}", args.cmd_ship);
45}
examples/hashmap.rs (line 24)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}
Source

pub fn deserialize<'a, 'de: 'a, D>(&'a self) -> Result<D, Error>
where D: Deserialize<'de>,

Parse and deserialize the given argv.

This is a convenience method for parse().and_then(|vals| vals.deserialize()).

For details on how decoding works, please see the documentation for ArgvMap.

Examples found in repository?
examples/cp.rs (line 23)
21fn main() {
22    let args: Args = Docopt::new(USAGE)
23        .and_then(|d| d.deserialize())
24        .unwrap_or_else(|e| e.exit());
25    println!("{:?}", args);
26}
More examples
Hide additional examples
examples/optional_command.rs (line 69)
67fn main() {
68    let args: Args = Docopt::new(USAGE)
69        .and_then(|d| d.deserialize())
70        .unwrap_or_else(|e| e.exit());
71    println!("{:?}", args);
72}
examples/verbose_multiple.rs (line 31)
29fn main() {
30    let args: Args = Docopt::new(USAGE)
31        .and_then(|d| d.deserialize())
32        .unwrap_or_else(|e| e.exit());
33    println!("{:?}", args);
34}
examples/cargo.rs (line 53)
51fn main() {
52    let args: Args = Docopt::new(USAGE)
53        .and_then(|d| d.options_first(true).deserialize())
54        .unwrap_or_else(|e| e.exit());
55    println!("{:?}", args);
56}
examples/decode.rs (line 36)
34fn main() {
35    let args: Args = Docopt::new(USAGE)
36        .and_then(|d| d.deserialize())
37        .unwrap_or_else(|e| e.exit());
38    println!("{:?}", args);
39
40    println!("\nSome values:");
41    println!("  Speed: {}", args.flag_speed);
42    println!("  Drifting? {}", args.flag_drifting);
43    println!("  Names: {:?}", args.arg_name);
44    println!("  Command 'ship' invoked? {:?}", args.cmd_ship);
45}
Source

pub fn parse(&self) -> Result<ArgvMap, Error>

Parse command line arguments and try to match them against a usage pattern specified in the Docopt string.

If there is a match, then an ArgvMap is returned, which maps flags, commands and arguments to values.

If parsing the command line arguments fails, then an Argv error is returned. If parsing succeeds but there is no match, then a NoMatch error is returned. Both of these errors are always returned inside a WithProgramUsage error.

If special handling of help or version is enabled (the former is enabled by default), then Help or Version errors are returned if --help or --version is present.

Examples found in repository?
examples/hashmap.rs (line 25)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}
Source

pub fn argv<I, S>(self, argv: I) -> Docopt
where I: IntoIterator<Item = S>, S: AsRef<str>,

Set the argv to be used for Docopt parsing.

By default, when no argv is set, and it is automatically taken from std::env::args().

The argv given must be the full set of argv passed to the program. e.g., ["cp", "src", "dest"] is right while ["src", "dest"] is wrong.

Source

pub fn options_first(self, yes: bool) -> Docopt

Enables the “options first” Docopt behavior.

The options first behavior means that all flags must appear before position arguments. That is, after the first position argument is seen, all proceeding arguments are interpreted as positional arguments unconditionally.

Examples found in repository?
examples/cargo.rs (line 53)
51fn main() {
52    let args: Args = Docopt::new(USAGE)
53        .and_then(|d| d.options_first(true).deserialize())
54        .unwrap_or_else(|e| e.exit());
55    println!("{:?}", args);
56}
Source

pub fn help(self, yes: bool) -> Docopt

Enables automatic handling of --help.

When this is enabled and --help appears anywhere in the arguments, then a Help error will be returned. You may then use the exit method on the error value to conveniently quit the program (which will print the full usage string to stdout).

Note that for this to work, --help must be a valid pattern.

When disabled, there is no special handling of --help.

Source

pub fn version(self, version: Option<String>) -> Docopt

Enables automatic handling of --version.

When this is enabled and --version appears anywhere in the arguments, then a Version(s) error will be returned, where s is the string given here. You may then use the exit method on the error value to convenient quit the program (which will print the version to stdout).

When disabled (a None value), there is no special handling of --version.

Examples found in repository?
examples/hashmap.rs (line 25)
22fn main() {
23    let version = "1.2.3".to_owned();
24    let args = Docopt::new(USAGE)
25                      .and_then(|dopt| dopt.version(Some(version)).parse())
26                      .unwrap_or_else(|e| e.exit());
27    println!("{:?}", args);
28
29    // You can conveniently access values with `get_{bool,count,str,vec}`
30    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
31    // a switch), then a sensible default value is returned.
32    println!("\nSome values:");
33    println!("  Speed: {}", args.get_str("--speed"));
34    println!("  Drifting? {}", args.get_bool("--drifting"));
35    println!("  Names: {:?}", args.get_vec("<name>"));
36    println!("  Command 'ship' invoked? {:?}", args.get_bool("ship"));
37}

Trait Implementations§

Source§

impl Clone for Docopt

Source§

fn clone(&self) -> Docopt

Returns a duplicate 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 Docopt

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Docopt

§

impl RefUnwindSafe for Docopt

§

impl Send for Docopt

§

impl Sync for Docopt

§

impl Unpin for Docopt

§

impl UnwindSafe for Docopt

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