Skip to main content

Command

Derive Macro Command 

Source
#[derive(Command)]
{
    // Attributes available to this derive:
    #[command]
    #[option]
    #[argument]
    #[pass_context]
    #[pass_obj]
    #[version_option]
    #[help_option]
    #[confirmation_option]
    #[password_option]
}
Expand description

Derive macro for creating CLI commands from structs.

§Container Attributes

  • #[command(name = "...")] - Set the command name (defaults to struct name in kebab-case)
  • #[command(help = "...")] - Set the help text (defaults to doc comment)
  • #[command(run)] - Wire Self::run(&self|self, &Context) -> Result<()> as callback
  • #[command(hidden)] - Hide the command from help
  • #[command(no_args_is_help)] - Show help when no arguments provided

§Field Attributes

§Options

  • #[option(short, long)] - Create option with short (-n) and long (–name) flags
  • #[option(short = 'n')] - Specify custom short flag
  • #[option(long = "name")] - Specify custom long flag name
  • #[option(help = "...")] - Set help text
  • #[option(default = value)] - Set default value
  • #[option(required)] - Mark as required
  • #[option(count)] - Count occurrences (-v -v -v = 3)
  • #[option(flag)] - Boolean flag (no value)
  • #[option(nargs = -1)] - Variadic option values
  • #[option(type = click::PathType::new())] - Explicit converter expression
  • #[option(validate = my_validator)] - Declarative validation (fn(&T) -> Result<(), String>)
  • #[option(envvar = "VAR")] - Read from environment variable
  • #[option(dest = "name")] - Override destination parameter name
  • #[option(shell_complete = my_completer)] - Custom value completion callback

§Arguments

  • #[argument] - Positional argument
  • #[argument(help = "...")] - Set help text
  • #[argument(required = false)] - Optional argument
  • #[argument(multiple)] - Accept multiple values
  • #[argument(nargs = -1)] - Variadic argument values
  • #[argument(type = click::FileType::new())] - Explicit converter expression
  • #[argument(validate = my_validator)] - Declarative validation (fn(&T) -> Result<(), String>)
  • #[argument(shell_complete = my_completer)] - Custom completion callback

§Example

#[derive(Command)]
#[command(name = "greet")]
struct Greet {
    #[option(short, long)]
    name: String,

    #[option(short, long, default = 1)]
    count: i32,

    #[argument]
    target: String,
}