pimalaya_cli/clap/commands/
completion.rs1use 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#[derive(Debug, Parser)]
20pub struct CompletionCommand {
21 #[arg(value_parser = value_parser!(Shell))]
25 pub shells: Vec<Shell>,
26
27 #[arg(short, long, value_name = "PATH", value_parser = path_parser)]
29 pub dir: Option<PathBuf>,
30}
31
32impl CompletionCommand {
33 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#[derive(Serialize, JsonSchema)]
78#[serde(untagged)]
79pub(crate) enum CompletionOutput {
80 Script {
82 #[serde(serialize_with = "serialize_shell")]
84 #[schemars(with = "String")]
85 shell: Shell,
86 script: String,
88 },
89 Files {
91 dir: PathBuf,
93 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#[derive(Serialize, JsonSchema)]
120pub(crate) struct ScriptFile {
121 #[serde(serialize_with = "serialize_shell")]
123 #[schemars(with = "String")]
124 shell: Shell,
125 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}