runi-cli 0.1.2

Terminal styling and CLI utilities for the Runi library collection
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::marker::PhantomData;
use std::process;

use super::error::{Error, Result};
use super::help::HelpPrinter;
use super::parser::{OptionParser, ParseResult};
use super::schema::{CLArgument, CommandSchema};

/// A command (root or subcommand) that knows how to produce its argument
/// schema and how to construct itself from a [`ParseResult`].
pub trait Command: Sized {
    fn schema() -> CommandSchema;
    fn from_parsed(parsed: &ParseResult) -> Result<Self>;
}

/// A root command that can be run standalone. The launcher calls `run` after
/// parsing arguments when no subcommands are registered.
pub trait Runnable {
    fn run(&self) -> Result<()>;
}

/// A subcommand invoked in the context of a parent (global-options) struct `G`.
pub trait SubCommandOf<G>: Sized {
    fn run(&self, global: &G) -> Result<()>;
}

type Runner<G> = Box<dyn Fn(&G, &ParseResult) -> Result<()>>;

struct Entry<G> {
    schema: CommandSchema,
    runner: Runner<G>,
}

/// Launcher before any subcommand has been registered.
///
/// Calling [`Launcher::command`] transitions to [`LauncherWithSubs`].
pub struct Launcher<G: Command> {
    _marker: PhantomData<G>,
}

impl<G: Command + 'static> Launcher<G> {
    pub fn of() -> Self {
        Self {
            _marker: PhantomData,
        }
    }

    /// Register the first subcommand, moving into subcommand mode.
    pub fn command<S>(self, name: &str) -> LauncherWithSubs<G>
    where
        S: Command + SubCommandOf<G> + 'static,
    {
        LauncherWithSubs::<G>::new().command::<S>(name)
    }

    /// Like [`Launcher::command`] but with a description override.
    pub fn command_with_description<S>(self, name: &str, description: &str) -> LauncherWithSubs<G>
    where
        S: Command + SubCommandOf<G> + 'static,
    {
        LauncherWithSubs::<G>::new().command_with_description::<S>(name, description)
    }

    /// Parse `args` into a `G` without running.
    pub fn parse(&self, args: &[String]) -> Result<G> {
        let schema = root_schema::<G>();
        let parsed = OptionParser::parse(&schema, args)?;
        G::from_parsed(&parsed)
    }

    /// Parse `std::env::args()`, run `G::run`, and exit. Parse-origin
    /// failures (including those from `G::from_parsed`, e.g. missing
    /// required args, invalid typed values) route through the help printer
    /// with exit code 2. Runtime failures from `G::run` exit with code 1
    /// and no help banner.
    pub fn execute(self) -> !
    where
        G: Runnable,
    {
        let args = env_args();
        let schema = root_schema::<G>();
        let parse_result =
            OptionParser::parse(&schema, &args).and_then(|parsed| G::from_parsed(&parsed));
        let code = match parse_result {
            Ok(g) => match g.run() {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("error: {e}");
                    1
                }
            },
            Err(e) => report_error(e, &schema),
        };
        process::exit(code);
    }
}

/// Launcher that already has at least one subcommand registered.
pub struct LauncherWithSubs<G: Command> {
    subs: Vec<Entry<G>>,
}

