clap-rs / clap

A full featured, fast Command Line Argument Parser for Rust
docs.rs/clap
Apache License 2.0
13.65k stars 1.02k forks source link

feat(complete): generate completions for visible aliases #5476

Closed pzmarzly closed 4 weeks ago

pzmarzly commented 2 months ago

Fixes #4265

Closes #5412

This PR picks up work from #5412 to get it to a merge-able state.

I'm splitting the work into 2 standalone commits (all tests pass on both of them), to make it easier to review. I leave it up to you whether to merge them in or squash them into one.

Commit 1. Fixing the iteration over all_subcommands in zsh.rs. We deduplicate values on (sc_name, bin_name) keys, but then only iterate on bin_name. This doesn't cause problems now, since all bin names seem to be unique. However, without fixing this, the second commit would have started generating duplicated functions with same names.

Commit 2. Starting to generate autocompletions for aliased subcommands. This is taking the code from #5412 and updating it to latest changes.

Testing the change

Adapting the test code from #4265's first comment:

[package]
name = "clap-test"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { path = "../clap", version = "4.5.4" }
clap_complete = { path = "../clap/clap_complete", version = "4.5.2" }
clap_derive = { path = "../clap/clap_derive", version = "4.5.4" }
use std::io::{stdout, Write};
use clap::CommandFactory;
use clap_derive::Parser;
use clap_derive::Args;

#[derive(Parser, Debug)]
enum App {
    #[clap(visible_alias = "bar")]
    Foo(FooArgs),
}

#[derive(Args, Clone, Debug)]
struct FooArgs {
    #[clap(long)]
    my_flag: bool,
}

fn main() {
    let mut app = App::command().disable_help_flag(true).disable_help_subcommand(true);
    let mut buf = vec![];
    clap_complete::generate(clap_complete::Shell::Zsh, &mut app, "clap-test", &mut buf);
    stdout().write_all(&mut buf).unwrap();
}
$ cargo run > before.zsh
$ source before.zsh
$ clap-test [TAB] <- gives me "foo bar --"
$ clap-test foo [TAB] <- gives me "--my-flag"
$ clap-test bar [TAB] <- no reaction

After making this change to clap_complete:

$ cargo run > after.zsh
$ source after.zsh
$ clap-test [TAB] <- gives me "foo bar --"
$ clap-test foo [TAB] <- gives me "--my-flag"
$ clap-test bar [TAB] <- gives me "--my-flag"
pzmarzly commented 2 months ago

Re: linter error. Commit subject max line length of 50 is brutal, even feat(complete): Autocomplete visible_alias powershell doesn't fit (53 chars).

pzmarzly commented 1 month ago

I fixed the linter issues, and implemented support for all shells.

@epage is there something you'd like me to do here, or something I can do to make it easier for you to review it? Many thanks.

epage commented 4 weeks ago

Thanks!