Merge branch 'master' into master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thayne McCombs · committed by GitHub · parents 22dbed0, 3e201de · Browse files · 22 files·+923 added−437 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+923 added−437 removed
- tests:+123 added−17 removed
- other:+800 added−420 removed
Provenance
- Commit
50c0fa8- Tree
23e6700- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
22dbed0- Parent 2
3e201de
22 files changed+923 added−437 removed
modified:.github/workflows/CICD.yml+13 added-3 removed
1 name: CICD2 3 env:4- MIN_SUPPORTED_RUST_VERSION: "1.53.0"4+ MIN_SUPPORTED_RUST_VERSION: "1.56.0"5 CICD_INTERMEDIATES_DIR: "_cicd-intermediates"6 7 on:8 workflow_dispatch:36 unmodified lines45 runs-on: ubuntu-20.0446 steps:47 - name: Checkout source code48 uses: actions/checkout@v249+50 - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }})51 uses: actions-rs/toolchain@v152 with:53 toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}54 default: true55+ components: clippy56+ - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix)57+ uses: actions-rs/cargo@v158+ with:59+ command: clippy60+ args: --locked --all-targets --all-features61 profile: minimal # minimal component installation (ie, no documentation)62 - name: Run tests63 uses: actions-rs/cargo@v164 with:254 unmodified lines319 Homepage: ${{ env.PROJECT_HOMEPAGE }}320 Architecture: ${DPKG_ARCH}321 Provides: ${{ env.PROJECT_NAME }}322 Conflicts: ${DPKG_CONFLICTS}316- Description: cat(1) clone with wings.317- A cat(1) clone with syntax highlighting and Git integration.323+ Description: simple, fast and user-friendly alternative to find324+ fd is a program to find entries in your filesystem.325+ It is a simple, fast and user-friendly alternative to find.326+ While it does not aim to support all of finds powerful functionality, it provides327+ sensible (opinionated) defaults for a majority of use cases.328 EOF329 330 DPKG_PATH="${DPKG_STAGING}/${DPKG_NAME}"331 echo ::set-output name=DPKG_PATH::${DPKG_PATH}33 unmodified linesadded:.github/FUNDING.yml+1 added
1github: [sharkdp, tavianator]modified:contrib/completion/_fd+4 added
55 unmodified lines56 57 + no-ignore-partial # some ignore files58 "(no-ignore-full --no-ignore-vcs)--no-ignore-vcs[don't respect .gitignore files]"59 "!(no-ignore-full --no-global-ignore-file)--no-global-ignore-file[don't respect the global ignore file]"60+ $no'(no-ignore-full --no-ignore-parent)--no-ignore-parent[]'61 62 + '(case)' # case-sensitivity63 {-s,--case-sensitive}'[perform a case-sensitive search]'64 {-i,--ignore-case}'[perform a case-insensitive search]'89 unmodified lines154 + search-path155 $no'(--base-directory)--base-directory=[change the current working directory to the given path]:directory:_files -/'156 $no'(*)*--search-path=[set search path (instead of positional <path> arguments)]:directory:_files -/'157 158+ + strip-cwd-prefix159+ $no'(strip-cwd-prefix exec-cmds)--strip-cwd-prefix[Strip ./ prefix when output is redirected]'160+161 + args # positional arguments162 '1: :_guard "^-*" pattern'163 '(--search-path)*:directory:_files -/'164 )109 unmodified linesmodified:doc/fd.1+24 added-1 removed
22 unmodified lines23 .SH DESCRIPTION24 .B fd25 is a simple, fast and user-friendly alternative to26 .BR find (1).27+.P28+By default29+.B fd30+uses regular expressions for the pattern. However, this can be changed to use simple glob patterns31+with the '\-\-glob' option.32 .SH OPTIONS33 .TP34 .B \-H, \-\-hidden35 Include hidden files and directories in the search results34 unmodified lines70 git setting, which defaults to71 .IR $HOME/.config/git/ignore ).72 The flag can be overridden with '--ignore-vcs'.73 .TP74+.B \-\-no\-ignore\-parent75+Show search results from files and directories that would otherwise be ignored by gitignore files in76+parent directories.77+.TP78 .B \-s, \-\-case\-sensitive79 Perform a case-sensitive search. By default, fd uses case-insensitive searches, unless the80 pattern contains an uppercase character (smart case).81 .TP52 unmodified lines134 .B \-\-show-errors135 Enable the display of filesystem errors for situations such as insufficient136 permissions or dead symlinks.137 .TP138+.B \-\-strip-cwd-prefix139+By default, relative paths are prefixed with './' when the output goes to a non interactive terminal140+(TTY). Use this flag to disable this behaviour.141+.TP142 .B \-\-one\-file\-system, \-\-mount, \-\-xdev143 By default, fd will traverse the file system tree as far as other options dictate. With this flag, fd ensures that it does not descend into a different file system than the one it started in. Comparable to the -mount or -xdev filters of find(1).144 .TP145 .B \-h, \-\-help194 unmodified lines340 - not to fd.341 It is therefore recommended to place the \-x/\-\-exec option last. Alternatively, you can supply342 a ';' argument to end the argument list and continue with more fd options.343 Most shells require ';' to be escaped: '\\;'.344+This option can be specified multiple times, in which case all commands are run for each345+file found, in the order they are provided. In that case, you must supply a ';' argument for346+all but the last commands.347 348 The following placeholders are substituted before the command is executed:349 .RS350 .IP {}45 unmodified lines396 .RE397 398 If no placeholder is present, an implicit "{}" at the end is assumed.399 400+Like \-\-exec, this can be used multiple times, in which case each command will be run in401+the order given.402+403 Examples:404 405 - Find all test_*.py files and open them in your favorite editor:406 4 unmodified lines411 - Find all *.rs files and count the lines with "wc -l ...":412 413 fd -e rs -X wc -l414 .RE396-415+.TP416+.BI "\-\-batch-size " size417+Maximum number of arguments to pass to the command given with -X. If the number of results is418+greater than the given size, the command given with -X is run again with remaining arguments. A419+batch size of zero means there is no limit.420 .SH PATTERN SYNTAX421 The regular expression syntax used by fd is documented here:422 423 https://docs.rs/regex/1.0.0/regex/#syntax41 unmodified linesadded:doc/logo.pngbinary
A binary file, added.
added:doc/logo.svg+161 added
1+<?xml version="1.0" encoding="UTF-8" standalone="no"?>2+<!-- Created with Inkscape (http://www.inkscape.org/) -->3+4+<svg5+ width="66mm"6+ height="66mm"7+ viewBox="0 0 66 66.000001"8+ version="1.1"9+ id="svg5"10+ inkscape:version="1.1 (c4e8f9ed74, 2021-05-24)"11+ sodipodi:docname="logo.svg"12+ inkscape:export-filename="/home/shark/Informatik/rust/fd/doc/logo.png"13+ inkscape:export-xdpi="192.42"14+ inkscape:export-ydpi="192.42"15+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"16+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"17+ xmlns="http://www.w3.org/2000/svg"18+ xmlns:svg="http://www.w3.org/2000/svg">19+ <sodipodi:namedview20+ id="namedview7"21+ pagecolor="#ffffff"22+ bordercolor="#999999"23+ borderopacity="1"24+ inkscape:pageshadow="0"25+ inkscape:pageopacity="1"26+ inkscape:pagecheckerboard="0"27+ inkscape:document-units="mm"28+ showgrid="false"29+ inkscape:zoom="2.1795515"30+ inkscape:cx="114.47309"31+ inkscape:cy="176.18304"32+ inkscape:window-width="1920"33+ inkscape:window-height="1175"34+ inkscape:window-x="1920"35+ inkscape:window-y="0"36+ inkscape:window-maximized="1"37+ inkscape:current-layer="layer1"38+ showguides="false"39+ inkscape:guide-bbox="true"40+ inkscape:snap-global="false"41+ fit-margin-top="2"42+ fit-margin-left="2"43+ fit-margin-right="2"44+ fit-margin-bottom="2"45+ lock-margins="true">46+ <sodipodi:guide47+ position="26.228232,26.126763"48+ orientation="0,-1"49+ id="guide47826" />50+ <sodipodi:guide51+ position="25.799494,2.3628924"52+ orientation="0,-1"53+ id="guide47828" />54+ </sodipodi:namedview>55+ <defs56+ id="defs2" />57+ <g58+ inkscape:label="Ebene 1"59+ inkscape:groupmode="layer"60+ id="layer1"61+ transform="translate(-21.358009,-148.28012)">62+ <g63+ id="g66267"64+ transform="matrix(0.84959471,0,0,0.84959471,7.9920783,43.351816)">65+ <text66+ xml:space="preserve"67+ style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:29.7126px;line-height:0;font-family:'Fira Sans Condensed';-inkscape-font-specification:'Fira Sans Condensed, ';white-space:pre;inline-size:37.3715;fill:#e5e5e5;fill-opacity:1;stroke-width:0.742816"68+ x="50.647034"69+ y="173.19841"70+ id="text50653"71+ transform="matrix(1.0604862,0,0,1.0604862,-3.3101428,-10.150043)"><tspan72+ x="50.647034"73+ y="173.19841"74+ id="tspan66635"><tspan75+ style="font-family:'Source Code Pro';-inkscape-font-specification:'Source Code Pro'"76+ id="tspan66633">fd</tspan></tspan></text>77+ <text78+ xml:space="preserve"79+ style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:29.7126px;line-height:0;font-family:'Fira Sans Condensed';-inkscape-font-specification:'Fira Sans Condensed, ';white-space:pre;inline-size:37.3715;fill:#00ccff;fill-opacity:0.996078;stroke-width:0.742816"80+ x="50.647034"81+ y="173.19841"82+ id="text1244"83+ transform="matrix(1.0604862,0,0,1.0604862,-2.8008599,-9.6407599)"><tspan84+ x="50.647034"85+ y="173.19841"86+ id="tspan66639"><tspan87+ style="font-family:'Source Code Pro';-inkscape-font-specification:'Source Code Pro'"88+ id="tspan66637">fd</tspan></tspan></text>89+ <g90+ id="g47824"91+ transform="translate(0.1724878,-0.35338542)">92+ <g93+ id="g42041">94+ <path95+ style="fill:none;stroke:#939dac;stroke-width:1.065;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"96+ d="m 28.209616,155.51329 v 15.68758 H 40.83001"97+ id="path39763"98+ sodipodi:nodetypes="ccc" />99+ <path100+ style="fill:#b7bec8;stroke:#939dac;stroke-width:1.065;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"101+ d="M 27.869464,161.83767 H 40.261291"102+ id="path39765" />103+ </g>104+ <g105+ id="g41945"106+ transform="translate(-1.0583333)">107+ <path108+ style="fill:#0088aa;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"109+ d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"110+ id="path40006"111+ sodipodi:nodetypes="ccccc" />112+ <rect113+ style="fill:#01ccff;fill-opacity:1;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"114+ id="rect39949"115+ width="9.4925022"116+ height="6.2080379"117+ x="37.492516"118+ y="158.82776"119+ ry="0.90871465" />120+ </g>121+ <g122+ id="g41951"123+ transform="translate(-1.0583334,9.3665773)">124+ <path125+ style="fill:#373e48;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"126+ d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"127+ id="path41947"128+ sodipodi:nodetypes="ccccc" />129+ <rect130+ style="fill:#535d6c;fill-opacity:0.993797;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"131+ id="rect41949"132+ width="9.4925022"133+ height="6.2080379"134+ x="37.492516"135+ y="158.82776"136+ ry="0.90871465" />137+ </g>138+ <g139+ id="g41957"140+ transform="translate(-14.306994,-6.8962642)">141+ <path142+ style="fill:#373e48;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"143+ d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"144+ id="path41953"145+ sodipodi:nodetypes="ccccc" />146+ <rect147+ style="fill:#535d6c;fill-opacity:0.993797;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"148+ id="rect41955"149+ width="9.4925022"150+ height="6.2080379"151+ x="37.492516"152+ y="158.82776"153+ ry="0.90871465" />154+ </g>155+ </g>156+ <g157+ id="g65006"158+ transform="matrix(0.55302761,0,0,0.55302761,66.463548,117.45819)" />159+ </g>160+ </g>161+</svg>modified:src/exec/command.rs+81 added-35 removed
4 unmodified lines5 6 use crate::error::print_error;7 use crate::exit_codes::ExitCode;8 9+struct Outputs {10+ stdout: Vec<u8>,11+ stderr: Vec<u8>,12+}13+struct OutputBuffer<'a> {14+ output_permission: &'a Mutex<()>,15+ outputs: Vec<Outputs>,16+}17+18+impl<'a> OutputBuffer<'a> {19+ fn new(output_permission: &'a Mutex<()>) -> Self {20+ Self {21+ output_permission,22+ outputs: Vec::new(),23+ }24+ }25+26+ fn push(&mut self, stdout: Vec<u8>, stderr: Vec<u8>) {27+ self.outputs.push(Outputs { stdout, stderr });28+ }29+30+ fn write(self) {31+ // avoid taking the lock if there is nothing to do32+ if self.outputs.is_empty() {33+ return;34+ }35+ // While this lock is active, this thread will be the only thread allowed36+ // to write its outputs.37+ let _lock = self.output_permission.lock().unwrap();38+39+ let stdout = io::stdout();40+ let stderr = io::stderr();41+42+ let mut stdout = stdout.lock();43+ let mut stderr = stderr.lock();44+45+ for output in self.outputs.iter() {46+ let _ = stdout.write_all(&output.stdout);47+ let _ = stderr.write_all(&output.stderr);48+ }49+ }50+}51+52 /// Executes a command.10-pub fn execute_command(11- mut cmd: Command,53+pub fn execute_commands<I: Iterator<Item = Command>>(54+ cmds: I,55 out_perm: &Mutex<()>,56 enable_output_buffering: bool,57 ) -> ExitCode {58+ let mut output_buffer = OutputBuffer::new(out_perm);59+ for mut cmd in cmds {15- // Spawn the supplied command.16- let output = if enable_output_buffering {17- cmd.output()18- } else {19- // If running on only one thread, don't buffer output20- // Allows for viewing and interacting with intermediate command output21- cmd.spawn().and_then(|c| c.wait_with_output())22- };60+ // Spawn the supplied command.61+ let output = if enable_output_buffering {62+ cmd.output()63+ } else {64+ // If running on only one thread, don't buffer output65+ // Allows for viewing and interacting with intermediate command output66+ cmd.spawn().and_then(|c| c.wait_with_output())67+ };68 24- // Then wait for the command to exit, if it was spawned.25- match output {26- Ok(output) => {27- // While this lock is active, this thread will be the only thread allowed28- // to write its outputs.29- let _lock = out_perm.lock().unwrap();30-31- let stdout = io::stdout();32- let stderr = io::stderr();33-34- let _ = stdout.lock().write_all(&output.stdout);35- let _ = stderr.lock().write_all(&output.stderr);36-37- if output.status.code() == Some(0) {38- ExitCode::Success39- } else {40- ExitCode::GeneralError69+ // Then wait for the command to exit, if it was spawned.70+ match output {71+ Ok(output) => {72+ if enable_output_buffering {73+ output_buffer.push(output.stdout, output.stderr);74+ }75+ if output.status.code() != Some(0) {76+ output_buffer.write();77+ return ExitCode::GeneralError;78+ }79 }80+ Err(why) => {81+ output_buffer.write();82+ return handle_cmd_error(&cmd, why);83+ }84 }43- Err(ref why) if why.kind() == io::ErrorKind::NotFound => {44- print_error(format!("Command not found: {:?}", cmd));45- ExitCode::GeneralError46- }47- Err(why) => {48- print_error(format!("Problem while executing command: {}", why));49- ExitCode::GeneralError50- }85 }86+ output_buffer.write();87+ ExitCode::Success88 }89+90+pub fn handle_cmd_error(cmd: &Command, err: io::Error) -> ExitCode {91+ if err.kind() == io::ErrorKind::NotFound {92+ print_error(format!("Command not found: {:?}", cmd));93+ ExitCode::GeneralError94+ } else {95+ print_error(format!("Problem while executing command: {}", err));96+ ExitCode::GeneralError97+ }98+}modified:src/exec/input.rs+2 added-2 removed
3 unmodified lines4 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_else(|| path.as_os_str())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_else(|| path.as_os_str());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()69 unmodified linesmodified:src/exec/job.rs+8 added-12 removed
1+use std::path::PathBuf;2+use std::sync::mpsc::Receiver;3 use std::sync::{Arc, Mutex};4 3-use crossbeam_channel::Receiver;5 6 use crate::dir_entry::DirEntry;7 use crate::error::print_error;8 use crate::exit_codes::{merge_exitcodes, ExitCode};9 use crate::walk::WorkerResult;10 10-use super::CommandTemplate;11+use super::CommandSet;12 13 /// An event loop that listens for inputs from the `rx` receiver. Each received input will14 /// generate a command with the supplied command template. The generated command will then15 /// be executed, and this process will continue until the receiver's sender has closed.16 pub fn job(17 rx: Arc<Mutex<Receiver<WorkerResult>>>,17- cmd: Arc<CommandTemplate>,18+ cmd: Arc<CommandSet>,19 out_perm: Arc<Mutex<()>>,20 show_filesystem_errors: bool,21 buffer_output: bool,22 ) -> ExitCode {17 unmodified lines40 41 // Drop the lock so that other threads can read from the receiver.42 drop(lock);43 // Generate a command, execute it and store its exit code.43- results.push(cmd.generate_and_execute(44- dir_entry.path(),45- Arc::clone(&out_perm),46- buffer_output,47- ))44+ results.push(cmd.execute(&dir_entry, Arc::clone(&out_perm), buffer_output))45 }46 // Returns error in case of any error.47 merge_exitcodes(results)48 }49 50 pub fn batch(51 rx: Receiver<WorkerResult>,55- cmd: &CommandTemplate,52+ cmd: &CommandSet,53 show_filesystem_errors: bool,57- buffer_output: bool,54 limit: usize,55 ) -> ExitCode {56 let paths = rx57 .into_iter()7 unmodified lines65 }66 });67 if limit == 0 {68 // no limit73- return cmd.generate_and_execute_batch(paths, buffer_output);69+ return cmd.execute_batch(paths);70 }71 72 let mut exit_codes = Vec::new();73 let mut peekable = paths.peekable();74 while peekable.peek().is_some() {75 let limited = peekable.by_ref().take(limit);80- let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);76+ let exit_code = cmd.execute_batch(limited);77 exit_codes.push(exit_code);78 }79 merge_exitcodes(exit_codes)80 }modified:src/exec/mod.rs+172 added-104 removed
7 unmodified lines8 use std::path::{Component, Path, PathBuf, Prefix};9 use std::process::{Command, Stdio};10 use std::sync::{Arc, Mutex};11 12-use anyhow::{anyhow, Result};12+use anyhow::{bail, Result};13 use once_cell::sync::Lazy;14 use regex::Regex;15 16 use crate::exit_codes::ExitCode;17 18-use self::command::execute_command;18+use self::command::{execute_commands, handle_cmd_error};19 use self::input::{basename, dirname, remove_extension};20 pub use self::job::{batch, job};21 use self::token::Token;22 5 unmodified lines28 /// Command is run for a batch of results at once29 Batch,30 }31 32-/// Represents a template that is utilized to generate command strings.33-///34-/// The template is meant to be coupled with an input in order to generate a command. The35-/// `generate_and_execute()` method will be used to generate a command and execute it.32 #[derive(Debug, Clone, PartialEq)]37-pub struct CommandTemplate {38- args: Vec<ArgumentTemplate>,33+pub struct CommandSet {34 mode: ExecutionMode,35 path_separator: Option<String>,36+ commands: Vec<CommandTemplate>,37 }38 43-impl CommandTemplate {44- pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate39+impl CommandSet {40+ pub fn new<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>41 where46- I: IntoIterator<Item = S>,42+ I: IntoIterator<Item = Vec<S>>,43 S: AsRef<str>,44 {49- Self::build(input, ExecutionMode::OneByOne, path_separator)45+ Ok(CommandSet {46+ mode: ExecutionMode::OneByOne,47+ path_separator,48+ commands: input49+ .into_iter()50+ .map(CommandTemplate::new)51+ .collect::<Result<_>>()?,52+ })53 }54 52- pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>55+ pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>56 where54- I: IntoIterator<Item = S>,57+ I: IntoIterator<Item = Vec<S>>,58 S: AsRef<str>,59 {57- let cmd = Self::build(input, ExecutionMode::Batch, path_separator);58- if cmd.number_of_tokens() > 1 {59- return Err(anyhow!("Only one placeholder allowed for batch commands"));60+ Ok(CommandSet {61+ mode: ExecutionMode::Batch,62+ path_separator,63+ commands: input64+ .into_iter()65+ .map(|args| {66+ let cmd = CommandTemplate::new(args)?;67+ if cmd.number_of_tokens() > 1 {68+ bail!("Only one placeholder allowed for batch commands");69+ }70+ if cmd.args[0].has_tokens() {71+ bail!("First argument of exec-batch is expected to be a fixed executable");72+ }73+ Ok(cmd)74+ })75+ .collect::<Result<Vec<_>>>()?,76+ })77+ }78+79+ pub fn in_batch_mode(&self) -> bool {80+ self.mode == ExecutionMode::Batch81+ }82+83+ pub fn execute(&self, input: &Path, out_perm: Arc<Mutex<()>>, buffer_output: bool) -> ExitCode {84+ let path_separator = self.path_separator.as_deref();85+ let commands = self86+ .commands87+ .iter()88+ .map(|c| c.generate(input, path_separator));89+ execute_commands(commands, &out_perm, buffer_output)90+ }91+92+ pub fn execute_batch<I>(&self, paths: I) -> ExitCode93+ where94+ I: Iterator<Item = PathBuf>,95+ {96+ let path_separator = self.path_separator.as_deref();97+ let mut paths = paths.collect::<Vec<_>>();98+ paths.sort();99+ for cmd in &self.commands {100+ let exit = cmd.generate_and_execute_batch(&paths, path_separator);101+ if exit != ExitCode::Success {102+ return exit;103+ }104 }61- if cmd.args[0].has_tokens() {62- return Err(anyhow!(63- "First argument of exec-batch is expected to be a fixed executable"64- ));65- }66- Ok(cmd)105+ ExitCode::Success106 }107+}108 69- fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate109+/// Represents a template that is utilized to generate command strings.110+///111+/// The template is meant to be coupled with an input in order to generate a command. The112+/// `generate_and_execute()` method will be used to generate a command and execute it.113+#[derive(Debug, Clone, PartialEq)]114+struct CommandTemplate {115+ args: Vec<ArgumentTemplate>,116+}117+118+impl CommandTemplate {119+ fn new<I, S>(input: I) -> Result<CommandTemplate>120 where121 I: IntoIterator<Item = S>,122 S: AsRef<str>,123 {42 unmodified lines166 167 args.push(ArgumentTemplate::Tokens(tokens));168 }169 170+ // We need to check that we have at least one argument, because if not171+ // it will try to execute each file and directory it finds.172+ //173+ // Sadly, clap can't currently handle this for us, see174+ // https://github.com/clap-rs/clap/issues/3542175+ if args.is_empty() {176+ bail!("No executable provided for --exec or --exec-batch");177+ }178+179 // If a placeholder token was not supplied, append one at the end of the command.180 if !has_placeholder {181 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));182 }183 125- CommandTemplate {126- args,127- mode,128- path_separator,129- }184+ Ok(CommandTemplate { args })185 }186 187 fn number_of_tokens(&self) -> usize {188 self.args.iter().filter(|arg| arg.has_tokens()).count()1 unmodified line190 191 /// Generates and executes a command.192 ///193 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be139- /// build. Once all arguments have been processed, the command is executed.140- pub fn generate_and_execute(141- &self,142- input: &Path,143- out_perm: Arc<Mutex<()>>,144- buffer_output: bool,145- ) -> ExitCode {146- let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));194+ /// build.195+ fn generate(&self, input: &Path, path_separator: Option<&str>) -> Command {196+ let mut cmd = Command::new(self.args[0].generate(&input, path_separator));197 for arg in &self.args[1..] {148- cmd.arg(arg.generate(&input, self.path_separator.as_deref()));198+ cmd.arg(arg.generate(&input, path_separator));199 }150-151- execute_command(cmd, &out_perm, buffer_output)200+ cmd201 }202 154- pub fn in_batch_mode(&self) -> bool {155- self.mode == ExecutionMode::Batch156- }157-158- pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode159- where160- I: Iterator<Item = PathBuf>,161- {203+ fn generate_and_execute_batch(204+ &self,205+ paths: &[PathBuf],206+ path_separator: Option<&str>,207+ ) -> ExitCode {208 let mut cmd = Command::new(self.args[0].generate("", None));209 cmd.stdin(Stdio::inherit());210 cmd.stdout(Stdio::inherit());211 cmd.stderr(Stdio::inherit());212 167- let mut paths: Vec<_> = paths.collect();213 let mut has_path = false;214 215 for arg in &self.args[1..] {216 if arg.has_tokens() {172- paths.sort();173-174- // A single `Tokens` is expected175- // So we can directly consume the iterator once and for all176- for path in &mut paths {177- cmd.arg(arg.generate(path, self.path_separator.as_deref()));217+ for path in paths {218+ cmd.arg(arg.generate(path, path_separator));219 has_path = true;220 }221 } else {222 cmd.arg(arg.generate("", None));223 }224 }225 226 if has_path {186- execute_command(cmd, &Mutex::new(()), buffer_output)227+ match cmd.spawn().and_then(|mut c| c.wait()) {228+ Ok(_) => ExitCode::Success,229+ Err(e) => handle_cmd_error(&cmd, e),230+ }231 } else {232 ExitCode::Success233 }234 }110 unmodified lines345 346 #[test]347 fn tokens_with_placeholder() {348 assert_eq!(305- CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),306- CommandTemplate {307- args: vec![308- ArgumentTemplate::Text("echo".into()),309- ArgumentTemplate::Text("${SHELL}:".into()),310- ArgumentTemplate::Tokens(vec![Token::Placeholder]),311- ],349+ CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None).unwrap(),350+ CommandSet {351+ commands: vec![CommandTemplate {352+ args: vec![353+ ArgumentTemplate::Text("echo".into()),354+ ArgumentTemplate::Text("${SHELL}:".into()),355+ ArgumentTemplate::Tokens(vec![Token::Placeholder]),356+ ]357+ }],358 mode: ExecutionMode::OneByOne,359 path_separator: None,360 }361 );1 unmodified line363 364 #[test]365 fn tokens_with_no_extension() {366 assert_eq!(367+ CommandSet::new(vec![vec!["echo", "{.}"]], None).unwrap(),321- CommandTemplate::new(&["echo", "{.}"], None),322- CommandTemplate {323- args: vec![324- ArgumentTemplate::Text("echo".into()),325- ArgumentTemplate::Tokens(vec![Token::NoExt]),326- ],368+ CommandSet {369+ commands: vec![CommandTemplate {370+ args: vec![371+ ArgumentTemplate::Text("echo".into()),372+ ArgumentTemplate::Tokens(vec![Token::NoExt]),373+ ],374+ }],375 mode: ExecutionMode::OneByOne,376 path_separator: None,377 }378 );1 unmodified line380 381 #[test]382 fn tokens_with_basename() {383 assert_eq!(384+ CommandSet::new(vec![vec!["echo", "{/}"]], None).unwrap(),336- CommandTemplate::new(&["echo", "{/}"], None),337- CommandTemplate {338- args: vec![339- ArgumentTemplate::Text("echo".into()),340- ArgumentTemplate::Tokens(vec![Token::Basename]),341- ],385+ CommandSet {386+ commands: vec![CommandTemplate {387+ args: vec![388+ ArgumentTemplate::Text("echo".into()),389+ ArgumentTemplate::Tokens(vec![Token::Basename]),390+ ],391+ }],392 mode: ExecutionMode::OneByOne,393 path_separator: None,394 }395 );1 unmodified line397 398 #[test]399 fn tokens_with_parent() {400 assert_eq!(401+ CommandSet::new(vec![vec!["echo", "{//}"]], None).unwrap(),351- CommandTemplate::new(&["echo", "{//}"], None),352- CommandTemplate {353- args: vec![354- ArgumentTemplate::Text("echo".into()),355- ArgumentTemplate::Tokens(vec![Token::Parent]),356- ],402+ CommandSet {403+ commands: vec![CommandTemplate {404+ args: vec![405+ ArgumentTemplate::Text("echo".into()),406+ ArgumentTemplate::Tokens(vec![Token::Parent]),407+ ],408+ }],409 mode: ExecutionMode::OneByOne,410 path_separator: None,411 }412 );1 unmodified line414 415 #[test]416 fn tokens_with_basename_no_extension() {417 assert_eq!(418+ CommandSet::new(vec![vec!["echo", "{/.}"]], None).unwrap(),366- CommandTemplate::new(&["echo", "{/.}"], None),367- CommandTemplate {368- args: vec![369- ArgumentTemplate::Text("echo".into()),370- ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),371- ],419+ CommandSet {420+ commands: vec![CommandTemplate {421+ args: vec![422+ ArgumentTemplate::Text("echo".into()),423+ ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),424+ ],425+ }],426 mode: ExecutionMode::OneByOne,427 path_separator: None,428 }429 );1 unmodified line431 432 #[test]433 fn tokens_multiple() {434 assert_eq!(435+ CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None).unwrap(),381- CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),382- CommandTemplate {383- args: vec![384- ArgumentTemplate::Text("cp".into()),385- ArgumentTemplate::Tokens(vec![Token::Placeholder]),386- ArgumentTemplate::Tokens(vec![387- Token::BasenameNoExt,388- Token::Text(".ext".into())389- ]),390- ],436+ CommandSet {437+ commands: vec![CommandTemplate {438+ args: vec![439+ ArgumentTemplate::Text("cp".into()),440+ ArgumentTemplate::Tokens(vec![Token::Placeholder]),441+ ArgumentTemplate::Tokens(vec![442+ Token::BasenameNoExt,443+ Token::Text(".ext".into())444+ ]),445+ ],446+ }],447 mode: ExecutionMode::OneByOne,448 path_separator: None,449 }450 );1 unmodified line452 453 #[test]454 fn tokens_single_batch() {455 assert_eq!(456+ CommandSet::new_batch(vec![vec!["echo", "{.}"]], None).unwrap(),400- CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),401- CommandTemplate {402- args: vec![403- ArgumentTemplate::Text("echo".into()),404- ArgumentTemplate::Tokens(vec![Token::NoExt]),405- ],457+ CommandSet {458+ commands: vec![CommandTemplate {459+ args: vec![460+ ArgumentTemplate::Text("echo".into()),461+ ArgumentTemplate::Tokens(vec![Token::NoExt]),462+ ],463+ }],464 mode: ExecutionMode::Batch,465 path_separator: None,466 }467 );468 }469 470 #[test]471 fn tokens_multiple_batch() {414- assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());472+ assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());473 }474 475 #[test]476+ fn template_no_args() {477+ assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());478+ }479+480+ #[test]481+ fn command_set_no_args() {482+ assert!(CommandSet::new(vec![vec!["echo"], vec![]], None).is_err());483+ }484+485+ #[test]486 fn generate_custom_path_separator() {487 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);488 macro_rules! check {489 ($input:expr, $expected:expr) => {37 unmodified linesmodified:src/app.rs+133 added-121 removed
1-use clap::{crate_version, App, AppSettings, Arg};1+use clap::{crate_version, AppSettings, Arg, ColorChoice, Command};2 3-pub fn build_app() -> App<'static, 'static> {4- let clap_color_setting = if std::env::var_os("NO_COLOR").is_none() {5- AppSettings::ColoredHelp3+pub fn build_app() -> Command<'static> {4+ let clap_color_choice = if std::env::var_os("NO_COLOR").is_none() {5+ ColorChoice::Auto6 } else {7- AppSettings::ColorNever7+ ColorChoice::Never8 };9 10- let mut app = App::new("fd")10+ let mut app = Command::new("fd")11 .version(crate_version!())12- .usage("fd [FLAGS/OPTIONS] [<pattern>] [<path>...]")13- .setting(clap_color_setting)12+ .color(clap_color_choice)13 .setting(AppSettings::DeriveDisplayOrder)14+ .dont_collapse_args_in_usage(true)15 .after_help(16 "Note: `fd -h` prints a short and concise overview while `fd --help` gives all \17 details.",18 )19 .arg(20- Arg::with_name("hidden")20+ Arg::new("hidden")21 .long("hidden")22- .short("H")22+ .short('H')23 .overrides_with("hidden")24 .help("Search hidden files and directories")25 .long_help(26 "Include hidden directories and files in the search results (default: \2 unmodified lines29 The flag can be overridden with --no-hidden.",30 ),31 )32 .arg(33- Arg::with_name("no-hidden")33+ Arg::new("no-hidden")34 .long("no-hidden")35 .overrides_with("hidden")36- .hidden(true)36+ .hide(true)37 .long_help(38 "Overrides --hidden.",39 ),40 )41 .arg(42- Arg::with_name("no-ignore")42+ Arg::new("no-ignore")43 .long("no-ignore")44- .short("I")44+ .short('I')45 .overrides_with("no-ignore")46 .help("Do not respect .(git|fd)ignore files")47 .long_help(48 "Show search results from files and directories that would otherwise be \1 unmodified line50 The flag can be overridden with --ignore.",51 ),52 )53 .arg(54- Arg::with_name("ignore")54+ Arg::new("ignore")55 .long("ignore")56 .overrides_with("no-ignore")57- .hidden(true)57+ .hide(true)58 .long_help(59 "Overrides --no-ignore.",60 ),61 )62 .arg(63- Arg::with_name("no-ignore-vcs")63+ Arg::new("no-ignore-vcs")64 .long("no-ignore-vcs")65 .overrides_with("no-ignore-vcs")66- .hidden_short_help(true)66+ .hide_short_help(true)67 .help("Do not respect .gitignore files")68 .long_help(69 "Show search results from files and directories that would otherwise be \70 ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs.",71 ),72 )73 .arg(74- Arg::with_name("ignore-vcs")74+ Arg::new("ignore-vcs")75 .long("ignore-vcs")76 .overrides_with("no-ignore-vcs")77- .hidden(true)77+ .hide(true)78 .long_help(79 "Overrides --no-ignore-vcs.",80 ),81 )82 .arg(83- Arg::with_name("no-ignore-parent")83+ Arg::new("no-ignore-parent")84 .long("no-ignore-parent")85 .overrides_with("no-ignore-parent")86- .hidden_short_help(true)86+ .hide_short_help(true)87 .help("Do not respect .(git|fd)ignore files in parent directories")88 .long_help(89 "Show search results from files and directories that would otherwise be \90 ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.",91 ),92 )93 .arg(94- Arg::with_name("no-global-ignore-file")94+ Arg::new("no-global-ignore-file")95 .long("no-global-ignore-file")96- .hidden(true)96+ .hide(true)97 .help("Do not respect the global ignore file")98 .long_help("Do not respect the global ignore file."),99 )100 .arg(101- Arg::with_name("rg-alias-hidden-ignore")102- .short("u")101+ Arg::new("rg-alias-hidden-ignore")102+ .short('u')103 .long("unrestricted")104 .overrides_with_all(&["ignore", "no-hidden"])105- .multiple(true)106- .hidden_short_help(true)105+ .multiple_occurrences(true)106+ .hide_short_help(true)107 .help("Alias for '--no-ignore', and '--hidden' when given twice")108 .long_help(109 "Alias for '--no-ignore'. Can be repeated. '-uu' is an alias for \110 '--no-ignore --hidden'.",111 ),112 )113 .arg(114- Arg::with_name("case-sensitive")114+ Arg::new("case-sensitive")115 .long("case-sensitive")116- .short("s")116+ .short('s')117 .overrides_with_all(&["ignore-case", "case-sensitive"])118 .help("Case-sensitive search (default: smart case)")119 .long_help(120 "Perform a case-sensitive search. By default, fd uses case-insensitive \1 unmodified line122 case).",123 ),124 )125 .arg(126- Arg::with_name("ignore-case")126+ Arg::new("ignore-case")127 .long("ignore-case")128- .short("i")128+ .short('i')129 .overrides_with_all(&["case-sensitive", "ignore-case"])130 .help("Case-insensitive search (default: smart case)")131 .long_help(132 "Perform a case-insensitive search. By default, fd uses case-insensitive \1 unmodified line134 case).",135 ),136 )137 .arg(138- Arg::with_name("glob")138+ Arg::new("glob")139 .long("glob")140- .short("g")140+ .short('g')141 .conflicts_with("fixed-strings")142 .overrides_with("glob")143 .help("Glob-based search (default: regular expression)")144 .long_help("Perform a glob-based search instead of a regular expression search."),145 )146 .arg(147- Arg::with_name("regex")147+ Arg::new("regex")148 .long("regex")149 .overrides_with_all(&["glob", "regex"])150- .hidden_short_help(true)150+ .hide_short_help(true)151 .help("Regular-expression based search (default)")152 .long_help(153 "Perform a regular-expression based search (default). This can be used to \154 override --glob.",155 ),156 )157 .arg(158- Arg::with_name("fixed-strings")158+ Arg::new("fixed-strings")159 .long("fixed-strings")160- .short("F")160+ .short('F')161 .alias("literal")162 .overrides_with("fixed-strings")163- .hidden_short_help(true)163+ .hide_short_help(true)164 .help("Treat pattern as literal string instead of regex")165 .long_help(166 "Treat the pattern as a literal string instead of a regular expression. Note \167 that this also performs substring comparison. If you want to match on an \168 exact filename, consider using '--glob'.",169 ),170 )171 .arg(172- Arg::with_name("absolute-path")172+ Arg::new("absolute-path")173 .long("absolute-path")174- .short("a")174+ .short('a')175 .overrides_with("absolute-path")176 .help("Show absolute instead of relative paths")177 .long_help(178 "Shows the full path starting from the root as opposed to relative paths. \179 The flag can be overridden with --relative-path.",180 ),181 )182 .arg(183- Arg::with_name("relative-path")183+ Arg::new("relative-path")184 .long("relative-path")185 .overrides_with("absolute-path")186- .hidden(true)186+ .hide(true)187 .long_help(188 "Overrides --absolute-path.",189 ),190 )191 .arg(192- Arg::with_name("list-details")192+ Arg::new("list-details")193 .long("list-details")194- .short("l")194+ .short('l')195 .conflicts_with("absolute-path")196 .help("Use a long listing format with file metadata")197 .long_help(198 "Use a detailed listing format like 'ls -l'. This is basically an alias \2 unmodified lines201 deterministic sort order.",202 ),203 )204 .arg(205- Arg::with_name("follow")205+ Arg::new("follow")206 .long("follow")207- .short("L")207+ .short('L')208 .alias("dereference")209 .overrides_with("follow")210 .help("Follow symbolic links")211 .long_help(2 unmodified lines214 Flag can be overriden with --no-follow.",215 ),216 )217 .arg(218- Arg::with_name("no-follow")218+ Arg::new("no-follow")219 .long("no-follow")220 .overrides_with("follow")221- .hidden(true)221+ .hide(true)222 .long_help(223 "Overrides --follow.",224 ),225 )226 .arg(227- Arg::with_name("full-path")227+ Arg::new("full-path")228 .long("full-path")229- .short("p")229+ .short('p')230 .overrides_with("full-path")231 .help("Search full abs. path (default: filename only)")232 .long_help(233 "By default, the search pattern is only matched against the filename (or \2 unmodified lines236 fd --glob -p '**/.git/config'",237 ),238 )239 .arg(240- Arg::with_name("null_separator")240+ Arg::new("null_separator")241 .long("print0")242- .short("0")242+ .short('0')243 .overrides_with("print0")244 .conflicts_with("list-details")245- .hidden_short_help(true)245+ .hide_short_help(true)246 .help("Separate results by the null character")247 .long_help(248 "Separate search results by the null character (instead of newlines). \249 Useful for piping results to 'xargs'.",250 ),251 )252 .arg(253- Arg::with_name("max-depth")253+ Arg::new("max-depth")254 .long("max-depth")255- .short("d")255+ .short('d')256 .takes_value(true)257 .value_name("depth")258 .help("Set maximum search depth (default: none)")259 .long_help(2 unmodified lines262 ),263 )264 // support --maxdepth as well, for compatibility with rg265 .arg(266- Arg::with_name("rg-depth")266+ Arg::new("rg-depth")267 .long("maxdepth")268- .hidden(true)268+ .hide(true)269 .takes_value(true)270 .help("Set maximum search depth (default: none)")271 )272 .arg(273- Arg::with_name("min-depth")273+ Arg::new("min-depth")274 .long("min-depth")275 .takes_value(true)276 .value_name("depth")277- .hidden_short_help(true)277+ .hide_short_help(true)278 .help("Only show results starting at given depth")279 .long_help(280 "Only show search results starting at the given depth. \281 See also: '--max-depth' and '--exact-depth'",282 ),283 )284 .arg(285- Arg::with_name("exact-depth")285+ Arg::new("exact-depth")286 .long("exact-depth")287 .takes_value(true)288 .value_name("depth")289- .hidden_short_help(true)289+ .hide_short_help(true)290 .conflicts_with_all(&["max-depth", "min-depth"])291 .help("Only show results at exact given depth")292 .long_help(293 "Only show search results at the exact given depth. This is an alias for \294 '--min-depth <depth> --max-depth <depth>'.",295 ),296 )297 .arg(298- Arg::with_name("prune")298+ Arg::new("prune")299 .long("prune")300 .conflicts_with_all(&["size", "exact-depth"])301- .hidden_short_help(true)301+ .hide_short_help(true)302 .help("Do not traverse into matching directories")303 .long_help("Do not traverse into directories that match the search criteria. If \304 you want to exclude specific directories, use the '--exclude=…' option.")305 )306 .arg(307- Arg::with_name("file-type")307+ Arg::new("file-type")308 .long("type")309- .short("t")310- .multiple(true)309+ .short('t')310+ .multiple_occurrences(true)311 .number_of_values(1)312 .takes_value(true)313 .value_name("filetype")314 .possible_values(&[50 unmodified lines365 fd -te -td"366 ),367 )368 .arg(369- Arg::with_name("extension")369+ Arg::new("extension")370 .long("extension")371- .short("e")372- .multiple(true)371+ .short('e')372+ .multiple_occurrences(true)373 .number_of_values(1)374 .takes_value(true)375 .value_name("ext")376 .help("Filter by file extension")4 unmodified lines381 you can use the regex '^[^.]+$' as a normal search pattern.",382 ),383 )384 .arg(385- Arg::with_name("exec")385+ Arg::new("exec")386 .long("exec")387- .short("x")387+ .short('x')388 .min_values(1)389+ .multiple_occurrences(true)390 .allow_hyphen_values(true)391 .value_terminator(";")392 .value_name("cmd")393 .conflicts_with("list-details")19 unmodified lines413 ",414 ),415 )416 .arg(416- Arg::with_name("exec-batch")417+ Arg::new("exec-batch")418 .long("exec-batch")418- .short("X")419+ .short('X')420 .min_values(1)421+ .multiple_occurrences(true)422 .allow_hyphen_values(true)423 .value_terminator(";")424 .value_name("cmd")425 .conflicts_with_all(&["exec", "list-details"])15 unmodified lines441 "442 ),443 )444 .arg(443- Arg::with_name("batch-size")445+ Arg::new("batch-size")446 .long("batch-size")447 .takes_value(true)448 .value_name("size")447- .hidden_short_help(true)449+ .hide_short_help(true)450 .requires("exec-batch")451 .help("Max number of arguments to run as a batch with -X")452 .long_help(453 "Maximum number of arguments to pass to the command given with -X. \2 unmodified lines456 A batch size of zero means there is no limit.",457 ),458 )459 .arg(458- Arg::with_name("exclude")460+ Arg::new("exclude")461 .long("exclude")460- .short("E")462+ .short('E')463 .takes_value(true)464 .value_name("pattern")465 .number_of_values(1)464- .multiple(true)466+ .multiple_occurrences(true)467 .help("Exclude entries that match the given glob pattern")468 .long_help(469 "Exclude files/directories that match the given glob pattern. This \470 overrides any other ignore logic. Multiple exclude patterns can be \3 unmodified lines474 --exclude node_modules",475 ),476 )477 .arg(476- Arg::with_name("ignore-file")478+ Arg::new("ignore-file")479 .long("ignore-file")480 .takes_value(true)481 .value_name("path")482 .number_of_values(1)481- .multiple(true)482- .hidden_short_help(true)483+ .multiple_occurrences(true)484+ .hide_short_help(true)485 .help("Add custom ignore-file in '.gitignore' format")486 .long_help(487 "Add a custom ignore-file in '.gitignore' format. These files have a low \488 precedence.",489 ),490 )491 .arg(490- Arg::with_name("color")492+ Arg::new("color")493 .long("color")492- .short("c")494+ .short('c')495 .takes_value(true)496 .value_name("when")497 .possible_values(&["never", "auto", "always"])498 .hide_possible_values(true)5 unmodified lines504 'always': always use colorized output",505 ),506 )507 .arg(506- Arg::with_name("threads")508+ Arg::new("threads")509 .long("threads")508- .short("j")510+ .short('j')511 .takes_value(true)512 .value_name("num")511- .hidden_short_help(true)513+ .hide_short_help(true)514 .help("Set number of threads")515 .long_help(516 "Set number of threads to use for searching & executing (default: number \517 of available CPU cores)",518 ),519 )520 .arg(519- Arg::with_name("size")521+ Arg::new("size")522 .long("size")521- .short("S")523+ .short('S')524 .takes_value(true)525 .number_of_values(1)526 .allow_hyphen_values(true)525- .multiple(true)527+ .multiple_occurrences(true)528 .help("Limit results based on the size of files")529 .long_help(530 "Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \531 '+': file size must be greater than or equal to this\n \13 unmodified lines545 'ti': tebibytes",546 ),547 )548 .arg(547- Arg::with_name("max-buffer-time")549+ Arg::new("max-buffer-time")550 .long("max-buffer-time")551 .takes_value(true)550- .hidden(true)552+ .hide(true)553 .help("Milliseconds to buffer before streaming search results to console")554 .long_help(555 "Amount of time in milliseconds to buffer, before streaming the search \556 results to the console.",557 ),558 )559 .arg(558- Arg::with_name("changed-within")560+ Arg::new("changed-within")561 .long("changed-within")562 .alias("change-newer-than")563 .alias("newer")564 .takes_value(true)11 unmodified lines576 --newer 2018-10-27",577 ),578 )579 .arg(578- Arg::with_name("changed-before")580+ Arg::new("changed-before")581 .long("changed-before")582 .alias("change-older-than")583 .alias("older")584 .takes_value(true)10 unmodified lines595 --older 2018-10-27",596 ),597 )598 .arg(597- Arg::with_name("max-results")599+ Arg::new("max-results")600 .long("max-results")601 .takes_value(true)602 .value_name("count")603 // We currently do not support --max-results in combination with1 unmodified line605 // search are non-deterministic. Users might think that they can run the606 // same search with `--exec rm` attached and get a reliable removal of607 // the files they saw in the previous search.608 .conflicts_with_all(&["exec", "exec-batch", "list-details"])607- .hidden_short_help(true)609+ .hide_short_help(true)610 .help("Limit number of search results")611 .long_help("Limit the number of search results to 'count' and quit immediately."),612 )613 .arg(612- Arg::with_name("max-one-result")613- .short("1")614- .hidden_short_help(true)614+ Arg::new("max-one-result")615+ .short('1')616+ .hide_short_help(true)617 .overrides_with("max-results")618 .conflicts_with_all(&["exec", "exec-batch", "list-details"])619 .help("Limit search to a single result")620 .long_help("Limit the search to a single result and quit immediately. \621 This is an alias for '--max-results=1'.")622 )623 .arg(622- Arg::with_name("quiet")624+ Arg::new("quiet")625 .long("quiet")624- .short("q")626+ .short('q')627 .alias("has-results")626- .hidden_short_help(true)628+ .hide_short_help(true)629 .conflicts_with_all(&["exec", "exec-batch", "list-details", "max-results"])630 .help("Print nothing, exit code 0 if match found, 1 otherwise")631 .long_help(632 "When the flag is present, the program does not print anything and will \2 unmodified lines635 '--has-results' can be used as an alias."636 )637 )638 .arg(637- Arg::with_name("show-errors")639+ Arg::new("show-errors")640 .long("show-errors")639- .hidden_short_help(true)641+ .hide_short_help(true)642 .overrides_with("show-errors")643 .help("Show filesystem errors")644 .long_help(645 "Enable the display of filesystem errors for situations such as \646 insufficient permissions or dead symlinks.",647 ),648 )649 .arg(648- Arg::with_name("base-directory")650+ Arg::new("base-directory")651 .long("base-directory")652 .takes_value(true)653 .value_name("path")654 .number_of_values(1)655+ .allow_invalid_utf8(true)653- .hidden_short_help(true)656+ .hide_short_help(true)657 .help("Change current working directory")658 .long_help(659 "Change the current working directory of fd to the provided path. This \660 means that search results will be shown with respect to the given base \2 unmodified lines663 relative to this directory.",664 ),665 )666 .arg(664- Arg::with_name("pattern").help(667+ Arg::new("pattern")668+ .allow_invalid_utf8(true)669+ .help(670 "the search pattern (a regular expression, unless '--glob' is used; optional)",671 ).long_help(672 "the search pattern which is either a regular expression (default) or a glob \673 pattern (if --glob is used). If no pattern has been specified, every entry \674 is considered a match. If your pattern starts with a dash (-), make sure to \675 pass '--' first, or it will be considered as a flag (fd -- '-foo').")676 )677 .arg(673- Arg::with_name("path-separator")678+ Arg::new("path-separator")679 .takes_value(true)680 .value_name("separator")681 .long("path-separator")677- .hidden_short_help(true)682+ .hide_short_help(true)683 .help("Set path separator when printing file paths")684 .long_help(685 "Set the path separator to use when printing file paths. The default is \686 the OS-specific separator ('/' on Unix, '\\' on Windows).",687 ),688 )689 .arg(685- Arg::with_name("path")686- .multiple(true)690+ Arg::new("path")691+ .multiple_occurrences(true)692+ .allow_invalid_utf8(true)693 .help("the root directory for the filesystem search (optional)")694 .long_help(695 "The directory where the filesystem search is rooted (optional). If \696 omitted, search the current working directory.",697 ),698 )699 .arg(694- Arg::with_name("search-path")700+ Arg::new("search-path")701 .long("search-path")702 .takes_value(true)703 .conflicts_with("path")698- .multiple(true)699- .hidden_short_help(true)704+ .multiple_occurrences(true)705+ .hide_short_help(true)706 .number_of_values(1)707+ .allow_invalid_utf8(true)708 .help("Provide paths to search as an alternative to the positional <path>")709 .long_help(710 "Provide paths to search as an alternative to the positional <path> \704- argument. Changes the usage to `fd [FLAGS/OPTIONS] --search-path <path> \711+ argument. Changes the usage to `fd [OPTIONS] --search-path <path> \712 --search-path <path2> [<pattern>]`",713 ),714 )715 .arg(709- Arg::with_name("strip-cwd-prefix")716+ Arg::new("strip-cwd-prefix")717 .long("strip-cwd-prefix")718 .conflicts_with_all(&["path", "search-path"])712- .hidden_short_help(true)719+ .hide_short_help(true)720 .help("strip './' prefix from non-tty outputs")721 .long_help(722 "By default, relative paths are prefixed with './' when the output goes to a non \723 interactive terminal (TTY). Use this flag to disable this behaviour."1 unmodified line725 );726 727 if cfg!(unix) {728 app = app.arg(722- Arg::with_name("owner")729+ Arg::new("owner")730 .long("owner")724- .short("o")731+ .short('o')732 .takes_value(true)733 .value_name("user:group")734 .help("Filter by owning user and/or group")735 .long_help(12 unmodified lines748 // restrictions on the corresponding option in the `ignore` crate.749 // Provide aliases `mount` and `xdev` for people coming from `find`.750 if cfg!(any(unix, windows)) {751 app = app.arg(745- Arg::with_name("one-file-system")752+ Arg::new("one-file-system")753 .long("one-file-system")754 .aliases(&["mount", "xdev"])748- .hidden_short_help(true)755+ .hide_short_help(true)756 .help("Do not descend into a different file system")757 .long_help(758 "By default, fd will traverse the file system tree as far as other options \759 dictate. With this flag, fd ensures that it does not descend into a \4 unmodified lines764 }765 766 app767 }768+769+#[test]770+fn verify_app() {771+ build_app().debug_assert()772+}modified:src/config.rs+2 added-2 removed
1 unmodified line2 3 use lscolors::LsColors;4 use regex::bytes::RegexSet;5 6-use crate::exec::CommandTemplate;6+use crate::exec::CommandSet;7 use crate::filetypes::FileTypes;8 #[cfg(unix)]9 use crate::filter::OwnerFilter;10 use crate::filter::{SizeFilter, TimeFilter};71 unmodified lines82 /// The value (if present) will be a lowercase string without leading dots.83 pub extensions: Option<RegexSet>,84 85 /// If a value is supplied, each item found will be used to generate and execute commands.86- pub command: Option<Arc<CommandTemplate>>,86+ pub command: Option<Arc<CommandSet>>,87 88 /// Maximum number of search results to pass to each `command`. If zero, the number is89 /// unlimited.90 pub batch_size: usize,29 unmodified linesmodified:src/main.rs+14 added-19 removed
23 unmodified lines24 use regex::bytes::{RegexBuilder, RegexSetBuilder};25 26 use crate::config::Config;27 use crate::error::print_error;28-use crate::exec::CommandTemplate;28+use crate::exec::CommandSet;29 use crate::exit_codes::ExitCode;30 use crate::filetypes::FileTypes;31 #[cfg(unix)]32 use crate::filter::OwnerFilter;6 unmodified lines39 not(windows),40 not(target_os = "android"),41 not(target_os = "macos"),42 not(target_os = "freebsd"),43- not(target_env = "musl")43+ not(target_env = "musl"),44+ not(target_arch = "riscv64"),45+ feature = "use-jemalloc"46 ))]47 #[global_allocator]48 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;49 62 unmodified lines112 ))113 }114 }115 114-fn extract_search_pattern<'a>(matches: &'a clap::ArgMatches) -> Result<&'a str> {116+fn extract_search_pattern(matches: &clap::ArgMatches) -> Result<&'_ str> {117 let pattern = matches118 .value_of_os("pattern")119 .map(|p| {120 p.to_str()141 unmodified lines262 || matches.is_present("rg-alias-hidden-ignore")),263 read_vcsignore: !(matches.is_present("no-ignore")264 || matches.is_present("rg-alias-hidden-ignore")265 || matches.is_present("no-ignore-vcs")),264- read_parent_ignore: !(matches.is_present("no-ignore")265- || matches.is_present("rg-alias-hidden-ignore")266- || matches.is_present("no-ignore-vcs")267- || matches.is_present("no-ignore-parent")),266+ read_parent_ignore: !matches.is_present("no-ignore-parent"),267 read_global_ignore: !(matches.is_present("no-ignore")268 || matches.is_present("rg-alias-hidden-ignore")269 || matches.is_present("no-global-ignore-file")),270 follow_links: matches.is_present("follow"),119 unmodified lines390 fn extract_command(391 matches: &clap::ArgMatches,392 path_separator: Option<&str>,393 colored_output: bool,395-) -> Result<Option<CommandTemplate>> {394+) -> Result<Option<CommandSet>> {395 None.or_else(|| {397- matches.values_of("exec").map(|args| {398- Ok(CommandTemplate::new(399- args,400- path_separator.map(str::to_string),401- ))402- })396+ matches397+ .grouped_values_of("exec")398+ .map(|args| CommandSet::new(args, path_separator.map(str::to_string)))399 })400 .or_else(|| {401 matches406- .values_of("exec-batch")407- .map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))402+ .grouped_values_of("exec-batch")403+ .map(|args| CommandSet::new_batch(args, path_separator.map(str::to_string)))404 })405 .or_else(|| {406 if !matches.is_present("list-details") {407 return None;1 unmodified line409 410 let color = matches.value_of("color").unwrap_or("auto");411 let color_arg = format!("--color={}", color);412 417- let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {418- CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()419- });413+ let res = determine_ls_command(&color_arg, colored_output)414+ .map(|cmd| CommandSet::new_batch([cmd], path_separator.map(str::to_string)).unwrap());415 416 Some(res)417 })418 .transpose()147 unmodified linesmodified:src/walk.rs+11 added-19 removed
1 unmodified line2 use std::io;3 use std::mem;4 use std::path::PathBuf;5 use std::sync::atomic::{AtomicBool, Ordering};6+use std::sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender};7 use std::sync::{Arc, Mutex};8 use std::thread;9 use std::time::{Duration, Instant};10 use std::{borrow::Cow, io::Write};11 12 use anyhow::{anyhow, Result};12-use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};13 use ignore::overrides::OverrideBuilder;14 use ignore::{self, WalkBuilder};15 use regex::bytes::Regex;16 36 unmodified lines53 let mut path_iter = path_vec.iter();54 let first_path_buf = path_iter55 .next()56 .expect("Error: Path vector can not be empty");57- let (tx, rx) = unbounded();57+ let (tx, rx) = channel();58 59 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());60 61 for pattern in &config.exclude_patterns {8 unmodified lines70 let mut walker = WalkBuilder::new(first_path_buf.as_path());71 walker72 .hidden(config.ignore_hidden)73 .ignore(config.read_fdignore)74- .parents(config.read_parent_ignore)74+ .parents(config.read_parent_ignore && (config.read_fdignore || config.read_vcsignore))75 .git_ignore(config.read_vcsignore)76 .git_global(config.read_vcsignore)77 .git_exclude(config.read_vcsignore)78 .overrides(overrides)23 unmodified lines102 let result = walker.add_ignore(global_ignore_file);103 match result {104 Some(ignore::Error::Partial(_)) => (),105 Some(err) => {106- print_error(format!(107- "Malformed pattern in global ignore file. {}.",108- err.to_string()109- ));106+ print_error(format!("Malformed pattern in global ignore file. {}.", err));107 }108 None => (),109 }110 }3 unmodified lines114 let result = walker.add_ignore(ignore_file);115 match result {116 Some(ignore::Error::Partial(_)) => (),117 Some(err) => {121- print_error(format!(122- "Malformed pattern in custom ignore file. {}.",123- err.to_string()124- ));118+ print_error(format!("Malformed pattern in custom ignore file. {}.", err));119 }120 None => (),121 }122 }101 unmodified lines224 fn recv(&self) -> Result<WorkerResult, RecvTimeoutError> {225 match self.mode {226 ReceiverMode::Buffering => {227 // Wait at most until we should switch to streaming234- self.rx.recv_deadline(self.deadline)228+ let now = Instant::now();229+ self.deadline230+ .checked_duration_since(now)231+ .ok_or(RecvTimeoutError::Timeout)232+ .and_then(|t| self.rx.recv_timeout(t))233 }234 ReceiverMode::Streaming => {235 // Wait however long it takes for a result236 Ok(self.rx.recv()?)111 unmodified lines348 thread::spawn(move || {349 // This will be set to `Some` if the `--exec` argument was supplied.350 if let Some(ref cmd) = config.command {351 if cmd.in_batch_mode() {354- exec::batch(355- rx,356- cmd,357- show_filesystem_errors,358- enable_output_buffering,359- config.batch_size,360- )352+ exec::batch(rx, cmd, show_filesystem_errors, config.batch_size)353 } else {354 let shared_rx = Arc::new(Mutex::new(rx));355 356 let out_perm = Arc::new(Mutex::new(()));206 unmodified linesmodified:tests/testenv/mod.rs+27 added-13 removed
128 unmodified lines129 lines.sort();130 lines.join("\n")131 }132 133+/// Trim whitespace from the beginning of each line.134+fn trim_lines(s: &str) -> String {135+ s.lines()136+ .map(|line| line.trim_start())137+ .fold(String::new(), |mut str, line| {138+ str.push_str(line);139+ str.push('\n');140+ str141+ })142+}143+144 impl TestEnv {145 pub fn new(directories: &[&'static str], files: &[&'static str]) -> TestEnv {146 let temp_dir = create_working_directory(directories, files).expect("working directory");147 let fd_exe = find_fd_exe();65 unmodified lines213 214 output215 }216 217+ pub fn assert_success_and_get_normalized_output<P: AsRef<Path>>(218+ &self,219+ path: P,220+ args: &[&str],221+ ) -> String {222+ let output = self.assert_success_and_get_output(path, args);223+ normalize_output(224+ &String::from_utf8_lossy(&output.stdout),225+ false,226+ self.normalize_line,227+ )228+ }229+230 /// Assert that calling *fd* with the specified arguments produces the expected output.231 pub fn assert_output(&self, args: &[&str], expected: &str) {232 self.assert_output_subdirectory(".", args, expected)233 }13 unmodified lines247 path: P,248 args: &[&str],249 expected: &str,250 ) {227- let output = self.assert_success_and_get_output(path, args);228-251 // Normalize both expected and actual output.252 let expected = normalize_output(expected, true, self.normalize_line);231- let actual = normalize_output(232- &String::from_utf8_lossy(&output.stdout),233- false,234- self.normalize_line,235- );253+ let actual = self.assert_success_and_get_normalized_output(path, args);254 255 // Compare actual output to expected output.256 if expected != actual {257 panic!("{}", format_output_error(args, &expected, &actual));39 unmodified lines297 let output = cmd.output().expect("fd output");298 299 if let Some(expected) = expected {300 // Normalize both expected and actual output.283- let expected_error = normalize_output(expected, true, self.normalize_line);284- let actual_err = normalize_output(285- &String::from_utf8_lossy(&output.stderr),286- false,287- self.normalize_line,288- );301+ let expected_error = trim_lines(expected);302+ let actual_err = trim_lines(&String::from_utf8_lossy(&output.stderr));303 304 // Compare actual output to expected output.305 if !actual_err.trim_start().starts_with(&expected_error) {306 panic!(9 unmodified linesmodified:tests/tests.rs+96 added-4 removed
612 unmodified lines613 ./one/two/three/directory_foo/",614 );615 }616 617+/// Test that --no-ignore-vcs still respects .fdignored in parent directory618+#[test]619+fn test_no_ignore_vcs_child_dir() {620+ let te = TestEnv::new(621+ &["inner"],622+ &["inner/fdignored.foo", "inner/foo", "inner/gitignored.foo"],623+ );624+625+ te.assert_output_subdirectory(626+ "inner",627+ &["--no-ignore-vcs", "foo"],628+ "./foo629+ ./gitignored.foo",630+ );631+}632+633 /// Custom ignore files (--ignore-file)634 #[test]635 fn test_custom_ignore_files() {636 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);746 unmodified lines1383 }1384 }1385 1386 #[test]1387+fn test_exec_multi() {1388+ // TODO test for windows1389+ if cfg!(windows) {1390+ return;1391+ }1392+ let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1393+1394+ te.assert_output(1395+ &[1396+ "--absolute-path",1397+ "foo",1398+ "--exec",1399+ "echo",1400+ ";",1401+ "--exec",1402+ "echo",1403+ "test",1404+ "{/}",1405+ ],1406+ &format!(1407+ "{abs_path}/a.foo1408+ {abs_path}/one/b.foo1409+ {abs_path}/one/two/C.Foo21410+ {abs_path}/one/two/c.foo1411+ {abs_path}/one/two/three/d.foo1412+ {abs_path}/one/two/three/directory_foo1413+ test a.foo1414+ test b.foo1415+ test C.Foo21416+ test c.foo1417+ test d.foo1418+ test directory_foo",1419+ abs_path = &abs_path1420+ ),1421+ );1422+1423+ te.assert_output(1424+ &[1425+ "e1", "--exec", "echo", "{.}", ";", "--exec", "echo", "{/}", ";", "--exec", "echo",1426+ "{//}", ";", "--exec", "echo", "{/.}",1427+ ],1428+ "e1 e21429+ e1 e21430+ .1431+ e1 e2",1432+ );1433+1434+ te.assert_output(1435+ &[1436+ "foo", "--exec", "echo", "-n", "{/}: ", ";", "--exec", "echo", "{//}",1437+ ],1438+ "a.foo: .1439+ b.foo: ./one1440+ C.Foo2: ./one/two1441+ c.foo: ./one/two1442+ d.foo: ./one/two/three1443+ directory_foo: ./one/two/three",1444+ );1445+}1446+1447+#[test]1448 fn test_exec_batch() {1449 let (te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1450 let te = te.normalize_line(true);1451 28 unmodified lines1480 );1481 1482 te.assert_failure_with_error(1483 &["foo", "--exec-batch", "echo", "{/}", ";", "-x", "echo"],1407- "error: The argument '--exec <cmd>' cannot be used with '--exec-batch <cmd>'",1484+ "error: The argument '--exec-batch <cmd>...' cannot be used with '--exec <cmd>...'",1485 );1486 1487 te.assert_failure_with_error(1488 &["foo", "--exec-batch"],1412- "error: The argument '--exec-batch <cmd>' requires a value but none was supplied",1489+ "error: The argument '--exec-batch <cmd>...' requires a value but none was supplied",1490 );1491 1492 te.assert_failure_with_error(1493 &["foo", "--exec-batch", "echo {}"],2 unmodified lines1496 }1497 }1498 1499 #[test]1500+fn test_exec_batch_multi() {1501+ // TODO test for windows1502+ if cfg!(windows) {1503+ return;1504+ }1505+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1506+1507+ te.assert_output(1508+ &["foo", "--exec-batch", "echo", "{}", ";", "--exec-batch", "echo", "{/}"],1509+ "./a.foo ./one/b.foo ./one/two/C.Foo2 ./one/two/c.foo ./one/two/three/d.foo ./one/two/three/directory_foo1510+ a.foo b.foo C.Foo2 c.foo d.foo directory_foo",1511+ );1512+}1513+1514+#[test]1515 fn test_exec_batch_with_limit() {1516 // TODO Test for windows1517 if cfg!(windows) {1518 return;526 unmodified lines2045 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);2046 2047 let mut flags = vec![flag];2048 flags.extend_from_slice(opposing_flags);1957- let out_no_flags = te.assert_success_and_get_output(".", &[]);1958- let out_opposing_flags = te.assert_success_and_get_output(".", &flags);2049+ let out_no_flags = te.assert_success_and_get_normalized_output(".", &[]);2050+ let out_opposing_flags = te.assert_success_and_get_normalized_output(".", &flags);2051 2052 assert_eq!(2053 out_no_flags,2054 out_opposing_flags,40 unmodified linesmodified:build.rs+8 added-5 removed
1 use std::fs;2 3-use clap::Shell;3+use clap_complete::{generate_to, Shell};4+use Shell::*;5+//use clap_complete::shells::Shel{Bash, Fish, PowerShell, Elvish};6 7 include!("src/app.rs");8 9 fn main() {8- let min_version = "1.53";10+ let min_version = "1.56";11 12 match version_check::is_min_version(min_version) {13 Some(true) => {}14 // rustc version too small or can't figure it out10 unmodified lines25 };26 fs::create_dir_all(&outdir).unwrap();27 28 let mut app = build_app();27- app.gen_completions("fd", Shell::Bash, &outdir);28- app.gen_completions("fd", Shell::Fish, &outdir);29- app.gen_completions("fd", Shell::PowerShell, &outdir);29+ // NOTE: zsh completions are hand written in contrib/completion/_fd30+ for shell in [Bash, PowerShell, Fish, Elvish] {31+ generate_to(shell, &mut app, "fd", &outdir).unwrap();32+ }33 }modified:Cargo.lock+118 added-73 removed
20 unmodified lines21 ]22 23 [[package]]24 name = "anyhow"25-version = "1.0.51"25+version = "1.0.55"26 source = "registry+https://github.com/rust-lang/crates.io-index"27-checksum = "8b26702f315f53b6071259e15dd9d64528213b44d61de1ec926eca7715d62203"27+checksum = "159bb86af3a200e19a068f4224eae4c8bb2d0fa054c7e5d1cacd5cef95e684cd"28 29 [[package]]30 name = "atty"31 version = "0.2.14"6 unmodified lines38 ]39 40 [[package]]41 name = "autocfg"42-version = "1.0.1"42+version = "1.1.0"43 source = "registry+https://github.com/rust-lang/crates.io-index"44-checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"44+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"45 46 [[package]]47 name = "bitflags"48 version = "1.3.2"10 unmodified lines59 ]60 61 [[package]]62 name = "cc"63-version = "1.0.72"63+version = "1.0.73"64 source = "registry+https://github.com/rust-lang/crates.io-index"65-checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee"65+checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"66 67 [[package]]68 name = "cfg-if"69 version = "1.0.0"14 unmodified lines84 ]85 86 [[package]]87 name = "clap"88-version = "2.34.0"88+version = "3.1.5"89 source = "registry+https://github.com/rust-lang/crates.io-index"90-checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"90+checksum = "ced1892c55c910c1219e98d6fc8d71f6bddba7905866ce740066d8bfea859312"91 dependencies = [92- "ansi_term",92 "atty",93 "bitflags",94+ "indexmap",95+ "lazy_static",96+ "os_str_bytes",97 "strsim",96- "term_size",98+ "termcolor",99+ "terminal_size",100 "textwrap",98- "unicode-width",99- "vec_map",101 ]102 103 [[package]]103-name = "crossbeam-channel"104-version = "0.5.1"104+name = "clap_complete"105+version = "3.1.1"106 source = "registry+https://github.com/rust-lang/crates.io-index"106-checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4"107+checksum = "df6f3613c0a3cddfd78b41b10203eb322cb29b600cbdf808a7d3db95691b8e25"108 dependencies = [108- "cfg-if",109- "crossbeam-utils",109+ "clap",110 ]111 112 [[package]]113 name = "crossbeam-utils"114-version = "0.8.5"114+version = "0.8.7"115 source = "registry+https://github.com/rust-lang/crates.io-index"116-checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db"116+checksum = "b5e5bed1f1c269533fa816a0a5492b3545209a205ca1a54842be180eb63a16a6"117 dependencies = [118 "cfg-if",119 "lazy_static",120 ]36 unmodified lines157 ]158 159 [[package]]160 name = "fd-find"161-version = "8.3.0"161+version = "8.3.2"162 dependencies = [163 "ansi_term",164 "anyhow",165 "atty",166 "chrono",167 "clap",168- "crossbeam-channel",168+ "clap_complete",169 "ctrlc",170 "diff",171 "dirs-next",172 "filetime",46 unmodified lines219 checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"220 221 [[package]]222 name = "getrandom"223-version = "0.2.3"223+version = "0.2.5"224 source = "registry+https://github.com/rust-lang/crates.io-index"225-checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"225+checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77"226 dependencies = [227 "cfg-if",228 "libc",229 "wasi",12 unmodified lines242 "regex",243 ]244 245 [[package]]246+name = "hashbrown"247+version = "0.11.2"248+source = "registry+https://github.com/rust-lang/crates.io-index"249+checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"250+251+[[package]]252 name = "hermit-abi"253 version = "0.1.19"254 source = "registry+https://github.com/rust-lang/crates.io-index"255 checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"25 unmodified lines281 "winapi-util",282 ]283 284 [[package]]285+name = "indexmap"286+version = "1.8.0"287+source = "registry+https://github.com/rust-lang/crates.io-index"288+checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223"289+dependencies = [290+ "autocfg",291+ "hashbrown",292+]293+294+[[package]]295 name = "jemalloc-sys"296 version = "0.3.2"297 source = "registry+https://github.com/rust-lang/crates.io-index"298 checksum = "0d3b9f3f5c9b31aa0f5ed3260385ac205db665baa41d49bb8338008ae94ede45"20 unmodified lines319 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"320 321 [[package]]322 name = "libc"307-version = "0.2.108"323+version = "0.2.119"324 source = "registry+https://github.com/rust-lang/crates.io-index"309-checksum = "8521a1b57e76b1ec69af7599e75e38e7b7fad6610f037db8c79b127201b5d119"325+checksum = "1bf2e165bb3457c8e098ea76f3e3bc9db55f87aa90d52d0e6be741470916aaa4"326 327 [[package]]328 name = "log"329 version = "0.4.14"4 unmodified lines334 ]335 336 [[package]]337 name = "lscolors"322-version = "0.8.1"338+version = "0.9.0"339 source = "registry+https://github.com/rust-lang/crates.io-index"324-checksum = "9dd58d8727f3035fa6d5272f16b519741fd4875936b99d8a7cde21291b7d9174"340+checksum = "4e9323b3525d4efad2dead1837a105e313253bfdbad1d470994038eededa4d62"341 dependencies = [342 "ansi_term",343 ]344 4 unmodified lines349 checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"350 351 [[package]]352 name = "memoffset"337-version = "0.6.4"353+version = "0.6.5"354 source = "registry+https://github.com/rust-lang/crates.io-index"339-checksum = "59accc507f1338036a0477ef61afdae33cde60840f4dfe481319ce3ad116ddf9"355+checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"356 dependencies = [357 "autocfg",358 ]359 360 [[package]]361 name = "nix"346-version = "0.23.0"362+version = "0.23.1"363 source = "registry+https://github.com/rust-lang/crates.io-index"348-checksum = "f305c2c2e4c39a82f7bf0bf65fb557f9070ce06781d4f2454295cc34b1c43188"364+checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6"365 dependencies = [366 "bitflags",367 "cc",368 "cfg-if",2 unmodified lines371 ]372 373 [[package]]374 name = "normpath"359-version = "0.3.1"375+version = "0.3.2"376 source = "registry+https://github.com/rust-lang/crates.io-index"361-checksum = "640c20e9df4a2d4a5adad5b47e17d76dac3e824346b181931c3ec9f7a85687b1"377+checksum = "04aaf5e9cb0fbf883cc0423159eacdf96a9878022084b35c462c428cab73bcaf"378 dependencies = [379 "winapi",380 ]381 17 unmodified lines399 ]400 401 [[package]]402 name = "num_cpus"387-version = "1.13.0"403+version = "1.13.1"404 source = "registry+https://github.com/rust-lang/crates.io-index"389-checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3"405+checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"406 dependencies = [407 "hermit-abi",408 "libc",409 ]410 411 [[package]]412 name = "once_cell"397-version = "1.8.0"413+version = "1.9.0"414 source = "registry+https://github.com/rust-lang/crates.io-index"399-checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"415+checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5"416 417 [[package]]418+name = "os_str_bytes"419+version = "6.0.0"420+source = "registry+https://github.com/rust-lang/crates.io-index"421+checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"422+dependencies = [423+ "memchr",424+]425+426+[[package]]427+name = "proc-macro-error"428+version = "1.0.4"429+source = "registry+https://github.com/rust-lang/crates.io-index"430+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"431+dependencies = [432+ "proc-macro-error-attr",433+ "proc-macro2",434+ "quote",435+ "syn",436+ "version_check",437+]438+439+[[package]]440+name = "proc-macro-error-attr"441+version = "1.0.4"442+source = "registry+https://github.com/rust-lang/crates.io-index"443+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"444+dependencies = [445+ "proc-macro2",446+ "quote",447+ "version_check",448+]449+450+[[package]]451 name = "proc-macro2"403-version = "1.0.32"452+version = "1.0.36"453 source = "registry+https://github.com/rust-lang/crates.io-index"405-checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43"454+checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"455 dependencies = [456 "unicode-xid",457 ]458 459 [[package]]460 name = "quote"412-version = "1.0.10"461+version = "1.0.15"462 source = "registry+https://github.com/rust-lang/crates.io-index"414-checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"463+checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145"464 dependencies = [465 "proc-macro2",466 ]467 35 unmodified lines503 ]504 505 [[package]]506 name = "redox_syscall"458-version = "0.2.10"507+version = "0.2.11"508 source = "registry+https://github.com/rust-lang/crates.io-index"460-checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"509+checksum = "8380fe0152551244f0747b1bf41737e0f8a74f97a14ccefd1148187271634f3c"510 dependencies = [511 "bitflags",512 ]513 43 unmodified lines557 ]558 559 [[package]]560 name = "strsim"512-version = "0.8.0"561+version = "0.10.0"562 source = "registry+https://github.com/rust-lang/crates.io-index"514-checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"563+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"564 565 [[package]]566 name = "syn"518-version = "1.0.82"567+version = "1.0.86"568 source = "registry+https://github.com/rust-lang/crates.io-index"520-checksum = "8daf5dd0bb60cbd4137b1b587d2fc0ae729bc07cf01cd70b36a1ed5ade3b9d59"569+checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b"570 dependencies = [571 "proc-macro2",572 "quote",573 "unicode-xid",9 unmodified lines583 "remove_dir_all",584 ]585 586 [[package]]538-name = "term_size"539-version = "0.3.2"587+name = "termcolor"588+version = "1.1.3"589 source = "registry+https://github.com/rust-lang/crates.io-index"541-checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"590+checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"591 dependencies = [592+ "winapi-util",593+]594+595+[[package]]596+name = "terminal_size"597+version = "0.1.17"598+source = "registry+https://github.com/rust-lang/crates.io-index"599+checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df"600+dependencies = [601 "libc",602 "winapi",603 ]604 605 [[package]]606 name = "test-case"549-version = "1.2.1"607+version = "2.0.0"608 source = "registry+https://github.com/rust-lang/crates.io-index"551-checksum = "c7cad0a06f9a61e94355aa3b3dc92d85ab9c83406722b1ca5e918d4297c12c23"609+checksum = "4f7d58e237f65d5fe5eaf1105188c94c9a441e1fbc298ed5df45ec9c9af236d3"610 dependencies = [611 "cfg-if",612+ "proc-macro-error",613 "proc-macro2",614 "quote",615 "syn",557- "version_check",616 ]617 618 [[package]]619 name = "textwrap"562-version = "0.11.0"620+version = "0.15.0"621 source = "registry+https://github.com/rust-lang/crates.io-index"564-checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"622+checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"623 dependencies = [566- "term_size",567- "unicode-width",624+ "terminal_size",625 ]626 627 [[package]]628 name = "thread_local"572-version = "1.1.3"629+version = "1.1.4"630 source = "registry+https://github.com/rust-lang/crates.io-index"574-checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd"631+checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180"632 dependencies = [633 "once_cell",634 ]635 7 unmodified lines643 "winapi",644 ]645 646 [[package]]590-name = "unicode-width"591-version = "0.1.9"592-source = "registry+https://github.com/rust-lang/crates.io-index"593-checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"594-595-[[package]]647 name = "unicode-xid"648 version = "0.2.2"649 source = "registry+https://github.com/rust-lang/crates.io-index"650 checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"8 unmodified lines659 "log",660 ]661 662 [[package]]612-name = "vec_map"613-version = "0.8.2"614-source = "registry+https://github.com/rust-lang/crates.io-index"615-checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"616-617-[[package]]663 name = "version_check"619-version = "0.9.3"664+version = "0.9.4"665 source = "registry+https://github.com/rust-lang/crates.io-index"621-checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"666+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"667 668 [[package]]669 name = "walkdir"670 version = "2.3.2"44 unmodified linesmodified:Cargo.toml+18 added-14 removed
14 unmodified lines15 license = "MIT/Apache-2.0"16 name = "fd-find"17 readme = "README.md"18 repository = "https://github.com/sharkdp/fd"19-version = "8.3.0"20-edition= "2018"19+version = "8.3.2"20+edition= "2021"21 22 [badges.appveyor]23 repository = "sharkdp/fd"24 4 unmodified lines29 name = "fd"30 path = "src/main.rs"31 32 [build-dependencies]33-clap = "2.34.0"33+clap = { version = "3.1", features = ["cargo"] }34+clap_complete = "3.1"35 version_check = "0.9"36 37 [dependencies]38 ansi_term = "0.12"39 atty = "0.2"40 ignore = "0.4.3"40-num_cpus = "1.8"41+num_cpus = "1.13"42 regex = "1.5.4"43 regex-syntax = "0.6"44 ctrlc = "3.2"45 humantime = "2.1"45-lscolors = "0.8"46+lscolors = "0.9"47 globset = "0.4"48 anyhow = "1.0"49 dirs-next = "2.0"49-normpath = "0.3"50+normpath = "0.3.2"51 chrono = "0.4"51-once_cell = "1.8.0"52-crossbeam-channel = "0.5.1"52+once_cell = "1.9.0"53 54 [dependencies.clap]55-version = "2.34.0"56-features = ["suggestions", "color", "wrap_help"]55+version = "3.1"56+features = ["suggestions", "color", "wrap_help", "cargo", "unstable-grouped"]57 58 [target.'cfg(unix)'.dependencies]59 users = "0.11.0"60-nix = "0.23.0"60+nix = "0.23.1"61 62 [target.'cfg(all(unix, not(target_os = "redox")))'.dependencies]63 libc = "0.2"64 65 # FIXME: Re-enable jemalloc on macOS66 # jemalloc is currently disabled on macOS due to a bug in jemalloc in combination with macOS67 # Catalina. See https://github.com/sharkdp/fd/issues/498 for details.68-[target.'cfg(all(not(windows), not(target_os = "android"), not(target_os = "macos"), not(target_os = "freebsd"), not(target_env = "musl")))'.dependencies]69-jemallocator = "0.3.0"68+[target.'cfg(all(not(windows), not(target_os = "android"), not(target_os = "macos"), not(target_os = "freebsd"), not(target_env = "musl"), not(target_arch = "riscv64")))'.dependencies]69+jemallocator = {version = "0.3.0", optional = true}70 71 [dev-dependencies]72 diff = "0.1"73 tempdir = "0.3"74 filetime = "0.2"75-test-case = "1.2"75+test-case = "2.0"76 77 [profile.release]78 lto = true79 codegen-units = 180+81+[features]82+use-jemalloc = ["jemallocator"]83+default = ["use-jemalloc"]modified:CHANGELOG.md+26 added
1 # Upcoming release2 3 ## Performance improvements4 5+6 ## Features7 8+9 ## Bugfixes10 11+12 ## Changes13 14 - Directories are now printed with an additional path separator at the end: `foo/bar/`15+16 ## Other17 18 19+# v8.3.220 21+## Bugfixes22+23+- Invalid absolute path on windows when searching from the drive root, see #931 and #936 (@gbarta)24+25+26+# v8.3.127+28+## Bugfixes29+30+- Stop implying `--no-ignore-parent` when `--no-vcs-ignore` is supplied, see #907, #901, #908 (@tmccombs)31+- fd no longer waits for the whole traversal if the only matches arrive within max_buffer_time, see #868 and #895 (@tavianator)32+- `--max-results=1` now immediately quits after the first result, see #86733+- `fd -h` does not panic anymore when stdout is closed, see #89734+35+## Changes36+37+- Disable jemalloc on FreeBSD, see #896 (@xanderio)38+- Updated man page, see #912 (@rlue)39+- Updated zsh completions, see #932 (@tmccombs)40+41+42 # v8.3.043 44 ## Performance improvements45 544 unmodified linesmodified:clippy.toml+1 added-1 removed
1-msrv = "1.53.0"1+msrv = "1.56.0"modified:README.md+3 added-9 removed
18 unmodified lines19 20 * Intuitive syntax: `fd PATTERN` instead of `find -iname '*PATTERN*'`.21 * Regular expression (default) and glob-based patterns.22 * [Very fast](#benchmark) due to parallelized directory traversal.23-* Uses colors to highlight different file types (same as *ls*).23+* Uses colors to highlight different file types (same as `ls`).24 * Supports [parallel command execution](#command-execution)25 * Smart case: the search is case-insensitive by default. It switches to26 case-sensitive if the pattern contains an uppercase27 character[\*](http://vimdoc.sourceforge.net/htmldoc/options.html#'smartcase').506 unmodified lines534 535 If you use an older version of Ubuntu, you can download the latest `.deb` package from the536 [release page](https://github.com/sharkdp/fd/releases) and install it via:537 ``` bash538-sudo dpkg -i fd_8.3.0_amd64.deb # adapt version number and architecture538+sudo dpkg -i fd_8.3.2_amd64.deb # adapt version number and architecture539 ```540 541 ### On Debian542 13 unmodified lines556 ``` bash557 dnf install fd-find558 ```559 560-For older versions, you can use this [Fedora copr](https://copr.fedorainfracloud.org/coprs/keefle/fd/) to install `fd`:561-``` bash562-dnf copr enable keefle/fd563-dnf install fd564-```565-560 ### On Alpine Linux561 562 You can install [the fd package](https://pkgs.alpinelinux.org/packages?name=fd)563 from the official sources, provided you have the appropriate repository enabled:81 unmodified lines645 With Rust's package manager [cargo](https://github.com/rust-lang/cargo), you can install *fd* via:646 ```647 cargo install fd-find648 ```655-Note that rust version *1.53.0* or later is required.649+Note that rust version *1.56.0* or later is required.650 651 `make` is also needed for the build.652 653 ### From binaries31 unmodified lines