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