From 7d00328f778bb231211934c8f3bf147468e2b60c Mon Sep 17 00:00:00 2001 From: Erwan Moutymbo Date: Wed, 22 Jan 2025 14:20:15 +0100 Subject: [PATCH] move completion to dedicated module --- src/cmd/completion.rs | 37 +++++++++++++++++++++++++++++++++++++ src/cmd/mod.rs | 31 +++---------------------------- 2 files changed, 40 insertions(+), 28 deletions(-) create mode 100644 src/cmd/completion.rs diff --git a/src/cmd/completion.rs b/src/cmd/completion.rs new file mode 100644 index 0000000..cd4439a --- /dev/null +++ b/src/cmd/completion.rs @@ -0,0 +1,37 @@ +use crate::Cli; +use clap::CommandFactory; +use clap_complete::generate; +use clap_complete::Shell::{Bash, Fish, Zsh}; +use std::path::Path; +use std::{env, io}; + +/// Generate shell completion +#[derive(Debug, clap::Parser)] +#[command(rename_all_env = "SNAKE_CASE")] +pub struct GetCompletion { + /// The shell to generate completions for. Supported values are bash, zsh or fish + pub shell: String, +} + +impl GetCompletion { + pub async fn run(self) -> anyhow::Result<()> { + let shell = self.shell; + let mut cmd = Cli::command(); + let bin_name = env::args() + .next() + .and_then(|path| { + Path::new(&path) + .file_stem() + .map(|name| name.to_string_lossy().into_owned()) + }) + .unwrap(); + + match shell.as_str() { + "bash" => generate(Bash, &mut cmd, &bin_name, &mut io::stdout()), + "zsh" => generate(Zsh, &mut cmd, &bin_name, &mut io::stdout()), + "fish" => generate(Fish, &mut cmd, &bin_name, &mut io::stdout()), + _ => eprintln!("Unsupported shell: {}", shell), + } + Ok(()) + } +} diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index 73a6048..b8fc39e 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -1,18 +1,11 @@ +mod completion; mod create; mod delete; mod inspect; mod list; mod token; -use crate::Cli; -use clap::CommandFactory; -use clap_complete::{ - generate, - shells::{Bash, Fish, Zsh}, -}; -use std::path::Path; use std::process::ExitCode; -use std::{env, io}; #[derive(Debug, clap::Subcommand)] pub enum Command { @@ -21,7 +14,7 @@ pub enum Command { Token(token::GetToken), List(list::List), Inspect(inspect::Inspect), - Completion { shell: String }, + Completion(completion::GetCompletion), } impl Command { @@ -32,25 +25,7 @@ impl Command { Self::Token(cmd) => cmd.run().await, Self::List(cmd) => cmd.run().await, Self::Inspect(cmd) => cmd.run().await, - Self::Completion { shell } => { - let mut cmd = Cli::command(); - let bin_name = env::args() - .next() - .and_then(|path| { - Path::new(&path) - .file_stem() - .map(|name| name.to_string_lossy().into_owned()) - }) - .unwrap(); - - match shell.as_str() { - "bash" => generate(Bash, &mut cmd, &bin_name, &mut io::stdout()), - "zsh" => generate(Zsh, &mut cmd, &bin_name, &mut io::stdout()), - "fish" => generate(Fish, &mut cmd, &bin_name, &mut io::stdout()), - _ => eprintln!("Unsupported shell: {}", shell), - } - Ok(()) - } + Self::Completion(cmd) => cmd.run().await, } .map(|()| ExitCode::SUCCESS) }