Search code examples
rustclap

I can't seem to get my clap parser to take in a vector of string AND use flags


I've been trying to write my own GNU utils like mkdir, cd, ls, Etc. but I'm having trouble with Clap. I want to take in a vector of strings to use as paths for my mkdir function, which worked fine, but when I started trying to add flags to the program it kept saying that the paths I supplied were invalid arguments.

Here is the error I'm getting back

r-utils git:(main) ✗ cargo run --bin mkdir -v test
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/mkdir test`
error: Found argument 'test' which wasn't expected, or isn't valid in this context

USAGE:
    mkdir [OPTIONS] [--] <directories>...

let matches = Command::new("mkdir")
        .version("0.1.0")
        .author("Sarah Petkovic")
        .about("make directories")
        .arg(Arg::new("verbose")
            .short('v')
            .long("verbose")
            .required(false)
            .takes_value(false)
            .help("print a message for each created directory"))
        .arg(Arg::new("directories")
            .required(true)
            .takes_value(true)
            .help("path of directory(ies) to create")
            .multiple_values(true)
            .last(true))
        .get_matches();

Solution

  • You need to use -- to separate the arguments going to your binary from the arguments to cargo run:

    cargo run --bin mkdir -- -v test