impl<G: Command + 'static> LauncherWithSubs<G> {
    fn new() -> Self {
        Self { subs: Vec::new() }
    }

    /// Register a subcommand. `S` must implement [`Command`] (for parsing)
    /// and [`SubCommandOf<G>`] (for running with access to the parsed global
    /// options).
    pub fn command<S>(self, name: &str) -> Self
    where
        S: Command + SubCommandOf<G> + 'static,
    {
        self.register::<S>(name, None)
    }

    /// Like [`LauncherWithSubs::command`] but overrides the help description
    /// for the registered subcommand (otherwise `S::schema().description`
    /// is used). Primarily called by `#[derive(Command)]` on enums when a
    /// variant carries its own `#[command(description = "...")]` or doc
    /// comment.
    pub fn command_with_description<S>(self, name: &str, description: &str) -> Self
    where
        S: Command + SubCommandOf<G> + 'static,
    {
        self.register::<S>(name, Some(description))
    }

    fn register<S>(mut self, name: &str, description: Option<&str>) -> Self
    where
        S: Command + SubCommandOf<G> + 'static,
    {
        // Silently accepting a duplicate would make later registrations
        // unreachable because parsing stops at the first match. That's a
        // programmer error — fail loudly at startup.
        assert!(
            !self.subs.iter().any(|e| e.schema.name == name),
            "duplicate subcommand name: {name}",
        );
        let mut schema = S::schema();
        schema.name = name.to_string();
        if let Some(d) = description {
            schema.description = d.to_string();
        }
        let name_owned = schema.name.clone();
        let runner: Runner<G> = Box::new(move |global, parsed| {
            // S::from_parsed failures are parse-origin — wrap them with
            // subcommand context so the launcher picks the right help.
            // S::run failures are runtime — wrap them in Error::Runtime so
            // the launcher can tell them apart from parse variants even
            // when user code reuses e.g. MissingArgument for its own
            // validation.
            let sub = S::from_parsed(parsed).map_err(|e| Error::InSubcommand {
                path: vec![name_owned.clone()],
                source: Box::new(e),
            })?;
            sub.run(global).map_err(|e| Error::Runtime(Box::new(e)))
        });
        self.subs.push(Entry { schema, runner });
        self
    }

    /// Return the combined root + subcommand schema. Useful for tests and
    /// for introspection (e.g. generating shell completions in the
    /// future). Panics on the same invariants as execution — don't call
    /// this from production code if those might fire.
    pub fn schema(&self) -> CommandSchema {
        self.combined_schema()
    }

    fn combined_schema(&self) -> CommandSchema {
        let mut schema = G::schema();
        // A subcommand declared directly on G::schema() would not have a
        // runner registered here, so if parsing matched it run_args would
        // report `UnknownSubcommand` at dispatch time. Force users to
        // register subcommands via Launcher::command() where a runner is
        // always attached.
        assert!(
            schema.subcommands.is_empty(),
            "G::schema() must not declare subcommands directly; register them via Launcher::command()",
        );
        schema
            .subcommands
            .extend(self.subs.iter().map(|e| e.schema.clone()));
        schema
    }

    /// Parse `args` and run the matched subcommand. Use this in tests to
    /// exercise the launcher without touching the process environment.
    pub fn run_args(&self, args: &[String]) -> Result<()> {
        let schema = self.combined_schema();
        let parsed = OptionParser::parse(&schema, args)?;
        let global = G::from_parsed(&parsed)?;
        let (name, sub_parsed) = parsed
            .subcommand()
            .ok_or_else(|| Error::MissingSubcommand {
                available: self.subs.iter().map(|e| e.schema.name.clone()).collect(),
            })?;
        let entry = self
            .subs
            .iter()
            .find(|e| e.schema.name == name)
            .ok_or_else(|| Error::UnknownSubcommand {
                name: name.to_string(),
                available: self.subs.iter().map(|e| e.schema.name.clone()).collect(),
            })?;
        (entry.runner)(&global, sub_parsed)
    }

    /// Parse `std::env::args()`, dispatch to the matching subcommand, and
    /// exit. Prints help on `--help` and parse error messages to stderr
    /// before exiting. When the subcommand's own `run` returns an error
    /// (wrapped in `Error::Runtime` by the registered runner), that is
    /// treated as a runtime failure (exit code 1) without printing help,
    /// so legitimate runtime errors aren't reported as bad CLI syntax —
    /// even when the subcommand reuses parse-origin `Error` variants for
    /// its own post-parse validation.
    pub fn execute(self) -> ! {
        let args = env_args();
        let schema = self.combined_schema();
        let code = match self.run_args(&args) {
            Ok(()) => 0,
            Err(Error::Runtime(inner)) => {
                eprintln!("error: {inner}");
                1
            }
            Err(e) => report_error(e, &schema),
        };
        process::exit(code);
    }
}

