Skip to content
Myr

Implement option for printing custom formats

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

authored by Thayne McCombs · committed by Thayne McCombs · parent 6becb66 · Browse files · 12 files+528 added−353 removed
This commit

State

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

Diff stats

12 files+528 added−353 removed

  • tests:+60 added−0 removed
  • other:+468 added−353 removed

12 files+528 added−353 removed

modified:doc/fd.1+30 added-33 removed
373 unmodified lines
374.BI "\-\-search\-path " search\-path375Provide paths to search as an alternative to the positional \fIpath\fR argument. Changes the usage to376\'fd [FLAGS/OPTIONS] \-\-search\-path PATH \-\-search\-path PATH2 [PATTERN]\'377.TP378.BI "\-\-format " fmt379Specify a template string that is used for printing a line for each file found.380381The following placeholders are substituted into the string for each file before printing:382.RS383.IP {}384path (of the current search result)385.IP {/}386basename387.IP {//}388parent directory389.IP {.}390path without file extension391.IP {/.}392basename without file extension393.IP {{394literal '{' (an escape sequence)395.IP }}396literal '}' (an escape sequence)397.P398Notice that you can use "{{" and "}}" to escape "{" and "}" respectively, which is especially399useful if you need to include the literal text of one of the above placeholders.400.RE401.TP402.BI "\-x, \-\-exec " command403.RS404Execute405.I command
12 unmodified lines
418If parallelism is enabled, the order commands will be executed in is non-deterministic. And even with419--threads=1, the order is determined by the operating system and may not be what you expect. Thus, it is420recommended that you don't rely on any ordering of the results.421398The following placeholders are substituted before the command is executed:399.RS400.IP {}401path (of the current search result)402.IP {/}403basename404.IP {//}405parent directory406.IP {.}407path without file extension408.IP {/.}409basename without file extension410.IP {{411literal '{' (an escape sequence)412.IP }}413literal '}' (an escape sequence)414.RE422Before executing the command, any placeholder patterns in the command are replaced with the423corresponding values for the current file. The same placeholders are used as in the "\-\-format"424option.425426If no placeholder is present, an implicit "{}" at the end is assumed.427418Notice that you can use "{{" and "}}" to escape "{" and "}" respectively, which is especially419useful if you need to include the literal text of one of the above placeholders.420428Examples:429430 - find all *.zip files and unzip them:431
15 unmodified lines
447once, with all search results as arguments.448449The order of the arguments is non-deterministic and should not be relied upon.450444One of the following placeholders is substituted before the command is executed:445.RS446.IP {}447path (of all search results)448.IP {/}449basename450.IP {//}451parent directory452.IP {.}453path without file extension454.IP {/.}455basename without file extension456.RE451This uses the same placeholders as "\-\-format" and "\-\-exec", but instead of expanding452once per command invocation each argument containing a placeholder is expanding for every453file in a batch and passed as separate arguments.454455If no placeholder is present, an implicit "{}" at the end is assumed.456457Like \-\-exec, this can be used multiple times, in which case each command will be run in
82 unmodified lines
deleted:src/exec/input.rs-87 removed
1use std::ffi::{OsStr, OsString};2use std::path::{Path, PathBuf};34use crate::filesystem::strip_current_dir;56/// Removes the parent component of the path7pub fn basename(path: &Path) -> &OsStr {8 path.file_name().unwrap_or(path.as_os_str())9}1011/// Removes the extension from the path12pub fn remove_extension(path: &Path) -> OsString {13 let dirname = dirname(path);14 let stem = path.file_stem().unwrap_or(path.as_os_str());1516 let path = PathBuf::from(dirname).join(stem);1718 strip_current_dir(&path).to_owned().into_os_string()19}2021/// Removes the basename from the path.22pub fn dirname(path: &Path) -> OsString {23 path.parent()24 .map(|p| {25 if p == OsStr::new("") {26 OsString::from(".")27 } else {28 p.as_os_str().to_owned()29 }30 })31 .unwrap_or_else(|| path.as_os_str().to_owned())32}3334#[cfg(test)]35mod path_tests {36 use super::*;37 use std::path::MAIN_SEPARATOR_STR;3839 fn correct(input: &str) -> String {40 input.replace('/', MAIN_SEPARATOR_STR)41 }4243 macro_rules! func_tests {44 ($($name:ident: $func:ident for $input:expr => $output:expr)+) => {45 $(46 #[test]47 fn $name() {48 let input_path = PathBuf::from(&correct($input));49 let output_string = OsString::from(correct($output));50 assert_eq!($func(&input_path), output_string);51 }52 )+53 }54 }5556 func_tests! {57 remove_ext_simple: remove_extension for "foo.txt" => "foo"58 remove_ext_dir: remove_extension for "dir/foo.txt" => "dir/foo"59 hidden: remove_extension for ".foo" => ".foo"60 remove_ext_utf8: remove_extension for "💖.txt" => "💖"61 remove_ext_empty: remove_extension for "" => ""6263 basename_simple: basename for "foo.txt" => "foo.txt"64 basename_dir: basename for "dir/foo.txt" => "foo.txt"65 basename_empty: basename for "" => ""66 basename_utf8_0: basename for "💖/foo.txt" => "foo.txt"67 basename_utf8_1: basename for "dir/💖.txt" => "💖.txt"6869 dirname_simple: dirname for "foo.txt" => "."70 dirname_dir: dirname for "dir/foo.txt" => "dir"71 dirname_utf8_0: dirname for "💖/foo.txt" => "💖"72 dirname_utf8_1: dirname for "dir/💖.txt" => "dir"73 }7475 #[test]76 #[cfg(windows)]77 fn dirname_root() {78 assert_eq!(dirname(&PathBuf::from("C:")), OsString::from("C:"));79 assert_eq!(dirname(&PathBuf::from("\\")), OsString::from("\\"));80 }8182 #[test]83 #[cfg(not(windows))]84 fn dirname_root() {85 assert_eq!(dirname(&PathBuf::from("/")), OsString::from("/"));86 }87}
modified:src/exec/mod.rs+25 added-134 removed
1mod command;2mod input;2mod job;4mod token;36use std::borrow::Cow;7use std::ffi::{OsStr, OsString};4use std::ffi::OsString;5use std::io;6use std::iter;10use std::path::{Component, Path, PathBuf, Prefix};7use std::path::{Path, PathBuf};8use std::process::Stdio;9use std::sync::Mutex;1011use anyhow::{bail, Result};12use argmax::Command;1314use crate::exit_codes::{merge_exitcodes, ExitCode};15use crate::fmt::{FormatTemplate, Token};1617use self::command::{execute_commands, handle_cmd_error};20use self::input::{basename, dirname, remove_extension};18pub use self::job::{batch, job};22use self::token::{tokenize, Token};1920/// Execution mode of the command21#[derive(Debug, Clone, Copy, PartialEq, Eq)]22pub enum ExecutionMode {
103 unmodified lines
126/// Represents a multi-exec command as it is built.127#[derive(Debug)]128struct CommandBuilder {129 pre_args: Vec<OsString>,134 path_arg: ArgumentTemplate,130 path_arg: FormatTemplate,131 post_args: Vec<OsString>,132 cmd: Command,133 count: usize,134 limit: usize,
80 unmodified lines
215/// The template is meant to be coupled with an input in order to generate a command. The216/// `generate_and_execute()` method will be used to generate a command and execute it.217#[derive(Debug, Clone, PartialEq)]218struct CommandTemplate {223 args: Vec<ArgumentTemplate>,219 args: Vec<FormatTemplate>,220}221222impl CommandTemplate {223 fn new<I, S>(input: I) -> Result<CommandTemplate>
6 unmodified lines
230231 for arg in input {232 let arg = arg.as_ref();233238 let tmpl = tokenize(arg);234 let tmpl = FormatTemplate::parse(arg);235 has_placeholder |= tmpl.has_tokens();236 args.push(tmpl);237 }238
7 unmodified lines
246 }247248 // If a placeholder token was not supplied, append one at the end of the command.249 if !has_placeholder {254 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));250 args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));251 }252253 Ok(CommandTemplate { args })254 }
14 unmodified lines
269 Ok(cmd)270 }271}272277/// Represents a template for a single command argument.278///279/// The argument is either a collection of `Token`s including at least one placeholder variant, or280/// a fixed text.281#[derive(Clone, Debug, PartialEq)]282enum ArgumentTemplate {283 Tokens(Vec<Token>),284 Text(String),285}286287impl ArgumentTemplate {288 pub fn has_tokens(&self) -> bool {289 matches!(self, ArgumentTemplate::Tokens(_))290 }291292 /// Generate an argument from this template. If path_separator is Some, then it will replace293 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by294 /// path separator substitution.295 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {296 use self::Token::*;297 let path = path.as_ref();298299 match *self {300 ArgumentTemplate::Tokens(ref tokens) => {301 let mut s = OsString::new();302 for token in tokens {303 match *token {304 Basename => s.push(Self::replace_separator(basename(path), path_separator)),305 BasenameNoExt => s.push(Self::replace_separator(306 &remove_extension(basename(path).as_ref()),307 path_separator,308 )),309 NoExt => s.push(Self::replace_separator(310 &remove_extension(path),311 path_separator,312 )),313 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),314 Placeholder => {315 s.push(Self::replace_separator(path.as_ref(), path_separator))316 }317 Text(ref string) => s.push(string),318 }319 }320 s321 }322 ArgumentTemplate::Text(ref text) => OsString::from(text),323 }324 }325326 /// Replace the path separator in the input with the custom separator string. If path_separator327 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is328 /// interpreted as a Path and its components are iterated through and re-joined into a new329 /// OsString.330 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {331 // fast-path - no replacement necessary332 if path_separator.is_none() {333 return Cow::Borrowed(path);334 }335336 let path_separator = path_separator.unwrap();337 let mut out = OsString::with_capacity(path.len());338 let mut components = Path::new(path).components().peekable();339340 while let Some(comp) = components.next() {341 match comp {342 // Absolute paths on Windows are tricky. A Prefix component is usually a drive343 // letter or UNC path, and is usually followed by RootDir. There are also344 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to345 // ignore verbatim path prefixes here because they're very rare, might be346 // impossible to reach here, and there's no good way to deal with them. If users347 // are doing something advanced involving verbatim windows paths, they can do their348 // own output filtering with a tool like sed.349 Component::Prefix(prefix) => {350 if let Prefix::UNC(server, share) = prefix.kind() {351 // Prefix::UNC is a parsed version of '\\server\share'352 out.push(path_separator);353 out.push(path_separator);354 out.push(server);355 out.push(path_separator);356 out.push(share);357 } else {358 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for359 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,360 // but they're not returned by directories fd can search anyway so we don't worry361 // about them.362 out.push(comp.as_os_str());363 }364 }365366 // Root directory is always replaced with the custom separator.367 Component::RootDir => out.push(path_separator),368369 // Everything else is joined normally, with a trailing separator if we're not last370 _ => {371 out.push(comp.as_os_str());372 if components.peek().is_some() {373 out.push(path_separator);374 }375 }376 }377 }378 Cow::Owned(out)379 }380}381273#[cfg(test)]274mod tests {275 use super::*;276
11 unmodified lines
288 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),289 CommandSet {290 commands: vec![CommandTemplate {291 args: vec![401 ArgumentTemplate::Text("echo".into()),402 ArgumentTemplate::Text("${SHELL}:".into()),403 ArgumentTemplate::Tokens(vec![Token::Placeholder]),292 FormatTemplate::Text("echo".into()),293 FormatTemplate::Text("${SHELL}:".into()),294 FormatTemplate::Tokens(vec![Token::Placeholder]),295 ]296 }],297 mode: ExecutionMode::OneByOne,298 }
6 unmodified lines
305 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),306 CommandSet {307 commands: vec![CommandTemplate {308 args: vec![418 ArgumentTemplate::Text("echo".into()),419 ArgumentTemplate::Tokens(vec![Token::NoExt]),309 FormatTemplate::Text("echo".into()),310 FormatTemplate::Tokens(vec![Token::NoExt]),311 ],312 }],313 mode: ExecutionMode::OneByOne,314 }
6 unmodified lines
321 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),322 CommandSet {323 commands: vec![CommandTemplate {324 args: vec![434 ArgumentTemplate::Text("echo".into()),435 ArgumentTemplate::Tokens(vec![Token::Basename]),325 FormatTemplate::Text("echo".into()),326 FormatTemplate::Tokens(vec![Token::Basename]),327 ],328 }],329 mode: ExecutionMode::OneByOne,330 }
6 unmodified lines
337 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),338 CommandSet {339 commands: vec![CommandTemplate {340 args: vec![450 ArgumentTemplate::Text("echo".into()),451 ArgumentTemplate::Tokens(vec![Token::Parent]),341 FormatTemplate::Text("echo".into()),342 FormatTemplate::Tokens(vec![Token::Parent]),343 ],344 }],345 mode: ExecutionMode::OneByOne,346 }
6 unmodified lines
353 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),354 CommandSet {355 commands: vec![CommandTemplate {356 args: vec![466 ArgumentTemplate::Text("echo".into()),467 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),357 FormatTemplate::Text("echo".into()),358 FormatTemplate::Tokens(vec![Token::BasenameNoExt]),359 ],360 }],361 mode: ExecutionMode::OneByOne,362 }
21 unmodified lines
384 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),385 CommandSet {386 commands: vec![CommandTemplate {387 args: vec![497 ArgumentTemplate::Text("cp".into()),498 ArgumentTemplate::Tokens(vec![Token::Placeholder]),499 ArgumentTemplate::Tokens(vec![388 FormatTemplate::Text("cp".into()),389 FormatTemplate::Tokens(vec![Token::Placeholder]),390 FormatTemplate::Tokens(vec![391 Token::BasenameNoExt,392 Token::Text(".ext".into())393 ]),394 ],
9 unmodified lines
404 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),405 CommandSet {406 commands: vec![CommandTemplate {407 args: vec![517 ArgumentTemplate::Text("echo".into()),518 ArgumentTemplate::Tokens(vec![Token::NoExt]),408 FormatTemplate::Text("echo".into()),409 FormatTemplate::Tokens(vec![Token::NoExt]),410 ],411 }],412 mode: ExecutionMode::Batch,413 }
16 unmodified lines
430 }431432 #[test]433 fn generate_custom_path_separator() {543 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);434 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);435 macro_rules! check {436 ($input:expr, $expected:expr) => {437 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));438 };
6 unmodified lines
445446 #[cfg(windows)]447 #[test]448 fn generate_custom_path_separator_windows() {558 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);449 let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);450 macro_rules! check {451 ($input:expr, $expected:expr) => {452 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));453 };
20 unmodified lines
deleted:src/exec/token.rs-98 removed
1use aho_corasick::AhoCorasick;2use std::fmt::{self, Display, Formatter};3use std::sync::OnceLock;45use super::ArgumentTemplate;67/// Designates what should be written to a buffer8///9/// Each `Token` contains either text, or a placeholder variant, which will be used to generate10/// commands after all tokens for a given command template have been collected.11#[derive(Clone, Debug, PartialEq, Eq)]12pub enum Token {13 Placeholder,14 Basename,15 Parent,16 NoExt,17 BasenameNoExt,18 Text(String),19}2021impl Display for Token {22 fn fmt(&self, f: &mut Formatter) -> fmt::Result {23 match *self {24 Token::Placeholder => f.write_str("{}")?,25 Token::Basename => f.write_str("{/}")?,26 Token::Parent => f.write_str("{//}")?,27 Token::NoExt => f.write_str("{.}")?,28 Token::BasenameNoExt => f.write_str("{/.}")?,29 Token::Text(ref string) => f.write_str(string)?,30 }31 Ok(())32 }33}3435static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();3637pub(super) fn tokenize(input: &str) -> ArgumentTemplate {38 // NOTE: we assume that { and } have the same length39 const BRACE_LEN: usize = '{'.len_utf8();40 let mut tokens = Vec::new();41 let mut remaining = input;42 let mut buf = String::new();43 let placeholders = PLACEHOLDERS.get_or_init(|| {44 AhoCorasick::new(["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()45 });46 while let Some(m) = placeholders.find(remaining) {47 match m.pattern().as_u32() {48 0 | 1 => {49 // we found an escaped {{ or }}, so add50 // everything up to the first char to the buffer51 // then skip the second one.52 buf += &remaining[..m.start() + BRACE_LEN];53 remaining = &remaining[m.end()..];54 }55 id if !remaining[m.end()..].starts_with('}') => {56 buf += &remaining[..m.start()];57 if !buf.is_empty() {58 tokens.push(Token::Text(std::mem::take(&mut buf)));59 }60 tokens.push(token_from_pattern_id(id));61 remaining = &remaining[m.end()..];62 }63 _ => {64 // We got a normal pattern, but the final "}"65 // is escaped, so add up to that to the buffer, then66 // skip the final }67 buf += &remaining[..m.end()];68 remaining = &remaining[m.end() + BRACE_LEN..];69 }70 }71 }72 // Add the rest of the string to the buffer, and add the final buffer to the tokens73 if !remaining.is_empty() {74 buf += remaining;75 }76 if tokens.is_empty() {77 // No placeholders were found, so just return the text78 return ArgumentTemplate::Text(buf);79 }80 // Add final text segment81 if !buf.is_empty() {82 tokens.push(Token::Text(buf));83 }84 debug_assert!(!tokens.is_empty());85 ArgumentTemplate::Tokens(tokens)86}8788fn token_from_pattern_id(id: u32) -> Token {89 use Token::*;90 match id {91 2 => Placeholder,92 3 => Basename,93 4 => Parent,94 5 => NoExt,95 6 => BasenameNoExt,96 _ => unreachable!(),97 }98}
added:src/fmt/input.rs+87 added
1use std::ffi::{OsStr, OsString};2use std::path::{Path, PathBuf};34use crate::filesystem::strip_current_dir;56/// Removes the parent component of the path7pub fn basename(path: &Path) -> &OsStr {8 path.file_name().unwrap_or(path.as_os_str())9}1011/// Removes the extension from the path12pub fn remove_extension(path: &Path) -> OsString {13 let dirname = dirname(path);14 let stem = path.file_stem().unwrap_or(path.as_os_str());1516 let path = PathBuf::from(dirname).join(stem);1718 strip_current_dir(&path).to_owned().into_os_string()19}2021/// Removes the basename from the path.22pub fn dirname(path: &Path) -> OsString {23 path.parent()24 .map(|p| {25 if p == OsStr::new("") {26 OsString::from(".")27 } else {28 p.as_os_str().to_owned()29 }30 })31 .unwrap_or_else(|| path.as_os_str().to_owned())32}3334#[cfg(test)]35mod path_tests {36 use super::*;37 use std::path::MAIN_SEPARATOR_STR;3839 fn correct(input: &str) -> String {40 input.replace('/', MAIN_SEPARATOR_STR)41 }4243 macro_rules! func_tests {44 ($($name:ident: $func:ident for $input:expr => $output:expr)+) => {45 $(46 #[test]47 fn $name() {48 let input_path = PathBuf::from(&correct($input));49 let output_string = OsString::from(correct($output));50 assert_eq!($func(&input_path), output_string);51 }52 )+53 }54 }5556 func_tests! {57 remove_ext_simple: remove_extension for "foo.txt" => "foo"58 remove_ext_dir: remove_extension for "dir/foo.txt" => "dir/foo"59 hidden: remove_extension for ".foo" => ".foo"60 remove_ext_utf8: remove_extension for "💖.txt" => "💖"61 remove_ext_empty: remove_extension for "" => ""6263 basename_simple: basename for "foo.txt" => "foo.txt"64 basename_dir: basename for "dir/foo.txt" => "foo.txt"65 basename_empty: basename for "" => ""66 basename_utf8_0: basename for "💖/foo.txt" => "foo.txt"67 basename_utf8_1: basename for "dir/💖.txt" => "💖.txt"6869 dirname_simple: dirname for "foo.txt" => "."70 dirname_dir: dirname for "dir/foo.txt" => "dir"71 dirname_utf8_0: dirname for "💖/foo.txt" => "💖"72 dirname_utf8_1: dirname for "dir/💖.txt" => "dir"73 }7475 #[test]76 #[cfg(windows)]77 fn dirname_root() {78 assert_eq!(dirname(&PathBuf::from("C:")), OsString::from("C:"));79 assert_eq!(dirname(&PathBuf::from("\\")), OsString::from("\\"));80 }8182 #[test]83 #[cfg(not(windows))]84 fn dirname_root() {85 assert_eq!(dirname(&PathBuf::from("/")), OsString::from("/"));86 }87}
added:src/fmt/mod.rs+281 added
1mod input;23use std::borrow::Cow;4use std::ffi::{OsStr, OsString};5use std::fmt::{self, Display, Formatter};6use std::path::{Component, Path, Prefix};7use std::sync::OnceLock;89use aho_corasick::AhoCorasick;1011use self::input::{basename, dirname, remove_extension};1213/// Designates what should be written to a buffer14///15/// Each `Token` contains either text, or a placeholder variant, which will be used to generate16/// commands after all tokens for a given command template have been collected.17#[derive(Clone, Debug, PartialEq, Eq)]18pub enum Token {19 Placeholder,20 Basename,21 Parent,22 NoExt,23 BasenameNoExt,24 Text(String),25}2627impl Display for Token {28 fn fmt(&self, f: &mut Formatter) -> fmt::Result {29 match *self {30 Token::Placeholder => f.write_str("{}")?,31 Token::Basename => f.write_str("{/}")?,32 Token::Parent => f.write_str("{//}")?,33 Token::NoExt => f.write_str("{.}")?,34 Token::BasenameNoExt => f.write_str("{/.}")?,35 Token::Text(ref string) => f.write_str(string)?,36 }37 Ok(())38 }39}4041/// A parsed format string42///43/// This is either a collection of `Token`s including at least one placeholder variant,44/// or a fixed text.45#[derive(Clone, Debug, PartialEq)]46pub enum FormatTemplate {47 Tokens(Vec<Token>),48 Text(String),49}5051static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();5253impl FormatTemplate {54 pub fn has_tokens(&self) -> bool {55 matches!(self, FormatTemplate::Tokens(_))56 }5758 pub fn parse(fmt: &str) -> Self {59 // NOTE: we assume that { and } have the same length60 const BRACE_LEN: usize = '{'.len_utf8();61 let mut tokens = Vec::new();62 let mut remaining = fmt;63 let mut buf = String::new();64 let placeholders = PLACEHOLDERS.get_or_init(|| {65 AhoCorasick::new(["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()66 });67 while let Some(m) = placeholders.find(remaining) {68 match m.pattern().as_u32() {69 0 | 1 => {70 // we found an escaped {{ or }}, so add71 // everything up to the first char to the buffer72 // then skip the second one.73 buf += &remaining[..m.start() + BRACE_LEN];74 remaining = &remaining[m.end()..];75 }76 id if !remaining[m.end()..].starts_with('}') => {77 buf += &remaining[..m.start()];78 if !buf.is_empty() {79 tokens.push(Token::Text(std::mem::take(&mut buf)));80 }81 tokens.push(token_from_pattern_id(id));82 remaining = &remaining[m.end()..];83 }84 _ => {85 // We got a normal pattern, but the final "}"86 // is escaped, so add up to that to the buffer, then87 // skip the final }88 buf += &remaining[..m.end()];89 remaining = &remaining[m.end() + BRACE_LEN..];90 }91 }92 }93 // Add the rest of the string to the buffer, and add the final buffer to the tokens94 if !remaining.is_empty() {95 buf += remaining;96 }97 if tokens.is_empty() {98 // No placeholders were found, so just return the text99 return FormatTemplate::Text(buf);100 }101 // Add final text segment102 if !buf.is_empty() {103 tokens.push(Token::Text(buf));104 }105 debug_assert!(!tokens.is_empty());106 FormatTemplate::Tokens(tokens)107 }108109 /// Generate a result string from this template. If path_separator is Some, then it will replace110 /// the path separator in all placeholder tokens. Fixed text and tokens are not affected by111 /// path separator substitution.112 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {113 use Token::*;114 let path = path.as_ref();115116 match *self {117 Self::Tokens(ref tokens) => {118 let mut s = OsString::new();119 for token in tokens {120 match token {121 Basename => s.push(Self::replace_separator(basename(path), path_separator)),122 BasenameNoExt => s.push(Self::replace_separator(123 &remove_extension(basename(path).as_ref()),124 path_separator,125 )),126 NoExt => s.push(Self::replace_separator(127 &remove_extension(path),128 path_separator,129 )),130 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),131 Placeholder => {132 s.push(Self::replace_separator(path.as_ref(), path_separator))133 }134 Text(ref string) => s.push(string),135 }136 }137 s138 }139 Self::Text(ref text) => OsString::from(text),140 }141 }142143 /// Replace the path separator in the input with the custom separator string. If path_separator144 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is145 /// interpreted as a Path and its components are iterated through and re-joined into a new146 /// OsString.147 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {148 // fast-path - no replacement necessary149 if path_separator.is_none() {150 return Cow::Borrowed(path);151 }152153 let path_separator = path_separator.unwrap();154 let mut out = OsString::with_capacity(path.len());155 let mut components = Path::new(path).components().peekable();156157 while let Some(comp) = components.next() {158 match comp {159 // Absolute paths on Windows are tricky. A Prefix component is usually a drive160 // letter or UNC path, and is usually followed by RootDir. There are also161 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to162 // ignore verbatim path prefixes here because they're very rare, might be163 // impossible to reach here, and there's no good way to deal with them. If users164 // are doing something advanced involving verbatim windows paths, they can do their165 // own output filtering with a tool like sed.166 Component::Prefix(prefix) => {167 if let Prefix::UNC(server, share) = prefix.kind() {168 // Prefix::UNC is a parsed version of '\\server\share'169 out.push(path_separator);170 out.push(path_separator);171 out.push(server);172 out.push(path_separator);173 out.push(share);174 } else {175 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for176 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,177 // but they're not returned by directories fd can search anyway so we don't worry178 // about them.179 out.push(comp.as_os_str());180 }181 }182183 // Root directory is always replaced with the custom separator.184 Component::RootDir => out.push(path_separator),185186 // Everything else is joined normally, with a trailing separator if we're not last187 _ => {188 out.push(comp.as_os_str());189 if components.peek().is_some() {190 out.push(path_separator);191 }192 }193 }194 }195 Cow::Owned(out)196 }197}198199// Convert the id from an aho-corasick match to the200// appropriate token201fn token_from_pattern_id(id: u32) -> Token {202 use Token::*;203 match id {204 2 => Placeholder,205 3 => Basename,206 4 => Parent,207 5 => NoExt,208 6 => BasenameNoExt,209 _ => unreachable!(),210 }211}212213#[cfg(test)]214mod fmt_tests {215 use super::*;216 use std::path::PathBuf;217218 #[test]219 fn parse_no_placeholders() {220 let templ = FormatTemplate::parse("This string has no placeholders");221 assert_eq!(222 templ,223 FormatTemplate::Text("This string has no placeholders".into())224 );225 }226227 #[test]228 fn parse_only_brace_escapes() {229 let templ = FormatTemplate::parse("This string only has escapes like {{ and }}");230 assert_eq!(231 templ,232 FormatTemplate::Text("This string only has escapes like { and }".into())233 );234 }235236 #[test]237 fn all_placeholders() {238 use Token::*;239240 let templ = FormatTemplate::parse(241 "{{path={} \242 basename={/} \243 parent={//} \244 noExt={.} \245 basenameNoExt={/.} \246 }}",247 );248 assert_eq!(249 templ,250 FormatTemplate::Tokens(vec![251 Text("{path=".into()),252 Placeholder,253 Text(" basename=".into()),254 Basename,255 Text(" parent=".into()),256 Parent,257 Text(" noExt=".into()),258 NoExt,259 Text(" basenameNoExt=".into()),260 BasenameNoExt,261 Text(" }".into()),262 ])263 );264265 let mut path = PathBuf::new();266 path.push("a");267 path.push("folder");268 path.push("file.txt");269270 let expanded = templ.generate(&path, Some("/")).into_string().unwrap();271272 assert_eq!(273 expanded,274 "{path=a/folder/file.txt \275 basename=file.txt \276 parent=a/folder \277 noExt=a/folder/file \278 basenameNoExt=file }"279 );280 }281}
modified:src/cli.rs+14 added
450 unmodified lines
451 long_help,452 )]453 pub owner: Option<OwnerFilter>,454455 /// Instead of printing the file normally, print the format string with the following placeholders replaced:456 /// '{}': path (of the current search result)457 /// '{/}': basename458 /// '{//}': parent directory459 /// '{.}': path without file extension460 /// '{/.}': basename without file extension461 #[arg(462 long,463 value_name = "fmt",464 help = "Print results according to template",465 conflicts_with = "list_details"466 )]467 pub format: Option<String>,468469 #[command(flatten)]470 pub exec: Exec,471472 /// Maximum number of arguments to pass to the command given with -X.
439 unmodified lines
modified:src/config.rs+4 added
6 unmodified lines
7use crate::filetypes::FileTypes;8#[cfg(unix)]9use crate::filter::OwnerFilter;10use crate::filter::{SizeFilter, TimeFilter};11use crate::fmt::FormatTemplate;1213/// Configuration options for *fd*.14pub struct Config {15 /// Whether the search is case-sensitive or case-insensitive.
69 unmodified lines
85 ///86 /// The value (if present) will be a lowercase string without leading dots.87 pub extensions: Option<RegexSet>,8889 /// A format string to use to format results, similarly to exec90 pub format: Option<FormatTemplate>,9192 /// If a value is supplied, each item found will be used to generate and execute commands.93 pub command: Option<Arc<CommandSet>>,9495 /// Maximum number of search results to pass to each `command`. If zero, the number is
41 unmodified lines
modified:src/main.rs+5 added
5 unmodified lines
6mod exit_codes;7mod filesystem;8mod filetypes;9mod filter;10mod fmt;11mod output;12mod regex_helper;13mod walk;14
284 unmodified lines
299 .case_insensitive(true)300 .build()301 })302 .transpose()?,303 format: opts304 .format305 .as_deref()306 .map(crate::fmt::FormatTemplate::parse),307 command: command.map(Arc::new),308 batch_size: opts.batch_size,309 exclude_patterns: opts.exclude.iter().map(|p| String::from("!") + p).collect(),310 ignore_files: std::mem::take(&mut opts.ignore_file),
173 unmodified lines
modified:src/output.rs+21 added-1 removed
5 unmodified lines
6use crate::config::Config;7use crate::dir_entry::DirEntry;8use crate::error::print_error;9use crate::exit_codes::ExitCode;10use crate::fmt::FormatTemplate;1112fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14}1516// TODO: this function is performance critical and can probably be optimized17pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) {18 // TODO: use format if supplied19 let r = if let Some(ref format) = config.format {20 print_entry_format(stdout, entry, config, format)17 let r = if let Some(ref ls_colors) = config.ls_colors {21 } else if let Some(ref ls_colors) = config.ls_colors {22 print_entry_colorized(stdout, entry, config, ls_colors)23 } else {24 print_entry_uncolorized(stdout, entry, config)25 };
32 unmodified lines
58 Ok(())59}6061// TODO: this function is performance critical and can probably be optimized62fn print_entry_format<W: Write>(63 stdout: &mut W,64 entry: &DirEntry,65 config: &Config,66 format: &FormatTemplate,67) -> io::Result<()> {68 let separator = if config.null_separator { "\0" } else { "\n" };69 let output = format.generate(70 entry.stripped_path(config),71 config.path_separator.as_deref(),72 );73 // TODO: support writing raw bytes on unix?74 write!(stdout, "{}{}", output.to_string_lossy(), separator)75}7677// TODO: this function is performance critical and can probably be optimized78fn print_entry_colorized<W: Write>(79 stdout: &mut W,80 entry: &DirEntry,81 config: &Config,
99 unmodified lines
modified:tests/tests.rs+60 added
1622 unmodified lines
1623 symlink",1624 );1625}16261627#[test]1628fn format() {1629 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);16301631 te.assert_output(1632 &["--format", "path={}", "--path-separator=/"],1633 "path=a.foo1634 path=e1 e21635 path=one1636 path=one/b.foo1637 path=one/two1638 path=one/two/C.Foo21639 path=one/two/c.foo1640 path=one/two/three1641 path=one/two/three/d.foo1642 path=one/two/three/directory_foo1643 path=symlink",1644 );16451646 te.assert_output(1647 &["foo", "--format", "noExt={.}", "--path-separator=/"],1648 "noExt=a1649 noExt=one/b1650 noExt=one/two/C1651 noExt=one/two/c1652 noExt=one/two/three/d1653 noExt=one/two/three/directory_foo",1654 );16551656 te.assert_output(1657 &["foo", "--format", "basename={/}", "--path-separator=/"],1658 "basename=a.foo1659 basename=b.foo1660 basename=C.Foo21661 basename=c.foo1662 basename=d.foo1663 basename=directory_foo",1664 );16651666 te.assert_output(1667 &["foo", "--format", "name={/.}", "--path-separator=/"],1668 "name=a1669 name=b1670 name=C1671 name=c1672 name=d1673 name=directory_foo",1674 );16751676 te.assert_output(1677 &["foo", "--format", "parent={//}", "--path-separator=/"],1678 "parent=.1679 parent=one1680 parent=one/two1681 parent=one/two1682 parent=one/two/three1683 parent=one/two/three",1684 );1685}16861687/// Shell script execution (--exec)1688#[test]1689fn test_exec() {1690 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);
984 unmodified lines
modified:CHANGELOG.md+1 added
1 unmodified line
23## Features45- Allow passing an optional argument to `--strip-cwd-prefix` of "always", "never", or "auto". to force whether the cwd prefix is stripped or not.6- Add a `--format` option which allows using a format template for direct ouput similar to the template used for `--exec`. (#1043)78## Bugfixes910
760 unmodified lines