docopt.rs icon indicating copy to clipboard operation
docopt.rs copied to clipboard

argument name with `_` underscore is misaligned to `-` hyphen

Open rbuckland opened this issue 8 years ago • 1 comments

When an argument has an _ in the docopt, deserialising it to the Args struct fails as it is looking for an argument with an _

Example error

18:10 $ cargo run -- /
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/bar /`
Could not find argument '<foo-path>' (from struct field 'arg_foo_path').
Note that each struct field must have the right key prefix, which must
be one of `cmd_`, `flag_` or `arg_`.

Code sample causing error

#[macro_use]
extern crate serde_derive;
extern crate docopt;

use docopt::Docopt;

const USAGE: &'static str = "
JSON XPather

Usage:
  bar <foo_path>

";

#[derive(Debug, Deserialize)]
struct Args {
    arg_foo_path: String,
}


fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.deserialize())
                            .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}

rbuckland avatar Aug 29 '17 08:08 rbuckland

Here is the cause - https://github.com/docopt/docopt.rs/blob/62cf32bd22f96941cec998adda5550ac475d5d5e/src/dopt.rs#L491 and the workaround is to "change" docopt arguments (variables) to be - hyphened versions

eg:

Usage:
  bar <foo-path>

instead of

Usage:
  bar <foo_path>
#[macro_use]
extern crate serde_derive;
extern crate docopt;

use docopt::Docopt;

const USAGE: &'static str = "
JSON XPather

Usage:
  bar <foo-path>

";

#[derive(Debug, Deserialize)]
struct Args {
    arg_foo_path: String,
}


fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.deserialize())
                            .unwrap_or_else(|e| e.exit());
    println!("{:?}", args);
}

rbuckland avatar Aug 29 '17 08:08 rbuckland