Merge pull request #1043 from tmccombs/format-option
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Implement option for printing custom formats
authored by Thayne McCombs · committed by GitHub · parents 6becb66, d44badc · 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
Provenance
- Commit
ea22cbd- Tree
827bfe0- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
6becb66- Parent 2
d44badc
12 files changed+528 added−353 removed
modified:doc/fd.1+30 added-33 removed
373 unmodified lines374 .BI "\-\-search\-path " search\-path375 Provide 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 " fmt379+Specify a template string that is used for printing a line for each file found.380+381+The following placeholders are substituted into the string for each file before printing:382+.RS383+.IP {}384+path (of the current search result)385+.IP {/}386+basename387+.IP {//}388+parent directory389+.IP {.}390+path without file extension391+.IP {/.}392+basename without file extension393+.IP {{394+literal '{' (an escape sequence)395+.IP }}396+literal '}' (an escape sequence)397+.P398+Notice that you can use "{{" and "}}" to escape "{" and "}" respectively, which is especially399+useful if you need to include the literal text of one of the above placeholders.400+.RE401+.TP402 .BI "\-x, \-\-exec " command403 .RS404 Execute405 .I command12 unmodified lines418 If 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 is420 recommended that you don't rely on any ordering of the results.421 398-The following placeholders are substituted before the command is executed:399-.RS400-.IP {}401-path (of the current search result)402-.IP {/}403-basename404-.IP {//}405-parent directory406-.IP {.}407-path without file extension408-.IP {/.}409-basename without file extension410-.IP {{411-literal '{' (an escape sequence)412-.IP }}413-literal '}' (an escape sequence)414-.RE422+Before executing the command, any placeholder patterns in the command are replaced with the423+corresponding values for the current file. The same placeholders are used as in the "\-\-format"424+option.425 426 If no placeholder is present, an implicit "{}" at the end is assumed.427 418-Notice that you can use "{{" and "}}" to escape "{" and "}" respectively, which is especially419-useful if you need to include the literal text of one of the above placeholders.420-428 Examples:429 430 - find all *.zip files and unzip them:431 15 unmodified lines447 once, with all search results as arguments.448 449 The order of the arguments is non-deterministic and should not be relied upon.450 444-One of the following placeholders is substituted before the command is executed:445-.RS446-.IP {}447-path (of all search results)448-.IP {/}449-basename450-.IP {//}451-parent directory452-.IP {.}453-path without file extension454-.IP {/.}455-basename without file extension456-.RE451+This uses the same placeholders as "\-\-format" and "\-\-exec", but instead of expanding452+once per command invocation each argument containing a placeholder is expanding for every453+file in a batch and passed as separate arguments.454 455 If no placeholder is present, an implicit "{}" at the end is assumed.456 457 Like \-\-exec, this can be used multiple times, in which case each command will be run in82 unmodified linesdeleted:src/exec/input.rs-87 removed
1-use std::ffi::{OsStr, OsString};2-use std::path::{Path, PathBuf};3-4-use crate::filesystem::strip_current_dir;5-6-/// Removes the parent component of the path7-pub fn basename(path: &Path) -> &OsStr {8- path.file_name().unwrap_or(path.as_os_str())9-}10-11-/// Removes the extension from the path12-pub fn remove_extension(path: &Path) -> OsString {13- let dirname = dirname(path);14- let stem = path.file_stem().unwrap_or(path.as_os_str());15-16- let path = PathBuf::from(dirname).join(stem);17-18- strip_current_dir(&path).to_owned().into_os_string()19-}20-21-/// Removes the basename from the path.22-pub 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-}33-34-#[cfg(test)]35-mod path_tests {36- use super::*;37- use std::path::MAIN_SEPARATOR_STR;38-39- fn correct(input: &str) -> String {40- input.replace('/', MAIN_SEPARATOR_STR)41- }42-43- 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- }55-56- 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 "" => ""62-63- 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"68-69- 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- }74-75- #[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- }81-82- #[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
1 mod command;2-mod input;2 mod job;4-mod token;3 6-use std::borrow::Cow;7-use std::ffi::{OsStr, OsString};4+use std::ffi::OsString;5 use std::io;6 use std::iter;10-use std::path::{Component, Path, PathBuf, Prefix};7+use std::path::{Path, PathBuf};8 use std::process::Stdio;9 use std::sync::Mutex;10 11 use anyhow::{bail, Result};12 use argmax::Command;13 14 use crate::exit_codes::{merge_exitcodes, ExitCode};15+use crate::fmt::{FormatTemplate, Token};16 17 use self::command::{execute_commands, handle_cmd_error};20-use self::input::{basename, dirname, remove_extension};18 pub use self::job::{batch, job};22-use self::token::{tokenize, Token};19 20 /// Execution mode of the command21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]22 pub enum ExecutionMode {103 unmodified lines126 /// Represents a multi-exec command as it is built.127 #[derive(Debug)]128 struct 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 lines215 /// 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)]218 struct CommandTemplate {223- args: Vec<ArgumentTemplate>,219+ args: Vec<FormatTemplate>,220 }221 222 impl CommandTemplate {223 fn new<I, S>(input: I) -> Result<CommandTemplate>6 unmodified lines230 231 for arg in input {232 let arg = arg.as_ref();233 238- let tmpl = tokenize(arg);234+ let tmpl = FormatTemplate::parse(arg);235 has_placeholder |= tmpl.has_tokens();236 args.push(tmpl);237 }238 7 unmodified lines246 }247 248 // 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 }252 253 Ok(CommandTemplate { args })254 }14 unmodified lines269 Ok(cmd)270 }271 }272 277-/// 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)]282-enum ArgumentTemplate {283- Tokens(Vec<Token>),284- Text(String),285-}286-287-impl ArgumentTemplate {288- pub fn has_tokens(&self) -> bool {289- matches!(self, ArgumentTemplate::Tokens(_))290- }291-292- /// 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();298-299- 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- }325-326- /// 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- }335-336- let path_separator = path_separator.unwrap();337- let mut out = OsString::with_capacity(path.len());338- let mut components = Path::new(path).components().peekable();339-340- 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- }365-366- // Root directory is always replaced with the custom separator.367- Component::RootDir => out.push(path_separator),368-369- // 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-}381-273 #[cfg(test)]274 mod tests {275 use super::*;276 11 unmodified lines288 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 lines305 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 lines321 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 lines337 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 lines353 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 lines384 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 lines404 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 lines430 }431 432 #[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 lines445 446 #[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 linesdeleted:src/exec/token.rs-98 removed
1-use aho_corasick::AhoCorasick;2-use std::fmt::{self, Display, Formatter};3-use std::sync::OnceLock;4-5-use super::ArgumentTemplate;6-7-/// 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)]12-pub enum Token {13- Placeholder,14- Basename,15- Parent,16- NoExt,17- BasenameNoExt,18- Text(String),19-}20-21-impl 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-}34-35-static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();36-37-pub(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-}87-88-fn 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
1+use std::ffi::{OsStr, OsString};2+use std::path::{Path, PathBuf};3+4+use crate::filesystem::strip_current_dir;5+6+/// Removes the parent component of the path7+pub fn basename(path: &Path) -> &OsStr {8+ path.file_name().unwrap_or(path.as_os_str())9+}10+11+/// Removes the extension from the path12+pub fn remove_extension(path: &Path) -> OsString {13+ let dirname = dirname(path);14+ let stem = path.file_stem().unwrap_or(path.as_os_str());15+16+ let path = PathBuf::from(dirname).join(stem);17+18+ strip_current_dir(&path).to_owned().into_os_string()19+}20+21+/// Removes the basename from the path.22+pub 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+}33+34+#[cfg(test)]35+mod path_tests {36+ use super::*;37+ use std::path::MAIN_SEPARATOR_STR;38+39+ fn correct(input: &str) -> String {40+ input.replace('/', MAIN_SEPARATOR_STR)41+ }42+43+ 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+ }55+56+ 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 "" => ""62+63+ 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"68+69+ 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+ }74+75+ #[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+ }81+82+ #[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
1+mod input;2+3+use std::borrow::Cow;4+use std::ffi::{OsStr, OsString};5+use std::fmt::{self, Display, Formatter};6+use std::path::{Component, Path, Prefix};7+use std::sync::OnceLock;8+9+use aho_corasick::AhoCorasick;10+11+use self::input::{basename, dirname, remove_extension};12+13+/// 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)]18+pub enum Token {19+ Placeholder,20+ Basename,21+ Parent,22+ NoExt,23+ BasenameNoExt,24+ Text(String),25+}26+27+impl 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+}40+41+/// 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)]46+pub enum FormatTemplate {47+ Tokens(Vec<Token>),48+ Text(String),49+}50+51+static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();52+53+impl FormatTemplate {54+ pub fn has_tokens(&self) -> bool {55+ matches!(self, FormatTemplate::Tokens(_))56+ }57+58+ 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+ }108+109+ /// 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();115+116+ 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+ }142+143+ /// 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+ }152+153+ let path_separator = path_separator.unwrap();154+ let mut out = OsString::with_capacity(path.len());155+ let mut components = Path::new(path).components().peekable();156+157+ 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+ }182+183+ // Root directory is always replaced with the custom separator.184+ Component::RootDir => out.push(path_separator),185+186+ // 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+}198+199+// Convert the id from an aho-corasick match to the200+// appropriate token201+fn 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+}212+213+#[cfg(test)]214+mod fmt_tests {215+ use super::*;216+ use std::path::PathBuf;217+218+ #[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+ }226+227+ #[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+ }235+236+ #[test]237+ fn all_placeholders() {238+ use Token::*;239+240+ 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+ );264+265+ let mut path = PathBuf::new();266+ path.push("a");267+ path.push("folder");268+ path.push("file.txt");269+270+ let expanded = templ.generate(&path, Some("/")).into_string().unwrap();271+272+ 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 lines451 long_help,452 )]453 pub owner: Option<OwnerFilter>,454 455+ /// 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>,468+469 #[command(flatten)]470 pub exec: Exec,471 472 /// Maximum number of arguments to pass to the command given with -X.439 unmodified linesmodified:src/config.rs+4 added
6 unmodified lines7 use crate::filetypes::FileTypes;8 #[cfg(unix)]9 use crate::filter::OwnerFilter;10 use crate::filter::{SizeFilter, TimeFilter};11+use crate::fmt::FormatTemplate;12 13 /// Configuration options for *fd*.14 pub struct Config {15 /// Whether the search is case-sensitive or case-insensitive.69 unmodified lines85 ///86 /// The value (if present) will be a lowercase string without leading dots.87 pub extensions: Option<RegexSet>,88 89+ /// A format string to use to format results, similarly to exec90+ pub format: Option<FormatTemplate>,91+92 /// If a value is supplied, each item found will be used to generate and execute commands.93 pub command: Option<Arc<CommandSet>>,94 95 /// Maximum number of search results to pass to each `command`. If zero, the number is41 unmodified linesmodified:src/main.rs+5 added
5 unmodified lines6 mod exit_codes;7 mod filesystem;8 mod filetypes;9 mod filter;10+mod fmt;11 mod output;12 mod regex_helper;13 mod walk;14 284 unmodified lines299 .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 linesmodified:src/output.rs+21 added-1 removed
5 unmodified lines6 use crate::config::Config;7 use crate::dir_entry::DirEntry;8 use crate::error::print_error;9 use crate::exit_codes::ExitCode;10+use crate::fmt::FormatTemplate;11 12 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {13 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)14 }15 16 // TODO: this function is performance critical and can probably be optimized17 pub 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 lines58 Ok(())59 }60 61 // TODO: this function is performance critical and can probably be optimized62+fn 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+}76+77+// TODO: this function is performance critical and can probably be optimized78 fn print_entry_colorized<W: Write>(79 stdout: &mut W,80 entry: &DirEntry,81 config: &Config,99 unmodified linesmodified:tests/tests.rs+60 added
1622 unmodified lines1623 symlink",1624 );1625 }1626 1627+#[test]1628+fn format() {1629+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1630+1631+ 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+ );1645+1646+ 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+ );1655+1656+ 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+ );1665+1666+ te.assert_output(1667+ &["foo", "--format", "name={/.}", "--path-separator=/"],1668+ "name=a1669+ name=b1670+ name=C1671+ name=c1672+ name=d1673+ name=directory_foo",1674+ );1675+1676+ 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+}1686+1687 /// Shell script execution (--exec)1688 #[test]1689 fn test_exec() {1690 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);984 unmodified linesmodified:CHANGELOG.md+1 added
1 unmodified line2 3 ## Features4 5 - 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)7 8 ## Bugfixes9 10 760 unmodified lines