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