1use crate::ctx::{Ctx, Globals};
10use crate::error::{Error, Result};
11use crate::help::{self, AppInfo, HelpStyle};
12use crate::out;
13use crate::parse;
14use crate::spec::{Arg, Command, Flag};
15use crate::style;
16use std::process::exit;
17
18type Handler = Box<dyn Fn(&Ctx) -> Result<()>>;
20type Hook = Box<dyn Fn(&HookCtx)>;
22type ErrorHook = Box<dyn Fn(&Error)>;
24
25pub struct HookCtx<'a> {
27 pub app_name: &'a str,
28 pub command: &'a str,
29 pub globals: Globals,
30}
31
32struct Entry {
36 spec: Command,
37 handler: Option<Handler>,
38 children: Vec<Entry>,
39}
40
41impl Entry {
42 fn leaf(spec: Command, handler: Handler) -> Self {
43 Entry {
44 spec,
45 handler: Some(handler),
46 children: Vec::new(),
47 }
48 }
49 fn is_group(&self) -> bool {
50 !self.children.is_empty()
51 }
52}
53
54pub struct App {
56 name: String,
57 version: String,
58 about: String,
59 long_about: String,
60 style: HelpStyle,
61 help_renderer: Option<Box<dyn help::HelpRenderer>>,
62 theme: Option<crate::theme::Theme>,
63 entries: Vec<Entry>,
64 globals: Vec<Flag>,
65 pre: Vec<Hook>,
66 post: Vec<Hook>,
67 on_error: Vec<ErrorHook>,
68 specs_cache: Vec<Command>,
71}
72
73impl App {
74 pub fn new<S: Into<String>>(name: S) -> Self {
82 App {
83 name: name.into(),
84 version: env!("CARGO_PKG_VERSION").to_string(),
85 about: String::new(),
86 long_about: String::new(),
87 style: HelpStyle::Standard,
88 help_renderer: None,
89 theme: None,
90 entries: Vec::new(),
91 globals: default_globals(),
92 pre: Vec::new(),
93 post: Vec::new(),
94 on_error: Vec::new(),
95 specs_cache: Vec::new(),
96 }
97 }
98
99 pub fn about<S: Into<String>>(mut self, s: S) -> Self {
101 self.about = s.into();
102 self
103 }
104 pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
106 self.long_about = s.into();
107 self
108 }
109 pub fn version<S: Into<String>>(mut self, s: S) -> Self {
111 self.version = s.into();
112 self
113 }
114 pub fn help_style(mut self, style: HelpStyle) -> Self {
116 self.style = style;
117 self
118 }
119
120 pub fn help_renderer<R: help::HelpRenderer>(mut self, r: R) -> Self {
123 self.help_renderer = Some(Box::new(r));
124 self
125 }
126
127 pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
130 self.theme = Some(theme);
131 self
132 }
133
134 pub fn command<S, F>(mut self, name: S, about: S, body: F) -> Self
137 where
138 S: Into<String>,
139 F: Fn(&Ctx) -> Result<()> + 'static,
140 {
141 let mut spec = Command::new(name);
142 spec.about = about.into();
143 self.entries.push(Entry::leaf(spec, Box::new(body)));
144 self
145 }
146
147 pub fn command_with<S, C, F>(mut self, name: S, about: S, configure: C, body: F) -> Self
150 where
151 S: Into<String>,
152 C: FnOnce(CommandBuilder) -> CommandBuilder,
153 F: Fn(&Ctx) -> Result<()> + 'static,
154 {
155 let mut spec = Command::new(name);
156 spec.about = about.into();
157 let cb = configure(CommandBuilder { spec });
158 self.entries.push(Entry::leaf(cb.spec, Box::new(body)));
159 self
160 }
161
162 pub fn group<S, B>(mut self, name: S, about: S, build: B) -> Self
167 where
168 S: Into<String>,
169 B: FnOnce(Group) -> Group,
170 {
171 let mut spec = Command::new(name);
172 spec.about = about.into();
173 let g = build(Group {
174 spec,
175 children: Vec::new(),
176 });
177 let mut group_spec = g.spec;
178 group_spec.subcommands = g.children.iter().map(|c| c.spec.clone()).collect();
179 self.entries.push(Entry {
180 spec: group_spec,
181 handler: None,
182 children: g.children,
183 });
184 self
185 }
186
187 pub fn global_flag(mut self, f: Flag) -> Self {
189 self.globals.push(f);
190 self
191 }
192
193 pub fn pre_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
195 self.pre.push(Box::new(f));
196 self
197 }
198 pub fn post_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
200 self.post.push(Box::new(f));
201 self
202 }
203 pub fn on_error<F: Fn(&Error) + 'static>(mut self, f: F) -> Self {
205 self.on_error.push(Box::new(f));
206 self
207 }
208
209 pub fn run(self) -> ! {
211 let args: Vec<String> = std::env::args().skip(1).collect();
212 let code = self.finalize().run_inner(args);
213 exit(code);
214 }
215
216 pub fn run_with(self, args: Vec<String>) -> i32 {
219 self.finalize().run_inner(args)
220 }
221
222 fn run_inner(&self, args: Vec<String>) -> i32 {
223 crate::theme::set_active(self.theme.clone().unwrap_or_default());
225 crate::sig::install();
227 style::set_enabled(style::env_default());
229
230 let mut idx = 0;
232 let mut want_help = false;
233 let mut want_version = false;
234 let mut globals = Globals::default();
235
236 while idx < args.len() {
237 match args[idx].as_str() {
238 "-h" | "--help" => {
239 want_help = true;
240 idx += 1;
241 }
242 "-V" | "--version" => {
243 want_version = true;
244 idx += 1;
245 }
246 "-q" | "--quiet" => {
247 globals.quiet = true;
248 idx += 1;
249 }
250 "-v" | "--verbose" => {
251 globals.verbose += 1;
252 idx += 1;
253 }
254 t if t.len() >= 2 && t.starts_with('-') && !t.starts_with("--")
256 && t[1..].chars().all(|c| c == 'v') =>
257 {
258 globals.verbose += (t.len() - 1) as u8;
259 idx += 1;
260 }
261 "--json" => {
262 globals.json = true;
263 idx += 1;
264 }
265 "--dry-run" => {
266 globals.dry_run = true;
267 idx += 1;
268 }
269 "--sudo" => {
270 globals.sudo = true;
271 idx += 1;
272 }
273 _ => break,
275 }
276 }
277
278 if globals.quiet || globals.json {
280 style::set_enabled(false);
281 }
282 out::set_quiet(globals.quiet);
283 out::set_verbosity(globals.verbose);
284
285 if want_version {
286 println!("{} {}", self.name, self.version);
287 return crate::error::codes::OK;
288 }
289
290 if idx >= args.len() {
292 let long = want_help; print!("{}", self.render_app_help(long));
294 return if want_help {
295 crate::error::codes::OK
296 } else {
297 crate::error::codes::USAGE
299 };
300 }
301
302 let sub_start = idx;
303 let sub = &args[idx];
304 idx += 1;
305 let rest = &args[idx..];
306
307 if sub == "help" {
309 if !rest.is_empty() {
310 if let Some((entry, path)) = self.resolve_path(rest) {
311 print!("{}", self.render_command_help_path(&path, &entry.spec, true));
312 return crate::error::codes::OK;
313 }
314 }
315 print!("{}", self.render_app_help(true));
316 return crate::error::codes::OK;
317 }
318
319 if sub == "completions" {
321 return self.emit_completions(rest.first().map(|s| s.as_str()));
322 }
323
324 if sub == "docs" {
326 return self.emit_docs(rest.first().map(|s| s.as_str()));
327 }
328
329 let mut node_children = &self.entries;
333 let mut path: Vec<String> = Vec::new();
334 let mut cursor = sub_start; let target: &Entry;
336
337 loop {
338 let token = &args[cursor];
339 let found = node_children.iter().find(|e| &e.spec.name == token);
340 let entry = match found {
341 Some(e) => e,
342 None => {
343 let names: Vec<&str> = node_children.iter().map(|e| e.spec.name.as_str()).collect();
345 out::error(format!("unknown command '{}'", token));
346 if let Some(sug) = crate::suggest::closest(token, names.iter().copied()) {
347 out::info(format!("did you mean '{}'?", sug));
348 }
349 let ctx_name = if path.is_empty() {
350 self.name.clone()
351 } else {
352 format!("{} {}", self.name, path.join(" "))
353 };
354 out::info(format!("run '{} --help' for usage", ctx_name));
355 return crate::error::codes::USAGE;
356 }
357 };
358 path.push(entry.spec.name.clone());
359 cursor += 1;
360
361 let peek = &args[cursor..];
363 let want_long = peek.iter().any(|a| a == "--help");
364 let want_short = peek.iter().any(|a| a == "-h");
365 if want_long || want_short {
366 print!("{}", self.render_command_help_path(&path, &entry.spec, want_long));
367 return crate::error::codes::OK;
368 }
369
370 if entry.is_group() {
371 if cursor >= args.len() {
372 print!("{}", self.render_command_help_path(&path, &entry.spec, false));
374 return crate::error::codes::USAGE;
375 }
376 node_children = &entry.children;
377 continue;
378 } else {
379 target = entry;
380 break;
381 }
382 }
383
384 let entry = target;
385 let rest = &args[cursor..];
386
387 let mut cmd_args: Vec<String> = Vec::new();
389 for a in rest {
390 match a.as_str() {
391 "-q" | "--quiet" => globals.quiet = true,
392 "--json" => globals.json = true,
393 "--dry-run" => globals.dry_run = true,
394 "--sudo" => globals.sudo = true,
395 "-v" | "--verbose" => globals.verbose += 1,
396 t if t.len() >= 2 && t.starts_with('-') && !t.starts_with("--")
397 && t[1..].chars().all(|c| c == 'v') =>
398 {
399 globals.verbose += (t.len() - 1) as u8;
400 }
401 _ => cmd_args.push(a.clone()),
402 }
403 }
404 if globals.quiet || globals.json {
405 style::set_enabled(false);
406 }
407 out::set_quiet(globals.quiet);
408 out::set_verbosity(globals.verbose);
409
410 let matches = match parse::parse(&entry.spec, &cmd_args) {
412 Ok(m) => m,
413 Err(e) => {
414 self.report(&e);
415 return e.code;
416 }
417 };
418
419 let full_command = path.join(" ");
420 let ctx = Ctx::new(self.name.clone(), full_command.clone(), matches, globals);
421
422 let hc = HookCtx {
424 app_name: &self.name,
425 command: &full_command,
426 globals,
427 };
428 for h in &self.pre {
429 h(&hc);
430 }
431
432 let handler = entry.handler.as_ref().expect("leaf entry has a handler");
434 let result = handler(&ctx);
435
436 match result {
437 Ok(()) => {
438 for h in &self.post {
439 h(&hc);
440 }
441 crate::error::codes::OK
442 }
443 Err(e) => {
444 for h in &self.on_error {
445 h(&e);
446 }
447 self.report(&e);
448 e.code
449 }
450 }
451 }
452
453 fn report(&self, e: &Error) {
454 out::error(&e.message);
455 for n in &e.notes {
456 eprintln!(" {}", style::dim(n));
457 }
458 }
459
460 fn render_app_help(&self, long: bool) -> String {
462 match &self.help_renderer {
463 Some(r) => r.app_help(&self.app_info(), long),
464 None => help::app_help(&self.app_info(), self.style, long),
465 }
466 }
467
468 fn render_command_help_path(&self, path: &[String], cmd: &Command, long: bool) -> String {
471 let prefix = if path.len() > 1 {
472 format!("{} {}", self.name, path[..path.len() - 1].join(" "))
473 } else {
474 self.name.clone()
475 };
476 match &self.help_renderer {
477 Some(r) => r.command_help(&prefix, cmd, long),
478 None => help::command_help(&prefix, cmd, self.style, long),
479 }
480 }
481
482 fn resolve_path(&self, tokens: &[String]) -> Option<(&Entry, Vec<String>)> {
485 let mut children = &self.entries;
486 let mut path = Vec::new();
487 let mut current: Option<&Entry> = None;
488 for tok in tokens {
489 let found = children.iter().find(|e| &e.spec.name == tok)?;
490 path.push(found.spec.name.clone());
491 current = Some(found);
492 children = &found.children;
493 }
494 current.map(|e| (e, path))
495 }
496
497 fn emit_docs(&self, fmt: Option<&str>) -> i32 {
499 let fmt = match fmt.and_then(crate::docs::DocFormat::parse) {
500 Some(f) => f,
501 None => {
502 out::error(format!(
503 "usage: {} docs <{}>",
504 self.name,
505 crate::docs::DocFormat::all().join("|")
506 ));
507 return crate::error::codes::USAGE;
508 }
509 };
510 print!(
511 "{}",
512 crate::docs::generate(&self.name, &self.version, &self.about, self.specs(), fmt)
513 );
514 crate::error::codes::OK
515 }
516
517 fn emit_completions(&self, shell: Option<&str>) -> i32 {
519 let shell = match shell.and_then(crate::complete::Shell::parse) {
520 Some(s) => s,
521 None => {
522 out::error(format!(
523 "usage: {} completions <{}>",
524 self.name,
525 crate::complete::Shell::all().join("|")
526 ));
527 return crate::error::codes::USAGE;
528 }
529 };
530 print!(
531 "{}",
532 crate::complete::generate(&self.name, self.specs(), shell)
533 );
534 crate::error::codes::OK
535 }
536
537 fn app_info(&self) -> AppInfo<'_> {
538 AppInfo {
539 name: &self.name,
540 version: &self.version,
541 about: &self.about,
542 long_about: &self.long_about,
543 commands: self.specs(),
544 globals: &self.globals,
545 }
546 }
547
548 fn specs(&self) -> &[Command] {
549 &self.specs_cache
550 }
551
552 fn finalize(mut self) -> Self {
555 self.specs_cache = self.entries.iter().map(|e| e.spec.clone()).collect();
556 self
557 }
558}
559
560pub struct Group {
562 spec: Command,
563 children: Vec<Entry>,
564}
565
566impl Group {
567 pub fn command<S, F>(mut self, name: S, about: S, body: F) -> Self
569 where
570 S: Into<String>,
571 F: Fn(&Ctx) -> Result<()> + 'static,
572 {
573 let mut spec = Command::new(name);
574 spec.about = about.into();
575 self.children.push(Entry::leaf(spec, Box::new(body)));
576 self
577 }
578 pub fn command_with<S, C, F>(mut self, name: S, about: S, configure: C, body: F) -> Self
580 where
581 S: Into<String>,
582 C: FnOnce(CommandBuilder) -> CommandBuilder,
583 F: Fn(&Ctx) -> Result<()> + 'static,
584 {
585 let mut spec = Command::new(name);
586 spec.about = about.into();
587 let cb = configure(CommandBuilder { spec });
588 self.children.push(Entry::leaf(cb.spec, Box::new(body)));
589 self
590 }
591 pub fn group<S, B>(mut self, name: S, about: S, build: B) -> Self
593 where
594 S: Into<String>,
595 B: FnOnce(Group) -> Group,
596 {
597 let mut spec = Command::new(name);
598 spec.about = about.into();
599 let g = build(Group {
600 spec,
601 children: Vec::new(),
602 });
603 let mut group_spec = g.spec;
604 group_spec.subcommands = g.children.iter().map(|c| c.spec.clone()).collect();
605 self.children.push(Entry {
606 spec: group_spec,
607 handler: None,
608 children: g.children,
609 });
610 self
611 }
612}
613
614pub struct CommandBuilder {
616 spec: Command,
617}
618
619impl CommandBuilder {
620 pub fn arg<S: Into<String>>(mut self, name: S, help: S) -> Self {
622 self.spec.args.push(Arg::new(name).help(help));
623 self
624 }
625 pub fn arg_opt<S: Into<String>>(mut self, name: S, help: S) -> Self {
627 self.spec.args.push(Arg::new(name).help(help).optional());
628 self
629 }
630 pub fn args<S: Into<String>>(mut self, name: S, help: S) -> Self {
632 self.spec.args.push(Arg::new(name).help(help).variadic());
633 self
634 }
635 pub fn switch<S: Into<String>>(mut self, long: S, short: Option<char>, help: S) -> Self {
637 let mut f = Flag::switch(long).help(help);
638 if let Some(c) = short {
639 f = f.short(c);
640 }
641 self.spec.flags.push(f);
642 self
643 }
644 pub fn value<S: Into<String>>(mut self, long: S, short: Option<char>, help: S) -> Self {
646 let mut f = Flag::value(long).help(help);
647 if let Some(c) = short {
648 f = f.short(c);
649 }
650 self.spec.flags.push(f);
651 self
652 }
653 pub fn example<S: Into<String>>(mut self, ex: S) -> Self {
655 self.spec.examples.push(ex.into());
656 self
657 }
658 pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
660 self.spec.long_about = s.into();
661 self
662 }
663 pub fn destructive(mut self) -> Self {
665 self.spec.destructive = true;
666 self
667 }
668}
669
670fn default_globals() -> Vec<Flag> {
672 vec![
673 Flag::switch("help").short('h').help("Print help"),
674 Flag::switch("version").short('V').help("Print version"),
675 Flag::switch("quiet").short('q').help("Suppress non-error output"),
676 Flag::switch("verbose").short('v').help("Increase verbosity (repeatable)"),
677 Flag::switch("json").help("Emit machine-readable JSON where supported"),
678 Flag::switch("dry-run").help("Show what would happen without doing it"),
679 ]
680}