ctl-core 0.7.2

A framework for clap programs: typed results, help, and terminal or JSON output
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! A CLI's commands and flags as plain data, taken from its Clap types.
//!
//! Clap remains the command grammar. [`Surface`] lists what a user of the CLI
//! sees, for generated documentation files and the tests that compare them
//! with the CLI. It holds the binary name, the mise task name, every command
//! and alias, every argument, the Usage KDL, and the `#USAGE mount` line (see
//! [`usage`]).
//!
//! The `surface-model` feature builds a [`Surface`]. `surface-serde` adds
//! serialization. `surface-templates` adds the shared `minijinja` fragments
//! and the [`render`] function. A generated documentation file is then a
//! render of the CLI's own Clap types.
#![cfg_attr(
    not(feature = "surface-templates"),
    doc = "",
    doc = "[`render`]: crate#cargo-features"
)]

use std::collections::{BTreeMap, BTreeSet};

use clap::{Arg, Command};

use crate::usage;

#[cfg(feature = "surface-templates")]
mod templates;
#[cfg(feature = "surface-templates")]
pub use templates::{
    COMMANDS_FRAGMENT, INVOCATION_FRAGMENT, VERSION_FRAGMENT, add_fragments, environment, render,
};

/// What a user sees of one Clap command tree.
///
/// Build it with [`Surface::new`] or [`Surface::from_command`]. It is plain
/// data: a test compares a render of it with a committed file, and a template
/// reads its fields. A field can join it in a minor release.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "surface-serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Surface {
    /// Executable name declared by the root Clap command.
    pub binary: String,
    /// The mise task name that runs the CLI.
    pub mount: String,
    /// Root command description.
    pub about: String,
    /// Root package version, when Clap declares one.
    pub version: Option<String>,
    /// Arguments and flags declared directly on the root, in Clap order.
    pub arguments: Vec<SurfaceArgument>,
    /// Ancestor global arguments, always empty for the root.
    pub inherited_arguments: Vec<SurfaceArgument>,
    /// Root subcommands in Clap declaration order, including hidden commands.
    pub commands: Vec<SurfaceCommand>,
    /// Usage KDL for the mise task name.
    pub usage_kdl: String,
    /// The exact `#USAGE mount` line for the mise task.
    pub mount_line: String,
    /// Prose the CLI adds by name, for its documentation templates.
    pub notes: BTreeMap<String, String>,
}

/// One command in a [`Surface`], which [`Surface::new`] builds. A field can
/// join it in a minor release.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "surface-serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct SurfaceCommand {
    /// Command name.
    pub name: String,
    /// Full command path below the root.
    pub path: String,
    /// All declared aliases, including hidden aliases.
    pub aliases: Vec<String>,
    /// Aliases Clap exposes in help and completion.
    pub visible_aliases: Vec<String>,
    /// Whether Clap hides this command.
    pub hidden: bool,
    /// Command description.
    pub about: String,
    /// Arguments and flags declared directly on this command, in Clap order.
    ///
    /// Ancestor globals remain on their declaring command instead of being
    /// duplicated into every descendant.
    pub arguments: Vec<SurfaceArgument>,
    /// Ancestor global arguments this command also accepts, root-first.
    pub inherited_arguments: Vec<SurfaceArgument>,
    /// Nested subcommands in Clap declaration order.
    pub commands: Vec<Self>,
}

/// One positional argument or flag in a [`Surface`], which [`Surface::new`]
/// builds. A field can join it in a minor release.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "surface-serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct SurfaceArgument {
    /// Clap argument identifier.
    pub id: String,
    /// Positional index, absent for options and flags.
    pub index: Option<usize>,
    /// Short flag name.
    pub short: Option<char>,
    /// Long flag name without leading dashes.
    pub long: Option<String>,
    /// Visible short aliases.
    pub visible_short_aliases: Vec<char>,
    /// All short aliases, including hidden aliases.
    pub short_aliases: Vec<char>,
    /// Visible long aliases.
    pub visible_aliases: Vec<String>,
    /// All long aliases, including hidden aliases.
    pub aliases: Vec<String>,
    /// Value names shown by Clap.
    pub value_names: Vec<String>,
    /// Argument description.
    pub help: String,
    /// Whether Clap requires the argument.
    pub requirement: SurfaceRequirement,
    /// Whether Clap propagates the argument to subcommands.
    pub scope: SurfaceScope,
    /// Whether Clap hides the argument.
    pub hidden: bool,
    /// Whether the argument action accepts values.
    pub takes_values: bool,
}

