I am trying to have a subcommand launched if there is no argument that has been supplied by the user and I could not find any way to do this.
If there is no subcommand supplied the help will show up when I want some action instead to be passed.
While it's possible to mark the subcommand as optional and use pattern matching to use None
as the default command, I didn't like that it pushes that responsibility outside of the Cli.
A solution I've found was to keep the command
field private, and use a public method on Cli
to return it (or a default value). That way the implementation can all live inside the cli:
#[derive(Subcommand, Clone, Debug)]
pub enum Command {
Compile,
Format
}
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
command: Option<Command>,
}
impl Cli {
pub fn command(&self) -> Command {
self.command.clone().unwrap_or(Command::Compile)
}
}
Based on the official clap documentation.
Modified by wrapping the Subcommand in
Option
, which makes it optional: