【问题标题】:Getting relative order of different command line options using clap & structopt使用 clap 和 structopt 获取不同命令行选项的相对顺序
【发布时间】:2021-04-27 21:23:22
【问题描述】:

问题

我有一个带有不同选项的命令,这些选项的相对顺序对于命令的语义很重要。例如,在command --config A --some-option --config-file B --random-option --config C --another-option --more-options --config-file D 中,A, B, C, D 的相对顺序很重要,因为它会影响命令的含义。

如果我只定义选项如下:

#[derive(Debug, StructOpt)]
pub struct Command {
    #[structopt(long = "config")]
    configs: Vec<String>,

    #[structopt(long = "config-file")]
    config_files: Vec<String>,
}

然后我会得到两个向量,configs = [A, C]config_files = [B, D],但是 configsconfig_files 中元素之间的相对顺序已经丢失。

想法

自定义解析函数

这个想法是提供一个自定义解析函数,并在解析每个选项时使用计数器记录索引。不幸的是,解析函数没有按照命令定义的原始顺序调用。

fn get_next_atomic_int() -> usize {
    static ATOMIC_COUNTER: Lazy<AtomicUsize> = Lazy::new(|| AtomicUsize::new(0));
    ATOMIC_COUNTER.fetch_add(1, Ordering::Relaxed)
}

fn parse_passthrough_string_ordered(arg: &str) -> (String, usize) {
    (arg.to_owned(), get_next_atomic_int())
}

#[derive(Debug, StructOpt)]
#[structopt(name = "command"]
pub struct Command {
    #[structopt(long = "config-file", parse(from_str = parse_passthrough_string_ordered))]
    config_files: Vec<(String, usize)>,
    
    #[structopt(short = "c", long = "config", parse(from_str = parse_passthrough_string_ordered))]
    configs: Vec<(String, usize)>,
}

别名

我可以为该选项添加别名,如下所示:

#[derive(Debug, StructOpt)]
pub struct Command {
    #[structopt(long = "config", visible_alias = "config-file")]
    configs: Vec<String>,
}

这种方法有两个问题:

  • 我需要一种方法来区分选项是通过--config 还是--config-file 传递的(仅通过检查值并不总是能够弄清楚值是如何传递的)。
  • 我无法为可见别名提供简短选项。

同一个向量,多个选项

另一个想法是附加多个structopt 指令,以便两个选项使用相同的底层向量。不幸的是,它不起作用 - structopt 只使用最后一个指令。比如:

#[derive(Debug)]
enum Config {
    File(String),
    Literal(String),
}

fn parse_config_literal(arg: &str) -> Config {
    Config::Literal(arg.to_owned())
}

fn parse_config_file(arg: &str) -> Config {
    Config::File(arg.to_owned())
}

#[derive(Debug, StructOpt)]
#[structopt(name = "example")]
struct Opt {
    #[structopt(long = "--config-file", parse(from_str = parse_config_file))]
    #[structopt(short = "-c", long = "--config", parse(from_str = parse_config_literal))]
    options: Vec<Config>,
}

恢复订单

我可以尝试通过搜索解析值来恢复原始顺序。但这意味着我将不得不复制相当多的解析逻辑(例如,需要支持传递--config=X--config X,需要处理X 作为另一个选项的输入,等等)。

我宁愿有办法可靠地获取原件,而不是丢失订单并尝试以一种可能很脆弱的方式恢复它。

【问题讨论】:

  • 是否每个--config 选项都需要后跟--config-file?如果是这样,您能否定义--config 需要两个参数,并跳过--config-file 部分?
  • @JohnBayko:不,这只是一个例子。对于出现多少这样的选项没有限制(例如,只有--config,只有--config-file,两者都有,甚至与其他选项混合)。例如,--config X --some-other-option --config Y --another --verbose --config-file Z --debug --config M

标签: rust command-line-interface clap structopt


【解决方案1】:

正如@TeXitoi 所述,我错过了为我们提供所需信息的ArgMatches::indices_of() 函数。

use structopt::StructOpt;

#[derive(Debug)]
enum Config {
    File(String),
    Literal(String),
}

fn parse_config_literal(arg: &str) -> Config {
    Config::Literal(arg.to_owned())
}

fn parse_config_file(arg: &str) -> Config {
    Config::File(arg.to_owned())
}

#[derive(Debug, StructOpt)]
#[structopt(name = "example")]
struct Opt {
    #[structopt(short = "c", long = "config", parse(from_str = parse_config_literal))]
    configs: Vec<Config>,

    #[structopt(long = "config-file", parse(from_str = parse_config_file))]
    config_files: Vec<Config>,
}

fn with_indices<'a, I: IntoIterator + 'a>(
    collection: I,
    name: &str,
    matches: &'a structopt::clap::ArgMatches,
) -> impl Iterator<Item = (usize, I::Item)> + 'a {
    matches
        .indices_of(name)
        .into_iter()
        .flatten()
        .zip(collection)
}

fn main() {
    let args = vec!["example", "--config", "A", "--config-file", "B", "--config", "C", "--config-file", "D"];
    
    let clap = Opt::clap();
    let matches = clap.get_matches_from(args);
    let opt = Opt::from_clap(&matches);

    println!("configs:");
    for (i, c) in with_indices(&opt.configs, "configs", &matches) {
        println!("{}: {:#?}", i, c);
    }

    println!("\nconfig-files:");
    for (i, c) in with_indices(&opt.config_files, "config-files", &matches) {
        println!("{}: {:#?}", i, c);
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 2014-12-04
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    相关资源
    最近更新 更多