Skip to content

Commit

Permalink
Merge pull request #5613 from epage/flatten
Browse files Browse the repository at this point in the history
fix(derive): Improve flattening-skipped-group assert
  • Loading branch information
epage authored Jul 31, 2024
2 parents e1bdfcc + 13dfdb3 commit 6671d93
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
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
19 changes: 19 additions & 0 deletions tests/derive/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,22 @@ fn docstrings_ordering_with_multiple_clap_partial() {

assert!(short_help.contains("This is the docstring for Flattened"));
}

#[test]
#[should_panic = "cannot `#[flatten]` an `Option<Args>` with `#[group(skip)]"]
fn flatten_skipped_group() {
#[derive(clap::Parser, Debug)]
struct Cli {
#[clap(flatten)]
args: Option<Args>,
}

#[derive(clap::Args, Debug)]
#[group(skip)]
struct Args {
#[clap(short)]
param: bool,
}

Cli::try_parse_from(["test"]).unwrap();
}

0 comments on commit 6671d93

Please sign in to comment.