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            if let Some(spelling) = clause.conflicting_flag_spelling(&cmd.flags) {
762                bail_parse!(
763                    ctx,
764                    node.span(),
765                    "clause flag spelling {spelling:?} conflicts with another flag on this command"
766                );
767            }
768        }
769        Ok(cmd)
770    }
771
772    pub(crate) fn validate_sigil_prefixes(&self) -> Result<(), String> {
773        fn validate(cmd: &SpecCommand, ancestors: &[String]) -> Result<(), String> {
774            let mut active = ancestors.to_vec();
775            for sigil in cmd.args.iter().filter_map(|arg| arg.sigil.as_ref()) {
776                if let Some(existing) = active.iter().find(|existing| {
777                    existing.starts_with(sigil.as_str()) || sigil.starts_with(existing.as_str())
778                }) {
779                    return Err(format!(
780                        "argument sigils must not overlap: {existing:?} and {sigil:?}"
781                    ));
782                }
783                active.push(sigil.clone());
784            }
785            for subcommand in cmd.subcommands.values() {
786                validate(subcommand, &active)?;
787            }
788            Ok(())
789        }
790
791        validate(self, &[])
792    }
793
794    pub(crate) fn validate_clause_flag_spellings(&self) -> Result<(), String> {
795        fn validate(cmd: &SpecCommand) -> Result<(), String> {
796            if let Some(clause) = &cmd.clause {
797                if let Some(spelling) = clause.conflicting_flag_spelling(&cmd.flags) {
798                    return Err(format!(
799                        "clause flag spelling {spelling:?} conflicts with another flag on this command"
800                    ));
801                }
802            }
803            for subcommand in cmd.subcommands.values() {
804                validate(subcommand)?;
805            }
806            Ok(())
807        }
808
809        validate(self)
810    }
811    pub(crate) fn is_empty(&self) -> bool {
812        self.args.is_empty()
813            && self.clause.is_none()
814            && self.flags.is_empty()
815            && self.mounts.is_empty()
816            && self.subcommands.is_empty()
817    }
818    pub fn usage(&self) -> String {
819        self.usage_with_subcommands(true)
820    }
821
822    // `cli-help` only, like `SpecChoices::for_help`: the usage line without the subcommand
823    // placeholder is a help-page shape, and nothing else asks for it.
824    #[cfg(feature = "cli-help")]
825    pub(crate) fn usage_without_subcommands(&self) -> String {
826        self.usage_with_subcommands(false)
827    }
828
829    fn usage_with_subcommands(&self, include_subcommands: bool) -> String {
830        let mut usage = self.full_cmd.join(" ");
831        let flags = self
832            .flags
833            .iter()
834            .filter(|f| !f.hide && !f.builtin)
835            .collect_vec();
836        let args = self.args.iter().filter(|a| !a.hide).collect_vec();
837        if !flags.is_empty() {
838            if flags.len() <= 2 {
839                let inlines = flags
840                    .iter()
841                    .map(|f| {
842                        if f.required {
843                            format!("<{}>", f.usage())
844                        } else {
845                            format!("[{}]", f.usage())
846                        }
847                    })
848                    .join(" ");
849                usage = format!("{usage} {inlines}").trim().to_string();
850            } else if flags.iter().any(|f| f.required) {
851                usage = format!("{usage} <FLAGS>");
852            } else {
853                usage = format!("{usage} [FLAGS]");
854            }
855        }
856        if !args.is_empty() {
857            if args.len() <= 2 {
858                let inlines = args.iter().map(|a| a.usage()).join(" ");
859                usage = format!("{usage} {inlines}").trim().to_string();
860            } else if args.iter().any(|a| a.required) {
861                usage = format!("{usage} <ARGS>…");
862            } else {
863                usage = format!("{usage} [ARGS]…");
864            }
865        }
866        if let Some(clause) = &self.clause {
867            usage = format!("{usage} {}", clause.usage());
868        }
869        // TODO: mounts?
870        // if !self.mounts.is_empty() {
871        //     name = format!("{name} [mounts]");
872        // }
873        if include_subcommands && !self.subcommands.is_empty() {
874            let name = self
875                .subcommand_value_name
876                .as_deref()
877                .unwrap_or("SUBCOMMAND");
878            usage = format!("{usage} <{name}>");
879        }
880        usage.trim().to_string()
881    }
882    /// Forget which subcommands this command was asked for.
883    ///
884    /// `find_subcommand` memoizes names and aliases into a `OnceLock`, so anything that adds or
885    /// removes a subcommand has to say so or the lookup keeps answering for the old set.
886    pub(crate) fn reset_subcommand_lookup(&mut self) {
887        self.subcommand_lookup = OnceLock::new();
888    }
889
890    pub(crate) fn merge(&mut self, other: Self) {
891        // Merging can add subcommands and aliases, and `find_subcommand` memoizes
892        // its lookup into a OnceLock — so the cache has to go, or a name that
893        // arrived here would not be findable. This worked before only because
894        // mounting happened to precede the first lookup on a given command.
895        self.subcommand_lookup = OnceLock::new();
896        // Destructured exhaustively (no `..`) so that adding a field to
897        // SpecCommand fails to compile until this decides what merging it means.
898        // Runtime-derived fields are explicitly ignored rather than skipped.
899        let Self {
900            name,
901            help,
902            help_long,
903            help_md,
904            before_help,
905            before_help_long,
906            before_help_md,
907            after_help,
908            after_help_long,
909            after_help_md,
910            args,
911            clause,
912            flags,
913            uses,
914            mounts,
915            groups,
916            aliases,
917            hidden_aliases,
918            examples,
919            headings,
920            outputs,
921            select,
922            exit_codes,
923            hide,
924            help_heading,
925            surface,
926            available_if,
927            display_order,
928            subcommand_required,
929            subcommand_help_heading,
930            subcommand_value_name,
931            next_line_help,
932            flatten_help,
933            term_width,
934            max_term_width,
935            external_subcommand,
936            arg_required_else_help,
937            disable_help_flag,
938            disable_help_subcommand,
939            disable_version_flag,
940            dont_delimit_trailing_values,
941            args_override_self,
942            subcommand_negates_reqs,
943            args_conflicts_with_subcommands,
944            subcommand_precedence_over_arg,
945            allow_missing_positional,
946            restart_token,
947            subcommands,
948            complete,
949            deprecated,
950            deprecated_warn_at,
951            deprecated_remove_at,
952            effect,
953            unknown_flags,
954            // Recomputed from the merged command, never carried over.
955            full_cmd: _,
956            usage: _,
957            mounted: _,
958            flags_from_mount: _,
959            subcommand_lookup: _,
960        } = other;
961        if !name.is_empty() {
962            self.name = name;
963        }
964        if help.is_some() {
965            self.help = help;
966        }
967        if help_long.is_some() {
968            self.help_long = help_long;
969        }
970        if help_md.is_some() {
971            self.help_md = help_md;
972        }
973        if before_help.is_some() {
974            self.before_help = before_help;
975        }
976        if before_help_long.is_some() {
977            self.before_help_long = before_help_long;
978        }
979        if before_help_md.is_some() {
980            self.before_help_md = before_help_md;
981        }
982        if after_help.is_some() {
983            self.after_help = after_help;
984        }
985        if after_help_long.is_some() {
986            self.after_help_long = after_help_long;
987        }
988        if after_help_md.is_some() {
989            self.after_help_md = after_help_md;
990        }
991        if !args.is_empty() {
992            self.args = args;
993        }
994        if clause.is_some() {
995            self.clause = clause;
996        }
997        let flags_replaced = !flags.is_empty();
998        if flags_replaced {
999            self.flags = flags;
1000        }
1001        // Unresolved `use` nodes travel with the flags they were written among, for the same
1002        // reason groups do — including when that means going with none. A `use` is a
1003        // declaration of flags, so whoever owns the flag list owns it: an included file that
1004        // replaces this command's flags replaces what it says about them, and a `use` left
1005        // behind would splice a set into the incoming list at a position from the old one.
1006        //
1007        // `other.uses` is normally empty either way: a spec resolves its own sets before it
1008        // can be merged into another, and what arrives here has been through that already.
1009        if flags_replaced || !uses.is_empty() {
1010            self.uses = uses;
1011        }
1012        if !mounts.is_empty() {
1013            self.mounts = mounts;
1014        }
1015        // Groups travel with the flags they name. A mounted spec that replaces this
1016        // command's flags replaces its groups too — including with none, which is the
1017        // case that matters: keeping the old set would enforce exclusivity between flags
1018        // that are no longer here, and a required group whose members nothing answers to
1019        // would reject every invocation.
1020        if flags_replaced || !groups.is_empty() {
1021            self.groups = groups;
1022        }
1023        if !aliases.is_empty() {
1024            self.aliases = aliases;
1025        }
1026        if !hidden_aliases.is_empty() {
1027            self.hidden_aliases = hidden_aliases;
1028        }
1029        if !examples.is_empty() {
1030            self.examples = examples;
1031        }
1032        if !headings.is_empty() {
1033            self.headings = headings;
1034        }
1035        // Outputs describe what the *mounted* program writes, so they move with the flags
1036        // rather than being folded into what was here — the same reason groups follow the
1037        // flags they name.
1038        if flags_replaced || !outputs.is_empty() {
1039            self.outputs = outputs;
1040        }
1041        if flags_replaced || select.is_some() {
1042            self.select = select;
1043        }
1044        if !exit_codes.is_empty() {
1045            self.exit_codes = exit_codes;
1046        }
1047        self.hide = hide;
1048        if help_heading.is_some() {
1049            self.help_heading = help_heading;
1050        }
1051        if surface.is_some() {
1052            self.surface = surface;
1053        }
1054        if !available_if.is_empty() {
1055            self.available_if = available_if;
1056        }
1057        if display_order.is_some() {
1058            self.display_order = display_order;
1059        }
1060        self.subcommand_required = subcommand_required;
1061        if subcommand_help_heading.is_some() {
1062            self.subcommand_help_heading = subcommand_help_heading;
1063        }
1064        if subcommand_value_name.is_some() {
1065            self.subcommand_value_name = subcommand_value_name;
1066        }
1067        self.next_line_help = next_line_help;
1068        self.flatten_help = flatten_help;
1069        if term_width.is_some() {
1070            self.term_width = term_width;
1071        }
1072        if max_term_width.is_some() {
1073            self.max_term_width = max_term_width;
1074        }
1075        self.external_subcommand = external_subcommand;
1076        self.arg_required_else_help = arg_required_else_help;
1077        self.disable_help_flag = disable_help_flag;
1078        self.disable_help_subcommand = disable_help_subcommand;
1079        self.disable_version_flag = disable_version_flag;
1080        self.dont_delimit_trailing_values = dont_delimit_trailing_values;
1081        self.args_override_self = args_override_self;
1082        self.subcommand_negates_reqs = subcommand_negates_reqs;
1083        self.args_conflicts_with_subcommands = args_conflicts_with_subcommands;
1084        self.subcommand_precedence_over_arg = subcommand_precedence_over_arg;
1085        self.allow_missing_positional = allow_missing_positional;
1086        if effect.is_some() {
1087            self.effect = effect;
1088        }
1089        if unknown_flags.is_some() {
1090            self.unknown_flags = unknown_flags;
1091        }
1092        if deprecated.is_some() {
1093            self.deprecated = deprecated;
1094        }
1095        if deprecated_warn_at.is_some() {
1096            self.deprecated_warn_at = deprecated_warn_at;
1097        }
1098        if deprecated_remove_at.is_some() {
1099            self.deprecated_remove_at = deprecated_remove_at;
1100        }
1101        if restart_token.is_some() {
1102            self.restart_token = restart_token;
1103        }
1104        for (name, cmd) in subcommands {
1105            self.subcommands.insert(name, cmd);
1106        }
1107        for (name, complete) in complete {
1108            self.complete.insert(name, complete);
1109        }
1110    }
1111
1112    pub fn all_subcommands(&self) -> Vec<&SpecCommand> {
1113        let mut cmds = vec![];
1114        for cmd in self.subcommands.values() {
1115            cmds.push(cmd);
1116            cmds.extend(cmd.all_subcommands());
1117        }
1118        cmds
1119    }
1120
1121    pub fn find_subcommand(&self, name: &str) -> Option<&SpecCommand> {
1122        let sl = self.subcommand_lookup.get_or_init(|| {
1123            let mut map = HashMap::new();
1124            // Names first, then aliases only where nothing answers already: a
1125            // command's own name outranks another command's alias, so reordering
1126            // `cmd` blocks cannot change which command a word selects.
1127            //
1128            // Inserting both in one pass instead let the *last* declaration win,
1129            // which was the opposite of what usage-argv did with the same spec —
1130            // it takes the first. Neither was a rule anyone had chosen.
1131            for name in self.subcommands.keys() {
1132                map.insert(name.clone(), name.clone());
1133            }
1134            for (name, cmd) in &self.subcommands {
1135                for alias in cmd.aliases.iter().chain(&cmd.hidden_aliases) {
1136                    map.entry(alias.clone()).or_insert_with(|| name.clone());
1137                }
1138            }
1139            map
1140        });
1141        let name = sl.get(name)?;
1142        self.subcommands.get(name)
1143    }
1144
1145    pub(crate) fn mount(
1146        &mut self,
1147        global_flag_args: &[String],
1148        injected: Option<&HashMap<String, String>>,
1149    ) -> Result<(), UsageErr> {
1150        for mount in self.mounts.iter().cloned().collect_vec() {
1151            let cmd = if global_flag_args.is_empty() {
1152                mount.run.clone()
1153            } else {
1154                // Parse the mount command into tokens, insert global flags after the first token
1155                // e.g., "mise tasks ls" becomes "mise --cd dir2 tasks ls"
1156                // Handles quoted arguments correctly: "cmd 'arg with spaces'" stays correct
1157                let mut tokens = crate::shell_words::split(&mount.run)
1158                    .expect("mount command should be valid shell syntax");
1159                if !tokens.is_empty() {
1160                    // Insert global flags after the first token (the command name)
1161                    tokens.splice(1..1, global_flag_args.iter().cloned());
1162                }
1163                // Join tokens back into a properly quoted command string
1164                crate::shell_words::join(tokens)
1165            };
1166            let output = match injected {
1167                Some(outputs) => outputs
1168                    .get(&mount.run)
1169                    .cloned()
1170                    .ok_or_else(|| UsageErr::MissingMountOutput(mount.run.clone()))?,
1171                None => sh(&cmd)?,
1172            };
1173            let mut spec: Spec = output.parse()?;
1174            if let Some(outputs) = injected {
1175                // A mounted spec's root is merged into this command, so its root-only
1176                // default-subcommand precedence does not apply while composing mounts.
1177                spec.resolve_mount_outputs_at_root(outputs, false)?;
1178            }
1179            // The subcommands emitted by a mount describe another program, so mark them (and
1180            // everything below them) as mounted. See `SpecCommand::mounted`.
1181            for cmd in spec.cmd.subcommands.values_mut() {
1182                cmd.mark_mounted();
1183            }
1184            // `merge` folds the mounted spec's root flags into this command; remember that they
1185            // came from the mount. See `SpecCommand::flags_from_mount`.
1186            self.flags_from_mount |= !spec.cmd.flags.is_empty();
1187            self.merge(spec.cmd);
1188        }
1189        self.validate_clause_flag_spellings()
1190            .map_err(UsageErr::InvalidSpec)
1191    }
1192
1193    /// Mark this command and all of its subcommands as coming from a mount.
1194    pub(crate) fn mark_mounted(&mut self) {
1195        self.mounted = true;
1196        for cmd in self.subcommands.values_mut() {
1197            cmd.mark_mounted();
1198        }
1199    }
1200}
1201
1202impl From<&SpecCommand> for KdlNode {
1203    fn from(cmd: &SpecCommand) -> Self {
1204        // Destructured exhaustively (no `..`) so that adding a field to
1205        // SpecCommand fails to compile until this decides how to serialize it.
1206        let SpecCommand {
1207            name,
1208            hide,
1209            help_heading,
1210            surface,
1211            available_if,
1212            display_order,
1213            subcommand_required,
1214            subcommand_help_heading,
1215            subcommand_value_name,
1216            next_line_help,
1217            flatten_help,
1218            term_width,
1219            max_term_width,
1220            external_subcommand,
1221            arg_required_else_help,
1222            disable_help_flag,
1223            disable_help_subcommand,
1224            disable_version_flag,
1225            dont_delimit_trailing_values,
1226            args_override_self,
1227            subcommand_negates_reqs,
1228            args_conflicts_with_subcommands,
1229            subcommand_precedence_over_arg,
1230            allow_missing_positional,
1231            restart_token,
1232            unknown_flags,
1233            aliases,
1234            hidden_aliases,
1235            help,
1236            help_long,
1237            help_md,
1238            before_help,
1239            before_help_long,
1240            before_help_md,
1241            after_help,
1242            after_help_long,
1243            after_help_md,
1244            deprecated,
1245            deprecated_warn_at,
1246            deprecated_remove_at,
1247            effect,
1248            flags,
1249            args,
1250            clause,
1251            mounts,
1252            groups,
1253            subcommands,
1254            complete,
1255            examples,
1256            headings,
1257            outputs,
1258            select,
1259            exit_codes,
1260            // Resolved while the spec was read: whatever a `use` named is among `flags`
1261            // by now, so emitting the request too would declare those flags twice.
1262            uses: _,
1263            // Derived from the spec rather than written by it.
1264            full_cmd: _,
1265            usage: _,
1266            mounted: _,
1267            flags_from_mount: _,
1268            subcommand_lookup: _,
1269        } = cmd;
1270        let mut node = Self::new("cmd");
1271        node.entries_mut().push(name.clone().into());
1272        if *hide {
1273            node.entries_mut().push(KdlEntry::new_prop("hide", true));
1274        }
1275        if let Some(heading) = help_heading {
1276            node.entries_mut()
1277                .push(KdlEntry::new_prop("help_heading", heading.clone()));
1278        }
1279        if let Some(surface) = surface {
1280            node.push(KdlEntry::new_prop("surface", surface.clone()));
1281        }
1282        if !available_if.is_empty() {
1283            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1284            let mut condition = KdlNode::new("available_if");
1285            for value in available_if {
1286                condition.push(string_entry(None, value));
1287            }
1288            children.nodes_mut().push(condition);
1289        }
1290        if let Some(order) = display_order {
1291            node.entries_mut()
1292                .push(KdlEntry::new_prop("display_order", *order as i128));
1293        }
1294        if *subcommand_required {
1295            node.entries_mut()
1296                .push(KdlEntry::new_prop("subcommand_required", true));
1297        }
1298        if let Some(heading) = subcommand_help_heading {
1299            node.push(KdlEntry::new_prop(
1300                "subcommand_help_heading",
1301                heading.clone(),
1302            ));
1303        }
1304        if let Some(name) = subcommand_value_name {
1305            node.push(KdlEntry::new_prop("subcommand_value_name", name.clone()));
1306        }
1307        if *next_line_help {
1308            node.push(KdlEntry::new_prop("next_line_help", true));
1309        }
1310        if *flatten_help {
1311            node.push(KdlEntry::new_prop("flatten_help", true));
1312        }
1313        if let Some(width) = term_width {
1314            node.push(KdlEntry::new_prop("term_width", *width as i128));
1315        }
1316        if let Some(width) = max_term_width {
1317            node.push(KdlEntry::new_prop("max_term_width", *width as i128));
1318        }
1319        if *external_subcommand {
1320            node.entries_mut()
1321                .push(KdlEntry::new_prop("external_subcommand", true));
1322        }
1323        if *arg_required_else_help {
1324            node.entries_mut()
1325                .push(KdlEntry::new_prop("arg_required_else_help", true));
1326        }
1327        if *disable_help_flag {
1328            node.push(KdlEntry::new_prop("disable_help_flag", true));
1329        }
1330        if *disable_help_subcommand {
1331            node.push(KdlEntry::new_prop("disable_help_subcommand", true));
1332        }
1333        if *disable_version_flag {
1334            node.push(KdlEntry::new_prop("disable_version_flag", true));
1335        }
1336        if *dont_delimit_trailing_values {
1337            node.entries_mut()
1338                .push(KdlEntry::new_prop("dont_delimit_trailing_values", true));
1339        }
1340        if !*args_override_self {
1341            node.push(KdlEntry::new_prop("args_override_self", false));
1342        }
1343        if *subcommand_negates_reqs {
1344            node.push(KdlEntry::new_prop("subcommand_negates_reqs", true));
1345        }
1346        if *args_conflicts_with_subcommands {
1347            node.push(KdlEntry::new_prop("args_conflicts_with_subcommands", true));
1348        }
1349        if *subcommand_precedence_over_arg {
1350            node.push(KdlEntry::new_prop("subcommand_precedence_over_arg", true));
1351        }
1352        if *allow_missing_positional {
1353            node.push(KdlEntry::new_prop("allow_missing_positional", true));
1354        }
1355        if let Some(restart_token) = &restart_token {
1356            node.entries_mut()
1357                .push(KdlEntry::new_prop("restart_token", restart_token.clone()));
1358        }
1359        if !aliases.is_empty() {
1360            let mut alias_node = KdlNode::new("alias");
1361            for alias in aliases {
1362                alias_node.entries_mut().push(alias.clone().into());
1363            }
1364            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1365            children.nodes_mut().push(alias_node);
1366        }
1367        if !hidden_aliases.is_empty() {
1368            let mut alias_node = KdlNode::new("alias");
1369            for alias in hidden_aliases {
1370                alias_node.entries_mut().push(alias.clone().into());
1371            }
1372            alias_node
1373                .entries_mut()
1374                .push(KdlEntry::new_prop("hide", true));
1375            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1376            children.nodes_mut().push(alias_node);
1377        }
1378        if let Some(help) = &help {
1379            node.entries_mut().push(string_entry(Some("help"), help));
1380        }
1381        if let Some(help) = &help_long {
1382            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1383            let mut node = KdlNode::new("long_help");
1384            node.push(string_entry(None, help));
1385            children.nodes_mut().push(node);
1386        }
1387        if let Some(help) = &help_md {
1388            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1389            let mut node = KdlNode::new("help_md");
1390            node.push(string_entry(None, help));
1391            children.nodes_mut().push(node);
1392        }
1393        if let Some(help) = &before_help {
1394            node.entries_mut()
1395                .push(string_entry(Some("before_help"), help));
1396        }
1397        if let Some(help) = &before_help_long {
1398            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1399            let mut node = KdlNode::new("before_long_help");
1400            node.push(string_entry(None, help));
1401            children.nodes_mut().push(node);
1402        }
1403        if let Some(help) = &before_help_md {
1404            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1405            let mut node = KdlNode::new("before_help_md");
1406            node.push(string_entry(None, help));
1407            children.nodes_mut().push(node);
1408        }
1409        if let Some(help) = &after_help {
1410            node.entries_mut()
1411                .push(string_entry(Some("after_help"), help));
1412        }
1413        if let Some(help) = &after_help_long {
1414            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1415            let mut node = KdlNode::new("after_long_help");
1416            node.push(string_entry(None, help));
1417            children.nodes_mut().push(node);
1418        }
1419        if let Some(help) = &after_help_md {
1420            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1421            let mut node = KdlNode::new("after_help_md");
1422            node.push(string_entry(None, help));
1423            children.nodes_mut().push(node);
1424        }
1425        if let Some(deprecated) = &deprecated {
1426            node.entries_mut()
1427                .push(string_entry(Some("deprecated"), deprecated));
1428        }
1429        if let Some(at) = deprecated_warn_at {
1430            node.push(string_entry(Some("deprecated_warn_at"), at));
1431        }
1432        if let Some(at) = deprecated_remove_at {
1433            node.push(string_entry(Some("deprecated_remove_at"), at));
1434        }
1435        if let Some(effect) = effect {
1436            node.entries_mut()
1437                .push(string_entry(Some("effect"), effect.as_str()));
1438        }
1439        if let Some(unknown_flags) = unknown_flags {
1440            node.entries_mut()
1441                .push(string_entry(Some("unknown_flags"), unknown_flags.as_str()));
1442        }
1443        for flag in flags {
1444            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1445            children.nodes_mut().push(flag.into());
1446        }
1447        for arg in args {
1448            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1449            children.nodes_mut().push(arg.into());
1450        }
1451        if let Some(clause) = clause {
1452            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1453            children.nodes_mut().push(clause.into());
1454        }
1455        for mount in mounts {
1456            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1457            children.nodes_mut().push(mount.into());
1458        }
1459        // After the flags they name, so a reader meets the members before the rule
1460        // about them.
1461        for group in groups {
1462            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1463            children.nodes_mut().push(group.into());
1464        }
1465        for cmd in subcommands.values() {
1466            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1467            children.nodes_mut().push(cmd.into());
1468        }
1469        for example in examples {
1470            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1471            children.nodes_mut().push(example.into());
1472        }
1473        for heading in headings {
1474            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1475            children.nodes_mut().push(heading.into());
1476        }
1477        // Outputs before the flag that picks among them, so a reader meets the things
1478        // being chosen before the rule for choosing — the same order groups follow.
1479        for output in outputs {
1480            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1481            children.nodes_mut().push(output.into());
1482        }
1483        if let Some(select) = select {
1484            let mut select_node = KdlNode::new("select");
1485            select_node.push(string_entry(None, select));
1486            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1487            children.nodes_mut().push(select_node);
1488        }
1489        for exit_code in exit_codes {
1490            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1491            children.nodes_mut().push(exit_code.into());
1492        }
1493        for complete in complete.values() {
1494            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
1495            children.nodes_mut().push(complete.into());
1496        }
1497        node
1498    }
1499}
1500
1501#[cfg(feature = "clap")]
1502impl From<&clap::Command> for SpecCommand {
1503    fn from(cmd: &clap::Command) -> Self {
1504        let mut spec = Self {
1505            name: cmd.get_name().to_string(),
1506            hide: cmd.is_hide_set(),
1507            help: cmd.get_about().map(|s| s.to_string()),
1508            help_long: cmd.get_long_about().map(|s| s.to_string()),
1509            before_help: cmd.get_before_help().map(|s| s.to_string()),
1510            before_help_long: cmd.get_before_long_help().map(|s| s.to_string()),
1511            after_help: cmd.get_after_help().map(|s| s.to_string()),
1512            after_help_long: cmd.get_after_long_help().map(|s| s.to_string()),
1513            ..Default::default()
1514        };
1515        // What clap would do with a dash-word it does not recognize, said out loud.
1516        //
1517        // clap rejects one; this spec's default is to offer it to the positionals, because a
1518        // spec also describes wrappers — a script run through `usage exec`, a task's arguments —
1519        // where a dash-word is data in transit rather than a mistake. A CLI generated *from
1520        // clap*, though, is not one of those: clap already decided, and saying nothing here
1521        // silently loosened every command it described. mise's spec has 211 commands and not one
1522        // of them said `unknown_flags`, so `mise use --globa` became a tool named `--globa`
1523        // rather than the error clap gives.
1524        //
1525        // Which commands forward unknown *flags* is clap's own knowledge: an argument that
1526        // accepts hyphen values, or a trailing var arg. In mise that is five commands —
1527        // `run`, `watch`, `asdf`, `tool-stub` and the root's implicit task arguments — and
1528        // the other two hundred get the stricter reading back.
1529        //
1530        // An external subcommand is a different shape: an unmatched *word* is forwarded with
1531        // the rest of argv. clap still rejects an unknown flag on such a command (`x --wat`),
1532        // so mapping `allow_external_subcommands` onto `unknown_flags=value` silently loosened
1533        // every clap CLI that allowed one.
1534        spec.external_subcommand = cmd.is_allow_external_subcommands_set();
1535        let forwards = cmd
1536            .get_arguments()
1537            .any(|arg| arg.is_allow_hyphen_values_set() || arg.is_trailing_var_arg_set());
1538        spec.unknown_flags = Some(if forwards {
1539            UnknownFlags::Value
1540        } else {
1541            UnknownFlags::Error
1542        });
1543
1544        for alias in cmd.get_visible_aliases() {
1545            spec.aliases.push(alias.to_string());
1546        }
1547        for alias in cmd.get_all_aliases() {
1548            if spec.aliases.contains(&alias.to_string()) {
1549                continue;
1550            }
1551            spec.hidden_aliases.push(alias.to_string());
1552        }
1553        for arg in cmd.get_arguments() {
1554            let complete_type = crate::spec::arg::value_hint_type(arg.get_value_hint());
1555            let conflicts: Vec<String> = cmd
1556                .get_arg_conflicts_with(arg)
1557                .iter()
1558                .filter_map(|other| match (other.get_long(), other.get_short()) {
1559                    (Some(long), _) => Some(format!("--{long}")),
1560                    (None, Some(short)) => Some(format!("-{short}")),
1561                    (None, None) if other.is_positional() => Some(SpecArg::from(*other).name),
1562                    (None, None) => None,
1563                })
1564                .collect();
1565            if arg.is_positional() {
1566                let mut positional: SpecArg = arg.into();
1567                positional.allow_negative_numbers |= cmd.is_allow_negative_numbers_set();
1568                positional.conflicts = conflicts;
1569                if let Some(type_) = complete_type {
1570                    let name = positional.name.to_lowercase();
1571                    spec.complete.insert(
1572                        name.clone(),
1573                        SpecComplete {
1574                            name,
1575                            type_: Some(type_.to_string()),
1576                            ..Default::default()
1577                        },
1578                    );
1579                }
1580                spec.args.push(positional)
1581            } else {
1582                let mut flag: SpecFlag = arg.into();
1583                if let Some(value) = &mut flag.arg {
1584                    value.allow_negative_numbers |= cmd.is_allow_negative_numbers_set();
1585                }
1586                // clap keeps conflicts on the command rather than on the argument, so
1587                // this is the only place both are in view. Written with dashes,
1588                // matching how the spec refers to a flag everywhere else.
1589                //
1590                // A short-only flag is named `-s`, which selectors accept as readily as
1591                // `--long`: taking only the long form would have dropped the conflict
1592                // and let the spec accept a combination clap rejects.
1593                flag.conflicts = conflicts;
1594                if let (Some(type_), Some(value)) = (complete_type, flag.arg.as_ref()) {
1595                    let name = value.name.to_lowercase();
1596                    spec.complete.insert(
1597                        name.clone(),
1598                        SpecComplete {
1599                            name,
1600                            type_: Some(type_.to_string()),
1601                            ..Default::default()
1602                        },
1603                    );
1604                }
1605                spec.flags.push(flag)
1606            }
1607        }
1608        // clap assigns an implicit monotonically increasing order to arguments. Emitting
1609        // that number for every ordinary declaration makes generated specs noisy without
1610        // changing presentation, since usage already retains declaration order. Keep the
1611        // values only when they actually reorder a section.
1612        if spec
1613            .args
1614            .windows(2)
1615            .all(|pair| pair[0].display_order <= pair[1].display_order)
1616        {
1617            for arg in &mut spec.args {
1618                arg.display_order = None;
1619            }
1620        }
1621        if spec
1622            .flags
1623            .windows(2)
1624            .all(|pair| pair[0].display_order <= pair[1].display_order)
1625        {
1626            for flag in &mut spec.flags {
1627                flag.display_order = None;
1628            }
1629        }
1630        // Groups, which clap does expose — `get_groups`, and `get_args` on each. A group
1631        // names its members by clap's internal id, so each is resolved back to the flag it
1632        // points at and written as a selector, the way conflicts are just above.
1633        //
1634        // clap's own `--help` groups (`ArgGroup` ids it creates for its built-in flags)
1635        // have no members of ours in them, so the two-member floor drops them naturally
1636        // rather than needing a name check.
1637        for group in cmd.get_groups() {
1638            let members: Vec<String> = group
1639                .get_args()
1640                .filter_map(|id| cmd.get_arguments().find(|arg| arg.get_id() == id))
1641                .filter_map(|arg| match (arg.get_long(), arg.get_short()) {
1642                    (Some(long), _) => Some(format!("--{long}")),
1643                    (None, Some(short)) => Some(format!("-{short}")),
1644                    (None, None) if arg.is_positional() => Some(SpecArg::from(arg).name),
1645                    (None, None) => None,
1646                })
1647                .collect();
1648            // Below two members there is no rule left to enforce: whatever the group said
1649            // about "at most one" or "at least one" is either vacuous or is plain
1650            // required-ness on the single flag, which the flag already carries.
1651            if members.len() < 2 {
1652                continue;
1653            }
1654            // `multiple` without `required` enforces nothing at all — any number of
1655            // members, none of them needed — so there is nothing to carry across.
1656            //
1657            // This is not a corner case. clap's *derive* emits exactly that group for
1658            // every `#[derive(Args)]` struct, named after the struct and holding all its
1659            // fields, to make `flatten` work: `clap_derive`'s `args.rs` builds
1660            // `ArgGroup::new(id).multiple(true)`. Carrying them would put a `group Lint
1661            // …` in the spec of every clap-derived CLI, including this repository's own,
1662            // describing bookkeeping rather than a rule anyone declared.
1663            let required = group.is_required_set();
1664            // `is_multiple` takes `&mut self` in clap, and a `&ArgGroup` is all a
1665            // `Command` hands out — so the group is cloned to ask. Once per group at
1666            // spec-generation time, which is a build step rather than a parse.
1667            let multiple = group.clone().is_multiple();
1668            if multiple && !required {
1669                continue;
1670            }
1671            let mut spec_group = SpecGroup::new(group.get_id().as_str(), members);
1672            spec_group.required = required;
1673            spec_group.multiple = multiple;
1674            spec.groups.push(spec_group);
1675        }
1676        spec.subcommand_required = cmd.is_subcommand_required_set();
1677        spec.subcommand_help_heading = cmd.get_subcommand_help_heading().map(str::to_string);
1678        spec.subcommand_value_name = cmd.get_subcommand_value_name().map(str::to_string);
1679        spec.next_line_help = cmd.is_next_line_help_set();
1680        spec.flatten_help = cmd.is_flatten_help_set();
1681        spec.arg_required_else_help = cmd.is_arg_required_else_help_set();
1682        spec.disable_help_flag = cmd.is_disable_help_flag_set();
1683        spec.disable_help_subcommand =
1684            cmd.get_subcommands().next().is_some() && cmd.is_disable_help_subcommand_set();
1685        spec.disable_version_flag = (cmd.get_version().is_some()
1686            || cmd.get_long_version().is_some())
1687            && cmd.is_disable_version_flag_set();
1688        spec.dont_delimit_trailing_values = cmd.is_dont_delimit_trailing_values_set();
1689        spec.args_override_self = cmd.is_args_override_self();
1690        spec.subcommand_negates_reqs = cmd.is_subcommand_negates_reqs_set();
1691        spec.args_conflicts_with_subcommands = cmd.is_args_conflicts_with_subcommands_set();
1692        spec.subcommand_precedence_over_arg = cmd.is_subcommand_precedence_over_arg_set();
1693        spec.allow_missing_positional = cmd.is_allow_missing_positional_set();
1694        for subcmd in cmd.get_subcommands() {
1695            let mut scmd: SpecCommand = subcmd.into();
1696            scmd.name = subcmd.get_name().to_string();
1697            scmd.display_order = Some(subcmd.get_display_order());
1698            spec.subcommands.insert(scmd.name.clone(), scmd);
1699        }
1700        // 999 is clap's ordinary subcommand order. Leaving every command at that value lets
1701        // usage's existing alphabetical tie-breaker produce the same page without serializing
1702        // redundant metadata.
1703        if spec
1704            .subcommands
1705            .iter()
1706            .all(|(_, subcommand)| subcommand.display_order == Some(999))
1707        {
1708            for (_, subcommand) in &mut spec.subcommands {
1709                subcommand.display_order = None;
1710            }
1711        }
1712        spec
1713    }
1714}
1715
1716#[cfg(feature = "clap")]
1717impl From<clap::Command> for Spec {
1718    fn from(cmd: clap::Command) -> Self {
1719        (&cmd).into()
1720    }
1721}
1722
1723#[cfg(test)]
1724mod tests {
1725    use crate::spec::effect::SpecCommandEffect;
1726    use crate::Spec;
1727    use insta::assert_snapshot;
1728
1729    #[test]
1730    fn overlapping_sigils_are_rejected_on_one_command_and_across_subcommands() {
1731        for spec in [
1732            r#"bin "ex"
1733arg "[short]..." sigil="+"
1734arg "[long]..." sigil="++"
1735"#,
1736            r#"bin "ex"
1737arg "[short]..." sigil="+"
1738cmd "run" { arg "[long]..." sigil="++" }
1739"#,
1740        ] {
1741            let error = Spec::parse(&Default::default(), spec).unwrap_err();
1742            assert!(
1743                format!("{error:?}").contains("argument sigils must not overlap"),
1744                "{error:?}"
1745            );
1746        }
1747    }
1748
1749    #[test]
1750    fn test_effect_prop_and_child_node() {
1751        let spec = Spec::parse(
1752            &Default::default(),
1753            r#"
1754bin "mise"
1755cmd "ls" effect="read"
1756cmd "use" effect="write"
1757cmd "uninstall" {
1758    effect "destructive"
1759}
1760cmd "version"
1761            "#,
1762        )
1763        .unwrap();
1764
1765        let cmds = &spec.cmd.subcommands;
1766        assert_eq!(cmds["ls"].effect, Some(SpecCommandEffect::Read));
1767        assert_eq!(cmds["use"].effect, Some(SpecCommandEffect::Write));
1768        assert_eq!(
1769            cmds["uninstall"].effect,
1770            Some(SpecCommandEffect::Destructive)
1771        );
1772        // Unspecified stays unknown rather than defaulting to anything.
1773        assert_eq!(cmds["version"].effect, None);
1774    }
1775
1776    #[test]
1777    fn test_effect_is_not_inherited_by_subcommands() {
1778        let spec = Spec::parse(
1779            &Default::default(),
1780            r#"
1781bin "git"
1782cmd "remote" effect="read" {
1783    cmd "add" effect="write"
1784    cmd "show"
1785}
1786            "#,
1787        )
1788        .unwrap();
1789
1790        let remote = &spec.cmd.subcommands["remote"];
1791        assert_eq!(remote.effect, Some(SpecCommandEffect::Read));
1792        assert_eq!(
1793            remote.subcommands["add"].effect,
1794            Some(SpecCommandEffect::Write)
1795        );
1796        assert_eq!(remote.subcommands["show"].effect, None);
1797    }
1798
1799    #[test]
1800    fn test_effect_roundtrips_through_kdl() {
1801        let spec = Spec::parse(
1802            &Default::default(),
1803            r#"
1804bin "mise"
1805cmd "ls" effect="read"
1806cmd "uninstall" effect="destructive"
1807            "#,
1808        )
1809        .unwrap();
1810
1811        assert_snapshot!(spec, @r#"
1812        name mise
1813        bin mise
1814        cmd ls effect=read
1815        cmd uninstall effect=destructive
1816        "#);
1817    }
1818
1819    /// `merge` is how included and mounted specs are composed onto a command.
1820    /// It has to treat `effect` the way it treats every other optional field:
1821    /// an overlay that says nothing must not erase what is already declared.
1822    #[test]
1823    fn test_effect_survives_merge() {
1824        let cmd_with = |src: &str| {
1825            Spec::parse(&Default::default(), src)
1826                .unwrap()
1827                .cmd
1828                .subcommands["uninstall"]
1829                .clone()
1830        };
1831
1832        let declared = cmd_with(r#"cmd "uninstall" effect="destructive""#);
1833        let silent = cmd_with(r#"cmd "uninstall" help="Remove a tool""#);
1834        let contradicting = cmd_with(r#"cmd "uninstall" effect="write""#);
1835
1836        let mut cmd = declared.clone();
1837        cmd.merge(silent);
1838        assert_eq!(cmd.effect, Some(SpecCommandEffect::Destructive));
1839
1840        let mut cmd = declared;
1841        cmd.merge(contradicting);
1842        assert_eq!(cmd.effect, Some(SpecCommandEffect::Write));
1843    }
1844
1845    #[test]
1846    fn test_unknown_effect_is_an_error() {
1847        let err = Spec::parse(
1848            &Default::default(),
1849            r#"
1850bin "mise"
1851cmd "ls" effect="readonly"
1852            "#,
1853        )
1854        .unwrap_err();
1855        assert!(
1856            err.to_string().contains("Invalid usage config"),
1857            "unexpected error: {err}"
1858        );
1859    }
1860}
1861
1862#[cfg(test)]
1863mod merge_tests {
1864    use crate::Spec;
1865
1866    fn uninstall(src: &str) -> crate::SpecCommand {
1867        Spec::parse(&Default::default(), src)
1868            .unwrap()
1869            .cmd
1870            .subcommands["uninstall"]
1871            .clone()
1872    }
1873
1874    /// An overlay that says nothing about deprecation must not un-deprecate a
1875    /// command that already declared it.
1876    #[test]
1877    fn test_deprecated_survives_merge() {
1878        let declared = uninstall(r#"cmd "uninstall" deprecated="use `remove`""#);
1879        let silent = uninstall(r#"cmd "uninstall" help="Remove a tool""#);
1880        let contradicting = uninstall(r#"cmd "uninstall" deprecated="gone in v3""#);
1881
1882        let mut cmd = declared.clone();
1883        cmd.merge(silent);
1884        assert_eq!(cmd.deprecated.as_deref(), Some("use `remove`"));
1885
1886        let mut cmd = declared;
1887        cmd.merge(contradicting);
1888        assert_eq!(cmd.deprecated.as_deref(), Some("gone in v3"));
1889    }
1890
1891    #[test]
1892    fn mounted_flags_replace_outputs_and_their_selector() {
1893        let mut mounting = uninstall(
1894            r#"cmd "uninstall" { flag "--format <FORMAT>"; output "json" framing="json"; select "--format" }"#,
1895        );
1896        let mounted = uninstall(r#"cmd "uninstall" { flag "--quiet" }"#);
1897
1898        mounting.merge(mounted);
1899
1900        assert!(mounting.outputs.is_empty());
1901        assert!(mounting.select.is_none());
1902    }
1903}
1904
1905#[cfg(test)]
1906mod roundtrip_tests {
1907    use crate::kdl;
1908    use crate::Spec;
1909
1910    /// Serializing a spec back to KDL and reparsing it must not lose anything.
1911    ///
1912    /// The parser is a match on node names, so exhaustive destructuring can't
1913    /// catch a field the serializer knows about but the parser doesn't, or the
1914    /// reverse. Comparing the serde representation covers every field without
1915    /// this test having to enumerate them, so a new field is covered the day it
1916    /// is added.
1917    #[test]
1918    fn test_spec_survives_a_kdl_roundtrip() {
1919        let src = r#"
1920name "My CLI"
1921bin "mycli"
1922about "does things"
1923version "1.0.0"
1924author "nobody"
1925license "MIT"
1926
1927flag "-v --verbose" help="Verbose logging" global=#true count=#true
1928arg "<dir>" help="Directory to use"
1929
1930cmd "install" help="Install a package" subcommand_required=#false {
1931    alias "i"
1932    alias "add" hide=#true
1933    long_help "The long help for install"
1934    help_md "The **markdown** help for install"
1935    before_help "before"
1936    before_long_help "The long before-help for install"
1937    before_help_md "The **markdown** before-help for install"
1938    after_help "after"
1939    after_long_help "The long after-help for install"
1940    after_help_md "The **markdown** after-help for install"
1941    arg "<pkg>" help="Package to install"
1942    arg "[dest]" effect="write"
1943    flag "-f --force" help="Overwrite"
1944    flag "--purge" effect="destructive" overrides="-f" required_unless="--keep"
1945    flag "--format <FMT>" help="Output format"
1946    complete "pkg" run="mycli list --available" descriptions=#true
1947    example "mycli install foo" header="Install foo" help="Installs foo" lang="sh"
1948    example "mycli install bar"
1949    heading "Output" help="Formats are stable across releases."
1950    output "human" default=#true help="A progress log"
1951    output "json" framing="json" help="One report object" {
1952        schema "{\n  \"type\": \"object\"\n}"
1953    }
1954    select "--format"
1955    exit_code 0 "installed"
1956    exit_code 1 "the package was not found"
1957    cmd "from" help="Install from a source" {
1958        arg "<src>"
1959    }
1960}
1961cmd "wrapped" help="Wraps another CLI" {
1962    mount run="mycli plugin usage-spec"
1963}
1964cmd "remove" help="Remove a package" deprecated="use `uninstall`" effect="destructive"
1965cmd "run" restart_token=":::" help="Run tasks"
1966cmd "exec" external_subcommand=#true help="Run an external command"
1967cmd "hidden" hide=#true
1968        "#;
1969
1970        let original = Spec::parse(&Default::default(), src).unwrap();
1971        let reparsed = Spec::parse(&Default::default(), &original.to_string()).unwrap();
1972
1973        let original = serde_json::to_value(&original).unwrap();
1974        let reparsed = serde_json::to_value(&reparsed).unwrap();
1975        pretty_assertions::assert_eq!(original, reparsed);
1976
1977        // Equality is only meaningful if the fixture actually populated the
1978        // fields, so guard against a future edit quietly emptying it out.
1979        let install = &original["cmd"]["subcommands"]["install"];
1980        let purge = install["flags"]
1981            .as_array()
1982            .unwrap()
1983            .iter()
1984            .find(|flag| flag["name"] == "purge")
1985            .unwrap();
1986        assert_eq!(purge["overrides"], serde_json::json!(["-f"]));
1987        assert_eq!(purge["required_unless"], serde_json::json!(["--keep"]));
1988        for key in [
1989            "help_long",
1990            "help_md",
1991            "before_help",
1992            "before_help_long",
1993            "before_help_md",
1994            "after_help",
1995            "after_help_long",
1996            "after_help_md",
1997            "deprecated",
1998            "effect",
1999            "restart_token",
2000            "examples",
2001            "headings",
2002            "complete",
2003            "mounts",
2004            "aliases",
2005            "hidden_aliases",
2006            "outputs",
2007            "select",
2008            "exit_codes",
2009        ] {
2010            let populated = match key {
2011                // These sit on other commands in the fixture.
2012                "deprecated" | "effect" => {
2013                    original["cmd"]["subcommands"]["remove"].get(key).is_some()
2014                }
2015                "restart_token" => original["cmd"]["subcommands"]["run"].get(key).is_some(),
2016                "mounts" => !original["cmd"]["subcommands"]["wrapped"]["mounts"]
2017                    .as_array()
2018                    .unwrap()
2019                    .is_empty(),
2020                _ => match install.get(key) {
2021                    Some(serde_json::Value::Array(a)) => !a.is_empty(),
2022                    Some(serde_json::Value::Object(o)) => !o.is_empty(),
2023                    Some(_) => true,
2024                    None => false,
2025                },
2026            };
2027            assert!(populated, "fixture does not exercise `{key}`");
2028        }
2029
2030        // Flag- and arg-level effects live one level down, so check them
2031        // explicitly rather than by name against the command object.
2032        assert!(
2033            install["flags"]
2034                .as_array()
2035                .unwrap()
2036                .iter()
2037                .any(|f| f.get("effect").is_some()),
2038            "fixture does not exercise a flag-level `effect`"
2039        );
2040        assert!(
2041            install["args"]
2042                .as_array()
2043                .unwrap()
2044                .iter()
2045                .any(|a| a.get("effect").is_some()),
2046            "fixture does not exercise an arg-level `effect`"
2047        );
2048    }
2049    #[cfg(feature = "clap")]
2050    #[test]
2051    fn a_clap_command_says_what_clap_would_do_with_an_unknown_flag() {
2052        use super::{SpecCommand, UnknownFlags};
2053
2054        // clap rejects a dash-word it does not know; this spec's default is to offer it to the
2055        // positionals. Saying nothing therefore loosened every command generated from clap —
2056        // which is how `mise use --globa` became a tool named `--globa` rather than an error.
2057        let plain = clap::Command::new("build")
2058            .arg(clap::Arg::new("target").required(false))
2059            .arg(clap::Arg::new("force").long("force").num_args(0));
2060        let spec: SpecCommand = (&plain).into();
2061        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Error));
2062
2063        // A command that forwards says so, and clap is the one that knows: an argument taking
2064        // hyphen values is what a wrapper looks like.
2065        let wrapper = clap::Command::new("run").arg(
2066            clap::Arg::new("args")
2067                .num_args(0..)
2068                .allow_hyphen_values(true),
2069        );
2070        let spec: SpecCommand = (&wrapper).into();
2071        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Value));
2072
2073        // As does one whose trailing argument swallows the rest.
2074        let trailing = clap::Command::new("exec").arg(
2075            clap::Arg::new("cmd")
2076                .num_args(0..)
2077                .trailing_var_arg(true)
2078                .allow_hyphen_values(true),
2079        );
2080        let spec: SpecCommand = (&trailing).into();
2081        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Value));
2082
2083        // And a command that takes whatever subcommand it is given, which is a different
2084        // shape from forwarding unknown flags: clap still rejects `x --wat`.
2085        let external = clap::Command::new("x").allow_external_subcommands(true);
2086        let spec: SpecCommand = (&external).into();
2087        assert_eq!(spec.unknown_flags, Some(UnknownFlags::Error));
2088        assert!(spec.external_subcommand);
2089    }
2090
2091    #[cfg(feature = "clap")]
2092    #[test]
2093    fn the_decision_survives_being_written_and_read_back() {
2094        use super::SpecCommand;
2095
2096        // The point of setting it is what a *parser* does with the spec afterwards, so the round
2097        // trip is what makes it true rather than the field.
2098        let plain = clap::Command::new("build").arg(clap::Arg::new("target").required(false));
2099        let spec: SpecCommand = (&plain).into();
2100        let node: kdl::KdlNode = (&spec).into();
2101        let kdl = node.to_string();
2102        assert!(kdl.contains("unknown_flags=error"), "{kdl}");
2103    }
2104
2105    #[cfg(feature = "clap")]
2106    #[test]
2107    fn the_clap_bridge_preserves_args_override_self() {
2108        use super::SpecCommand;
2109
2110        let strict: SpecCommand = (&clap::Command::new("strict")).into();
2111        assert!(!strict.args_override_self, "clap is strict by default");
2112
2113        let permissive: SpecCommand =
2114            (&clap::Command::new("permissive").args_override_self(true)).into();
2115        assert!(permissive.args_override_self);
2116
2117        let node: kdl::KdlNode = (&strict).into();
2118        assert!(node.to_string().contains("args_override_self=#false"));
2119    }
2120
2121    #[cfg(feature = "clap")]
2122    #[test]
2123    fn the_clap_bridge_preserves_subcommand_presentation() {
2124        use super::SpecCommand;
2125
2126        let spec: SpecCommand = (&clap::Command::new("ex")
2127            .subcommand(clap::Command::new("run"))
2128            .subcommand_help_heading("Actions")
2129            .subcommand_value_name("ACTION"))
2130            .into();
2131        assert_eq!(spec.subcommand_help_heading.as_deref(), Some("Actions"));
2132        assert_eq!(spec.subcommand_value_name.as_deref(), Some("ACTION"));
2133        let node: kdl::KdlNode = (&spec).into();
2134        let kdl = node.to_string();
2135        assert!(kdl.contains("subcommand_help_heading=Actions"), "{kdl}");
2136        assert!(kdl.contains("subcommand_value_name=ACTION"), "{kdl}");
2137    }
2138
2139    #[cfg(feature = "clap")]
2140    #[test]
2141    fn the_clap_bridge_preserves_subcommand_negates_requirements() {
2142        use super::SpecCommand;
2143
2144        let spec: SpecCommand = (&clap::Command::new("ex").subcommand_negates_reqs(true)).into();
2145        assert!(spec.subcommand_negates_reqs);
2146        let node: kdl::KdlNode = (&spec).into();
2147        assert!(node.to_string().contains("subcommand_negates_reqs=#true"));
2148    }
2149
2150    #[cfg(feature = "clap")]
2151    #[test]
2152    fn the_clap_bridge_preserves_argument_subcommand_conflicts() {
2153        use super::SpecCommand;
2154
2155        let spec: SpecCommand =
2156            (&clap::Command::new("ex").args_conflicts_with_subcommands(true)).into();
2157        assert!(spec.args_conflicts_with_subcommands);
2158        let node: kdl::KdlNode = (&spec).into();
2159        assert!(node
2160            .to_string()
2161            .contains("args_conflicts_with_subcommands=#true"));
2162    }
2163
2164    #[cfg(feature = "clap")]
2165    #[test]
2166    fn the_clap_bridge_preserves_allow_missing_positional() {
2167        use super::SpecCommand;
2168
2169        let spec: SpecCommand = (&clap::Command::new("ex").allow_missing_positional(true)).into();
2170        assert!(spec.allow_missing_positional);
2171        let node: kdl::KdlNode = (&spec).into();
2172        assert!(node.to_string().contains("allow_missing_positional=#true"));
2173    }
2174}