Skip to content
Myr

walk.rs

This file

Path

src/walk.rs

776 lines · 25.7 KiB · Rust

Last changed by

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

History of this file

Take it

The walk stopped after 200 commits: lines older than 86d6e2d point at it.

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 1–4why, one step back
1use std::borrow::Cow;
2use std::ffi::OsStr;3use std::io::{self, Write};4use std::mem;

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

line 5why, one step back
5use std::path::PathBuf;

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 6–10why, one step back
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex, MutexGuard};8use std::thread;9use std::time::{Duration, Instant};10

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 11–12why, one step back
11use anyhow::{Result, anyhow};
12use crossbeam_channel::{Receiver, RecvTimeoutError, SendError, Sender, bounded};

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 13–20why, one step back
13use etcetera::BaseStrategy;
14use ignore::overrides::{Override, OverrideBuilder};15use ignore::{WalkBuilder, WalkParallel, WalkState};16use regex::bytes::Regex;1718use crate::config::Config;19use crate::dir_entry::DirEntry;20use crate::exec;

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

line 21why, one step back
21use crate::exit_codes::{ExitCode, merge_exitcodes};

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 22–219why, one step back
22use crate::filesystem;
23use crate::output;2425/// The receiver thread can either be buffering results or directly streaming to the console.26#[derive(PartialEq)]27enum ReceiverMode {28 /// Receiver is still buffering in order to sort the results, if the search finishes fast29 /// enough.30 Buffering,3132 /// Receiver is directly printing results to the output.33 Streaming,34}3536/// The Worker threads can result in a valid entry having PathBuf or an error.37#[allow(clippy::large_enum_variant)]38#[derive(Debug)]39pub enum WorkerResult {40 // Errors should be rare, so it's probably better to allow large_enum_variant than41 // to box the Entry variant42 Entry(DirEntry),43 Error(ignore::Error),44}4546/// A batch of WorkerResults to send over a channel.47#[derive(Clone)]48struct Batch {49 items: Arc<Mutex<Option<Vec<WorkerResult>>>>,50}5152impl Batch {53 fn new() -> Self {54 Self {55 items: Arc::new(Mutex::new(Some(vec![]))),56 }57 }5859 fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {60 self.items.lock().unwrap()61 }62}6364impl IntoIterator for Batch {65 type Item = WorkerResult;66 type IntoIter = std::vec::IntoIter<WorkerResult>;6768 fn into_iter(self) -> Self::IntoIter {69 self.lock().take().unwrap().into_iter()70 }71}7273/// Wrapper that sends batches of items at once over a channel.74struct BatchSender {75 batch: Batch,76 tx: Sender<Batch>,77 limit: usize,78}7980impl BatchSender {81 fn new(tx: Sender<Batch>, limit: usize) -> Self {82 Self {83 batch: Batch::new(),84 tx,85 limit,86 }87 }8889 /// Check if we need to flush a batch.90 fn needs_flush(&self, batch: Option<&Vec<WorkerResult>>) -> bool {91 match batch {92 // Limit the batch size to provide some backpressure93 Some(vec) => vec.len() >= self.limit,94 // Batch was already taken by the receiver, so make a new one95 None => true,96 }97 }9899 /// Add an item to a batch.100 fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {101 let mut batch = self.batch.lock();102103 if self.needs_flush(batch.as_ref()) {104 drop(batch);105 self.batch = Batch::new();106 batch = self.batch.lock();107 }108109 let items = batch.as_mut().unwrap();110 items.push(item);111112 if items.len() == 1 {113 // New batch, send it over the channel114 self.tx115 .send(self.batch.clone())116 .map_err(|_| SendError(()))?;117 }118119 Ok(())120 }121}122123/// Maximum size of the output buffer before flushing results to the console124const MAX_BUFFER_LENGTH: usize = 1000;125/// Default duration until output buffering switches to streaming.126const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);127128/// Wrapper for the receiver thread's buffering behavior.129struct ReceiverBuffer<'a, W> {130 /// The configuration.131 config: &'a Config,132 /// For shutting down the senders.133 quit_flag: &'a AtomicBool,134 /// The ^C notifier.135 interrupt_flag: &'a AtomicBool,136 /// Receiver for worker results.137 rx: Receiver<Batch>,138 /// Standard output.139 stdout: W,140 /// The current buffer mode.141 mode: ReceiverMode,142 /// The deadline to switch to streaming mode.143 deadline: Instant,144 /// The buffer of quickly received paths.145 buffer: Vec<DirEntry>,146 /// Result count.147 num_results: usize,148}149150impl<'a, W: Write> ReceiverBuffer<'a, W> {151 /// Create a new receiver buffer.152 fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {153 let config = &state.config;154 let quit_flag = state.quit_flag.as_ref();155 let interrupt_flag = state.interrupt_flag.as_ref();156 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);157 let deadline = Instant::now() + max_buffer_time;158159 Self {160 config,161 quit_flag,162 interrupt_flag,163 rx,164 stdout,165 mode: ReceiverMode::Buffering,166 deadline,167 buffer: Vec::with_capacity(MAX_BUFFER_LENGTH),168 num_results: 0,169 }170 }171172 /// Process results until finished.173 fn process(&mut self) -> ExitCode {174 loop {175 if let Err(ec) = self.poll() {176 self.quit_flag.store(true, Ordering::Relaxed);177 return ec;178 }179 }180 }181182 /// Receive the next worker result.183 fn recv(&self) -> Result<Batch, RecvTimeoutError> {184 match self.mode {185 ReceiverMode::Buffering => {186 // Wait at most until we should switch to streaming187 self.rx.recv_deadline(self.deadline)188 }189 ReceiverMode::Streaming => {190 // Wait however long it takes for a result191 Ok(self.rx.recv()?)192 }193 }194 }195196 /// Wait for a result or state change.197 fn poll(&mut self) -> Result<(), ExitCode> {198 match self.recv() {199 Ok(batch) => {200 for result in batch {201 match result {202 WorkerResult::Entry(dir_entry) => {203 if self.config.quiet {204 return Err(ExitCode::HasResults(true));205 }206207 match self.mode {208 ReceiverMode::Buffering => {209 self.buffer.push(dir_entry);210 if self.buffer.len() > MAX_BUFFER_LENGTH {211 self.stream()?;212 }213 }214 ReceiverMode::Streaming => {215 self.print(&dir_entry)?;216 }217 }218219 self.num_results += 1;

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 220–223why, one step back
220 if let Some(max_results) = self.config.max_results
221 && self.num_results >= max_results222 {223 return self.stop();

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 224–227why, one step back
224 }
225 }226 WorkerResult::Error(err) => {227 if self.config.show_filesystem_errors {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 228why, one step back
228 print_error!("{}", err);

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 229–251why, one step back
229 }
230 }231 }232 }233234 // If we don't have another batch ready, flush before waiting235 if self.mode == ReceiverMode::Streaming && self.rx.is_empty() {236 self.flush()?;237 }238 }239 Err(RecvTimeoutError::Timeout) => {240 self.stream()?;241 }242 Err(RecvTimeoutError::Disconnected) => {243 return self.stop();244 }245 }246247 Ok(())248 }249250 /// Output a path.251 fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 252–254why, one step back
252 if let Err(e) = output::print_entry(&mut self.stdout, entry, self.config)
253 && e.kind() != ::std::io::ErrorKind::BrokenPipe254 {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 255why, one step back
255 print_error!("Could not write to output: {}", e);

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

line 256why, one step back
256 return Err(ExitCode::GeneralError);

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 257–369why, one step back
257 }
258259 if self.interrupt_flag.load(Ordering::Relaxed) {260 // Ignore any errors on flush, because we're about to exit anyway261 let _ = self.flush();262 return Err(ExitCode::KilledBySigint);263 }264265 Ok(())266 }267268 /// Switch ourselves into streaming mode.269 fn stream(&mut self) -> Result<(), ExitCode> {270 self.mode = ReceiverMode::Streaming;271272 let buffer = mem::take(&mut self.buffer);273 for path in buffer {274 self.print(&path)?;275 }276277 self.flush()278 }279280 /// Stop looping.281 fn stop(&mut self) -> Result<(), ExitCode> {282 if self.mode == ReceiverMode::Buffering {283 self.buffer.sort();284 self.stream()?;285 }286287 if self.config.quiet {288 Err(ExitCode::HasResults(self.num_results > 0))289 } else {290 Err(ExitCode::Success)291 }292 }293294 /// Flush stdout if necessary.295 fn flush(&mut self) -> Result<(), ExitCode> {296 if self.stdout.flush().is_err() {297 // Probably a broken pipe. Exit gracefully.298 return Err(ExitCode::GeneralError);299 }300 Ok(())301 }302}303304/// State shared by the sender and receiver threads.305struct WorkerState {306 /// The search patterns.307 patterns: Vec<Regex>,308 /// The command line configuration.309 config: Config,310 /// Flag for cleanly shutting down the parallel walk311 quit_flag: Arc<AtomicBool>,312 /// Flag specifically for quitting due to ^C313 interrupt_flag: Arc<AtomicBool>,314}315316impl WorkerState {317 fn new(patterns: Vec<Regex>, config: Config) -> Self {318 let quit_flag = Arc::new(AtomicBool::new(false));319 let interrupt_flag = Arc::new(AtomicBool::new(false));320321 Self {322 patterns,323 config,324 quit_flag,325 interrupt_flag,326 }327 }328329 fn build_overrides(&self, paths: &[PathBuf]) -> Result<Override> {330 let first_path = &paths[0];331 let config = &self.config;332333 let mut builder = OverrideBuilder::new(first_path);334335 for pattern in &config.exclude_patterns {336 builder337 .add(pattern)338 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;339 }340341 builder342 .build()343 .map_err(|_| anyhow!("Mismatch in exclude patterns"))344 }345346 fn build_walker(&self, paths: &[PathBuf]) -> Result<WalkParallel> {347 let first_path = &paths[0];348 let config = &self.config;349 let overrides = self.build_overrides(paths)?;350351 let mut builder = WalkBuilder::new(first_path);352 builder353 .hidden(config.ignore_hidden)354 .ignore(config.read_fdignore)355 .parents(config.read_parent_ignore && (config.read_fdignore || config.read_vcsignore))356 .git_ignore(config.read_vcsignore)357 .git_global(config.read_vcsignore)358 .git_exclude(config.read_vcsignore)359 .require_git(config.require_git_to_read_vcsignore)360 .overrides(overrides)361 .follow_links(config.follow_links)362 // No need to check for supported platforms, option is unavailable on unsupported ones363 .same_file_system(config.one_file_system)364 .max_depth(config.max_depth);365366 if config.read_fdignore {367 builder.add_custom_ignore_filename(".fdignore");368 }369

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 370–378why, one step back
370 if config.read_global_ignore
371 && let Ok(basedirs) = etcetera::choose_base_strategy()372 {373 let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");374 if global_ignore_file.is_file() {375 let result = builder.add_ignore(global_ignore_file);376 match result {377 Some(ignore::Error::Partial(_)) => (),378 Some(err) => {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 379why, one step back
379 print_error!("Malformed pattern in global ignore file. {}.", err);

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

line 380why, one step back
380 }

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

line 381why, one step back
381 None => (),

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 382–390why, one step back
382 }
383 }384 }385386 for ignore_file in &config.ignore_files {387 let result = builder.add_ignore(ignore_file);388 match result {389 Some(ignore::Error::Partial(_)) => (),390 Some(err) => {

fix: Better sanitizingThayne McCombsbefore adoption24198d9

line 391why, one step back
391 print_error!("Malformed pattern in custom ignore file. {}.", err);

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 392–422why, one step back
392 }
393 None => (),394 }395 }396397 for path in &paths[1..] {398 builder.add(path);399 }400401 let walker = builder.threads(config.threads).build_parallel();402 Ok(walker)403 }404405 /// Run the receiver work, either on this thread or a pool of background406 /// threads (for --exec).407 fn receive(&self, rx: Receiver<Batch>) -> ExitCode {408 let config = &self.config;409410 // This will be set to `Some` if the `--exec` argument was supplied.411 if let Some(ref cmd) = config.command {412 if cmd.in_batch_mode() {413 exec::batch(rx.into_iter().flatten(), cmd, config)414 } else {415 thread::scope(|scope| {416 // Each spawned job will store its thread handle in here.417 let threads = config.threads;418 let mut handles = Vec::with_capacity(threads);419 for _ in 0..threads {420 let rx = rx.clone();421422 // Spawn a job thread that will listen for and execute inputs.

Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40

