From 69c153ba30fc1c83711fb0a56ea35293d7bd0f3f Mon Sep 17 00:00:00 2001 From: Nicky Meuleman Date: Tue, 17 Oct 2023 15:16:18 +0200 Subject: [PATCH] add shell completion generation (#100) * add shell completion generation * remove extra printline * use long form only for completion arg Co-authored-by: Trent <2771466+tbillington@users.noreply.github.com> --------- Co-authored-by: Trent <2771466+tbillington@users.noreply.github.com> --- Cargo.lock | 10 ++++++++++ kondo/Cargo.toml | 1 + kondo/src/main.rs | 18 +++++++++++++++++- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index e574859..2b07598 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,6 +120,15 @@ dependencies = [ "strsim", ] +[[package]] +name = "clap_complete" +version = "4.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ae8ba90b9d8b007efe66e55e48fb936272f5ca00349b5b0e89877520d35ea7" +dependencies = [ + "clap", +] + [[package]] name = "clap_derive" version = "4.3.2" @@ -229,6 +238,7 @@ name = "kondo" version = "0.7.0" dependencies = [ "clap", + "clap_complete", "kondo-lib", ] diff --git a/kondo/Cargo.toml b/kondo/Cargo.toml index 849f281..1d8d6bb 100644 --- a/kondo/Cargo.toml +++ b/kondo/Cargo.toml @@ -20,6 +20,7 @@ edition = "2021" [dependencies] clap = { version = "4", features = ["derive"] } +clap_complete = "4" [dependencies.kondo-lib] path = "../kondo-lib" diff --git a/kondo/src/main.rs b/kondo/src/main.rs index f98e3e9..aac3c9e 100644 --- a/kondo/src/main.rs +++ b/kondo/src/main.rs @@ -8,7 +8,8 @@ use std::{ sync::mpsc::{Receiver, Sender, SyncSender}, }; -use clap::Parser; +use clap::{Command, CommandFactory, Parser}; +use clap_complete::{generate, Generator, Shell}; use kondo_lib::{ dir_size, path_canonicalise, pretty_size, print_elapsed, scan, Project, ScanOptions, @@ -49,6 +50,10 @@ struct Opt { #[arg(short, long, value_parser = parse_age_filter, default_value = "0d")] older: u64, + /// Generates completions for the specified shell + #[arg(long = "completions", value_enum)] + generator: Option, + /// If there is no input, defaults to yes #[arg(short, long)] default: bool, @@ -285,9 +290,20 @@ fn interactive_prompt( } } +fn print_completions(gen: G, cmd: &mut Command) { + generate(gen, cmd, cmd.get_name().to_string(), &mut stdout()); +} + fn main() -> Result<(), Box> { let mut opt = Opt::parse(); + if let Some(generator) = opt.generator { + let mut cmd = Opt::command(); + eprintln!("Generating completion file for {generator:?}..."); + print_completions(generator, &mut cmd); + return Ok(()); + } + if opt.quiet > 0 && !opt.all { eprintln!("Quiet mode can only be used with --all."); std::process::exit(1);