/// Print a parse error with the most specific help schema available and
/// return the exit code to use. `HelpRequested` is not an error to the user,
/// so it exits 0.
fn report_error(err: Error, root: &CommandSchema) -> i32 {
    match err {
        Error::HelpRequested => {
            HelpPrinter::print(root);
            0
        }
        Error::InSubcommand { path, source } => {
            let composed = compose_help_schema(root, &path);
            let schema = composed.as_ref().unwrap_or(root);
            match *source {
                Error::HelpRequested => {
                    HelpPrinter::print(schema);
                    0
                }
                inner => {
                    eprintln!("error: {inner}");
                    HelpPrinter::print_error(schema);
                    2
                }
            }
        }
        other => {
            eprintln!("error: {other}");
            HelpPrinter::print_error(root);
            2
        }
    }
}

/// Build a help-only schema that represents `root ... path` as a single
/// command. The usage line reads e.g. `git clone [OPTIONS] <url>` or
/// `app <workspace> run [OPTIONS] <target>` — ancestor positionals and
/// subcommand names are folded into the composed schema's `name` so they
/// appear in the order the user must actually type them. Options from the
/// whole chain are merged into a single options list. The returned schema
/// is only suitable for help printing — it is not used for parsing.
fn compose_help_schema(root: &CommandSchema, path: &[String]) -> Option<CommandSchema> {
    let mut options = root.options.clone();
    let mut name_parts = vec![root.name.clone()];
    for arg in &root.arguments {
        name_parts.push(argument_display(arg));
    }

    let mut schema = root;
    for (i, sub_name) in path.iter().enumerate() {
        schema = schema.subcommands.iter().find(|s| s.name == *sub_name)?;
        options.extend(schema.options.iter().cloned());
        name_parts.push(sub_name.clone());
        // Intermediate subcommands' positionals come between this name and
        // the next subcommand. The deepest subcommand's arguments are left
        // in the composed schema's `arguments` so the help printer renders
        // them after `[OPTIONS]`.
        if i + 1 < path.len() {
            for arg in &schema.arguments {
                name_parts.push(argument_display(arg));
            }
        }
    }

    let mut composed = schema.clone();
    composed.name = name_parts.join(" ");
    composed.options = options;
    Some(composed)
}

fn argument_display(arg: &CLArgument) -> String {
    if arg.required {
        format!("<{}>", arg.name)
    } else {
        format!("[{}]", arg.name)
    }
}

fn env_args() -> Vec<String> {
    std::env::args().skip(1).collect()
}

/// Fetch `G::schema()` and assert it declares no subcommands. The root-only
/// `Launcher` path has no dispatch table, so a subcommand declared directly
/// on the schema would parse successfully but never execute — forcing
/// callers to register subcommands via `Launcher::command()` makes the
/// misuse impossible.
fn root_schema<G: Command>() -> CommandSchema {
    let schema = G::schema();
    assert!(
        schema.subcommands.is_empty(),
        "Launcher::<G> does not dispatch subcommands; register them via Launcher::command()",
    );
    schema
}

#[cfg(test)]
mod tests {
    use super::*;
    use runi_test::pretty_assertions::assert_eq;
    use std::cell::RefCell;

    // ----- Root-only command ---------------------------------------------

    struct Greeter {
        loud: bool,
        target: String,
    }

    impl Command for Greeter {
        fn schema() -> CommandSchema {
            CommandSchema::new("greet", "Say hello")
                .flag("-l,--loud", "Shout")
                .argument("target", "Who to greet")
        }