lines 423–424why, one step back
423 let handle =
424 scope.spawn(|| exec::job(rx.into_iter().flatten(), cmd, config));

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 425–448why, one step back
425
426 // Push the handle of the spawned thread into the vector for later joining.427 handles.push(handle);428 }429 let exit_codes = handles.into_iter().map(|handle| handle.join().unwrap());430 merge_exitcodes(exit_codes)431 })432 }433 } else {434 let stdout = io::stdout().lock();435 let stdout = io::BufWriter::new(stdout);436437 ReceiverBuffer::new(self, rx, stdout).process()438 }439 }440441 /// Spawn the sender threads.442 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {443 walker.run(|| {444 let patterns = &self.patterns;445 let config = &self.config;446 let quit_flag = self.quit_flag.as_ref();447448 let mut limit = 0x100;

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 449–454why, one step back
449 if let Some(cmd) = &config.command
450 && !cmd.in_batch_mode()451 && config.threads > 1452 {453 // Evenly distribute work between multiple receivers454 limit = 1;

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 455–462why, one step back
455 }
456 let mut tx = BatchSender::new(tx.clone(), limit);457458 Box::new(move |entry| {459 if quit_flag.load(Ordering::Relaxed) {460 return WalkState::Quit;461 }462

Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9

line 463why, one step back
463 if let Ok(e) = &entry {

Merge pull request #1914 from tmccombs/faster-ignore-containsThayne McCombsbefore adoptioncb3fad4

lines 464–471why, one step back
464 // If the entry is a directory that contains a
465 // "ignore contain" file", we want to skip this466 // directory.467 // Check the filetype first to avoid unnecessary468 // syscalls.469 if e.file_type().is_some_and(|t| t.is_dir()) {470 let entry_path = e.path();471 if config

Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9

lines 472–474why, one step back
472 .ignore_contain
473 .iter()474 .any(|ic| entry_path.join(ic).exists())

Merge pull request #1914 from tmccombs/faster-ignore-containsThayne McCombsbefore adoptioncb3fad4

lines 475–477why, one step back
475 {
476 return WalkState::Skip;477 }

Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9

lines 478–479why, one step back
478 }
479 if e.depth() == 0 {

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 480–482why, one step back
480 // Skip the root directory entry.
481 return WalkState::Continue;482 }

Merge pull request #1852 from fischman/1727-ignore-containThayne McCombsbefore adoptionbf81fb9

lines 483–484why, one step back
483 }
484 let entry = match entry {

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

line 485why, one step back
485 Ok(e) => DirEntry::normal(e),

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

lines 486–492why, one step back
486 Err(err) => match broken_symlink_from_err(err) {
487 Ok(entry) => entry,488 Err(err) => {489 return match tx.send(WorkerResult::Error(err)) {490 Ok(_) => WalkState::Continue,491 Err(_) => WalkState::Quit,492 };

Merge pull request #2039 from hexbinoct/fix/min-depth-broken-symlinkThayne McCombsbefore adoptionce97e47

line 493why, one step back
493 }

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

line 494why, one step back
494 },

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 495–496why, one step back
495 };
496

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 497–500why, one step back
497 if let Some(min_depth) = config.min_depth
498 && entry.depth().is_none_or(|d| d < min_depth)499 {500 return WalkState::Continue;

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 501–505why, one step back
501 }
502503 // Check the name first, since it doesn't require metadata504 let entry_path = entry.path();505

Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8

line 506why, one step back
506 let search_str = search_str_for_entry(entry_path, config.full_path_base.as_deref());

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 507–526why, one step back
507
508 if !patterns509 .iter()510 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))511 {512 return WalkState::Continue;513 }514515 // Filter out unwanted extensions.516 if let Some(ref exts_regex) = config.extensions {517 if let Some(path_str) = entry_path.file_name() {518 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {519 return WalkState::Continue;520 }521 } else {522 return WalkState::Continue;523 }524 }525526 // Filter out unwanted file types.

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 527–530why, one step back
527 if let Some(ref file_types) = config.file_types
528 && file_types.should_ignore(&entry)529 {530 return WalkState::Continue;

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 531–568why, one step back
531 }
532533 #[cfg(unix)]534 {535 if let Some(ref owner_constraint) = config.owner_constraint {536 if let Some(metadata) = entry.metadata() {537 if !owner_constraint.matches(metadata) {538 return WalkState::Continue;539 }540 } else {541 return WalkState::Continue;542 }543 }544 }545546 // Filter out unwanted sizes if it is a file and we have been given size constraints.547 if !config.size_constraints.is_empty() {548 if entry_path.is_file() {549 if let Some(metadata) = entry.metadata() {550 let file_size = metadata.len();551 if config552 .size_constraints553 .iter()554 .any(|sc| !sc.is_within(file_size))555 {556 return WalkState::Continue;557 }558 } else {559 return WalkState::Continue;560 }561 } else {562 return WalkState::Continue;563 }564 }565566 // Filter out unwanted modification times567 if !config.time_constraints.is_empty() {568 let mut matched = false;

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 569–575why, one step back
569 if let Some(metadata) = entry.metadata()
570 && let Ok(modified) = metadata.modified()571 {572 matched = config573 .time_constraints574 .iter()575 .all(|tf| tf.applies_to(&modified));

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 576–581why, one step back
576 }
577 if !matched {578 return WalkState::Continue;579 }580 }581

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

