Provide dynamic completions for cargo {add,install}

`cargo search` can be used to quickly get crates matching a search string, so we
can pass the current token for first-arg completions to `cargo add` and `cargo
install` to `cargo search` to look up matches.

`cargo search` doesn't restrict itself to (nor prioritize for) prefix matches,
while fish will only display prefix matches (for dynamically generated
completions) so it's perfectly possible for `cargo search foo` to return 20
results none of which will successfully result in a completion, but for a
further-narrowed completion of `cargo install foob^I" to then result in
completions because `cargo search` ended up returning a prefix match for `foob`
while it didn't for `foo`.

The only other oob cargo subcommand that takes a crate name (that isn't the name
of a crate specified in `Cargo.toml`) is `cargo search` but there's no point in
providing completions to that... I think (it's possible to search for crate
"foo" in order to get its latest version number rather than its name, but I'm
not sure that's worth supporting).
This commit is contained in:
Mahmoud Al-Qudsi 2022-09-01 13:52:54 -05:00
parent db92109db5
commit 9466ff2a22

View file

@ -26,6 +26,28 @@ end
complete -c cargo -n '__fish_seen_subcommand_from run test build debug check' -l package \
-xa "(__fish_cargo_packages)"
# Look up crates.io crates matching the the single argument provided to this function
function __fish_cargo_search
if test (string length "$argv[1]") -le 2
# Don't waste time searching for strings with too many results to realistically
# provide a meaningful completion within our results limit.
return
end
# This doesn't do a prefix search, so bump up the limit a tiny bit to try and
# get enough results to show something.
cargo search --color never --quiet --limit 20 $argv[1] |
# Filter out placeholders and "... and xxx more crates"
string match -rvi '^\.\.\.|= "0.0.0"|# .*(reserved|yanked)' |
# Remove the version number and map the description
string replace -rf '^([^ ]+).*# (.*)' '$1\t$2'
end
# Complete possible crate names by search the crates.io index
complete -c cargo -n '__fish_seen_subcommand_from add install' -n '__fish_is_nth_token 2' \
-a "(__fish_cargo_search (commandline -ct))"
## --- AUTO-GENERATED WITH `cargo complete fish` ---
complete -c cargo -n __fish_use_subcommand -l explain -d 'Run `rustc --explain CODE`'
complete -c cargo -n __fish_use_subcommand -l color -d 'Coloring: auto, always, never'