/// Whether Clap requires an argument, as [`SurfaceArgument::requirement`]
/// reports.
///
/// The set is closed, and the enum is not `#[non_exhaustive]`: Clap marks an
/// argument required or leaves it optional.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "surface-serde", derive(serde::Serialize))]
#[cfg_attr(feature = "surface-serde", serde(rename_all = "snake_case"))]
pub enum SurfaceRequirement {
    /// The invocation can omit this argument.
    Optional,
    /// The invocation must provide this argument.
    Required,
}

/// How far Clap propagates an argument, as [`SurfaceArgument::scope`]
/// reports.
///
/// The set is closed, and the enum is not `#[non_exhaustive]`: Clap marks an
/// argument global or leaves it on its own command.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "surface-serde", derive(serde::Serialize))]
#[cfg_attr(feature = "surface-serde", serde(rename_all = "snake_case"))]
pub enum SurfaceScope {
    /// The argument belongs only to its declaring command.
    Local,
    /// The argument remains available to nested commands.
    Global,
}

impl Surface {
    /// The surface of the Clap parser type `C`.
    ///
    /// `mount` is the mise task name that runs the CLI, such as `toy` in
    /// `mise run toy status`. See [`Self::from_command`].
    #[must_use]
    pub fn new<C: clap::CommandFactory>(mount: impl Into<String>) -> Self {
        Self::from_command(C::command(), mount)
    }

    /// The surface of a Clap command tree.
    ///
    /// `mount` is the mise task name that runs the CLI. The Usage KDL and the
    /// `#USAGE mount` line use it. Hidden commands are listed with `hidden`
    /// set. The Usage KDL holds the `-h/--help` flag and `help` subcommand
    /// ctl-core declares on every command, as
    /// [`apply_defaults`](crate::parser::apply_defaults) does for parsing. The
    /// lists of arguments and commands leave them out.
    #[must_use]
    pub fn from_command(command: Command, mount: impl Into<String>) -> Self {
        let mut declared_arguments = BTreeMap::new();
        let mut help_settings = BTreeMap::new();
        collect_declarations(&command, "", &mut declared_arguments, &mut help_settings);
        let mut command = crate::parser::with_help(command);
        command.build();
        let command = restore_help_settings(command, "", &help_settings);
        let mount = mount.into();
        let binary = command.get_name().to_owned();
        let about = command
            .get_about()
            .map(ToString::to_string)
            .unwrap_or_default();
        let version = command.get_version().map(ToOwned::to_owned);
        let arguments = declared_arguments_for(&command, "", &declared_arguments);
        let inherited_arguments = arguments
            .iter()
            .filter(|argument| argument.scope == SurfaceScope::Global)
            .cloned()
            .collect::<Vec<_>>();
        let commands = command
            .get_subcommands()
            .filter(|child| declared_arguments.contains_key(child.get_name()))
            .map(|child| surface_command(child, "", &declared_arguments, &inherited_arguments))
            .collect();
        let usage_kdl = usage::spec(command, &mount);
        let mount_line = usage::mount_line(&mount);
        Self {
            binary,
            mount,
            about,
            version,
            arguments,
            inherited_arguments: Vec::new(),
            commands,
            usage_kdl,
            mount_line,
            notes: BTreeMap::new(),
        }
    }

