Skip to main content

pimalaya_cli/clap/commands/
completion.rs

1use std::{fmt, fs, path::PathBuf};
2
3use anyhow::{Context, Result, bail};
4use clap::{Command, Parser, ValueEnum, value_parser};
5use clap_complete::Shell;
6use log::debug;
7use serde::{Serialize, Serializer};
8
9use crate::{clap::parsers::path_parser, printer::Printer};
10
11/// Generate completion script for the given shell(s).
12///
13/// This command allows you to generate completion script for a given
14/// shell. The script is printed to the standard output, so it can be
15/// written to a file using unix redirection. Giving a directory
16/// instead writes one script per shell in it, creating the directory
17/// if it does not exist.
18#[derive(Debug, Parser)]
19pub struct CompletionCommand {
20    /// Shell(s) for which completion script should be generated for.
21    ///
22    /// Defaults to every supported shell, which requires a directory.
23    #[arg(value_parser = value_parser!(Shell))]
24    pub shells: Vec<Shell>,
25
26    /// Save completion scripts to the given directory.
27    #[arg(short, long, value_name = "PATH", value_parser = path_parser)]
28    pub dir: Option<PathBuf>,
29}
30
31impl CompletionCommand {
32    /// Generates the completion scripts, either to the standard
33    /// output or to the given directory.
34    pub fn execute(self, printer: &mut impl Printer, mut command: Command) -> Result<()> {
35        let cmd_name = command.get_name().to_string();
36
37        let shells = if self.shells.is_empty() {
38            Shell::value_variants().to_vec()
39        } else {
40            self.shells
41        };
42
43        let Some(dir) = self.dir else {
44            let [shell] = shells[..] else {
45                bail!(
46                    "Writing several completion scripts to the standard output is ambiguous, use --dir to generate them as files"
47                );
48            };
49
50            let mut script = Vec::new();
51            clap_complete::generate(shell, &mut command, cmd_name, &mut script);
52            let script = String::from_utf8(script)
53                .context("Read generated completion script as UTF-8 error")?;
54            debug!("generated {shell} completion script");
55
56            return printer.out(Completion { shell, script });
57        };
58
59        let dir = dir.canonicalize().unwrap_or(dir);
60        fs::create_dir_all(&dir)?;
61
62        let mut scripts = Vec::with_capacity(5);
63
64        for shell in shells {
65            let path = clap_complete::generate_to(shell, &mut command, &cmd_name, &dir)?;
66            let path = path.canonicalize().unwrap_or(path);
67            debug!("generated {shell} completion script at {}", path.display());
68            scripts.push(Script { shell, path })
69        }
70
71        printer.out(Completions { dir, scripts })
72    }
73}
74
75/// Defines a struct-wrapper to provide a JSON output.
76#[derive(Serialize)]
77struct Completion {
78    #[serde(serialize_with = "serialize_shell")]
79    pub shell: Shell,
80    pub script: String,
81}
82
83impl fmt::Display for Completion {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(&self.script)
86    }
87}
88
89/// Defines a struct-wrapper to provide a JSON output.
90#[derive(Serialize)]
91struct Completions {
92    dir: PathBuf,
93    scripts: Vec<Script>,
94}
95
96impl fmt::Display for Completions {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        let n = self.scripts.len();
99        let p = self.dir.display();
100        writeln!(f, "{n} completion script(s) successfully generated in {p}:")?;
101
102        for Script { shell, path } in &self.scripts {
103            let p = path.display();
104            writeln!(f, " - {shell} completion script at {p}")?;
105        }
106
107        Ok(())
108    }
109}
110
111/// Defines a struct-wrapper to provide a JSON output.
112#[derive(Serialize)]
113struct Script {
114    #[serde(serialize_with = "serialize_shell")]
115    pub shell: Shell,
116    pub path: PathBuf,
117}
118
119pub fn serialize_shell<S: Serializer>(shell: &Shell, s: S) -> Result<S::Ok, S::Error> {
120    s.serialize_str(&shell.to_string())
121}
122
123#[cfg(test)]
124mod tests {
125    use clap::Command;
126    use clap_complete::Shell;
127
128    use super::CompletionCommand;
129    use crate::printer::TestPrinter;
130
131    #[test]
132    fn single_shell_script_goes_to_output() {
133        let cmd = CompletionCommand {
134            shells: vec![Shell::Bash],
135            dir: None,
136        };
137
138        let mut printer = TestPrinter::default();
139        cmd.execute(&mut printer, Command::new("test")).unwrap();
140
141        assert!(printer.0.starts_with("_test() {"), "{}", printer.0);
142    }
143
144    #[test]
145    fn several_shells_without_dir_are_rejected() {
146        let cmd = CompletionCommand {
147            shells: vec![Shell::Bash, Shell::Zsh],
148            dir: None,
149        };
150
151        let err = cmd
152            .execute(&mut TestPrinter::default(), Command::new("test"))
153            .unwrap_err();
154
155        assert!(err.to_string().contains("use --dir"), "{err}");
156    }
157}