2

I use structopt to parse the command-line arguments to my rust application. The flags in question are the following: query (positional), and case_sensitive (optional).

#[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,
}

What I ultimately want to do is to write parse_regex, which builds a regex from the query string argument.

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

What I'm wondering is whether or not it is possible for a custom parsing function to grab the value of another flag (in this case case_sensitive), in order to dynamically parse its own flag.

jonathanGB
  • 1,500
  • 2
  • 16
  • 28

1 Answers1

0

On the command line, flags can normally be passed in any order. This makes it difficult to introduce this kind of dependency in the parser.

My recommendation, therefore, will be to introduce a 2-steps processing:

  1. Gather the flags, with some pre-processing.
  2. Handle interactions.

In your case:

#[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,
}

And then later:

fn build_regex(config: &Config) -> Result<Regex, Error> {
    RegexBuilder::new(&config.query)
        .case_insensitive(!config.case_sensitive)
        .build()
}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • That's a totally valid way, but I was wondering if it was possible to do that inside of the `Config` struct in one go. – jonathanGB Jun 24 '19 at 16:32
  • 1
    @jonathanGB: I very much doubt so given the amount of complexity this would introduce (a dependency graphs between fields) for such a minor gain. – Matthieu M. Jun 24 '19 at 17:05