-
We have this requirement: Our app has a few subcommands. Some of them share a few arguments. We would like to process these shared argument at the top level, before calling handlers for the individual commands. Is this possible? This is what I currently have: #[derive(Parser, Debug, Clone)]
struct Cli {
#[clap(subcommand)]
command: Command,
#[clap(long, default_value_t = DEFAULT_RPC_PORT)]
rpc_port: u16,
#[clap(long, default_value_t = DEFAULT_BIND_ADDR)]
bind_addr: SocketAddr,
}
#[derive(Parser, Debug, Clone)]
pub enum Command {
#[clap(flatten)]
Node(#[clap(subcommand)] NodeCommand),
#[clap(flatten)]
Rpc(#[clap(subcommand)] RpcCommand),
}
#[derive(Subcommand, Debug, Clone)]
pub enum NodeCommand {
Start,
Get
}
#[derive(Subcommand, Debug, Clone)]
pub enum RpcCommand {
Status,
Add,
// ...
} This works, however what I'd want is that the Is this possible? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
From a CLI design perspective, it seems to me like an argument that only applies to some subcommands shouldn't be "above" the subcommands but "underneath" them. Is there a reason you are putting them at the top-level? |
Beta Was this translation helpful? Give feedback.
-
For the immediate question, the answer is "there isn't a built-in way". This can be handled on the users end by
In terms of the features we support, we need to balance ease of use, build time, and binary size (which all encourage fewer features) with flexibility. We try to strike this balance by asking (1) what the CLI best practices are that we should be encouraging and (2) can exception cases be worked around. In this case, the exception case can be worked around. We are considering making clap's design more open-ended (#3476) though that will have a degree of boilerplate to it unless a pattern becomes common enough for people to provide in a library, making the workaround a better route. |
Beta Was this translation helpful? Give feedback.
-
Thank you very much for your response! I will think through the available options, and am looking forward to progress on #3476 . |
Beta Was this translation helpful? Give feedback.
For the immediate question, the answer is "there isn't a built-in way".
This can be handled on the users end by
help_heading
that is named after the subcommandOption
for the arguments, rather than setting a default, since you don't have access toArgMatches::value_source
(#3846)In terms of the features we support, we need to balance ease of use, build time, and binary size (which all encourage fewer features) with flexibility. We try to strike this balance by asking (1) what the CLI best practices are that we should be encouraging and (2) can excepti…