macos_agent/
completion.rs1use clap::{CommandFactory, ValueEnum};
2use clap_complete::{Shell, generate};
3use std::io::{self, Write};
4
5use crate::cli::Cli;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
8pub enum CompletionShell {
9 Bash,
10 Zsh,
11}
12
13pub fn run(shell: CompletionShell) -> i32 {
14 let mut command = Cli::command();
15 let bin_name = command.get_name().to_string();
16
17 match shell {
18 CompletionShell::Bash => print_completion(Shell::Bash, &mut command, &bin_name),
19 CompletionShell::Zsh => print_completion(Shell::Zsh, &mut command, &bin_name),
20 }
21
22 0
23}
24
25fn print_completion(generator: Shell, command: &mut clap::Command, bin_name: &str) {
26 if matches!(generator, Shell::Bash) {
27 let mut output = Vec::new();
28 generate(generator, command, bin_name, &mut output);
29 let normalized = normalize_bash_completion(
30 String::from_utf8(output).expect("bash completion should be valid UTF-8"),
31 );
32 io::stdout()
33 .write_all(normalized.as_bytes())
34 .expect("failed to write bash completion");
35 return;
36 }
37
38 generate(generator, command, bin_name, &mut io::stdout());
39}
40
41fn normalize_bash_completion(script: String) -> String {
42 script.replace("__subcmd__", "__")
43}