walk.rs
This file
Path
src/walk.rs
672 lines · 22.7 KiB · Rust
Last changed by
Merge pull request #1517 from one230six/masterThayne McCombsbefore adoption68fe31d
History of this fileTake it
The walk stopped after 200 commits: lines older than fcf8099 point at it.
walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 1why, one step back1use std::borrow::Cow;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 2why, one step back2use std::ffi::OsStr;walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 3why, one step back3use std::io::{self, Write};Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 4–6why, one step back4use std::mem;5use std::path::PathBuf;6use std::sync::atomic::{AtomicBool, Ordering};Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 7why, one step back7use std::sync::{Arc, Mutex, MutexGuard};Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 8–11why, one step back8use std::thread;9use std::time::{Duration, Instant};1011use anyhow::{anyhow, Result};Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 12why, one step back12use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, SendError, Sender};Replace `dirs-next` crate with `etcetera` crateUtkarsh Guptabefore adoption3ae0454
line 13why, one step back13use etcetera::BaseStrategy;walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 14why, one step back14use ignore::overrides::{Override, OverrideBuilder};Merge pull request #1517 from one230six/masterThayne McCombsbefore adoption68fe31d
line 15why, one step back15use ignore::{WalkBuilder, WalkParallel, WalkState};Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 16–37why, one step back16use regex::bytes::Regex;1718use crate::config::Config;19use crate::dir_entry::DirEntry;20use crate::error::print_error;21use crate::exec;22use crate::exit_codes::{merge_exitcodes, ExitCode};23use crate::filesystem;24use crate::output;2526/// The receiver thread can either be buffering results or directly streaming to the console.27#[derive(PartialEq)]28enum ReceiverMode {29 /// Receiver is still buffering in order to sort the results, if the search finishes fast30 /// enough.31 Buffering,3233 /// Receiver is directly printing results to the output.34 Streaming,35}3637/// The Worker threads can result in a valid entry having PathBuf or an error.Merge pull request #1159 from tmccombs/silence-large-variantDavid Peterbefore adoptionfbef976
line 38why, one step back38#[allow(clippy::large_enum_variant)]Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 39why, one step back39#[derive(Debug)]Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 40why, one step back40pub enum WorkerResult {Merge pull request #1159 from tmccombs/silence-large-variantDavid Peterbefore adoptionfbef976
lines 41–42why, one step back41 // Errors should be rare, so it's probably better to allow large_enum_variant than42 // to box the Entry variantAdd Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 43–46why, one step back43 Entry(DirEntry),44 Error(ignore::Error),45}46Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
lines 47–123why, one step back47/// A batch of WorkerResults to send over a channel.48#[derive(Clone)]49struct Batch {50 items: Arc<Mutex<Option<Vec<WorkerResult>>>>,51}5253impl Batch {54 fn new() -> Self {55 Self {56 items: Arc::new(Mutex::new(Some(vec![]))),57 }58 }5960 fn lock(&self) -> MutexGuard<'_, Option<Vec<WorkerResult>>> {61 self.items.lock().unwrap()62 }63}6465impl IntoIterator for Batch {66 type Item = WorkerResult;67 type IntoIter = std::vec::IntoIter<WorkerResult>;6869 fn into_iter(self) -> Self::IntoIter {70 self.lock().take().unwrap().into_iter()71 }72}7374/// Wrapper that sends batches of items at once over a channel.75struct BatchSender {76 batch: Batch,77 tx: Sender<Batch>,78 limit: usize,79}8081impl BatchSender {82 fn new(tx: Sender<Batch>, limit: usize) -> Self {83 Self {84 batch: Batch::new(),85 tx,86 limit,87 }88 }8990 /// 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 }99100 /// Add an item to a batch.101 fn send(&mut self, item: WorkerResult) -> Result<(), SendError<()>> {102 let mut batch = self.batch.lock();103104 if self.needs_flush(batch.as_ref()) {105 drop(batch);106 self.batch = Batch::new();107 batch = self.batch.lock();108 }109110 let items = batch.as_mut().unwrap();111 items.push(item);112113 if items.len() == 1 {114 // New batch, send it over the channel115 self.tx116 .send(self.batch.clone())117 .map_err(|_| SendError(()))?;118 }119120 Ok(())121 }122}123Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 124why, one step back124/// Maximum size of the output buffer before flushing results to the consolewalk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 125why, one step back125const MAX_BUFFER_LENGTH: usize = 1000;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 126why, one step back126/// Default duration until output buffering switches to streaming.walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 127why, one step back127const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 128–129why, one step back128129/// Wrapper for the receiver thread's buffering behavior.walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 130why, one step back130struct ReceiverBuffer<'a, W> {Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 131why, one step back131 /// The configuration.walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 132why, one step back132 config: &'a Config,Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 133why, one step back133 /// For shutting down the senders.walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 134why, one step back134 quit_flag: &'a AtomicBool,Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 135why, one step back135 /// The ^C notifier.walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 136why, one step back136 interrupt_flag: &'a AtomicBool,Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 137why, one step back137 /// Receiver for worker results.Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 138why, one step back138 rx: Receiver<Batch>,Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 139–150why, one step back139 /// Standard output.140 stdout: W,141 /// The current buffer mode.142 mode: ReceiverMode,143 /// The deadline to switch to streaming mode.144 deadline: Instant,145 /// The buffer of quickly received paths.146 buffer: Vec<DirEntry>,147 /// Result count.148 num_results: usize,149}150walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 151why, one step back151impl<'a, W: Write> ReceiverBuffer<'a, W> {Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 152why, one step back152 /// Create a new receiver buffer.Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 153why, one step back153 fn new(state: &'a WorkerState, rx: Receiver<Batch>, stdout: W) -> Self {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 154–156why, one step back154 let config = &state.config;155 let quit_flag = state.quit_flag.as_ref();156 let interrupt_flag = state.interrupt_flag.as_ref();Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 157–183why, one step back157 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);158 let deadline = Instant::now() + max_buffer_time;159160 Self {161 config,162 quit_flag,163 interrupt_flag,164 rx,165 stdout,166 mode: ReceiverMode::Buffering,167 deadline,168 buffer: Vec::with_capacity(MAX_BUFFER_LENGTH),169 num_results: 0,170 }171 }172173 /// Process results until finished.174 fn process(&mut self) -> ExitCode {175 loop {176 if let Err(ec) = self.poll() {177 self.quit_flag.store(true, Ordering::Relaxed);178 return ec;179 }180 }181 }182183 /// Receive the next worker result.Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 184why, one step back184 fn recv(&self) -> Result<Batch, RecvTimeoutError> {Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 185–187why, one step back185 match self.mode {186 ReceiverMode::Buffering => {187 // Wait at most until we should switch to streamingwalk: Switch back to crossbeam-channelTavian Barnesbefore adoption5bb7a52
line 188why, one step back188 self.rx.recv_deadline(self.deadline)Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 189–199why, one step back189 }190 ReceiverMode::Streaming => {191 // Wait however long it takes for a result192 Ok(self.rx.recv()?)193 }194 }195 }196197 /// Wait for a result or state change.198 fn poll(&mut self) -> Result<(), ExitCode> {199 match self.recv() {Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
lines 200–206why, one step back200 Ok(batch) => {201 for result in batch {202 match result {203 WorkerResult::Entry(dir_entry) => {204 if self.config.quiet {205 return Err(ExitCode::HasResults(true));206 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 207why, one step back207Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
lines 208–225why, one step back208 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 }219220 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 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 226why, one step back226 }Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
lines 227–231why, one step back227 WorkerResult::Error(err) => {228 if self.config.show_filesystem_errors {229 print_error(err.to_string());230 }231 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 232–233why, one step back232 }233 }walk: Flush stdout in batchesTavian Barnesbefore adoption16c2d1e
lines 234–238why, one step back234235 // If we don't have another batch ready, flush before waiting236 if self.mode == ReceiverMode::Streaming && self.rx.is_empty() {237 self.flush()?;238 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 239–252why, one step back239 }240 Err(RecvTimeoutError::Timeout) => {241 self.stream()?;242 }243 Err(RecvTimeoutError::Disconnected) => {244 return self.stop();245 }246 }247248 Ok(())249 }250251 /// Output a path.252 fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {Merge pull request #1510 from garlic-hub/clippyTavian Barnesbefore adoption4efc05e
line 253why, one step back253 output::print_entry(&mut self.stdout, entry, self.config);Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 254–291why, one step back254255 if self.interrupt_flag.load(Ordering::Relaxed) {256 // Ignore any errors on flush, because we're about to exit anyway257 let _ = self.flush();258 return Err(ExitCode::KilledBySigint);259 }260261 Ok(())262 }263264 /// Switch ourselves into streaming mode.265 fn stream(&mut self) -> Result<(), ExitCode> {266 self.mode = ReceiverMode::Streaming;267268 let buffer = mem::take(&mut self.buffer);269 for path in buffer {270 self.print(&path)?;271 }272273 self.flush()274 }275276 /// Stop looping.277 fn stop(&mut self) -> Result<(), ExitCode> {278 if self.mode == ReceiverMode::Buffering {279 self.buffer.sort();280 self.stream()?;281 }282283 if self.config.quiet {284 Err(ExitCode::HasResults(self.num_results > 0))285 } else {286 Err(ExitCode::Success)287 }288 }289290 /// Flush stdout if necessary.291 fn flush(&mut self) -> Result<(), ExitCode> {walk: Flush stdout in batchesTavian Barnesbefore adoption16c2d1e
line 292why, one step back292 if self.stdout.flush().is_err() {Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 293–299why, one step back293 // Probably a broken pipe. Exit gracefully.294 return Err(ExitCode::GeneralError);295 }296 Ok(())297 }298}299walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 300–310why, one step back300/// State shared by the sender and receiver threads.301struct WorkerState {302 /// The search patterns.303 patterns: Vec<Regex>,304 /// The command line configuration.305 config: Config,306 /// Flag for cleanly shutting down the parallel walk307 quit_flag: Arc<AtomicBool>,308 /// Flag specifically for quitting due to ^C309 interrupt_flag: Arc<AtomicBool>,310}Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 311why, one step back311walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 312–409why, one step back312impl WorkerState {313 fn new(patterns: Vec<Regex>, config: Config) -> Self {314 let quit_flag = Arc::new(AtomicBool::new(false));315 let interrupt_flag = Arc::new(AtomicBool::new(false));316317 Self {318 patterns,319 config,320 quit_flag,321 interrupt_flag,322 }323 }324325 fn build_overrides(&self, paths: &[PathBuf]) -> Result<Override> {326 let first_path = &paths[0];327 let config = &self.config;328329 let mut builder = OverrideBuilder::new(first_path);330331 for pattern in &config.exclude_patterns {332 builder333 .add(pattern)334 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;335 }336337 if config.read_vcsignore {338 builder.add("!.git/").expect("Invalid exclude pattern");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 }369370 if config.read_global_ignore {371 if let Ok(basedirs) = etcetera::choose_base_strategy() {372 let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");373 if global_ignore_file.is_file() {374 let result = builder.add_ignore(global_ignore_file);375 match result {376 Some(ignore::Error::Partial(_)) => (),377 Some(err) => {378 print_error(format!(379 "Malformed pattern in global ignore file. {}.",380 err381 ));382 }383 None => (),384 }385 }386 }387 }388389 for ignore_file in &config.ignore_files {390 let result = builder.add_ignore(ignore_file);391 match result {392 Some(ignore::Error::Partial(_)) => (),393 Some(err) => {394 print_error(format!("Malformed pattern in custom ignore file. {}.", err));395 }396 None => (),397 }398 }399400 for path in &paths[1..] {401 builder.add(path);402 }403404 let walker = builder.threads(config.threads).build_parallel();405 Ok(walker)406 }407408 /// Run the receiver work, either on this thread or a pool of background409 /// threads (for --exec).Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 410why, one step back410 fn receive(&self, rx: Receiver<Batch>) -> ExitCode {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 411–412why, one step back411 let config = &self.config;412Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 413–415why, one step back413 // 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() {Merge pull request #1510 from garlic-hub/clippyTavian Barnesbefore adoption4efc05e
line 416why, one step back416 exec::batch(rx.into_iter().flatten(), cmd, config)Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 417why, one step back417 } else {Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10
line 418why, one step back418 let out_perm = Mutex::new(());Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 419why, one step back419Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10
line 420why, one step back420 thread::scope(|scope| {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 421–422why, one step back421 // Each spawned job will store its thread handle in here.422 let threads = config.threads;Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10
lines 423–425why, one step back423 let mut handles = Vec::with_capacity(threads);424 for _ in 0..threads {425 let rx = rx.clone();Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 426why, one step back426Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10
line 427why, one step back427 // Spawn a job thread that will listen for and execute inputs.Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 428why, one step back428 let handle = scopeMerge pull request #1510 from garlic-hub/clippyTavian Barnesbefore adoption4efc05e
line 429why, one step back429 .spawn(|| exec::job(rx.into_iter().flatten(), cmd, &out_perm, config));Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 430why, one step back430Merge pull request #1283 from tmccombs/new-rust-versionTavian Barnesbefore adoptione4bca10
lines 431–436why, one step back431 // Push the handle of the spawned thread into the vector for later joining.432 handles.push(handle);433 }434 let exit_codes = handles.into_iter().map(|handle| handle.join().unwrap());435 merge_exitcodes(exit_codes)436 })Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 437–438why, one step back437 }438 } else {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 439why, one step back439 let stdout = io::stdout().lock();Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 440–441why, one step back440 let stdout = io::BufWriter::new(stdout);441walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 442why, one step back442 ReceiverBuffer::new(self, rx, stdout).process()Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 443why, one step back443 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 444why, one step back444 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 445why, one step back445walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 446why, one step back446 /// Spawn the sender threads.Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 447why, one step back447 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 448–451why, one step back448 walker.run(|| {449 let patterns = &self.patterns;450 let config = &self.config;451 let quit_flag = self.quit_flag.as_ref();Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 452why, one step back452Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
lines 453–461why, one step back453 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);461walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 462–464why, one step back462 Box::new(move |entry| {463 if quit_flag.load(Ordering::Relaxed) {464 return WalkState::Quit;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 465why, one step back465 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 466–470why, one step back466467 let entry = match entry {468 Ok(ref e) if e.depth() == 0 => {469 // Skip the root directory entry.470 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 471why, one step back471 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 472–484why, one step back472 Ok(e) => DirEntry::normal(e),473 Err(ignore::Error::WithPath {474 path,475 err: inner_err,476 }) => match inner_err.as_ref() {477 ignore::Error::Io(io_error)478 if io_error.kind() == io::ErrorKind::NotFound479 && path480 .symlink_metadata()481 .ok()482 .map_or(false, |m| m.file_type().is_symlink()) =>483 {484 DirEntry::broken_symlink(path)Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 485why, one step back485 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 486–500why, one step back486 _ => {487 return match tx.send(WorkerResult::Error(ignore::Error::WithPath {488 path,489 err: inner_err,490 })) {491 Ok(_) => WalkState::Continue,492 Err(_) => WalkState::Quit,493 }494 }495 },496 Err(err) => {497 return match tx.send(WorkerResult::Error(err)) {498 Ok(_) => WalkState::Continue,499 Err(_) => WalkState::Quit,500 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 501why, one step back501 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 502–506why, one step back502 };503504 if let Some(min_depth) = config.min_depth {505 if entry.depth().map_or(true, |d| d < min_depth) {506 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 507–509why, one step back507 }508 }509walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 510–511why, one step back510 // Check the name first, since it doesn't require metadata511 let entry_path = entry.path();Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 512why, one step back512walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 513–526why, one step back513 let search_str: Cow<OsStr> = if config.search_full_path {514 let path_abs_buf = filesystem::path_absolute_form(entry_path)515 .expect("Retrieving absolute path succeeds");516 Cow::Owned(path_abs_buf.as_os_str().to_os_string())517 } else {518 match entry_path.file_name() {519 Some(filename) => Cow::Borrowed(filename),520 None => unreachable!(521 "Encountered file system entry without a file name. This should only \522 happen for paths like 'foo/bar/..' or '/' which are not supposed to \523 appear in a file system traversal."524 ),525 }526 };Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 527why, one step back527walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 528–532why, one step back528 if !patterns529 .iter()530 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))531 {532 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 533–534why, one step back533 }534walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 535–544why, one step back535 // Filter out unwanted extensions.536 if let Some(ref exts_regex) = config.extensions {537 if let Some(path_str) = entry_path.file_name() {538 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {539 return WalkState::Continue;540 }541 } else {542 return WalkState::Continue;543 }544 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 545why, one step back545walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 546–549why, one step back546 // Filter out unwanted file types.547 if let Some(ref file_types) = config.file_types {548 if file_types.should_ignore(&entry) {549 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 550–552why, one step back550 }551 }552walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 553–563why, one step back553 #[cfg(unix)]554 {555 if let Some(ref owner_constraint) = config.owner_constraint {556 if let Some(metadata) = entry.metadata() {557 if !owner_constraint.matches(metadata) {558 return WalkState::Continue;559 }560 } else {561 return WalkState::Continue;562 }563 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 564–565why, one step back564 }565walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 566–579why, one step back566 // Filter out unwanted sizes if it is a file and we have been given size constraints.567 if !config.size_constraints.is_empty() {568 if entry_path.is_file() {569 if let Some(metadata) = entry.metadata() {570 let file_size = metadata.len();571 if config572 .size_constraints573 .iter()574 .any(|sc| !sc.is_within(file_size))575 {576 return WalkState::Continue;577 }578 } else {579 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 580–581why, one step back580 }581 } else {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
line 582why, one step back582 return WalkState::Continue;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 583–585why, one step back583 }584 }585walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 586–588why, one step back586 // Filter out unwanted modification times587 if !config.time_constraints.is_empty() {588 let mut matched = false;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 589why, one step back589 if let Some(metadata) = entry.metadata() {walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 590–594why, one step back590 if let Ok(modified) = metadata.modified() {591 matched = config592 .time_constraints593 .iter()594 .all(|tf| tf.applies_to(&modified));Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 595–596why, one step back595 }596 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 597–599why, one step back597 if !matched {598 return WalkState::Continue;599 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 600–601why, one step back600 }601walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 602–605why, one step back602 if config.is_printing() {603 if let Some(ls_colors) = &config.ls_colors {604 // Compute colors in parallel605 entry.style(ls_colors);Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 606–607why, one step back606 }607 }walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 608–612why, one step back608609 let send_result = tx.send(WorkerResult::Entry(entry));610611 if send_result.is_err() {612 return WalkState::Quit;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
lines 613–614why, one step back613 }614walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 615–617why, one step back615 // Apply pruning.616 if config.prune {617 return WalkState::Skip;Compute colors in parallelTavian Barnesbefore adoption17d849d
lines 618–619why, one step back618 }619walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 620–623why, one step back620 WalkState::Continue621 })622 });623 }Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 624why, one step back624walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 625–628why, one step back625 /// Perform the recursive scan.626 fn scan(&self, paths: &[PathBuf]) -> Result<ExitCode> {627 let config = &self.config;628 let walker = self.build_walker(paths)?;Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 629why, one step back629walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 630–632why, one step back630 if config.ls_colors.is_some() && config.is_printing() {631 let quit_flag = Arc::clone(&self.quit_flag);632 let interrupt_flag = Arc::clone(&self.interrupt_flag);Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 633why, one step back633walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 634–644why, one step back634 ctrlc::set_handler(move || {635 quit_flag.store(true, Ordering::Relaxed);636637 if interrupt_flag.fetch_or(true, Ordering::Relaxed) {638 // Ctrl-C has been pressed twice, exit NOW639 ExitCode::KilledBySigint.exit();640 }641 })642 .unwrap();643 }644Merge pull request #1422 from tavianator/batchTavian Barnesbefore adoption84f032e
line 645why, one step back645 let (tx, rx) = bounded(2 * config.threads);walk: New WorkerState struct shared by the worker threadsTavian Barnesbefore adoption8bbbd76
lines 646–671why, one step back646647 let exit_code = thread::scope(|scope| {648 // Spawn the receiver thread(s)649 let receiver = scope.spawn(|| self.receive(rx));650651 // Spawn the sender threads.652 self.spawn_senders(walker, tx);653654 receiver.join().unwrap()655 });656657 if self.interrupt_flag.load(Ordering::Relaxed) {658 Ok(ExitCode::KilledBySigint)659 } else {660 Ok(exit_code)661 }662 }663}664665/// Recursively scan the given search path for files / pathnames matching the patterns.666///667/// If the `--exec` argument was supplied, this will create a thread pool for executing668/// jobs in parallel from a given command line and the discovered paths. Otherwise, each669/// path will simply be written to standard output.670pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {671 WorkerState::new(patterns, config).scan(paths)Add Github URL to `--help` alsoScott Bakerbefore adoptionfcf8099
line 672why, one step back672}