cuc-lib 0.1.1

Library for working with usage spec and cuc-cli.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use kdl::KdlNode;
use std::{
    collections::{HashMap, HashSet},
    io,
};

use crate::namespace::NameSpace;

#[derive(Debug, Default, Clone)]
pub struct UsageSpec {
    pub info: Info,
    pub flags: Vec<Flag>,
    pub args: Vec<Arg>,
    pub cmds: Vec<Cmd>,
    pub completes: HashMap<String, Complete>,
}

#[derive(Debug, Default, Clone)]
pub struct Info {
    pub name: String,
    pub bin: String,
}

#[derive(Debug, Clone)]
pub enum Usage {
    Flag(Flag),
    Arg(Arg),
    Cmd(Cmd),
    Complete(Complete),
}

#[derive(Debug, Default, Clone)]
pub struct Alias {
    pub name: String,
    pub hide: bool,
}

#[derive(Debug, Default, Clone)]
pub enum GlobalFlag {
    #[default]
    None,
    Itself,
    Imposed(NameSpace),
}

#[derive(Debug, Default, Clone)]
pub struct Flag {
    pub name: String,
    pub names: Vec<String>,
    pub help: String,
    pub hide: bool,
    pub global: GlobalFlag,
    pub aliases: Vec<Alias>,
    pub arg: Option<Arg>,
}

#[derive(Debug, Default, Clone)]
pub struct Arg {
    pub name: String,
    pub repr: String,
    pub required: bool,
    pub choices: Vec<String>,
    pub hide: bool,
    pub var: bool,
    pub min: Option<i128>,
    pub max: Option<i128>,
    pub default: Option<String>,
}

#[derive(Debug, Default, Clone)]
pub struct Cmd {
    pub name: String,
    pub help: String,
    pub hide: bool,
    pub args: Vec<Arg>,
    pub flags: Vec<Flag>,
    pub aliases: Vec<Alias>,
    pub cmds: Vec<Box<Cmd>>,
}

#[derive(Debug, Default, Clone)]
pub struct Complete {
    pub name: String,
    pub kind: CompleteKind,
    pub descs: bool,
}

#[derive(Debug, Clone)]
pub enum CompleteKind {
    None,
    File,
    Dir,
    Run(String),
}

pub fn parse_name(node: &KdlNode) -> Result<String, UError> {
    if node.name().value() != "name" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't name!\n{:?}", node),
        )));
    }
    let name = node
        .get(0)
        .map(|v| v.as_string().unwrap_or_default().to_string())
        .ok_or_else(|| {
            UError::InvalidNodeFirstArg(io::Error::new(
                io::ErrorKind::NotFound,
                format!("No name found in {:?}", node),
            ))
        })?;
    Ok(name)
}

pub fn parse_bin(node: &KdlNode) -> Result<String, UError> {
    if node.name().value() != "bin" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't bin!\n{:?}", node),
        )));
    }
    let bin = node
        .get(0)
        .map(|v| v.as_string().unwrap_or_default().to_string())
        .ok_or_else(|| {
            UError::InvalidNodeFirstArg(io::Error::new(
                io::ErrorKind::NotFound,
                format!("No bin found in {:?}", node),
            ))
        })?;
    Ok(bin)
}

pub fn parse_include(node: &KdlNode) -> Result<String, UError> {
    if node.name().value() != "include" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't include!\n{:?}", node),
        )));
    }
    let include = node
        .get(0)
        .map(|v| v.as_string().unwrap_or_default().to_string())
        .ok_or_else(|| {
            UError::InvalidNodeFirstArg(io::Error::new(
                io::ErrorKind::NotFound,
                format!("No include found in {:?}", node),
            ))
        })?;
    Ok(include)
}