    /// Add the CLI's own prose under `name`, for one template section or
    /// reader. A template reads it as `surface.notes.<name>`. A later note of
    /// the same name replaces an earlier one.
    #[must_use]
    pub fn note(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.notes.insert(name.into(), value.into());
        self
    }

    /// Long flags that have no short, as `(command path, long name)`.
    ///
    /// The root path is empty. Inherited globals are not repeated on children.
    /// Hidden flags are included so a long-only option cannot hide from the
    /// check. [`FormatLong`](crate::flags::FormatLong) and
    /// [`ColorLong`](crate::flags::ColorLong) leave `--format` / `--color`
    /// without shorts on purpose; pass those names to [`Self::require_shorts`].
    #[must_use]
    pub fn long_options_without_short(&self) -> Vec<(String, String)> {
        let mut missing = Vec::new();
        collect_missing_shorts("", &self.arguments, &mut missing);
        for command in &self.commands {
            collect_command_missing_shorts(command, &mut missing);
        }
        missing
    }

    /// Fail when a long option has no visible short, except tokens in
    /// `allow`.
    ///
    /// A root allowance is the displayed long option (`--format`). A nested
    /// allowance includes its command path (`status --archived`). ctl-core's
    /// shared flags that leave a letter free for the CLI on purpose
    /// (`--format` for `-f`/`--file`, `--color` for `-c`) belong there.
    ///
    /// # Errors
    ///
    /// Returns a message that lists every long option without a short,
    /// outside `allow`.
    pub fn require_shorts<'a>(
        &self,
        allow: impl IntoIterator<Item = &'a str>,
    ) -> Result<(), String> {
        let allowed: BTreeSet<&str> = allow.into_iter().collect();
        let missing: Vec<(String, String)> = self
            .long_options_without_short()
            .into_iter()
            .filter(|(path, long)| !allowed.contains(scoped_long(path, long).as_str()))
            .collect();
        if missing.is_empty() {
            return Ok(());
        }
        let listing = missing
            .iter()
            .map(|(path, long)| {
                if path.is_empty() {
                    format!("--{long}")
                } else {
                    format!("{path} --{long}")
                }
            })
            .collect::<Vec<_>>()
            .join(", ");
        Err(format!("long option has no short: {listing}"))
    }
}

fn scoped_long(path: &str, long: &str) -> String {
    if path.is_empty() {
        format!("--{long}")
    } else {
        format!("{path} --{long}")
    }
}

fn collect_missing_shorts(
    path: &str,
    arguments: &[SurfaceArgument],
    missing: &mut Vec<(String, String)>,
) {
    for argument in arguments {
        if let Some(long) = &argument.long
            && argument.short.is_none()
            && argument.visible_short_aliases.is_empty()
        {
            missing.push((path.to_owned(), long.clone()));
        }
    }
}

fn collect_command_missing_shorts(command: &SurfaceCommand, missing: &mut Vec<(String, String)>) {
    collect_missing_shorts(&command.path, &command.arguments, missing);
    for child in &command.commands {
        collect_command_missing_shorts(child, missing);
    }
}

fn surface_command(
    command: &Command,
    parent: &str,
    declared_arguments: &BTreeMap<String, BTreeSet<String>>,
    inherited_arguments: &[SurfaceArgument],
) -> SurfaceCommand {
    let name = command.get_name().to_owned();
    let path = if parent.is_empty() {
        name.clone()
    } else {
        format!("{parent} {name}")
    };
    let arguments = declared_arguments_for(command, &path, declared_arguments);
    let mut child_inherited_arguments = inherited_arguments.to_vec();
    child_inherited_arguments.extend(
        arguments
            .iter()
            .filter(|argument| argument.scope == SurfaceScope::Global)
            .cloned(),
    );
    SurfaceCommand {
        name,
        path: path.clone(),
        aliases: command.get_all_aliases().map(ToOwned::to_owned).collect(),
        visible_aliases: command
            .get_visible_aliases()
            .map(ToOwned::to_owned)
            .collect(),
        hidden: command.is_hide_set(),
        about: command
            .get_about()
            .map(ToString::to_string)
            .unwrap_or_default(),
        arguments,
        inherited_arguments: inherited_arguments.to_vec(),
        commands: command
            .get_subcommands()
            .filter(|child| {
                declared_arguments.contains_key(&format!("{path} {}", child.get_name()))
            })
            .map(|child| {
                surface_command(child, &path, declared_arguments, &child_inherited_arguments)
            })
            .collect(),
    }
}

