Skip to main content

astrs_cli/command/
completion.rs

1//! `astrs completion` (blueprint §17): shell completion scripts via
2//! `clap_complete`, for bash, zsh and fish.
3
4use std::io::Write;
5
6use crate::error::CliError;
7
8/// A shell `astrs completion` can generate a script for.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
10#[value(rename_all = "lower")]
11pub enum CompletionShell {
12    /// GNU Bash.
13    Bash,
14    /// Z shell.
15    Zsh,
16    /// Fish.
17    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/// Arguments for `astrs completion`.
31#[derive(Debug, Clone, Copy)]
32pub struct CompletionArgs {
33    /// Which shell to generate a script for.
34    pub shell: CompletionShell,
35}
36
37/// The result of generating one completion script.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct CompletionReport {
40    /// The generated script text — exactly what was written to the
41    /// output sink.
42    pub script: String,
43}
44
45/// Generate a completion script for `command` and print it to `out`.
46///
47/// `command` is the caller's full clap [`clap::Command`] tree (built from
48/// [`crate::cli::Cli::command`]) rather than something this module
49/// constructs itself, so a change to the verb tree in `cli.rs` is picked
50/// up automatically with no separate description to keep in sync.
51///
52/// # Errors
53///
54/// Returns [`CliError::Io`] if writing to `out` fails.
55pub 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}