fix(derive): Re-allow expressions for id's

Fixes #5407
This commit is contained in:
Ed Page 2024-03-25 14:42:22 -05:00
parent 8eab48fa3c
commit df915fefef
2 changed files with 32 additions and 3 deletions

View file

@ -717,9 +717,21 @@ fn gen_parsers(
},
Ty::Other => {
quote_spanned! { ty.span()=>
#arg_matches.#get_one(#id)
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, concat!("The following required argument was not provided: ", #id)))?
// Prefer `concat` where possible for reduced code size but fallback to `format!` to
// allow non-literal `id`s
match id {
Name::Assigned(_) => {
quote_spanned! { ty.span()=>
#arg_matches.#get_one(#id)
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, format!("The following required argument was not provided: {}", #id)))?
}
}
Name::Derived(_) => {
quote_spanned! { ty.span()=>
#arg_matches.#get_one(#id)
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, concat!("The following required argument was not provided: ", #id)))?
}
}
}
}
};

View file

@ -156,3 +156,20 @@ fn test_parse_hex_function_path() {
err
);
}
#[test]
#[cfg(feature = "error-context")]
fn test_const_name() {
#[derive(Parser, PartialEq, Debug)]
struct Opt {
#[arg(id = NAME, short, long)]
number: u64,
}
const NAME: &str = "fun";
assert_eq!(
Opt { number: 5 },
Opt::try_parse_from(["test", "-f", "5"]).unwrap()
);
}