Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions clap_complete/src/engine/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ pub struct PathCompleter {
#[allow(clippy::type_complexity)]
filter: Option<Box<dyn Fn(&std::path::Path) -> bool + Send + Sync>>,
stdio: bool,
#[allow(clippy::type_complexity)]
mapper: Option<Box<dyn Fn(CompletionCandidate) -> CompletionCandidate + Send + Sync>>,
}

impl PathCompleter {
Expand All @@ -225,6 +227,7 @@ impl PathCompleter {
filter: None,
current_dir: None,
stdio: false,
mapper: None,
}
}

Expand Down Expand Up @@ -253,6 +256,15 @@ impl PathCompleter {
self
}

/// Transform completion candidates after filtering
pub fn map(
mut self,
mapper: impl Fn(CompletionCandidate) -> CompletionCandidate + Send + Sync + 'static,
) -> Self {
self.mapper = Some(Box::new(mapper));
self
}

/// Override [`std::env::current_dir`]
pub fn current_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
self.current_dir = Some(path.into());
Expand All @@ -275,6 +287,12 @@ impl ValueCompleter for PathCompleter {
current_dir_actual.as_deref()
});
let mut candidates = complete_path(current, current_dir, filter);
if let Some(mapper) = &self.mapper {
candidates = candidates
.into_iter()
.map(|candidate| mapper(candidate))
.collect();
}
if self.stdio && current.is_empty() {
candidates.push(CompletionCandidate::new("-").help(Some("stdio".into())));
}
Expand Down
94 changes: 94 additions & 0 deletions clap_complete/tests/testsuite/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1191,3 +1191,97 @@ fn complete(cmd: &mut Command, args: impl AsRef<str>, current_dir: Option<&Path>
.collect::<Vec<_>>()
.join("\n")
}

#[test]
fn suggest_value_path_with_filter_and_mapper() {
Comment on lines +1195 to +1196
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intention of the split commits was for this test to overwrite the suggest_value_path_without_mapper, showing the change in behavior. Only the call to map and output should change in this commit.

Copy link
Author

@Gmin2 Gmin2 Mar 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in this and added an additional test mentioned here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All test additions should be done in the first commit

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So @epage, i should do that same as i did for suggest_value_path_with_mapper (in the first commit showing the behaviour without mapper and then showing the behaviour with mapper right ?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

let testdir = snapbox::dir::DirRoot::mutable_temp().unwrap();
let testdir_path = testdir.path().unwrap();
fs::write(testdir_path.join("a_file"), "").unwrap();
fs::write(testdir_path.join("b_file"), "").unwrap();
fs::create_dir_all(testdir_path.join("c_dir")).unwrap();
fs::create_dir_all(testdir_path.join("d_dir")).unwrap();

fs::write(testdir_path.join("c_dir").join("Cargo.toml"), "").unwrap();

let mut cmd = Command::new("dynamic")
.arg(
clap::Arg::new("input")
.long("input")
.short('i')
.add(ArgValueCompleter::new(
PathCompleter::dir()
.current_dir(testdir_path.to_owned())
.filter(|path| {
path.file_name()
.and_then(|n| n.to_str())
.map_or(false, |name| name.starts_with('c'))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you ran clippy on this, it would complain about the use of map_or. CI isn't catching it because we aren't running it on unstable features from non-default packages.

})
.map(|candidate| {
if candidate.get_value().to_string_lossy().contains("c_dir") {
candidate
.help(Some("Addable cargo package".into()))
.display_order(Some(0))
} else {
candidate.display_order(Some(1))
Comment on lines +1224 to +1225
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this this being done? display order should be taken care of

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the display_order in the else branch ensures that c_dir comes first, if i dont include display_order() in the else branch it does not sort it properly

---- expected: tests/testsuite/engine.rs:1232:9
++++ actual:   In-memory
   1      - c_dir/      Addable cargo package
   2      - d_dir/∅
        1 + .
        2 + d_dir/
        3 + c_dir/      Addable cargo package∅

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we filtered out d_dir, then it should be last. If it isn't, something else is going on and should be investigated and fixed.

}
}),
)),
)
.args_conflicts_with_subcommands(true);

assert_data_eq!(
complete!(cmd, "--input [TAB]", current_dir = Some(testdir_path)),
snapbox::str![[r#"
c_dir/ Addable cargo package
d_dir/
"#]],
);
}

#[test]
fn suggest_value_file_path_with_mapper() {
let testdir = snapbox::dir::DirRoot::mutable_temp().unwrap();
let testdir_path = testdir.path().unwrap();
fs::write(testdir_path.join("a_file.txt"), "").unwrap();
fs::write(testdir_path.join("b_file.md"), "").unwrap();
fs::write(testdir_path.join("c_file.rs"), "").unwrap();
fs::create_dir_all(testdir_path.join("d_dir")).unwrap();

let mut cmd = Command::new("dynamic")
.arg(
clap::Arg::new("input")
.long("input")
.short('i')
.add(ArgValueCompleter::new(
PathCompleter::file()
.current_dir(testdir_path.to_owned())
.map(|candidate| {
let path = Path::new(candidate.get_value());
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
match ext {
"rs" => candidate
.help(Some("Rust source file".into()))
.display_order(Some(0)),
"txt" => candidate
.help(Some("Text file".into()))
.display_order(Some(1)),
_ => candidate.display_order(Some(2))
}
} else {
candidate.display_order(Some(3))
}
}),
)),
)
.args_conflicts_with_subcommands(true);

assert_data_eq!(
complete!(cmd, "--input [TAB]", current_dir = Some(testdir_path)),
snapbox::str![[r#"
c_file.rs Rust source file
a_file.txt Text file
b_file.md
d_dir/
"#]],
);
}