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