Skip to main content

usage/spec/
cmd.rs

1use std::collections::HashMap;
2use std::sync::OnceLock;
3
4use crate::error::UsageErr;
5use crate::kdl::{KdlDocument, KdlEntry, KdlNode};
6use crate::sh::sh;
7use crate::spec::builder::SpecCommandBuilder;
8use crate::spec::clause::SpecClause;
9use crate::spec::context::ParsingContext;
10use crate::spec::effect::{SpecCommandEffect, EFFECT_VALUES};
11use crate::spec::exit_code::SpecExitCode;
12use crate::spec::flagset::SpecUse;
13use crate::spec::group::SpecGroup;
14use crate::spec::helpers::{string_entry, NodeHelper};
15use crate::spec::is_false;
16use crate::spec::mount::SpecMount;
17use crate::spec::output::SpecOutput;
18use crate::spec::unknown_flags::UnknownFlags;
19use crate::{Spec, SpecArg, SpecComplete, SpecFlag};
20use indexmap::IndexMap;
21use itertools::Itertools;
22use serde::Serialize;
23
24/// A CLI command or subcommand specification.
25///
26/// Commands define the structure of a CLI, including their flags, arguments,
27/// and nested subcommands. The root command represents the main CLI entry point.
28///
29/// # Example
30///
31/// ```
32/// use usage::{SpecCommand, SpecFlag, SpecArg};
33///
34/// let cmd = SpecCommand::builder()
35///     .name("install")
36///     .help("Install a package")
37///     .alias("i")
38///     .flag(SpecFlag::builder().short('f').long("force").build())
39///     .arg(SpecArg::builder().name("package").required(true).build())
40///     .build();
41/// ```
42#[derive(Debug, Serialize, Clone)]
43pub struct SpecCommand {
44    /// Full command path from root (e.g., ["git", "remote", "add"])
45    pub full_cmd: Vec<String>,
46    /// Generated usage string
47    pub usage: String,
48    /// Nested subcommands indexed by name
49    pub subcommands: IndexMap<String, SpecCommand>,
50    /// Positional arguments for this command
51    pub args: Vec<SpecArg>,
52    /// A repeatable separator-delimited positional group.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub clause: Option<SpecClause>,
55    /// Flags/options for this command
56    pub flags: Vec<SpecFlag>,
57    /// Flagsets this command pulls in, and where in [`Self::flags`] they belong.
58    ///
59    /// `pub(crate)` because it is always empty by the time anyone else can see it: a `use` is
60    /// resolved while the spec is read, so a consumer holding a `SpecCommand` holds the flags
61    /// the sets named. Visible to the rest of the crate only so that other modules can
62    /// destructure `SpecCommand` exhaustively.
63    #[serde(skip)]
64    pub(crate) uses: Vec<SpecUse>,
65    /// Mounted external specs
66    pub mounts: Vec<SpecMount>,
67    /// Sets of flags that relate to one another as a set.
68    ///
69    /// Pairwise [`conflicts`](SpecFlag::conflicts) can say everything a plain group says
70    /// and cannot say `required`: "one of these is needed" is a statement about the set.
71    #[serde(skip_serializing_if = "Vec::is_empty")]
72    pub groups: Vec<SpecGroup>,
73    /// Deprecation message if this command is deprecated
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub deprecated: Option<String>,
76    /// Version at which consumers should begin warning about this command.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub deprecated_warn_at: Option<String>,
79    /// Version at which consumers expect this command to be removed.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub deprecated_remove_at: Option<String>,
82    /// What running this command does to the world: read, write or destructive.
83    /// Not inherited by subcommands.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub effect: Option<SpecCommandEffect>,
86    /// What to do here with a flag-like token that names no declared flag.
87    ///
88    /// Unset means "whatever encloses this command decided" — the nearest command
89    /// above that set one, or failing that the spec, or failing that
90    /// [`UnknownFlags::Value`]. Unlike [`SpecCommandEffect`] this *is* inherited,
91    /// because it describes how a command line is read rather than what a command
92    /// does, and a CLI that forwards options generally forwards them everywhere.
93    pub unknown_flags: Option<UnknownFlags>,
94    /// Whether to hide this command from help output
95    pub hide: bool,
96    /// Help section this command appears under in its parent's command list.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub help_heading: Option<String>,
99    /// Named audience or contract surface this command belongs to. Metadata only.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub surface: Option<String>,
102    /// Descriptive conditions under which this command is available.
103    #[serde(skip_serializing_if = "Vec::is_empty")]
104    pub available_if: Vec<String>,
105    /// Explicit placement within its parent's command section.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub display_order: Option<usize>,
108    /// True when this command came from a [`SpecMount`], i.e. it describes another
109    /// program's CLI that was merged in at parse time.
110    ///
111    /// The flags of the commands *above* a mounted command belong to the mounting CLI,
112    /// not to the mounted program, so they are not offered in completions once a mounted
113    /// command has been reached. They stay recognized by the parser, since they may
114    /// legitimately appear *before* the mounted command on the command line.
115    ///
116    /// Runtime-only: it is derived from `mount` nodes and is not part of the spec syntax.
117    #[serde(skip)]
118    pub mounted: bool,
119    /// True when a [`SpecMount`] brought flags of its own onto this command. A mounted spec's
120    /// root flags are merged into the command the mount sits on, *replacing* that command's
121    /// flags (see [`SpecCommand::merge`]), so when this is set every flag here describes the
122    /// mounted program and is offered inside the mounted commands accordingly.
123    ///
124    /// Runtime-only, like [`SpecCommand::mounted`].
125    #[serde(skip)]
126    pub flags_from_mount: bool,
127    /// Whether a subcommand must be provided
128    #[serde(skip_serializing_if = "is_false")]
129    pub subcommand_required: bool,
130    /// Heading used for this command's subcommand section.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub subcommand_help_heading: Option<String>,
133    /// Placeholder used for subcommands in the synopsis.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub subcommand_value_name: Option<String>,
136    /// Put each argument, flag, and subcommand description on the following line.
137    #[serde(skip_serializing_if = "is_false")]
138    pub next_line_help: bool,
139    /// Expand each visible subcommand's summary and arguments into this command's help page.
140    #[serde(skip_serializing_if = "is_false")]
141    pub flatten_help: bool,
142    /// Fixed help width. Zero disables wrapping.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub term_width: Option<usize>,
145    /// Maximum detected terminal width when `term_width` is unset. Zero disables the cap.
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub max_term_width: Option<usize>,
148    /// Whether an unmatched word is forwarded as an external command plus the rest of argv.
149    ///
150    /// clap's `allow_external_subcommands` / `#[command(external_subcommand)]`. Known
151    /// subcommands still win; a `default_subcommand` still catches first. Once the
152    /// unmatched word is taken, remaining tokens — including `--help` — are not parsed
153    /// as this command's flags.
154    #[serde(skip_serializing_if = "is_false")]
155    pub external_subcommand: bool,
156    /// Whether a bare invocation of this command shows its help.
157    #[serde(skip_serializing_if = "is_false")]
158    pub arg_required_else_help: bool,
159    #[serde(skip_serializing_if = "is_false")]
160    pub disable_help_flag: bool,
161    #[serde(skip_serializing_if = "is_false")]
162    pub disable_help_subcommand: bool,
163    #[serde(skip_serializing_if = "is_false")]
164    pub disable_version_flag: bool,
165    /// Whether delimiter splitting is disabled after `--` or for an automatic trailing arg.
166    #[serde(skip_serializing_if = "is_false")]
167    pub dont_delimit_trailing_values: bool,
168    /// Whether a later occurrence of a single-valued argument replaces the earlier one.
169    /// Permissive by default; set false to report duplicates.
170    pub args_override_self: bool,
171    /// Whether selecting a subcommand satisfies this command's required arguments.
172    #[serde(skip_serializing_if = "is_false")]
173    pub subcommand_negates_reqs: bool,
174    /// Whether binding an argument prevents selecting a later subcommand.
175    #[serde(skip_serializing_if = "is_false")]
176    pub args_conflicts_with_subcommands: bool,
177    #[serde(skip_serializing_if = "is_false")]
178    pub subcommand_precedence_over_arg: bool,
179    /// Allow required positionals after optional positionals to claim the remaining words.
180    #[serde(skip_serializing_if = "is_false")]
181    pub allow_missing_positional: bool,
182    /// Token that resets argument parsing, allowing multiple command invocations.
183    /// e.g., `mise run lint ::: test ::: check` with restart_token=":::"
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub restart_token: Option<String>,
186    /// Short help text shown in command listings
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub help: Option<String>,
189    /// Extended help text shown with --help
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub help_long: Option<String>,
192    /// Markdown-formatted help text
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub help_md: Option<String>,
195    /// Command name (e.g., "install")
196    pub name: String,
197    /// Alternative names for this command
198    pub aliases: Vec<String>,
199    /// Hidden alternative names (not shown in help)
200    pub hidden_aliases: Vec<String>,
201    /// Text displayed before the help content
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub before_help: Option<String>,
204    /// Extended text displayed before help content
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub before_help_long: Option<String>,
207    /// Markdown text displayed before help content
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub before_help_md: Option<String>,
210    /// Text displayed after the help content
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub after_help: Option<String>,
213    /// Extended text displayed after help content
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub after_help_long: Option<String>,
216    /// Markdown text displayed after help content
217    #[serde(skip_serializing_if = "Option::is_none")]
218    pub after_help_md: Option<String>,
219    /// Usage examples for this command
220    pub examples: Vec<SpecExample>,
221    /// Prose introducing this command's help sections, by heading title.
222    pub headings: Vec<SpecHeading>,
223    /// What this command writes, and how a consumer should read it.
224    ///
225    /// Folded with the spec's CLI-wide outputs on read rather than here — see
226    /// [`effective_outputs`](crate::spec::output::effective_outputs).
227    #[serde(skip_serializing_if = "Vec::is_empty")]
228    pub outputs: Vec<SpecOutput>,
229    /// The flag whose *value* picks among [`Self::outputs`], e.g. `--format`.
230    ///
231    /// The other spelling — a boolean flag picking one output — lives on the output
232    /// itself, because that is where it is scoped.
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub select: Option<String>,
235    /// What this command's exit statuses mean.
236    #[serde(skip_serializing_if = "Vec::is_empty")]
237    pub exit_codes: Vec<SpecExitCode>,
238    /// Custom completers for arguments
239    #[serde(skip_serializing_if = "IndexMap::is_empty")]
240    pub complete: IndexMap<String, SpecComplete>,
241
242    /// Cache for subcommand name lookups (including aliases).
243    ///
244    /// `pub(crate)` only so that other modules can destructure `SpecCommand`
245    /// exhaustively; it stays private to the crate.
246    #[serde(skip)]
247    pub(crate) subcommand_lookup: OnceLock<HashMap<String, String>>,
248}
249
250impl Default for SpecCommand {
251    fn default() -> Self {
252        Self {
253            full_cmd: vec![],
254            usage: "".to_string(),
255            subcommands: IndexMap::new(),
256            args: vec![],
257            flags: vec![],
258            uses: vec![],
259            mounts: vec![],
260            groups: vec![],
261            deprecated: None,
262            deprecated_warn_at: None,
263            deprecated_remove_at: None,
264            effect: None,
265            unknown_flags: None,
266            hide: false,
267            help_heading: None,
268            surface: None,
269            available_if: vec![],
270            display_order: None,
271            mounted: false,
272            flags_from_mount: false,
273            subcommand_required: false,
274            subcommand_help_heading: None,
275            subcommand_value_name: None,
276            next_line_help: false,
277            flatten_help: false,
278            term_width: None,
279            max_term_width: None,
280            external_subcommand: false,
281            arg_required_else_help: false,
282            disable_help_flag: false,
283            disable_help_subcommand: false,
284            disable_version_flag: false,
285            dont_delimit_trailing_values: false,
286            args_override_self: true,
287            subcommand_negates_reqs: false,
288            args_conflicts_with_subcommands: false,
289            subcommand_precedence_over_arg: false,
290            allow_missing_positional: false,
291            restart_token: None,
292            clause: None,
293            help: None,
294            help_long: None,
295            help_md: None,
296            name: "".to_string(),
297            aliases: vec![],
298            hidden_aliases: vec![],
299            before_help: None,
300            before_help_long: None,
301            before_help_md: None,
302            after_help: None,
303            after_help_long: None,
304            after_help_md: None,
305            examples: vec![],
306            headings: vec![],
307            outputs: vec![],
308            select: None,
309            exit_codes: vec![],
310            subcommand_lookup: OnceLock::new(),
311            complete: IndexMap::new(),
312        }
313    }
314}
315
316#[derive(Debug, Default, Serialize, Clone)]
317#[non_exhaustive]
318pub struct SpecExample {
319    pub code: String,
320    pub header: Option<String>,
321    pub help: Option<String>,
322    pub lang: String,
323}
324
325impl SpecExample {
326    /// An example invocation shown in generated docs and help.
327    pub fn new(code: impl Into<String>) -> Self {
328        Self {
329            code: code.into(),
330            ..Default::default()
331        }
332    }
333
334    /// Heading shown above the example.
335    pub fn header(mut self, header: impl Into<String>) -> Self {
336        self.header = Some(header.into());
337        self
338    }
339
340    /// Prose shown with the example.
341    pub fn help(mut self, help: impl Into<String>) -> Self {
342        self.help = Some(help.into());
343        self
344    }
345
346    /// Language used for syntax highlighting.
347    pub fn lang(mut self, lang: impl Into<String>) -> Self {
348        self.lang = lang.into();
349        self
350    }
351}
352
353/// Prose introducing one help section.
354///
355/// Keyed by the heading's title, because a section is assembled from every flag and
356/// argument that names it and the text describes the section rather than any one of them.
357#[derive(Debug, Default, Serialize, Clone)]
358#[non_exhaustive]
359pub struct SpecHeading {
360    pub title: String,
361    pub help: String,
362}
363
364impl SpecHeading {
365    /// Prose shown between a help section's heading and its entries.
366    pub fn new(title: impl Into<String>, help: impl Into<String>) -> Self {
367        Self {
368            title: title.into(),
369            help: help.into(),
370        }
371    }
372}
373
374impl From<&SpecHeading> for KdlNode {
375    fn from(heading: &SpecHeading) -> KdlNode {
376        let mut node = KdlNode::new("heading");
377        node.push(string_entry(None, &heading.title));
378        node.push(string_entry(Some("help"), &heading.help));
379        node
380    }
381}
382
383impl From<&SpecExample> for KdlNode {
384    fn from(example: &SpecExample) -> KdlNode {
385        let mut node = KdlNode::new("example");
386        node.push(string_entry(None, &example.code));
387        if let Some(header) = &example.header {
388            node.push(string_entry(Some("header"), header));
389        }
390        if let Some(help) = &example.help {
391            node.push(string_entry(Some("help"), help));
392        }
393        if !example.lang.is_empty() {
394            node.push(string_entry(Some("lang"), &example.lang));
395        }
396        node
397    }
398}
399
400impl SpecCommand {
401    /// Create a new builder for SpecCommand
402    pub fn builder() -> SpecCommandBuilder {
403        SpecCommandBuilder::new()
404    }
405
406    pub(crate) fn parse(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
407        node.ensure_arg_len(1..=1)?;
408        let mut cmd = Self {
409            name: node.arg(0)?.ensure_string()?.to_string(),
410            ..Default::default()
411        };
412        for (k, v) in node.props() {
413            match k {
414                "help" => cmd.help = Some(v.ensure_string()?),
415                "long_help" => cmd.help_long = Some(v.ensure_string()?),
416                "help_long" => cmd.help_long = Some(v.ensure_string()?),
417                "help_md" => cmd.help_md = Some(v.ensure_string()?),
418                "before_help" => cmd.before_help = Some(v.ensure_string()?),
419                "before_long_help" => cmd.before_help_long = Some(v.ensure_string()?),
420                "before_help_long" => cmd.before_help_long = Some(v.ensure_string()?),
421                "before_help_md" => cmd.before_help_md = Some(v.ensure_string()?),
422                "after_help" => cmd.after_help = Some(v.ensure_string()?),
423                "after_long_help" => {
424                    cmd.after_help_long = Some(v.ensure_string()?);
425                }
426                "after_help_long" => {
427                    cmd.after_help_long = Some(v.ensure_string()?);
428                }
429                "after_help_md" => cmd.after_help_md = Some(v.ensure_string()?),
430                "subcommand_required" => cmd.subcommand_required = v.ensure_bool()?,
431                "subcommand_help_heading" => cmd.subcommand_help_heading = Some(v.ensure_string()?),
432                "subcommand_value_name" => cmd.subcommand_value_name = Some(v.ensure_string()?),
433                "next_line_help" => cmd.next_line_help = v.ensure_bool()?,
434                "flatten_help" => cmd.flatten_help = v.ensure_bool()?,
435                "term_width" => cmd.term_width = Some(v.ensure_usize()?),
436                "max_term_width" => cmd.max_term_width = Some(v.ensure_usize()?),
437                "external_subcommand" => cmd.external_subcommand = v.ensure_bool()?,
438                "arg_required_else_help" => cmd.arg_required_else_help = v.ensure_bool()?,
439                "disable_help_flag" => cmd.disable_help_flag = v.ensure_bool()?,
440                "disable_help_subcommand" => cmd.disable_help_subcommand = v.ensure_bool()?,
441                "disable_version_flag" => cmd.disable_version_flag = v.ensure_bool()?,
442                "dont_delimit_trailing_values" => {
443                    cmd.dont_delimit_trailing_values = v.ensure_bool()?
444                }
445                "args_override_self" => cmd.args_override_self = v.ensure_bool()?,
446                "subcommand_negates_reqs" => cmd.subcommand_negates_reqs = v.ensure_bool()?,
447                "args_conflicts_with_subcommands" => {
448                    cmd.args_conflicts_with_subcommands = v.ensure_bool()?
449                }
450                "subcommand_precedence_over_arg" => {
451                    cmd.subcommand_precedence_over_arg = v.ensure_bool()?
452                }
453                "allow_missing_positional" => cmd.allow_missing_positional = v.ensure_bool()?,
454                "hide" => cmd.hide = v.ensure_bool()?,
455                "help_heading" => cmd.help_heading = Some(v.ensure_string()?),
456                "surface" => cmd.surface = Some(v.ensure_string()?),
457                "available_if" => cmd.available_if = vec![v.ensure_string()?],
458                "display_order" => cmd.display_order = Some(v.ensure_usize()?),
459                "unknown_flags" => {
460                    let raw = v.ensure_string()?;
461                    match raw.parse() {
462                        Ok(mode) => cmd.unknown_flags = Some(mode),
463                        Err(_) => bail_parse!(
464                            ctx,
465                            v.entry.span(),
466                            "unsupported unknown_flags {raw}, expected one of: {}",
467                            crate::spec::unknown_flags::UNKNOWN_FLAGS_VALUES
468                        ),
469                    }
470                }
471                "effect" => {
472                    let raw = v.ensure_string()?;
473                    match raw.parse() {
474                        Ok(effect) => cmd.effect = Some(effect),
475                        Err(_) => bail_parse!(
476                            ctx,
477                            v.entry.span(),
478                            "unsupported effect {raw}, expected one of: {EFFECT_VALUES}"
479                        ),
480                    }
481                }
482                "restart_token" => cmd.restart_token = Some(v.ensure_string()?),
483                "deprecated" => {
484                    cmd.deprecated = match v.value.as_bool() {
485                        Some(true) => Some("deprecated".to_string()),
486                        Some(false) => None,
487                        None => Some(v.ensure_string()?),
488                    }
489                }
490                "deprecated_warn_at" => cmd.deprecated_warn_at = Some(v.ensure_string()?),
491                "deprecated_remove_at" => cmd.deprecated_remove_at = Some(v.ensure_string()?),
492                k => bail_parse!(ctx, v.entry.span(), "unsupported cmd prop {k}"),
493            }
494        }
495        for child in node.children() {
496            match child.name() {
497                "flag" => cmd.flags.push(SpecFlag::parse(ctx, &child)?),
498                "use" => {
499                    let at = cmd.flags.len();
500                    cmd.uses.push(SpecUse::parse(ctx, &child, at)?);
501                }
502                "arg" => {
503                    let arg = SpecArg::parse(ctx, &child)?;
504                    // As on a flag: splitting a word that has room for one value would
505                    // drop everything after the first separator.
506                    if arg.delimiter.is_some() && !arg.var {
507                        bail_parse!(
508                            ctx,
509                            child.node.name().span(),
510                            "argument <{}> has a delimiter and holds one value; add \
511                             `var=#true` for the values it splits into",
512                            arg.name
513                        );
514                    }
515                    cmd.args.push(arg);
516                }
517                "clause" => {
518                    if cmd.clause.is_some() {
519                        bail_parse!(
520                            ctx,
521                            child.node.name().span(),
522                            "a command may declare at most one clause"
523                        );
524                    }
525                    cmd.clause = Some(SpecClause::parse(ctx, &child)?);
526                }
527                "mount" => cmd.mounts.push(SpecMount::parse(ctx, &child)?),
528                "group" => cmd.groups.push(SpecGroup::parse(ctx, &child)?),
529                "cmd" => {
530                    let node = SpecCommand::parse(ctx, &child)?;
531                    cmd.subcommands.insert(node.name.to_string(), node);
532                }
533                "alias" => {
534                    let alias = child
535                        .ensure_arg_len(1..)?
536                        .args()
537                        .map(|e| e.ensure_string())
538                        .collect::<Result<Vec<_>, _>>()?;
539                    let hide = child
540                        .get("hide")
541                        .map(|n| n.ensure_bool())
542                        .unwrap_or(Ok(false))?;
543                    if hide {
544                        cmd.hidden_aliases.extend(alias);
545                    } else {
546                        cmd.aliases.extend(alias);
547                    }
548                }
549                "example" => {
550                    let code = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?;
551                    let mut example = SpecExample::new(code.trim().to_string());
552                    for (k, v) in child.props() {
553                        match k {
554                            "header" => example.header = Some(v.ensure_string()?),
555                            "help" => example.help = Some(v.ensure_string()?),
556                            "lang" => example.lang = v.ensure_string()?,
557                            k => bail_parse!(ctx, v.entry.span(), "unsupported example key {k}"),
558                        }
559                    }
560                    cmd.examples.push(example);
561                }
562                "heading" => {
563                    let title = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?;
564                    let mut help = None;
565                    for (k, v) in child.props() {
566                        match k {
567                            "help" => help = Some(v.ensure_string()?),
568                            k => bail_parse!(ctx, v.entry.span(), "unsupported heading key {k}"),
569                        }
570                    }
571                    let Some(help) = help else {
572                        bail_parse!(ctx, child.node.span(), "heading {title} needs help text");
573                    };
574                    cmd.headings.push(SpecHeading::new(title, help));
575                }
576                "output" => cmd.outputs.push(SpecOutput::parse(ctx, &child)?),
577                "exit_code" => cmd.exit_codes.push(SpecExitCode::parse(ctx, &child)?),
578                "select" => {
579                    cmd.select = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
580                }
581                "help" => {
582                    cmd.help = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
583                }
584                "long_help" => {
585                    cmd.help_long = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
586                }
587                "help_md" => {
588                    cmd.help_md = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
589                }
590                "before_help" => {
591                    cmd.before_help = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
592                }
593                "before_long_help" => {
594                    cmd.before_help_long =
595                        Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
596                }
597                "before_help_md" => {
598                    cmd.before_help_md =
599                        Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
600                }
601                "after_help" => {
602                    cmd.after_help = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
603                }
604                "after_long_help" => {
605                    cmd.after_help_long =
606                        Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
607                }
608                "after_help_md" => {
609                    cmd.after_help_md = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?);
610                }
611                "subcommand_required" => {
612                    cmd.subcommand_required = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
613                }
614                "help_heading" => {
615                    cmd.help_heading = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?)
616                }
617                "surface" => {
618                    cmd.surface = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?)
619                }
620                "available_if" => {
621                    cmd.available_if = child
622                        .ensure_arg_len(1..)?
623                        .args()
624                        .map(|entry| entry.ensure_string())
625                        .collect::<Result<Vec<_>, _>>()?;
626                }
627                "subcommand_help_heading" => {
628                    cmd.subcommand_help_heading =
629                        Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?)
630                }
631                "subcommand_value_name" => {
632                    cmd.subcommand_value_name =
633                        Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?)
634                }
635                "next_line_help" => {
636                    cmd.next_line_help = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
637                }
638                "flatten_help" => {
639                    cmd.flatten_help = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
640                }
641                "term_width" => {
642                    cmd.term_width = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_usize()?)
643                }
644                "max_term_width" => {
645                    cmd.max_term_width = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_usize()?)
646                }
647                "external_subcommand" => {
648                    cmd.external_subcommand = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
649                }
650                "arg_required_else_help" => {
651                    cmd.arg_required_else_help =
652                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
653                }
654                "disable_help_flag" => {
655                    cmd.disable_help_flag = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
656                }
657                "disable_help_subcommand" => {
658                    cmd.disable_help_subcommand =
659                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
660                }
661                "disable_version_flag" => {
662                    cmd.disable_version_flag = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
663                }
664                "dont_delimit_trailing_values" => {
665                    cmd.dont_delimit_trailing_values =
666                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
667                }
668                "args_override_self" => {
669                    cmd.args_override_self = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
670                }
671                "subcommand_negates_reqs" => {
672                    cmd.subcommand_negates_reqs =
673                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
674                }
675                "args_conflicts_with_subcommands" => {
676                    cmd.args_conflicts_with_subcommands =
677                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
678                }
679                "subcommand_precedence_over_arg" => {
680                    cmd.subcommand_precedence_over_arg =
681                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
682                }
683                "allow_missing_positional" => {
684                    cmd.allow_missing_positional =
685                        child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?
686                }
687                "hide" => cmd.hide = child.ensure_arg_len(1..=1)?.arg(0)?.ensure_bool()?,
688                "effect" => {
689                    let arg = child.ensure_arg_len(1..=1)?.arg(0)?;
690                    let raw = arg.ensure_string()?;
691                    match raw.parse() {
692                        Ok(effect) => cmd.effect = Some(effect),
693                        Err(_) => bail_parse!(
694                            ctx,
695                            arg.entry.span(),
696                            "unsupported effect {raw}, expected one of: {EFFECT_VALUES}"
697                        ),
698                    }
699                }
700                "restart_token" => {
701                    cmd.restart_token = Some(child.ensure_arg_len(1..=1)?.arg(0)?.ensure_string()?)
702                }
703                "deprecated" => {
704                    cmd.deprecated = match child.arg(0)?.value.as_bool() {
705                        Some(true) => Some("deprecated".to_string()),
706                        Some(false) => None,
707                        None => Some(child.arg(0)?.ensure_string()?),
708                    }
709                }
710                "deprecated_warn_at" => {
711                    cmd.deprecated_warn_at = Some(child.arg(0)?.ensure_string()?)
712                }
713                "deprecated_remove_at" => {
714                    cmd.deprecated_remove_at = Some(child.arg(0)?.ensure_string()?)
715                }
716                "complete" => {
717                    let complete = SpecComplete::parse(ctx, &child)?;
718                    cmd.complete.insert(complete.name.clone(), complete);
719                }
720                k => bail_parse!(ctx, child.node.name().span(), "unsupported cmd key {k}"),
721            }
722        }
723        let mut sigils: Vec<&str> = Vec::new();
724        for arg in &cmd.args {
725            if let Some(sigil) = &arg.sigil {
726                if let Some(existing) = sigils
727                    .iter()
728                    .find(|existing| existing.starts_with(sigil) || sigil.starts_with(**existing))
729                {
730                    bail_parse!(
731                        ctx,
732                        node.node.name().span(),
733                        "argument sigils must not overlap: {existing:?} and {sigil:?}"
734                    );
735                }
736                sigils.push(sigil);
737            }
738        }
739        if let Some(clause) = &cmd.clause {
740            if !cmd.args.is_empty() {
741                bail_parse!(
742                    ctx,
743                    node.span(),
744                    "a command cannot declare both top-level arguments and a clause"
745                );
746            }
747            if cmd.restart_token.is_some() {
748                bail_parse!(
749                    ctx,
750                    node.span(),
751                    "a command cannot declare both restart_token and a clause"
752                );
753            }
754            if clause.args.iter().any(|arg| arg.sigil.is_some()) {
755                bail_parse!(
756                    ctx,
757                    node.span(),
758                    "sigil arguments are not supported inside clauses"
759                );
760            }
761        }
762        Ok(cmd)
763    }
764
765    pub(crate) fn validate_sigil_prefixes(&self) -> Result<(), String> {
766        fn validate(cmd: &SpecCommand, ancestors: &[String]) -> Result<(), String> {
767            let mut active = ancestors.to_vec();
768            for sigil in cmd.args.iter().filter_map(|arg| arg.sigil.as_ref()) {
769                if let Some(existing) = active.iter().find(|existing| {
770                    existing.starts_with(sigil.as_str()) || sigil.starts_with(existing.as_str())
771                }) {
772                    return Err(format!(
773                        "argument sigils must not overlap: {existing:?} and {sigil:?}"
774                    ));
775                }
776                active.push(sigil.clone());
777            }
778            for subcommand in cmd.subcommands.values() {
779                validate(subcommand, &active)?;
780            }
781            Ok(())
782        }
783
784        validate(self, &[])
785    }
786    pub(crate) fn is_empty(&self) -> bool {
787        self.args.is_empty()
788            && self.clause.is_none()
789            && self.flags.is_empty()
790            && self.mounts.is_empty()
791            && self.subcommands.is_empty()
792    }
793    pub fn usage(&self) -> String {
794        self.usage_with_subcommands(true)
795    }
796
797    // `cli-help` only, like `SpecChoices::for_help`: the usage line without the subcommand
798    // placeholder is a help-page shape, and nothing else asks for it.
799    #[cfg(feature = "cli-help")]
800    pub(crate) fn usage_without_subcommands(&self) -> String {
801        self.usage_with_subcommands(false)
802    }
803
804    fn usage_with_subcommands(&self, include_subcommands: bool) -> String {
805        let mut usage = self.full_cmd.join(" ");
806        let flags = self
807            .flags
808            .iter()
809            .filter(|f| !f.hide && !f.builtin)
810            .collect_vec();
811        let args = self.args.iter().filter(|a| !a.hide).collect_vec();
812        if !flags.is_empty() {
813            if flags.len() <= 2 {
814                let inlines = flags
815                    .iter()
816                    .map(|f| {
817                        if f.required {
818                            format!("<{}>", f.usage())
819                        } else {
820                            format!("[{}]", f.usage())
821                        }
822                    })
823                    .join(" ");
824                usage = format!("{usage} {inlines}").trim().to_string();
825            } else if flags.iter().any(|f| f.required) {
826                usage = format!("{usage} <FLAGS>");
827            } else {
828                usage = format!("{usage} [FLAGS]");
829            }
830        }
831        if !args.is_empty() {
832            if args.len() <= 2 {
833                let inlines = args.iter().map(|a| a.usage()).join(" ");
834                usage = format!("{usage} {inlines}").trim().to_string();
835            } else if args.iter().any(|a| a.required) {
836                usage = format!("{usage} <ARGS>…");
837            } else {
838                usage = format!("{usage} [ARGS]…");
839            }
840        }
841        if let Some(clause) = &self.clause {
842            usage = format!("{usage} {}", clause.usage());
843        }
844        // TODO: mounts?
845        // if !self.mounts.is_empty() {
846        //     name = format!("{name} [mounts]");
847        // }
848        if include_subcommands && !self.subcommands.is_empty() {
849            let name = self
850                .subcommand_value_name
851                .as_deref()
852                .unwrap_or("SUBCOMMAND");
853            usage = format!("{usage} <{name}>");
854        }
855        usage.trim().to_string()
856    }
857    /// Forget which subcommands this command was asked for.
858    ///
859    /// `find_subcommand` memoizes names and aliases into a `OnceLock`, so anything that adds or
860    /// removes a subcommand has to say so or the lookup keeps answering for the old set.
861    pub(crate) fn reset_subcommand_lookup(&mut self) {
862        self.subcommand_lookup = OnceLock::new();
863    }
864
865    pub(crate) fn merge(&mut self, other: Self) {
866        // Merging can add subcommands and aliases, and `find_subcommand` memoizes
867        // its lookup into a OnceLock — so the cache has to go, or a name that
868        // arrived here would not be findable. This worked before only because
869        // mounting happened to precede the first lookup on a given command.
870        self.subcommand_lookup = OnceLock::new();
871        // Destructured exhaustively (no `..`) so that adding a field to
872        // SpecCommand fails to compile until this decides what merging it means.
873        // Runtime-derived fields are explicitly ignored rather than skipped.
874        let Self {
875            name,
876            help,
877            help_long,
878            help_md,
879            before_help,
880            before_help_long,
881            before_help_md,
882            after_help,
883            after_help_long,
884            after_help_md,
885            args,
886            clause,
887            flags,
888            uses,
889            mounts,
890            groups,
891            aliases,
892            hidden_aliases,
893            examples,
894            headings,
895            outputs,
896            select,
897            exit_codes,
898            hide,
899            help_heading,
900            surface,
901            available_if,
902            display_order,
903            subcommand_required,
904            subcommand_help_heading,
905            subcommand_value_name,
906            next_line_help,
907            flatten_help,
908            term_width,
909            max_term_width,
910            external_subcommand,
911            arg_required_else_help,
912            disable_help_flag,
913            disable_help_subcommand,
914            disable_version_flag,
915            dont_delimit_trailing_values,
916            args_override_self,
917            subcommand_negates_reqs,
918            args_conflicts_with_subcommands,
919            subcommand_precedence_over_arg,
920            allow_missing_positional,
921            restart_token,
922            subcommands,
923            complete,
924            deprecated,
925            deprecated_warn_at,
926            deprecated_remove_at,
927            effect,
928            unknown_flags,
929            // Recomputed from the merged command, never carried over.
930            full_cmd: _,
931            usage: _,
932            mounted: _,
933            flags_from_mount: _,
934            subcommand_lookup: _,
935        } = other;
936        if !name.is_empty() {
937            self.name = name;
938        }
939        if help.is_some() {
940            self.help = help;
941        }
942        if help_long.is_some() {
943            self.help_long = help_long;
944        }
945        if help_md.is_some() {
946            self.help_md = help_md;
947        }
948        if before_help.is_some() {
949            self.before_help = before_help;
950        }
951        if before_help_long.is_some() {
952            self.before_help_long = before_help_long;
953        }
954        if before_help_md.is_some() {
955            self.before_help_md = before_help_md;
956        }
957        if after_help.is_some() {
958            self.after_help = after_help;
959        }
960        if after_help_long.is_some() {
961            self.after_help_long = after_help_long;
962        }
963        if after_help_md.is_some() {
964            self.after_help_md = after_help_md;
965        }
966        if !args.is_empty() {
967            self.args = args;
968        }
969        if clause.is_some() {
970            self.clause = clause;
971        }
972        let flags_replaced = !flags.is_empty();
973        if flags_replaced {
974            self.flags = flags;
975        }
976        // Unresolved `use` nodes travel with the flags they were written among, for the same
977        // reason groups do — including when that means going with none. A `use` is a
978        // declaration of flags, so whoever owns the flag list owns it: an included file that
979        // replaces this command's flags replaces what it says about them, and a `use` left
980        // behind would splice a set into the incoming list at a position from the old one.
981        //
982        // `other.uses` is normally empty either way: a spec resolves its own sets before it
983        // can be merged into another, and what arrives here has been through that already.
984        if flags_replaced || !uses.is_empty() {
985            self.uses = uses;
986        }
987        if !mounts.is_empty() {
988            self.mounts = mounts;
989        }
990        // Groups travel with the flags they name. A mounted spec that replaces this
991        // command's flags replaces its groups too — including with none, which is the
992        // case that matters: keeping the old set would enforce exclusivity between flags
993        // that are no longer here, and a required group whose members nothing answers to
994        // would reject every invocation.
995        if flags_replaced || !groups.is_empty() {
996            self.groups = groups;
997        }
998        if !aliases.is_empty() {
999            self.aliases = aliases;
1000        }
1001        if !hidden_aliases.is_empty() {
1002            self.hidden_aliases = hidden_aliases;
1003        }
1004        if !examples.is_empty() {
1005            self.examples = examples;
1006        }
1007        if !headings.is_empty() {
1008            self.headings = headings;
1009        }
1010        // Outputs describe what the *mounted* program writes, so they move with the flags
1011        // rather than being folded into what was here — the same reason groups follow the
1012        // flags they name.
1013        if flags_replaced || !outputs.is_empty() {
1014            self.outputs = outputs;
1015        }
1016        if flags_replaced || select.is_some() {
1017            self.select = select;
1018        }
1019        if !exit_codes.is_empty() {
1020            self.exit_codes = exit_codes;
1021        }
1022        self.hide = hide;
1023        if help_heading.is_some() {
1024            self.help_heading = help_heading;
1025        }
1026        if surface.is_some() {
1027            self.surface = surface;
1028        }
1029        if !available_if.is_empty() {
1030            self.available_if = available_if;
1031        }
1032        if display_order.is_some() {
1033            self.display_order = display_order;
1034        }
1035        self.subcommand_required = subcommand_required;
1036        if subcommand_help_heading.is_some() {
1037            self.subcommand_help_heading = subcommand_help_heading;
1038        }
1039        if subcommand_value_name.is_some() {
1040            self.subcommand_value_name = subcommand_value_name;
1041        }
1042        self.next_line_help = next_line_help;
1043        self.flatten_help = flatten_help;
1044        if term_width.is_some() {
1045            self.term_width = term_width;
1046        }
1047        if max_term_width.is_some() {
1048            self.max_term_width = max_term_width;
1049        }
1050        self.external_subcommand = external_subcommand;
1051        self.arg_required_else_help = arg_required_else_help;
1052        self.disable_help_flag = disable_help_flag;
1053        self.disable_help_subcommand = disable_help_subcommand;
1054        self.disable_version_flag = disable_version_flag;
1055        self.dont_delimit_trailing_values = dont_delimit_trailing_values;
1056        self.args_override_self = args_override_self;
1057        self.subcommand_negates_reqs = subcommand_negates_reqs;
1058        self.args_conflicts_with_subcommands = args_conflicts_with_subcommands;
1059        self.subcommand_precedence_over_arg = subcommand_precedence_over_arg;
1060        self.allow_missing_positional = allow_missing_positional;
1061        if effect.is_some() {
1062            self.effect = effect;
1063        }
1064        if unknown_flags.is_some() {
1065            self.unknown_flags = unknown_flags;
1066        }
1067        if deprecated.is_some() {
1068            self.deprecated = deprecated;
1069        }
1070        if deprecated_warn_at.is_some() {
1071            self.deprecated_warn_at = deprecated_warn_at;
1072        }
1073        if deprecated_remove_at.is_some() {
1074            self.deprecated_remove_at = deprecated_remove_at;
1075        }
1076        if restart_token.is_some() {
1077            self.restart_token = restart_token;
1078        }
1079        for (name, cmd) in subcommands {
1080            self.subcommands.insert(name, cmd);
1081        }
1082        for (name, complete) in complete {
1083            self.complete.insert(name, complete);
1084        }
1085    }
1086
1087    pub fn all_subcommands(&self) -> Vec<&SpecCommand> {
1088        let mut cmds = vec![];
1089        for cmd in self.subcommands.values() {
1090            cmds.push(cmd);
1091            cmds.extend(cmd.all_subcommands());
1092        }
1093        cmds
1094    }
1095
1096    pub fn find_subcommand(&self, name: &str) -> Option<&SpecCommand> {
1097        let sl = self.subcommand_lookup.get_or_init(|| {
1098            let mut map = HashMap::new();
1099            // Names first, then aliases only where nothing answers already: a
1100            // command's own name outranks another command's alias, so reordering
1101            // `cmd` blocks cannot change which command a word selects.
1102            //
1103            // Inserting both in one pass instead let the *last* declaration win,
1104            // which was the opposite of what usage-argv did with the same spec —
1105            // it takes the first. Neither was a rule anyone had chosen.
1106            for name in self.subcommands.keys() {
1107                map.insert(name.clone(), name.clone());
1108            }
1109            for (name, cmd) in &self.subcommands {
1110                for alias in cmd.aliases.iter().chain(&cmd.hidden_aliases) {
1111                    map.entry(alias.clone()).or_insert_with(|| name.clone());
1112                }
1113            }
1114            map
1115        });
1116        let name = sl.get(name)?;
1117        self.subcommands.get(name)
1118    }
1119
1120    pub(crate) fn mount(
1121        &mut self,
1122        global_flag_args: &[String],
1123        injected: Option<&HashMap<String, String>>,
1124    ) -> Result<(), UsageErr> {
1125        for mount in self.mounts.iter().cloned().collect_vec() {
1126            let cmd = if global_flag_args.is_empty() {
1127                mount.run.clone()
1128            } else {
1129                // Parse the mount command into tokens, insert global flags after the first token
1130                // e.g., "mise tasks ls" becomes "mise --cd dir2 tasks ls"
1131                // Handles quoted arguments correctly: "cmd 'arg with spaces'" stays correct
1132                let mut tokens = crate::shell_words::split(&mount.run)
1133                    .expect("mount command should be valid shell syntax");
1134                if !tokens.is_empty() {
1135                    // Insert global flags after the first token (the command name)
1136                    tokens.splice(1..1, global_flag_args.iter().cloned());
1137                }
1138                // Join tokens back into a properly quoted command string
1139                crate::shell_words::join(tokens)
1140            };
1141            let output = match injected {
1142                Some(outputs) => outputs
1143                    .get(&mount.run)
1144                    .cloned()
1145                    .ok_or_else(|| UsageErr::MissingMountOutput(mount.run.clone()))?,
1146                None => sh(&cmd)?,
1147            };
1148            let mut spec: Spec = output.parse()?;
1149            if let Some(outputs) = injected {
1150                // A mounted spec's root is merged into this command, so its root-only
1151                // default-subcommand precedence does not apply while composing mounts.
1152                spec.resolve_mount_outputs_at_root(outputs, false)?;
1153            }
1154            // The subcommands emitted by a mount describe another program, so mark them (and
1155            // everything below them) as mounted. See `SpecCommand::mounted`.
1156            for cmd in spec.cmd.subcommands.values_mut() {
1157                cmd.mark_mounted();
1158            }
1159            // `merge` folds the mounted spec's root flags into this command; remember that they
1160            // came from the mount. See `SpecCommand::flags_from_mount`.
1161            self.flags_from_mount |= !spec.cmd.flags.is_empty();
1162            self.merge(spec.cmd);
1163        }
1164        Ok(())
1165    }
1166
1167    /// Mark this command and all of its subcommands as coming from a mount.
1168    pub(crate) fn mark_mounted(&mut self) {
1169        self.mounted = true;
1170        for cmd in self.subcommands.values_mut() {
1171            cmd.mark_mounted();
1172        }
1173    }
1174}
1175
1176impl From<&SpecCommand> for KdlNode {
1177    fn from(cmd: &SpecCommand) -> Self {
1178        // Destructured exhaustively (no `..`) so that adding a field to
1179        // SpecCommand fails to compile until this decides how to serialize it.
1180        let SpecCommand {
1181            name,
1182            hide,
1183            help_heading,
1184            surface,
1185            available_if,
1186            display_order,
1187            subcommand_required,
1188            subcommand_help_heading,
1189            subcommand_value_name,
1190            next_line_help,
1191            flatten_help,
1192            term_width,
1193            max_term_width,
1194            external_subcommand,
1195            arg_required_else_help,
1196            disable_help_flag,
1197            disable_help_subcommand,
1198            disable_version_flag,
1199            dont_delimit_trailing_values,
1200            args_override_self,
1201            subcommand_negates_reqs,
1202            args_conflicts_with_subcommands,
1203            subcommand_precedence_over_arg,
1204            allow_missing_positional,
1205            restart_token,
1206            unknown_flags,
1207            aliases,
1208            hidden_aliases,
1209            help,
1210            help_long,
1211            help_md,
1212            before_help,
1213            before_help_long,
1214            before_help_md,
1215            after_help,
1216            after_help_long,
1217            after_help_md,
1218            deprecated,
1219            deprecated_warn_at,
1220            deprecated_remove_at,
1221            effect,
1222            flags,
1223            args,
1224            clause,
1225            mounts,
1226            groups,
1227            subcommands,
1228            complete,
1229            examples,
1230            headings,
1231            outputs,
1232            select,
1233            exit_codes,
1234            // Resolved while the spec was read: whatever a `use` named is among `flags`
1235            // by now, so emitting the request too would declare those flags twice.
1236            uses: _,
1237            // Derived from the spec rather than written by it.
1238            full_cmd: _,
1239            usage: _,
1240            mounted: _,
1241            flags_from_mount: _,
1242            subcommand_lookup: _,
1243        } = cmd;
1244        let mut node = Self::new("cmd");
1245        node.entries_mut().push(name.clone().into());
1246        if *hide {
1247            node.entries_mut().push(KdlEntry::new_prop("hide", true));
1248        }
1249        if let Some(heading) = help_heading {
1250            node.entries_mut()
1251                .push(KdlEntry::new_prop("help_heading", heading.clone()));
1252        }
1253        if let Some(surface) = surface {
1254            node.push(KdlEntry::new_prop("surface", surface.clone()));
1255        }
1256        if !available_if.is_empty() {
1257            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1258            let mut condition = KdlNode::new("available_if");
1259            for value in available_if {
1260                condition.push(string_entry(None, value));
1261            }
1262            children.nodes_mut().push(condition);
1263        }
1264        if let Some(order) = display_order {
1265            node.entries_mut()
1266                .push(KdlEntry::new_prop("display_order", *order as i128));
1267        }
1268        if *subcommand_required {
1269            node.entries_mut()
1270                .push(KdlEntry::new_prop("subcommand_required", true));
1271        }
1272        if let Some(heading) = subcommand_help_heading {
1273            node.push(KdlEntry::new_prop(
1274                "subcommand_help_heading",
1275                heading.clone(),
1276            ));
1277        }
1278        if let Some(name) = subcommand_value_name {
1279            node.push(KdlEntry::new_prop("subcommand_value_name", name.clone()));
1280        }
1281        if *next_line_help {
1282            node.push(KdlEntry::new_prop("next_line_help", true));
1283        }
1284        if *flatten_help {
1285            node.push(KdlEntry::new_prop("flatten_help", true));
1286        }
1287        if let Some(width) = term_width {
1288            node.push(KdlEntry::new_prop("term_width", *width as i128));
1289        }
1290        if let Some(width) = max_term_width {
1291            node.push(KdlEntry::new_prop("max_term_width", *width as i128));
1292        }
1293        if *external_subcommand {
1294            node.entries_mut()
1295                .push(KdlEntry::new_prop("external_subcommand", true));
1296        }
1297        if *arg_required_else_help {
1298            node.entries_mut()
1299                .push(KdlEntry::new_prop("arg_required_else_help", true));
1300        }
1301        if *disable_help_flag {
1302            node.push(KdlEntry::new_prop("disable_help_flag", true));
1303        }
1304        if *disable_help_subcommand {
1305            node.push(KdlEntry::new_prop("disable_help_subcommand", true));
1306        }
1307        if *disable_version_flag {
1308            node.push(KdlEntry::new_prop("disable_version_flag", true));
1309        }
1310        if *dont_delimit_trailing_values {
1311            node.entries_mut()
1312                .push(KdlEntry::new_prop("dont_delimit_trailing_values", true));
1313        }
1314        if !*args_override_self {
1315            node.push(KdlEntry::new_prop("args_override_self", false));
1316        }
1317        if *subcommand_negates_reqs {
1318            node.push(KdlEntry::new_prop("subcommand_negates_reqs", true));
1319        }
1320        if *args_conflicts_with_subcommands {
1321            node.push(KdlEntry::new_prop("args_conflicts_with_subcommands", true));
1322        }
1323        if *subcommand_precedence_over_arg {
1324            node.push(KdlEntry::new_prop("subcommand_precedence_over_arg", true));
1325        }
1326        if *allow_missing_positional {
1327            node.push(KdlEntry::new_prop("allow_missing_positional", true));
1328        }
1329        if let Some(restart_token) = &restart_token {
1330            node.entries_mut()
1331                .push(KdlEntry::new_prop("restart_token", restart_token.clone()));
1332        }
1333        if !aliases.is_empty() {
1334            let mut alias_node = KdlNode::new("alias");
1335            for alias in aliases {
1336                alias_node.entries_mut().push(alias.clone().into());
1337            }
1338            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1339            children.nodes_mut().push(alias_node);
1340        }
1341        if !hidden_aliases.is_empty() {
1342            let mut alias_node = KdlNode::new("alias");
1343            for alias in hidden_aliases {
1344                alias_node.entries_mut().push(alias.clone().into());
1345            }
1346            alias_node
1347                .entries_mut()
1348                .push(KdlEntry::new_prop("hide", true));
1349            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1350            children.nodes_mut().push(alias_node);
1351        }
1352        if let Some(help) = &help {
1353            node.entries_mut().push(string_entry(Some("help"), help));
1354        }
1355        if let Some(help) = &help_long {
1356            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1357            let mut node = KdlNode::new("long_help");
1358            node.push(string_entry(None, help));
1359            children.nodes_mut().push(node);
1360        }
1361        if let Some(help) = &help_md {
1362            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1363            let mut node = KdlNode::new("help_md");
1364            node.push(string_entry(None, help));
1365            children.nodes_mut().push(node);
1366        }
1367        if let Some(help) = &before_help {
1368            node.entries_mut()
1369                .push(string_entry(Some("before_help"), help));
1370        }
1371        if let Some(help) = &before_help_long {
1372            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1373            let mut node = KdlNode::new("before_long_help");
1374            node.push(string_entry(None, help));
1375            children.nodes_mut().push(node);
1376        }
1377        if let Some(help) = &before_help_md {
1378            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1379            let mut node = KdlNode::new("before_help_md");
1380            node.push(string_entry(None, help));
1381            children.nodes_mut().push(node);
1382        }
1383        if let Some(help) = &after_help {
1384            node.entries_mut()
1385                .push(string_entry(Some("after_help"), help));
1386        }
1387        if let Some(help) = &after_help_long {
1388            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1389            let mut node = KdlNode::new("after_long_help");
1390            node.push(string_entry(None, help));
1391            children.nodes_mut().push(node);
1392        }
1393        if let Some(help) = &after_help_md {
1394            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1395            let mut node = KdlNode::new("after_help_md");
1396            node.push(string_entry(None, help));
1397            children.nodes_mut().push(node);
1398        }
1399        if let Some(deprecated) = &deprecated {
1400            node.entries_mut()
1401                .push(string_entry(Some("deprecated"), deprecated));
1402        }
1403        if let Some(at) = deprecated_warn_at {
1404            node.push(string_entry(Some("deprecated_warn_at"), at));
1405        }
1406        if let Some(at) = deprecated_remove_at {
1407            node.push(string_entry(Some("deprecated_remove_at"), at));
1408        }
1409        if let Some(effect) = effect {
1410            node.entries_mut()
1411                .push(string_entry(Some("effect"), effect.as_str()));
1412        }
1413        if let Some(unknown_flags) = unknown_flags {
1414            node.entries_mut()
1415                .push(string_entry(Some("unknown_flags"), unknown_flags.as_str()));
1416        }
1417        for flag in flags {
1418            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1419            children.nodes_mut().push(flag.into());
1420        }
1421        for arg in args {
1422            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1423            children.nodes_mut().push(arg.into());
1424        }
1425        if let Some(clause) = clause {
1426            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1427            children.nodes_mut().push(clause.into());
1428        }
1429        for mount in mounts {
1430            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1431            children.nodes_mut().push(mount.into());
1432        }
1433        // After the flags they name, so a reader meets the members before the rule
1434        // about them.
1435        for group in groups {
1436            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1437            children.nodes_mut().push(group.into());
1438        }
1439        for cmd in subcommands.values() {
1440            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1441            children.nodes_mut().push(cmd.into());
1442        }
1443        for example in examples {
1444            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1445            children.nodes_mut().push(example.into());
1446        }
1447        for heading in headings {
1448            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1449            children.nodes_mut().push(heading.into());
1450        }
1451        // Outputs before the flag that picks among them, so a reader meets the things
1452        // being chosen before the rule for choosing — the same order groups follow.
1453        for output in outputs {
1454            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1455            children.nodes_mut().push(output.into());
1456        }
1457        if let Some(select) = select {
1458            let mut select_node = KdlNode::new("select");
1459            select_node.push(string_entry(None, select));
1460            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1461            children.nodes_mut().push(select_node);
1462        }
1463        for exit_code in exit_codes {
1464            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1465            children.nodes_mut().push(exit_code.into());
1466        }
1467        for complete in complete.values() {
1468            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1469            children.nodes_mut().push(complete.into());
1470        }
1471        node
1472    }
1473}
1474
1475#[cfg(feature = "clap")]
1476impl From<&clap::Command> for SpecCommand {
1477    fn from(cmd: &clap::Command) -> Self {
1478        let mut spec = Self {
1479            name: cmd.get_name().to_string(),
1480            hide: cmd.is_hide_set(),
1481            help: cmd.get_about().map(|s| s.to_string()),
1482            help_long: cmd.get_long_about().map(|s| s.to_string()),
1483            before_help: cmd.get_before_help().map(|s| s.to_string()),
1484            before_help_long: cmd.get_before_long_help().map(|s| s.to_string()),
1485            after_help: cmd.get_after_help().map(|s| s.to_string()),
1486            after_help_long: cmd.get_after_long_help().map(|s| s.to_string()),
1487            ..Default::default()
1488        };
1489        // What clap would do with a dash-word it does not recognize, said out loud.
1490        //
1491        // clap rejects one; this spec's default is to offer it to the positionals, because a
1492        // spec also describes wrappers — a script run through `usage exec`, a task's arguments —
1493        // where a dash-word is data in transit rather than a mistake. A CLI generated *from
1494        // clap*, though, is not one of those: clap already decided, and saying nothing here
1495        // silently loosened every command it described. mise's spec has 211 commands and not one
1496        // of them said `unknown_flags`, so `mise use --globa` became a tool named `--globa`
1497        // rather than the error clap gives.
1498        //
1499        // Which commands forward unknown *flags* is clap's own knowledge: an argument that
1500        // accepts hyphen values, or a trailing var arg. In mise that is five commands —
1501        // `run`, `watch`, `asdf`, `tool-stub` and the root's implicit task arguments — and
1502        // the other two hundred get the stricter reading back.
1503        //
1504        // An external subcommand is a different shape: an unmatched *word* is forwarded with
1505        // the rest of argv. clap still rejects an unknown flag on such a command (`x --wat`),
1506        // so mapping `allow_external_subcommands` onto `unknown_flags=value` silently loosened
1507        // every clap CLI that allowed one.
1508        spec.external_subcommand = cmd.is_allow_external_subcommands_set();
1509        let forwards = cmd
1510            .get_arguments()
1511            .any(|arg| arg.is_allow_hyphen_values_set() || arg.is_trailing_var_arg_set());
1512        spec.unknown_flags = Some(if forwards {
1513            UnknownFlags::Value
1514        } else {
1515            UnknownFlags::Error
1516        });
1517
1518        for alias in cmd.get_visible_aliases() {
1519            spec.aliases.push(alias.to_string());
1520        }
1521        for alias in cmd.get_all_aliases() {
1522            if spec.aliases.contains(&alias.to_string()) {
1523                continue;
1524            }
1525            spec.hidden_aliases.push(alias.to_string());
1526        }
1527        for arg in cmd.get_arguments() {
1528            let complete_type = crate::spec::arg::value_hint_type(arg.get_value_hint());
1529            let conflicts: Vec<String> = cmd
1530                .get_arg_conflicts_with(arg)
1531                .iter()
1532                .filter_map(|other| match (other.get_long(), other.get_short()) {
1533                    (Some(long), _) => Some(format!("--{long}")),
1534                    (None, Some(short)) => Some(format!("-{short}")),
1535                    (None, None) if other.is_positional() => Some(SpecArg::from(*other).name),
1536                    (None, None) => None,
1537                })
1538                .collect();
1539            if arg.is_positional() {
1540                let mut positional: SpecArg = arg.into();
1541                positional.allow_negative_numbers |= cmd.is_allow_negative_numbers_set();
1542                positional.conflicts = conflicts;
1543                if let Some(type_) = complete_type {
1544                    let name = positional.name.to_lowercase();
1545                    spec.complete.insert(
1546                        name.clone(),
1547                        SpecComplete {
1548                            name,
1549                            type_: Some(type_.to_string()),
1550                            ..Default::default()
1551                        },
1552                    );
1553                }
1554                spec.args.push(positional)
1555            } else {
1556                let mut flag: SpecFlag = arg.into();
1557                if let Some(value) = &mut flag.arg {
1558                    value.allow_negative_numbers |= cmd.is_allow_negative_numbers_set();
1559                }
1560                // clap keeps conflicts on the command rather than on the argument, so
1561                // this is the only place both are in view. Written with dashes,
1562                // matching how the spec refers to a flag everywhere else.
1563                //
1564                // A short-only flag is named `-s`, which selectors accept as readily as
1565                // `--long`: taking only the long form would have dropped the conflict
1566                // and let the spec accept a combination clap rejects.
1567                flag.conflicts = conflicts;
1568                if let (Some(type_), Some(value)) = (complete_type, flag.arg.as_ref()) {
1569                    let name = value.name.to_lowercase();
1570                    spec.complete.insert(
1571                        name.clone(),
1572                        SpecComplete {
1573                            name,
1574                            type_: Some(type_.to_string()),
1575                            ..Default::default()
1576                        },
1577                    );
1578                }
1579                spec.flags.push(flag)
1580            }
1581        }
1582        // clap assigns an implicit monotonically increasing order to arguments. Emitting
1583        // that number for every ordinary declaration makes generated specs noisy without
1584        // changing presentation, since usage already retains declaration order. Keep the
1585        // values only when they actually reorder a section.
1586        if spec
1587            .args
1588            .windows(2)
1589            .all(|pair| pair[0].display_order <= pair[1].display_order)
1590        {
1591            for arg in &mut spec.args {
1592                arg.display_order = None;
1593            }
1594        }
1595        if spec
1596            .flags
1597            .windows(2)
1598            .all(|pair| pair[0].display_order <= pair[1].display_order)
1599        {
1600            for flag in &mut spec.flags {
1601                flag.display_order = None;
1602            }
1603        }
1604        // Groups, which clap does expose — `get_groups`, and `get_args` on each. A group
1605        // names its members by clap's internal id, so each is resolved back to the flag it
1606        // points at and written as a selector, the way conflicts are just above.
1607        //
1608        // clap's own `--help` groups (`ArgGroup` ids it creates for its built-in flags)
1609        // have no members of ours in them, so the two-member floor drops them naturally
1610        // rather than needing a name check.
1611        for group in cmd.get_groups() {
1612            let members: Vec<String> = group
1613                .get_args()
1614                .filter_map(|id| cmd.get_arguments().find(|arg| arg.get_id() == id))
1615                .filter_map(|arg| match (arg.get_long(), arg.get_short()) {
1616                    (Some(long), _) => Some(format!("--{long}")),
1617                    (None, Some(short)) => Some(format!("-{short}")),
1618                    (None, None) if arg.is_positional() => Some(SpecArg::from(arg).name),
1619                    (None, None) => None,
1620                })
1621                .collect();
1622            // Below two members there is no rule left to enforce: whatever the group said
1623            // about "at most one" or "at least one" is either vacuous or is plain
1624            // required-ness on the single flag, which the flag already carries.
1625            if members.len() < 2 {
1626                continue;
1627            }
1628            // `multiple` without `required` enforces nothing at all — any number of
1629            // members, none of them needed — so there is nothing to carry across.
1630            //
1631            // This is not a corner case. clap's *derive* emits exactly that group for
1632            // every `#[derive(Args)]` struct, named after the struct and holding all its
1633            // fields, to make `flatten` work: `clap_derive`'s `args.rs` builds
1634            // `ArgGroup::new(id).multiple(true)`. Carrying them would put a `group Lint
1635            // …` in the spec of every clap-derived CLI, including this repository's own,
1636            // describing bookkeeping rather than a rule anyone declared.
1637            let required = group.is_required_set();
1638            // `is_multiple` takes `&mut self` in clap, and a `&ArgGroup` is all a
1639            // `Command` hands out — so the group is cloned to ask. Once per group at
1640            // spec-generation time, which is a build step rather than a parse.
1641            let multiple = group.clone().is_multiple();
1642            if multiple && !required {
1643                continue;
1644            }
1645            let mut spec_group = SpecGroup::new(group.get_id().as_str(), members);
1646            spec_group.required = required;
1647            spec_group.multiple = multiple;
1648            spec.groups.push(spec_group);
1649        }
1650        spec.subcommand_required = cmd.is_subcommand_required_set();
1651        spec.subcommand_help_heading = cmd.get_subcommand_help_heading().map(str::to_string);
1652        spec.subcommand_value_name = cmd.get_subcommand_value_name().map(str::to_string);
1653        spec.next_line_help = cmd.is_next_line_help_set();
1654        spec.flatten_help = cmd.is_flatten_help_set();
1655        spec.arg_required_else_help = cmd.is_arg_required_else_help_set();
1656        spec.disable_help_flag = cmd.is_disable_help_flag_set();
1657        spec.disable_help_subcommand =
1658            cmd.get_subcommands().next().is_some() && cmd.is_disable_help_subcommand_set();
1659        spec.disable_version_flag = (cmd.get_version().is_some()
1660            || cmd.get_long_version().is_some())
1661            && cmd.is_disable_version_flag_set();
1662        spec.dont_delimit_trailing_values = cmd.is_dont_delimit_trailing_values_set();
1663        spec.args_override_self = cmd.is_args_override_self();
1664        spec.subcommand_negates_reqs = cmd.is_subcommand_negates_reqs_set();
1665        spec.args_conflicts_with_subcommands = cmd.is_args_conflicts_with_subcommands_set();
1666        spec.subcommand_precedence_over_arg = cmd.is_subcommand_precedence_over_arg_set();
1667        spec.allow_missing_positional = cmd.is_allow_missing_positional_set();
1668        for subcmd in cmd.get_subcommands() {
1669            let mut scmd: SpecCommand = subcmd.into();
1670            scmd.name = subcmd.get_name().to_string();
1671            scmd.display_order = Some(subcmd.get_display_order());
1672            spec.subcommands.insert(scmd.name.clone(), scmd);
1673        }
1674        // 999 is clap's ordinary subcommand order. Leaving every command at that value lets
1675        // usage's existing alphabetical tie-breaker produce the same page without serializing
1676        // redundant metadata.
1677        if spec
1678            .subcommands
1679            .iter()
1680            .all(|(_, subcommand)| subcommand.display_order == Some(999))
1681        {
1682            for (_, subcommand) in &mut spec.subcommands {
1683                subcommand.display_order = None;
1684            }
1685        }
1686        spec
1687    }
1688}
1689
1690#[cfg(feature = "clap")]
1691impl From<clap::Command> for Spec {
1692    fn from(cmd: clap::Command) -> Self {
1693        (&cmd).into()
1694    }
1695}
1696
1697#[cfg(test)]
1698mod tests {
1699    use crate::spec::effect::SpecCommandEffect;
1700    use crate::Spec;
1701    use insta::assert_snapshot;
1702
1703    #[test]
1704    fn overlapping_sigils_are_rejected_on_one_command_and_across_subcommands() {
1705        for spec in [
1706            r#"bin "ex"
1707arg "[short]..." sigil="+"
1708arg "[long]..." sigil="++"
1709"#,
1710            r#"bin "ex"
1711arg "[short]..." sigil="+"
1712cmd "run" { arg "[long]..." sigil="++" }
1713"#,
1714        ] {
1715            let error = Spec::parse(&Default::default(), spec).unwrap_err();
1716            assert!(
1717                format!("{error:?}").contains("argument sigils must not overlap"),
1718                "{error:?}"
1719            );
1720        }
1721    }
1722
1723    #[test]
1724    fn test_effect_prop_and_child_node() {
1725        let spec = Spec::parse(
1726            &Default::default(),
1727            r#"
1728bin "mise"
1729cmd "ls" effect="read"
1730cmd "use" effect="write"
1731cmd "uninstall" {
1732    effect "destructive"
1733}
1734cmd "version"
1735            "#,
1736        )
1737        .unwrap();
1738
1739        let cmds = &spec.cmd.subcommands;
1740        assert_eq!(cmds["ls"].effect, Some(SpecCommandEffect::Read));
1741        assert_eq!(cmds["use"].effect, Some(SpecCommandEffect::Write));
1742        assert_eq!(
1743            cmds["uninstall"].effect,
1744            Some(SpecCommandEffect::Destructive)
1745        );
1746        // Unspecified stays unknown rather than defaulting to anything.
1747        assert_eq!(cmds["version"].effect, None);
1748    }
1749
1750    #[test]
1751    fn test_effect_is_not_inherited_by_subcommands() {
1752        let spec = Spec::parse(
1753            &Default::default(),
1754            r#"
1755bin "git"
1756cmd "remote" effect="read" {
1757    cmd "add" effect="write"
1758    cmd "show"
1759}
1760            "#,
1761        )
1762        .unwrap();
1763
1764        let remote = &spec.cmd.subcommands["remote"];
1765        assert_eq!(remote.effect, Some(SpecCommandEffect::Read));
1766        assert_eq!(
1767            remote.subcommands["add"].effect,
1768            Some(SpecCommandEffect::Write)
1769        );
1770        assert_eq!(remote.subcommands["show"].effect, None);
1771    }
1772
1773    #[test]
1774    fn test_effect_roundtrips_through_kdl() {
1775        let spec = Spec::parse(
1776            &Default::default(),
1777            r#"
1778bin "mise"
1779cmd "ls" effect="read"
1780cmd "uninstall" effect="destructive"
1781            "#,
1782        )
1783        .unwrap();
1784
1785        assert_snapshot!(spec, @r#"
1786        name mise
1787        bin mise
1788        cmd ls effect=read
1789        cmd uninstall effect=destructive
1790        "#);
1791    }
1792
1793    /// `merge` is how included and mounted specs are composed onto a command.
1794    /// It has to treat `effect` the way it treats every other optional field:
1795    /// an overlay that says nothing must not erase what is already declared.
1796    #[test]
1797    fn test_effect_survives_merge() {
1798        let cmd_with = |src: &str| {
1799            Spec::parse(&Default::default(), src)
1800                .unwrap()
1801                .cmd
1802                .subcommands["uninstall"]
1803                .clone()
1804        };
1805
1806        let declared = cmd_with(r#"cmd "uninstall" effect="destructive""#);
1807        let silent = cmd_with(r#"cmd "uninstall" help="Remove a tool""#);
1808        let contradicting = cmd_with(r#"cmd "uninstall" effect="write""#);
1809
1810        let mut cmd = declared.clone();
1811        cmd.merge(silent);
1812        assert_eq!(cmd.effect, Some(SpecCommandEffect::Destructive));
1813
1814        let mut cmd = declared;
1815        cmd.merge(contradicting);
1816        assert_eq!(cmd.effect, Some(SpecCommandEffect::Write));
1817    }
1818
1819    #[test]
1820    fn test_unknown_effect_is_an_error() {
1821        let err = Spec::parse(
1822            &Default::default(),
1823            r#"
1824bin "mise"
1825cmd "ls" effect="readonly"
1826            "#,
1827        )
1828        .unwrap_err();
1829        assert!(
1830            err.to_string().contains("Invalid usage config"),
1831            "unexpected error: {err}"
1832        );
1833    }
1834}
1835
1836#[cfg(test)]
1837mod merge_tests {
1838    use crate::Spec;
1839
1840    fn uninstall(src: &str) -> crate::SpecCommand {
1841        Spec::parse(&Default::default(), src)
1842            .unwrap()
1843            .cmd
1844            .subcommands["uninstall"]
1845            .clone()
1846    }
1847
1848    /// An overlay that says nothing about deprecation must not un-deprecate a
1849    /// command that already declared it.
1850    #[test]
1851    fn test_deprecated_survives_merge() {
1852        let declared = uninstall(r#"cmd "uninstall" deprecated="use `remove`""#);
1853        let silent = uninstall(r#"cmd "uninstall" help="Remove a tool""#);
1854        let contradicting = uninstall(r#"cmd "uninstall" deprecated="gone in v3""#);
1855
1856        let mut cmd = declared.clone();
1857        cmd.merge(silent);
1858        assert_eq!(cmd.deprecated.as_deref(), Some("use `remove`"));
1859
1860        let mut cmd = declared;
1861        cmd.merge(contradicting);
1862        assert_eq!(cmd.deprecated.as_deref(), Some("gone in v3"));
1863    }
1864
1865    #[test]
1866    fn mounted_flags_replace_outputs_and_their_selector() {
1867        let mut mounting = uninstall(
1868            r#"cmd "uninstall" { flag "--format <FORMAT>"; output "json" framing="json"; select "--format" }"#,
1869        );
1870        let mounted = uninstall(r#"cmd "uninstall" { flag "--quiet" }"#);
1871
1872        mounting.merge(mounted);
1873
1874        assert!(mounting.outputs.is_empty());
1875        assert!(mounting.select.is_none());
1876    }
1877}
1878
1879#[cfg(test)]
1880mod roundtrip_tests {
1881    use crate::kdl;
1882    use crate::Spec;
1883
1884    /// Serializing a spec back to KDL and reparsing it must not lose anything.
1885    ///
1886    /// The parser is a match on node names, so exhaustive destructuring can't
1887    /// catch a field the serializer knows about but the parser doesn't, or the
1888    /// reverse. Comparing the serde representation covers every field without
1889    /// this test having to enumerate them, so a new field is covered the day it
1890    /// is added.
1891    #[test]
1892    fn test_spec_survives_a_kdl_roundtrip() {
1893        let src = r#"
1894name "My CLI"
1895bin "mycli"
1896about "does things"
1897version "1.0.0"
1898author "nobody"
1899license "MIT"
1900
1901flag "-v --verbose" help="Verbose logging" global=#true count=#true
1902arg "<dir>" help="Directory to use"
1903
1904cmd "install" help="Install a package" subcommand_required=#false {
1905    alias "i"
1906    alias "add" hide=#true
1907    long_help "The long help for install"
1908    help_md "The **markdown** help for install"
1909    before_help "before"
1910    before_long_help "The long before-help for install"
1911    before_help_md "The **markdown** before-help for install"
1912    after_help "after"
1913    after_long_help "The long after-help for install"
1914    after_help_md "The **markdown** after-help for install"
1915    arg "<pkg>" help="Package to install"
1916    arg "[dest]" effect="write"
1917    flag "-f --force" help="Overwrite"
1918    flag "--purge" effect="destructive" overrides="-f" required_unless="--keep"
1919    flag "--format <FMT>" help="Output format"
1920    complete "pkg" run="mycli list --available" descriptions=#true
1921    example "mycli install foo" header="Install foo" help="Installs foo" lang="sh"
1922    example "mycli install bar"
1923    heading "Output" help="Formats are stable across releases."
1924    output "human" default=#true help="A progress log"
1925    output "json" framing="json" help="One report object" {
1926        schema "{\n  \"type\": \"object\"\n}"
1927    }
1928    select "--format"
1929    exit_code 0 "installed"
1930    exit_code 1 "the package was not found"
1931    cmd "from" help="Install from a source" {
1932        arg "<src>"
1933    }
1934}
1935cmd "wrapped" help="Wraps another CLI" {
1936    mount run="mycli plugin usage-spec"
1937}
1938cmd "remove" help="Remove a package" deprecated="use `uninstall`" effect="destructive"
1939cmd "run" restart_token=":::" help="Run tasks"
1940cmd "exec" external_subcommand=#true help="Run an external command"
1941cmd "hidden" hide=#true
1942        "#;
1943
1944        let original = Spec::parse(&Default::default(), src).unwrap();
1945        let reparsed = Spec::parse(&Default::default(), &original.to_string()).unwrap();
1946
1947        let original = serde_json::to_value(&original).unwrap();
1948        let reparsed = serde_json::to_value(&reparsed).unwrap();
1949        pretty_assertions::assert_eq!(original, reparsed);
1950
1951        // Equality is only meaningful if the fixture actually populated the
1952        // fields, so guard against a future edit quietly emptying it out.
1953        let install = &original["cmd"]["subcommands"]["install"];
1954        let purge = install["flags"]
1955            .as_array()
1956            .unwrap()
1957            .iter()
1958            .find(|flag| flag["name"] == "purge")
1959            .unwrap();
1960        assert_eq!(purge["overrides"], serde_json::json!(["-f"]));
1961        assert_eq!(purge["required_unless"], serde_json::json!(["--keep"]));
1962        for key in [
1963            "help_long",
1964            "help_md",
1965            "before_help",
1966            "before_help_long",
1967            "before_help_md",
1968            "after_help",
1969            "after_help_long",
1970            "after_help_md",
1971            "deprecated",
1972            "effect",
1973            "restart_token",
1974            "examples",
1975            "headings",
1976            "complete",
1977            "mounts",
1978            "aliases",
1979            "hidden_aliases",
1980            "outputs",
1981            "select",
1982            "exit_codes",
1983        ] {
1984            let populated = match key {
1985                // These sit on other commands in the fixture.
1986                "deprecated" | "effect" => {
1987                    original["cmd"]["subcommands"]["remove"].get(key).is_some()
1988                }
1989                "restart_token" => original["cmd"]["subcommands"]["run"].get(key).is_some(),
1990                "mounts" => !original["cmd"]["subcommands"]["wrapped"]["mounts"]
1991                    .as_array()
1992                    .unwrap()
1993                    .is_empty(),
1994                _ => match install.get(key) {
1995                    Some(serde_json::Value::Array(a)) => !a.is_empty(),
1996                    Some(serde_json::Value::Object(o)) => !o.is_empty(),
1997                    Some(_) => true,
1998                    None => false,
1999                },
2000            };
2001            assert!(populated, "fixture does not exercise `{key}`");
2002        }
2003
2004        // Flag- and arg-level effects live one level down, so check them
2005        // explicitly rather than by name against the command object.
2006        assert!(
2007            install["flags"]
2008                .as_array()
2009                .unwrap()
2010                .iter()
2011                .any(|f| f.get("effect").is_some()),
2012            "fixture does not exercise a flag-level `effect`"
2013        );
2014        assert!(
2015            install["args"]
2016                .as_array()
2017                .unwrap()
2018                .iter()
2019                .any(|a| a.get("effect").is_some()),
2020            "fixture does not exercise an arg-level `effect`"
2021        );
2022    }
2023    #[cfg(feature = "clap")]
2024    #[test]
2025    fn a_clap_command_says_what_clap_would_do_with_an_unknown_flag() {
2026        use super::{SpecCommand, UnknownFlags};
2027
2028        // clap rejects a dash-word it does not know; this spec's default is to offer it to the
2029        // positionals. Saying nothing therefore loosened every command generated from clap —
2030        // which is how `mise use --globa` became a tool named `--globa` rather than an error.
2031        let plain = clap::Command::new("build")
2032            .arg(clap::Arg::new("target").required(false))
2033            .arg(clap::Arg::new("force").long("force").num_args(0));
2034        let spec: SpecCommand = (&plain).into();
2035        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Error));
2036
2037        // A command that forwards says so, and clap is the one that knows: an argument taking
2038        // hyphen values is what a wrapper looks like.
2039        let wrapper = clap::Command::new("run").arg(
2040            clap::Arg::new("args")
2041                .num_args(0..)
2042                .allow_hyphen_values(true),
2043        );
2044        let spec: SpecCommand = (&wrapper).into();
2045        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Value));
2046
2047        // As does one whose trailing argument swallows the rest.
2048        let trailing = clap::Command::new("exec").arg(
2049            clap::Arg::new("cmd")
2050                .num_args(0..)
2051                .trailing_var_arg(true)
2052                .allow_hyphen_values(true),
2053        );
2054        let spec: SpecCommand = (&trailing).into();
2055        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Value));
2056
2057        // And a command that takes whatever subcommand it is given, which is a different
2058        // shape from forwarding unknown flags: clap still rejects `x --wat`.
2059        let external = clap::Command::new("x").allow_external_subcommands(true);
2060        let spec: SpecCommand = (&external).into();
2061        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Error));
2062        assert!(spec.external_subcommand);
2063    }
2064
2065    #[cfg(feature = "clap")]
2066    #[test]
2067    fn the_decision_survives_being_written_and_read_back() {
2068        use super::SpecCommand;
2069
2070        // The point of setting it is what a *parser* does with the spec afterwards, so the round
2071        // trip is what makes it true rather than the field.
2072        let plain = clap::Command::new("build").arg(clap::Arg::new("target").required(false));
2073        let spec: SpecCommand = (&plain).into();
2074        let node: kdl::KdlNode = (&spec).into();
2075        let kdl = node.to_string();
2076        assert!(kdl.contains("unknown_flags=error"), "{kdl}");
2077    }
2078
2079    #[cfg(feature = "clap")]
2080    #[test]
2081    fn the_clap_bridge_preserves_args_override_self() {
2082        use super::SpecCommand;
2083
2084        let strict: SpecCommand = (&clap::Command::new("strict")).into();
2085        assert!(!strict.args_override_self, "clap is strict by default");
2086
2087        let permissive: SpecCommand =
2088            (&clap::Command::new("permissive").args_override_self(true)).into();
2089        assert!(permissive.args_override_self);
2090
2091        let node: kdl::KdlNode = (&strict).into();
2092        assert!(node.to_string().contains("args_override_self=#false"));
2093    }
2094
2095    #[cfg(feature = "clap")]
2096    #[test]
2097    fn the_clap_bridge_preserves_subcommand_presentation() {
2098        use super::SpecCommand;
2099
2100        let spec: SpecCommand = (&clap::Command::new("ex")
2101            .subcommand(clap::Command::new("run"))
2102            .subcommand_help_heading("Actions")
2103            .subcommand_value_name("ACTION"))
2104            .into();
2105        assert_eq!(spec.subcommand_help_heading.as_deref(), Some("Actions"));
2106        assert_eq!(spec.subcommand_value_name.as_deref(), Some("ACTION"));
2107        let node: kdl::KdlNode = (&spec).into();
2108        let kdl = node.to_string();
2109        assert!(kdl.contains("subcommand_help_heading=Actions"), "{kdl}");
2110        assert!(kdl.contains("subcommand_value_name=ACTION"), "{kdl}");
2111    }
2112
2113    #[cfg(feature = "clap")]
2114    #[test]
2115    fn the_clap_bridge_preserves_subcommand_negates_requirements() {
2116        use super::SpecCommand;
2117
2118        let spec: SpecCommand = (&clap::Command::new("ex").subcommand_negates_reqs(true)).into();
2119        assert!(spec.subcommand_negates_reqs);
2120        let node: kdl::KdlNode = (&spec).into();
2121        assert!(node.to_string().contains("subcommand_negates_reqs=#true"));
2122    }
2123
2124    #[cfg(feature = "clap")]
2125    #[test]
2126    fn the_clap_bridge_preserves_argument_subcommand_conflicts() {
2127        use super::SpecCommand;
2128
2129        let spec: SpecCommand =
2130            (&clap::Command::new("ex").args_conflicts_with_subcommands(true)).into();
2131        assert!(spec.args_conflicts_with_subcommands);
2132        let node: kdl::KdlNode = (&spec).into();
2133        assert!(node
2134            .to_string()
2135            .contains("args_conflicts_with_subcommands=#true"));
2136    }
2137
2138    #[cfg(feature = "clap")]
2139    #[test]
2140    fn the_clap_bridge_preserves_allow_missing_positional() {
2141        use super::SpecCommand;
2142
2143        let spec: SpecCommand = (&clap::Command::new("ex").allow_missing_positional(true)).into();
2144        assert!(spec.allow_missing_positional);
2145        let node: kdl::KdlNode = (&spec).into();
2146        assert!(node.to_string().contains("allow_missing_positional=#true"));
2147    }
2148}