Skip to content

Commit df915fe

Browse files
committed
fix(derive): Re-allow expressions for id's
Fixes #5407
1 parent 8eab48f commit df915fe

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

clap_derive/src/derives/args.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -717,9 +717,21 @@ fn gen_parsers(
717717
},
718718

719719
Ty::Other => {
720-
quote_spanned! { ty.span()=>
721-
#arg_matches.#get_one(#id)
722-
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, concat!("The following required argument was not provided: ", #id)))?
720+
// Prefer `concat` where possible for reduced code size but fallback to `format!` to
721+
// allow non-literal `id`s
722+
match id {
723+
Name::Assigned(_) => {
724+
quote_spanned! { ty.span()=>
725+
#arg_matches.#get_one(#id)
726+
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, format!("The following required argument was not provided: {}", #id)))?
727+
}
728+
}
729+
Name::Derived(_) => {
730+
quote_spanned! { ty.span()=>
731+
#arg_matches.#get_one(#id)
732+
.ok_or_else(|| clap::Error::raw(clap::error::ErrorKind::MissingRequiredArgument, concat!("The following required argument was not provided: ", #id)))?
733+
}
734+
}
723735
}
724736
}
725737
};

tests/derive/non_literal_attributes.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,20 @@ fn test_parse_hex_function_path() {
156156
err
157157
);
158158
}
159+
160+
#[test]
161+
#[cfg(feature = "error-context")]
162+
fn test_const_name() {
163+
#[derive(Parser, PartialEq, Debug)]
164+
struct Opt {
165+
#[arg(id = NAME, short, long)]
166+
number: u64,
167+
}
168+
169+
const NAME: &str = "fun";
170+
171+
assert_eq!(
172+
Opt { number: 5 },
173+
Opt::try_parse_from(["test", "-f", "5"]).unwrap()
174+
);
175+
}

0 commit comments

Comments
 (0)