Skip to main content

cuc/
usage.rs

1use kdl::KdlNode;
2use std::{
3    collections::{HashMap, HashSet},
4    io,
5};
6
7use crate::namespace::NameSpace;
8
9#[derive(Debug, Default, Clone)]
10pub struct UsageSpec {
11    pub info: Info,
12    pub flags: Vec<Flag>,
13    pub args: Vec<Arg>,
14    pub cmds: Vec<Cmd>,
15    pub completes: HashMap<String, Complete>,
16    pub default_subcommand: Option<String>,
17    pub default_subcommand_flags: bool,
18    /// Root-level mounts, whose commands the generated completion discovers by
19    /// running them.
20    pub pending_mounts: Vec<PendingMount>,
21    /// Root-level sigil arguments.
22    pub sigils: Vec<Arg>,
23}
24
25#[derive(Debug, Default, Clone)]
26pub struct Info {
27    pub name: String,
28    pub bin: String,
29}
30
31#[derive(Debug, Clone)]
32pub enum Usage {
33    Flag(Flag),
34    Arg(Arg),
35    Cmd(Cmd),
36    Complete(Complete),
37}
38
39#[derive(Debug, Default, Clone)]
40pub struct Alias {
41    pub name: String,
42    pub hide: bool,
43}
44
45#[derive(Debug, Default, Clone)]
46pub enum GlobalFlag {
47    #[default]
48    None,
49    Itself,
50    Imposed(NameSpace),
51}
52
53#[derive(Debug, Default, Clone)]
54pub struct Flag {
55    pub name: String,
56    pub names: Vec<String>,
57    pub help: String,
58    pub hide: bool,
59    pub global: GlobalFlag,
60    pub aliases: Vec<Alias>,
61    pub arg: Option<Arg>,
62}
63
64#[derive(Debug, Default, Clone)]
65pub struct Arg {
66    pub name: String,
67    pub repr: String,
68    pub required: bool,
69    pub choices: Vec<String>,
70    pub hide: bool,
71    pub var: bool,
72    pub min: Option<i128>,
73    pub max: Option<i128>,
74    pub default: Option<String>,
75    pub double_dash: DoubleDash,
76    /// A leading prefix that classifies this argument independently of its place in
77    /// the positional sequence, e.g. `+` for `+node`. The prefix is removed before the
78    /// value is stored or completed.
79    pub sigil: Option<String>,
80}
81
82#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
83pub enum DoubleDash {
84    Automatic,
85    #[default]
86    Optional,
87    Required,
88    Preserve,
89}
90
91#[derive(Debug, Default, Clone)]
92pub struct Cmd {
93    pub name: String,
94    pub help: String,
95    pub hide: bool,
96    pub args: Vec<Arg>,
97    pub flags: Vec<Flag>,
98    pub aliases: Vec<Alias>,
99    pub cmds: Vec<Box<Cmd>>,
100    pub completes: HashMap<String, Complete>,
101    pub mounted: bool,
102    /// Mounts declared by this command. Their commands are discovered by running the
103    /// mount while completing, never while generating.
104    pub pending_mounts: Vec<PendingMount>,
105    /// Sigil arguments in effect here: this command's own plus every ancestor's, because
106    /// a subcommand inherits the sigils declared by its ancestors.
107    pub sigils: Vec<Arg>,
108    /// Token that restarts argument parsing, letting one command line hold several
109    /// invocations of this command.
110    pub restart_token: Option<String>,
111}
112
113/// A Usage `mount`: the mounted commands are discovered by running `run` while
114/// completing, as usage itself does when it resolves a mount.
115#[derive(Debug, Default, Clone, PartialEq, Eq)]
116pub struct PendingMount {
117    /// Command executed while completing to print the mounted command names.
118    pub run: String,
119    /// Placeholder shown for the discovered commands, e.g. `[TASK] [ARGS]…`.
120    pub synopsis: Option<String>,
121}
122
123#[derive(Debug, Default, Clone)]
124pub struct Complete {
125    pub name: String,
126    pub kind: CompleteKind,
127    pub descs: bool,
128}
129
130#[derive(Debug, Clone, Default)]
131pub enum CompleteKind {
132    #[default]
133    None,
134    File,
135    Dir,
136    Run(String),
137}
138
139pub fn parse_name(node: &KdlNode) -> Result<String, UError> {
140    if node.name().value() != "name" {
141        return Err(UError::InvalidNodeName(io::Error::new(
142            io::ErrorKind::InvalidInput,
143            format!("Node name wasn't name!\n{:?}", node),
144        )));
145    }
146    let name = node
147        .get(0)
148        .map(|v| v.as_string().unwrap_or_default().to_string())
149        .ok_or_else(|| {
150            UError::InvalidNodeFirstArg(io::Error::new(
151                io::ErrorKind::NotFound,
152                format!("No name found in {:?}", node),
153            ))
154        })?;
155    Ok(name)
156}
157
158pub fn parse_bin(node: &KdlNode) -> Result<String, UError> {
159    if node.name().value() != "bin" {
160        return Err(UError::InvalidNodeName(io::Error::new(
161            io::ErrorKind::InvalidInput,
162            format!("Node name wasn't bin!\n{:?}", node),
163        )));
164    }
165    let bin = node
166        .get(0)
167        .map(|v| v.as_string().unwrap_or_default().to_string())
168        .ok_or_else(|| {
169            UError::InvalidNodeFirstArg(io::Error::new(
170                io::ErrorKind::NotFound,
171                format!("No bin found in {:?}", node),
172            ))
173        })?;
174    Ok(bin)
175}
176
177pub fn parse_include(node: &KdlNode) -> Result<String, UError> {
178    if node.name().value() != "include" {
179        return Err(UError::InvalidNodeName(io::Error::new(
180            io::ErrorKind::InvalidInput,
181            format!("Node name wasn't include!\n{:?}", node),
182        )));
183    }
184    let include = node
185        .get(0)
186        .map(|v| v.as_string().unwrap_or_default().to_string())
187        .ok_or_else(|| {
188            UError::InvalidNodeFirstArg(io::Error::new(
189                io::ErrorKind::NotFound,
190                format!("No include found in {:?}", node),
191            ))
192        })?;
193    Ok(include)
194}
195
196pub fn parse_alias(node: &KdlNode) -> Result<Vec<Alias>, UError> {
197    if node.name().value() != "alias" {
198        return Err(UError::InvalidNodeName(io::Error::new(
199            io::ErrorKind::InvalidInput,
200            format!("Node name wasn't alias!\n{:?}", node),
201        )));
202    }
203
204    let mut aliases: Vec<Alias> = vec![];
205    for entry in node.entries() {
206        let mut hide = false;
207        if entry.name().is_none() {
208            let alias_name = entry
209                .value()
210                .as_string()
211                .ok_or_else(|| {
212                    UError::InvalidNodeFirstArg(io::Error::new(
213                        io::ErrorKind::NotFound,
214                        format!("No alias found in {:?}", entry),
215                    ))
216                })?
217                .to_string();
218            if let Some(hide_val) = node.get("hide") {
219                hide = hide_val.as_bool().unwrap_or_default();
220            }
221            let alias = Alias {
222                name: alias_name,
223                hide,
224            };
225            aliases.push(alias);
226        }
227    }
228    Ok(aliases)
229}
230
231pub fn parse_choices(node: &KdlNode) -> Result<Vec<String>, UError> {
232    if node.name().value() != "choices" {
233        return Err(UError::InvalidNodeName(io::Error::new(
234            io::ErrorKind::InvalidInput,
235            format!("Node name wasn't choices!\n{:?}", node),
236        )));
237    }
238
239    let mut choices: Vec<String> = vec![];
240    for entry in node.entries() {
241        let choice = entry
242            .value()
243            .as_string()
244            .ok_or_else(|| {
245                UError::InvalidNodeFirstArg(io::Error::new(
246                    io::ErrorKind::NotFound,
247                    format!("No choice found in {:?}", entry),
248                ))
249            })?
250            .to_string();
251        choices.push(choice);
252    }
253    Ok(choices)
254}
255
256pub fn parse_flag(node: &KdlNode) -> Result<Flag, UError> {
257    if node.name().value() != "flag" {
258        return Err(UError::InvalidNodeName(io::Error::new(
259            io::ErrorKind::InvalidInput,
260            format!("Node name wasn't flag!\n{:?}", node),
261        )));
262    }
263
264    let mut flag = Flag::default();
265    for (index, entry) in node.entries().iter().enumerate() {
266        if index == 0 {
267            let entry_flag_names = entry
268                .value()
269                .as_string()
270                .ok_or_else(|| {
271                    UError::InvalidNodeFirstArg(io::Error::new(
272                        io::ErrorKind::NotFound,
273                        format!("No flag found in {:?}", entry),
274                    ))
275                })?
276                .to_string();
277
278            // the longest flag name is set as an identifier to flag.name
279            let (long_flag_index, flag_names) = {
280                let mut name_len = 0;
281                let mut flag_index = 0;
282                let mut long_flag_index = flag_index;
283                let flag_names: Vec<String> = entry_flag_names
284                    .split_whitespace()
285                    .map(|s| {
286                        let s = String::from(s);
287                        let len = s.len();
288                        if len > name_len {
289                            name_len = len;
290                            long_flag_index = flag_index;
291                        };
292                        flag_index += 1;
293                        s
294                    })
295                    .collect();
296                (long_flag_index, flag_names)
297            };
298
299            let slugify = |mut c: char| {
300                if !c.is_alphanumeric() && c != '_' {
301                    c = '_';
302                }
303                c
304            };
305
306            let flag_name = flag_names[long_flag_index]
307                .trim_matches('-')
308                .chars()
309                .map(slugify)
310                .collect();
311
312            flag.name = flag_name;
313            flag.names = flag_names;
314        }
315
316        if let Some(iden_name) = entry.name() {
317            match iden_name.value() {
318                "help" => flag.help = entry.value().as_string().unwrap_or_default().to_string(),
319                "hide" => flag.hide = entry.value().as_bool().unwrap_or_default(),
320                "global" => flag.global = entry.value().as_bool().unwrap_or_default().into(),
321                "negate" => {
322                    let negate_flag = entry.value().as_string().unwrap_or_default().to_string();
323                    if !negate_flag.is_empty() {
324                        flag.names.push(negate_flag);
325                    }
326                }
327                _ => {}
328            }
329        }
330    }
331
332    if let Some(child_doc) = node.children() {
333        for child_node in child_doc.nodes() {
334            match child_node.name().value() {
335                "arg" => flag.arg = Some(parse_arg(child_node)?),
336                "alias" => flag.aliases = parse_alias(child_node)?,
337                "choices" => {
338                    if let Some(arg_name) = flag.names.pop() {
339                        let arg = Arg {
340                            required: arg_name.starts_with('<'),
341                            name: arg_name,
342                            choices: parse_choices(child_node)?,
343                            ..Default::default()
344                        };
345                        flag.arg = Some(arg);
346                    }
347                }
348                _ => {}
349            }
350        }
351    }
352    Ok(flag)
353}
354
355pub fn parse_arg(node: &KdlNode) -> Result<Arg, UError> {
356    if node.name().value() != "arg" {
357        return Err(UError::InvalidNodeName(io::Error::new(
358            io::ErrorKind::InvalidInput,
359            format!("Node name wasn't arg!\n{:?}", node),
360        )));
361    }
362
363    let mut arg = Arg::default();
364    for (index, entry) in node.entries().iter().enumerate() {
365        if index == 0 {
366            let entry_arg_name = entry
367                .value()
368                .as_string()
369                .ok_or_else(|| {
370                    UError::InvalidNodeFirstArg(io::Error::new(
371                        io::ErrorKind::NotFound,
372                        format!("No arg found in {:?}", entry),
373                    ))
374                })?
375                .to_string();
376
377            if entry_arg_name.starts_with("<") {
378                arg.required = true;
379                let end = entry_arg_name.find(">").unwrap_or(entry_arg_name.len());
380                arg.name = entry_arg_name[1..end].to_string();
381            } else if entry_arg_name.starts_with("[") {
382                arg.required = false;
383                let end = entry_arg_name.find("]").unwrap_or(entry_arg_name.len());
384                arg.name = entry_arg_name[1..end].to_string();
385            }
386            arg.repr = entry_arg_name;
387        }
388
389        if let Some(iden_name) = entry.name() {
390            match iden_name.value() {
391                "hide" => arg.hide = entry.value().as_bool().unwrap_or_default(),
392                "default" => arg.default = entry.value().as_string().map(String::from),
393                "var" => arg.var = entry.value().as_bool().unwrap_or_default(),
394                "var_max" => arg.max = entry.value().as_integer(),
395                "var_min" => arg.min = entry.value().as_integer(),
396                _ => {}
397            }
398        }
399    }
400
401    arg.max = arg.max.or(Some(-1));
402    arg.min = arg.min.or(Some(0));
403
404    if let Some(child_doc) = node.children() {
405        for child_node in child_doc.nodes() {
406            if child_node.name().value() == "choices" {
407                let mut choices: Vec<String> = vec![];
408                for cn_entry in child_node.entries() {
409                    let choice = cn_entry
410                        .value()
411                        .as_string()
412                        .unwrap_or_else(|| panic!("No choice found in {:?}", cn_entry))
413                        .to_string();
414                    choices.push(choice);
415                }
416                arg.choices = choices;
417            }
418        }
419    }
420    Ok(arg)
421}
422
423pub fn parse_cmd(node: &KdlNode) -> Result<Cmd, UError> {
424    if node.name().value() != "cmd" {
425        return Err(UError::InvalidNodeName(io::Error::new(
426            io::ErrorKind::InvalidInput,
427            format!("Node name wasn't cmd!\n{:?}", node),
428        )));
429    }
430
431    let mut cmd = Cmd::default();
432    for (index, entry) in node.entries().iter().enumerate() {
433        if index == 0 {
434            let entry_cmd_name = entry
435                .value()
436                .as_string()
437                .ok_or_else(|| {
438                    UError::InvalidNodeFirstArg(io::Error::new(
439                        io::ErrorKind::NotFound,
440                        format!("No cmd found in {:?}", entry),
441                    ))
442                })?
443                .to_string();
444
445            cmd.name = entry_cmd_name;
446        }
447
448        if let Some(iden_name) = entry.name() {
449            match iden_name.value() {
450                "help" => {
451                    cmd.help = entry
452                        .value()
453                        .as_string()
454                        .map(String::from)
455                        .unwrap_or_default()
456                }
457                "hide" => cmd.hide = entry.value().as_bool().unwrap_or_default(),
458                _ => {}
459            }
460        }
461    }
462
463    if let Some(child_doc) = node.children() {
464        for child_node in child_doc.nodes() {
465            match child_node.name().value() {
466                "alias" => {
467                    let mut alias = parse_alias(child_node)?;
468                    cmd.aliases.append(&mut alias);
469                }
470                "flag" => {
471                    let flag = parse_flag(child_node)?;
472                    cmd.flags.push(flag);
473                }
474                "arg" => {
475                    let arg = parse_arg(child_node)?;
476                    cmd.args.push(arg);
477                }
478                "cmd" => {
479                    let child_cmd = parse_cmd(child_node)?;
480                    cmd.cmds.push(Box::new(child_cmd));
481                }
482                _ => {}
483            }
484        }
485    }
486    Ok(cmd)
487}
488
489pub fn parse_complete(node: &KdlNode) -> Result<Complete, UError> {
490    if node.name().value() != "complete" {
491        return Err(UError::InvalidNodeName(io::Error::new(
492            io::ErrorKind::InvalidInput,
493            format!("Node name wasn't complete!\n{:?}", node),
494        )));
495    }
496
497    let mut complete = Complete::default();
498    for (index, entry) in node.entries().iter().enumerate() {
499        if index == 0 {
500            let entry_complete_name = entry
501                .value()
502                .as_string()
503                .ok_or_else(|| {
504                    UError::InvalidNodeFirstArg(io::Error::new(
505                        io::ErrorKind::NotFound,
506                        format!("No complete found in {:?}", entry),
507                    ))
508                })?
509                .to_string();
510            complete.name = entry_complete_name;
511        }
512
513        if let Some(iden_name) = entry.name() {
514            match iden_name.value() {
515                "descriptions" => complete.descs = entry.value().as_bool().unwrap_or_default(),
516                "run" => {
517                    let run = entry
518                        .value()
519                        .as_string()
520                        .map(String::from)
521                        .unwrap_or_default();
522                    complete.kind = CompleteKind::Run(run);
523                }
524                "type" => {
525                    let arg_type = entry.value().as_string().unwrap_or_default();
526                    if arg_type == "file" {
527                        complete.kind = CompleteKind::File;
528                    }
529                }
530                _ => {}
531            }
532        }
533    }
534    Ok(complete)
535}
536
537pub fn parse_usage(node: &KdlNode) -> Result<Option<Usage>, UError> {
538    match node.name().value() {
539        "flag" => Ok(Some(Usage::Flag(parse_flag(node)?))),
540        "arg" => Ok(Some(Usage::Arg(parse_arg(node)?))),
541        "cmd" => Ok(Some(Usage::Cmd(parse_cmd(node)?))),
542        "complete" => {
543            let complete = parse_complete(node)?;
544            if !complete.kind.is_none() {
545                Ok(Some(Usage::Complete(complete)))
546            } else {
547                Ok(None)
548            }
549        }
550        _ => Ok(None),
551    }
552}
553
554impl Complete {
555    pub fn file_complete() -> Self {
556        Self {
557            name: "file".to_string(),
558            kind: CompleteKind::File,
559            descs: false,
560        }
561    }
562
563    pub fn dir_complete() -> Self {
564        Self {
565            name: "file".to_string(),
566            kind: CompleteKind::Dir,
567            descs: false,
568        }
569    }
570}
571
572impl PartialEq for Flag {
573    fn eq(&self, other: &Self) -> bool {
574        self.name == other.name && self.names.len() == other.names.len() && {
575            let a: HashSet<_> = self.names.iter().collect();
576            let b: HashSet<_> = other.names.iter().collect();
577            a == b
578        }
579    }
580}
581impl Eq for Flag {}
582
583impl PartialEq for Arg {
584    fn eq(&self, other: &Self) -> bool {
585        self.name == other.name
586    }
587}
588impl Eq for Arg {}
589
590impl PartialEq for Cmd {
591    fn eq(&self, other: &Self) -> bool {
592        self.name == other.name
593    }
594}
595impl Eq for Cmd {}
596
597impl PartialEq for Complete {
598    fn eq(&self, other: &Self) -> bool {
599        self.name == other.name
600    }
601}
602impl Eq for Complete {}
603
604impl CompleteKind {
605    pub fn is_none(&self) -> bool {
606        matches!(self, Self::None)
607    }
608
609    pub fn is_file(&self) -> bool {
610        matches!(self, Self::File)
611    }
612
613    pub fn run(&self) -> Option<&String> {
614        match self {
615            Self::Run(run) => Some(run),
616            _ => None,
617        }
618    }
619}
620
621#[derive(Debug)]
622pub enum UError {
623    InvalidNodeName(io::Error),
624    InvalidNodeFirstArg(io::Error),
625}
626
627impl std::fmt::Display for UError {
628    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629        match self {
630            UError::InvalidNodeName(error) => error.fmt(f),
631            UError::InvalidNodeFirstArg(error) => error.fmt(f),
632        }
633    }
634}
635
636impl std::error::Error for UError {}
637
638impl From<UError> for io::Error {
639    fn from(value: UError) -> Self {
640        match value {
641            UError::InvalidNodeName(error) => error,
642            UError::InvalidNodeFirstArg(error) => error,
643        }
644    }
645}
646
647impl AsRef<Cmd> for Cmd {
648    fn as_ref(&self) -> &Cmd {
649        self
650    }
651}
652
653impl From<bool> for GlobalFlag {
654    fn from(value: bool) -> Self {
655        match value {
656            true => Self::Itself,
657            false => Self::None,
658        }
659    }
660}
661
662impl Flag {
663    pub fn is_global(&self) -> bool {
664        !matches!(self.global, GlobalFlag::None)
665    }
666
667    pub fn is_global_itself(&self) -> bool {
668        matches!(self.global, GlobalFlag::Itself)
669    }
670
671    pub fn is_global_imposed(&self) -> bool {
672        matches!(self.global, GlobalFlag::Imposed(_))
673    }
674}