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 serde::{Serialize, Serializer};
8
9use crate::{clap::parsers::path_parser, printer::Printer};
10
11#[derive(Debug, Parser)]
19pub struct CompletionCommand {
20 #[arg(value_parser = value_parser!(Shell))]
24 pub shells: Vec<Shell>,
25
26 #[arg(short, long, value_name = "PATH", value_parser = path_parser)]
28 pub dir: Option<PathBuf>,
29}
30
31impl CompletionCommand {
32 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#[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#[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#[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}