        fn from_parsed(p: &ParseResult) -> Result<Self> {
            Ok(Self {
                loud: p.flag("--loud"),
                target: p.require::<String>("target")?,
            })
        }
    }

    impl Runnable for Greeter {
        fn run(&self) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn root_command_parse() {
        let launcher = Launcher::<Greeter>::of();
        let g = launcher.parse(&["-l".into(), "world".into()]).unwrap();
        assert!(g.loud);
        assert_eq!(g.target, "world");
    }

    // ----- Subcommand mode -----------------------------------------------

    struct GitApp {
        verbose: bool,
    }

    impl Command for GitApp {
        fn schema() -> CommandSchema {
            CommandSchema::new("git", "VCS").flag("-v,--verbose", "Verbose")
        }

        fn from_parsed(p: &ParseResult) -> Result<Self> {
            Ok(Self {
                verbose: p.flag("--verbose"),
            })
        }
    }

    #[derive(Clone)]
    struct CloneCmd {
        url: String,
        depth: Option<u32>,
    }

    impl Command for CloneCmd {
        fn schema() -> CommandSchema {
            CommandSchema::new("clone", "Clone a repo")
                .option("--depth", "Clone depth")
                .argument("url", "Repository URL")
        }

        fn from_parsed(p: &ParseResult) -> Result<Self> {
            Ok(Self {
                url: p.require::<String>("url")?,
                depth: p.get::<u32>("--depth")?,
            })
        }
    }

    thread_local! {
        static CAPTURE: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    }

    impl SubCommandOf<GitApp> for CloneCmd {
        fn run(&self, global: &GitApp) -> Result<()> {
            CAPTURE.with(|c| {
                c.borrow_mut().push(format!(
                    "clone verbose={} url={} depth={:?}",
                    global.verbose, self.url, self.depth
                ))
            });
            Ok(())
        }
    }

    #[test]
    fn dispatch_subcommand_with_globals() {
        CAPTURE.with(|c| c.borrow_mut().clear());
        let launcher = Launcher::<GitApp>::of().command::<CloneCmd>("clone");
        launcher
            .run_args(&[
                "-v".into(),
                "clone".into(),
                "--depth".into(),
                "1".into(),
                "https://example.com".into(),
            ])
            .unwrap();
        CAPTURE.with(|c| {
            let captured = c.borrow();
            assert_eq!(captured.len(), 1);
            assert_eq!(
                captured[0],
                "clone verbose=true url=https://example.com depth=Some(1)"
            );
        });
    }

    #[test]
    fn missing_subcommand_error() {
        let launcher = Launcher::<GitApp>::of().command::<CloneCmd>("clone");
        let err = launcher.run_args(&[]).unwrap_err();
        assert!(matches!(err, Error::MissingSubcommand { .. }));
    }

    #[test]
    fn help_requested_error_propagates() {
        let launcher = Launcher::<GitApp>::of().command::<CloneCmd>("clone");
        let err = launcher.run_args(&["--help".into()]).unwrap_err();
        assert!(matches!(err, Error::HelpRequested));
    }

    #[test]
    fn subcommand_rejects_unknown_name() {
        let launcher = Launcher::<GitApp>::of().command::<CloneCmd>("clone");
        let err = launcher.run_args(&["nope".into()]).unwrap_err();
        match err {
            Error::UnknownSubcommand { name, .. } => assert_eq!(name, "nope"),
            other => panic!("unexpected: {other:?}"),
        }
    }

    // Sanity check that the from_parsed path reports invalid types with the
    // argument name, not just the FromStr::Err message.
    #[derive(Debug, Clone)]
    struct NeedsInt {
        n: u32,
    }

    impl Command for NeedsInt {
        fn schema() -> CommandSchema {
            CommandSchema::new("n", "").option("-n,--num", "a number")
        }

        fn from_parsed(p: &ParseResult) -> Result<Self> {
            Ok(Self {
                n: p.require::<u32>("--num")?,
            })
        }
    }
    impl Runnable for NeedsInt {
        fn run(&self) -> Result<()> {
            let _ = self.n;
            Ok(())
        }
    }