lines 582–586why, one step back
582 if config.is_printing()
583 && let Some(ls_colors) = &config.ls_colors584 {585 // Compute colors in parallel586 entry.style(ls_colors);

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 587–640why, one step back
587 }
588589 let send_result = tx.send(WorkerResult::Entry(entry));590591 if send_result.is_err() {592 return WalkState::Quit;593 }594595 // Apply pruning.596 if config.prune {597 return WalkState::Skip;598 }599600 WalkState::Continue601 })602 });603 }604605 /// Perform the recursive scan.606 fn scan(&self, paths: &[PathBuf]) -> Result<ExitCode> {607 let config = &self.config;608 let walker = self.build_walker(paths)?;609610 if config.ls_colors.is_some() && config.is_printing() {611 let quit_flag = Arc::clone(&self.quit_flag);612 let interrupt_flag = Arc::clone(&self.interrupt_flag);613614 ctrlc::set_handler(move || {615 quit_flag.store(true, Ordering::Relaxed);616617 if interrupt_flag.fetch_or(true, Ordering::Relaxed) {618 // Ctrl-C has been pressed twice, exit NOW619 ExitCode::KilledBySigint.exit();620 }621 })622 .unwrap();623 }624625 let (tx, rx) = bounded(2 * config.threads);626627 let exit_code = thread::scope(|scope| {628 // Spawn the receiver thread(s)629 let receiver = scope.spawn(|| self.receive(rx));630631 // Spawn the sender threads.632 self.spawn_senders(walker, tx);633634 receiver.join().unwrap()635 });636637 if self.interrupt_flag.load(Ordering::Relaxed) {638 Ok(ExitCode::KilledBySigint)639 } else {640 Ok(exit_code)

