Reputation: 219
I want to create a CLI application using the clap library. The problem I have is that I want to use my application like this :
./my_app file.txt read2.txt -d
The objective is that I can recover in my program in the form of Vec
with file.txt read2.txt
values.
my code :
use clap::{App, load_yaml};
#[derive(Debug)]
enum EFlag {
Debug,
None,
}
#[derive(Debug)]
pub struct Flag {
debug: EFlag,
}
impl Flag {
pub fn new() -> Flag {
Flag {
debug: EFlag::None,
}
}
pub fn fill_flag(&mut self) {
let yaml = load_yaml!("cli.yaml");
let matches = App::from(yaml).get_matches();
match matches.is_present("debug") {
true => self.debug = EFlag::Debug,
_ => self.debug = EFlag::None,
}
// HERE I WANT TO RECEIVE file.txt file2.txt
}
}
fn main() {
let mut flag = Flag::new();
flag.fill_flag();
}
I use the beta version of clap to create a yaml file to manage the flags.
the yaml file :
name: bs-script
version: "1.0.0"
author: Clement B. <[email protected]>
about: Write perform, secure and easy script with an Rust script interpretor
args:
- debug:
short: d
long: debug
about: display debug information
Upvotes: 3
Views: 1204
Reputation: 26207
To have an argument accept zero-to-many values, you just need to specify multiple: true
.
- files:
multiple: true
Then to obtain the files you'd use values_of()
along with a collect::<Vec<&str>>()
:
if let Some(files) = matches.values_of("files") {
let files = files.collect::<Vec<_>>();
println!("{:?}", files);
}
// Prints nothing for `cargo run -- -d`
// Prints `["file.txt"]` for `cargo run -- file.txt -d`
// Prints `["file.txt", "read2.txt"]` for `cargo run -- file.txt read2.txt -d`
Here's the complete cli.yaml
:
name: bs-script
version: "1.0.0"
author: Clement B. <[email protected]>
about: Write perform, secure and easy script with an Rust script interpretor
args:
- files:
multiple: true
about: Files
- debug:
short: d
long: debug
about: display debug information
Upvotes: 1