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