Skip to main content

Crate click

Crate click 

Source
Expand description

click-rs: A Rust port of Python’s Click library for creating command-line interfaces.

This crate provides a declarative way to build command-line applications with support for commands, options, arguments, and help generation.

§Quick Start with Derive Macros

The easiest way to use click-rs is with derive macros (enabled by default):

use click::Command;

#[derive(Command)]
#[command(name = "greet")]
/// A friendly greeter
struct Greet {
    /// Name to greet
    #[argument]
    name: String,

    /// Number of times to greet
    #[option(short, long, default = 1)]
    count: i32,
}

impl Greet {
    fn run(&self) {
        for _ in 0..self.count {
            println!("Hello, {}!", self.name);
        }
    }
}

fn main() {
    Greet::main_with(std::env::args().skip(1).collect(), |greet, _ctx| {
        greet.run();
        Ok(())
    }).unwrap();
}

§Builder API

For more control, use the builder API directly:

use click::{Command, ClickOption, Argument};

let cmd = Command::new("greet")
    .help("A friendly greeter")
    .argument(Argument::new("name").build())
    .option(ClickOption::new(&["--count", "-c"]).default("1").build())
    .callback(|ctx| {
        let name = ctx.get_param::<String>("name").unwrap();
        let count: i32 = ctx.get_param::<String>("count")
            .map(|s| s.parse().unwrap_or(1))
            .unwrap_or(1);
        for _ in 0..count {
            println!("Hello, {}!", name);
        }
        Ok(())
    })
    .build();

cmd.main(vec!["World".to_string()]).unwrap();

Re-exports§

pub use argument::AnyTypeConverter;
pub use argument::Argument;
pub use argument::ArgumentBuilder;
pub use argument::ShellCompleteCallback;
pub use command::Command;
pub use command::CommandBuilder;
pub use command::CommandCallback;
pub use context::get_current_context;
pub use context::pop_context;
pub use context::push_context;
pub use context::Context;
pub use context::ContextBuilder;
pub use decorators::make_pass_decorator;
pub use decorators::PassDecorator;
pub use error::ClickError;
pub use error::ErrorContext;
pub use error::ParamType;
pub use error::Result;
pub use group::CommandCollection;
pub use group::CommandCollectionBuilder;
pub use group::CommandLike;
pub use group::Group;
pub use group::GroupBuilder;
pub use group::ResultCallback;
pub use option::parse_option_name;
pub use option::split_option_names;
pub use option::ClickOption;
pub use option::OptionBuilder;
pub use parameter::DeprecationInfo;
pub use parameter::Nargs;
pub use parameter::Parameter;
pub use parameter::ParameterConfig;
pub use parser::split_opt;
pub use parser::OptionAction;
pub use parser::OptionParser;
pub use parser::ParseResult;
pub use parser::ParsedValue;
pub use formatting::detect_terminal_width;
pub use formatting::get_terminal_width;
pub use formatting::make_rule;
pub use formatting::split_into_lines;
pub use formatting::truncate_text;
pub use formatting::wrap_text;
pub use formatting::HelpFormatter;
pub use types::BoolType;
pub use types::Choice;
pub use types::CompletionItem;
pub use types::DateTimeType;
pub use types::FileMode;
pub use types::FileType;
pub use types::FloatRange;
pub use types::FloatType;
pub use types::IntRange;
pub use types::IntType;
pub use types::LazyFile;
pub use types::PathType;
pub use types::StringType;
pub use types::TupleType;
pub use types::TupleValue;
pub use types::TypeConverter;
pub use types::UnprocessedType;
pub use types::UuidType;
pub use types::BOOL;
pub use types::FLOAT;
pub use types::INT;
pub use types::STRING;
pub use types::UNPROCESSED;
pub use types::UUID;
pub use termui::clear;
pub use termui::confirm;
pub use termui::echo;
pub use termui::echo_via_pager;
pub use termui::edit_text;
pub use termui::get_terminal_size;
pub use termui::getchar;
pub use termui::isatty;
pub use termui::launch;
pub use termui::pause;
pub use termui::progressbar;
pub use termui::prompt;
pub use termui::secho;
pub use termui::stderr_isatty;
pub use termui::stdin_isatty;
pub use termui::stdout_isatty;
pub use termui::strip_ansi_codes;
pub use termui::style;
pub use termui::Color;
pub use termui::ProgressBar;
pub use completion::shell_complete;
pub use completion::BashComplete;
pub use completion::FishComplete;
pub use completion::ShellComplete;
pub use completion::ZshComplete;
pub use testing::CliRunner;
pub use testing::InvokeResult;
pub use testing::IsolatedFilesystem;
pub use utils::expand_path;
pub use utils::format_filename;
pub use utils::get_app_dir;
pub use utils::get_binary_stdout;
pub use utils::get_os_args;
pub use utils::get_text_stderr;
pub use utils::get_text_stdout;
pub use utils::safecall;
pub use utils::should_strip_ansi;

Modules§

argument
Positional argument parameter for click-rs.
command
Command building block for click-rs.
complete
Built-in shell completion helpers for common patterns.
completion
Shell completion support for click-rs.
context
Central execution context for click-rs.
decorators
Decorator-like convenience helpers.
error
Error types for click-rs.
formatting
Help text formatting utilities.
group
Command groups for click-rs.
option
Option parameter for click-rs.
parameter
Base parameter abstraction for click-rs.
parser
Low-level argument parsing for click-rs.
termui
Terminal UI utilities for click-rs.
testing
Testing utilities for click-rs applications.
types
Parameter types for click-rs.
utils
Utility functions for click-rs.

Macros§

assert_failure
Assert that a result indicates failure.
assert_output_contains
Assert that the output contains a substring.
assert_success
Assert that a result indicates success.
echo
Convenience macro for printing to the terminal.

Enums§

ParameterSource
Indicates the source of a parameter’s value.

Functions§

run
Run a command/group with process arguments and standard Click-style error handling.
run_with_completion
Run a command/group with optional shell-completion handling.
try_run
Run a command/group with explicit arguments.

Attribute Macros§

command
Attribute macro for function-first command definitions.
group
Attribute macro for function-first group definitions.

Derive Macros§

Command
Derive macro for creating CLI commands from structs.
Group
Derive macro for creating CLI command groups from structs.