Skip to main content

Command

Struct Command 

Source
pub struct Command {
Show 15 fields pub name: Option<String>, pub callback: Option<CommandCallback>, pub options: Vec<ClickOption>, pub arguments: Vec<Argument>, pub help: Option<String>, pub epilog: Option<String>, pub short_help: Option<String>, pub options_metavar: String, pub add_help_option: bool, pub no_args_is_help: bool, pub hidden: bool, pub deprecated: Option<String>, pub allow_extra_args: bool, pub allow_interspersed_args: bool, pub ignore_unknown_options: bool, /* private fields */
}
Expand description

A command is the basic building block of click-rs CLIs.

Commands handle argument parsing and invoke a callback with the parsed values. They can be nested within [Group]s to create subcommand hierarchies.

§Construction

Use Command::new to create a CommandBuilder for fluent construction:

use click::command::Command;

let cmd = Command::new("mycommand")
    .help("Description of the command")
    .build();

Fields§

§name: Option<String>

The name of the command.

When registered on a [Group], this becomes the subcommand name. Use Context::info_name to get the actual invocation name.

§callback: Option<CommandCallback>

The callback to execute when the command is invoked.

May be None if the command is just a container for subcommands.

§options: Vec<ClickOption>

The options for this command.

§arguments: Vec<Argument>

The arguments for this command.

§help: Option<String>

The help text for this command.

Displayed in the help output after the usage line.

§epilog: Option<String>

Text printed at the end of the help page.

§short_help: Option<String>

Short help shown in parent command listings.

If not set, derived from the first line of help.

§options_metavar: String

The metavar for options (default: “[OPTIONS]”).

§add_help_option: bool

Whether to add a –help option automatically.

§no_args_is_help: bool

Show help if no arguments are provided.

§hidden: bool

Hide this command from help output.

§deprecated: Option<String>

Mark this command as deprecated.

If Some, the command shows a deprecation warning when invoked. The string can be empty for a generic message, or contain custom text.

§allow_extra_args: bool

Whether to allow extra arguments (default: false).

§allow_interspersed_args: bool

Whether to allow interspersed arguments (default: true).

§ignore_unknown_options: bool

Whether to ignore unknown options (default: false).

Implementations§

Source§

impl Command

Source

pub fn new(name: &str) -> CommandBuilder

Create a new command builder with the given name.

§Example
use click::command::Command;

let cmd = Command::new("hello")
    .help("Say hello")
    .build();
Source

pub fn get_help_option(&self, ctx: &Context) -> Option<ClickOption>

Get the help option if enabled.

Returns None if add_help_option is false or if the help option names conflict with existing parameters.

Source

pub fn param_count(&self) -> usize

Get the total number of parameters (options + arguments).

Source

pub fn get_params(&self, _ctx: &Context) -> Vec<&dyn Parameter>

Get all parameters (options and arguments) for this command.

Returns a vector of trait objects. Options are returned first, followed by arguments, in the order they were added.

Source

pub fn make_context( &self, info_name: &str, args: Vec<String>, parent: Option<Arc<Context>>, ) -> Result<Context, ClickError>

Create a context for this command.

This sets up parsing state and applies command defaults.

§Arguments
  • info_name - The name to display in help/usage (usually the command name)
  • args - The arguments to parse
  • parent - Optional parent context for nested commands
§Example
use click::command::Command;

let cmd = Command::new("hello").build();
let ctx = cmd.make_context("hello", vec![], None).unwrap();
assert_eq!(ctx.info_name(), Some("hello"));
Source

pub fn parse_args( &self, ctx: &mut Context, args: Vec<String>, ) -> Result<(), ClickError>

Parse arguments and populate the context.

This method creates a parser, adds all parameters to it, parses the arguments, and stores the results in the context.

Source

pub fn invoke(&self, ctx: &Context) -> Result<(), ClickError>

Invoke the command callback with the context.

Returns Ok(()) if no callback is set.

Source

pub fn main(&self, args: Vec<String>) -> Result<(), ClickError>

Main entry point - make context, parse args, and invoke.

This is the primary way to run a command as a CLI application.

§Arguments
  • args - Command-line arguments (typically std::env::args().skip(1))
§Example
use click::command::Command;

let cmd = Command::new("hello")
    .callback(|_ctx| {
        println!("Hello, world!");
        Ok(())
    })
    .build();

let args: Vec<String> = std::env::args().skip(1).collect();
if let Err(e) = cmd.main(args) {
    eprintln!("{}", e.format_full());
    std::process::exit(e.exit_code());
}
Source

pub fn get_version_output_from_args(&self, args: &[String]) -> Option<String>

Check if a version option was triggered and return the version output.

This is used internally by main() and Group::main() to handle version options that trigger Exit { code: 0 }.

Source

pub fn get_usage(&self, ctx: &Context) -> String

Format the usage line.

Returns a string like: Usage: COMMAND [OPTIONS] ARGUMENT

Source

pub fn get_help(&self, ctx: &Context) -> String

Format the help text.

Returns the complete help output including usage, description, options, arguments, and epilog.

Source

pub fn get_short_help(&self) -> String

Get the short help text for command listings.

Returns short_help if set, otherwise derives from the first sentence of help.

Trait Implementations§

Source§

impl CommandLike for Command

Source§

fn name(&self) -> Option<&str>

Get the name of this command.
Source§

fn make_context( &self, info_name: &str, args: Vec<String>, parent: Option<Arc<Context>>, ) -> Result<Context, ClickError>

Create a context for executing this command. Read more
Source§

fn invoke(&self, ctx: &Context) -> Result<(), ClickError>

Invoke the command with the given context.
Source§

fn main(&self, args: Vec<String>) -> Result<(), ClickError>

Main entry point - make context, parse args, and invoke.
Source§

fn get_help(&self, ctx: &Context) -> String

Get the full help text for this command.
Source§

fn get_short_help(&self) -> String

Get the short help text for command listings.
Source§

fn is_hidden(&self) -> bool

Check if this command is hidden from help output.
Source§

fn get_usage(&self, ctx: &Context) -> String

Get the usage line for this command.
Source§

fn as_any(&self) -> &dyn Any

Convert to Any for downcasting.
Source§

impl Debug for Command

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Command

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.