Skip to main content

usage/spec/
arg.rs

1use crate::kdl::{KdlDocument, KdlEntry, KdlNode};
2use crate::miette;
3use serde::Serialize;
4use std::fmt::Display;
5use std::hash::Hash;
6use std::str::FromStr;
7
8use crate::error::UsageErr;
9use crate::spec::builder::SpecArgBuilder;
10use crate::spec::context::ParsingContext;
11use crate::spec::effect::{SpecCommandEffect, EFFECT_VALUES};
12use crate::spec::helpers::{string_entry, NodeHelper};
13use crate::spec::is_false;
14use crate::{string, SpecAdmonition, SpecAdmonitionKind, SpecChoices};
15#[cfg(feature = "clap")]
16use crate::{SpecChoice, SpecChoiceAlias};
17
18/// A value comparison that can make another argument required.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
20pub struct SpecRequiredIfEq {
21    pub selector: String,
22    pub value: String,
23}
24
25#[derive(Debug, Default, Clone, Serialize, PartialEq, Eq)]
26pub enum SpecDoubleDashChoices {
27    /// Once an arg is entered, behave as if "--" was passed
28    Automatic,
29    /// Allow "--" to be passed
30    #[default]
31    Optional,
32    /// Require "--" to be passed
33    Required,
34    /// Preserve "--" tokens as values (only for variadic args)
35    Preserve,
36}
37
38impl_string_enum!(SpecDoubleDashChoices {
39    SpecDoubleDashChoices::Automatic => "automatic",
40    SpecDoubleDashChoices::Optional => "optional",
41    SpecDoubleDashChoices::Required => "required",
42    SpecDoubleDashChoices::Preserve => "preserve",
43});
44
45/// A positional argument specification.
46///
47/// Arguments are positional values passed to a command without a flag prefix.
48/// They can be required or optional, and can accept multiple values (variadic).
49///
50/// # Example
51///
52/// ```
53/// use usage::SpecArg;
54///
55/// let arg = SpecArg::builder()
56///     .name("file")
57///     .required(true)
58///     .help("Input file to process")
59///     .build();
60/// ```
61#[derive(Debug, Default, Clone, Serialize)]
62#[non_exhaustive]
63pub struct SpecArg {
64    /// Name of the argument (used in help text)
65    pub name: String,
66    /// Ordered placeholders for a fixed-arity value, such as `START` and `END`.
67    /// Empty means the argument's `name` is the sole placeholder.
68    #[serde(skip_serializing_if = "Vec::is_empty")]
69    pub value_names: Vec<String>,
70    /// Generated usage string (e.g., "<file>" or "[file]")
71    pub usage: String,
72    /// Short help text shown in command listings
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub help: Option<String>,
75    /// Extended help text shown with --help
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub help_long: Option<String>,
78    /// Markdown-formatted help text
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub help_md: Option<String>,
81    /// Structured notes and warnings, in presentation order.
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub admonitions: Vec<SpecAdmonition>,
84    /// First line of help text (auto-generated)
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub help_first_line: Option<String>,
87    /// Whether this argument must be provided
88    pub required: bool,
89    /// How to handle the "--" separator
90    pub double_dash: SpecDoubleDashChoices,
91    /// Whether this argument accepts multiple values
92    #[serde(skip_serializing_if = "is_false")]
93    pub var: bool,
94    /// Minimum number of values for variadic arguments
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub var_min: Option<usize>,
97    /// Maximum number of values for variadic arguments
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub var_max: Option<usize>,
100    /// The character a single word is split on to produce several values.
101    ///
102    /// `--tags a,b,c` as three values rather than one, which is clap's
103    /// `value_delimiter`. Only meaningful where several values can land, so it goes with
104    /// [`SpecArg::var`]; declaring it anywhere else is refused rather than silently
105    /// dropping everything after the first separator.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub delimiter: Option<char>,
108    /// Accept negative numeric tokens without accepting arbitrary dash-prefixed words.
109    #[serde(skip_serializing_if = "is_false")]
110    pub allow_negative_numbers: bool,
111    /// End this variadic argument when this token is seen, without binding it.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub value_terminator: Option<String>,
114    /// Whether to hide this argument from help output
115    pub hide: bool,
116    /// Hide the default annotation while keeping the default behavior.
117    #[serde(skip_serializing_if = "is_false")]
118    pub hide_default_value: bool,
119    /// Hide the environment annotation entirely.
120    #[serde(skip_serializing_if = "is_false")]
121    pub hide_env: bool,
122    /// Hide an environment value while retaining its variable name.
123    #[serde(skip_serializing_if = "is_false")]
124    pub hide_env_values: bool,
125    /// Hide possible values from help without changing validation.
126    #[serde(skip_serializing_if = "is_false")]
127    pub hide_possible_values: bool,
128    /// Hide this argument only from short help.
129    #[serde(skip_serializing_if = "is_false")]
130    pub hide_short_help: bool,
131    /// Hide this argument only from long help.
132    #[serde(skip_serializing_if = "is_false")]
133    pub hide_long_help: bool,
134    /// Arguments and flags that cannot be given alongside this positional.
135    ///
136    /// A bare selector names another positional by name; flag selectors keep their
137    /// `--long` or `-s` spelling.
138    #[serde(skip_serializing_if = "Vec::is_empty")]
139    pub conflicts: Vec<String>,
140    /// Arguments that must also be present when this positional is present.
141    #[serde(skip_serializing_if = "Vec::is_empty")]
142    pub requires: Vec<String>,
143    /// Presence conditions, any one of which makes this positional required.
144    #[serde(skip_serializing_if = "Vec::is_empty")]
145    pub required_if: Vec<String>,
146    /// Value conditions, any one of which makes this positional required.
147    #[serde(skip_serializing_if = "Vec::is_empty")]
148    pub required_if_eq: Vec<SpecRequiredIfEq>,
149    /// Value conditions which must all match to make this positional required.
150    #[serde(skip_serializing_if = "Vec::is_empty")]
151    pub required_if_eq_all: Vec<SpecRequiredIfEq>,
152    /// Any present selector waives this positional's requirement.
153    #[serde(skip_serializing_if = "Vec::is_empty")]
154    pub required_unless: Vec<String>,
155    /// Only the presence of every selector waives this positional's requirement.
156    #[serde(skip_serializing_if = "Vec::is_empty")]
157    pub required_unless_all: Vec<String>,
158    /// Default value(s) if the argument is not provided
159    #[serde(skip_serializing_if = "Vec::is_empty")]
160    pub default: Vec<String>,
161    /// Valid choices for this argument
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub choices: Option<SpecChoices>,
164    /// A portable expr expression that must return true for each raw value.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub validate: Option<String>,
167    /// Message reported when [`SpecArg::validate`] returns false.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub validate_error: Option<String>,
170    /// Raises the effect of the command when this argument is supplied.
171    /// See [`crate::spec::effect::SpecCommandEffect`]; never lowers it.
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub effect: Option<SpecCommandEffect>,
174    /// Environment variable that can provide this argument's value
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub env: Option<String>,
177    /// Additional environment variables, consulted in declaration order.
178    #[serde(skip_serializing_if = "Vec::is_empty")]
179    pub env_fallback: Vec<String>,
180    /// Deprecated environment aliases, consulted after ordinary fallbacks.
181    #[serde(skip_serializing_if = "Vec::is_empty")]
182    pub deprecated_env: Vec<String>,
183    /// Heading this argument is listed under in help output. Presentational only,
184    /// like the flag field of the same name.
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub help_heading: Option<String>,
187    /// Named audience or contract surface this argument belongs to.
188    ///
189    /// Metadata only: parsers and help renderers do not filter on this value.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub surface: Option<String>,
192    /// Conditions under which this argument is available, in declaration order.
193    ///
194    /// These are descriptive labels for docs, schema consumers, and compatibility tools.
195    #[serde(skip_serializing_if = "Vec::is_empty")]
196    pub available_if: Vec<String>,
197    /// Explicit placement within its help section.
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub display_order: Option<usize>,
200}
201
202impl SpecArg {
203    /// Create a new builder for SpecArg
204    pub fn builder() -> SpecArgBuilder {
205        SpecArgBuilder::new()
206    }
207
208    /// Environment variable names in the order used to fill this argument.
209    pub fn env_names(&self) -> impl Iterator<Item = &str> {
210        self.env
211            .iter()
212            .map(String::as_str)
213            .chain(self.env_fallback.iter().map(String::as_str))
214            .chain(self.deprecated_env.iter().map(String::as_str))
215    }
216
217    pub(crate) fn parse(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
218        let mut arg: SpecArg = node.arg(0)?.ensure_string()?.parse()?;
219        for (k, v) in node.props() {
220            match k {
221                "help" => arg.help = Some(v.ensure_string()?),
222                "long_help" => arg.help_long = Some(v.ensure_string()?),
223                "help_long" => arg.help_long = Some(v.ensure_string()?),
224                "help_md" => arg.help_md = Some(v.ensure_string()?),
225                "required" => arg.required = v.ensure_bool()?,
226                "double_dash" => arg.double_dash = v.ensure_string()?.parse()?,
227                "var" => arg.var = v.ensure_bool()?,
228                "delimiter" => {
229                    let raw = v.ensure_string()?;
230                    let mut chars = raw.chars();
231                    match (chars.next(), chars.next()) {
232                        // ASCII, not merely one character. Splitting is by byte everywhere
233                        // below this — the derive says so where it reads the same property —
234                        // and a non-ASCII separator has no single byte to be. Worse than
235                        // having none: its bytes are continuation bytes, which appear inside
236                        // unrelated characters, so it would split words nobody separated.
237                        (Some(c), None) if c.is_ascii() => arg.delimiter = Some(c),
238                        (Some(c), None) => bail_parse!(
239                            ctx,
240                            v.entry.span(),
241                            "a delimiter is one byte, and {c:?} is more than one; use an \
242                             ASCII separator"
243                        ),
244                        _ => bail_parse!(
245                            ctx,
246                            v.entry.span(),
247                            "a delimiter is one character, and {raw:?} is not"
248                        ),
249                    }
250                }
251                "allow_negative_numbers" => arg.allow_negative_numbers = v.ensure_bool()?,
252                "value_terminator" => arg.value_terminator = v.ensure_string().map(Some)?,
253                "hide" => arg.hide = v.ensure_bool()?,
254                "hide_default_value" => arg.hide_default_value = v.ensure_bool()?,
255                "hide_env" => arg.hide_env = v.ensure_bool()?,
256                "hide_env_values" => arg.hide_env_values = v.ensure_bool()?,
257                "hide_possible_values" => arg.hide_possible_values = v.ensure_bool()?,
258                "hide_short_help" => arg.hide_short_help = v.ensure_bool()?,
259                "hide_long_help" => arg.hide_long_help = v.ensure_bool()?,
260                "conflicts" => arg.conflicts = vec![v.ensure_string()?],
261                "requires" => arg.requires = vec![v.ensure_string()?],
262                "required_if" => arg.required_if = vec![v.ensure_string()?],
263                "required_unless" => arg.required_unless = vec![v.ensure_string()?],
264                "required_unless_all" => arg.required_unless_all = vec![v.ensure_string()?],
265                "var_min" => arg.var_min = v.ensure_usize().map(Some)?,
266                "var_max" => arg.var_max = v.ensure_usize().map(Some)?,
267                "default" => arg.default = vec![v.ensure_string()?],
268                "effect" => {
269                    let raw = v.ensure_string()?;
270                    match raw.parse() {
271                        Ok(effect) => arg.effect = Some(effect),
272                        Err(_) => bail_parse!(
273                            ctx,
274                            v.entry.span(),
275                            "unsupported effect {raw}, expected one of: {EFFECT_VALUES}"
276                        ),
277                    }
278                }
279                "env" => arg.env = v.ensure_string().map(Some)?,
280                "env_fallback" => arg.env_fallback = vec![v.ensure_string()?],
281                "deprecated_env" => arg.deprecated_env = vec![v.ensure_string()?],
282                "validate" => arg.validate = v.ensure_string().map(Some)?,
283                "validate_error" => arg.validate_error = v.ensure_string().map(Some)?,
284                "help_heading" => arg.help_heading = v.ensure_string().map(Some)?,
285                "surface" => arg.surface = v.ensure_string().map(Some)?,
286                "available_if" => arg.available_if = vec![v.ensure_string()?],
287                "display_order" => arg.display_order = v.ensure_usize().map(Some)?,
288                k => bail_parse!(ctx, v.entry.span(), "unsupported arg key {k}"),
289            }
290        }
291        if !arg.default.is_empty() {
292            arg.required = false;
293        }
294        for child in node.children() {
295            match child.name() {
296                "choices" => arg.choices = Some(SpecChoices::parse(ctx, &child)?),
297                "effect" => {
298                    let a = child.arg(0)?;
299                    let raw = a.ensure_string()?;
300                    match raw.parse() {
301                        Ok(effect) => arg.effect = Some(effect),
302                        Err(_) => bail_parse!(
303                            ctx,
304                            a.entry.span(),
305                            "unsupported effect {raw}, expected one of: {EFFECT_VALUES}"
306                        ),
307                    }
308                }
309                "env" => arg.env = child.arg(0)?.ensure_string().map(Some)?,
310                "env_fallback" => arg.env_fallback = string_args(&child)?,
311                "deprecated_env" => arg.deprecated_env = string_args(&child)?,
312                "validate" => arg.validate = child.arg(0)?.ensure_string().map(Some)?,
313                "validate_error" => {
314                    arg.validate_error = child.arg(0)?.ensure_string().map(Some)?;
315                }
316                "help_heading" => {
317                    arg.help_heading = child.arg(0)?.ensure_string().map(Some)?;
318                }
319                "surface" => arg.surface = child.arg(0)?.ensure_string().map(Some)?,
320                "available_if" => arg.available_if = string_args(&child)?,
321                "display_order" => {
322                    arg.display_order = child.arg(0)?.ensure_usize().map(Some)?;
323                }
324                "default" => {
325                    // Support both single value and multiple values
326                    // default "bar"            -> vec!["bar"]
327                    // default { "xyz"; "bar" } -> vec!["xyz", "bar"]
328                    let children = child.children();
329                    if children.is_empty() {
330                        // Single value: default "bar"
331                        arg.default = vec![child.arg(0)?.ensure_string()?];
332                    } else {
333                        // Multiple values from children: default { "xyz"; "bar" }
334                        // In KDL, these are child nodes where the string is the node name
335                        arg.default = children.iter().map(|c| c.name().to_string()).collect();
336                    }
337                }
338                "help" => arg.help = Some(child.arg(0)?.ensure_string()?),
339                "long_help" => arg.help_long = Some(child.arg(0)?.ensure_string()?),
340                "help_long" => arg.help_long = Some(child.arg(0)?.ensure_string()?),
341                "help_md" => arg.help_md = Some(child.arg(0)?.ensure_string()?),
342                "note" => arg
343                    .admonitions
344                    .push(SpecAdmonition::note(child.arg(0)?.ensure_string()?)),
345                "warning" => arg
346                    .admonitions
347                    .push(SpecAdmonition::warning(child.arg(0)?.ensure_string()?)),
348                "required" => arg.required = child.arg(0)?.ensure_bool()?,
349                "var" => arg.var = child.arg(0)?.ensure_bool()?,
350                "var_min" => arg.var_min = child.arg(0)?.ensure_usize().map(Some)?,
351                "var_max" => arg.var_max = child.arg(0)?.ensure_usize().map(Some)?,
352                "value_names" => {
353                    arg.value_names = child
354                        .ensure_arg_len(1..)?
355                        .args()
356                        .map(|entry| entry.ensure_string())
357                        .collect::<Result<Vec<_>, _>>()?;
358                }
359                "allow_negative_numbers" => {
360                    arg.allow_negative_numbers = child.arg(0)?.ensure_bool()?;
361                }
362                "value_terminator" => {
363                    arg.value_terminator = child.arg(0)?.ensure_string().map(Some)?;
364                }
365                "hide" => arg.hide = child.arg(0)?.ensure_bool()?,
366                "hide_default_value" => arg.hide_default_value = child.arg(0)?.ensure_bool()?,
367                "hide_env" => arg.hide_env = child.arg(0)?.ensure_bool()?,
368                "hide_env_values" => arg.hide_env_values = child.arg(0)?.ensure_bool()?,
369                "hide_possible_values" => arg.hide_possible_values = child.arg(0)?.ensure_bool()?,
370                "hide_short_help" => arg.hide_short_help = child.arg(0)?.ensure_bool()?,
371                "hide_long_help" => arg.hide_long_help = child.arg(0)?.ensure_bool()?,
372                "conflicts" => {
373                    arg.conflicts = child
374                        .ensure_arg_len(1..)?
375                        .args()
376                        .map(|entry| entry.ensure_string())
377                        .collect::<Result<Vec<_>, _>>()?;
378                }
379                "requires" => arg.requires = string_args(&child)?,
380                "required_if" => arg.required_if = string_args(&child)?,
381                "required_if_eq" => arg.required_if_eq.push(required_if_eq(&child)?),
382                "required_if_eq_all" => {
383                    let len = child.args().count();
384                    if len < 2 || len % 2 != 0 {
385                        bail_parse!(
386                            ctx,
387                            child.node.name().span(),
388                            "required_if_eq_all needs selector/value pairs"
389                        );
390                    }
391                    arg.required_if_eq_all = required_if_eq_pairs(&child)?;
392                }
393                "required_unless" => arg.required_unless = string_args(&child)?,
394                "required_unless_all" => arg.required_unless_all = string_args(&child)?,
395                "double_dash" => arg.double_dash = child.arg(0)?.ensure_string()?.parse()?,
396                k => bail_parse!(ctx, child.node.name().span(), "unsupported arg child {k}"),
397            }
398        }
399        if let Some(first) = arg.value_names.first() {
400            arg.name.clone_from(first);
401        }
402        if arg.value_names.len() > 1 {
403            let arity = arg.value_names.len();
404            match (arg.var_min, arg.var_max) {
405                (None, None) => {
406                    arg.var_min = Some(arity);
407                    arg.var_max = Some(arity);
408                }
409                (Some(min), Some(max)) if min == arity && max == arity => {}
410                _ => bail_parse!(
411                    ctx,
412                    node.node.name().span(),
413                    "{arity} value names require var_min={arity} and var_max={arity}"
414                ),
415            }
416            arg.var = true;
417        }
418        if arg.validate_error.is_some() && arg.validate.is_none() {
419            bail_parse!(
420                ctx,
421                node.node.name().span(),
422                "validate_error requires a validate expression"
423            );
424        }
425        if arg.value_terminator.as_deref() == Some("") {
426            bail_parse!(
427                ctx,
428                node.node.name().span(),
429                "value_terminator cannot be empty"
430            );
431        }
432        if arg.value_terminator.is_some() && !arg.var {
433            bail_parse!(
434                ctx,
435                node.node.name().span(),
436                "value_terminator requires a variadic argument"
437            );
438        }
439        #[cfg(feature = "validation")]
440        if let Some(expression) = &arg.validate {
441            if let Err(error) = usage_validation::check(expression) {
442                bail_parse!(
443                    ctx,
444                    node.node.name().span(),
445                    "invalid validation expression: {error}"
446                );
447            }
448        }
449        arg.usage = arg.usage();
450        if let Some(help) = &arg.help {
451            arg.help_first_line = Some(string::first_line(help));
452        }
453        Ok(arg)
454    }
455}
456
457impl SpecArg {
458    pub fn usage(&self) -> String {
459        let exact_arity = self.var.then_some(()).and_then(|()| {
460            self.var_min
461                .zip(self.var_max)
462                .filter(|(min, max)| min == max && *min > 1)
463                .map(|(arity, _)| arity)
464        });
465        if self.value_names.len() > 1 || exact_arity.is_some() {
466            let labels = if self.value_names.len() > 1 {
467                self.value_names.clone()
468            } else {
469                vec![
470                    self.value_names
471                        .first()
472                        .cloned()
473                        .unwrap_or_else(|| self.name.clone());
474                    exact_arity.expect("branch checked")
475                ]
476            };
477            let placeholders = labels
478                .iter()
479                .map(|name| {
480                    if self.required {
481                        format!("<{name}>")
482                    } else {
483                        format!("[{name}]")
484                    }
485                })
486                .collect::<Vec<_>>()
487                .join(" ");
488            return if self.double_dash == SpecDoubleDashChoices::Required {
489                format!("-- {placeholders}")
490            } else {
491                placeholders
492            };
493        }
494        let name = if self.double_dash == SpecDoubleDashChoices::Required {
495            format!("-- {}", self.name)
496        } else {
497            self.name.clone()
498        };
499        let mut name = if self.required {
500            format!("<{name}>")
501        } else {
502            format!("[{name}]")
503        };
504        if self.var {
505            name = format!("{name}…");
506        }
507        name
508    }
509}
510
511impl From<&SpecArg> for KdlNode {
512    fn from(arg: &SpecArg) -> Self {
513        let mut node = KdlNode::new("arg");
514        node.push(KdlEntry::new(arg.usage()));
515        if let Some(desc) = &arg.help {
516            node.push(string_entry(Some("help"), desc));
517        }
518        if let Some(desc) = &arg.help_long {
519            node.push(string_entry(Some("help_long"), desc));
520        }
521        if let Some(desc) = &arg.help_md {
522            node.push(string_entry(Some("help_md"), desc));
523        }
524        for admonition in &arg.admonitions {
525            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
526            let name = match admonition.kind {
527                SpecAdmonitionKind::Note => "note",
528                SpecAdmonitionKind::Warning => "warning",
529            };
530            let mut block = KdlNode::new(name);
531            block.push(string_entry(None, &admonition.text));
532            children.nodes_mut().push(block);
533        }
534        if !arg.required {
535            node.push(KdlEntry::new_prop("required", false));
536        }
537        if arg.double_dash == SpecDoubleDashChoices::Automatic
538            || arg.double_dash == SpecDoubleDashChoices::Preserve
539        {
540            node.push(KdlEntry::new_prop(
541                "double_dash",
542                arg.double_dash.to_string(),
543            ));
544        }
545        if arg.var {
546            node.push(KdlEntry::new_prop("var", true));
547        }
548        if let Some(min) = arg.var_min {
549            node.push(KdlEntry::new_prop("var_min", min as i128));
550        }
551        if let Some(max) = arg.var_max {
552            node.push(KdlEntry::new_prop("var_max", max as i128));
553        }
554        if let Some(delimiter) = arg.delimiter {
555            node.push(string_entry(Some("delimiter"), &delimiter.to_string()));
556        }
557        if arg.allow_negative_numbers {
558            node.push(KdlEntry::new_prop("allow_negative_numbers", true));
559        }
560        if let Some(terminator) = &arg.value_terminator {
561            node.push(string_entry(Some("value_terminator"), terminator));
562        }
563        if arg.hide {
564            node.push(KdlEntry::new_prop("hide", true));
565        }
566        for (name, hidden) in [
567            ("hide_default_value", arg.hide_default_value),
568            ("hide_env", arg.hide_env),
569            ("hide_env_values", arg.hide_env_values),
570            ("hide_possible_values", arg.hide_possible_values),
571            ("hide_short_help", arg.hide_short_help),
572            ("hide_long_help", arg.hide_long_help),
573        ] {
574            if hidden {
575                node.push(KdlEntry::new_prop(name, true));
576            }
577        }
578        if arg.conflicts.len() == 1 {
579            node.push(string_entry(Some("conflicts"), &arg.conflicts[0]));
580        } else if !arg.conflicts.is_empty() {
581            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
582            let mut conflicts = KdlNode::new("conflicts");
583            for target in &arg.conflicts {
584                conflicts.push(string_entry(None, target));
585            }
586            children.nodes_mut().push(conflicts);
587        }
588        serialize_selector_list(&mut node, "requires", &arg.requires);
589        serialize_selector_list(&mut node, "required_if", &arg.required_if);
590        serialize_required_if_eq(&mut node, "required_if_eq", &arg.required_if_eq);
591        if !arg.required_if_eq_all.is_empty() {
592            serialize_required_if_eq(&mut node, "required_if_eq_all", &arg.required_if_eq_all);
593        }
594        serialize_selector_list(&mut node, "required_unless", &arg.required_unless);
595        serialize_selector_list(&mut node, "required_unless_all", &arg.required_unless_all);
596        // Serialize default values
597        if !arg.default.is_empty() {
598            if arg.default.len() == 1 {
599                // Single value: use property default="bar"
600                node.push(string_entry(Some("default"), &arg.default[0]));
601            } else {
602                // Multiple values: use child node default { "xyz"; "bar" }
603                let children = node.children_mut().get_or_insert_with(KdlDocument::new);
604                let mut default_node = KdlNode::new("default");
605                let default_children = default_node
606                    .children_mut()
607                    .get_or_insert_with(KdlDocument::new);
608                for val in &arg.default {
609                    default_children
610                        .nodes_mut()
611                        .push(KdlNode::new(val.as_str()));
612                }
613                children.nodes_mut().push(default_node);
614            }
615        }
616        if let Some(env) = &arg.env {
617            node.push(string_entry(Some("env"), env));
618        }
619        serialize_selector_list(&mut node, "env_fallback", &arg.env_fallback);
620        serialize_selector_list(&mut node, "deprecated_env", &arg.deprecated_env);
621        if let Some(validate) = &arg.validate {
622            node.push(string_entry(Some("validate"), validate));
623        }
624        if arg.validate.is_some() {
625            if let Some(error) = &arg.validate_error {
626                node.push(string_entry(Some("validate_error"), error));
627            }
628        }
629        if let Some(help_heading) = &arg.help_heading {
630            node.push(string_entry(Some("help_heading"), help_heading));
631        }
632        if let Some(surface) = &arg.surface {
633            node.push(string_entry(Some("surface"), surface));
634        }
635        serialize_selector_list(&mut node, "available_if", &arg.available_if);
636        if let Some(order) = arg.display_order {
637            node.push(KdlEntry::new_prop("display_order", order as i128));
638        }
639        if let Some(effect) = &arg.effect {
640            node.push(string_entry(Some("effect"), effect.as_str()));
641        }
642        if let Some(choices) = &arg.choices {
643            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
644            children.nodes_mut().push(choices.into());
645        }
646        node
647    }
648}
649
650fn string_args(node: &NodeHelper<'_>) -> Result<Vec<String>, UsageErr> {
651    node.ensure_arg_len(1..)?
652        .args()
653        .map(|entry| entry.ensure_string())
654        .collect()
655}
656
657fn required_if_eq(node: &NodeHelper<'_>) -> Result<SpecRequiredIfEq, UsageErr> {
658    node.ensure_arg_len(2..=2)?;
659    Ok(SpecRequiredIfEq {
660        selector: node.arg(0)?.ensure_string()?,
661        value: node.arg(1)?.ensure_string()?,
662    })
663}
664
665fn required_if_eq_pairs(node: &NodeHelper<'_>) -> Result<Vec<SpecRequiredIfEq>, UsageErr> {
666    let entries = node.args().collect::<Vec<_>>();
667    entries
668        .chunks_exact(2)
669        .map(|pair| {
670            Ok(SpecRequiredIfEq {
671                selector: pair[0].ensure_string()?,
672                value: pair[1].ensure_string()?,
673            })
674        })
675        .collect()
676}
677
678fn serialize_selector_list(node: &mut KdlNode, name: &str, selectors: &[String]) {
679    if selectors.len() == 1 {
680        node.push(string_entry(Some(name), &selectors[0]));
681    } else if !selectors.is_empty() {
682        let children = node.children_mut().get_or_insert_with(KdlDocument::new);
683        let mut relation = KdlNode::new(name);
684        for selector in selectors {
685            relation.push(string_entry(None, selector));
686        }
687        children.nodes_mut().push(relation);
688    }
689}
690
691fn serialize_required_if_eq(node: &mut KdlNode, name: &str, conditions: &[SpecRequiredIfEq]) {
692    if conditions.is_empty() {
693        return;
694    }
695    let children = node.children_mut().get_or_insert_with(KdlDocument::new);
696    if name == "required_if_eq_all" {
697        let mut relation = KdlNode::new(name);
698        for condition in conditions {
699            relation.push(string_entry(None, &condition.selector));
700            relation.push(string_entry(None, &condition.value));
701        }
702        children.nodes_mut().push(relation);
703    } else {
704        for condition in conditions {
705            let mut relation = KdlNode::new(name);
706            relation.push(string_entry(None, &condition.selector));
707            relation.push(string_entry(None, &condition.value));
708            children.nodes_mut().push(relation);
709        }
710    }
711}
712
713impl From<&str> for SpecArg {
714    fn from(input: &str) -> Self {
715        let (input, after_double_dash) = input
716            .strip_prefix("-- ")
717            .map_or((input, false), |rest| (rest, true));
718        if let Some(placeholders) = fixed_placeholders(input) {
719            let required = placeholders
720                .iter()
721                .all(|placeholder| placeholder.starts_with('<'));
722            let value_names = placeholders
723                .iter()
724                .map(|placeholder| placeholder[1..placeholder.len() - 1].to_string())
725                .collect::<Vec<_>>();
726            let mut arg = SpecArg {
727                name: value_names[0].clone(),
728                value_names,
729                required,
730                var: true,
731                var_min: Some(placeholders.len()),
732                var_max: Some(placeholders.len()),
733                double_dash: if after_double_dash {
734                    SpecDoubleDashChoices::Required
735                } else {
736                    SpecDoubleDashChoices::Optional
737                },
738                ..Default::default()
739            };
740            arg.usage = arg.usage();
741            return arg;
742        }
743        let mut arg = SpecArg {
744            name: input.to_string(),
745            required: true,
746            double_dash: if after_double_dash {
747                SpecDoubleDashChoices::Required
748            } else {
749                SpecDoubleDashChoices::Optional
750            },
751            ..Default::default()
752        };
753        // Handle trailing ellipsis: "foo..." or "foo…" or "<foo>..." or "[foo]..."
754        if let Some(name) = arg
755            .name
756            .strip_suffix("...")
757            .or_else(|| arg.name.strip_suffix("…"))
758        {
759            arg.var = true;
760            arg.name = name.to_string();
761        }
762        let first = arg.name.chars().next().unwrap_or_default();
763        let last = arg.name.chars().last().unwrap_or_default();
764        match (first, last) {
765            ('[', ']') => {
766                arg.name = arg.name[1..arg.name.len() - 1].to_string();
767                arg.required = false;
768            }
769            ('<', '>') => {
770                arg.name = arg.name[1..arg.name.len() - 1].to_string();
771            }
772            _ => {}
773        }
774        // The single-placeholder shorthand encloses the separator with the value:
775        // `[-- target]`. Multi-placeholder canonical output puts it before the
776        // placeholders (`-- [START] [END]`) and was handled above.
777        if let Some(name) = arg.name.strip_prefix("-- ") {
778            arg.double_dash = SpecDoubleDashChoices::Required;
779            arg.name = name.to_string();
780        }
781        // Also handle ellipsis inside brackets: "[args...]" or "<args...>"
782        if !arg.var {
783            if let Some(name) = arg
784                .name
785                .strip_suffix("...")
786                .or_else(|| arg.name.strip_suffix("…"))
787            {
788                arg.var = true;
789                arg.name = name.to_string();
790            }
791        }
792        // As `SpecArg::parse` does for the KDL child-node spelling. Without it, an arg
793        // written inline on a flag (`flag "--format <FMT>"`) carried an empty `usage`
794        // until the spec had been through one round trip, at which point it came back as
795        // a child node and got one — so a spec was not equal to itself re-read.
796        arg.usage = arg.usage();
797        arg
798    }
799}
800impl FromStr for SpecArg {
801    type Err = UsageErr;
802    fn from_str(input: &str) -> std::result::Result<Self, UsageErr> {
803        if fixed_placeholders(input.strip_prefix("-- ").unwrap_or(input)).is_some_and(
804            |placeholders| {
805                placeholders
806                    .windows(2)
807                    .any(|pair| pair[0].starts_with('<') != pair[1].starts_with('<'))
808            },
809        ) {
810            let message =
811                "fixed-arity placeholders must be either all required or all optional".to_string();
812            return Err(UsageErr::InvalidInput(
813                message,
814                (0, input.len()).into(),
815                miette::NamedSource::new("argument", input.to_string()),
816            ));
817        }
818        Ok(input.into())
819    }
820}
821
822/// Return a multi-placeholder declaration without allocating for the overwhelmingly common
823/// single-placeholder case.
824fn fixed_placeholders(input: &str) -> Option<Vec<&str>> {
825    if !input.bytes().any(|byte| byte.is_ascii_whitespace()) {
826        return None;
827    }
828    let placeholders: Vec<_> = input.split_whitespace().collect();
829    (placeholders.len() > 1
830        && placeholders.iter().all(|placeholder| {
831            matches!(
832                (placeholder.chars().next(), placeholder.chars().last()),
833                (Some('<'), Some('>')) | (Some('['), Some(']'))
834            )
835        }))
836    .then_some(placeholders)
837}
838
839/// A clap argument's defaults, as the spec has to record them.
840///
841/// clap splits a value by the argument's `value_delimiter` before anyone sees it, defaults
842/// included — so `default_value = "a,b,c"` with `value_delimiter = ','` is three values, not one.
843/// The spec has no delimiter of its own; it has a list, which is the same statement. Recording the
844/// joined string instead described a CLI whose default is a single value that its own `choices`
845/// forbid, which is how mise's `--fs-events` reached the spec.
846#[cfg(feature = "clap")]
847pub(crate) fn default_values(arg: &clap::Arg) -> Vec<String> {
848    let raw = arg
849        .get_default_values()
850        .iter()
851        .map(|v| v.to_string_lossy().to_string());
852    match arg.get_value_delimiter() {
853        Some(delimiter) => raw
854            .flat_map(|v| {
855                v.split(delimiter)
856                    .map(|part| part.to_string())
857                    .collect::<Vec<_>>()
858            })
859            .collect(),
860        None => raw.collect(),
861    }
862}
863
864/// Carry clap's value-count range into the spec where the two parsers mean the same thing.
865///
866/// A positional may accept zero values through its ordinary optionality. A flag
867/// with `num_args(0..)` additionally permits a bare occurrence; callers pass
868/// `zero_values_supported` only when they also carry that executable policy on
869/// the containing flag.
870#[cfg(feature = "clap")]
871pub(crate) fn value_bounds(source: &clap::Arg, target: &mut SpecArg, zero_values_supported: bool) {
872    // clap verifies num_args against raw command-line tokens and only splits each token on the
873    // delimiter afterward. Usage splits first and its bounds count the resulting values. Carrying
874    // the range would therefore change the contract (for example, two comma-separated tokens can
875    // become four Usage values), so leave it unmapped until the spec can distinguish both counts.
876    if source.get_value_delimiter().is_some() {
877        return;
878    }
879
880    let Some(range) = source.get_num_args() else {
881        if target.value_names.len() > 1 {
882            let arity = target.value_names.len();
883            target.var = true;
884            target.var_min = Some(arity);
885            target.var_max = Some(arity);
886        }
887        return;
888    };
889    let min = range.min_values();
890    let max = range.max_values();
891    if max <= 1 || min == 0 && !zero_values_supported {
892        return;
893    }
894
895    target.var = true;
896    target.var_min = Some(min);
897    target.var_max = (max != usize::MAX).then_some(max);
898}
899
900/// Value labels that can survive the spec's fixed-arity representation.
901///
902/// Clap permits several labels beside a ranged `num_args`; usage gives distinct labels only to
903/// an exact number of slots. Keep the first display label for a range and let the fidelity report
904/// name the loss instead of emitting KDL that cannot be parsed back.
905#[cfg(feature = "clap")]
906pub(crate) fn value_names_from_clap(source: &clap::Arg) -> Vec<String> {
907    let names: Vec<String> = source
908        .get_value_names()
909        .unwrap_or_default()
910        .iter()
911        .map(ToString::to_string)
912        .collect();
913    if names.len() <= 1 {
914        return names;
915    }
916    let mismatched_range = source.get_num_args().is_some_and(|range| {
917        range.min_values() != names.len() || range.max_values() != names.len()
918    });
919    if source.get_value_delimiter().is_some() || mismatched_range {
920        names.into_iter().take(1).collect()
921    } else {
922        names
923    }
924}
925
926/// The portable completion type corresponding to clap's complete `ValueHint` vocabulary.
927#[cfg(feature = "clap")]
928pub(crate) fn value_hint_type(hint: clap::ValueHint) -> Option<&'static str> {
929    use clap::ValueHint;
930
931    match hint {
932        ValueHint::Unknown => None,
933        ValueHint::Other => Some("none"),
934        ValueHint::AnyPath | ValueHint::FilePath => Some("path"),
935        ValueHint::DirPath => Some("dir"),
936        ValueHint::ExecutablePath => Some("executable"),
937        ValueHint::CommandName | ValueHint::CommandString => Some("command"),
938        ValueHint::CommandWithArguments => Some("command_args"),
939        ValueHint::Username => Some("username"),
940        ValueHint::Hostname => Some("hostname"),
941        ValueHint::Url => Some("url"),
942        ValueHint::EmailAddress => Some("email"),
943        _ => None,
944    }
945}
946
947#[cfg(feature = "clap")]
948pub(crate) fn choices_from_clap(arg: &clap::Arg) -> Option<SpecChoices> {
949    let possible = arg.get_possible_values();
950    if possible.is_empty() {
951        return None;
952    }
953    let choices = possible
954        .iter()
955        .map(|value| value.get_name().to_string())
956        .collect();
957    let details = possible
958        .iter()
959        .filter_map(|value| {
960            let aliases: Vec<_> = value
961                .get_name_and_aliases()
962                .skip(1)
963                .map(|alias| SpecChoiceAlias {
964                    value: alias.to_string(),
965                    // clap PossibleValue aliases are always hidden.
966                    hide: true,
967                })
968                .collect();
969            let detail = SpecChoice {
970                value: value.get_name().to_string(),
971                help: value.get_help().map(ToString::to_string),
972                hide: value.is_hide_set(),
973                aliases,
974            };
975            (detail.help.is_some() || detail.hide || !detail.aliases.is_empty()).then_some(detail)
976        })
977        .collect();
978    Some(SpecChoices {
979        choices,
980        details,
981        ignore_case: arg.is_ignore_case_set(),
982        ..Default::default()
983    })
984}
985
986#[cfg(feature = "clap")]
987impl From<&clap::Arg> for SpecArg {
988    fn from(arg: &clap::Arg) -> Self {
989        let source = arg;
990        let required = arg.is_required_set();
991        let help = arg.get_help().map(|s| s.to_string());
992        let help_long = arg.get_long_help().map(|s| s.to_string());
993        let help_first_line = help.as_ref().map(|s| string::first_line(s));
994        let hide = arg.is_hide_set();
995        // One byte only, for the reason given on the flag: a wider separator cannot be
996        // written back out. `var` below still reads the original, since clap splits on it
997        // either way and the field does collect several values.
998        let delimiter = arg.get_value_delimiter();
999        let recorded_delimiter = delimiter.filter(char::is_ascii);
1000        let value_terminator = arg.get_value_terminator().map(ToString::to_string);
1001        let var = matches!(
1002            arg.get_action(),
1003            clap::ArgAction::Count | clap::ArgAction::Append
1004        ) || delimiter.is_some();
1005        let choices = choices_from_clap(arg);
1006        let value_names = value_names_from_clap(arg);
1007        let mut arg = Self {
1008            name: value_names
1009                .first()
1010                .cloned()
1011                .unwrap_or_else(|| source.get_id().to_string()),
1012            value_names,
1013            usage: "".into(),
1014            required,
1015            double_dash: if arg.is_last_set() {
1016                SpecDoubleDashChoices::Required
1017            } else if arg.is_trailing_var_arg_set() {
1018                SpecDoubleDashChoices::Automatic
1019            } else {
1020                SpecDoubleDashChoices::Optional
1021            },
1022            help,
1023            help_long,
1024            help_md: None,
1025            admonitions: Vec::new(),
1026            help_first_line,
1027            var,
1028            var_max: None,
1029            var_min: None,
1030            // clap answers for this one, and the same getter `default_values` already
1031            // uses just above: a default is split by it, and so is a typed value.
1032            delimiter: recorded_delimiter,
1033            allow_negative_numbers: arg.is_allow_negative_numbers_set(),
1034            value_terminator: None,
1035            hide,
1036            hide_default_value: arg.is_hide_default_value_set(),
1037            hide_env: arg.is_hide_env_set(),
1038            hide_env_values: arg.is_hide_env_values_set(),
1039            hide_possible_values: arg.is_hide_possible_values_set(),
1040            hide_short_help: arg.is_hide_short_help_set(),
1041            hide_long_help: arg.is_hide_long_help_set(),
1042            conflicts: Vec::new(),
1043            requires: Vec::new(),
1044            required_if: Vec::new(),
1045            required_if_eq: Vec::new(),
1046            required_if_eq_all: Vec::new(),
1047            required_unless: Vec::new(),
1048            required_unless_all: Vec::new(),
1049            default: default_values(arg),
1050            choices: None,
1051            validate: None,
1052            validate_error: None,
1053            effect: None,
1054            env: None,
1055            env_fallback: Vec::new(),
1056            deprecated_env: Vec::new(),
1057            help_heading: arg.get_help_heading().map(|s| s.to_string()),
1058            surface: None,
1059            available_if: Vec::new(),
1060            display_order: Some(arg.get_display_order()),
1061        };
1062        arg.choices = choices;
1063
1064        value_bounds(source, &mut arg, true);
1065        if arg.var {
1066            arg.value_terminator = value_terminator;
1067        }
1068
1069        arg
1070    }
1071}
1072
1073impl Display for SpecArg {
1074    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1075        write!(f, "{}", self.usage())
1076    }
1077}
1078impl PartialEq for SpecArg {
1079    fn eq(&self, other: &Self) -> bool {
1080        self.name == other.name
1081    }
1082}
1083impl Eq for SpecArg {}
1084impl Hash for SpecArg {
1085    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1086        self.name.hash(state);
1087    }
1088}
1089
1090#[cfg(all(test, feature = "validation"))]
1091mod validation_tests {
1092    use std::collections::HashMap;
1093
1094    use crate::{parse, parse::Parser, Spec};
1095
1096    fn spec() -> Spec {
1097        r#"
1098name "ex"
1099bin "ex"
1100arg "<port>" validate="int(value) >= 1 && int(value) <= 65535" validate_error="must be a valid port"
1101        "#
1102        .parse()
1103        .unwrap()
1104    }
1105
1106    #[test]
1107    fn validation_round_trips_through_kdl() {
1108        let spec = spec();
1109        let kdl = spec.to_string();
1110        let reparsed: Spec = kdl.parse().unwrap();
1111        let arg = &reparsed.cmd.args[0];
1112        assert_eq!(
1113            arg.validate.as_deref(),
1114            Some("int(value) >= 1 && int(value) <= 65535")
1115        );
1116        assert_eq!(arg.validate_error.as_deref(), Some("must be a valid port"));
1117    }
1118
1119    #[test]
1120    fn invalid_validation_declarations_are_rejected_with_the_spec() {
1121        let missing_expression = r#"name "demo"
1122bin "demo"
1123arg "<port>" validate_error="must be a port"
1124"#;
1125        assert!(missing_expression.parse::<Spec>().is_err());
1126
1127        let invalid_expression = r#"name "demo"
1128bin "demo"
1129arg "<port>" validate="int(value) >"
1130"#;
1131        assert!(invalid_expression.parse::<Spec>().is_err());
1132    }
1133
1134    #[test]
1135    fn reference_parser_validates_each_raw_value() {
1136        parse(&spec(), &["ex".to_string(), "9229".to_string()]).unwrap();
1137
1138        let error = parse(&spec(), &["ex".to_string(), "0".to_string()]).unwrap_err();
1139        assert!(
1140            error.to_string().contains("must be a valid port"),
1141            "{error:?}"
1142        );
1143
1144        let variadic: Spec = r#"
1145name "ex"
1146bin "ex"
1147arg "<port>" var=#true validate="int(value) > 0" validate_error="port must be positive"
1148        "#
1149        .parse()
1150        .unwrap();
1151        let error = parse(
1152            &variadic,
1153            &["ex".to_string(), "0".to_string(), "-1".to_string()],
1154        )
1155        .unwrap_err()
1156        .to_string();
1157        assert_eq!(error.matches("port must be positive").count(), 1, "{error}");
1158    }
1159
1160    #[test]
1161    fn reference_parser_validates_environment_and_default_fallbacks() {
1162        let spec: Spec = r#"
1163name "ex"
1164bin "ex"
1165arg "[port]" env="PORT" validate="int(value) > 0" validate_error="port must be positive"
1166flag "--mode" default="bad" {
1167    arg "<mode>" validate="value == 'good'" validate_error="mode must be good"
1168}
1169arg "[ports]..." env="PORTS" var=#true var_max=1 delimiter="," validate="int(value) > 0" validate_error="all ports must be positive"
1170flag "--levels" env="LEVELS" {
1171    arg "<level>..." var=#true var_max=1 delimiter="," validate="value == 'good'" validate_error="all levels must be good"
1172}
1173flag "--modes" default="good,bad" {
1174    arg "<mode>..." var=#true var_max=1 delimiter="," validate="value == 'good'" validate_error="all modes must be good"
1175}
1176flag "--conditional" {
1177    default_if "--trigger" "good,bad"
1178    arg "<conditional>..." var=#true var_max=1 delimiter="," validate="value == 'good'" validate_error="all conditional values must be good"
1179}
1180flag "--repeats <repeat>" env="REPEATS" var=#true var_max=1 delimiter=","
1181flag "--trigger"
1182        "#
1183        .parse()
1184        .unwrap();
1185        let env = HashMap::from([
1186            ("PORT".to_string(), "0".to_string()),
1187            ("PORTS".to_string(), "1,0".to_string()),
1188            ("LEVELS".to_string(), "good,bad".to_string()),
1189            ("REPEATS".to_string(), "one,two".to_string()),
1190        ]);
1191        let error = Parser::new(&spec)
1192            .with_env(env)
1193            .parse(&["ex".to_string(), "--trigger".to_string()])
1194            .unwrap_err();
1195        let error = error.to_string();
1196        assert!(error.contains("port must be positive"), "{error}");
1197        assert!(error.contains("mode must be good"), "{error}");
1198        assert!(error.contains("all ports must be positive"), "{error}");
1199        assert!(error.contains("all levels must be good"), "{error}");
1200        assert!(error.contains("all modes must be good"), "{error}");
1201        assert!(
1202            error.contains("all conditional values must be good"),
1203            "{error}"
1204        );
1205        assert!(
1206            error.contains("Variadic argument <ports> accepts at most 1 value(s), got 2"),
1207            "{error}"
1208        );
1209        for flag in ["levels", "modes", "conditional", "repeats"] {
1210            assert!(
1211                error.contains(&format!(
1212                    "Variadic flag --{flag} accepts at most 1 value(s), got 2"
1213                )),
1214                "{error}"
1215            );
1216        }
1217    }
1218}
1219
1220#[cfg(test)]
1221mod delimiter_tests {
1222    use crate::Spec;
1223
1224    #[test]
1225    fn a_delimiter_has_to_be_one_byte() {
1226        // Splitting is by byte below the spec. A separator that is one *character* but
1227        // several bytes has no byte to be, and picking its low one would match the
1228        // continuation bytes inside unrelated characters — `§` would split `aЧb`. Refused
1229        // where it is written, which is the derive's rule too.
1230        for spec in [
1231            "flag \"--tags <tag>\" var=#true delimiter=\"§\"\n",
1232            "arg \"[tags]...\" var=#true delimiter=\"、\"\n",
1233        ] {
1234            let err = spec.parse::<Spec>().unwrap_err();
1235            assert!(format!("{err:?}").contains("one byte"), "{err:?}");
1236        }
1237
1238        // A clap command may still declare one; clap splits on it by character. The spec
1239        // cannot say so, and drops it rather than recording a separator it could not write
1240        // back out — the values still arrive, since `var` is set either way.
1241        let cmd = clap::Command::new("ex").arg(
1242            clap::Arg::new("tags")
1243                .long("tags")
1244                .value_delimiter('、')
1245                .action(clap::ArgAction::Set),
1246        );
1247        let spec = Spec::from(&cmd);
1248        let arg = spec.cmd.flags[0].arg.as_ref().unwrap();
1249        assert_eq!(
1250            arg.delimiter, None,
1251            "a separator it cannot write is not recorded"
1252        );
1253        assert!(arg.var, "clap still splits, so the values still arrive");
1254        spec.to_string()
1255            .parse::<Spec>()
1256            .expect("what the bridge produces has to parse back");
1257    }
1258
1259    #[test]
1260    fn a_delimiter_round_trips_and_comes_across_from_clap() {
1261        let spec: Spec = "flag \"--tags <tag>\" var=#true delimiter=\",\"\n"
1262            .parse()
1263            .unwrap();
1264        let arg = spec.cmd.flags[0].arg.as_ref().unwrap();
1265        assert_eq!(arg.delimiter, Some(','));
1266
1267        let reparsed: Spec = spec.to_string().parse().unwrap();
1268        let arg = reparsed.cmd.flags[0].arg.as_ref().unwrap();
1269        assert_eq!(arg.delimiter, Some(','), "{spec}");
1270
1271        // clap answers for this one, through the same getter the default splitting
1272        // already used.
1273        let cmd = clap::Command::new("ex").arg(
1274            clap::Arg::new("tags")
1275                .long("tags")
1276                .value_delimiter(',')
1277                .num_args(1..)
1278                .default_value("a,b"),
1279        );
1280        let spec = Spec::from(&cmd);
1281        let flag = &spec.cmd.flags[0];
1282        assert_eq!(flag.arg.as_ref().unwrap().delimiter, Some(','));
1283        // And the default is still recorded split, which is the same statement. On the
1284        // flag rather than on its argument, which is where the bridge puts a flag's.
1285        assert_eq!(flag.default, vec!["a", "b"]);
1286    }
1287
1288    #[test]
1289    fn a_single_valued_clap_arg_keeps_its_delimiter() {
1290        // clap's parser splits whenever a delimiter is set, whatever `num_args` says, so
1291        // `ArgAction::Set` with `value_delimiter(',')` is one word becoming several — the
1292        // common spelling. Reading it as single-valued dropped the delimiter and left a
1293        // CLI whose defaults split and whose typed values did not.
1294        let cmd = clap::Command::new("ex").arg(
1295            clap::Arg::new("tags")
1296                .long("tags")
1297                .action(clap::ArgAction::Set)
1298                .value_delimiter(','),
1299        );
1300        let spec = Spec::from(&cmd);
1301        let arg = spec.cmd.flags[0].arg.as_ref().unwrap();
1302        assert_eq!(arg.delimiter, Some(','));
1303        // And it says so: a delimiter is the statement that several values can land, so
1304        // the emitted spec has somewhere to put them and parses back.
1305        assert!(arg.var, "a delimiter brings `var` with it");
1306        let _: Spec = spec.to_string().parse().expect("{spec}");
1307    }
1308
1309    #[test]
1310    fn a_single_valued_clap_positional_splits_into_stored_values() {
1311        // The positional bridge uses `SpecArg::from(&clap::Arg)` directly, unlike a
1312        // flag. A delimiter therefore has to make that argument variadic here too or
1313        // parsing validates the split parts and then stores the original unsplit word.
1314        let cmd = clap::Command::new("ex").arg(
1315            clap::Arg::new("tags")
1316                .action(clap::ArgAction::Set)
1317                .value_delimiter(',')
1318                .value_parser(["a", "b"]),
1319        );
1320        let spec = Spec::from(&cmd);
1321        let arg = &spec.cmd.args[0];
1322        assert!(arg.var, "a positional delimiter brings `var` with it");
1323        assert_eq!(arg.delimiter, Some(','));
1324
1325        let input = ["ex", "a,b"].map(str::to_string);
1326        let parsed = crate::parse(&spec, &input).expect("both split values are choices");
1327        let value = parsed
1328            .args
1329            .values()
1330            .next()
1331            .expect("the positional was stored");
1332        assert!(matches!(
1333            value,
1334            crate::parse::ParseValue::MultiString(values)
1335                if values == &["a".to_string(), "b".to_string()]
1336        ));
1337    }
1338
1339    #[test]
1340    fn a_delimiter_needs_somewhere_to_put_what_it_splits() {
1341        // Without `var` everything after the first separator would be dropped, silently.
1342        let err = "flag \"--tags <tag>\" delimiter=\",\"\n"
1343            .parse::<Spec>()
1344            .unwrap_err();
1345        assert!(format!("{err:?}").contains("one value"), "{err:?}");
1346
1347        let err = "arg \"[tags]\" delimiter=\",\"\n"
1348            .parse::<Spec>()
1349            .unwrap_err();
1350        assert!(format!("{err:?}").contains("one value"), "{err:?}");
1351
1352        // A flag that takes no value has nothing to split at all.
1353        let err = "flag \"--quiet\" delimiter=\",\"\n"
1354            .parse::<Spec>()
1355            .unwrap_err();
1356        assert!(format!("{err:?}").contains("takes none"), "{err:?}");
1357
1358        // One character, or it is not a delimiter.
1359        let err = "flag \"--tags <tag>\" var=#true delimiter=\"::\"\n"
1360            .parse::<Spec>()
1361            .unwrap_err();
1362        assert!(format!("{err:?}").contains("one character"), "{err:?}");
1363    }
1364}
1365
1366#[cfg(test)]
1367mod possible_value_tests {
1368    use clap::builder::PossibleValue;
1369
1370    #[test]
1371    fn clap_possible_value_metadata_survives_the_bridge() {
1372        let command = clap::Command::new("ex").arg(
1373            clap::Arg::new("color").ignore_case(true).value_parser([
1374                PossibleValue::new("always")
1375                    .help("Always use color")
1376                    .alias("yes"),
1377                PossibleValue::new("never").hide(true),
1378            ]),
1379        );
1380        let spec = crate::Spec::from(&command);
1381        let choices = spec.cmd.args[0].choices.as_ref().unwrap();
1382        assert_eq!(choices.choices, ["always", "never"]);
1383        assert!(choices.ignore_case);
1384        assert!(choices.matches("YES"));
1385        assert_eq!(choices.values(), ["always"]);
1386        assert_eq!(choices.details[0].help.as_deref(), Some("Always use color"));
1387        assert!(choices.details[0].aliases[0].hide);
1388        assert!(choices.details[1].hide);
1389    }
1390}
1391
1392#[cfg(test)]
1393mod tests {
1394    use crate::{Spec, SpecArg};
1395    use insta::assert_snapshot;
1396
1397    #[test]
1398    fn test_arg_with_env() {
1399        let spec = Spec::parse(
1400            &Default::default(),
1401            r#"
1402arg "<input>" env="MY_INPUT" help="Input file"
1403arg "<output>" env="MY_OUTPUT"
1404            "#,
1405        )
1406        .unwrap();
1407
1408        assert_snapshot!(spec, @r#"
1409        arg <input> help="Input file" env=MY_INPUT
1410        arg <output> env=MY_OUTPUT
1411        "#);
1412
1413        let input_arg = spec.cmd.args.iter().find(|a| a.name == "input").unwrap();
1414        assert_eq!(input_arg.env, Some("MY_INPUT".to_string()));
1415
1416        let output_arg = spec.cmd.args.iter().find(|a| a.name == "output").unwrap();
1417        assert_eq!(output_arg.env, Some("MY_OUTPUT".to_string()));
1418    }
1419
1420    #[test]
1421    fn test_arg_with_env_child_node() {
1422        let spec = Spec::parse(
1423            &Default::default(),
1424            r#"
1425arg "<input>" help="Input file" {
1426    env "MY_INPUT"
1427}
1428arg "<output>" {
1429    env "MY_OUTPUT"
1430}
1431            "#,
1432        )
1433        .unwrap();
1434
1435        assert_snapshot!(spec, @r#"
1436        arg <input> help="Input file" env=MY_INPUT
1437        arg <output> env=MY_OUTPUT
1438        "#);
1439
1440        let input_arg = spec.cmd.args.iter().find(|a| a.name == "input").unwrap();
1441        assert_eq!(input_arg.env, Some("MY_INPUT".to_string()));
1442
1443        let output_arg = spec.cmd.args.iter().find(|a| a.name == "output").unwrap();
1444        assert_eq!(output_arg.env, Some("MY_OUTPUT".to_string()));
1445    }
1446
1447    #[test]
1448    fn test_arg_variadic_syntax() {
1449        use crate::SpecArg;
1450
1451        // Trailing ellipsis with required brackets
1452        let arg: SpecArg = "<files>...".into();
1453        assert_eq!(arg.name, "files");
1454        assert!(arg.var);
1455        assert!(arg.required);
1456
1457        // Trailing ellipsis with optional brackets
1458        let arg: SpecArg = "[files]...".into();
1459        assert_eq!(arg.name, "files");
1460        assert!(arg.var);
1461        assert!(!arg.required);
1462
1463        // Unicode ellipsis
1464        let arg: SpecArg = "<files>…".into();
1465        assert_eq!(arg.name, "files");
1466        assert!(arg.var);
1467
1468        let arg: SpecArg = "[files]…".into();
1469        assert_eq!(arg.name, "files");
1470        assert!(arg.var);
1471        assert!(!arg.required);
1472
1473        // Ellipsis inside brackets: [args...] and <args...>
1474        let arg: SpecArg = "[args...]".into();
1475        assert_eq!(arg.name, "args");
1476        assert!(arg.var);
1477        assert!(!arg.required);
1478
1479        let arg: SpecArg = "<args...>".into();
1480        assert_eq!(arg.name, "args");
1481        assert!(arg.var);
1482        assert!(arg.required);
1483
1484        // Unicode ellipsis inside brackets
1485        let arg: SpecArg = "[args…]".into();
1486        assert_eq!(arg.name, "args");
1487        assert!(arg.var);
1488        assert!(!arg.required);
1489    }
1490
1491    #[test]
1492    fn fixed_arity_placeholders_round_trip() {
1493        let spec: Spec = "arg \"<START> <END>\"\n".parse().unwrap();
1494        let arg = &spec.cmd.args[0];
1495        assert_eq!(arg.value_names, ["START", "END"]);
1496        assert_eq!((arg.var_min, arg.var_max), (Some(2), Some(2)));
1497        assert_eq!(arg.usage, "<START> <END>");
1498
1499        let reparsed: Spec = spec.to_string().parse().unwrap();
1500        assert_eq!(reparsed.cmd.args[0].value_names, ["START", "END"]);
1501    }
1502
1503    #[test]
1504    fn fixed_arity_placeholders_reject_mismatched_bounds() {
1505        let error = "arg \"<START> <END>\" var_min=1 var_max=2\n"
1506            .parse::<Spec>()
1507            .unwrap_err();
1508        assert!(
1509            format!("{error:?}").contains("require var_min=2 and var_max=2"),
1510            "{error:?}"
1511        );
1512    }
1513
1514    #[test]
1515    fn a_single_value_name_replaces_the_display_name() {
1516        let spec: Spec = "arg \"<input>\" { value_names \"INPUT\" }\n"
1517            .parse()
1518            .unwrap();
1519        let arg = &spec.cmd.args[0];
1520        assert_eq!(arg.name, "INPUT");
1521        assert_eq!(arg.usage, "<INPUT>");
1522
1523        let built = SpecArg::builder()
1524            .name("input")
1525            .required(true)
1526            .value_names(["INPUT"])
1527            .build();
1528        assert_eq!(built.name, "INPUT");
1529        assert_eq!(built.usage, "<INPUT>");
1530    }
1531
1532    #[test]
1533    fn builder_fixed_arity_survives_later_bound_setters() {
1534        let after = SpecArg::builder()
1535            .value_names(["START", "END"])
1536            .var(false)
1537            .var_min(1)
1538            .var_max(4)
1539            .build();
1540        let before = SpecArg::builder()
1541            .var(false)
1542            .var_min(1)
1543            .var_max(4)
1544            .value_names(["START", "END"])
1545            .build();
1546        for arg in [after, before] {
1547            assert!(arg.var);
1548            assert_eq!((arg.var_min, arg.var_max), (Some(2), Some(2)));
1549            assert_eq!(arg.usage, "[START] [END]");
1550        }
1551    }
1552
1553    #[test]
1554    fn one_label_with_exact_bounds_renders_each_value_slot() {
1555        let spec: Spec = "arg \"<item>…\" var_min=2 var_max=2 { value_names \"ITEM\" }\n"
1556            .parse()
1557            .unwrap();
1558        assert_eq!(spec.cmd.args[0].usage, "<ITEM> <ITEM>");
1559        let reparsed: Spec = spec.to_string().parse().unwrap();
1560        assert_eq!(reparsed.cmd.args[0].value_names, ["ITEM", "ITEM"]);
1561        assert_eq!(
1562            (reparsed.cmd.args[0].var_min, reparsed.cmd.args[0].var_max),
1563            (Some(2), Some(2))
1564        );
1565
1566        let built = SpecArg::builder()
1567            .value_names(["ITEM"])
1568            .required(true)
1569            .var(true)
1570            .var_min(2)
1571            .var_max(2)
1572            .build();
1573        assert_eq!(built.usage, "<ITEM> <ITEM>");
1574    }
1575
1576    #[test]
1577    fn fixed_arity_placeholders_reject_mixed_requiredness() {
1578        let error = "arg \"<START> [END]\"\n".parse::<Spec>().unwrap_err();
1579        assert!(
1580            format!("{error:?}")
1581                .contains("fixed-arity placeholders must be either all required or all optional"),
1582            "{error:?}"
1583        );
1584    }
1585
1586    #[test]
1587    fn test_arg_child_nodes() {
1588        let spec = Spec::parse(
1589            &Default::default(),
1590            r#"
1591arg "<environment>" {
1592    help "Deployment environment"
1593    choices "dev" "staging" "prod"
1594}
1595arg "[services]" {
1596    help "Services to deploy"
1597    var #true
1598    var_min 0
1599}
1600            "#,
1601        )
1602        .unwrap();
1603
1604        let env_arg = spec
1605            .cmd
1606            .args
1607            .iter()
1608            .find(|a| a.name == "environment")
1609            .unwrap();
1610        assert_eq!(env_arg.help, Some("Deployment environment".to_string()));
1611        assert!(env_arg.choices.is_some());
1612
1613        let svc_arg = spec.cmd.args.iter().find(|a| a.name == "services").unwrap();
1614        assert_eq!(svc_arg.help, Some("Services to deploy".to_string()));
1615        assert!(svc_arg.var);
1616        assert_eq!(svc_arg.var_min, Some(0));
1617    }
1618
1619    #[test]
1620    fn test_arg_long_help_child_node() {
1621        let spec = Spec::parse(
1622            &Default::default(),
1623            r#"
1624arg "<input>" {
1625    help "Input file"
1626    long_help "Extended help text for input"
1627}
1628            "#,
1629        )
1630        .unwrap();
1631
1632        let input_arg = spec.cmd.args.iter().find(|a| a.name == "input").unwrap();
1633        assert_eq!(input_arg.help, Some("Input file".to_string()));
1634        assert_eq!(
1635            input_arg.help_long,
1636            Some("Extended help text for input".to_string())
1637        );
1638    }
1639
1640    #[test]
1641    fn positional_conflicts_round_trip_without_dropping_members() {
1642        let spec: Spec = "arg \"[VALUE]\" { conflicts \"--from-file\" \"--stdin\" }\n"
1643            .parse()
1644            .unwrap();
1645        assert_eq!(
1646            spec.cmd.args[0].conflicts,
1647            vec!["--from-file".to_string(), "--stdin".to_string()]
1648        );
1649
1650        let rendered = spec.to_string();
1651        let reparsed: Spec = rendered.parse().unwrap();
1652        assert_eq!(reparsed.cmd.args[0].conflicts, spec.cmd.args[0].conflicts);
1653    }
1654}