use crate::ctx::{Ctx, Globals};
use crate::error::{Error, Result};
use crate::help::{self, AppInfo, HelpStyle};
use crate::out;
use crate::parse;
use crate::spec::{Arg, Command, Flag};
use crate::style;
use std::process::exit;
type Handler = Box<dyn Fn(&Ctx) -> Result<()>>;
type Hook = Box<dyn Fn(&HookCtx)>;
type ErrorHook = Box<dyn Fn(&Error)>;
pub struct HookCtx<'a> {
pub app_name: &'a str,
pub command: &'a str,
pub globals: Globals,
}
struct Entry {
spec: Command,
handler: Option<Handler>,
children: Vec<Entry>,
}
impl Entry {
fn leaf(spec: Command, handler: Handler) -> Self {
Entry {
spec,
handler: Some(handler),
children: Vec::new(),
}
}
fn is_group(&self) -> bool {
!self.children.is_empty()
}
}
pub struct App {
name: String,
version: String,
about: String,
long_about: String,
style: HelpStyle,
help_renderer: Option<Box<dyn help::HelpRenderer>>,
theme: Option<crate::theme::Theme>,
entries: Vec<Entry>,
globals: Vec<Flag>,
pre: Vec<Hook>,
post: Vec<Hook>,
on_error: Vec<ErrorHook>,
specs_cache: Vec<Command>,
}
impl App {
pub fn new<S: Into<String>>(name: S) -> Self {
App {
name: name.into(),
version: env!("CARGO_PKG_VERSION").to_string(),
about: String::new(),
long_about: String::new(),
style: HelpStyle::Standard,
help_renderer: None,
theme: None,
entries: Vec::new(),
globals: default_globals(),
pre: Vec::new(),
post: Vec::new(),
on_error: Vec::new(),
specs_cache: Vec::new(),
}
}
pub fn about<S: Into<String>>(mut self, s: S) -> Self {
self.about = s.into();
self
}
pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
self.long_about = s.into();
self
}
pub fn version<S: Into<String>>(mut self, s: S) -> Self {
self.version = s.into();
self
}
pub fn help_style(mut self, style: HelpStyle) -> Self {
self.style = style;
self
}
pub fn help_renderer<R: help::HelpRenderer>(mut self, r: R) -> Self {
self.help_renderer = Some(Box::new(r));
self
}
pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
self.theme = Some(theme);
self
}
pub fn command<S, F>(mut self, name: S, about: S, body: F) -> Self
where
S: Into<String>,
F: Fn(&Ctx) -> Result<()> + 'static,
{
let mut spec = Command::new(name);
spec.about = about.into();
self.entries.push(Entry::leaf(spec, Box::new(body)));
self
}
pub fn command_with<S, C, F>(mut self, name: S, about: S, configure: C, body: F) -> Self
where
S: Into<String>,
C: FnOnce(CommandBuilder) -> CommandBuilder,
F: Fn(&Ctx) -> Result<()> + 'static,
{
let mut spec = Command::new(name);
spec.about = about.into();
let cb = configure(CommandBuilder { spec });
self.entries.push(Entry::leaf(cb.spec, Box::new(body)));
self
}
pub fn group<S, B>(mut self, name: S, about: S, build: B) -> Self
where
S: Into<String>,
B: FnOnce(Group) -> Group,
{
let mut spec = Command::new(name);
spec.about = about.into();
let g = build(Group {
spec,
children: Vec::new(),
});
let mut group_spec = g.spec;
group_spec.subcommands = g.children.iter().map(|c| c.spec.clone()).collect();
self.entries.push(Entry {
spec: group_spec,
handler: None,
children: g.children,
});
self
}
pub fn global_flag(mut self, f: Flag) -> Self {
self.globals.push(f);
self
}
pub fn pre_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
self.pre.push(Box::new(f));
self
}
pub fn post_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
self.post.push(Box::new(f));
self
}
pub fn on_error<F: Fn(&Error) + 'static>(mut self, f: F) -> Self {
self.on_error.push(Box::new(f));
self
}
pub fn run(self) -> ! {
let args: Vec<String> = std::env::args().skip(1).collect();
let code = self.finalize().run_inner(args);
exit(code);
}
pub fn run_with(self, args: Vec<String>) -> i32 {
self.finalize().run_inner(args)
}
fn run_inner(&self, args: Vec<String>) -> i32 {
crate::theme::set_active(self.theme.clone().unwrap_or_default());
crate::sig::install();
style::set_enabled(style::env_default());
let mut idx = 0;
let mut want_help = false;
let mut want_version = false;
let mut globals = Globals::default();
while idx < args.len() {
match args[idx].as_str() {
"-h" | "--help" => {
want_help = true;
idx += 1;
}
"-V" | "--version" => {
want_version = true;
idx += 1;
}
"-q" | "--quiet" => {
globals.quiet = true;
idx += 1;
}
"-v" | "--verbose" => {
globals.verbose += 1;
idx += 1;
}
t if t.len() >= 2 && t.starts_with('-') && !t.starts_with("--")
&& t[1..].chars().all(|c| c == 'v') =>
{
globals.verbose += (t.len() - 1) as u8;
idx += 1;
}
"--json" => {
globals.json = true;
idx += 1;
}
"--dry-run" => {
globals.dry_run = true;
idx += 1;
}
"--sudo" => {
globals.sudo = true;
idx += 1;
}
_ => break,
}
}
if globals.quiet || globals.json {
style::set_enabled(false);
}
out::set_quiet(globals.quiet);
out::set_verbosity(globals.verbose);
if want_version {
println!("{} {}", self.name, self.version);
return crate::error::codes::OK;
}
if idx >= args.len() {
let long = want_help; print!("{}", self.render_app_help(long));
return if want_help {
crate::error::codes::OK
} else {
crate::error::codes::USAGE
};
}
let sub_start = idx;
let sub = &args[idx];
idx += 1;
let rest = &args[idx..];
if sub == "help" {
if !rest.is_empty() {
if let Some((entry, path)) = self.resolve_path(rest) {
print!("{}", self.render_command_help_path(&path, &entry.spec, true));
return crate::error::codes::OK;
}
}
print!("{}", self.render_app_help(true));
return crate::error::codes::OK;
}
if sub == "completions" {
return self.emit_completions(rest.first().map(|s| s.as_str()));
}
if sub == "docs" {
return self.emit_docs(rest.first().map(|s| s.as_str()));
}
let mut node_children = &self.entries;
let mut path: Vec<String> = Vec::new();
let mut cursor = sub_start; let target: &Entry;
loop {
let token = &args[cursor];
let found = node_children.iter().find(|e| &e.spec.name == token);
let entry = match found {
Some(e) => e,
None => {
let names: Vec<&str> = node_children.iter().map(|e| e.spec.name.as_str()).collect();
out::error(format!("unknown command '{}'", token));
if let Some(sug) = crate::suggest::closest(token, names.iter().copied()) {
out::info(format!("did you mean '{}'?", sug));
}
let ctx_name = if path.is_empty() {
self.name.clone()
} else {
format!("{} {}", self.name, path.join(" "))
};
out::info(format!("run '{} --help' for usage", ctx_name));
return crate::error::codes::USAGE;
}
};
path.push(entry.spec.name.clone());
cursor += 1;
let peek = &args[cursor..];
let want_long = peek.iter().any(|a| a == "--help");
let want_short = peek.iter().any(|a| a == "-h");
if want_long || want_short {
print!("{}", self.render_command_help_path(&path, &entry.spec, want_long));
return crate::error::codes::OK;
}
if entry.is_group() {
if cursor >= args.len() {
print!("{}", self.render_command_help_path(&path, &entry.spec, false));
return crate::error::codes::USAGE;
}
node_children = &entry.children;
continue;
} else {
target = entry;
break;
}
}
let entry = target;
let rest = &args[cursor..];
let mut cmd_args: Vec<String> = Vec::new();
for a in rest {
match a.as_str() {
"-q" | "--quiet" => globals.quiet = true,
"--json" => globals.json = true,
"--dry-run" => globals.dry_run = true,
"--sudo" => globals.sudo = true,
"-v" | "--verbose" => globals.verbose += 1,
t if t.len() >= 2 && t.starts_with('-') && !t.starts_with("--")
&& t[1..].chars().all(|c| c == 'v') =>
{
globals.verbose += (t.len() - 1) as u8;
}
_ => cmd_args.push(a.clone()),
}
}
if globals.quiet || globals.json {
style::set_enabled(false);
}
out::set_quiet(globals.quiet);
out::set_verbosity(globals.verbose);
let matches = match parse::parse(&entry.spec, &cmd_args) {
Ok(m) => m,
Err(e) => {
self.report(&e);
return e.code;
}
};
let full_command = path.join(" ");
let ctx = Ctx::new(self.name.clone(), full_command.clone(), matches, globals);
let hc = HookCtx {
app_name: &self.name,
command: &full_command,
globals,
};
for h in &self.pre {
h(&hc);
}
let handler = entry.handler.as_ref().expect("leaf entry has a handler");
let result = handler(&ctx);
match result {
Ok(()) => {
for h in &self.post {
h(&hc);
}
crate::error::codes::OK
}
Err(e) => {
for h in &self.on_error {
h(&e);
}
self.report(&e);
e.code
}
}
}
fn report(&self, e: &Error) {
out::error(&e.message);
for n in &e.notes {
eprintln!(" {}", style::dim(n));
}
}
fn render_app_help(&self, long: bool) -> String {
match &self.help_renderer {
Some(r) => r.app_help(&self.app_info(), long),
None => help::app_help(&self.app_info(), self.style, long),
}
}
fn render_command_help_path(&self, path: &[String], cmd: &Command, long: bool) -> String {
let prefix = if path.len() > 1 {
format!("{} {}", self.name, path[..path.len() - 1].join(" "))
} else {
self.name.clone()
};
match &self.help_renderer {
Some(r) => r.command_help(&prefix, cmd, long),
None => help::command_help(&prefix, cmd, self.style, long),
}
}
fn resolve_path(&self, tokens: &[String]) -> Option<(&Entry, Vec<String>)> {
let mut children = &self.entries;
let mut path = Vec::new();
let mut current: Option<&Entry> = None;
for tok in tokens {
let found = children.iter().find(|e| &e.spec.name == tok)?;
path.push(found.spec.name.clone());
current = Some(found);
children = &found.children;
}
current.map(|e| (e, path))
}
fn emit_docs(&self, fmt: Option<&str>) -> i32 {
let fmt = match fmt.and_then(crate::docs::DocFormat::parse) {
Some(f) => f,
None => {
out::error(format!(
"usage: {} docs <{}>",
self.name,
crate::docs::DocFormat::all().join("|")
));
return crate::error::codes::USAGE;
}
};
print!(
"{}",
crate::docs::generate(&self.name, &self.version, &self.about, self.specs(), fmt)
);
crate::error::codes::OK
}
fn emit_completions(&self, shell: Option<&str>) -> i32 {
let shell = match shell.and_then(crate::complete::Shell::parse) {
Some(s) => s,
None => {
out::error(format!(
"usage: {} completions <{}>",
self.name,
crate::complete::Shell::all().join("|")
));
return crate::error::codes::USAGE;
}
};
print!(
"{}",
crate::complete::generate(&self.name, self.specs(), shell)
);
crate::error::codes::OK
}
fn app_info(&self) -> AppInfo<'_> {
AppInfo {
name: &self.name,
version: &self.version,
about: &self.about,
long_about: &self.long_about,
commands: self.specs(),
globals: &self.globals,
}
}
fn specs(&self) -> &[Command] {
&self.specs_cache
}
fn finalize(mut self) -> Self {
self.specs_cache = self.entries.iter().map(|e| e.spec.clone()).collect();
self
}
}
pub struct Group {
spec: Command,
children: Vec<Entry>,
}
impl Group {
pub fn command<S, F>(mut self, name: S, about: S, body: F) -> Self
where
S: Into<String>,
F: Fn(&Ctx) -> Result<()> + 'static,
{
let mut spec = Command::new(name);
spec.about = about.into();
self.children.push(Entry::leaf(spec, Box::new(body)));
self
}
pub fn command_with<S, C, F>(mut self, name: S, about: S, configure: C, body: F) -> Self
where
S: Into<String>,
C: FnOnce(CommandBuilder) -> CommandBuilder,
F: Fn(&Ctx) -> Result<()> + 'static,
{
let mut spec = Command::new(name);
spec.about = about.into();
let cb = configure(CommandBuilder { spec });
self.children.push(Entry::leaf(cb.spec, Box::new(body)));
self
}
pub fn group<S, B>(mut self, name: S, about: S, build: B) -> Self
where
S: Into<String>,
B: FnOnce(Group) -> Group,
{
let mut spec = Command::new(name);
spec.about = about.into();
let g = build(Group {
spec,
children: Vec::new(),
});
let mut group_spec = g.spec;
group_spec.subcommands = g.children.iter().map(|c| c.spec.clone()).collect();
self.children.push(Entry {
spec: group_spec,
handler: None,
children: g.children,
});
self
}
}
pub struct CommandBuilder {
spec: Command,
}
impl CommandBuilder {
pub fn arg<S: Into<String>>(mut self, name: S, help: S) -> Self {
self.spec.args.push(Arg::new(name).help(help));
self
}
pub fn arg_opt<S: Into<String>>(mut self, name: S, help: S) -> Self {
self.spec.args.push(Arg::new(name).help(help).optional());
self
}
pub fn args<S: Into<String>>(mut self, name: S, help: S) -> Self {
self.spec.args.push(Arg::new(name).help(help).variadic());
self
}
pub fn switch<S: Into<String>>(mut self, long: S, short: Option<char>, help: S) -> Self {
let mut f = Flag::switch(long).help(help);
if let Some(c) = short {
f = f.short(c);
}
self.spec.flags.push(f);
self
}
pub fn value<S: Into<String>>(mut self, long: S, short: Option<char>, help: S) -> Self {
let mut f = Flag::value(long).help(help);
if let Some(c) = short {
f = f.short(c);
}
self.spec.flags.push(f);
self
}
pub fn example<S: Into<String>>(mut self, ex: S) -> Self {
self.spec.examples.push(ex.into());
self
}
pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
self.spec.long_about = s.into();
self
}
pub fn destructive(mut self) -> Self {
self.spec.destructive = true;
self
}
}
fn default_globals() -> Vec<Flag> {
vec![
Flag::switch("help").short('h').help("Print help"),
Flag::switch("version").short('V').help("Print version"),
Flag::switch("quiet").short('q').help("Suppress non-error output"),
Flag::switch("verbose").short('v').help("Increase verbosity (repeatable)"),
Flag::switch("json").help("Emit machine-readable JSON where supported"),
Flag::switch("dry-run").help("Show what would happen without doing it"),
]
}