fn declared_arguments_for(
    command: &Command,
    path: &str,
    declared_arguments: &BTreeMap<String, BTreeSet<String>>,
) -> Vec<SurfaceArgument> {
    command
        .get_arguments()
        .filter(|argument| declared_argument(declared_arguments, path, argument))
        .map(argument)
        .collect()
}

fn collect_declarations(
    command: &Command,
    path: &str,
    declared_arguments: &mut BTreeMap<String, BTreeSet<String>>,
    help_settings: &mut BTreeMap<String, HelpSettings>,
) {
    declared_arguments.insert(
        path.to_owned(),
        command
            .get_arguments()
            .map(|argument| argument.get_id().to_string())
            .collect(),
    );
    let owns_help_flag = command
        .get_arguments()
        .any(|argument| argument.get_id() == "help");
    let owns_help_subcommand = command.find_subcommand("help").is_some();
    help_settings.insert(
        path.to_owned(),
        HelpSettings {
            flag_off: command.is_disable_help_flag_set() && !owns_help_flag,
            subcommand_off: command.is_disable_help_subcommand_set() && !owns_help_subcommand,
        },
    );
    for child in command
        .get_subcommands()
        .filter(|child| !crate::parser::is_generated_help(child))
    {
        let child_path = child_path(path, child.get_name());
        collect_declarations(child, &child_path, declared_arguments, help_settings);
    }
}

fn child_path(path: &str, name: &str) -> String {
    if path.is_empty() {
        name.to_owned()
    } else {
        format!("{path} {name}")
    }
}

/// Whether a command turned off its help flag and its `help` subcommand.
///
/// Clap's build turns both off on every command when its `help` feature is
/// off. ctl-core turns them off where it declares its own. Only the command
/// as declared holds what the CLI turned off. A command that already holds a
/// `help` argument or subcommand did not turn that one off.
#[derive(Clone, Copy, Debug)]
struct HelpSettings {
    flag_off: bool,
    subcommand_off: bool,
}

/// `command` after its build, with the help settings each declared command
/// had put back, so the Usage KDL records only what the CLI turned off. The
/// `help` subcommands ctl-core generates were not declared, and keep the
/// settings that turn help off, as Clap's own do.
fn restore_help_settings(
    command: Command,
    path: &str,
    help_settings: &BTreeMap<String, HelpSettings>,
) -> Command {
    let command = match help_settings.get(path) {
        Some(declared) => command
            .disable_help_flag(declared.flag_off)
            .disable_help_subcommand(declared.subcommand_off),
        None => command,
    };
    command.mut_subcommands(|child| {
        let child_path = child_path(path, child.get_name());
        restore_help_settings(child, &child_path, help_settings)
    })
}

fn declared_argument(
    declared_arguments: &BTreeMap<String, BTreeSet<String>>,
    path: &str,
    argument: &Arg,
) -> bool {
    declared_arguments
        .get(path)
        .is_some_and(|arguments| arguments.contains(argument.get_id().as_str()))
}