pub fn parse_alias(node: &KdlNode) -> Result<Vec<Alias>, UError> {
    if node.name().value() != "alias" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't alias!\n{:?}", node),
        )));
    }

    let mut aliases: Vec<Alias> = vec![];
    for entry in node.entries() {
        let mut hide = false;
        if entry.name().is_none() {
            let alias_name = entry
                .value()
                .as_string()
                .ok_or_else(|| {
                    UError::InvalidNodeFirstArg(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No alias found in {:?}", entry),
                    ))
                })?
                .to_string();
            if let Some(hide_val) = node.get("hide") {
                hide = hide_val.as_bool().unwrap_or_default();
            }
            let alias = Alias {
                name: alias_name,
                hide,
            };
            aliases.push(alias);
        }
    }
    Ok(aliases)
}

pub fn parse_choices(node: &KdlNode) -> Result<Vec<String>, UError> {
    if node.name().value() != "choices" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't choices!\n{:?}", node),
        )));
    }

    let mut choices: Vec<String> = vec![];
    for entry in node.entries() {
        let choice = entry
            .value()
            .as_string()
            .ok_or_else(|| {
                UError::InvalidNodeFirstArg(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("No choice found in {:?}", entry),
                ))
            })?
            .to_string();
        choices.push(choice);
    }
    Ok(choices)
}

pub fn parse_flag(node: &KdlNode) -> Result<Flag, UError> {
    if node.name().value() != "flag" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't flag!\n{:?}", node),
        )));
    }

    let mut flag = Flag::default();
    for (index, entry) in node.entries().iter().enumerate() {
        if index == 0 {
            let entry_flag_names = entry
                .value()
                .as_string()
                .ok_or_else(|| {
                    UError::InvalidNodeFirstArg(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No flag found in {:?}", entry),
                    ))
                })?
                .to_string();

            // the longest flag name is set as an identifier to flag.name
            let (long_flag_index, flag_names) = {
                let mut name_len = 0;
                let mut flag_index = 0;
                let mut long_flag_index = flag_index;
                let flag_names: Vec<String> = entry_flag_names
                    .split_whitespace()
                    .map(|s| {
                        let s = String::from(s);
                        let len = s.len();
                        if len > name_len {
                            name_len = len;
                            long_flag_index = flag_index;
                        };
                        flag_index += 1;
                        s
                    })
                    .collect();
                (long_flag_index, flag_names)
            };

            let slugify = |mut c: char| {
                if !c.is_alphanumeric() && c != '_' {
                    c = '_';
                }
                c
            };

            let flag_name = flag_names[long_flag_index]
                .trim_matches('-')
                .chars()
                .map(slugify)
                .collect();

            flag.name = flag_name;
            flag.names = flag_names;
        }

        if let Some(iden_name) = entry.name() {
            match iden_name.value() {
                "help" => flag.help = entry.value().as_string().unwrap_or_default().to_string(),
                "hide" => flag.hide = entry.value().as_bool().unwrap_or_default(),
                "global" => flag.global = entry.value().as_bool().unwrap_or_default().into(),
                "negate" => {
                    let negate_flag = entry.value().as_string().unwrap_or_default().to_string();
                    if !negate_flag.is_empty() {
                        flag.names.push(negate_flag);
                    }
                }
                _ => {}
            }
        }
    }

    if let Some(child_doc) = node.children() {
        for child_node in child_doc.nodes() {
            match child_node.name().value() {
                "arg" => flag.arg = Some(parse_arg(child_node)?),
                "alias" => flag.aliases = parse_alias(child_node)?,
                "choices" => {
                    if let Some(arg_name) = flag.names.pop() {
                        let mut arg = Arg::default();
                        arg.name = arg_name;
                        arg.choices = parse_choices(child_node)?;
                        if arg.name.starts_with("<") {
                            arg.required = true;
                        }
                        flag.arg = Some(arg);
                    }
                }
                _ => {}
            }
        }
    }
    Ok(flag)
}

