【问题标题】:Define a custom parser using structopt that changes based on another flag使用基于另一个标志更改的 structopt 定义自定义解析器
【发布时间】:2019-06-24 01:03:29
【问题描述】:

我使用 structopt 来解析我的 rust 应用程序的命令行参数。有问题的标志如下:query(位置)和case_sensitive(可选)。

#[derive(StructOpt, Debug)]
pub struct Config {
    /// Query to search for.
    #[structopt(parse(try_from_str = "parse_regex"))]
    query: Regex,

    /// Specify whether or not the query is case sensitive.
    #[structopt(long)]
    case_sensitive: bool,
}

我最终想做的是写parse_regex,它从查询字符串参数构建一个正则表达式。

fn parse_regex(src: &str) -> Result<Regex, Error> {
    let case_sensitive = true; // !!! problem here: how to grab the value of the `case_sensitive` flag?
    RegexBuilder::new(src).case_insensitive(!case_sensitive).build()
}

我想知道的是自定义解析函数是否可以获取另一个标志的值(在本例中为 case_sensitive),以便动态解析自己的标志。

【问题讨论】:

  • 标志通常以任意顺序传递,你建议怎么做?

标签: rust structopt


【解决方案1】:

在命令行上,标志通常可以按任何顺序传递。这使得在解析器中引入这种依赖变得很困难。

因此,我的建议是引入两步处理:

  1. 收集标志,进行一些预处理。
  2. 处理交互。

在你的情况下:

#[derive(StructOpt, Debug)]
pub struct Config {
    /// Query to search for.
    #[structopt(string)]
    query: String,

    /// Specify whether or not the query is case sensitive.
    #[structopt(long)]
    case_sensitive: bool,
}

然后:

fn build_regex(config: &Config) -> Result<Regex, Error> {
    RegexBuilder::new(&config.query)
        .case_insensitive(!config.case_sensitive)
        .build()
}

【讨论】:

  • 这是一种完全有效的方法,但我想知道是否可以一次性在 Config 结构中做到这一点。
  • @jonathanGB:我非常怀疑,考虑到这会带来如此小的收益(字段之间的依赖图)的复杂性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 2022-01-23
  • 2021-10-17
  • 1970-01-01
相关资源
最近更新 更多