How to define global options but only for a subset of subcommands? #5578
-
Hi 👋, We've the following structure on defining subcommands and global options using the derive API: #[derive(Debug, Parser)]
pub struct Args {
#[command(subcommand)]
pub(crate) command: Command,
#[clap(flatten)]
pub(crate) global_options: GlobalConfigArgs,
}
#[derive(Debug, Default, Clone, clap::Args)]
pub struct GlobalConfigArgs {
// ...
}
#[derive(Debug, clap::Subcommand)]
pub enum Command {
Foo(FooArgs),
Bar(BarArgs),
Baz(BazArgs),
} My query is how to define the global options only for certain subset of commands? I'm aware that I could include the global options manually for the commands that requires it like: pub enum Command {
Foo {
#[clap(flatten)]
args: FooArgs,
#[clap(flatten)]
global: GlobalConfigArgs,
},
// ...
} But, I was wondering if there was any other API / structure that can be used. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
At this time, it is unsupported. Personally, I find this case odd as the argument is no longer truly "global". I'd recommend considering whether the argument is global because it is universally applicable or global for code reuse. The fact that exceptions are being made makes it seem like the latter and it seems like the best course would be to flatten in each command. That said, you can workaround this on your side by #[derive(Debug, Parser)]
pub struct Args {
#[command(subcommand)]
pub(crate) command: Command,
#[clap(flatten)]
pub(crate) global_options: Option<GlobalConfigArgs>,
} You can do We do want to play with our validation being more extensible so we can more organically develop more forms of validation. See #2763 |
Beta Was this translation helpful? Give feedback.
At this time, it is unsupported. Personally, I find this case odd as the argument is no longer truly "global". I'd recommend considering whether the argument is global because it is universally applicable or global for code reuse. The fact that exceptions are being made makes it seem like the latter and it seems like the best course would be to flatten in each command.
That said, you can workaround this on your side by
You can do
global_option.is_some() && !command.supports_globals()
and then error.We do wan…