reactive_graph_client/shared/completions/
install.rs

1use crate::shared::completions::error::InstallShellCompletionError;
2use clap::Command;
3use clap_complete::Generator;
4use clap_complete::Shell;
5use clap_complete::generate;
6use std::fs::create_dir_all;
7
8pub fn install_shell_completions<G: Generator>(generator: G, shell: Shell, cmd: &mut Command) -> Result<(), InstallShellCompletionError> {
9    let bin_name = cmd.get_name().to_string();
10
11    let path = match shell {
12        Shell::Fish => xdg::BaseDirectories::new()
13            .place_config_file(format!("fish/completions/{bin_name}.fish"))
14            .map_err(InstallShellCompletionError::Io)?,
15        Shell::Bash => format!("/usr/share/bash-completion/completions/{bin_name}").into(),
16        Shell::Zsh => format!("/usr/share/zsh/functions/Completion/Base/_{bin_name}").into(),
17        _ => {
18            return Err(InstallShellCompletionError::UnsupportedShell(shell));
19        }
20    };
21
22    if let Some(parent) = path.parent() {
23        create_dir_all(parent).map_err(InstallShellCompletionError::Io)?;
24    }
25
26    eprintln!("Writing completions to {}", path.display());
27
28    let mut buffer = Vec::with_capacity(512);
29    generate(generator, cmd, &bin_name, &mut buffer);
30    std::fs::write(path, buffer).map_err(InstallShellCompletionError::Io)?;
31    Ok(())
32}