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
  • Loading branch information
shannmu committed Sep 26, 2024
1 parent 9d66d13 commit 869064b
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/cargo/util/command_prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ pub trait CommandExt: Sized {
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(
get_ws_member_candidates,
)),
)
}

Expand All @@ -99,7 +102,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 @@ -1298,6 +1304,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 869064b

Please sign in to comment.