cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! The application builder — the one type most authors use.
//!
//! An author declares the app, its commands, each command's args/flags, and a
//! closure body per command. [`App::run`] then does everything else: parses
//! argv, handles `--help`/`--version`/global flags, sets up color and quiet
//! state, runs lifecycle hooks, dispatches to the matched command, and turns a
//! returned [`Error`] into a printed message and the right exit code.

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;

/// The closure type for a command body.
type Handler = Box<dyn Fn(&Ctx) -> Result<()>>;
/// The closure type for lifecycle hooks.
type Hook = Box<dyn Fn(&HookCtx)>;
/// The closure type for the error hook.
type ErrorHook = Box<dyn Fn(&Error)>;

/// Minimal info passed to lifecycle hooks.
pub struct HookCtx<'a> {
    pub app_name: &'a str,
    pub command: &'a str,
    pub globals: Globals,
}

/// A command plus its handler, assembled through the builder. A command may be
/// a leaf (has a handler, runs work) or a group (has children, dispatches to
/// them). A group with no handler prints its help when invoked bare.
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()
    }
}

/// The application.
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>,
    /// Mirror of entry specs, populated by `finalize()` so help can hand out a
    /// `&[Command]` without borrowing temporaries.
    specs_cache: Vec<Command>,
}

impl App {
    /// Start a new app with the given program name.
    ///
    /// The version defaults to Cornerstone's own crate version, which is almost
    /// never what you want. Set your tool's version explicitly with
    /// [`App::version`], typically `.version(env!("CARGO_PKG_VERSION"))` so it
    /// tracks *your* crate — `env!` must be expanded in your crate, not here, to
    /// pick up your version rather than the library's.
    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(),
        }
    }

    /// One-line description shown at the top of help.
    pub fn about<S: Into<String>>(mut self, s: S) -> Self {
        self.about = s.into();
        self
    }
    /// Longer description shown in `--help` (long tier).
    pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
        self.long_about = s.into();
        self
    }
    /// The version string reported by `--version` (defaults to the crate's).
    pub fn version<S: Into<String>>(mut self, s: S) -> Self {
        self.version = s.into();
        self
    }
    /// Choose a built-in help preset.
    pub fn help_style(mut self, style: HelpStyle) -> Self {
        self.style = style;
        self
    }

    /// Supply a fully custom help renderer, overriding the preset. Use this when
    /// none of the three built-in presets fit the look you want.
    pub fn help_renderer<R: help::HelpRenderer>(mut self, r: R) -> Self {
        self.help_renderer = Some(Box::new(r));
        self
    }

    /// Install a custom [`Theme`](crate::theme::Theme). Every glyph, label, and
    /// color the library emits is read from it. Called once; defaults are neutral.
    pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Register a simple command: name, one-line about, and a body. For commands
    /// that need arguments or flags, use [`App::command_with`].
    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
    }

    /// Register a command, configuring its spec (args, flags, examples) through
    /// a builder closure before attaching the body.
    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
    }

    /// Register a command *group*: a subcommand that itself contains
    /// subcommands (e.g. `tool remote add`). The `build` closure receives a
    /// [`Group`] to attach child commands to. Invoking the group bare prints its
    /// help.
    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
    }

    /// Add an app-wide flag available to every command (beyond the built-ins).
    pub fn global_flag(mut self, f: Flag) -> Self {
        self.globals.push(f);
        self
    }

    /// Run before any command body.
    pub fn pre_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
        self.pre.push(Box::new(f));
        self
    }
    /// Run after a command body that returned `Ok`.
    pub fn post_run<F: Fn(&HookCtx) + 'static>(mut self, f: F) -> Self {
        self.post.push(Box::new(f));
        self
    }
    /// Run when a command body returns `Err`, before the process exits.
    pub fn on_error<F: Fn(&Error) + 'static>(mut self, f: F) -> Self {
        self.on_error.push(Box::new(f));
        self
    }

    /// Parse `std::env::args` and run. Never returns — calls `exit`.
    pub fn run(self) -> ! {
        let args: Vec<String> = std::env::args().skip(1).collect();
        let code = self.finalize().run_inner(args);
        exit(code);
    }

    /// Testable entry point: run against an explicit argument vector and return
    /// the exit code instead of exiting.
    pub fn run_with(self, args: Vec<String>) -> i32 {
        self.finalize().run_inner(args)
    }

    fn run_inner(&self, args: Vec<String>) -> i32 {
        // Install the theme (neutral default if none supplied) so out/guard read it.
        crate::theme::set_active(self.theme.clone().unwrap_or_default());
        // Install the SIGINT handler so long operations can exit cleanly.
        crate::sig::install();
        // Resolve color first, from environment; refined by --quiet below.
        style::set_enabled(style::env_default());

        // Split global flags that can appear before the subcommand.
        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;
                }
                // Bundled verbosity: -vv, -vvv, ...
                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;
                }
                // First non-global token is the subcommand.
                _ => break,
            }
        }

        // Apply resolved global state.
        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;
        }

        // No subcommand given.
        if idx >= args.len() {
            let long = want_help; // bare -h/--help both show app help
            print!("{}", self.render_app_help(long));
            return if want_help {
                crate::error::codes::OK
            } else {
                // No command and no help request: show help, usage exit code.
                crate::error::codes::USAGE
            };
        }

        let sub_start = idx;
        let sub = &args[idx];
        idx += 1;
        let rest = &args[idx..];

        // Built-in `help [path...]`.
        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;
        }

        // Built-in `completions <shell>`.
        if sub == "completions" {
            return self.emit_completions(rest.first().map(|s| s.as_str()));
        }

        // Built-in `docs <man|markdown>`.
        if sub == "docs" {
            return self.emit_docs(rest.first().map(|s| s.as_str()));
        }

        // Walk the command tree, consuming tokens for group names until we reach
        // a leaf command (or a bare group). `path` accumulates the names for help
        // and context; `remaining` is what's left for the leaf's own parser.
        let mut node_children = &self.entries;
        let mut path: Vec<String> = Vec::new();
        let mut cursor = sub_start; // index into `args`, at the first subcommand token
        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 => {
                    // Unknown at this level: suggest a near-miss.
                    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;

            // Help requested for this node?
            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() {
                    // Bare group: show its help.
                    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..];

        // Also let global flags appear after the subcommand.
        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);

        // Parse the command's own args/flags.
        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);

        // Lifecycle: pre-run hooks.
        let hc = HookCtx {
            app_name: &self.name,
            command: &full_command,
            globals,
        };
        for h in &self.pre {
            h(&hc);
        }

        // Run the body (guaranteed present on a leaf).
        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));
        }
    }

    /// Render app help, preferring a custom renderer over the preset.
    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),
        }
    }

    /// Render command help for a resolved path, prefixing the app + group names
    /// so usage lines read `app group cmd`.
    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),
        }
    }

    /// Resolve a token path (as given to `help a b c`) into the entry it names,
    /// returning the entry and the accumulated name path.
    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))
    }

    /// Emit generated documentation in the requested format.
    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
    }

    /// Emit a shell-completion script for the requested shell.
    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
    }

    /// Populate `specs_cache` from the top-level entries so help can borrow it.
    /// Called once at the start of `run`/`run_with`.
    fn finalize(mut self) -> Self {
        self.specs_cache = self.entries.iter().map(|e| e.spec.clone()).collect();
        self
    }
}

