Rustのclapで必須なサブコマンドのあるコマンドを作るときはarg_required_else_help(false)を書かないと引数なしで実行したときにエラーじゃなくてヘルプが表示されるの想定外

use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(version)]
struct Opt {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Add file.
    Add(Add),

    /// Remove file.
    Remove(Remove),
}

#[derive(Args, Debug)]
pub struct Add {
    /// File to add.
    file: Option<PathBuf>,
}

#[derive(Args, Debug)]
pub struct Remove {
    /// File to remove.
    file: Option<PathBuf>,
}

fn main() {
    let opt = Opt::parse();
    println!("{opt:?}");
}
@@ -3,7 +3,7 @@
 use clap::{Args, Parser, Subcommand};
 
 #[derive(Debug, Parser)]
-#[command(version)]
+#[command(version, arg_required_else_help(false))]
 struct Opt {
     #[command(subcommand)]
     command: Command,

0

If you have a fediverse account, you can quote this note from your own instance. Search https://misskey.io/notes/a7ohqhvx8jpb08wi on your instance and quote it. (Note that quoting is not supported in Mastodon.)

修正前:

$ demo
Usage: demo <COMMAND>

Commands:
  add     Add file
  remove  Remove file
  help    Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

修正後:
$ demo
error: 'demo' requires a subcommand but one was not provided
  [subcommands: add, remove, help]

Usage: demo <COMMAND>

For more information, try '--help'.

RE:
https://misskey.io/notes/a7ohqhvx8jpb08wi

0