繁体   English   中英

如何使用未指定的 arguments 与拍手

[英]How to use unspecified arguments with clap

我想使用 clap 库创建一个 CLI 应用程序。 我遇到的问题是我想像这样使用我的应用程序:

./my_app file.txt read2.txt -d

目标是我可以在我的程序中以具有file.txt read2.txt值的Vec形式恢复。

我的代码:

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();
}

我使用 clap 的 beta 版本创建了一个 yaml 文件来管理标志。

yaml 文件:

name: bs-script
version: "1.0.0"
author: Clement B. <clement.bolin@epitech.eu>
about: Write perform, secure and easy script with an Rust script interpretor
args:
  - debug:
      short: d
      long: debug
      about: display debug information

要让参数接受零对多的值,您只需要指定multiple: true

- files:
    multiple: true

然后获取您将使用values_of()以及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`

这是完整的cli.yaml

name: bs-script
version: "1.0.0"
author: Clement B. <clement.bolin@epitech.eu>
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM