Reputation: 1540
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.
Upvotes: 2
Views: 973
Reputation: 300099
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:
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()
}
Upvotes: 0