Skip to content

Commit

Permalink
feat(completion): add completion command
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielBrandao1618 committed Jul 25, 2024
1 parent f32e46d commit 417309a
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/action/completion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use crate::cli::Cli;
use clap::{Command, CommandFactory};
use clap_complete::{generator::generate, Generator, Shell};

#[derive(Debug, clap::Args)]
pub struct CompletionArgs {
#[arg(name = "shell", long = "shell", short)]
shell: String,
}

fn get_command() -> Command {
Cli::command()
}

fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
}

fn get_shell_by_name(shell_name: &str) -> Option<Shell> {
match shell_name {
"zsh" => Some(Shell::Zsh),
"bash" => Some(Shell::Bash),
"fish" => Some(Shell::Fish),
"powershell" => Some(Shell::PowerShell),
"elvish" => Some(Shell::Elvish),
_ => None,
}
}

pub fn completion(args: CompletionArgs) {
if let Some(shell) = get_shell_by_name(&args.shell) {
let mut cmd = get_command();
print_completions(shell, &mut cmd);
} else {
eprintln!("No such shell was found: {}", &args.shell);
}
}
2 changes: 2 additions & 0 deletions src/action/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::QuartzResult;
use crate::{cli::Cmd, Ctx};

pub mod body;
pub mod completion;
pub mod config;
pub mod cookie;
pub mod env;
Expand Down Expand Up @@ -39,6 +40,7 @@ pub async fn cmd(ctx: &mut Ctx, command: Cmd) -> QuartzResult {
Cmd::Var { command } => action::var::cmd(ctx, command)?,
Cmd::Env { command } => action::env::cmd(ctx, command)?,
Cmd::Config { command } => action::config::cmd(ctx, command)?,
Cmd::Completion(args) => action::completion::completion(args),
};

Ok(())
Expand Down
5 changes: 5 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ pub enum Cmd {
#[command(subcommand)]
command: ConfigCmd,
},
#[command(
name = "completion",
about = "outputs a completion script for a given shell"
)]
Completion(action::completion::CompletionArgs),
}

#[derive(Debug, Subcommand)]
Expand Down
Empty file added src/completion.rs
Empty file.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod action;
pub mod cli;
pub mod completion;
pub mod config;
pub mod cookie;
pub mod endpoint;
Expand Down

0 comments on commit 417309a

Please sign in to comment.