Merge pull request #1917 from Xavrir/issue-1900Thayne McCombsbefore adoption6d77799

lines 641–642why, one step back
641 }
642 }

Merge pull request #2039 from hexbinoct/fix/min-depth-broken-symlinkThayne McCombsbefore adoptionce97e47

lines 643–644why, one step back
643}
644

Merge pull request #2143 from tmccombs/broken-symlink-refactorThayne McCombsbefore adoption9fe5cb7

lines 645–685why, one step back
645/// If `err` is for a broken symlink, create a broken symlink DirEntry,
646/// otherwise, return the original error.647fn broken_symlink_from_err(mut err: ignore::Error) -> Result<DirEntry, ignore::Error> {648 use ignore::Error::*;649 let mut depth = None;650 let mut path = None;651 let mut current = &mut err;652 // Loop through the items in the chain, and extract the path and depth as we find them.653 // Then once we get to the (terminal) io error, check that it is for a broken symlink.654 loop {655 match current {656 WithPath { err, path: p } => {657 path = Some(p);658 current = err;659 }660 WithDepth { err, depth: d } => {661 depth = Some(*d);662 current = err;663 }664 Io(e) if e.kind() == io::ErrorKind::NotFound => {665 if let Some(path) = path666 && path667 .symlink_metadata()668 .ok()669 .is_some_and(|m| m.file_type().is_symlink())670 {671 // Since we no longer need the original error, we can take the PathBuf of the672 // path out of it.673 return Ok(DirEntry::broken_symlink(mem::take(path), depth));674 } else {675 // This is pretty unlikely.676 return Err(err);677 }678 }679 // We don't care about Loop because that won't happen680 // for broken symlinks, and there are two paths involved681 // and we don't care about WithLineNumber because that only applies682 // to errors while parsing ignore files.683 _ => return Err(err),684 }685 }