/// Builder for a command group (a subcommand containing subcommands).
pub struct Group {
    spec: Command,
    children: Vec<Entry>,
}

impl Group {
    /// Add a leaf command to this 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
    }
    /// Add a leaf command with args/flags to this group.
    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
    }
    /// Nest a further group inside this one (arbitrary depth).
    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
    }
}

/// Builder for a single command's spec.
pub struct CommandBuilder {
    spec: Command,
}

impl CommandBuilder {
    /// Add a required positional argument.
    pub fn arg<S: Into<String>>(mut self, name: S, help: S) -> Self {
        self.spec.args.push(Arg::new(name).help(help));
        self
    }
    /// Add an optional positional argument.
    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
    }
    /// Add a variadic trailing argument.
    pub fn args<S: Into<String>>(mut self, name: S, help: S) -> Self {
        self.spec.args.push(Arg::new(name).help(help).variadic());
        self
    }
    /// Add a boolean switch flag.
    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
    }
    /// Add a value-taking flag.
    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
    }
    /// Attach an example invocation (shown in long help).
    pub fn example<S: Into<String>>(mut self, ex: S) -> Self {
        self.spec.examples.push(ex.into());
        self
    }
    /// Longer description for the command's own `--help`.
    pub fn long_about<S: Into<String>>(mut self, s: S) -> Self {
        self.spec.long_about = s.into();
        self
    }
    /// Mark this command as destructive (enables guard helpers/semantics).
    pub fn destructive(mut self) -> Self {
        self.spec.destructive = true;
        self
    }
}

/// The built-in global flags every app gets.
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"),
    ]
}