Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a subcommand to generate shell completions #427

Merged
merged 1 commit into from
Aug 11, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clap::{App, Arg, crate_description, crate_name, crate_version, arg_enum, value_t};
use clap::{App, AppSettings, Arg, crate_description, crate_name, crate_version, arg_enum, value_t};
use remoteprocess::Pid;

/// Options on how to collect samples from a python process
Expand Down Expand Up @@ -222,6 +222,13 @@ impl Config {
.long("json")
.help("Format output as JSON"));

let completions = clap::SubCommand::with_name("completions")
.about("Generate shell completions")
.setting(AppSettings::Hidden)
.arg(Arg::with_name("shell")
.possible_values(&clap::Shell::variants())
.help("Shell type"));

// add native unwinding if appropiate
#[cfg(unwind)]
let record = record.arg(native.clone());
Expand All @@ -238,7 +245,7 @@ impl Config {
#[cfg(not(target_os="freebsd"))]
let dump = dump.arg(nonblocking.clone());

let matches = App::new(crate_name!())
let mut app = App::new(crate_name!())
.version(crate_version!())
.about(crate_description!())
.setting(clap::AppSettings::InferSubcommands)
Expand All @@ -248,7 +255,8 @@ impl Config {
.subcommand(record)
.subcommand(top)
.subcommand(dump)
.get_matches_from_safe(args)?;
.subcommand(completions);
let matches = app.clone().get_matches_from_safe(args)?;
info!("Command line args: {:?}", matches);

let mut config = Config::default();
Expand All @@ -269,6 +277,11 @@ impl Config {
"top" => {
config.sampling_rate = value_t!(matches, "rate", u64)?;
}
"completions" => {
let shell = value_t!(matches.value_of("shell"), clap::Shell).unwrap_or_else(|e| e.exit());
app.gen_completions_to(crate_name!(), shell, &mut std::io::stdout());
std::process::exit(0);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this, but IMO Config is currently too tied with clap::App.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case you don't know, I'd recommend using structopt instead of using clap directly.

}
_ => {}
}
config.command = subcommand.to_owned();
Expand Down