Skip to content

Commit

Permalink
feat(clap_complete): Support to complete custom value of argument
Browse files Browse the repository at this point in the history
  • Loading branch information
shannmu committed Aug 7, 2024
1 parent 018ae6c commit 9410401
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ string = ["clap_builder/string"] # Allow runtime generated strings

# In-work features
unstable-v5 = ["clap_builder/unstable-v5", "clap_derive?/unstable-v5", "deprecated"]
unstable-ext = []
unstable-ext = ["clap_builder/unstable-ext"]
unstable-styles = ["clap_builder/unstable-styles"] # deprecated

[lib]
Expand Down
2 changes: 1 addition & 1 deletion clap_complete/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ required-features = ["unstable-dynamic"]
[features]
default = []
unstable-doc = ["unstable-dynamic"] # for docs.rs
unstable-dynamic = ["dep:clap_lex", "dep:shlex", "dep:unicode-xid", "clap/derive", "dep:is_executable", "dep:pathdiff"]
unstable-dynamic = ["dep:clap_lex", "dep:shlex", "dep:unicode-xid", "clap/derive", "dep:is_executable", "dep:pathdiff", "clap/unstable-ext"]
debug = ["clap/debug"]

[lints]
Expand Down
87 changes: 86 additions & 1 deletion clap_complete/src/dynamic/completer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use core::num;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::sync::Arc;

use clap::builder::ArgExt;
use clap::builder::StyledStr;
use clap_lex::OsStrExt as _;

Expand Down Expand Up @@ -385,6 +386,10 @@ fn complete_arg_value(
values.extend(complete_path(value_os, current_dir, |_| true));
}
}

// Add custom completion at the same level as the ValueHint.
values.extend(complete_custom_arg_value(value_os, arg));

values.sort();
}

Expand Down Expand Up @@ -442,6 +447,20 @@ fn complete_path(
completions
}

fn complete_custom_arg_value(value: &OsStr, arg: &clap::Arg) -> Vec<CompletionCandidate> {
let mut values = Vec::new();
debug!("complete_custom_arg_value: arg={arg:?}, value={value:?}");

if let Some(completer) = arg.get::<ArgValueCompleter>() {
let custom_arg_values = completer.0.completions();
values.extend(custom_arg_values);
}

values.retain(|comp| comp.get_content().starts_with(&value.to_string_lossy()));

values
}

fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandidate> {
debug!(
"complete_subcommand: cmd={:?}, value={:?}",
Expand Down Expand Up @@ -704,3 +723,69 @@ impl CompletionCandidate {
self.visible
}
}

/// This trait is used to provide users a way to add custom value hint to the argument.
/// This is useful when predefined value hints are not enough.
pub trait CustomCompleter: core::fmt::Debug + Send + Sync {
/// This method should return a list of custom value completions.
/// If there is no completion, it should return `vec![]`.
///
/// See [`CompletionCandidate`] for more information.
fn completions(&self) -> Vec<CompletionCandidate>;
}

/// A wrapper for custom completer
///
/// # Example
///
/// ```rust
/// use clap_complete::dynamic::{ArgValueCompleter, CustomCompleter};
/// use clap_complete::dynamic::CompletionCandidate;
/// use std::ffi::OsString;
///
/// #[derive(Debug)]
/// struct MyCustomCompleter {
/// file: std::path::PathBuf,
/// }
///
/// impl CustomCompleter for MyCustomCompleter {
/// fn completions(&self) -> Vec<CompletionCandidate> {
/// let content = std::fs::read_to_string(&self.file);
/// match content {
/// Ok(content) => {
/// content.lines().map(|os| CompletionCandidate::new(os).visible(true)).collect()
/// }
/// Err(_) => vec![],
/// }
/// }
/// }
///
/// fn main() {
/// let completer = ArgValueCompleter::new(MyCustomCompleter{
/// file: std::path::PathBuf::from("/path/to/file"),
/// });
///
/// // TODO: Need to implement this command by using derive API.
/// // This is just a placeholder to show how to add custom completer.
/// let mut cmd = clap::Command::new("dynamic").arg(
/// clap::Arg::new("custom")
/// .long("custom")
/// .add(completer),
/// );
/// }
///
/// ```
#[derive(Debug, Clone)]
pub struct ArgValueCompleter(Arc<dyn CustomCompleter>);

impl ArgValueCompleter {
/// Create a new `ArgValueCompleter` with a custom completer
pub fn new<C: CustomCompleter>(completer: C) -> Self
where
C: 'static + CustomCompleter,
{
Self(Arc::new(completer))
}
}

impl ArgExt for ArgValueCompleter {}
29 changes: 27 additions & 2 deletions clap_complete/tests/testsuite/dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fs;
use std::path::Path;

use clap::{builder::PossibleValue, Command};
use clap_complete::dynamic::{ArgValueCompleter, CompletionCandidate, CustomCompleter};
use snapbox::assert_data_eq;

macro_rules! complete {
Expand Down Expand Up @@ -592,9 +593,33 @@ val3

#[test]
fn suggest_custom_arg_value() {
let mut cmd = Command::new("dynamic").arg(clap::Arg::new("custom").long("custom"));
#[derive(Debug)]
struct MyCustomCompleter {}

impl CustomCompleter for MyCustomCompleter {
fn completions(&self) -> Vec<CompletionCandidate> {
vec![
CompletionCandidate::new("custom1"),
CompletionCandidate::new("custom2"),
CompletionCandidate::new("custom3"),
]
}
}

let mut cmd = Command::new("dynamic").arg(
clap::Arg::new("custom")
.long("custom")
.add::<ArgValueCompleter>(ArgValueCompleter::new(MyCustomCompleter {})),
);

assert_data_eq!(complete!(cmd, "--custom [TAB]"), snapbox::str![""],);
assert_data_eq!(
complete!(cmd, "--custom [TAB]"),
snapbox::str![
"custom1
custom2
custom3"
],
);
}

#[test]
Expand Down

0 comments on commit 9410401

Please sign in to comment.