Merge branch 'master' into dir_alias
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Atomei Alexandru · committed by GitHub · parents 9f09673, f483726 · Browse files · 11 files·+260 added−159 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+260 added−159 removed
- other:+260 added−159 removed
Provenance
- Commit
c591106- Tree
eb6be83- Author
Atomei Alexandru <118962363+Ato2207@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
9f09673- Parent 2
f483726
11 files changed+260 added−159 removed
modified:.github/workflows/CICD.yml+1 added-1 removed
207 unmodified lines208 mkdir -p "${DPKG_DIR}"209 210 DPKG_BASENAME=${{ needs.crate_metadata.outputs.name }}211 DPKG_CONFLICTS=${{ needs.crate_metadata.outputs.name }}-musl212- case ${{ matrix.job.target }} in *-musl) DPKG_BASENAME=${{ needs.crate_metadata.outputs.name }}-musl ; DPKG_CONFLICTS=${{ needs.crate_metadata.outputs.name }} ;; esac;212+ case ${{ matrix.job.target }} in *-musl*) DPKG_BASENAME=${{ needs.crate_metadata.outputs.name }}-musl ; DPKG_CONFLICTS=${{ needs.crate_metadata.outputs.name }} ;; esac;213 DPKG_VERSION=${{ needs.crate_metadata.outputs.version }}214 215 unset DPKG_ARCH216 case ${{ matrix.job.target }} in136 unmodified linesmodified:doc/release-checklist.md+1 added-1 removed
7 unmodified lines89101112121314151650 unmodified lines7 unmodified lines- [ ] Create a new branch for the required changes for this release.- [ ] Update version in `Cargo.toml`. Run `cargo build` to update `Cargo.lock`. Make sure to `git add` the `Cargo.lock` changes as well.- [ ] Find the current min. supported Rust version by running `grep '^\s*MIN_SUPPORTED_RUST_VERSION' .github/workflows/CICD.yml`. `grep rust-version Cargo.toml`.- [ ] Update the `fd` version and the min. supported Rust version in `README.md`.- [ ] Update `CHANGELOG.md`. Change the heading of the *"Upcoming release"* section to the version of this release.
50 unmodified linesmodified:src/exec/job.rs+16 added-15 removed
1 use std::sync::Mutex;2 3-use crossbeam_channel::Receiver;4-3 use crate::config::Config;6-use crate::dir_entry::DirEntry;4 use crate::error::print_error;5 use crate::exit_codes::{merge_exitcodes, ExitCode};6 use crate::walk::WorkerResult;7 2 unmodified lines10 /// An event loop that listens for inputs from the `rx` receiver. Each received input will11 /// generate a command with the supplied command template. The generated command will then12 /// be executed, and this process will continue until the receiver's sender has closed.13 pub fn job(17- rx: Receiver<WorkerResult>,14+ results: impl IntoIterator<Item = WorkerResult>,15 cmd: &CommandSet,16 out_perm: &Mutex<()>,17 config: &Config,18 ) -> ExitCode {19 // Output should be buffered when only running a single thread20 let buffer_output: bool = config.threads > 1;21 25- let mut results: Vec<ExitCode> = Vec::new();26- loop {22+ let mut ret = ExitCode::Success;23+ for result in results {24 // Obtain the next result from the receiver, else if the channel25 // has closed, exit from the loop29- let dir_entry: DirEntry = match rx.recv() {30- Ok(WorkerResult::Entry(dir_entry)) => dir_entry,31- Ok(WorkerResult::Error(err)) => {26+ let dir_entry = match result {27+ WorkerResult::Entry(dir_entry) => dir_entry,28+ WorkerResult::Error(err) => {29 if config.show_filesystem_errors {30 print_error(err.to_string());31 }32 continue;33 }37- Err(_) => break,34 };35 36 // Generate a command, execute it and store its exit code.41- results.push(cmd.execute(37+ let code = cmd.execute(38 dir_entry.stripped_path(config),39 config.path_separator.as_deref(),40 out_perm,41 buffer_output,46- ))42+ );43+ ret = merge_exitcodes([ret, code]);44 }45 // Returns error in case of any error.49- merge_exitcodes(results)46+ ret47 }48 52-pub fn batch(rx: Receiver<WorkerResult>, cmd: &CommandSet, config: &Config) -> ExitCode {53- let paths = rx49+pub fn batch(50+ results: impl IntoIterator<Item = WorkerResult>,51+ cmd: &CommandSet,52+ config: &Config,53+) -> ExitCode {54+ let paths = results55 .into_iter()56 .filter_map(|worker_result| match worker_result {57 WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),58 WorkerResult::Error(err) => {9 unmodified linesmodified:src/cli.rs+7 added-28 removed
713 unmodified lines714 /// Get the default number of threads to use, if not explicitly specified.715 fn default_num_threads() -> NonZeroUsize {716 // If we can't get the amount of parallelism for some reason, then717 // default to a single thread, because that is safe.718- // Note that the minimum value for a NonZeroUsize is 1.719- // Unfortunately, we can't do `NonZeroUsize::new(1).unwrap()`720- // in a const context.721- const FALLBACK_PARALLELISM: NonZeroUsize = NonZeroUsize::MIN;722- // As the number of threads increases, the startup time suffers from723- // initializing the threads, and we get diminishing returns from additional724- // parallelism. So set a maximum number of threads to use by default.725- //726- // This value is based on some empirical observations, but the ideal value727- // probably depends on the exact hardware in use.728- //729- // Safety: The literal "20" is known not to be zero.730- const MAX_DEFAULT_THREADS: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(20) };718+ let fallback = NonZeroUsize::MIN;719+ // To limit startup overhead on massively parallel machines, don't use more720+ // than 64 threads.721+ let limit = NonZeroUsize::new(64).unwrap();722 732- std::cmp::min(733- std::thread::available_parallelism().unwrap_or(FALLBACK_PARALLELISM),734- MAX_DEFAULT_THREADS,735- )723+ std::thread::available_parallelism()724+ .unwrap_or(fallback)725+ .min(limit)726 }727 728 #[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]729 pub enum FileType {27 unmodified lines757 /// do not use colorized output758 Never,759 }760 771-impl ColorWhen {772- pub fn as_str(&self) -> &'static str {773- use ColorWhen::*;774- match *self {775- Auto => "auto",776- Never => "never",777- Always => "always",778- }779- }780-}781-761 // there isn't a derive api for getting grouped values yet,762 // so we have to use hand-rolled parsing for exec and exec-batch763 pub struct Exec {764 pub command: Option<CommandSet>,110 unmodified linesmodified:src/dir_entry.rs+2 added
6 unmodified lines7 8 use crate::config::Config;9 use crate::filesystem::strip_current_dir;10 11+#[derive(Debug)]12 enum DirEntryInner {13 Normal(ignore::DirEntry),14 BrokenSymlink(PathBuf),15 }16 17+#[derive(Debug)]18 pub struct DirEntry {19 inner: DirEntryInner,20 metadata: OnceCell<Option<Metadata>>,21 style: OnceCell<Option<Style>>,134 unmodified linesmodified:src/main.rs+7 added-3 removed
323 unmodified lines324 .or_else(|| {325 if !opts.list_details {326 return None;327 }328- let color_arg = format!("--color={}", opts.color.as_str());328 330- let res = determine_ls_command(&color_arg, colored_output)329+ let res = determine_ls_command(colored_output)330 .map(|cmd| CommandSet::new_batch([cmd]).unwrap());331 Some(res)332 })333 .transpose()334 }335 337-fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {336+fn determine_ls_command(colored_output: bool) -> Result<Vec<&'static str>> {337 #[allow(unused)]338 let gnu_ls = |command_name| {339+ let color_arg = if colored_output {340+ "--color=always"341+ } else {342+ "--color=never"343+ };344 // Note: we use short options here (instead of --long-options) to support more345 // platforms (like BusyBox).346 vec![347 command_name,132 unmodified linesmodified:src/walk.rs+132 added-36 removed
2 unmodified lines3 use std::io::{self, Write};4 use std::mem;5 use std::path::PathBuf;6 use std::sync::atomic::{AtomicBool, Ordering};7-use std::sync::{Arc, Mutex};7+use std::sync::{Arc, Mutex, MutexGuard};8 use std::thread;9 use std::time::{Duration, Instant};10 11 use anyhow::{anyhow, Result};12-use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};12+use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, SendError, Sender};13 use etcetera::BaseStrategy;14 use ignore::overrides::{Override, OverrideBuilder};15 use ignore::{self, WalkBuilder, WalkParallel, WalkState};16 use regex::bytes::Regex;18 unmodified lines35 }36 37 /// The Worker threads can result in a valid entry having PathBuf or an error.38 #[allow(clippy::large_enum_variant)]39+#[derive(Debug)]40 pub enum WorkerResult {41 // Errors should be rare, so it's probably better to allow large_enum_variant than42 // to box the Entry variant43 Entry(DirEntry),44 Error(ignore::Error),45 }46 47+/// A batch of WorkerResults to send over a channel.48+#[derive(Clone)]49+struct Batch {50+ items: Arc<Mutex<Option<Vec<WorkerResult>>>>,51+}52+53+impl Batch {54+ fn new() -> Self {55+ Self {56+ items: Arc::new(Mutex::new(Some(vec![]))),57+ }58+ }59+60+ fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {61+ self.items.lock().unwrap()62+ }63+}64+65+impl IntoIterator for Batch {66+ type Item = WorkerResult;67+ type IntoIter = std::vec::IntoIter<WorkerResult>;68+69+ fn into_iter(self) -> Self::IntoIter {70+ self.lock().take().unwrap().into_iter()71+ }72+}73+74+/// Wrapper that sends batches of items at once over a channel.75+struct BatchSender {76+ batch: Batch,77+ tx: Sender<Batch>,78+ limit: usize,79+}80+81+impl BatchSender {82+ fn new(tx: Sender<Batch>, limit: usize) -> Self {83+ Self {84+ batch: Batch::new(),85+ tx,86+ limit,87+ }88+ }89+90+ /// Check if we need to flush a batch.91+ fn needs_flush(&self, batch: Option<&Vec<WorkerResult>>) -> bool {92+ match batch {93+ // Limit the batch size to provide some backpressure94+ Some(vec) => vec.len() >= self.limit,95+ // Batch was already taken by the receiver, so make a new one96+ None => true,97+ }98+ }99+100+ /// Add an item to a batch.101+ fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {102+ let mut batch = self.batch.lock();103+104+ if self.needs_flush(batch.as_ref()) {105+ drop(batch);106+ self.batch = Batch::new();107+ batch = self.batch.lock();108+ }109+110+ let items = batch.as_mut().unwrap();111+ items.push(item);112+113+ if items.len() == 1 {114+ // New batch, send it over the channel115+ self.tx116+ .send(self.batch.clone())117+ .map_err(|_| SendError(()))?;118+ }119+120+ Ok(())121+ }122+}123+124 /// Maximum size of the output buffer before flushing results to the console125 const MAX_BUFFER_LENGTH: usize = 1000;126 /// Default duration until output buffering switches to streaming.127 const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);6 unmodified lines134 quit_flag: &'a AtomicBool,135 /// The ^C notifier.136 interrupt_flag: &'a AtomicBool,137 /// Receiver for worker results.60- rx: Receiver<WorkerResult>,138+ rx: Receiver<Batch>,139 /// Standard output.140 stdout: W,141 /// The current buffer mode.142 mode: ReceiverMode,6 unmodified lines149 }150 151 impl<'a, W: Write> ReceiverBuffer<'a, W> {152 /// Create a new receiver buffer.75- fn new(state: &'a WorkerState, rx: Receiver<WorkerResult>, stdout: W) -> Self {153+ fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {154 let config = &state.config;155 let quit_flag = state.quit_flag.as_ref();156 let interrupt_flag = state.interrupt_flag.as_ref();157 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);22 unmodified lines180 }181 }182 183 /// Receive the next worker result.106- fn recv(&self) -> Result<WorkerResult, RecvTimeoutError> {184+ fn recv(&self) -> Result<Batch, RecvTimeoutError> {185 match self.mode {186 ReceiverMode::Buffering => {187 // Wait at most until we should switch to streaming188 self.rx.recv_deadline(self.deadline)7 unmodified lines196 197 /// Wait for a result or state change.198 fn poll(&mut self) -> Result<(), ExitCode> {199 match self.recv() {200+ Ok(batch) => {201+ for result in batch {202+ match result {122- Ok(WorkerResult::Entry(dir_entry)) => {123- if self.config.quiet {124- return Err(ExitCode::HasResults(true));125- }203+ WorkerResult::Entry(dir_entry) => {204+ if self.config.quiet {205+ return Err(ExitCode::HasResults(true));206+ }207 127- match self.mode {128- ReceiverMode::Buffering => {129- self.buffer.push(dir_entry);130- if self.buffer.len() > MAX_BUFFER_LENGTH {131- self.stream()?;208+ match self.mode {209+ ReceiverMode::Buffering => {210+ self.buffer.push(dir_entry);211+ if self.buffer.len() > MAX_BUFFER_LENGTH {212+ self.stream()?;213+ }214+ }215+ ReceiverMode::Streaming => {216+ self.print(&dir_entry)?;217+ }218+ }219+220+ self.num_results += 1;221+ if let Some(max_results) = self.config.max_results {222+ if self.num_results >= max_results {223+ return self.stop();224+ }225+ }226 }227+ WorkerResult::Error(err) => {228+ if self.config.show_filesystem_errors {229+ print_error(err.to_string());230+ }231+ }232 }134- ReceiverMode::Streaming => {135- self.print(&dir_entry)?;136- self.flush()?;137- }233 }234 140- self.num_results += 1;141- if let Some(max_results) = self.config.max_results {142- if self.num_results >= max_results {143- return self.stop();144- }235+ // If we don't have another batch ready, flush before waiting236+ if self.mode == ReceiverMode::Streaming && self.rx.is_empty() {237+ self.flush()?;238 }239 }147- Ok(WorkerResult::Error(err)) => {148- if self.config.show_filesystem_errors {149- print_error(err.to_string());150- }151- }240 Err(RecvTimeoutError::Timeout) => {241 self.stream()?;242 }243 Err(RecvTimeoutError::Disconnected) => {44 unmodified lines288 }289 290 /// Flush stdout if necessary.291 fn flush(&mut self) -> Result<(), ExitCode> {204- if self.config.interactive_terminal && self.stdout.flush().is_err() {292+ if self.stdout.flush().is_err() {293 // Probably a broken pipe. Exit gracefully.294 return Err(ExitCode::GeneralError);295 }296 Ok(())109 unmodified lines406 }407 408 /// Run the receiver work, either on this thread or a pool of background409 /// threads (for --exec).322- fn receive(&self, rx: Receiver<WorkerResult>) -> ExitCode {410+ fn receive(&self, rx: Receiver<Batch>) -> ExitCode {411 let config = &self.config;412 413 // This will be set to `Some` if the `--exec` argument was supplied.414 if let Some(ref cmd) = config.command {415 if cmd.in_batch_mode() {328- exec::batch(rx, cmd, &config)416+ exec::batch(rx.into_iter().flatten(), cmd, &config)417 } else {418 let out_perm = Mutex::new(());419 420 thread::scope(|scope| {3 unmodified lines424 for _ in 0..threads {425 let rx = rx.clone();426 427 // Spawn a job thread that will listen for and execute inputs.340- let handle = scope.spawn(|| exec::job(rx, cmd, &out_perm, &config));428+ let handle = scope429+ .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, &config));430 431 // Push the handle of the spawned thread into the vector for later joining.432 handles.push(handle);433 }9 unmodified lines443 }444 }445 446 /// Spawn the sender threads.358- fn spawn_senders(&self, walker: WalkParallel, tx: Sender<WorkerResult>) {447+ fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {448 walker.run(|| {449 let patterns = &self.patterns;450 let config = &self.config;451 let quit_flag = self.quit_flag.as_ref();363- let tx = tx.clone();452 453+ let mut limit = 0x100;454+ if let Some(cmd) = &config.command {455+ if !cmd.in_batch_mode() && config.threads > 1 {456+ // Evenly distribute work between multiple receivers457+ limit = 1;458+ }459+ }460+ let mut tx = BatchSender::new(tx.clone(), limit);461+462 Box::new(move |entry| {463 if quit_flag.load(Ordering::Relaxed) {464 return WalkState::Quit;465 }175 unmodified lines641 })642 .unwrap();643 }644 548- // Channel capacity was chosen empircally to perform similarly to an unbounded channel549- let (tx, rx) = bounded(0x4000 * config.threads);645+ let (tx, rx) = bounded(2 * config.threads);646 647 let exit_code = thread::scope(|scope| {648 // Spawn the receiver thread(s)649 let receiver = scope.spawn(|| self.receive(rx));23 unmodified linesmodified:Cargo.lock+11 added-11 removed
152 unmodified lines153 ]154 155 [[package]]156 name = "clap"157-version = "4.4.7"157+version = "4.4.10"158 source = "registry+https://github.com/rust-lang/crates.io-index"159-checksum = "ac495e00dcec98c83465d5ad66c5c4fabd652fd6686e7c6269b117e729a6f17b"159+checksum = "41fffed7514f420abec6d183b1d3acfd9099c79c3a10a06ade4f8203f1411272"160 dependencies = [161 "clap_builder",162 "clap_derive",163 ]164 165 [[package]]166 name = "clap_builder"167-version = "4.4.7"167+version = "4.4.9"168 source = "registry+https://github.com/rust-lang/crates.io-index"169-checksum = "c77ed9a32a62e6ca27175d00d29d05ca32e396ea1eb5fb01d8256b669cec7663"169+checksum = "63361bae7eef3771745f02d8d892bec2fee5f6e34af316ba556e7f97a7069ff1"170 dependencies = [171 "anstream",172 "anstyle",173 "clap_lex",138 unmodified lines312 checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"313 314 [[package]]315 name = "fd-find"316-version = "8.7.1"316+version = "9.0.0"317 dependencies = [318 "aho-corasick",319 "anyhow",320 "argmax",143 unmodified lines464 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"465 466 [[package]]467 name = "libc"468-version = "0.2.149"468+version = "0.2.150"469 source = "registry+https://github.com/rust-lang/crates.io-index"470-checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b"470+checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"471 472 [[package]]473 name = "linux-raw-sys"474 version = "0.4.10"7 unmodified lines482 checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"483 484 [[package]]485 name = "lscolors"486-version = "0.15.0"486+version = "0.16.0"487 source = "registry+https://github.com/rust-lang/crates.io-index"488-checksum = "bf7015a04103ad78abb77e4b79ed151e767922d1cfde5f62640471c629a2320d"488+checksum = "ab0b209ec3976527806024406fe765474b9a1750a0ed4b8f0372364741f50e7b"489 dependencies = [490 "nu-ansi-term",491 ]492 255 unmodified lines748 ]749 750 [[package]]751 name = "test-case"752-version = "3.2.1"752+version = "3.3.1"753 source = "registry+https://github.com/rust-lang/crates.io-index"754-checksum = "c8f1e820b7f1d95a0cdbf97a5df9de10e1be731983ab943e56703ac1b8e9d425"754+checksum = "eb2550dd13afcd286853192af8601920d959b14c401fcece38071d53bf0768a8"755 dependencies = [756 "test-case-macros",757 ]758 213 unmodified linesmodified:Cargo.toml+4 added-4 removed
14 unmodified lines15 license = "MIT OR Apache-2.0"16 name = "fd-find"17 readme = "README.md"18 repository = "https://github.com/sharkdp/fd"19-version = "8.7.1"19+version = "9.0.0"20 edition= "2021"21 rust-version = "1.70.0"22 23 [badges.appveyor]26 unmodified lines50 clap_complete = {version = "4.4.4", optional = true}51 faccess = "0.2.4"52 53 [dependencies.clap]54-version = "4.4.7"54+version = "4.4.10"55 features = ["suggestions", "color", "wrap_help", "cargo", "derive"]56 57 [dependencies.chrono]58 version = "0.4.31"59 default-features = false60 features = ["std", "clock"]61 62 [dependencies.lscolors]63-version = "0.15"63+version = "0.16"64 default-features = false65 features = ["nu-ansi-term"]66 67 [target.'cfg(unix)'.dependencies]11 unmodified lines79 [dev-dependencies]80 diff = "0.1"81 tempfile = "3.8"82 filetime = "0.2"83-test-case = "3.1"83+test-case = "3.3"84 85 [profile.release]86 lto = true87 strip = true7 unmodified linesmodified:CHANGELOG.md+39 added-5 removed
1 # Upcoming release2 3 ## Features4 5+6+## Bugfixes7+8+- Respect NO_COLOR environment variable with `--list-details` option. (#1455)9+10+11+## Changes12+13+14+## Other15+16+17+18+19+# v9.0.020+21+## Performance22+23+- Performance has been *significantly improved*, both due to optimizations in the underlying `ignore`24+ crate (#1429), and in `fd` itself (#1422, #1408, #1362) - @tavianator.25+ [Benchmarks results](https://gist.github.com/tavianator/32edbe052f33ef60570cf5456b59de81) show gains26+ of 6-8x for full traversals of smaller directories (100k files) and up to 13x for larger directories (1M files).27+28+- The default number of threads is now constrained to be at most 64. This should improve startup time on29+ systems with many CPU cores. (#1203, #1410, #1412, #1431) - @tmccombs and @tavianator30+31+- New flushing behavior when writing output to stdout, providing better performance for TTY and non-TTY32+ use cases, see #1452 and #1313 (@tavianator).33+34+## Features35+36+- Support character and block device file types, see #1213 and #1336 (@cgzones)37 - Breaking: `.git/` is now ignored by default when using `--hidden` / `-H`, use `--no-ignore` / `-I` or38 `--no-ignore-vcs` to override, see #1387 and #1396 (@skoriop)39 8-40 ## Bugfixes41 42 - Fix `NO_COLOR` support, see #1421 (@acuteenvy)43 13-## Changes44+## Other45 15-- The default number of threads is now constrained to be at most 16. This should improve startup time on16- systems with many CPU cores. (#1203)46+- Fixed documentation typos, see #1409 (@marcospb19)47 18-## Other48+## Thanks49 50+Special thanks to @tavianator for his incredible work on performance in the `ignore` crate and `fd` itself.51+52+53+54 # v8.7.155 56 ## Bugfixes57 691 unmodified linesmodified:README.md+40 added-55 removed
141 unmodified lines142 target/debug/deps/libnum_cpus-f5ce7ef99006aa05.rlib143 ```144 145 To really search *all* files and directories, simply combine the hidden and ignore features to show146-everything (`-HI`).146+everything (`-HI`) or use `-u`/`--unrestricted`.147 148 ### Matching the full path149 By default, *fd* only matches the filename of each file. However, using the `--full-path` or `-p` option,150 you can match against the full path.109 unmodified lines260 > cat ~/.fdignore261 /mnt/external-drive262 *.bak263 ```264-Note: `fd` also supports `.ignore` files that are used by other programs such as `rg` or `ag`.264 265+> [!NOTE]266+> `fd` also supports `.ignore` files that are used by other programs such as `rg` or `ag`.267+268 If you want `fd` to ignore these patterns globally, you can put them in `fd`'s global ignore file.269 This is usually located in `~/.config/fd/ignore` in macOS or Linux, and `%APPDATA%\fd\ignore` in270 Windows.271 13 unmodified lines285 286 If you also want to remove a certain class of directories, you can use the same technique. You will287 have to use `rm`s `--recursive`/`-r` flag to remove directories.288 289+> [!NOTE]287-Note: there are scenarios where using `fd … -X rm -r` can cause race conditions: if you have a290+> There are scenarios where using `fd … -X rm -r` can cause race conditions: if you have a291 path like `…/foo/bar/foo/…` and want to remove all directories named `foo`, you can end up in a292 situation where the outer `foo` directory is removed first, leading to (harmless) *"'foo/bar/foo':293 No such file or directory"* errors in the `rm` call.294 38 unmodified lines333 ```334 335 ## Benchmark336 334-Let's search my home folder for files that end in `[0-9].jpg`. It contains ~190.000335-subdirectories and about a million files. For averaging and statistical analysis, I'm using337+Let's search my home folder for files that end in `[0-9].jpg`. It contains ~750.000338+subdirectories and about a 4 million files. For averaging and statistical analysis, I'm using339 [hyperfine](https://github.com/sharkdp/hyperfine). The following benchmarks are performed340 with a "warm"/pre-filled disk-cache (results for a "cold" disk-cache show the same trends).341 342 Let's start with `find`:343 ```341-Benchmark #1: find ~ -iregex '.*[0-9]\.jpg$'342-343- Time (mean ± σ): 7.236 s ± 0.090 s344-345- Range (min … max): 7.133 s … 7.385 s344+Benchmark 1: find ~ -iregex '.*[0-9]\.jpg$'345+ Time (mean ± σ): 19.922 s ± 0.109 s346+ Range (min … max): 19.765 s … 20.065 s347 ```348 349 `find` is much faster if it does not need to perform a regular-expression search:350 ```350-Benchmark #2: find ~ -iname '*[0-9].jpg'351-352- Time (mean ± σ): 3.914 s ± 0.027 s353-354- Range (min … max): 3.876 s … 3.964 s351+Benchmark 2: find ~ -iname '*[0-9].jpg'352+ Time (mean ± σ): 11.226 s ± 0.104 s353+ Range (min … max): 11.119 s … 11.466 s354 ```355 357-Now let's try the same for `fd`. Note that `fd` *always* performs a regular expression358-search. The options `--hidden` and `--no-ignore` are needed for a fair comparison,359-otherwise `fd` does not have to traverse hidden folders and ignored paths (see below):356+Now let's try the same for `fd`. Note that `fd` performs a regular expression357+search by default. The options `-u`/`--unrestricted` option is needed here for358+a fair comparison. Otherwise `fd` does not have to traverse hidden folders and359+ignored paths (see below):360 ```361-Benchmark #3: fd -HI '.*[0-9]\.jpg$' ~362-363- Time (mean ± σ): 811.6 ms ± 26.9 ms364-365- Range (min … max): 786.0 ms … 870.7 ms361+Benchmark 3: fd -u '[0-9]\.jpg$' ~362+ Time (mean ± σ): 854.8 ms ± 10.0 ms363+ Range (min … max): 839.2 ms … 868.9 ms364 ```367-For this particular example, `fd` is approximately nine times faster than `find -iregex`368-and about five times faster than `find -iname`. By the way, both tools found the exact369-same 20880 files :smile:.365+For this particular example, `fd` is approximately **23 times faster** than `find -iregex`366+and about **13 times faster** than `find -iname`. By the way, both tools found the exact367+same 546 files :smile:.368 371-Finally, let's run `fd` without `--hidden` and `--no-ignore` (this can lead to different372-search results, of course). If *fd* does not have to traverse the hidden and git-ignored373-folders, it is almost an order of magnitude faster:374-```375-Benchmark #4: fd '[0-9]\.jpg$' ~376-377- Time (mean ± σ): 123.7 ms ± 6.0 ms378-379- Range (min … max): 118.8 ms … 140.0 ms380-```381-382-**Note**: This is *one particular* benchmark on *one particular* machine. While I have383-performed quite a lot of different tests (and found consistent results), things might384-be different for you! I encourage everyone to try it out on their own. See369+**Note**: This is *one particular* benchmark on *one particular* machine. While we have370+performed a lot of different tests (and found consistent results), things might371+be different for you! We encourage everyone to try it out on their own. See372 [this repository](https://github.com/sharkdp/fd-benchmarks) for all necessary scripts.373 387-Concerning *fd*'s speed, the main credit goes to the `regex` and `ignore` crates that are also used388-in [ripgrep](https://github.com/BurntSushi/ripgrep) (check it out!).374+Concerning *fd*'s speed, a lot of credit goes to the `regex` and `ignore` crates that are375+also used in [ripgrep](https://github.com/BurntSushi/ripgrep) (check it out!).376 377 ## Troubleshooting378 379+### `fd` does not find my file!380+381+Remember that `fd` ignores hidden directories and files by default. It also ignores patterns382+from `.gitignore` files. If you want to make sure to find absolutely every possible file, always383+use the options `-u`/`--unrestricted` option (or `-HI` to enable hidden and ignored files):384+``` bash385+> fd -u …386+```387+388 ### Colorized output389 390 `fd` can colorize files by extension, just like `ls`. In order for this to work, the environment391 variable [`LS_COLORS`](https://linux.die.net/man/5/dir_colors) has to be set. Typically, the value5 unmodified lines397 [here](https://github.com/trapd00r/LS_COLORS).398 399 `fd` also honors the [`NO_COLOR`](https://no-color.org/) environment variable.400 405-### `fd` does not find my file!406-407-Remember that `fd` ignores hidden directories and files by default. It also ignores patterns408-from `.gitignore` files. If you want to make sure to find absolutely every possible file, always409-use the options `-H` and `-I` to disable these two features:410-``` bash411-> fd -HI …412-```413-401 ### `fd` doesn't seem to interpret my regex pattern correctly402 403 A lot of special regex characters (like `[]`, `^`, `$`, ..) are also special characters in your404 shell. If in doubt, always make sure to put single quotes around the regex pattern:124 unmodified lines529 530 If you use an older version of Ubuntu, you can download the latest `.deb` package from the531 [release page](https://github.com/sharkdp/fd/releases) and install it via:532 ``` bash546-sudo dpkg -i fd_8.7.1_amd64.deb # adapt version number and architecture533+sudo dpkg -i fd_9.0.0_amd64.deb # adapt version number and architecture534 ```535 536 ### On Debian537 125 unmodified lines663 With Rust's package manager [cargo](https://github.com/rust-lang/cargo), you can install *fd* via:664 ```665 cargo install fd-find666 ```680-Note that rust version *1.64.0* or later is required.667+Note that rust version *1.70.0* or later is required.668 669 `make` is also needed for the build.670 671 ### From binaries22 unmodified lines694 - [tavianator](https://github.com/tavianator)695 696 ## License697 711-Copyright (c) 2017-2021 The fd developers712-698 `fd` is distributed under the terms of both the MIT License and the Apache License 2.0.699 700 See the [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) files for license details.