Created
January 30, 2024 12:39
-
-
Save developedby/00805328f56d0498d174405a16a3e0e3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use clap::{CommandFactory, FromArgMatches, Id}; | |
#[derive(clap::Parser, Debug)] | |
#[command()] | |
struct Args { | |
#[command(flatten)] | |
opts: Opts, | |
} | |
#[derive(clap::Args, Debug)] | |
#[group(multiple = true)] | |
struct Opts { | |
#[arg(short = 'a', action = clap::ArgAction::Append)] | |
pub a: Vec<String>, | |
#[arg(action = clap::ArgAction::Append)] | |
pub b: Vec<String>, | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let matches = Args::command().get_matches(); | |
// This returns the actual struct with the values | |
let args = Args::from_arg_matches(&matches)?; | |
// This returns the order of given args between multiple options | |
let opt_order: Vec<_> = matches | |
.get_many::<Id>("Opts") | |
.unwrap().map(|x| x.to_string()).collect(); | |
println!("{:?}", ordered_opts(args.opts, opt_order)); | |
Ok(()) | |
} | |
fn ordered_opts(opts: Opts, id_order: Vec<String>) -> Vec<(String, String)> { | |
let mut ordered_opts = vec![]; | |
let mut a = opts.a.into_iter(); | |
let mut b = opts.b.into_iter(); | |
for id in id_order { | |
match id.as_str() { | |
"a" => ordered_opts.push((id, a.next().unwrap())), | |
"b" => ordered_opts.push((id, b.next().unwrap())), | |
_ => unreachable!(), | |
} | |
} | |
ordered_opts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment