usage-cli 6.12.0

CLI for working with usage-based CLIs
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
use std::path::PathBuf;
use std::vec;

use indexmap::IndexMap;
use itertools::Itertools;
use usage::{SpecArg, SpecCommand, SpecComplete, SpecFlag};
use usage_rs::Args;

use crate::cli::generate;
use serde::{Deserialize, Serialize, Serializer};
use serde_with::{OneOrMany, serde_as};

fn is_false(value: &bool) -> bool {
    !*value
}

mod description_format {
    use serde::{self, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(description: &Option<String>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s: &str = match description.as_ref() {
            Some(s) => s,
            None => return serializer.serialize_str(""),
        };
        if s.is_empty() {
            return serializer.serialize_str("");
        }
        let mut v: Vec<char> = s.chars().collect();
        if let Some(first_upper) = v[0].to_uppercase().next() {
            v[0] = first_upper;
        }
        serializer.serialize_str(v.iter().collect::<String>().as_str())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(Some(s))
    }
}

/// Generate a completion spec in the legacy Fig format
#[derive(Args)]
#[usage(effect = "read")]
pub struct Fig {
    /// A usage spec file, or a script with a usage shebang; "-" reads stdin
    #[usage(short, long)]
    file: Option<PathBuf>,

    /// Where to write the spec, or "-" for stdout (default)
    #[usage(
        long,
        value_hint = usage_rs::ValueHint::FilePath,
        effect = "write"
    )]
    out_file: Option<PathBuf>,

    /// The spec itself, as a string, instead of a file
    #[usage(long, required_unless = "--file", overrides = "--file")]
    spec: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
enum GeneratorType {
    EnvVar,
    Complete,
}

#[derive(Deserialize, Clone)]
struct FigGenerator {
    type_: GeneratorType,
    post_process: String,
    template_str: String,
}

impl Serialize for FigGenerator {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.template_str)
    }
}

#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
struct FigArg {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "description_format")]
    description: Option<String>,
    #[serde(skip_serializing_if = "is_false")]
    is_optional: bool,
    #[serde(skip_serializing_if = "is_false")]
    is_variadic: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    template: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    generators: Option<FigGenerator>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    suggestions: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    debounce: Option<bool>,
    /// Whether a `complete` declaration has been applied to this argument, as opposed to
    /// the template and generator inferred from its name. Not part of a Fig spec — it
    /// only decides which declaration wins while one is being built.
    #[serde(skip)]
    declared: bool,
    /// Whether the argument declares `choices`. `usage complete-word` answers from them and
    /// never runs a `complete run=` for such an argument, so neither does Fig. Not part of a
    /// Fig spec.
    #[serde(skip)]
    has_choices: bool,
}

#[serde_as]
#[derive(Serialize, Deserialize, Clone)]
struct FigOption {
    #[serde_as(as = "OneOrMany<_>")]
    name: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "description_format")]
    description: Option<String>,
    #[serde(rename(serialize = "isRepeatable"))]
    is_repeatable: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    args: Option<FigArg>,
}

#[serde_as]
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
struct FigCommand {
    #[serde_as(as = "OneOrMany<_>")]
    name: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    subcommands: Vec<FigCommand>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    options: Vec<FigOption>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde_as(as = "OneOrMany<_>")]
    args: Vec<FigArg>,

    #[serde(skip_serializing_if = "Option::is_none")]
    generate_spec: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cache: Option<bool>,
}

impl FigGenerator {
    pub fn create_simple_generator(type_: GeneratorType) -> Self {
        Self {
            type_: type_.clone(),
            template_str: FigGenerator::get_generator_name(type_).to_uppercase(),
            post_process: "".to_string(),
        }
    }

    fn get_generator_name(type_: GeneratorType) -> String {
        match type_.clone() {
            GeneratorType::EnvVar => "envVarGenerator".to_string(),
            GeneratorType::Complete => "completionGeneratorTemplate".to_string(),
        }
    }

