novel_cli/cmd/
completions.rs

1use std::io;
2
3use clap::{Args, CommandFactory, ValueEnum};
4use clap_complete::Generator;
5use color_eyre::eyre::Result;
6use fluent_templates::Loader;
7
8use crate::config::Config;
9use crate::{LANG_ID, LOCALES};
10
11#[must_use]
12#[derive(Clone, ValueEnum)]
13pub enum Shell {
14    Bash,
15    Elvish,
16    Fish,
17    PowerShell,
18    Zsh,
19    Nushell,
20}
21
22impl Shell {
23    fn to_clap_type(&self) -> Box<dyn Generator> {
24        match self {
25            Self::Bash => Box::new(clap_complete::Shell::Bash),
26            Self::Elvish => Box::new(clap_complete::Shell::Elvish),
27            Self::Fish => Box::new(clap_complete::Shell::Fish),
28            Self::PowerShell => Box::new(clap_complete::Shell::PowerShell),
29            Self::Zsh => Box::new(clap_complete::Shell::Zsh),
30            Self::Nushell => Box::new(clap_complete_nushell::Nushell),
31        }
32    }
33}
34
35#[must_use]
36#[derive(Args)]
37#[command(arg_required_else_help = true,
38    about = LOCALES.lookup(&LANG_ID, "completions_command"))]
39pub struct Completions {
40    #[arg(value_enum,
41        help = LOCALES.lookup(&LANG_ID, "shell"))]
42    pub shell: Shell,
43}
44
45pub fn execute(config: Completions) -> Result<()> {
46    let mut cmd = Config::command();
47    let bin_name = cmd.get_name().to_string();
48
49    cmd.set_bin_name(bin_name);
50    cmd.build();
51
52    config
53        .shell
54        .to_clap_type()
55        .generate(&cmd, &mut io::stdout());
56
57    Ok(())
58}