Merge pull request #1917 from Xavrir/issue-1900Thayne McCombsbefore adoption6d77799

lines 686–689why, one step back
686}
687688fn search_str_for_entry<'a>(689 entry_path: &'a std::path::Path,

Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8

line 690why, one step back
690 full_path_base: Option<&std::path::Path>,

Merge pull request #1917 from Xavrir/issue-1900Thayne McCombsbefore adoption6d77799

line 691why, one step back
691) -> Cow<'a, OsStr> {

Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8

lines 692–699why, one step back
692 if let Some(cwd) = full_path_base {
693 // If full_path_base is some, that means that we need to return694 // the absolute path695 if entry_path.is_absolute() {696 return Cow::Borrowed(entry_path.as_os_str());697 }698 let path = entry_path.strip_prefix(".").unwrap_or(entry_path);699 Cow::Owned(cwd.join(path).into())

Merge pull request #1917 from Xavrir/issue-1900Thayne McCombsbefore adoption6d77799

lines 700–707why, one step back
700 } else {
701 match entry_path.file_name() {702 Some(filename) => Cow::Borrowed(filename),703 None => unreachable!(704 "Encountered file system entry without a file name. This should only \705 happen for paths like 'foo/bar/..' or '/' which are not supposed to \706 appear in a file system traversal."707 ),

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

lines 708–718why, one step back
708 }
709 }710}711712/// Recursively scan the given search path for files / pathnames matching the patterns.713///714/// If the `--exec` argument was supplied, this will create a thread pool for executing715/// jobs in parallel from a given command line and the discovered paths. Otherwise, each716/// path will simply be written to standard output.717pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {718 WorkerState::new(patterns, config).scan(paths)

