r/rust•
shadow31

Need some help with docopt in Cargo

I'll preface this by saying that I'm a newbie to Rust and so this is probably a simple issue. I'm trying to change the cargo new command to use a --vcs (git|hg) flag instead of --git and --hg. Here's the code I've added to src/bin/new.rs:

#[deriving(Show, PartialEq)]
enum VersionControl { Git, Hg, NoVcs }

impl<E, D: Decoder<E>> Decodable<D, E> for VersionControl {
    fn decode(d: &mut D) -> Result<VersionControl, E> {
        println!("hit");
        let s = d.read_str();
        println!("s: {}", s.is_ok());
        Ok(match try!(s).as_slice() {
            //"git" => VersionControl::Git,
            n => {
                let err = format!("Could not decode '{}' as version control.", n);
                println!("Error: {}", n);
                return Err(d.error(err.as_slice()));
            }
        })
    }
}

#[deriving(RustcDecodable)]
struct Options {
    flag_verbose: bool,
    flag_bin: bool,
    flag_travis: bool,
    arg_path: String,
    arg_vcs: VersionControl,
}

pub const USAGE: &'static str = "
Create a new cargo package at <path>

Usage:
    cargo new --vcs <vcs> [options] <path>
    cargo new -h | --help

Options:
    -h, --help          Print this message
    --vcs <vcs>         Initialize a new repository for the given version
                        control system (git or hg) or do not initialize any version 
                        control at all overriding a global configuration. 
    --travis            Create a .travis.yml file
    --bin               Use a binary instead of a library template
    -v, --verbose       Use verbose output
";

I can't seem to get docopt to parse the VersionControl enum correctly. Running cargo run -- new --vcs git test results in:

hit
s: false
failed to decode
An unknown error occurred

I can't figure out why the call to d.read_str() isn't working. Based on this article it seems like it should be working.

Any help would be greatly appreciated! Thanks

Posted Jan 4, 2015, 8:39 PM UTC

23
burntsushirust•

The main problem is that you're using arg_vcs when you should be using flag_vcs in your struct. The way that docopt arguments map to struct field names is documented in the README:

-g       => flag_g
--group  => flag_group
FILE     => arg_FILE
<file>   => arg_file
build    => cmd_build

Here is code that compiles and runs on rustc 0.13.0-nightly (c6c786671 2015-01-04 00:50:59 +0000): https://gist.github.com/anonymous/b009afcb28c42f732a4b (with a couple of tweaks to make NoVcs work right).

2
burntsushirust•

Also, OP, when I ran your code, I got this error message:

Could not find argument '<vcs>' (from struct field 'arg_vcs').

Which is what tipped me off (because vcs is a flag, not an argument).

2
shadow31OP•

Thank you! I though the flag_ fields could only be bools which is why I used arg_vcs instead.

1