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 17, 2024
1 parent 75ab4e5 commit 1aaae04
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/cargo/util/command_prelude.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::core::compiler::{BuildConfig, MessageFormat, TimingOutput};
use crate::core::resolver::CliFeatures;
use crate::core::{shell, Edition, Target, TargetKind, Workspace};
use crate::core::{shell, Edition, Package, Target, TargetKind, Workspace};
use crate::ops::lockfile::LOCKFILE_NAME;
use crate::ops::registry::RegistryOrIndex;
use crate::ops::{CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
Expand Down Expand Up @@ -86,7 +86,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_package_candidates,
)),
)
}

Expand All @@ -95,7 +98,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_package_candidates,
)),
)
}

Expand Down Expand Up @@ -1067,6 +1073,24 @@ fn get_targets_from_metadata() -> CargoResult<Vec<Target>> {
Ok(targets)
}

fn get_package_candidates() -> Vec<clap_complete::CompletionCandidate> {
get_packages_from_metadata()
.unwrap_or_default()
.into_iter()
.map(|pkg| clap_complete::CompletionCandidate::new(pkg.name().as_str()))
.collect::<Vec<_>>()
}

fn get_packages_from_metadata() -> CargoResult<Vec<Package>> {
let cwd = std::env::current_dir()?;
let gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
let ws = Workspace::new(&find_root_manifest_for_wd(&cwd)?, &gctx)?;

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

Ok(packages)
}

#[track_caller]
pub fn ignore_unknown<T: Default>(r: Result<T, clap::parser::MatchesError>) -> T {
match r {
Expand Down

0 comments on commit 1aaae04

Please sign in to comment.