astrs_cli/command/
completion.rs1use std::io::Write;
5
6use crate::error::CliError;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
10#[value(rename_all = "lower")]
11pub enum CompletionShell {
12 Bash,
14 Zsh,
16 Fish,
18}
19
20impl From<CompletionShell> for clap_complete::Shell {
21 fn from(shell: CompletionShell) -> Self {
22 match shell {
23 CompletionShell::Bash => Self::Bash,
24 CompletionShell::Zsh => Self::Zsh,
25 CompletionShell::Fish => Self::Fish,
26 }
27 }
28}
29
30#[derive(Debug, Clone, Copy)]
32pub struct CompletionArgs {
33 pub shell: CompletionShell,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct CompletionReport {
40 pub script: String,
43}
44
45pub fn run(
56 out: &mut dyn Write,
57 mut command: clap::Command,
58 args: &CompletionArgs,
59) -> Result<CompletionReport, CliError> {
60 let bin_name = command.get_name().to_string();
61 let mut buf: Vec<u8> = Vec::new();
62 clap_complete::generate(
63 clap_complete::Shell::from(args.shell),
64 &mut command,
65 bin_name,
66 &mut buf,
67 );
68 out.write_all(&buf)
69 .map_err(|e| CliError::io("<output>", e))?;
70 Ok(CompletionReport {
71 script: String::from_utf8_lossy(&buf).into_owned(),
72 })
73}
74
75#[cfg(test)]
76mod tests {
77 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
78 use super::*;
79
80 fn sample_command() -> clap::Command {
81 clap::Command::new("astrs")
82 .subcommand(clap::Command::new("validate"))
83 .subcommand(clap::Command::new("expand"))
84 }
85
86 #[test]
87 fn bash_completion_mentions_the_binary_name_and_subcommands() {
88 let mut out = Vec::new();
89 let report = run(
90 &mut out,
91 sample_command(),
92 &CompletionArgs {
93 shell: CompletionShell::Bash,
94 },
95 )
96 .unwrap();
97 assert!(report.script.contains("astrs"));
98 assert!(report.script.contains("validate"));
99 assert_eq!(out, report.script.into_bytes());
100 }
101
102 #[test]
103 fn zsh_and_fish_both_generate_non_empty_scripts() {
104 for shell in [CompletionShell::Zsh, CompletionShell::Fish] {
105 let mut out = Vec::new();
106 let report = run(&mut out, sample_command(), &CompletionArgs { shell }).unwrap();
107 assert!(!report.script.is_empty());
108 }
109 }
110
111 #[test]
112 fn shell_value_enum_parses_lowercase_names() {
113 use clap::ValueEnum;
114 assert_eq!(
115 CompletionShell::from_str("bash", true).unwrap(),
116 CompletionShell::Bash
117 );
118 assert_eq!(
119 CompletionShell::from_str("fish", true).unwrap(),
120 CompletionShell::Fish
121 );
122 }
123}