Skip to content

Commit

Permalink
fix(derive): Improve flattening-skipped-group assert
Browse files Browse the repository at this point in the history
- Improves the error message
- Happens on initialization, rather than parse, making it so it will
  always show up and not just when certain parts of the CLI are
  exercised

Fixes #5609
  • Loading branch information
epage committed Jul 31, 2024
1 parent 4f875ff commit 13dfdb3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
11 changes: 10 additions & 1 deletion clap_derive/src/derives/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,15 +228,24 @@ pub(crate) fn gen_augment(

let next_help_heading = item.next_help_heading();
let next_display_order = item.next_display_order();
let flatten_group_assert = if matches!(**ty, Ty::Option) {
quote_spanned! { kind.span()=>
<#inner_type as clap::Args>::group_id().expect("cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]");
}
} else {
quote! {}
};
if override_required {
Some(quote_spanned! { kind.span()=>
#flatten_group_assert
let #app_var = #app_var
#next_help_heading
#next_display_order;
let #app_var = <#inner_type as clap::Args>::augment_args_for_update(#app_var);
})
} else {
Some(quote_spanned! { kind.span()=>
#flatten_group_assert
let #app_var = #app_var
#next_help_heading
#next_display_order;
Expand Down Expand Up @@ -499,7 +508,7 @@ pub(crate) fn gen_constructor(fields: &[(&Field, Item)]) -> Result<TokenStream,
quote_spanned! { kind.span()=>
#field_name: {
let group_id = <#inner_type as clap::Args>::group_id()
.expect("`#[arg(flatten)]`ed field type implements `Args::group_id`");
.expect("asserted during `Arg` creation");
if #arg_matches.contains_id(group_id.as_str()) {
Some(
<#inner_type as clap::FromArgMatches>::from_arg_matches_mut(#arg_matches)?
Expand Down
2 changes: 1 addition & 1 deletion tests/derive/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ fn docstrings_ordering_with_multiple_clap_partial() {
}

#[test]
#[should_panic = "#[arg(flatten)]`ed field type implements `Args::group_id"]
#[should_panic = "cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]"]
fn flatten_skipped_group() {
#[derive(clap::Parser, Debug)]
struct Cli {
Expand Down

0 comments on commit 13dfdb3

Please sign in to comment.