Skip to main content

Group

Struct Group 

Source
pub struct Group {
    pub command: Command,
    pub commands: HashMap<String, Arc<dyn CommandLike>>,
    pub chain: bool,
    pub invoke_without_command: bool,
    pub result_callback: Option<ResultCallback>,
    pub subcommand_required: bool,
    pub subcommand_metavar: String,
    /* private fields */
}
Expand description

A command group that contains and dispatches to subcommands.

Groups are the primary way to organize CLI applications with multiple commands. They can be nested to create complex command hierarchies.

§Features

  • Subcommand registration and dispatch
  • Optional group callback (runs before subcommand)
  • Chain mode for executing multiple subcommands
  • Automatic help generation with command listing

§Example

use click::group::Group;
use click::command::Command;

let cli = Group::new("myapp")
    .help("My application")
    .invoke_without_command(true)
    .callback(|_ctx| {
        println!("No subcommand provided");
        Ok(())
    })
    .command(
        Command::new("hello")
            .help("Say hello")
            .build()
    )
    .build();

Fields§

§command: Command

The underlying command (for the group’s own options/arguments).

§commands: HashMap<String, Arc<dyn CommandLike>>

Registered subcommands (name -> Command or Group).

§chain: bool

Whether to execute multiple subcommands in sequence.

§invoke_without_command: bool

Whether to invoke the group callback even if no subcommand is provided.

§result_callback: Option<ResultCallback>

Optional callback to process subcommand results.

§subcommand_required: bool

Whether a subcommand is required (error if not provided).

Defaults to true unless invoke_without_command is true.

§subcommand_metavar: String

The metavar to show for subcommands in usage.

Implementations§

Source§

impl Group

Source

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

Create a new group builder with the given name.

§Example
use click::group::Group;

let group = Group::new("mygroup")
    .help("My command group")
    .build();
Source

pub fn add_command( &mut self, cmd: impl CommandLike + 'static, name: Option<&str>, )

Add a subcommand to this group.

If name is provided, it overrides the command’s own name.

§Example
use click::group::Group;
use click::command::Command;

let mut group = Group::new("cli").build();
group.add_command(Command::new("hello").build(), None);
group.add_command(Command::new("greet").build(), Some("hi")); // registered as "hi"

assert!(group.get_command("hello").is_some());
assert!(group.get_command("hi").is_some());
assert!(group.get_command("greet").is_none()); // not found by original name
Source

pub fn add_command_shared( &mut self, cmd: Arc<dyn CommandLike>, name: Option<&str>, )

Add a subcommand to this group using a shared command object.

This makes it possible to register the same command under multiple names (aliases) while still being able to query alias metadata.

Source

pub fn get_command(&self, name: &str) -> Option<&dyn CommandLike>

Get a subcommand by name.

§Example
use click::group::Group;
use click::command::Command;

let group = Group::new("cli")
    .command(Command::new("hello").build())
    .build();

assert!(group.get_command("hello").is_some());
assert!(group.get_command("unknown").is_none());
Source

pub fn list_command_entries(&self) -> Vec<(String, &dyn CommandLike)>

List all command registrations as (registered_name, command) pairs.

This is useful when you need both the registered key and the canonical name stored inside the command itself (command.name()).

Source

pub fn list_command_aliases(&self, name: &str) -> Vec<String>

List other registered names (aliases) that map to the same command.

Returns an empty list if the command is not found or if it has no aliases.

Source

pub fn list_commands(&self) -> Vec<&str>

List all subcommand names (sorted alphabetically).

§Example
use click::group::Group;
use click::command::Command;

let group = Group::new("cli")
    .command(Command::new("build").build())
    .command(Command::new("init").build())
    .command(Command::new("deploy").build())
    .build();

let commands = group.list_commands();
assert_eq!(commands, vec!["build", "deploy", "init"]);
Source

pub fn resolve_command<'a>( &'a self, ctx: &Context, args: &[String], ) -> Result<Option<(&'a str, &'a dyn CommandLike, Vec<String>)>, ClickError>

Resolve a command from arguments.

Returns the command name, the command, and the remaining arguments. Returns an error if the command is not found (unless in resilient parsing mode).

§Arguments
  • ctx - The current context
  • args - The arguments to parse
Source

pub fn format_commands(&self, _ctx: &Context) -> String

Format the commands section for help output.

Returns a formatted string listing all visible subcommands.

Trait Implementations§

Source§

impl CommandLike for Group

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 Group

Source§

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

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

impl Default for Group

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl !RefUnwindSafe for Group

§

impl !UnwindSafe for Group

§

impl Freeze for Group

§

impl Send for Group

§

impl Sync for Group

§

impl Unpin for Group

§

impl UnsafeUnpin for Group

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.