pub fn parse_arg(node: &KdlNode) -> Result<Arg, UError> {
    if node.name().value() != "arg" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't arg!\n{:?}", node),
        )));
    }

    let mut arg = Arg::default();
    for (index, entry) in node.entries().iter().enumerate() {
        if index == 0 {
            let entry_arg_name = entry
                .value()
                .as_string()
                .ok_or_else(|| {
                    UError::InvalidNodeFirstArg(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No arg found in {:?}", entry),
                    ))
                })?
                .to_string();

            if entry_arg_name.starts_with("<") {
                arg.required = true;
                let end = entry_arg_name.find(">").unwrap_or(entry_arg_name.len());
                arg.name = entry_arg_name[1..end].to_string();
            } else if entry_arg_name.starts_with("[") {
                arg.required = false;
                let end = entry_arg_name.find("]").unwrap_or(entry_arg_name.len());
                arg.name = entry_arg_name[1..end].to_string();
            }
            arg.repr = entry_arg_name;
        }

        if let Some(iden_name) = entry.name() {
            match iden_name.value() {
                "hide" => arg.hide = entry.value().as_bool().unwrap_or_default(),
                "default" => arg.default = entry.value().as_string().map(String::from),
                "var" => arg.var = entry.value().as_bool().unwrap_or_default(),
                "var_max" => arg.max = entry.value().as_integer(),
                "var_min" => arg.min = entry.value().as_integer(),
                _ => {}
            }
        }
    }

    arg.max = arg.max.or(Some(-1));
    arg.min = arg.min.or(Some(0));

    if let Some(child_doc) = node.children() {
        for child_node in child_doc.nodes() {
            if child_node.name().value() == "choices" {
                let mut choices: Vec<String> = vec![];
                for cn_entry in child_node.entries() {
                    let choice = cn_entry
                        .value()
                        .as_string()
                        .expect(format!("No choice found in {:?}", cn_entry).as_str())
                        .to_string();
                    choices.push(choice);
                }
                arg.choices = choices;
            }
        }
    }
    Ok(arg)
}

pub fn parse_cmd(node: &KdlNode) -> Result<Cmd, UError> {
    if node.name().value() != "cmd" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't cmd!\n{:?}", node),
        )));
    }

    let mut cmd = Cmd::default();
    for (index, entry) in node.entries().iter().enumerate() {
        if index == 0 {
            let entry_cmd_name = entry
                .value()
                .as_string()
                .ok_or_else(|| {
                    UError::InvalidNodeFirstArg(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No cmd found in {:?}", entry),
                    ))
                })?
                .to_string();

            cmd.name = entry_cmd_name;
        }

        if let Some(iden_name) = entry.name() {
            match iden_name.value() {
                "help" => {
                    cmd.help = entry
                        .value()
                        .as_string()
                        .map(String::from)
                        .unwrap_or_default()
                }
                "hide" => cmd.hide = entry.value().as_bool().unwrap_or_default(),
                _ => {}
            }
        }
    }

    if let Some(child_doc) = node.children() {
        for child_node in child_doc.nodes() {
            match child_node.name().value() {
                "alias" => {
                    let mut alias = parse_alias(child_node)?;
                    cmd.aliases.append(&mut alias);
                }
                "flag" => {
                    let flag = parse_flag(child_node)?;
                    cmd.flags.push(flag);
                }
                "arg" => {
                    let arg = parse_arg(child_node)?;
                    cmd.args.push(arg);
                }
                "cmd" => {
                    let child_cmd = parse_cmd(child_node)?;
                    cmd.cmds.push(Box::new(child_cmd));
                }
                _ => {}
            }
        }
    }
    Ok(cmd)
}

