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
The main problem is that you're using
arg_vcswhen you should be usingflag_vcsin your struct. The way that docopt arguments map to struct field names is documented in theREADME: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 makeNoVcswork right).Also, OP, when I ran your code, I got this error message:
Which is what tipped me off (because
vcsis a flag, not an argument).Thank you! I though the
flag_fields could only bebools which is why I usedarg_vcsinstead.