Skip to content

Commit

Permalink
chore: move completion to dedicated module
Browse files Browse the repository at this point in the history
  • Loading branch information
emouty committed Jan 23, 2025
1 parent 08d2fd3 commit 7934788
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 28 deletions.
37 changes: 37 additions & 0 deletions src/cmd/completion.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
31 changes: 3 additions & 28 deletions src/cmd/mod.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -21,7 +14,7 @@ pub enum Command {
Token(token::GetToken),
List(list::List),
Inspect(inspect::Inspect),
Completion { shell: String },
Completion(completion::GetCompletion),
}

impl Command {
Expand All @@ -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)
}
Expand Down

0 comments on commit 7934788

Please sign in to comment.