fn argument(argument: &Arg) -> SurfaceArgument {
    SurfaceArgument {
        id: argument.get_id().to_string(),
        index: argument.get_index(),
        short: argument.get_short(),
        long: argument.get_long().map(ToOwned::to_owned),
        visible_short_aliases: argument.get_visible_short_aliases().unwrap_or_default(),
        short_aliases: argument.get_all_short_aliases().unwrap_or_default(),
        visible_aliases: argument
            .get_visible_aliases()
            .unwrap_or_default()
            .iter()
            .map(|alias| (*alias).to_owned())
            .collect(),
        aliases: argument
            .get_all_aliases()
            .unwrap_or_default()
            .iter()
            .map(|alias| (*alias).to_owned())
            .collect(),
        value_names: argument
            .get_value_names()
            .unwrap_or_default()
            .iter()
            .map(ToString::to_string)
            .collect(),
        help: argument
            .get_help()
            .map(ToString::to_string)
            .unwrap_or_default(),
        requirement: if argument.is_required_set() {
            SurfaceRequirement::Required
        } else {
            SurfaceRequirement::Optional
        },
        scope: if argument.is_global_set() {
            SurfaceScope::Global
        } else {
            SurfaceScope::Local
        },
        hidden: argument.is_hide_set(),
        takes_values: argument.get_action().takes_values(),
    }
}

#[cfg(test)]
mod tests {
    use clap::{ArgAction, CommandFactory, Parser, Subcommand};
    #[cfg(feature = "surface-templates")]
    use indoc::indoc;
    #[cfg(feature = "surface-templates")]
    use serde::Serialize;

    #[cfg(feature = "surface-templates")]
    use super::render;
    use super::{Surface, SurfaceArgument, SurfaceScope};

    #[derive(Parser)]
    #[command(name = "toy", version = "1.2.3", about = "Control toys")]
    struct Cli {
        #[arg(short, long, global = true, help = "Select a profile")]
        profile: Option<String>,
        #[command(subcommand)]
        command: Commands,
    }

    #[derive(Subcommand)]
    enum Commands {
        /// Show current state.
        #[command(alias = "state", visible_alias = "ls")]
        Status {
            /// Include archived records.
            #[arg(long, action = ArgAction::SetTrue)]
            archived: bool,
        },
        /// Mutate one item.
        Item {
            #[command(subcommand)]
            command: ItemCommand,
        },
        #[command(hide = true)]
        Internal,
    }

    #[derive(Subcommand)]
    enum ItemCommand {
        /// Create one item.
        Add {
            /// Item name.
            name: String,
        },
    }

    #[test]
    fn extracts_the_complete_clap_surface() {
        let surface = Surface::new::<Cli>("t");
        assert_eq!(surface.binary, "toy");
        assert_eq!(surface.mount, "t");
        assert_eq!(surface.version.as_deref(), Some("1.2.3"));
        assert_eq!(surface.about, "Control toys");
        assert_eq!(
            surface.inherited_arguments.as_slice(),
            <&[SurfaceArgument]>::default()
        );
        assert!(surface.usage_kdl.contains("status"));
        assert_eq!(
            surface.mount_line,
            r#"#USAGE mount "mise run --quiet t -- --usage-spec=t""#
        );
        let status = &surface.commands[0];
        assert_eq!(status.visible_aliases, ["ls"]);
        assert_eq!(status.aliases, ["state", "ls"]);
        assert_eq!(status.about, "Show current state");
        assert_eq!(status.arguments[0].long.as_deref(), Some("archived"));
        assert!(!status.arguments[0].takes_values);
        assert_eq!(status.arguments.len(), 1);
        assert_eq!(status.inherited_arguments.len(), 1);
        assert_eq!(
            status.inherited_arguments[0].long.as_deref(),
            Some("profile")
        );
        assert_eq!(status.inherited_arguments[0].scope, SurfaceScope::Global);
        assert!(
            status
                .arguments
                .iter()
                .all(|argument| !matches!(argument.id.as_str(), "help" | "version" | "profile"))
        );
        let item = &surface.commands[1];
        assert_eq!(item.commands[0].path, "item add");
        assert_eq!(item.commands[0].arguments[0].index, Some(1));
        assert_eq!(item.commands[0].inherited_arguments.len(), 1);
        assert_eq!(
            item.commands[0].inherited_arguments[0].long.as_deref(),
            Some("profile")
        );
        assert!(surface.commands[2].hidden);
        assert!(
            surface
                .arguments
                .iter()
                .any(|arg| arg.long.as_deref() == Some("profile"))
        );
        assert!(
            surface
                .arguments
                .iter()
                .all(|argument| !matches!(argument.id.as_str(), "help" | "version"))
        );
        let noted = surface.note("skill", "Prefer the mounted task.");
        assert_eq!(noted.notes["skill"], "Prefer the mounted task.");
    }

