feat(complete): Allow de-duplicating of candidates

This commit is contained in:
Ed Page 2024-09-20 11:07:01 -05:00
parent 3bcc7f806d
commit 7b06d9a358
2 changed files with 22 additions and 0 deletions

View file

@ -8,6 +8,7 @@ use clap::builder::StyledStr;
pub struct CompletionCandidate {
value: OsString,
help: Option<StyledStr>,
id: Option<String>,
hidden: bool,
}
@ -27,6 +28,14 @@ impl CompletionCandidate {
self
}
/// Only first for a given Id is shown
///
/// To reduce the risk of conflicts, this should likely contain a namespace.
pub fn id(mut self, id: Option<String>) -> Self {
self.id = id;
self
}
/// Set the visibility of the completion candidate
///
/// Only shown when there is no visible candidate for completing the current argument.
@ -60,6 +69,11 @@ impl CompletionCandidate {
self.help.as_ref()
}
/// Get the id used for de-duplicating
pub fn get_id(&self) -> Option<&String> {
self.id.as_ref()
}
/// Get the visibility of the completion candidate
pub fn is_hide_set(&self) -> bool {
self.hidden

View file

@ -257,6 +257,14 @@ fn complete_arg(
if completions.iter().any(|a| !a.is_hide_set()) {
completions.retain(|a| !a.is_hide_set());
}
let mut seen_ids = std::collections::HashSet::new();
completions.retain(move |a| {
if let Some(id) = a.get_id().cloned() {
seen_ids.insert(id)
} else {
true
}
});
Ok(completions)
}