    fn get_generator_arg(&self) -> String {
        match self.type_ {
            GeneratorType::Complete => {
                format!("(`{}`)", escape_template_literal(&self.post_process))
            }
            _ => "".to_string(),
        }
    }

    pub fn get_generator_text(&self) -> String {
        let generator_name = FigGenerator::get_generator_name(self.type_.clone());
        let arg = self.get_generator_arg();

        format!("{generator_name}{arg}")
    }
}

/// A `run=` command as the body of a JavaScript template literal.
///
/// Shell commands are full of what a template literal treats as syntax: `${HOME}` would be
/// interpolated by JavaScript before the shell ever saw it, a backtick ends the literal, and a
/// backslash starts an escape. Each is escaped so the command reaches Fig as written.
fn escape_template_literal(command: &str) -> String {
    command
        .replace('\\', "\\\\")
        .replace('`', "\\`")
        .replace("${", "\\${")
}

/// The Fig template for a portable `complete … type=`, where there is one.
///
/// `executable` is filesystem completion in Fig's vocabulary too; the narrower kinds
/// (`command`, `user`, `host`, `none`) have no template and are left alone rather than
/// approximated with the wrong one.
fn template_for_type(type_: &str) -> Option<&'static str> {
    match type_ {
        "path" | "file" | "executable" => Some("filepaths"),
        "dir" => Some("folders"),
        _ => None,
    }
}

impl FigArg {
    fn get_template(name: &str) -> Option<String> {
        name.to_lowercase()
            .contains("file")
            .then(|| "filepaths".to_string())
            .or(name
                .to_lowercase()
                .contains("dir")
                .then(|| "folders".to_string()))
            .or(name
                .to_lowercase()
                .contains("path")
                .then(|| "filepaths".to_string()))
    }

    fn get_generator(name: &str) -> Option<FigGenerator> {
        name.to_lowercase()
            .contains("env_vars")
            .then(|| FigGenerator::create_simple_generator(GeneratorType::EnvVar))
            .or(name
                .to_lowercase()
                .contains("env_var")
                .then(|| FigGenerator::create_simple_generator(GeneratorType::EnvVar)))
    }

    pub fn get_generators(&self) -> Vec<FigGenerator> {
        match self.generators.clone() {
            Some(a) => vec![a],
            None => vec![],
        }
    }

    fn get_name(name: &str) -> String {
        name.replace("<", "")
            .replace(">", "")
            .replace("[", "")
            .replace("]", "")
            .to_ascii_lowercase()
    }

    /// The placeholder a `run=` generator is written as, swapped for the generator call by
    /// text once the spec is serialized. It has to tell two commands apart: the same argument
    /// name with a different `run=` is ordinary (`<name>` on one command listing tasks and on
    /// another listing tools), and would otherwise get whichever was replaced first. Both
    /// `complete run=` and `choices run=` go through here.
    fn run_placeholder(name: &str, run: &str) -> String {
        let mut hasher = std::hash::DefaultHasher::new();
        std::hash::Hash::hash(run, &mut hasher);
        let id = std::hash::Hasher::finish(&hasher);
        format!("${name}-{id:016x}$")
    }