pub fn parse_complete(node: &KdlNode) -> Result<Complete, UError> {
    if node.name().value() != "complete" {
        return Err(UError::InvalidNodeName(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Node name wasn't complete!\n{:?}", node),
        )));
    }

    let mut complete = Complete::default();
    for (index, entry) in node.entries().iter().enumerate() {
        if index == 0 {
            let entry_complete_name = entry
                .value()
                .as_string()
                .ok_or_else(|| {
                    UError::InvalidNodeFirstArg(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("No complete found in {:?}", entry),
                    ))
                })?
                .to_string();
            complete.name = entry_complete_name;
        }

        if let Some(iden_name) = entry.name() {
            match iden_name.value() {
                "descriptions" => complete.descs = entry.value().as_bool().unwrap_or_default(),
                "run" => {
                    let run = entry
                        .value()
                        .as_string()
                        .map(String::from)
                        .unwrap_or_default();
                    complete.kind = CompleteKind::Run(run);
                }
                "type" => {
                    let arg_type = entry.value().as_string().unwrap_or_default();
                    match arg_type {
                        "file" => complete.kind = CompleteKind::File,
                        _ => {}
                    }
                }
                _ => {}
            }
        }
    }
    Ok(complete)
}

pub fn parse_usage(node: &KdlNode) -> Result<Option<Usage>, UError> {
    match node.name().value() {
        "flag" => Ok(Some(Usage::Flag(parse_flag(node)?))),
        "arg" => Ok(Some(Usage::Arg(parse_arg(node)?))),
        "cmd" => Ok(Some(Usage::Cmd(parse_cmd(node)?))),
        "complete" => {
            let complete = parse_complete(node)?;
            if !complete.kind.is_none() {
                Ok(Some(Usage::Complete(complete)))
            } else {
                Ok(None)
            }
        }
        _ => Ok(None),
    }
}

impl Complete {
    pub fn file_complete() -> Self {
        Self {
            name: "file".to_string(),
            kind: CompleteKind::File,
            descs: false,
        }
    }

    pub fn dir_complete() -> Self {
        Self {
            name: "file".to_string(),
            kind: CompleteKind::Dir,
            descs: false,
        }
    }
}

impl PartialEq for Flag {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.names.len() == other.names.len() && {
            let a: HashSet<_> = self.names.iter().collect();
            let b: HashSet<_> = other.names.iter().collect();
            a == b
        }
    }
}
impl Eq for Flag {}

impl PartialEq for Arg {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}
impl Eq for Arg {}

impl PartialEq for Cmd {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}
impl Eq for Cmd {}

impl PartialEq for Complete {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}
impl Eq for Complete {}

impl CompleteKind {
    pub fn is_none(&self) -> bool {
        match self {
            Self::None => true,
            _ => false,
        }
    }

    pub fn is_file(&self) -> bool {
        match self {
            Self::File => true,
            _ => false,
        }
    }

    pub fn run(&self) -> Option<&String> {
        match self {
            Self::Run(run) => Some(run),
            _ => None,
        }
    }
}

#[derive(Debug)]
pub enum UError {
    InvalidNodeName(io::Error),
    InvalidNodeFirstArg(io::Error),
}

impl std::fmt::Display for UError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UError::InvalidNodeName(error) => error.fmt(f),
            UError::InvalidNodeFirstArg(error) => error.fmt(f),
        }
    }
}

impl std::error::Error for UError {}

impl From<UError> for io::Error {
    fn from(value: UError) -> Self {
        match value {
            UError::InvalidNodeName(error) => error,
            UError::InvalidNodeFirstArg(error) => error,
        }
    }
}

impl AsRef<Cmd> for Cmd {
    fn as_ref(&self) -> &Cmd {
        self
    }
}

impl Default for CompleteKind {
    fn default() -> Self {
        Self::None
    }
}

impl From<bool> for GlobalFlag {
    fn from(value: bool) -> Self {
        match value {
            true => Self::Itself,
            false => Self::None,
        }
    }
}

impl Flag {
    pub fn is_global(&self) -> bool {
        match self.global {
            GlobalFlag::None => false,
            _ => true,
        }
    }

    pub fn is_global_itself(&self) -> bool {
        match self.global {
            GlobalFlag::Itself => true,
            _ => false,
        }
    }

    pub fn is_global_imposed(&self) -> bool {
        match self.global {
            GlobalFlag::Imposed(_) => true,
            _ => false,
        }
    }
}