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)]
131pub enum CompleteKind {
132    None,
133    File,
134    Dir,
135    Run(String),
136}
137
138pub fn parse_name(node: &KdlNode) -> Result<String, UError> {
139    if node.name().value() != "name" {
140        return Err(UError::InvalidNodeName(io::Error::new(
141            io::ErrorKind::InvalidInput,
142            format!("Node name wasn't name!\n{:?}", node),
143        )));
144    }
145    let name = node
146        .get(0)
147        .map(|v| v.as_string().unwrap_or_default().to_string())
148        .ok_or_else(|| {
149            UError::InvalidNodeFirstArg(io::Error::new(
150                io::ErrorKind::NotFound,
151                format!("No name found in {:?}", node),
152            ))
153        })?;
154    Ok(name)
155}
156
157pub fn parse_bin(node: &KdlNode) -> Result<String, UError> {
158    if node.name().value() != "bin" {
159        return Err(UError::InvalidNodeName(io::Error::new(
160            io::ErrorKind::InvalidInput,
161            format!("Node name wasn't bin!\n{:?}", node),
162        )));
163    }
164    let bin = node
165        .get(0)
166        .map(|v| v.as_string().unwrap_or_default().to_string())
167        .ok_or_else(|| {
168            UError::InvalidNodeFirstArg(io::Error::new(
169                io::ErrorKind::NotFound,
170                format!("No bin found in {:?}", node),
171            ))
172        })?;
173    Ok(bin)
174}
175
176pub fn parse_include(node: &KdlNode) -> Result<String, UError> {
177    if node.name().value() != "include" {
178        return Err(UError::InvalidNodeName(io::Error::new(
179            io::ErrorKind::InvalidInput,
180            format!("Node name wasn't include!\n{:?}", node),
181        )));
182    }
183    let include = node
184        .get(0)
185        .map(|v| v.as_string().unwrap_or_default().to_string())
186        .ok_or_else(|| {
187            UError::InvalidNodeFirstArg(io::Error::new(
188                io::ErrorKind::NotFound,
189                format!("No include found in {:?}", node),
190            ))
191        })?;
192    Ok(include)
193}
194
195pub fn parse_alias(node: &KdlNode) -> Result<Vec<Alias>, UError> {
196    if node.name().value() != "alias" {
197        return Err(UError::InvalidNodeName(io::Error::new(
198            io::ErrorKind::InvalidInput,
199            format!("Node name wasn't alias!\n{:?}", node),
200        )));
201    }
202
203    let mut aliases: Vec<Alias> = vec![];
204    for entry in node.entries() {
205        let mut hide = false;
206        if entry.name().is_none() {
207            let alias_name = entry
208                .value()
209                .as_string()
210                .ok_or_else(|| {
211                    UError::InvalidNodeFirstArg(io::Error::new(
212                        io::ErrorKind::NotFound,
213                        format!("No alias found in {:?}", entry),
214                    ))
215                })?
216                .to_string();
217            if let Some(hide_val) = node.get("hide") {
218                hide = hide_val.as_bool().unwrap_or_default();
219            }
220            let alias = Alias {
221                name: alias_name,
222                hide,
223            };
224            aliases.push(alias);
225        }
226    }
227    Ok(aliases)
228}
229
230pub fn parse_choices(node: &KdlNode) -> Result<Vec<String>, UError> {
231    if node.name().value() != "choices" {
232        return Err(UError::InvalidNodeName(io::Error::new(
233            io::ErrorKind::InvalidInput,
234            format!("Node name wasn't choices!\n{:?}", node),
235        )));
236    }
237
238    let mut choices: Vec<String> = vec![];
239    for entry in node.entries() {
240        let choice = entry
241            .value()
242            .as_string()
243            .ok_or_else(|| {
244                UError::InvalidNodeFirstArg(io::Error::new(
245                    io::ErrorKind::NotFound,
246                    format!("No choice found in {:?}", entry),
247                ))
248            })?
249            .to_string();
250        choices.push(choice);
251    }
252    Ok(choices)
253}
254
255pub fn parse_flag(node: &KdlNode) -> Result<Flag, UError> {
256    if node.name().value() != "flag" {
257        return Err(UError::InvalidNodeName(io::Error::new(
258            io::ErrorKind::InvalidInput,
259            format!("Node name wasn't flag!\n{:?}", node),
260        )));
261    }
262
263    let mut flag = Flag::default();
264    for (index, entry) in node.entries().iter().enumerate() {
265        if index == 0 {
266            let entry_flag_names = entry
267                .value()
268                .as_string()
269                .ok_or_else(|| {
270                    UError::InvalidNodeFirstArg(io::Error::new(
271                        io::ErrorKind::NotFound,
272                        format!("No flag found in {:?}", entry),
273                    ))
274                })?
275                .to_string();
276
277            // the longest flag name is set as an identifier to flag.name
278            let (long_flag_index, flag_names) = {
279                let mut name_len = 0;
280                let mut flag_index = 0;
281                let mut long_flag_index = flag_index;
282                let flag_names: Vec<String> = entry_flag_names
283                    .split_whitespace()
284                    .map(|s| {
285                        let s = String::from(s);
286                        let len = s.len();
287                        if len > name_len {
288                            name_len = len;
289                            long_flag_index = flag_index;
290                        };
291                        flag_index += 1;
292                        s
293                    })
294                    .collect();
295                (long_flag_index, flag_names)
296            };
297
298            let slugify = |mut c: char| {
299                if !c.is_alphanumeric() && c != '_' {
300                    c = '_';
301                }
302                c
303            };
304
305            let flag_name = flag_names[long_flag_index]
306                .trim_matches('-')
307                .chars()
308                .map(slugify)
309                .collect();
310
311            flag.name = flag_name;
312            flag.names = flag_names;
313        }
314
315        if let Some(iden_name) = entry.name() {
316            match iden_name.value() {
317                "help" => flag.help = entry.value().as_string().unwrap_or_default().to_string(),
318                "hide" => flag.hide = entry.value().as_bool().unwrap_or_default(),
319                "global" => flag.global = entry.value().as_bool().unwrap_or_default().into(),
320                "negate" => {
321                    let negate_flag = entry.value().as_string().unwrap_or_default().to_string();
322                    if !negate_flag.is_empty() {
323                        flag.names.push(negate_flag);
324                    }
325                }
326                _ => {}
327            }
328        }
329    }
330
331    if let Some(child_doc) = node.children() {
332        for child_node in child_doc.nodes() {
333            match child_node.name().value() {
334                "arg" => flag.arg = Some(parse_arg(child_node)?),
335                "alias" => flag.aliases = parse_alias(child_node)?,
336                "choices" => {
337                    if let Some(arg_name) = flag.names.pop() {
338                        let mut arg = Arg::default();
339                        arg.name = arg_name;
340                        arg.choices = parse_choices(child_node)?;
341                        if arg.name.starts_with("<") {
342                            arg.required = true;
343                        }
344                        flag.arg = Some(arg);
345                    }
346                }
347                _ => {}
348            }
349        }
350    }
351    Ok(flag)
352}
353
354pub fn parse_arg(node: &KdlNode) -> Result<Arg, UError> {
355    if node.name().value() != "arg" {
356        return Err(UError::InvalidNodeName(io::Error::new(
357            io::ErrorKind::InvalidInput,
358            format!("Node name wasn't arg!\n{:?}", node),
359        )));
360    }
361
362    let mut arg = Arg::default();
363    for (index, entry) in node.entries().iter().enumerate() {
364        if index == 0 {
365            let entry_arg_name = entry
366                .value()
367                .as_string()
368                .ok_or_else(|| {
369                    UError::InvalidNodeFirstArg(io::Error::new(
370                        io::ErrorKind::NotFound,
371                        format!("No arg found in {:?}", entry),
372                    ))
373                })?
374                .to_string();
375
376            if entry_arg_name.starts_with("<") {
377                arg.required = true;
378                let end = entry_arg_name.find(">").unwrap_or(entry_arg_name.len());
379                arg.name = entry_arg_name[1..end].to_string();
380            } else if entry_arg_name.starts_with("[") {
381                arg.required = false;
382                let end = entry_arg_name.find("]").unwrap_or(entry_arg_name.len());
383                arg.name = entry_arg_name[1..end].to_string();
384            }
385            arg.repr = entry_arg_name;
386        }
387
388        if let Some(iden_name) = entry.name() {
389            match iden_name.value() {
390                "hide" => arg.hide = entry.value().as_bool().unwrap_or_default(),
391                "default" => arg.default = entry.value().as_string().map(String::from),
392                "var" => arg.var = entry.value().as_bool().unwrap_or_default(),
393                "var_max" => arg.max = entry.value().as_integer(),
394                "var_min" => arg.min = entry.value().as_integer(),
395                _ => {}
396            }
397        }
398    }
399
400    arg.max = arg.max.or(Some(-1));
401    arg.min = arg.min.or(Some(0));
402
403    if let Some(child_doc) = node.children() {
404        for child_node in child_doc.nodes() {
405            if child_node.name().value() == "choices" {
406                let mut choices: Vec<String> = vec![];
407                for cn_entry in child_node.entries() {
408                    let choice = cn_entry
409                        .value()
410                        .as_string()
411                        .expect(format!("No choice found in {:?}", cn_entry).as_str())
412                        .to_string();
413                    choices.push(choice);
414                }
415                arg.choices = choices;
416            }
417        }
418    }
419    Ok(arg)
420}
421
422pub fn parse_cmd(node: &KdlNode) -> Result<Cmd, UError> {
423    if node.name().value() != "cmd" {
424        return Err(UError::InvalidNodeName(io::Error::new(
425            io::ErrorKind::InvalidInput,
426            format!("Node name wasn't cmd!\n{:?}", node),
427        )));
428    }
429
430    let mut cmd = Cmd::default();
431    for (index, entry) in node.entries().iter().enumerate() {
432        if index == 0 {
433            let entry_cmd_name = entry
434                .value()
435                .as_string()
436                .ok_or_else(|| {
437                    UError::InvalidNodeFirstArg(io::Error::new(
438                        io::ErrorKind::NotFound,
439                        format!("No cmd found in {:?}", entry),
440                    ))
441                })?
442                .to_string();
443
444            cmd.name = entry_cmd_name;
445        }
446
447        if let Some(iden_name) = entry.name() {
448            match iden_name.value() {
449                "help" => {
450                    cmd.help = entry
451                        .value()
452                        .as_string()
453                        .map(String::from)
454                        .unwrap_or_default()
455                }
456                "hide" => cmd.hide = entry.value().as_bool().unwrap_or_default(),
457                _ => {}
458            }
459        }
460    }
461
462    if let Some(child_doc) = node.children() {
463        for child_node in child_doc.nodes() {
464            match child_node.name().value() {
465                "alias" => {
466                    let mut alias = parse_alias(child_node)?;
467                    cmd.aliases.append(&mut alias);
468                }
469                "flag" => {
470                    let flag = parse_flag(child_node)?;
471                    cmd.flags.push(flag);
472                }
473                "arg" => {
474                    let arg = parse_arg(child_node)?;
475                    cmd.args.push(arg);
476                }
477                "cmd" => {
478                    let child_cmd = parse_cmd(child_node)?;
479                    cmd.cmds.push(Box::new(child_cmd));
480                }
481                _ => {}
482            }
483        }
484    }
485    Ok(cmd)
486}
487
488pub fn parse_complete(node: &KdlNode) -> Result<Complete, UError> {
489    if node.name().value() != "complete" {
490        return Err(UError::InvalidNodeName(io::Error::new(
491            io::ErrorKind::InvalidInput,
492            format!("Node name wasn't complete!\n{:?}", node),
493        )));
494    }
495
496    let mut complete = Complete::default();
497    for (index, entry) in node.entries().iter().enumerate() {
498        if index == 0 {
499            let entry_complete_name = entry
500                .value()
501                .as_string()
502                .ok_or_else(|| {
503                    UError::InvalidNodeFirstArg(io::Error::new(
504                        io::ErrorKind::NotFound,
505                        format!("No complete found in {:?}", entry),
506                    ))
507                })?
508                .to_string();
509            complete.name = entry_complete_name;
510        }
511
512        if let Some(iden_name) = entry.name() {
513            match iden_name.value() {
514                "descriptions" => complete.descs = entry.value().as_bool().unwrap_or_default(),
515                "run" => {
516                    let run = entry
517                        .value()
518                        .as_string()
519                        .map(String::from)
520                        .unwrap_or_default();
521                    complete.kind = CompleteKind::Run(run);
522                }
523                "type" => {
524                    let arg_type = entry.value().as_string().unwrap_or_default();
525                    match arg_type {
526                        "file" => complete.kind = CompleteKind::File,
527                        _ => {}
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        match self {
607            Self::None => true,
608            _ => false,
609        }
610    }
611
612    pub fn is_file(&self) -> bool {
613        match self {
614            Self::File => true,
615            _ => false,
616        }
617    }
618
619    pub fn run(&self) -> Option<&String> {
620        match self {
621            Self::Run(run) => Some(run),
622            _ => None,
623        }
624    }
625}
626
627#[derive(Debug)]
628pub enum UError {
629    InvalidNodeName(io::Error),
630    InvalidNodeFirstArg(io::Error),
631}
632
633impl std::fmt::Display for UError {
634    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635        match self {
636            UError::InvalidNodeName(error) => error.fmt(f),
637            UError::InvalidNodeFirstArg(error) => error.fmt(f),
638        }
639    }
640}
641
642impl std::error::Error for UError {}
643
644impl From<UError> for io::Error {
645    fn from(value: UError) -> Self {
646        match value {
647            UError::InvalidNodeName(error) => error,
648            UError::InvalidNodeFirstArg(error) => error,
649        }
650    }
651}
652
653impl AsRef<Cmd> for Cmd {
654    fn as_ref(&self) -> &Cmd {
655        self
656    }
657}
658
659impl Default for CompleteKind {
660    fn default() -> Self {
661        Self::None
662    }
663}
664
665impl From<bool> for GlobalFlag {
666    fn from(value: bool) -> Self {
667        match value {
668            true => Self::Itself,
669            false => Self::None,
670        }
671    }
672}
673
674impl Flag {
675    pub fn is_global(&self) -> bool {
676        match self.global {
677            GlobalFlag::None => false,
678            _ => true,
679        }
680    }
681
682    pub fn is_global_itself(&self) -> bool {
683        match self.global {
684            GlobalFlag::Itself => true,
685            _ => false,
686        }
687    }
688
689    pub fn is_global_imposed(&self) -> bool {
690        match self.global {
691            GlobalFlag::Imposed(_) => true,
692            _ => false,
693        }
694    }
695}