    pub fn parse_from_spec(arg: &SpecArg) -> Self {
        let name = FigArg::get_name(&arg.name);
        // `choices run=` is the command a `complete run=` would be, and Fig runs it the same
        // way: when completing, never while this file is generated. It is a declaration, so
        // it displaces the guesses from the argument's name and any `complete` node, as
        // choices do in `usage complete-word`.
        if let Some(choices) = &arg.choices
            && let Some(run) = choices.run()
        {
            return Self {
                generators: Some(FigGenerator {
                    type_: GeneratorType::Complete,
                    post_process: run.to_string(),
                    template_str: FigArg::run_placeholder(&name, run),
                }),
                name,
                description: arg.help.clone(),
                is_variadic: arg.var,
                is_optional: !arg.required,
                template: None,
                suggestions: choices.choices.clone(),
                debounce: None,
                declared: true,
                has_choices: true,
            };
        }
        let guess = arg.choices.is_none();
        let mut fig_arg = Self {
            name,
            description: arg.help.clone(),
            is_variadic: arg.var,
            is_optional: !arg.required,
            // Choices are the whole answer in `usage complete-word`, so an argument that has
            // them gets no guess from its name: `<config_file>` with choices offers those
            // choices, not files the parser would reject.
            template: guess.then(|| FigArg::get_template(&arg.name)).flatten(),
            generators: guess.then(|| FigArg::get_generator(&arg.name)).flatten(),
            suggestions: arg.choices.clone().map(|c| c.choices).unwrap_or_default(),
            debounce: guess
                .then(|| FigArg::get_generator(&arg.name).map(|_| true))
                .flatten(),
            declared: false,
            has_choices: arg.choices.is_some(),
        };
        // A `complete` inside the `arg` is the nearest declaration there is, so it arrives
        // first and the named ones applied afterwards leave it alone.
        //
        // One with none of `run`, `type` or `delegate` still takes the place of the named ones, as it
        // does in `complete-word`, which then falls back to what the argument's name
        // suggests. So the name-based guesses stay, and the arg is marked declared so a named
        // completer does not replace them.
        if let Some(complete) = &arg.complete {
            if complete.run.is_none() && complete.type_.is_none() && complete.delegate.is_none() {
                fig_arg.declared = true;
            } else {
                fig_arg.update_from_complete(complete.clone());
            }
        }
        fig_arg
    }

    pub fn update_from_complete(&mut self, spec: SpecComplete) {
        let name = spec.name;

        // A `complete` node with neither a command to run nor a type says nothing about
        // what this value is, so it displaces nothing.
        if spec.run.is_none() && spec.type_.is_none() && spec.delegate.is_none() {
            return;
        }
        // Choices are a closed set that `usage complete-word` offers instead of running a
        // command, so a `run=` beside them would offer values nothing else accepts. It is
        // still the nearest declaration, so a farther one must not take its place.
        if self.has_choices && spec.type_.is_none() {
            self.declared = true;
            return;
        }

        // Two rules, and keeping them apart is the whole of this function.
        //
        // A declaration beats a guess. The template and generator an argument starts
        // with come from `get_template` and `get_generator` reading its *name* —
        // `out_file` gets paths because it contains "file" — which was all there was
        // before `type=` existed. A spec that says what its value is should not lose to a
        // substring match, so the first declaration to arrive clears every guess,
        // including when what it declares is that there is nothing to offer.
        //
        // The nearest declaration wins. Each command's completers are applied at its own
        // level and the root spec's over the whole tree afterwards, so a later one must
        // not overwrite a nearer one — which is what `or_else` used to arrange for the
        // generator alone.
        if self.declared {
            return;
        }
        self.declared = true;
        self.template = None;
        self.generators = None;
        self.debounce = None;

        // A command to run outranks a type: `run=` is what this argument's author wrote
        // for this argument, where a type names a category. It is also the only one of
        // the two that reached Fig before, so a spec declaring both keeps the behaviour
        // it already had.
        if let Some(run) = spec.run {
            self.generators = Some(FigGenerator {
                type_: GeneratorType::Complete,
                template_str: FigArg::run_placeholder(&name, &run),
                post_process: run,
            });
            return;
        }

        // A `delegate` names another program whose shell completion answers, and Fig has no
        // way to ask a shell. It is still a declaration — the name-based guess would be
        // wrong about a wrapped command line — so the argument is left bare, as below.
        //
        // And a type becomes the template Fig has its own name for, where Fig has one:
        // `none` says to offer nothing, and the kinds a shell answers for itself have no
        // Fig equivalent worth approximating. Both leave the argument bare, which is the
        // declaration being honoured rather than ignored.
        self.template = spec
            .type_
            .as_deref()
            .and_then(template_for_type)
            .map(str::to_string);
    }
}