    // Subcommand whose run() returns a runtime error.
    struct FailingCmd;
    impl Command for FailingCmd {
        fn schema() -> CommandSchema {
            CommandSchema::new("fail", "always fails")
        }
        fn from_parsed(_: &ParseResult) -> Result<Self> {
            Ok(Self)
        }
    }
    impl SubCommandOf<GitApp> for FailingCmd {
        fn run(&self, _: &GitApp) -> Result<()> {
            Err(Error::custom("something went wrong"))
        }
    }

    #[test]
    fn runtime_error_is_not_a_parse_error() {
        let launcher = Launcher::<GitApp>::of().command::<FailingCmd>("fail");
        let err = launcher.run_args(&["fail".into()]).unwrap_err();
        assert!(!err.is_parse_error());
        // The runner wraps SubCommandOf::run errors in Error::Runtime so
        // the launcher can tell them apart from parse-origin variants.
        match err {
            Error::Runtime(inner) => assert!(matches!(*inner, Error::Custom(_))),
            other => panic!("expected Error::Runtime, got {other:?}"),
        }
    }

    // Subcommand whose run() returns a parse-origin variant for its own
    // validation, to confirm Error::Runtime wrapping classifies it as a
    // runtime failure.
    struct ValidatingCmd;
    impl Command for ValidatingCmd {
        fn schema() -> CommandSchema {
            CommandSchema::new("validate", "")
        }
        fn from_parsed(_: &ParseResult) -> Result<Self> {
            Ok(Self)
        }
    }
    impl SubCommandOf<GitApp> for ValidatingCmd {
        fn run(&self, _: &GitApp) -> Result<()> {
            // User code legitimately uses a parse-origin variant for its
            // own post-parse validation.
            Err(Error::MissingArgument("config".into()))
        }
    }

    #[test]
    fn subcommand_run_returning_parse_variant_is_still_runtime() {
        let launcher = Launcher::<GitApp>::of().command::<ValidatingCmd>("validate");
        let err = launcher.run_args(&["validate".into()]).unwrap_err();
        assert!(!err.is_parse_error());
        match err {
            Error::Runtime(inner) => {
                assert!(matches!(*inner, Error::MissingArgument(_)));
            }
            other => panic!("expected Error::Runtime, got {other:?}"),
        }
    }

    // Subcommand that requires an argument — exercises parse-error wrapping
    // from inside the runner (S::from_parsed path).
    #[derive(Debug)]
    struct Needy {
        _name: String,
    }
    impl Command for Needy {
        fn schema() -> CommandSchema {
            CommandSchema::new("needy", "").argument("name", "required")
        }
        fn from_parsed(p: &ParseResult) -> Result<Self> {
            Ok(Self {
                _name: p.require::<String>("name")?,
            })
        }
    }
    impl SubCommandOf<GitApp> for Needy {
        fn run(&self, _: &GitApp) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn subcommand_from_parsed_error_wrapped_with_context() {
        // The parser accepts `needy` with no further args (the positional is
        // declared on the subcommand schema but nothing violates parse shape
        // there), so the MissingArgument surfaces from the runner's call to
        // from_parsed and must be wrapped with the subcommand path for the
        // launcher to pick the right help schema.
        let launcher = Launcher::<GitApp>::of().command::<Needy>("needy");
        let err = launcher.run_args(&["needy".into()]).unwrap_err();
        match err {
            Error::InSubcommand { path, source } => {
                assert_eq!(path, vec!["needy".to_string()]);
                assert!(matches!(*source, Error::MissingArgument(_)));
            }
            other => panic!("expected InSubcommand, got {other:?}"),
        }
    }

    #[test]
    #[should_panic(expected = "duplicate subcommand name: clone")]
    fn duplicate_subcommand_registration_panics() {
        let _ = Launcher::<GitApp>::of()
            .command::<CloneCmd>("clone")
            .command::<CloneCmd>("clone");
    }

