Skip to content
Myr

use custom --path-separator in arguments to --exec

Before adoption: this commit came in with the history the project adopted, so no landing records it.

When --path-separator is used, pass it on to commands run with --exec(-batch) and --list-details. On Windows, paths with drive letters (C:\foo) and UNC paths (\\server\share\path) are handled as expected, though they're unlikely to be found in normal usage of fd.

authored by Allen Wild · committed by David Peter · parent b8089f8 · Browse files · 4 files+233 added−31 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Fixes: https://github.com/sharkdp/fd/issues/697

Diff stats

4 files+233 added−31 removed

  • tests:+79 added−0 removed
  • other:+154 added−31 removed

4 files+233 added−31 removed

modified:src/exec/mod.rs+148 added-28 removed
1 unmodified line
2mod input;3mod job;4mod token;56use std::ffi::OsString;7use std::path::{Path, PathBuf};6use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::path::{Component, Path, PathBuf, Prefix};9use std::process::{Command, Stdio};10use std::sync::{Arc, Mutex};1112use anyhow::{anyhow, Result};
24 unmodified lines
37#[derive(Debug, Clone, PartialEq)]38pub struct CommandTemplate {39 args: Vec<ArgumentTemplate>,40 mode: ExecutionMode,41 path_separator: Option<String>,42}4344impl CommandTemplate {43 pub fn new<I, S>(input: I) -> CommandTemplate45 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate46 where47 I: IntoIterator<Item = S>,48 S: AsRef<str>,49 {48 Self::build(input, ExecutionMode::OneByOne)50 Self::build(input, ExecutionMode::OneByOne, path_separator)51 }5251 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate>53 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>54 where55 I: IntoIterator<Item = S>,56 S: AsRef<str>,57 {56 let cmd = Self::build(input, ExecutionMode::Batch);58 let cmd = Self::build(input, ExecutionMode::Batch, path_separator);59 if cmd.number_of_tokens() > 1 {60 return Err(anyhow!("Only one placeholder allowed for batch commands"));61 }62 if cmd.args[0].has_tokens() {
3 unmodified lines
66 }67 Ok(cmd)68 }6968 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate70 fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate71 where72 I: IntoIterator<Item = S>,73 S: AsRef<str>,74 {
48 unmodified lines
123 if !has_placeholder {124 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));125 }126125 CommandTemplate { args, mode }127 CommandTemplate {128 args,129 mode,130 path_separator,131 }132 }133134 fn number_of_tokens(&self) -> usize {135 self.args.iter().filter(|arg| arg.has_tokens()).count()
5 unmodified lines
141 /// build. Once all arguments have been processed, the command is executed.142 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {143 let input = strip_current_dir(input);144139 let mut cmd = Command::new(self.args[0].generate(&input));145 let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));146 for arg in &self.args[1..] {141 cmd.arg(arg.generate(&input));147 cmd.arg(arg.generate(&input, self.path_separator.as_deref()));148 }149150 execute_command(cmd, &out_perm)151 }
5 unmodified lines
157 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode158 where159 I: Iterator<Item = PathBuf>,160 {155 let mut cmd = Command::new(self.args[0].generate(""));161 let mut cmd = Command::new(self.args[0].generate("", None));162 cmd.stdin(Stdio::inherit());163 cmd.stdout(Stdio::inherit());164 cmd.stderr(Stdio::inherit());165
6 unmodified lines
172173 // A single `Tokens` is expected174 // So we can directly consume the iterator once and for all175 for path in &mut paths {170 cmd.arg(arg.generate(strip_current_dir(path)));176 cmd.arg(arg.generate(strip_current_dir(path), self.path_separator.as_deref()));177 has_path = true;178 }179 } else {174 cmd.arg(arg.generate(""));180 cmd.arg(arg.generate("", None));181 }182 }183184 if has_path {
21 unmodified lines
206 _ => false,207 }208 }209210 /// Generate an argument from this template. If path_separator is Some, then it will replace211 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by212 /// path separator substitution.204 pub fn generate(&self, path: impl AsRef<Path>) -> OsString {213 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {214 use self::Token::*;215 let path = path.as_ref();216217 match *self {218 ArgumentTemplate::Tokens(ref tokens) => {219 let mut s = OsString::new();220 for token in tokens {221 match *token {212 Basename => s.push(basename(path.as_ref())),213 BasenameNoExt => {214 s.push(remove_extension(&PathBuf::from(basename(path.as_ref()))))222 Basename => s.push(Self::replace_separator(basename(path), path_separator)),223 BasenameNoExt => s.push(Self::replace_separator(224 &remove_extension(basename(path).as_ref()),225 path_separator,226 )),227 NoExt => s.push(Self::replace_separator(228 &remove_extension(path),229 path_separator,230 )),231 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),232 Placeholder => {233 s.push(Self::replace_separator(path.as_ref(), path_separator))234 }216 NoExt => s.push(remove_extension(path.as_ref())),217 Parent => s.push(dirname(path.as_ref())),218 Placeholder => s.push(path.as_ref()),235 Text(ref string) => s.push(string),236 }237 }238 s239 }240 ArgumentTemplate::Text(ref text) => OsString::from(text),241 }242 }243244 /// Replace the path separator in the input with the custom separator string. If path_separator245 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is246 /// interpreted as a Path and its components are iterated through and re-joined into a new247 /// OsString.248 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {249 // fast-path - no replacement necessary250 if path_separator.is_none() {251 return Cow::Borrowed(path);252 }253254 let path_separator = path_separator.unwrap();255 let mut out = OsString::with_capacity(path.len());256 let mut components = Path::new(path).components().peekable();257258 while let Some(comp) = components.next() {259 match comp {260 // Absolute paths on Windows are tricky. A Prefix component is usually a drive261 // letter or UNC path, and is usually followed by RootDir. There are also262 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to263 // ignore verbatim path prefixes here because they're very rare, might be264 // impossible to reach here, and there's no good way to deal with them. If users265 // are doing something advanced involving verbatim windows paths, they can do their266 // own output filtering with a tool like sed.267 Component::Prefix(prefix) => {268 if let Prefix::UNC(server, share) = prefix.kind() {269 // Prefix::UNC is a parsed version of '\\server\share'270 out.push(path_separator);271 out.push(path_separator);272 out.push(server);273 out.push(path_separator);274 out.push(share);275 } else {276 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for277 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,278 // but they're not returned by directories fd can search anyway so we don't worry279 // about them.280 out.push(comp.as_os_str());281 }282 }283284 // Root directory is always replaced with the custom separator.285 Component::RootDir => out.push(path_separator),286287 // Everything else is joined normally, with a trailing separator if we're not last288 _ => {289 out.push(comp.as_os_str());290 if components.peek().is_some() {291 out.push(path_separator);292 }293 }294 }295 }296 Cow::Owned(out)297 }298}299300#[cfg(test)]301mod tests {
1 unmodified line
303304 #[test]305 fn tokens_with_placeholder() {306 assert_eq!(236 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),307 CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),308 CommandTemplate {309 args: vec![310 ArgumentTemplate::Text("echo".into()),311 ArgumentTemplate::Text("${SHELL}:".into()),312 ArgumentTemplate::Tokens(vec![Token::Placeholder]),313 ],314 mode: ExecutionMode::OneByOne,315 path_separator: None,316 }317 );318 }319320 #[test]321 fn tokens_with_no_extension() {322 assert_eq!(251 CommandTemplate::new(&["echo", "{.}"]),323 CommandTemplate::new(&["echo", "{.}"], None),324 CommandTemplate {325 args: vec![326 ArgumentTemplate::Text("echo".into()),327 ArgumentTemplate::Tokens(vec![Token::NoExt]),328 ],329 mode: ExecutionMode::OneByOne,330 path_separator: None,331 }332 );333 }334335 #[test]336 fn tokens_with_basename() {337 assert_eq!(265 CommandTemplate::new(&["echo", "{/}"]),338 CommandTemplate::new(&["echo", "{/}"], None),339 CommandTemplate {340 args: vec![341 ArgumentTemplate::Text("echo".into()),342 ArgumentTemplate::Tokens(vec![Token::Basename]),343 ],344 mode: ExecutionMode::OneByOne,345 path_separator: None,346 }347 );348 }349350 #[test]351 fn tokens_with_parent() {352 assert_eq!(279 CommandTemplate::new(&["echo", "{//}"]),353 CommandTemplate::new(&["echo", "{//}"], None),354 CommandTemplate {355 args: vec![356 ArgumentTemplate::Text("echo".into()),357 ArgumentTemplate::Tokens(vec![Token::Parent]),358 ],359 mode: ExecutionMode::OneByOne,360 path_separator: None,361 }362 );363 }364365 #[test]366 fn tokens_with_basename_no_extension() {367 assert_eq!(293 CommandTemplate::new(&["echo", "{/.}"]),368 CommandTemplate::new(&["echo", "{/.}"], None),369 CommandTemplate {370 args: vec![371 ArgumentTemplate::Text("echo".into()),372 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),373 ],374 mode: ExecutionMode::OneByOne,375 path_separator: None,376 }377 );378 }379380 #[test]381 fn tokens_multiple() {382 assert_eq!(307 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),383 CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),384 CommandTemplate {385 args: vec![386 ArgumentTemplate::Text("cp".into()),387 ArgumentTemplate::Tokens(vec![Token::Placeholder]),
2 unmodified lines
390 Token::Text(".ext".into())391 ]),392 ],393 mode: ExecutionMode::OneByOne,394 path_separator: None,395 }396 );397 }398399 #[test]400 fn tokens_single_batch() {401 assert_eq!(325 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),402 CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),403 CommandTemplate {404 args: vec![405 ArgumentTemplate::Text("echo".into()),406 ArgumentTemplate::Tokens(vec![Token::NoExt]),407 ],408 mode: ExecutionMode::Batch,409 path_separator: None,410 }411 );412 }413414 #[test]415 fn tokens_multiple_batch() {338 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());416 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());417 }418419 #[test]420 fn generate_custom_path_separator() {421 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);422 macro_rules! check {423 ($input:expr, $expected:expr) => {424 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));425 };426 }427428 check!("foo", "foo");429 check!("foo/bar", "foo#bar");430 check!("/foo/bar/baz", "#foo#bar#baz");431 }432433 #[cfg(windows)]434 #[test]435 fn generate_custom_path_separator_windows() {436 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);437 macro_rules! check {438 ($input:expr, $expected:expr) => {439 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));440 };441 }442443 // path starting with a drive letter444 check!(r"C:\foo\bar", "C:#foo#bar");445 // UNC path446 check!(r"\\server\share\path", "##server#share#path");447 // Drive Relative path - no separator after the colon omits the RootDir path component.448 // This is uncommon, but valid449 check!(r"C:foo\bar", "C:foo#bar");450451 // forward slashses should get normalized and interpreted as separators452 check!("C:/foo/bar", "C:#foo#bar");453 check!("C:foo/bar", "C:foo#bar");454455 // Rust does not intrepret "//server/share" as a UNC path, but rather as a normal456 // absolute path that begins with RootDir, and the two slashes get combined together as457 // a single path separator during normalization.458 //check!("//server/share/path", "##server#share#path");459 }460}
modified:src/main.rs+3 added-3 removed
180 unmodified lines
181 None182 };183184 let command = if let Some(args) = matches.values_of("exec") {185 Some(CommandTemplate::new(args))185 Some(CommandTemplate::new(args, path_separator.clone()))186 } else if let Some(args) = matches.values_of("exec-batch") {187 Some(CommandTemplate::new_batch(args)?)187 Some(CommandTemplate::new_batch(args, path_separator.clone())?)188 } else if matches.is_present("list-details") {189 let color = matches.value_of("color").unwrap_or("auto");190 let color_arg = ["--color=", color].concat();191
71 unmodified lines
263 "'fd --list-details' is not supported on this platform."264 ));265 };266267 Some(CommandTemplate::new_batch(&cmd).unwrap())267 Some(CommandTemplate::new_batch(&cmd, path_separator.clone()).unwrap())268 } else {269 None270 };271
201 unmodified lines
modified:tests/tests.rs+79 added
1335 unmodified lines
1336 );1337 }1338}13391340/// Shell script execution (--exec) with a custom --path-separator1341#[test]1342fn test_exec_with_separator() {1343 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1344 te.assert_output(1345 &[1346 "--path-separator=#",1347 "--absolute-path",1348 "foo",1349 "--exec",1350 "echo",1351 ],1352 &format!(1353 "{abs_path}#a.foo1354 {abs_path}#one#b.foo1355 {abs_path}#one#two#C.Foo21356 {abs_path}#one#two#c.foo1357 {abs_path}#one#two#three#d.foo1358 {abs_path}#one#two#three#directory_foo",1359 abs_path = abs_path.replace(std::path::MAIN_SEPARATOR, "#"),1360 ),1361 );13621363 te.assert_output(1364 &["--path-separator=#", "foo", "--exec", "echo", "{}"],1365 "a.foo1366 one#b.foo1367 one#two#C.Foo21368 one#two#c.foo1369 one#two#three#d.foo1370 one#two#three#directory_foo",1371 );13721373 te.assert_output(1374 &["--path-separator=#", "foo", "--exec", "echo", "{.}"],1375 "a1376 one#b1377 one#two#C1378 one#two#c1379 one#two#three#d1380 one#two#three#directory_foo",1381 );13821383 te.assert_output(1384 &["--path-separator=#", "foo", "--exec", "echo", "{/}"],1385 "a.foo1386 b.foo1387 C.Foo21388 c.foo1389 d.foo1390 directory_foo",1391 );13921393 te.assert_output(1394 &["--path-separator=#", "foo", "--exec", "echo", "{/.}"],1395 "a1396 b1397 C1398 c1399 d1400 directory_foo",1401 );14021403 te.assert_output(1404 &["--path-separator=#", "foo", "--exec", "echo", "{//}"],1405 ".1406 one1407 one#two1408 one#two1409 one#two#three1410 one#two#three",1411 );14121413 te.assert_output(1414 &["--path-separator=#", "e1", "--exec", "printf", "%s.%s\n"],1415 "e1 e2.",1416 );1417}14181419/// Literal search (--fixed-strings)1420#[test]1421fn test_fixed_strings() {1422 let dirs = &["test1", "test2"];
373 unmodified lines
modified:CHANGELOG.md+3 added
1 unmodified line
23## Features4## Bugfixes5## Changes67- Apply custom `--path-separator` to commands run with `--exec(-batch)` and `--list-details`, see #69789## Other1011# v8.2.112
502 unmodified lines