impl FigOption {
    fn get_names(flag: &SpecFlag) -> Vec<String> {
        let mut n: Vec<String> = flag.short.iter().map(|c| format!("-{c}")).collect();
        n.extend(flag.long.iter().map(|l| format!("--{l}")));
        n
    }

    pub fn get_generators(&self) -> Vec<FigGenerator> {
        self.args
            .iter()
            .filter_map(|a| a.generators.clone())
            .collect()
    }

    pub fn get_args(&mut self) -> Vec<&mut FigArg> {
        self.args.as_mut().map(|a| vec![a]).unwrap_or_default()
    }

    pub fn parse_from_spec(flag: &SpecFlag) -> Self {
        Self {
            name: FigOption::get_names(flag),
            description: flag.help.clone(),
            is_repeatable: flag.var,
            args: flag.arg.clone().map(|arg| FigArg::parse_from_spec(&arg)),
        }
    }
}
impl FigCommand {
    fn get_names(cmd: &SpecCommand) -> Vec<String> {
        let mut r = vec![cmd.name.clone()];
        r.extend(cmd.aliases.clone());
        r
    }

    pub fn get_generators(&self) -> Vec<FigGenerator> {
        let sub = self
            .subcommands
            .iter()
            .map(|s| s.get_generators())
            .collect_vec()
            .concat();
        let opt = self
            .options
            .iter()
            .map(|o| o.get_generators())
            .collect_vec()
            .concat();
        let args = self
            .args
            .iter()
            .map(|a| a.get_generators())
            .collect_vec()
            .concat();
        [sub, opt, args].concat()
    }

    pub fn get_commands(&self) -> Vec<FigCommand> {
        let subcmds = self.subcommands.iter().map(|s| s.get_commands()).concat();
        [subcmds, vec![self.clone()]].concat()
    }

    /// This command's own arguments — its positionals and its flags' values — without
    /// descending into subcommands.
    ///
    /// What a `complete` node inside a `cmd` block is about. [`Self::get_args`] gathers
    /// the whole subtree, which is right for the root spec's completers because those are
    /// inherited, and wrong for a command's own.
    pub fn get_own_args(&mut self) -> Vec<&mut FigArg> {
        let mut own: Vec<&mut FigArg> = self.options.iter_mut().map(|o| o.get_args()).concat();
        own.extend(self.args.iter_mut());
        own
    }

    pub fn get_args(&mut self) -> Vec<&mut FigArg> {
        let opt_args = self.options.iter_mut().map(|o| o.get_args()).concat();
        let sub_args = self.subcommands.iter_mut().map(|c| c.get_args()).concat();

        let args = self.args.iter_mut().collect_vec();
        let mut result = Vec::new();
        for vec in [opt_args, sub_args, args] {
            result.extend(vec);
        }
        result
    }

    pub fn parse_from_spec(cmd: &SpecCommand) -> Option<Self> {
        let mut command = Self::parse_declarations(cmd)?;
        // Each command's own completers, at its own level. Only the root spec's `complete`
        // nodes used to reach any argument, so a `complete` inside a `cmd` block — which
        // is where a typed value hint on a subcommand's argument lands — was dropped.
        Fig::fill_args_complete(command.get_own_args(), cmd.complete.clone());
        Some(command)
    }