Merge pull request #1928 from tmccombs/full-path-fixesTavian Barnesbefore adoptiond6b44b8

lines 719–759why, one step back
719}
720721#[cfg(test)]722mod tests {723 use super::search_str_for_entry;724 use std::path::{Path, PathBuf};725726 #[test]727 fn search_str_for_entry_with_relative_path() {728 let full_path_base = Some(Path::new("/home/user"));729 assert_eq!(730 search_str_for_entry(Path::new("foo/bar"), full_path_base),731 PathBuf::from("/home/user/foo/bar")732 );733 }734735 #[test]736 fn search_str_for_entry_strips_dot_prefix() {737 let full_path_base = Some(Path::new("/home/user"));738 assert_eq!(739 search_str_for_entry(Path::new("./foo/bar"), full_path_base),740 PathBuf::from("/home/user/foo/bar")741 );742 }743744 #[test]745 fn search_str_for_entry_with_absolute_path() {746 let full_path_base = Some(Path::new("/home/user"));747 assert_eq!(748 search_str_for_entry(Path::new("/absolute/path"), full_path_base),749 PathBuf::from("/absolute/path")750 );751 }752753 #[test]754 fn search_str_no_base_dir() {755 assert_eq!(756 search_str_for_entry(Path::new("./foo/bar"), None),757 PathBuf::from("bar")758 );759 }

Merge pull request #2037 from parneetsingh022/tests/search-str-for-entry-edge-casesThayne McCombsbefore adoption95dc645

lines 760–775why, one step back
760
761 #[test]762 fn search_str_no_base_dir_with_plain_relative_path() {763 assert_eq!(764 search_str_for_entry(Path::new("foo/bar"), None),765 PathBuf::from("bar")766 );767 }768769 #[test]770 fn search_str_no_base_dir_with_file_in_current_dir() {771 assert_eq!(772 search_str_for_entry(Path::new("foo"), None),773 PathBuf::from("foo")774 );775 }

Merge pull request #1657 from sharkdp/dependabot/cargo/clap-4.5.23Tavian Barnesbefore adoption86d6e2d

line 776why, one step back
776}