    struct AppWithStubSub;
    impl Command for AppWithStubSub {
        fn schema() -> CommandSchema {
            CommandSchema::new("app", "").subcommand(CommandSchema::new("clone", "stub"))
        }
        fn from_parsed(_: &ParseResult) -> Result<Self> {
            Ok(Self)
        }
    }

    // Root-only Launcher must also reject G::schema() declaring subcommands
    // — there is no dispatch table in that mode, so it would silently ignore
    // user input.
    struct RunnableStubSub;
    impl Command for RunnableStubSub {
        fn schema() -> CommandSchema {
            CommandSchema::new("app", "").subcommand(CommandSchema::new("clone", "stub"))
        }
        fn from_parsed(_: &ParseResult) -> Result<Self> {
            Ok(Self)
        }
    }
    impl Runnable for RunnableStubSub {
        fn run(&self) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    #[should_panic(expected = "Launcher::<G> does not dispatch subcommands")]
    fn root_launcher_rejects_schema_declared_subcommands() {
        let _ = Launcher::<RunnableStubSub>::of().parse(&[]);
    }

    #[test]
    #[should_panic(expected = "G::schema() must not declare subcommands")]
    fn schema_declared_subcommands_panic() {
        // combined_schema runs at parse time. Declaring a subcommand
        // directly on G::schema() is unsafe because no runner is
        // registered for it — reject up front.
        let launcher = Launcher::<AppWithStubSub>::of().command::<CloneCmd>("clone");
        let _ = launcher.run_args(&["clone".into()]);
    }

    // Dummy SubCommandOf<AppWithStubSub> impl so the Launcher registration
    // compiles; the panic in combined_schema fires before dispatch.
    impl SubCommandOf<AppWithStubSub> for CloneCmd {
        fn run(&self, _: &AppWithStubSub) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn compose_help_schema_prefixes_root_name_and_options() {
        let root = CommandSchema::new("git", "").flag("-v,--verbose", "Verbose");
        let sub = CommandSchema::new("clone", "Clone a repo").argument("url", "URL");
        let mut with_sub = root.clone();
        with_sub.subcommands.push(sub);
        let composed =
            compose_help_schema(&with_sub, &["clone".to_string()]).expect("must resolve");
        assert_eq!(composed.name, "git clone");
        // Root's --verbose must appear alongside clone's own options.
        assert!(composed.options.iter().any(|o| o.matches_long("verbose")));
        // Clone's own positional must be preserved.
        assert!(composed.arguments.iter().any(|a| a.name == "url"));
    }

    #[test]
    fn compose_help_schema_folds_root_positionals_into_name() {
        // `app <workspace> run <target>` — the root has a positional that
        // must appear before the subcommand name in the usage line.
        let root = CommandSchema::new("app", "").argument("workspace", "");
        let sub = CommandSchema::new("run", "").argument("target", "");
        let mut with_sub = root.clone();
        with_sub.subcommands.push(sub);
        let composed = compose_help_schema(&with_sub, &["run".to_string()]).expect("must resolve");
        assert_eq!(composed.name, "app <workspace> run");
        // The deepest subcommand's own arguments stay in `arguments` so the
        // help printer renders them after `[OPTIONS]` in the usage line.
        assert_eq!(composed.arguments.len(), 1);
        assert_eq!(composed.arguments[0].name, "target");
    }

    #[test]
    fn invalid_value_error_is_informative() {
        let launcher = Launcher::<NeedsInt>::of();
        let err = launcher.parse(&["--num".into(), "abc".into()]).unwrap_err();
        match err {
            Error::InvalidValue { name, value, .. } => {
                assert_eq!(name, "--num");
                assert_eq!(value, "abc");
            }
            other => panic!("unexpected: {other:?}"),
        }
    }
}