    fn parse_declarations(cmd: &SpecCommand) -> Option<Self> {
        (!cmd.hide).then(|| Self {
            name: FigCommand::get_names(cmd),
            description: cmd.help.clone(),
            subcommands: cmd
                .subcommands
                .iter()
                .filter(|(_, v)| !v.hide)
                .filter_map(|(_, v)| FigCommand::parse_from_spec(v))
                .collect(),
            options: cmd
                .flags
                .iter()
                .filter(|f| !f.hide)
                .map(FigOption::parse_from_spec)
                .collect(),
            args: cmd
                .args
                .iter()
                .filter(|a| !a.hide)
                .map(FigArg::parse_from_spec)
                .collect(),
            generate_spec: (!cmd.mounts.is_empty()).then(|| {
                let calls = cmd
                    .mounts
                    .iter()
                    .cloned()
                    .map(|m| {
                        let run = m.run;
                        format!("\"{run}\"")
                    })
                    .join(",");
                format!("${calls}$")
            }),
            cache: (!cmd.mounts.is_empty()).then_some(false),
        })
    }
}

impl Fig {
    fn get_prescript() -> String {
        format!(
            "// @generated by usage-cli from usage spec\n{}",
            include_str!("../../../assets/fig/generators.ts")
        )
    }

    fn get_postscript() -> String {
        "export default completionSpec;".to_string()
    }

    fn fill_args_complete(args: Vec<&mut FigArg>, completes: IndexMap<String, SpecComplete>) {
        args.into_iter()
            .filter_map(|a| completes.get(&a.name).map(|v| (a, v.clone())))
            .for_each(|(arg, complete)| arg.update_from_complete(complete));
    }
}

impl usage_rs::Run for Fig {
    type Output = usage::miette::Result<()>;

    fn run(self) -> Self::Output {
        let write = |path: &PathBuf, md: &str| -> usage::miette::Result<()> {
            generate::write_or_stdout(Some(path), &format!("{}\n", md.trim()))?;
            Ok(())
        };
        let spec = generate::file_or_spec(&self.file, &self.spec)?;
        let mut main_command = FigCommand::parse_from_spec(&spec.cmd).ok_or_else(|| {
            usage::miette::miette!("Failed to parse command spec (command may be hidden)")
        })?;
        let args = main_command.get_args();
        let completes = spec.complete;
        Fig::fill_args_complete(args, completes);
        let j = serde_json::to_string_pretty(&main_command)
            .map_err(|e| usage::miette::miette!("Failed to serialize Fig spec: {}", e))?;
        let mut result = format!("const completionSpec: Fig.Spec = {j}");

        let generators = main_command.get_generators();
        generators.iter().for_each(|g| {
            let template_str = g.template_str.clone();
            let generator_call_text = g.get_generator_text();
            result = result.replace(
                format!("\"{template_str}\"").as_str(),
                generator_call_text.as_str(),
            )
        });

        // Handle mount run commands
        main_command
            .get_commands()
            .iter()
            .filter_map(|cmd| cmd.generate_spec.as_ref().map(|spec| (cmd, spec)))
            .for_each(|(_, call_template_str)| {
                let args = call_template_str.replace("$", "");
                let replace_str = call_template_str.replace("\"", "\\\"");
                result = result.replace(
                    format!("\"{replace_str}\"").as_str(),
                    format!("usageGenerateSpec([{args}])").as_str(),
                )
            });

        // Only the file path wraps the spec in the prescript/postscript that make it usable
        // on its own; bare `usage g fig` prints the spec object alone. `--out-file -` follows
        // the file path, since it means "the bytes a file would have received". Whether the
        // two should agree is a separate question, left alone here.
        if let Some(path) = &self.out_file {
            let prescript = if let Some(source_file) = &self.file {
                let source_label = if source_file.as_os_str() == "-" {
                    "stdin".to_string()
                } else {
                    source_file.display().to_string()
                };
                format!(
                    "// @generated by usage-cli from {}\n{}",
                    source_label,
                    include_str!("../../../assets/fig/generators.ts")
                )
            } else {
                Fig::get_prescript()
            };
            result = [prescript, result, Fig::get_postscript()].join("\n\n");
            write(path, result.as_str())?;
        } else {
            print!("{result}");
        }

        Ok(())
    }
}