Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking multiple values in an argument in Clap

Tags:

rust

clap

I'm using Clap and I'm trying to make it so that a subcommand can take multiple values for the argument. The interface I'm after is:

just use repo [files]

An example:

just use radar/dot-files gitaliases ryan-aliases

The repo argument here will be the string "radar/dot-files" and the files argument will be a vector of ["gitaliases", "ryan-aliases"].

Here's the code that I'm trying to use:

let matches = App::new("just")
    .version("v1.0-beta")
    .subcommand(
        SubCommand::with_name("use")
            .arg(Arg::with_name("repo").required(true))
            .arg(
                Arg::with_name("files")
                    .required(true)
                    .multiple(true)
                    .number_of_values(1),
            ),
    )
    .get_matches();

if let Some(matches) = matches.subcommand_matches("use") {
    println!("{:?}", matches.value_of("files").unwrap())
}

This outputs just the first file that I specify, rather than all the files.

How can I make it output all the different files, for an arbitrary number of arguments?

like image 464
Ryan Bigg Avatar asked Jan 02 '18 21:01

Ryan Bigg


1 Answers

durka42 from irc.mozilla.org#rust told me to use values_of instead of value_of:

let matches = App::new("just")
    .version("v1.0-beta")
    .subcommand(
        SubCommand::with_name("use")
            .arg(Arg::with_name("repo").required(true))
            .arg(Arg::with_name("files").required(true).min_values(1)),
    )
    .get_matches();

if let Some(matches) = matches.subcommand_matches("use") {
    let files: Vec<_> = matches.values_of("files").unwrap().collect();
    println!("{}", files[0]);
    println!("{}", files[1]);
}

I could probably use an iter() call to go through the files if I wanted to.

like image 199
Ryan Bigg Avatar answered Oct 15 '22 23:10

Ryan Bigg