Skip to main content

cornerstone/
app.rs

1//! The application builder — the one type most authors use.
2//!
3//! An author declares the app, its commands, each command's args/flags, and a
4//! closure body per command. [`App::run`] then does everything else: parses
5//! argv, handles `--help`/`--version`/global flags, sets up color and quiet
6//! state, runs lifecycle hooks, dispatches to the matched command, and turns a
7//! returned [`Error`] into a printed message and the right exit code.
8
9use 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
18/// The closure type for a command body.
19type Handler = Box<dyn Fn(&Ctx) -> Result<()>>;
20/// The closure type for lifecycle hooks.
21type Hook = Box<dyn Fn(&HookCtx)>;
22/// The closure type for the error hook.
23type ErrorHook = Box<dyn Fn(&Error)>;
24
25/// Minimal info passed to lifecycle hooks.
26pub struct HookCtx<'a> {
27    pub app_name: &'a str,
28    pub command: &'a str,
29    pub globals: Globals,
30}
31
32/// A command plus its handler, assembled through the builder. A command may be
33/// a leaf (has a handler, runs work) or a group (has children, dispatches to
34/// them). A group with no handler prints its help when invoked bare.
35struct 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
54/// The application.
55pub 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    /// Mirror of entry specs, populated by `finalize()` so help can hand out a
69    /// `&[Command]` without borrowing temporaries.
70    specs_cache: Vec<Command>,
71}
72
73impl App {
74    /// Start a new app with the given program name.
75    ///
76    /// The version defaults to Cornerstone's own crate version, which is almost
77    /// never what you want. Set your tool's version explicitly with
78    /// [`App::version`], typically `.version(env!("CARGO_PKG_VERSION"))` so it
79    /// tracks *your* crate — `env!` must be expanded in your crate, not here, to
80    /// pick up your version rather than the library's.
81    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    /// One-line description shown at the top of help.
100    pub fn about<S: Into<String>>(mut self, s: S) -> Self {
101        self.about = s.into();
102        self
103    }
104    /// Longer description shown in `--help` (long tier).
105    pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
106        self.long_about = s.into();
107        self
108    }
109    /// The version string reported by `--version` (defaults to the crate's).
110    pub fn version<S: Into<String>>(mut self, s: S) -> Self {
111        self.version = s.into();
112        self
113    }
114    /// Choose a built-in help preset.
115    pub fn help_style(mut self, style: HelpStyle) -> Self {
116        self.style = style;
117        self
118    }
119
120    /// Supply a fully custom help renderer, overriding the preset. Use this when
121    /// none of the three built-in presets fit the look you want.
122    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    /// Install a custom [`Theme`](crate::theme::Theme). Every glyph, label, and
128    /// color the library emits is read from it. Called once; defaults are neutral.
129    pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
130        self.theme = Some(theme);
131        self
132    }
133
134    /// Register a simple command: name, one-line about, and a body. For commands
135    /// that need arguments or flags, use [`App::command_with`].
136    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    /// Register a command, configuring its spec (args, flags, examples) through
148    /// a builder closure before attaching the body.
149    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    /// Register a command *group*: a subcommand that itself contains
163    /// subcommands (e.g. `tool remote add`). The `build` closure receives a
164    /// [`Group`] to attach child commands to. Invoking the group bare prints its
165    /// help.
166    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    /// Add an app-wide flag available to every command (beyond the built-ins).
188    pub fn global_flag(mut self, f: Flag) -> Self {
189        self.globals.push(f);
190        self
191    }
192
193    /// Run before any command body.
194    pub fn pre_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
195        self.pre.push(Box::new(f));
196        self
197    }
198    /// Run after a command body that returned `Ok`.
199    pub fn post_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
200        self.post.push(Box::new(f));
201        self
202    }
203    /// Run when a command body returns `Err`, before the process exits.
204    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    /// Parse `std::env::args` and run. Never returns — calls `exit`.
210    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    /// Testable entry point: run against an explicit argument vector and return
217    /// the exit code instead of exiting.
218    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        // Install the theme (neutral default if none supplied) so out/guard read it.
224        crate::theme::set_active(self.theme.clone().unwrap_or_default());
225        // Install the SIGINT handler so long operations can exit cleanly.
226        crate::sig::install();
227        // Resolve color first, from environment; refined by --quiet below.
228        style::set_enabled(style::env_default());
229
230        // Split global flags that can appear before the subcommand.
231        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                // Bundled verbosity: -vv, -vvv, ...
255                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                // First non-global token is the subcommand.
274                _ => break,
275            }
276        }
277
278        // Apply resolved global state.
279        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        // No subcommand given.
291        if idx >= args.len() {
292            let long = want_help; // bare -h/--help both show app help
293            print!("{}", self.render_app_help(long));
294            return if want_help {
295                crate::error::codes::OK
296            } else {
297                // No command and no help request: show help, usage exit code.
298                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        // Built-in `help [path...]`.
308        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        // Built-in `completions <shell>`.
320        if sub == "completions" {
321            return self.emit_completions(rest.first().map(|s| s.as_str()));
322        }
323
324        // Built-in `docs <man|markdown>`.
325        if sub == "docs" {
326            return self.emit_docs(rest.first().map(|s| s.as_str()));
327        }
328
329        // Walk the command tree, consuming tokens for group names until we reach
330        // a leaf command (or a bare group). `path` accumulates the names for help
331        // and context; `remaining` is what's left for the leaf's own parser.
332        let mut node_children = &self.entries;
333        let mut path: Vec<String> = Vec::new();
334        let mut cursor = sub_start; // index into `args`, at the first subcommand token
335        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                    // Unknown at this level: suggest a near-miss.
344                    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            // Help requested for this node?
362            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                    // Bare group: show its help.
373                    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        // Also let global flags appear after the subcommand.
388        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        // Parse the command's own args/flags.
411        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        // Lifecycle: pre-run hooks.
423        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        // Run the body (guaranteed present on a leaf).
433        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    /// Render app help, preferring a custom renderer over the preset.
461    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    /// Render command help for a resolved path, prefixing the app + group names
469    /// so usage lines read `app group cmd`.
470    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    /// Resolve a token path (as given to `help a b c`) into the entry it names,
483    /// returning the entry and the accumulated name path.
484    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    /// Emit generated documentation in the requested format.
498    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    /// Emit a shell-completion script for the requested shell.
518    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    /// Populate `specs_cache` from the top-level entries so help can borrow it.
553    /// Called once at the start of `run`/`run_with`.
554    fn finalize(mut self) -> Self {
555        self.specs_cache = self.entries.iter().map(|e| e.spec.clone()).collect();
556        self
557    }
558}
559
560/// Builder for a command group (a subcommand containing subcommands).
561pub struct Group {
562    spec: Command,
563    children: Vec<Entry>,
564}
565
566impl Group {
567    /// Add a leaf command to this group.
568    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    /// Add a leaf command with args/flags to this group.
579    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    /// Nest a further group inside this one (arbitrary depth).
592    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
614/// Builder for a single command's spec.
615pub struct CommandBuilder {
616    spec: Command,
617}
618
619impl CommandBuilder {
620    /// Add a required positional argument.
621    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    /// Add an optional positional argument.
626    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    /// Add a variadic trailing argument.
631    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    /// Add a boolean switch flag.
636    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    /// Add a value-taking flag.
645    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    /// Attach an example invocation (shown in long help).
654    pub fn example<S: Into<String>>(mut self, ex: S) -> Self {
655        self.spec.examples.push(ex.into());
656        self
657    }
658    /// Longer description for the command's own `--help`.
659    pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
660        self.spec.long_about = s.into();
661        self
662    }
663    /// Mark this command as destructive (enables guard helpers/semantics).
664    pub fn destructive(mut self) -> Self {
665        self.spec.destructive = true;
666        self
667    }
668}
669
670/// The built-in global flags every app gets.
671fn 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}