Skip to main content

click/
lib.rs

1#![warn(unsafe_code)]
2//! click-rs: A Rust port of Python's Click library for creating command-line interfaces.
3//!
4//! This crate provides a declarative way to build command-line applications with
5//! support for commands, options, arguments, and help generation.
6//!
7//! # Quick Start with Derive Macros
8//!
9//! The easiest way to use click-rs is with derive macros (enabled by default):
10//!
11//! ```no_run
12//! use click::Command;
13//!
14//! #[derive(Command)]
15//! #[command(name = "greet")]
16//! /// A friendly greeter
17//! struct Greet {
18//!     /// Name to greet
19//!     #[argument]
20//!     name: String,
21//!
22//!     /// Number of times to greet
23//!     #[option(short, long, default = 1)]
24//!     count: i32,
25//! }
26//!
27//! impl Greet {
28//!     fn run(&self) {
29//!         for _ in 0..self.count {
30//!             println!("Hello, {}!", self.name);
31//!         }
32//!     }
33//! }
34//!
35//! fn main() {
36//!     Greet::main_with(std::env::args().skip(1).collect(), |greet, _ctx| {
37//!         greet.run();
38//!         Ok(())
39//!     }).unwrap();
40//! }
41//! ```
42//!
43//! # Builder API
44//!
45//! For more control, use the builder API directly:
46//!
47//! ```no_run
48//! use click::{Command, ClickOption, Argument};
49//!
50//! let cmd = Command::new("greet")
51//!     .help("A friendly greeter")
52//!     .argument(Argument::new("name").build())
53//!     .option(ClickOption::new(&["--count", "-c"]).default("1").build())
54//!     .callback(|ctx| {
55//!         let name = ctx.get_param::<String>("name").unwrap();
56//!         let count: i32 = ctx.get_param::<String>("count")
57//!             .map(|s| s.parse().unwrap_or(1))
58//!             .unwrap_or(1);
59//!         for _ in 0..count {
60//!             println!("Hello, {}!", name);
61//!         }
62//!         Ok(())
63//!     })
64//!     .build();
65//!
66//! cmd.main(vec!["World".to_string()]).unwrap();
67//! ```
68
69pub mod argument;
70pub mod command;
71pub mod complete;
72pub mod completion;
73pub mod context;
74pub mod decorators;
75pub mod error;
76pub mod formatting;
77pub mod group;
78pub mod option;
79pub mod parameter;
80pub mod parser;
81mod source;
82pub mod termui;
83pub mod testing;
84pub mod types;
85pub mod utils;
86
87pub use argument::{AnyTypeConverter, Argument, ArgumentBuilder, ShellCompleteCallback};
88pub use command::{Command, CommandBuilder, CommandCallback};
89pub use context::{get_current_context, pop_context, push_context, Context, ContextBuilder};
90pub use decorators::{make_pass_decorator, PassDecorator};
91pub use error::{ClickError, ErrorContext, ParamType, Result};
92pub use group::{
93    CommandCollection, CommandCollectionBuilder, CommandLike, Group, GroupBuilder, ResultCallback,
94};
95pub use option::{parse_option_name, split_option_names, ClickOption, OptionBuilder};
96pub use parameter::{DeprecationInfo, Nargs, Parameter, ParameterConfig};
97pub use parser::{split_opt, OptionAction, OptionParser, ParseResult, ParsedValue};
98pub use source::ParameterSource;
99
100/// Run a command/group with explicit arguments.
101pub fn try_run<I>(cmd: &dyn CommandLike, args: I) -> Result<()>
102where
103    I: IntoIterator<Item = String>,
104{
105    cmd.main(args.into_iter().collect())
106}
107
108/// Run a command/group with process arguments and standard Click-style error handling.
109///
110/// This helper prints formatted errors and exits with the command's exit code.
111pub fn run(cmd: &dyn CommandLike) {
112    if let Err(e) = try_run(cmd, std::env::args().skip(1)) {
113        eprintln!("{}", e.format_full());
114        std::process::exit(e.exit_code());
115    }
116}
117
118/// Run a command/group with optional shell-completion handling.
119///
120/// If completion is requested via `complete_var`, completion output is handled and this
121/// function returns immediately. Otherwise, it behaves like [`run`].
122pub fn run_with_completion(cmd: &dyn CommandLike, prog_name: &str, complete_var: &str) {
123    let completion_opt = completion::make_completion_option(complete_var);
124    if completion_opt.handle_completion(cmd, prog_name) {
125        return;
126    }
127    run(cmd);
128}
129
130// Re-export formatting utilities
131pub use formatting::{
132    detect_terminal_width, get_terminal_width, make_rule, split_into_lines, truncate_text,
133    wrap_text, HelpFormatter,
134};
135
136// Re-export derive macros when "derive" feature is enabled
137#[cfg(feature = "derive")]
138pub use click_derive::{command, group, Command, Group};
139
140// Re-export type converter trait and common types
141pub use types::{
142    // Type structs
143    BoolType,
144    Choice,
145    // Completion
146    CompletionItem,
147    DateTimeType,
148    FileMode,
149    FileType,
150    FloatRange,
151    FloatType,
152    IntRange,
153    IntType,
154    LazyFile,
155    PathType,
156    StringType,
157    TupleType,
158    TupleValue,
159    // Trait
160    TypeConverter,
161    UnprocessedType,
162    UuidType,
163    // Singleton types
164    BOOL,
165    FLOAT,
166    INT,
167    STRING,
168    UNPROCESSED,
169    UUID,
170};
171
172// Re-export terminal UI functions
173pub use termui::{
174    clear, confirm, echo, echo_via_pager, edit_text, get_terminal_size, getchar, isatty, launch,
175    pause, progressbar, prompt, secho, stderr_isatty, stdin_isatty, stdout_isatty,
176    strip_ansi_codes, style, Color, ProgressBar,
177};
178
179// Re-export shell completion
180pub use completion::{shell_complete, BashComplete, FishComplete, ShellComplete, ZshComplete};
181
182// Re-export testing utilities
183pub use testing::{CliRunner, InvokeResult, IsolatedFilesystem};
184
185// Re-export general utilities
186pub use utils::{
187    expand_path, format_filename, get_app_dir, get_binary_stdout, get_os_args, get_text_stderr,
188    get_text_stdout, safecall, should_strip_ansi,
189};