Skip to content

Commit

Permalink
feat: Add custom completer for completing `cargo build --packge <TAB>…
Browse files Browse the repository at this point in the history
…` / `cargo tree --package <TAB>`
  • Loading branch information
shannmu committed Oct 8, 2024
1 parent 845bb8b commit 2bac0b6
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions src/cargo/util/command_prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,18 @@ pub trait CommandExt: Sized {
}

fn arg_package_spec_simple(self, package: &'static str) -> Self {
let name = self._name();
self._arg(
optional_multi_opt("package", "SPEC", package)
.short('p')
.help_heading(heading::PACKAGE_SELECTION),
.help_heading(heading::PACKAGE_SELECTION)
.add(clap_complete::ArgValueCandidates::new(move || {
if ["build", "tree"].contains(&name.as_str()) {
get_ws_member_candidates()
} else {
vec![]
}
})),
)
}

Expand All @@ -101,7 +109,10 @@ pub trait CommandExt: Sized {
optional_opt("package", package)
.short('p')
.value_name("SPEC")
.help_heading(heading::PACKAGE_SELECTION),
.help_heading(heading::PACKAGE_SELECTION)
.add(clap_complete::ArgValueCandidates::new(
get_ws_member_candidates,
)),
)
}

Expand Down Expand Up @@ -1304,6 +1315,31 @@ fn get_packages() -> CargoResult<Vec<Package>> {
Ok(packages)
}

fn get_ws_member_candidates() -> Vec<clap_complete::CompletionCandidate> {
get_ws_member_packages()
.unwrap_or_default()
.into_iter()
.map(|pkg| {
clap_complete::CompletionCandidate::new(pkg.name().as_str()).help(
pkg.manifest()
.metadata()
.description
.to_owned()
.map(From::from),
)
})
.collect::<Vec<_>>()
}

fn get_ws_member_packages() -> CargoResult<Vec<Package>> {
let gctx = new_gctx_for_completions()?;
let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;

let packages = ws.members().map(|pkg| pkg.to_owned()).collect::<Vec<_>>();

Ok(packages)
}

fn new_gctx_for_completions() -> CargoResult<GlobalContext> {
let cwd = std::env::current_dir()?;
let mut gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
Expand Down

0 comments on commit 2bac0b6

Please sign in to comment.