| 1 |
use std::any::type_name; |
| 2 |
use std::ffi::OsStr; |
| 3 |
use std::ffi::OsString; |
| 4 |
use std::sync::Arc; |
| 5 |
|
| 6 |
use clap::builder::ArgExt; |
| 7 |
use clap::builder::CommandExt; |
| 8 |
use clap_lex::OsStrExt as _; |
| 9 |
|
| 10 |
use super::CompletionCandidate; |
| 11 |
|
| 12 |
/// Extend [`Arg`][clap::Arg] with a completer |
| 13 |
/// |
| 14 |
/// # Example |
| 15 |
/// |
| 16 |
/// ```rust |
| 17 |
/// use clap::Parser; |
| 18 |
/// use clap_complete::engine::{ArgValueCompleter, CompletionCandidate}; |
| 19 |
/// |
| 20 |
/// fn custom_completer(current: &std::ffi::OsStr) -> Vec<CompletionCandidate> { |
| 21 |
/// let mut completions = vec![]; |
| 22 |
/// let Some(current) = current.to_str() else { |
| 23 |
/// return completions; |
| 24 |
/// }; |
| 25 |
/// |
| 26 |
/// if "foo".starts_with(current) { |
| 27 |
/// completions.push(CompletionCandidate::new("foo")); |
| 28 |
/// } |
| 29 |
/// if "bar".starts_with(current) { |
| 30 |
/// completions.push(CompletionCandidate::new("bar")); |
| 31 |
/// } |
| 32 |
/// if "baz".starts_with(current) { |
| 33 |
/// completions.push(CompletionCandidate::new("baz")); |
| 34 |
/// } |
| 35 |
/// completions |
| 36 |
/// } |
| 37 |
/// |
| 38 |
/// #[derive(Debug, Parser)] |
| 39 |
/// struct Cli { |
| 40 |
/// #[arg(long, add = ArgValueCompleter::new(custom_completer))] |
| 41 |
/// custom: Option<String>, |
| 42 |
/// } |
| 43 |
/// ``` |
| 44 |
#[derive(Clone)] |
| 45 |
pub struct ArgValueCompleter(Arc<dyn ValueCompleter>); |
| 46 |
|
| 47 |
impl ArgValueCompleter { |
| 48 |
/// Create a new `ArgValueCompleter` with a custom completer |
| 49 |
pub fn new<C>(completer: C) -> Self |
| 50 |
where |
| 51 |
C: ValueCompleter + 'static, |
| 52 |
{ |
| 53 |
Self(Arc::new(completer)) |
| 54 |
} |
| 55 |
|
| 56 |
/// Candidates that match `current` |
| 57 |
/// |
| 58 |
/// See [`CompletionCandidate`] for more information. |
| 59 |
pub fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> { |
| 60 |
self.0.complete(current) |
| 61 |
} |
| 62 |
|
| 63 |
/// Candidates that match `current` at `arg_index` within the current occurrence. |
| 64 |
/// |
| 65 |
/// `arg_index` is the position of the value being completed within an |
| 66 |
/// argument's [`num_args`][clap::Arg::num_args] range, starting at `0`. |
| 67 |
/// This lets a completer return different candidates for each value of a |
| 68 |
/// multi-value argument (for example, a remote name first and a branch |
| 69 |
/// name second for `--set-upstream <REMOTE> <BRANCH>`). |
| 70 |
/// |
| 71 |
/// `arg_index` is unaffected by [`value_delimiter`][clap::Arg::value_delimiter]: |
| 72 |
/// it counts shell arguments, not delimiter-separated values. |
| 73 |
/// |
| 74 |
/// See [`CompletionCandidate`] for more information. |
| 75 |
pub fn complete_at(&self, arg_index: usize, current: &OsStr) -> Vec<CompletionCandidate> { |
| 76 |
self.0.complete_at(arg_index, current) |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
impl std::fmt::Debug for ArgValueCompleter { |
| 81 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 82 |
f.write_str(type_name::<Self>()) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
impl ArgExt for ArgValueCompleter {} |
| 87 |
|
| 88 |
/// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCompleter`] |
| 89 |
/// |
| 90 |
/// This is useful when predefined value hints are not enough. |
| 91 |
pub trait ValueCompleter: Send + Sync { |
| 92 |
/// All potential candidates for an argument. |
| 93 |
/// |
| 94 |
/// See [`CompletionCandidate`] for more information. |
| 95 |
fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate>; |
| 96 |
|
| 97 |
/// All potential candidates for the value at `arg_index` within the current occurrence. |
| 98 |
/// |
| 99 |
/// `arg_index` is the position of the value being completed within an |
| 100 |
/// argument's [`num_args`][clap::Arg::num_args] range, starting at `0`. |
| 101 |
/// This lets a completer return different candidates for each value of a |
| 102 |
/// multi-value argument (for example, a remote name first and a branch |
| 103 |
/// name second for `--set-upstream <REMOTE> <BRANCH>`). |
| 104 |
/// |
| 105 |
/// `arg_index` is unaffected by [`value_delimiter`][clap::Arg::value_delimiter]: |
| 106 |
/// it counts shell arguments, not delimiter-separated values. |
| 107 |
/// |
| 108 |
/// See [`CompletionCandidate`] for more information. |
| 109 |
fn complete_at(&self, arg_index: usize, current: &OsStr) -> Vec<CompletionCandidate> { |
| 110 |
let _ = arg_index; |
| 111 |
self.complete(current) |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
impl<F> ValueCompleter for F |
| 116 |
where |
| 117 |
F: Fn(&OsStr) -> Vec<CompletionCandidate> + Send + Sync, |
| 118 |
{ |
| 119 |
fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> { |
| 120 |
self(current) |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
/// Extend [`Arg`][clap::Arg] with a [`ValueCandidates`] |
| 125 |
/// |
| 126 |
/// # Example |
| 127 |
/// |
| 128 |
/// ```rust |
| 129 |
/// use clap::Parser; |
| 130 |
/// use clap_complete::engine::{ArgValueCandidates, CompletionCandidate}; |
| 131 |
/// |
| 132 |
/// #[derive(Debug, Parser)] |
| 133 |
/// struct Cli { |
| 134 |
/// #[arg(long, add = ArgValueCandidates::new(|| { vec![ |
| 135 |
/// CompletionCandidate::new("foo"), |
| 136 |
/// CompletionCandidate::new("bar"), |
| 137 |
/// CompletionCandidate::new("baz")] }))] |
| 138 |
/// custom: Option<String>, |
| 139 |
/// } |
| 140 |
/// ``` |
| 141 |
#[derive(Clone)] |
| 142 |
pub struct ArgValueCandidates(Arc<dyn ValueCandidates>); |
| 143 |
|
| 144 |
impl ArgValueCandidates { |
| 145 |
/// Create a new `ArgValueCandidates` with a custom completer |
| 146 |
pub fn new<C>(completer: C) -> Self |
| 147 |
where |
| 148 |
C: ValueCandidates + 'static, |
| 149 |
{ |
| 150 |
Self(Arc::new(completer)) |
| 151 |
} |
| 152 |
|
| 153 |
/// All potential candidates for an argument. |
| 154 |
/// |
| 155 |
/// See [`CompletionCandidate`] for more information. |
| 156 |
pub fn candidates(&self) -> Vec<CompletionCandidate> { |
| 157 |
self.0.candidates() |
| 158 |
} |
| 159 |
|
| 160 |
pub(crate) fn value_candidates(&self) -> &dyn ValueCandidates { |
| 161 |
&*self.0 |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
impl std::fmt::Debug for ArgValueCandidates { |
| 166 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 167 |
f.write_str(type_name::<Self>()) |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
impl ArgExt for ArgValueCandidates {} |
| 172 |
|
| 173 |
/// Extend [`Command`][clap::Command] with a [`ValueCandidates`] |
| 174 |
/// |
| 175 |
/// # Example |
| 176 |
/// ```rust |
| 177 |
/// use clap::Parser; |
| 178 |
/// use clap_complete::engine::{SubcommandCandidates, CompletionCandidate}; |
| 179 |
/// #[derive(Debug, Parser)] |
| 180 |
/// #[clap(name = "cli", add = SubcommandCandidates::new(|| { vec![ |
| 181 |
/// CompletionCandidate::new("foo"), |
| 182 |
/// CompletionCandidate::new("bar"), |
| 183 |
/// CompletionCandidate::new("baz")] }))] |
| 184 |
/// struct Cli { |
| 185 |
/// #[arg(long)] |
| 186 |
/// input: Option<String>, |
| 187 |
/// } |
| 188 |
/// ``` |
| 189 |
#[derive(Clone)] |
| 190 |
pub struct SubcommandCandidates(Arc<dyn ValueCandidates>); |
| 191 |
|
| 192 |
impl SubcommandCandidates { |
| 193 |
/// Create a new `SubcommandCandidates` with a custom completer |
| 194 |
pub fn new<C>(completer: C) -> Self |
| 195 |
where |
| 196 |
C: ValueCandidates + 'static, |
| 197 |
{ |
| 198 |
Self(Arc::new(completer)) |
| 199 |
} |
| 200 |
|
| 201 |
/// All potential candidates for an external subcommand. |
| 202 |
/// |
| 203 |
/// See [`CompletionCandidate`] for more information. |
| 204 |
pub fn candidates(&self) -> Vec<CompletionCandidate> { |
| 205 |
self.0.candidates() |
| 206 |
} |
| 207 |
|
| 208 |
pub(crate) fn value_candidates(&self) -> &dyn ValueCandidates { |
| 209 |
&*self.0 |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
impl std::fmt::Debug for SubcommandCandidates { |
| 214 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 215 |
f.write_str(type_name::<Self>()) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
impl CommandExt for SubcommandCandidates {} |
| 220 |
|
| 221 |
/// User-provided completion candidates for an [`Arg`][clap::Arg], see [`ArgValueCandidates`] |
| 222 |
/// |
| 223 |
/// User-provided completion candidates for an [`Subcommand`][clap::Subcommand], see [`SubcommandCandidates`] |
| 224 |
/// |
| 225 |
/// This is useful when predefined value hints are not enough. |
| 226 |
pub trait ValueCandidates: Send + Sync { |
| 227 |
/// All potential candidates for an argument. |
| 228 |
/// |
| 229 |
/// See [`CompletionCandidate`] for more information. |
| 230 |
fn candidates(&self) -> Vec<CompletionCandidate>; |
| 231 |
} |
| 232 |
|
| 233 |
impl<F> ValueCandidates for F |
| 234 |
where |
| 235 |
F: Fn() -> Vec<CompletionCandidate> + Send + Sync, |
| 236 |
{ |
| 237 |
fn candidates(&self) -> Vec<CompletionCandidate> { |
| 238 |
self() |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
/// Complete a value as a [`std::path::Path`] |
| 243 |
/// |
| 244 |
/// # Example |
| 245 |
/// |
| 246 |
/// ```rust |
| 247 |
/// use clap::Parser; |
| 248 |
/// use clap_complete::engine::{ArgValueCompleter, PathCompleter}; |
| 249 |
/// |
| 250 |
/// #[derive(Debug, Parser)] |
| 251 |
/// struct Cli { |
| 252 |
/// #[arg(long, add = ArgValueCompleter::new(PathCompleter::file()))] |
| 253 |
/// custom: Option<String>, |
| 254 |
/// } |
| 255 |
/// ``` |
| 256 |
pub struct PathCompleter { |
| 257 |
current_dir: Option<std::path::PathBuf>, |
| 258 |
#[allow(clippy::type_complexity)] |
| 259 |
filter: Option<Box<dyn Fn(&std::path::Path) -> bool + Send + Sync>>, |
| 260 |
stdio: bool, |
| 261 |
} |
| 262 |
|
| 263 |
impl PathCompleter { |
| 264 |
/// Any path is allowed |
| 265 |
pub fn any() -> Self { |
| 266 |
Self { |
| 267 |
filter: None, |
| 268 |
current_dir: None, |
| 269 |
stdio: false, |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
/// Complete only files |
| 274 |
pub fn file() -> Self { |
| 275 |
Self::any().filter(|p| p.is_file()) |
| 276 |
} |
| 277 |
|
| 278 |
/// Complete only directories |
| 279 |
pub fn dir() -> Self { |
| 280 |
Self::any().filter(|p| p.is_dir()) |
| 281 |
} |
| 282 |
|
| 283 |
/// Include stdio (`-`) |
| 284 |
pub fn stdio(mut self) -> Self { |
| 285 |
self.stdio = true; |
| 286 |
self |
| 287 |
} |
| 288 |
|
| 289 |
/// Select which paths should be completed |
| 290 |
pub fn filter( |
| 291 |
mut self, |
| 292 |
filter: impl Fn(&std::path::Path) -> bool + Send + Sync + 'static, |
| 293 |
) -> Self { |
| 294 |
self.filter = Some(Box::new(filter)); |
| 295 |
self |
| 296 |
} |
| 297 |
|
| 298 |
/// Override [`std::env::current_dir`] |
| 299 |
pub fn current_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self { |
| 300 |
self.current_dir = Some(path.into()); |
| 301 |
self |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
impl Default for PathCompleter { |
| 306 |
fn default() -> Self { |
| 307 |
Self::any() |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
impl ValueCompleter for PathCompleter { |
| 312 |
fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> { |
| 313 |
let filter = self.filter.as_deref().unwrap_or(&|_| true); |
| 314 |
let mut current_dir_actual = None; |
| 315 |
let current_dir = self.current_dir.as_deref().or_else(|| { |
| 316 |
current_dir_actual = std::env::current_dir().ok(); |
| 317 |
current_dir_actual.as_deref() |
| 318 |
}); |
| 319 |
let mut candidates = complete_path(current, current_dir, filter); |
| 320 |
if self.stdio && current.is_empty() { |
| 321 |
candidates.push(CompletionCandidate::new("-").help(Some("stdio".into()))); |
| 322 |
} |
| 323 |
candidates |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
pub(crate) fn complete_path( |
| 328 |
value_os: &OsStr, |
| 329 |
current_dir: Option<&std::path::Path>, |
| 330 |
is_wanted: &dyn Fn(&std::path::Path) -> bool, |
| 331 |
) -> Vec<CompletionCandidate> { |
| 332 |
let mut completions = Vec::new(); |
| 333 |
let mut potential = Vec::new(); |
| 334 |
|
| 335 |
let value_path = std::path::Path::new(value_os); |
| 336 |
let (prefix, current) = split_file_name(value_path); |
| 337 |
let current = current.to_string_lossy(); |
| 338 |
let search_root = if prefix.is_absolute() { |
| 339 |
prefix.to_owned() |
| 340 |
} else if prefix.iter().next() == Some(OsStr::new("~")) { |
| 341 |
let prefix = prefix.strip_prefix("~").unwrap_or(prefix); |
| 342 |
let home_dir = match std::env::home_dir() { |
| 343 |
Some(home_dir) => home_dir, |
| 344 |
None => { |
| 345 |
// Can't complete without a `home_dir` |
| 346 |
return completions; |
| 347 |
} |
| 348 |
}; |
| 349 |
home_dir.join(prefix) |
| 350 |
} else { |
| 351 |
let current_dir = match current_dir { |
| 352 |
Some(current_dir) => current_dir, |
| 353 |
None => { |
| 354 |
// Can't complete without a `current_dir` |
| 355 |
return completions; |
| 356 |
} |
| 357 |
}; |
| 358 |
current_dir.join(prefix) |
| 359 |
}; |
| 360 |
debug!("complete_path: search_root={search_root:?}, prefix={prefix:?}"); |
| 361 |
|
| 362 |
if value_os.is_empty() && is_wanted(&search_root) { |
| 363 |
completions.push(".".into()); |
| 364 |
} |
| 365 |
|
| 366 |
for entry in std::fs::read_dir(&search_root) |
| 367 |
.ok() |
| 368 |
.into_iter() |
| 369 |
.flatten() |
| 370 |
.filter_map(Result::ok) |
| 371 |
{ |
| 372 |
let raw_file_name = entry.file_name(); |
| 373 |
if !raw_file_name.starts_with(¤t) { |
| 374 |
continue; |
| 375 |
} |
| 376 |
|
| 377 |
if entry.path().is_dir() { |
| 378 |
let mut suggestion = prefix.join(&raw_file_name); |
| 379 |
suggestion.push(""); // Ensure trailing `/` |
| 380 |
let candidate = CompletionCandidate::new(suggestion.as_os_str().to_owned()) |
| 381 |
.hide(is_hidden(&raw_file_name)); |
| 382 |
|
| 383 |
if is_wanted(&entry.path()) { |
| 384 |
completions.push(candidate); |
| 385 |
} else { |
| 386 |
potential.push(candidate); |
| 387 |
} |
| 388 |
} else { |
| 389 |
if is_wanted(&entry.path()) { |
| 390 |
let suggestion = prefix.join(&raw_file_name); |
| 391 |
let candidate = CompletionCandidate::new(suggestion.as_os_str().to_owned()) |
| 392 |
.hide(is_hidden(&raw_file_name)); |
| 393 |
completions.push(candidate); |
| 394 |
} |
| 395 |
} |
| 396 |
} |
| 397 |
completions.sort(); |
| 398 |
potential.sort(); |
| 399 |
completions.extend(potential); |
| 400 |
|
| 401 |
completions |
| 402 |
} |
| 403 |
|
| 404 |
fn is_hidden(file_name: &OsStr) -> bool { |
| 405 |
file_name.starts_with(".") |
| 406 |
} |
| 407 |
|
| 408 |
fn split_file_name(path: &std::path::Path) -> (&std::path::Path, &OsStr) { |
| 409 |
// Workaround that `Path::new("name/").file_name()` reports `"name"` |
| 410 |
if path_has_name(path) { |
| 411 |
( |
| 412 |
path.parent().unwrap_or_else(|| std::path::Path::new("")), |
| 413 |
path.file_name().expect("not called with `..`"), |
| 414 |
) |
| 415 |
} else { |
| 416 |
(path, Default::default()) |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
fn path_has_name(path: &std::path::Path) -> bool { |
| 421 |
let path_bytes = path.as_os_str().as_encoded_bytes(); |
| 422 |
let Some(trailing) = path_bytes.last() else { |
| 423 |
return false; |
| 424 |
}; |
| 425 |
let trailing = *trailing as char; |
| 426 |
!std::path::is_separator(trailing) && path.file_name().is_some() |
| 427 |
} |
| 428 |
|
| 429 |
/// Create [`CompletionCandidate`]s for [`clap::builder::PossibleValue`] |
| 430 |
/// |
| 431 |
/// This is implicitly applied for arguments with either a [`clap::builder::PossibleValuesParser`] or [`clap::builder::EnumValueParser`]. |
| 432 |
/// |
| 433 |
/// Using this explicitly is intended for arguments that also accept other value formats that need |
| 434 |
/// to be completed and the completer is eager ([`ValueCandidates`]). |
| 435 |
/// For lazy completion, see [`complete_possible_values`]. |
| 436 |
pub fn possible_value_candidates( |
| 437 |
values: impl IntoIterator<Item = clap::builder::PossibleValue>, |
| 438 |
) -> Vec<CompletionCandidate> { |
| 439 |
values |
| 440 |
.into_iter() |
| 441 |
.map(|p| { |
| 442 |
CompletionCandidate::new(OsString::from(p.get_name())) |
| 443 |
.help(p.get_help().cloned()) |
| 444 |
.hide(p.is_hide_set()) |
| 445 |
}) |
| 446 |
.collect() |
| 447 |
} |
| 448 |
|
| 449 |
/// Create [`CompletionCandidate`]s for [`clap::builder::PossibleValue`] |
| 450 |
/// |
| 451 |
/// This is implicitly applied for arguments with either a [`clap::builder::PossibleValuesParser`] or [`clap::builder::EnumValueParser`]. |
| 452 |
/// |
| 453 |
/// Using this explicitly is intended for arguments that also accept other value formats that need |
| 454 |
/// to be completed and the completer is lazy ([`ValueCompleter`]). |
| 455 |
/// For eager completion, see [`possible_value_candidates`]. |
| 456 |
pub fn complete_possible_values( |
| 457 |
value: &OsStr, |
| 458 |
values: impl IntoIterator<Item = clap::builder::PossibleValue>, |
| 459 |
) -> Vec<CompletionCandidate> { |
| 460 |
let mut values = possible_value_candidates(values); |
| 461 |
values.retain(|comp| comp.get_value().starts_with(&value.to_string_lossy())); |
| 462 |
values |
| 463 |
} |