    /// The `-h/--help` flags and `help` command lines in a Usage KDL.
    fn help_lines(usage: &str) -> (usize, usize) {
        let lines = usage.lines().map(str::trim_start);
        let flags = lines
            .clone()
            .filter(|line| line.starts_with(r#"flag "-h --help""#) && line.contains("action=help"))
            .count();
        let commands = lines.filter(|line| line.starts_with("cmd help ")).count();
        (flags, commands)
    }

    /// Clap's `help` feature stays off in every ctl-core build. The Usage KDL
    /// holds the `-h/--help` flag and `help` subcommand ctl-core declares, as
    /// a build with that feature holds Clap's own. Only the `help`
    /// subcommands and their copies turn help off, as in that build.
    #[test]
    fn usage_kdl_keeps_the_declared_help() {
        let usage = Surface::new::<Cli>("t").usage_kdl;
        assert_eq!(help_lines(&usage), (5, 4), "{usage}");
        assert!(
            !usage.lines().any(|line| line.starts_with("disable_help")),
            "{usage}"
        );
        for declared in ["cmd status ", "cmd item ", "cmd add ", "cmd internal "] {
            assert!(
                usage
                    .lines()
                    .map(str::trim_start)
                    .any(|line| { line.starts_with(declared) && !line.contains("disable_help") }),
                "{declared}in {usage}"
            );
        }
        let applied = Surface::from_command(crate::parser::apply_defaults(Cli::command()), "t");
        assert_eq!(
            help_lines(&applied.usage_kdl),
            (5, 4),
            "{}",
            applied.usage_kdl
        );
        assert!(
            !applied
                .usage_kdl
                .lines()
                .any(|line| line.starts_with("disable_help")),
            "{}",
            applied.usage_kdl
        );
        for setting in ["disable_help_flag=#true", "disable_help_subcommand=#true"] {
            assert_eq!(
                applied.usage_kdl.matches(setting).count(),
                usage.matches(setting).count(),
                "{setting} in {}",
                applied.usage_kdl
            );
        }
    }

    #[cfg(feature = "surface-templates")]
    #[derive(Serialize)]
    struct Content<'a> {
        version: &'a str,
        invocations: [&'a str; 2],
    }

    #[cfg(feature = "surface-templates")]
    #[test]
    fn shared_fragments_render_committed_operator_blocks() {
        let surface = Surface::new::<Cli>("t");
        let template = indoc! {r#"
            {%- from "ctl/version.md.jinja" import version_line -%}
            {%- from "ctl/invocation.md.jinja" import mounted_invocation -%}
            {%- from "ctl/commands.md.jinja" import command_inventory -%}
            ---
            {{ version_line(content.version) }}
            ---

            {{ mounted_invocation(surface, content.invocations) }}

            {{ command_inventory(surface) -}}
        "#};
        let rendered = render(
            "operator.md.jinja",
            template,
            &surface,
            &Content {
                version: "1.2.3",
                invocations: ["status", "item add demo"],
            },
        )
        .unwrap_or_else(|error| panic!("render operator template: {error}"));
        let expected = indoc! {r"
            ---
            version: 1.2.3
            ---

            ## Invocation

            ```sh
            mise run t status
            mise run t item add demo
            ```

            Never `mise run t --`.

            The `--` in `#USAGE mount` is mise's completion bootstrap.

            ## Commands

            | Command | Aliases | Purpose |
            |:--|:--|:--|
            | `status` | `ls` | Show current state |
            | `item` | — | Mutate one item |
        "};
        assert_eq!(rendered, expected);
        assert!(!rendered.contains("internal"));
    }

    #[test]
    fn long_only_status_flag_fails_require_shorts() {
        let error = Surface::new::<Cli>("t")
            .require_shorts([])
            .expect_err("archived is long-only");
        assert!(error.contains("--archived"), "{error}");
    }

    #[derive(Parser)]
    struct ShortsCli {
        #[arg(long, global = true)]
        verbose: bool,
        #[command(subcommand)]
        command: ShortsCommand,
    }

    #[derive(Subcommand)]
    enum ShortsCommand {
        Status {
            #[arg(long)]
            archived: bool,
        },
        #[command(hide = true)]
        Internal {
            #[arg(long)]
            secret: bool,
        },
    }

    #[test]
    fn reports_hidden_flags_and_inherited_globals_once() {
        let surface = Surface::new::<ShortsCli>("t");
        assert_eq!(
            surface.long_options_without_short(),
            [
                (String::new(), "verbose".to_owned()),
                ("status".to_owned(), "archived".to_owned()),
                ("internal".to_owned(), "secret".to_owned()),
            ]
        );
        let error = surface
            .require_shorts([])
            .expect_err("three flags are long-only");
        assert_eq!(
            error,
            "long option has no short: --verbose, status --archived, internal --secret"
        );
    }

    #[test]
    fn require_shorts_accepts_an_allow_list() {
        Surface::new::<ShortsCli>("t")
            .require_shorts(["--verbose", "status --archived", "internal --secret"])
            .unwrap_or_else(|error| panic!("{error}"));
    }

    #[test]
    fn a_root_allowance_does_not_exempt_a_nested_flag() {
        let error = Surface::new::<ShortsCli>("t")
            .require_shorts(["--verbose", "--archived", "internal --secret"])
            .expect_err("archived needs its command path");
        assert_eq!(error, "long option has no short: status --archived");
    }

    #[derive(Parser)]
    struct ShortAliasCli {
        #[arg(long, visible_short_alias = 'x')]
        expanded: bool,
    }

    #[test]
    fn a_short_alias_satisfies_the_contract() {
        Surface::new::<ShortAliasCli>("t")
            .require_shorts([])
            .unwrap_or_else(|error| panic!("{error}"));
    }

    #[derive(Parser)]
    struct HiddenShortAliasCli {
        #[arg(long, short_alias = 'x')]
        expanded: bool,
    }

    #[test]
    fn a_hidden_short_alias_is_not_an_operator_short() {
        let error = Surface::new::<HiddenShortAliasCli>("t")
            .require_shorts([])
            .expect_err("the only short is hidden");
        assert_eq!(error, "long option has no short: --expanded");
    }

    #[derive(Parser)]
    struct OwnedFile {
        #[command(flatten)]
        format: crate::flags::FormatLong,
        #[command(flatten)]
        color: crate::flags::ColorLong,
        #[arg(short = 'f', long)]
        file: Option<String>,
        #[arg(short = 'c', long)]
        config: Option<String>,
    }

    #[test]
    fn format_long_and_color_long_are_the_allow_list() {
        let surface = Surface::new::<OwnedFile>("x");
        let error = surface
            .require_shorts([])
            .expect_err("format/color/no-color are long-only");
        assert!(error.contains("--format"), "{error}");
        assert!(error.contains("--color"), "{error}");
        assert!(error.contains("--no-color"), "{error}");
        surface
            .require_shorts(["--format", "--color", "--no-color"])
            .unwrap_or_else(|error| panic!("{error}"));
    }

    #[derive(Parser)]
    struct DefaultOutput {
        #[command(flatten)]
        output: crate::flags::OutputArgs,
    }

    #[test]
    fn output_args_only_exempt_no_color() {
        Surface::new::<DefaultOutput>("x")
            .require_shorts(["--no-color"])
            .unwrap_or_else(|error| panic!("{error}"));
    }

    #[cfg(feature = "surface-serde")]
    #[test]
    fn surface_serde_does_not_require_templates() {
        fn assert_serializable<T: serde::Serialize>() {}
        assert_serializable::<Surface>();
    }
}