Skip to content

Commit

Permalink
fix(derive): Re-allow expressions for id's
Browse files Browse the repository at this point in the history
Fixes #5407
  • Loading branch information
epage committed Mar 25, 2024
1 parent 8eab48f commit df915fe
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
18 changes: 15 additions & 3 deletions clap_derive/src/derives/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)))?
}
}
}
}
};
Expand Down
17 changes: 17 additions & 0 deletions tests/derive/non_literal_attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
);
}

0 comments on commit df915fe

Please sign in to comment.