Skip to main content

usage/spec/
arg.rs

1use kdl::{KdlDocument, KdlEntry, KdlNode};
2use serde::Serialize;
3use std::fmt::Display;
4use std::hash::Hash;
5use std::str::FromStr;
6
7use crate::error::UsageErr;
8use crate::spec::builder::SpecArgBuilder;
9use crate::spec::context::ParsingContext;
10use crate::spec::helpers::NodeHelper;
11use crate::spec::is_false;
12use crate::{string, SpecChoices};
13
14#[derive(Debug, Default, Clone, Serialize, PartialEq, Eq, strum::EnumString, strum::Display)]
15#[strum(serialize_all = "snake_case")]
16pub enum SpecDoubleDashChoices {
17    /// Once an arg is entered, behave as if "--" was passed
18    Automatic,
19    /// Allow "--" to be passed
20    #[default]
21    Optional,
22    /// Require "--" to be passed
23    Required,
24    /// Preserve "--" tokens as values (only for variadic args)
25    Preserve,
26}
27
28/// A positional argument specification.
29///
30/// Arguments are positional values passed to a command without a flag prefix.
31/// They can be required or optional, and can accept multiple values (variadic).
32///
33/// # Example
34///
35/// ```
36/// use usage::SpecArg;
37///
38/// let arg = SpecArg::builder()
39///     .name("file")
40///     .required(true)
41///     .help("Input file to process")
42///     .build();
43/// ```
44#[derive(Debug, Default, Clone, Serialize)]
45pub struct SpecArg {
46    /// Name of the argument (used in help text)
47    pub name: String,
48    /// Generated usage string (e.g., "<file>" or "[file]")
49    pub usage: String,
50    /// Short help text shown in command listings
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub help: Option<String>,
53    /// Extended help text shown with --help
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub help_long: Option<String>,
56    /// Markdown-formatted help text
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub help_md: Option<String>,
59    /// First line of help text (auto-generated)
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub help_first_line: Option<String>,
62    /// Whether this argument must be provided
63    pub required: bool,
64    /// How to handle the "--" separator
65    pub double_dash: SpecDoubleDashChoices,
66    /// Whether this argument accepts multiple values
67    #[serde(skip_serializing_if = "is_false")]
68    pub var: bool,
69    /// Minimum number of values for variadic arguments
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub var_min: Option<usize>,
72    /// Maximum number of values for variadic arguments
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub var_max: Option<usize>,
75    /// Whether to hide this argument from help output
76    pub hide: bool,
77    /// Default value(s) if the argument is not provided
78    #[serde(skip_serializing_if = "Vec::is_empty")]
79    pub default: Vec<String>,
80    /// Valid choices for this argument
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub choices: Option<SpecChoices>,
83    /// Environment variable that can provide this argument's value
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub env: Option<String>,
86}
87
88impl SpecArg {
89    /// Create a new builder for SpecArg
90    pub fn builder() -> SpecArgBuilder {
91        SpecArgBuilder::new()
92    }
93
94    pub(crate) fn parse(ctx: &ParsingContext, node: &NodeHelper) -> Result<Self, UsageErr> {
95        let mut arg: SpecArg = node.arg(0)?.ensure_string()?.parse()?;
96        for (k, v) in node.props() {
97            match k {
98                "help" => arg.help = Some(v.ensure_string()?),
99                "long_help" => arg.help_long = Some(v.ensure_string()?),
100                "help_long" => arg.help_long = Some(v.ensure_string()?),
101                "help_md" => arg.help_md = Some(v.ensure_string()?),
102                "required" => arg.required = v.ensure_bool()?,
103                "double_dash" => arg.double_dash = v.ensure_string()?.parse()?,
104                "var" => arg.var = v.ensure_bool()?,
105                "hide" => arg.hide = v.ensure_bool()?,
106                "var_min" => arg.var_min = v.ensure_usize().map(Some)?,
107                "var_max" => arg.var_max = v.ensure_usize().map(Some)?,
108                "default" => arg.default = vec![v.ensure_string()?],
109                "env" => arg.env = v.ensure_string().map(Some)?,
110                k => bail_parse!(ctx, v.entry.span(), "unsupported arg key {k}"),
111            }
112        }
113        if !arg.default.is_empty() {
114            arg.required = false;
115        }
116        for child in node.children() {
117            match child.name() {
118                "choices" => arg.choices = Some(SpecChoices::parse(ctx, &child)?),
119                "env" => arg.env = child.arg(0)?.ensure_string().map(Some)?,
120                "default" => {
121                    // Support both single value and multiple values
122                    // default "bar"            -> vec!["bar"]
123                    // default { "xyz"; "bar" } -> vec!["xyz", "bar"]
124                    let children = child.children();
125                    if children.is_empty() {
126                        // Single value: default "bar"
127                        arg.default = vec![child.arg(0)?.ensure_string()?];
128                    } else {
129                        // Multiple values from children: default { "xyz"; "bar" }
130                        // In KDL, these are child nodes where the string is the node name
131                        arg.default = children.iter().map(|c| c.name().to_string()).collect();
132                    }
133                }
134                k => bail_parse!(ctx, child.node.name().span(), "unsupported arg child {k}"),
135            }
136        }
137        arg.usage = arg.usage();
138        if let Some(help) = &arg.help {
139            arg.help_first_line = Some(string::first_line(help));
140        }
141        Ok(arg)
142    }
143}
144
145impl SpecArg {
146    pub fn usage(&self) -> String {
147        let name = if self.double_dash == SpecDoubleDashChoices::Required {
148            format!("-- {}", self.name)
149        } else {
150            self.name.clone()
151        };
152        let mut name = if self.required {
153            format!("<{name}>")
154        } else {
155            format!("[{name}]")
156        };
157        if self.var {
158            name = format!("{name}…");
159        }
160        name
161    }
162}
163
164impl From<&SpecArg> for KdlNode {
165    fn from(arg: &SpecArg) -> Self {
166        let mut node = KdlNode::new("arg");
167        node.push(KdlEntry::new(arg.usage()));
168        if let Some(desc) = &arg.help {
169            node.push(KdlEntry::new_prop("help", desc.clone()));
170        }
171        if let Some(desc) = &arg.help_long {
172            node.push(KdlEntry::new_prop("help_long", desc.clone()));
173        }
174        if let Some(desc) = &arg.help_md {
175            node.push(KdlEntry::new_prop("help_md", desc.clone()));
176        }
177        if !arg.required {
178            node.push(KdlEntry::new_prop("required", false));
179        }
180        if arg.double_dash == SpecDoubleDashChoices::Automatic
181            || arg.double_dash == SpecDoubleDashChoices::Preserve
182        {
183            node.push(KdlEntry::new_prop(
184                "double_dash",
185                arg.double_dash.to_string(),
186            ));
187        }
188        if arg.var {
189            node.push(KdlEntry::new_prop("var", true));
190        }
191        if let Some(min) = arg.var_min {
192            node.push(KdlEntry::new_prop("var_min", min as i128));
193        }
194        if let Some(max) = arg.var_max {
195            node.push(KdlEntry::new_prop("var_max", max as i128));
196        }
197        if arg.hide {
198            node.push(KdlEntry::new_prop("hide", true));
199        }
200        // Serialize default values
201        if !arg.default.is_empty() {
202            if arg.default.len() == 1 {
203                // Single value: use property default="bar"
204                node.push(KdlEntry::new_prop("default", arg.default[0].clone()));
205            } else {
206                // Multiple values: use child node default { "xyz"; "bar" }
207                let children = node.children_mut().get_or_insert_with(KdlDocument::new);
208                let mut default_node = KdlNode::new("default");
209                let default_children = default_node
210                    .children_mut()
211                    .get_or_insert_with(KdlDocument::new);
212                for val in &arg.default {
213                    default_children
214                        .nodes_mut()
215                        .push(KdlNode::new(val.as_str()));
216                }
217                children.nodes_mut().push(default_node);
218            }
219        }
220        if let Some(env) = &arg.env {
221            node.push(KdlEntry::new_prop("env", env.clone()));
222        }
223        if let Some(choices) = &arg.choices {
224            let children = node.children_mut().get_or_insert_with(KdlDocument::new);
225            children.nodes_mut().push(choices.into());
226        }
227        node
228    }
229}
230
231impl From<&str> for SpecArg {
232    fn from(input: &str) -> Self {
233        let mut arg = SpecArg {
234            name: input.to_string(),
235            required: true,
236            ..Default::default()
237        };
238        // Handle trailing ellipsis: "foo..." or "foo…" or "<foo>..." or "[foo]..."
239        if let Some(name) = arg
240            .name
241            .strip_suffix("...")
242            .or_else(|| arg.name.strip_suffix("…"))
243        {
244            arg.var = true;
245            arg.name = name.to_string();
246        }
247        let first = arg.name.chars().next().unwrap_or_default();
248        let last = arg.name.chars().last().unwrap_or_default();
249        match (first, last) {
250            ('[', ']') => {
251                arg.name = arg.name[1..arg.name.len() - 1].to_string();
252                arg.required = false;
253            }
254            ('<', '>') => {
255                arg.name = arg.name[1..arg.name.len() - 1].to_string();
256            }
257            _ => {}
258        }
259        // Also handle ellipsis inside brackets: "[args...]" or "<args...>"
260        if !arg.var {
261            if let Some(name) = arg
262                .name
263                .strip_suffix("...")
264                .or_else(|| arg.name.strip_suffix("…"))
265            {
266                arg.var = true;
267                arg.name = name.to_string();
268            }
269        }
270        if let Some(name) = arg.name.strip_prefix("-- ") {
271            arg.double_dash = SpecDoubleDashChoices::Required;
272            arg.name = name.to_string();
273        }
274        arg
275    }
276}
277impl FromStr for SpecArg {
278    type Err = UsageErr;
279    fn from_str(input: &str) -> std::result::Result<Self, UsageErr> {
280        Ok(input.into())
281    }
282}
283
284#[cfg(feature = "clap")]
285impl From<&clap::Arg> for SpecArg {
286    fn from(arg: &clap::Arg) -> Self {
287        let required = arg.is_required_set();
288        let help = arg.get_help().map(|s| s.to_string());
289        let help_long = arg.get_long_help().map(|s| s.to_string());
290        let help_first_line = help.as_ref().map(|s| string::first_line(s));
291        let hide = arg.is_hide_set();
292        let var = matches!(
293            arg.get_action(),
294            clap::ArgAction::Count | clap::ArgAction::Append
295        );
296        let choices = arg
297            .get_possible_values()
298            .iter()
299            .flat_map(|v| v.get_name_and_aliases().map(|s| s.to_string()))
300            .collect::<Vec<_>>();
301        let mut arg = Self {
302            name: arg
303                .get_value_names()
304                .unwrap_or_default()
305                .first()
306                .cloned()
307                .unwrap_or_default()
308                .to_string(),
309            usage: "".into(),
310            required,
311            double_dash: if arg.is_last_set() {
312                SpecDoubleDashChoices::Required
313            } else if arg.is_trailing_var_arg_set() {
314                SpecDoubleDashChoices::Automatic
315            } else {
316                SpecDoubleDashChoices::Optional
317            },
318            help,
319            help_long,
320            help_md: None,
321            help_first_line,
322            var,
323            var_max: None,
324            var_min: None,
325            hide,
326            default: arg
327                .get_default_values()
328                .iter()
329                .map(|v| v.to_string_lossy().to_string())
330                .collect(),
331            choices: None,
332            env: None,
333        };
334        if !choices.is_empty() {
335            arg.choices = Some(SpecChoices { choices });
336        }
337
338        arg
339    }
340}
341
342impl Display for SpecArg {
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        write!(f, "{}", self.usage())
345    }
346}
347impl PartialEq for SpecArg {
348    fn eq(&self, other: &Self) -> bool {
349        self.name == other.name
350    }
351}
352impl Eq for SpecArg {}
353impl Hash for SpecArg {
354    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
355        self.name.hash(state);
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use crate::Spec;
362    use insta::assert_snapshot;
363
364    #[test]
365    fn test_arg_with_env() {
366        let spec = Spec::parse(
367            &Default::default(),
368            r#"
369arg "<input>" env="MY_INPUT" help="Input file"
370arg "<output>" env="MY_OUTPUT"
371            "#,
372        )
373        .unwrap();
374
375        assert_snapshot!(spec, @r#"
376        arg <input> help="Input file" env=MY_INPUT
377        arg <output> env=MY_OUTPUT
378        "#);
379
380        let input_arg = spec.cmd.args.iter().find(|a| a.name == "input").unwrap();
381        assert_eq!(input_arg.env, Some("MY_INPUT".to_string()));
382
383        let output_arg = spec.cmd.args.iter().find(|a| a.name == "output").unwrap();
384        assert_eq!(output_arg.env, Some("MY_OUTPUT".to_string()));
385    }
386
387    #[test]
388    fn test_arg_with_env_child_node() {
389        let spec = Spec::parse(
390            &Default::default(),
391            r#"
392arg "<input>" help="Input file" {
393    env "MY_INPUT"
394}
395arg "<output>" {
396    env "MY_OUTPUT"
397}
398            "#,
399        )
400        .unwrap();
401
402        assert_snapshot!(spec, @r#"
403        arg <input> help="Input file" env=MY_INPUT
404        arg <output> env=MY_OUTPUT
405        "#);
406
407        let input_arg = spec.cmd.args.iter().find(|a| a.name == "input").unwrap();
408        assert_eq!(input_arg.env, Some("MY_INPUT".to_string()));
409
410        let output_arg = spec.cmd.args.iter().find(|a| a.name == "output").unwrap();
411        assert_eq!(output_arg.env, Some("MY_OUTPUT".to_string()));
412    }
413
414    #[test]
415    fn test_arg_variadic_syntax() {
416        use crate::SpecArg;
417
418        // Trailing ellipsis with required brackets
419        let arg: SpecArg = "<files>...".into();
420        assert_eq!(arg.name, "files");
421        assert!(arg.var);
422        assert!(arg.required);
423
424        // Trailing ellipsis with optional brackets
425        let arg: SpecArg = "[files]...".into();
426        assert_eq!(arg.name, "files");
427        assert!(arg.var);
428        assert!(!arg.required);
429
430        // Unicode ellipsis
431        let arg: SpecArg = "<files>…".into();
432        assert_eq!(arg.name, "files");
433        assert!(arg.var);
434
435        let arg: SpecArg = "[files]…".into();
436        assert_eq!(arg.name, "files");
437        assert!(arg.var);
438        assert!(!arg.required);
439
440        // Ellipsis inside brackets: [args...] and <args...>
441        let arg: SpecArg = "[args...]".into();
442        assert_eq!(arg.name, "args");
443        assert!(arg.var);
444        assert!(!arg.required);
445
446        let arg: SpecArg = "<args...>".into();
447        assert_eq!(arg.name, "args");
448        assert!(arg.var);
449        assert!(arg.required);
450
451        // Unicode ellipsis inside brackets
452        let arg: SpecArg = "[args…]".into();
453        assert_eq!(arg.name, "args");
454        assert!(arg.var);
455        assert!(!arg.required);
456    }
457}