Skip to content
Myr

walk: New WorkerState struct shared by the worker threads

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tavian Barnes · committed by David Peter · parent cd32a38 · Browse files · 2 files+315 added−291 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+315 added−291 removed

  • other:+315 added−291 removed

2 files+315 added−291 removed

modified:src/main.rs+1 added-1 removed
101 unmodified lines
102 .into_iter()103 .map(|pat| build_regex(pat, &config))104 .collect::<Result<Vec<Regex>>>()?;105106 walk::scan(&search_paths, Arc::new(regexps), Arc::new(config))106 walk::scan(&search_paths, regexps, config)107}108109#[cfg(feature = "completions")]110#[cold]
363 unmodified lines
modified:src/walk.rs+314 added-290 removed
1use std::borrow::Cow;2use std::ffi::OsStr;2use std::io;3use std::io::{self, Write};4use std::mem;5use std::path::PathBuf;6use std::sync::atomic::{AtomicBool, Ordering};7use std::sync::{Arc, Mutex};8use std::thread;9use std::time::{Duration, Instant};9use std::{borrow::Cow, io::Write};1011use anyhow::{anyhow, Result};12use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};13use etcetera::BaseStrategy;14use ignore::overrides::OverrideBuilder;15use ignore::{self, WalkBuilder};14use ignore::overrides::{Override, OverrideBuilder};15use ignore::{self, WalkBuilder, WalkParallel, WalkState};16use regex::bytes::Regex;1718use crate::config::Config;19use crate::dir_entry::DirEntry;
23 unmodified lines
43 Error(ignore::Error),44}4546/// Maximum size of the output buffer before flushing results to the console47pub const MAX_BUFFER_LENGTH: usize = 1000;47const MAX_BUFFER_LENGTH: usize = 1000;48/// Default duration until output buffering switches to streaming.49pub const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);49const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);5051/// Recursively scan the given search path for files / pathnames matching the patterns.52///53/// If the `--exec` argument was supplied, this will create a thread pool for executing54/// jobs in parallel from a given command line and the discovered paths. Otherwise, each55/// path will simply be written to standard output.56pub fn scan(paths: &[PathBuf], patterns: Arc<Vec<Regex>>, config: Arc<Config>) -> Result<ExitCode> {57 let first_path = &paths[0];5859 // Channel capacity was chosen empircally to perform similarly to an unbounded channel60 let (tx, rx) = bounded(0x4000 * config.threads);6162 let mut override_builder = OverrideBuilder::new(first_path);6364 for pattern in &config.exclude_patterns {65 override_builder66 .add(pattern)67 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;68 }6970 if config.read_vcsignore {71 override_builder72 .add("!.git/")73 .expect("Invalid exclude pattern");74 }7576 let overrides = override_builder77 .build()78 .map_err(|_| anyhow!("Mismatch in exclude patterns"))?;7980 let mut walker = WalkBuilder::new(first_path);81 walker82 .hidden(config.ignore_hidden)83 .ignore(config.read_fdignore)84 .parents(config.read_parent_ignore && (config.read_fdignore || config.read_vcsignore))85 .git_ignore(config.read_vcsignore)86 .git_global(config.read_vcsignore)87 .git_exclude(config.read_vcsignore)88 .require_git(config.require_git_to_read_vcsignore)89 .overrides(overrides)90 .follow_links(config.follow_links)91 // No need to check for supported platforms, option is unavailable on unsupported ones92 .same_file_system(config.one_file_system)93 .max_depth(config.max_depth);9495 if config.read_fdignore {96 walker.add_custom_ignore_filename(".fdignore");97 }9899 if config.read_global_ignore {100 if let Ok(basedirs) = etcetera::choose_base_strategy() {101 let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");102 if global_ignore_file.is_file() {103 let result = walker.add_ignore(global_ignore_file);104 match result {105 Some(ignore::Error::Partial(_)) => (),106 Some(err) => {107 print_error(format!("Malformed pattern in global ignore file. {}.", err));108 }109 None => (),110 }111 }112 }113 }114115 for ignore_file in &config.ignore_files {116 let result = walker.add_ignore(ignore_file);117 match result {118 Some(ignore::Error::Partial(_)) => (),119 Some(err) => {120 print_error(format!("Malformed pattern in custom ignore file. {}.", err));121 }122 None => (),123 }124 }125126 for path in &paths[1..] {127 walker.add(path);128 }129130 let parallel_walker = walker.threads(config.threads).build_parallel();131132 // Flag for cleanly shutting down the parallel walk133 let quit_flag = Arc::new(AtomicBool::new(false));134 // Flag specifically for quitting due to ^C135 let interrupt_flag = Arc::new(AtomicBool::new(false));136137 if config.ls_colors.is_some() && config.is_printing() {138 let quit_flag = Arc::clone(&quit_flag);139 let interrupt_flag = Arc::clone(&interrupt_flag);140141 ctrlc::set_handler(move || {142 quit_flag.store(true, Ordering::Relaxed);143144 if interrupt_flag.fetch_or(true, Ordering::Relaxed) {145 // Ctrl-C has been pressed twice, exit NOW146 ExitCode::KilledBySigint.exit();147 }148 })149 .unwrap();150 }151152 // Spawn the thread that receives all results through the channel.153 let receiver_thread = spawn_receiver(&config, &quit_flag, &interrupt_flag, rx);154155 // Spawn the sender threads.156 spawn_senders(&config, &quit_flag, patterns, parallel_walker, tx);157158 // Wait for the receiver thread to print out all results.159 let exit_code = receiver_thread.join().unwrap();160161 if interrupt_flag.load(Ordering::Relaxed) {162 Ok(ExitCode::KilledBySigint)163 } else {164 Ok(exit_code)165 }166}16751/// Wrapper for the receiver thread's buffering behavior.169struct ReceiverBuffer<W> {52struct ReceiverBuffer<'a, W> {53 /// The configuration.171 config: Arc<Config>,54 config: &'a Config,55 /// For shutting down the senders.173 quit_flag: Arc<AtomicBool>,56 quit_flag: &'a AtomicBool,57 /// The ^C notifier.175 interrupt_flag: Arc<AtomicBool>,58 interrupt_flag: &'a AtomicBool,59 /// Receiver for worker results.60 rx: Receiver<WorkerResult>,61 /// Standard output.62 stdout: W,
6 unmodified lines
69 /// Result count.70 num_results: usize,71}72190impl<W: Write> ReceiverBuffer<W> {73impl<'a, W: Write> ReceiverBuffer<'a, W> {74 /// Create a new receiver buffer.192 fn new(193 config: Arc<Config>,194 quit_flag: Arc<AtomicBool>,195 interrupt_flag: Arc<AtomicBool>,196 rx: Receiver<WorkerResult>,197 stdout: W,198 ) -> Self {75 fn new(state: &'a WorkerState, rx: Receiver<WorkerResult>, stdout: W) -> Self {76 let config = &state.config;77 let quit_flag = state.quit_flag.as_ref();78 let interrupt_flag = state.interrupt_flag.as_ref();79 let max_buffer_time = config.max_buffer_time.unwrap_or(DEFAULT_MAX_BUFFER_TIME);80 let deadline = Instant::now() + max_buffer_time;8182 Self {
125 unmodified lines
208 Ok(())209 }210}211332fn spawn_receiver(333 config: &Arc<Config>,334 quit_flag: &Arc<AtomicBool>,335 interrupt_flag: &Arc<AtomicBool>,336 rx: Receiver<WorkerResult>,337) -> thread::JoinHandle<ExitCode> {338 let config = Arc::clone(config);339 let quit_flag = Arc::clone(quit_flag);340 let interrupt_flag = Arc::clone(interrupt_flag);212/// State shared by the sender and receiver threads.213struct WorkerState {214 /// The search patterns.215 patterns: Vec<Regex>,216 /// The command line configuration.217 config: Config,218 /// Flag for cleanly shutting down the parallel walk219 quit_flag: Arc<AtomicBool>,220 /// Flag specifically for quitting due to ^C221 interrupt_flag: Arc<AtomicBool>,222}223342 let threads = config.threads;343 thread::spawn(move || {224impl WorkerState {225 fn new(patterns: Vec<Regex>, config: Config) -> Self {226 let quit_flag = Arc::new(AtomicBool::new(false));227 let interrupt_flag = Arc::new(AtomicBool::new(false));228229 Self {230 patterns,231 config,232 quit_flag,233 interrupt_flag,234 }235 }236237 fn build_overrides(&self, paths: &[PathBuf]) -> Result<Override> {238 let first_path = &paths[0];239 let config = &self.config;240241 let mut builder = OverrideBuilder::new(first_path);242243 for pattern in &config.exclude_patterns {244 builder245 .add(pattern)246 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;247 }248249 if config.read_vcsignore {250 builder.add("!.git/").expect("Invalid exclude pattern");251 }252253 builder254 .build()255 .map_err(|_| anyhow!("Mismatch in exclude patterns"))256 }257258 fn build_walker(&self, paths: &[PathBuf]) -> Result<WalkParallel> {259 let first_path = &paths[0];260 let config = &self.config;261 let overrides = self.build_overrides(paths)?;262263 let mut builder = WalkBuilder::new(first_path);264 builder265 .hidden(config.ignore_hidden)266 .ignore(config.read_fdignore)267 .parents(config.read_parent_ignore && (config.read_fdignore || config.read_vcsignore))268 .git_ignore(config.read_vcsignore)269 .git_global(config.read_vcsignore)270 .git_exclude(config.read_vcsignore)271 .require_git(config.require_git_to_read_vcsignore)272 .overrides(overrides)273 .follow_links(config.follow_links)274 // No need to check for supported platforms, option is unavailable on unsupported ones275 .same_file_system(config.one_file_system)276 .max_depth(config.max_depth);277278 if config.read_fdignore {279 builder.add_custom_ignore_filename(".fdignore");280 }281282 if config.read_global_ignore {283 if let Ok(basedirs) = etcetera::choose_base_strategy() {284 let global_ignore_file = basedirs.config_dir().join("fd").join("ignore");285 if global_ignore_file.is_file() {286 let result = builder.add_ignore(global_ignore_file);287 match result {288 Some(ignore::Error::Partial(_)) => (),289 Some(err) => {290 print_error(format!(291 "Malformed pattern in global ignore file. {}.",292 err293 ));294 }295 None => (),296 }297 }298 }299 }300301 for ignore_file in &config.ignore_files {302 let result = builder.add_ignore(ignore_file);303 match result {304 Some(ignore::Error::Partial(_)) => (),305 Some(err) => {306 print_error(format!("Malformed pattern in custom ignore file. {}.", err));307 }308 None => (),309 }310 }311312 for path in &paths[1..] {313 builder.add(path);314 }315316 let walker = builder.threads(config.threads).build_parallel();317 Ok(walker)318 }319320 /// Run the receiver work, either on this thread or a pool of background321 /// threads (for --exec).322 fn receive(&self, rx: Receiver<WorkerResult>) -> ExitCode {323 let config = &self.config;324325 // This will be set to `Some` if the `--exec` argument was supplied.326 if let Some(ref cmd) = config.command {327 if cmd.in_batch_mode() {328 exec::batch(rx, cmd, &config)329 } else {330 let out_perm = Mutex::new(());331332 thread::scope(|scope| {352 // Each spawned job will store it's thread handle in here.333 // Each spawned job will store its thread handle in here.334 let threads = config.threads;335 let mut handles = Vec::with_capacity(threads);336 for _ in 0..threads {337 let rx = rx.clone();338
7 unmodified lines
346 merge_exitcodes(exit_codes)347 })348 }349 } else {368 let stdout = io::stdout();369 let stdout = stdout.lock();350 let stdout = io::stdout().lock();351 let stdout = io::BufWriter::new(stdout);352372 let mut rxbuffer = ReceiverBuffer::new(config, quit_flag, interrupt_flag, rx, stdout);373 rxbuffer.process()353 ReceiverBuffer::new(self, rx, stdout).process()354 }375 })376}355 }356378fn spawn_senders(379 config: &Arc<Config>,380 quit_flag: &Arc<AtomicBool>,381 patterns: Arc<Vec<Regex>>,382 parallel_walker: ignore::WalkParallel,383 tx: Sender<WorkerResult>,384) {385 parallel_walker.run(|| {386 let config = Arc::clone(config);387 let patterns = Arc::clone(&patterns);388 let tx_thread = tx.clone();389 let quit_flag = Arc::clone(quit_flag);357 /// Spawn the sender threads.358 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<WorkerResult>) {359 walker.run(|| {360 let patterns = &self.patterns;361 let config = &self.config;362 let quit_flag = self.quit_flag.as_ref();363 let tx = tx.clone();364391 Box::new(move |entry_o| {392 if quit_flag.load(Ordering::Relaxed) {393 return ignore::WalkState::Quit;394 }395396 let entry = match entry_o {397 Ok(ref e) if e.depth() == 0 => {398 // Skip the root directory entry.399 return ignore::WalkState::Continue;365 Box::new(move |entry| {366 if quit_flag.load(Ordering::Relaxed) {367 return WalkState::Quit;368 }401 Ok(e) => DirEntry::normal(e),402 Err(ignore::Error::WithPath {403 path,404 err: inner_err,405 }) => match inner_err.as_ref() {406 ignore::Error::Io(io_error)407 if io_error.kind() == io::ErrorKind::NotFound408 && path409 .symlink_metadata()410 .ok()411 .map_or(false, |m| m.file_type().is_symlink()) =>412 {413 DirEntry::broken_symlink(path)369370 let entry = match entry {371 Ok(ref e) if e.depth() == 0 => {372 // Skip the root directory entry.373 return WalkState::Continue;374 }415 _ => {416 return match tx_thread.send(WorkerResult::Error(ignore::Error::WithPath {417 path,418 err: inner_err,419 })) {420 Ok(_) => ignore::WalkState::Continue,421 Err(_) => ignore::WalkState::Quit,375 Ok(e) => DirEntry::normal(e),376 Err(ignore::Error::WithPath {377 path,378 err: inner_err,379 }) => match inner_err.as_ref() {380 ignore::Error::Io(io_error)381 if io_error.kind() == io::ErrorKind::NotFound382 && path383 .symlink_metadata()384 .ok()385 .map_or(false, |m| m.file_type().is_symlink()) =>386 {387 DirEntry::broken_symlink(path)388 }389 _ => {390 return match tx.send(WorkerResult::Error(ignore::Error::WithPath {391 path,392 err: inner_err,393 })) {394 Ok(_) => WalkState::Continue,395 Err(_) => WalkState::Quit,396 }397 }398 },399 Err(err) => {400 return match tx.send(WorkerResult::Error(err)) {401 Ok(_) => WalkState::Continue,402 Err(_) => WalkState::Quit,403 }404 }424 },425 Err(err) => {426 return match tx_thread.send(WorkerResult::Error(err)) {427 Ok(_) => ignore::WalkState::Continue,428 Err(_) => ignore::WalkState::Quit,405 };406407 if let Some(min_depth) = config.min_depth {408 if entry.depth().map_or(true, |d| d < min_depth) {409 return WalkState::Continue;410 }411 }431 };412433 if let Some(min_depth) = config.min_depth {434 if entry.depth().map_or(true, |d| d < min_depth) {435 return ignore::WalkState::Continue;436 }437 }413 // Check the name first, since it doesn't require metadata414 let entry_path = entry.path();415439 // Check the name first, since it doesn't require metadata440 let entry_path = entry.path();416 let search_str: Cow<OsStr> = if config.search_full_path {417 let path_abs_buf = filesystem::path_absolute_form(entry_path)418 .expect("Retrieving absolute path succeeds");419 Cow::Owned(path_abs_buf.as_os_str().to_os_string())420 } else {421 match entry_path.file_name() {422 Some(filename) => Cow::Borrowed(filename),423 None => unreachable!(424 "Encountered file system entry without a file name. This should only \425 happen for paths like 'foo/bar/..' or '/' which are not supposed to \426 appear in a file system traversal."427 ),428 }429 };430442 let search_str: Cow<OsStr> = if config.search_full_path {443 let path_abs_buf = filesystem::path_absolute_form(entry_path)444 .expect("Retrieving absolute path succeeds");445 Cow::Owned(path_abs_buf.as_os_str().to_os_string())446 } else {447 match entry_path.file_name() {448 Some(filename) => Cow::Borrowed(filename),449 None => unreachable!(450 "Encountered file system entry without a file name. This should only \451 happen for paths like 'foo/bar/..' or '/' which are not supposed to \452 appear in a file system traversal."453 ),431 if !patterns432 .iter()433 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))434 {435 return WalkState::Continue;436 }455 };437457 if !patterns458 .iter()459 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))460 {461 return ignore::WalkState::Continue;462 }438 // Filter out unwanted extensions.439 if let Some(ref exts_regex) = config.extensions {440 if let Some(path_str) = entry_path.file_name() {441 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {442 return WalkState::Continue;443 }444 } else {445 return WalkState::Continue;446 }447 }448464 // Filter out unwanted extensions.465 if let Some(ref exts_regex) = config.extensions {466 if let Some(path_str) = entry_path.file_name() {467 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {468 return ignore::WalkState::Continue;449 // Filter out unwanted file types.450 if let Some(ref file_types) = config.file_types {451 if file_types.should_ignore(&entry) {452 return WalkState::Continue;453 }470 } else {471 return ignore::WalkState::Continue;454 }473 }455475 // Filter out unwanted file types.476 if let Some(ref file_types) = config.file_types {477 if file_types.should_ignore(&entry) {478 return ignore::WalkState::Continue;456 #[cfg(unix)]457 {458 if let Some(ref owner_constraint) = config.owner_constraint {459 if let Some(metadata) = entry.metadata() {460 if !owner_constraint.matches(metadata) {461 return WalkState::Continue;462 }463 } else {464 return WalkState::Continue;465 }466 }467 }480 }468482 #[cfg(unix)]483 {484 if let Some(ref owner_constraint) = config.owner_constraint {485 if let Some(metadata) = entry.metadata() {486 if !owner_constraint.matches(metadata) {487 return ignore::WalkState::Continue;469 // Filter out unwanted sizes if it is a file and we have been given size constraints.470 if !config.size_constraints.is_empty() {471 if entry_path.is_file() {472 if let Some(metadata) = entry.metadata() {473 let file_size = metadata.len();474 if config475 .size_constraints476 .iter()477 .any(|sc| !sc.is_within(file_size))478 {479 return WalkState::Continue;480 }481 } else {482 return WalkState::Continue;483 }484 } else {490 return ignore::WalkState::Continue;485 return WalkState::Continue;486 }487 }493 }488495 // Filter out unwanted sizes if it is a file and we have been given size constraints.496 if !config.size_constraints.is_empty() {497 if entry_path.is_file() {489 // Filter out unwanted modification times490 if !config.time_constraints.is_empty() {491 let mut matched = false;492 if let Some(metadata) = entry.metadata() {499 let file_size = metadata.len();500 if config501 .size_constraints502 .iter()503 .any(|sc| !sc.is_within(file_size))504 {505 return ignore::WalkState::Continue;493 if let Ok(modified) = metadata.modified() {494 matched = config495 .time_constraints496 .iter()497 .all(|tf| tf.applies_to(&modified));498 }507 } else {508 return ignore::WalkState::Continue;499 }510 } else {511 return ignore::WalkState::Continue;500 if !matched {501 return WalkState::Continue;502 }503 }513 }504515 // Filter out unwanted modification times516 if !config.time_constraints.is_empty() {517 let mut matched = false;518 if let Some(metadata) = entry.metadata() {519 if let Ok(modified) = metadata.modified() {520 matched = config521 .time_constraints522 .iter()523 .all(|tf| tf.applies_to(&modified));505 if config.is_printing() {506 if let Some(ls_colors) = &config.ls_colors {507 // Compute colors in parallel508 entry.style(ls_colors);509 }510 }526 if !matched {527 return ignore::WalkState::Continue;511512 let send_result = tx.send(WorkerResult::Entry(entry));513514 if send_result.is_err() {515 return WalkState::Quit;516 }529 }517531 if config.is_printing() {532 if let Some(ls_colors) = &config.ls_colors {533 // Compute colors in parallel534 entry.style(ls_colors);518 // Apply pruning.519 if config.prune {520 return WalkState::Skip;521 }536 }522538 let send_result = tx_thread.send(WorkerResult::Entry(entry));523 WalkState::Continue524 })525 });526 }527540 if send_result.is_err() {541 return ignore::WalkState::Quit;542 }528 /// Perform the recursive scan.529 fn scan(&self, paths: &[PathBuf]) -> Result<ExitCode> {530 let config = &self.config;531 let walker = self.build_walker(paths)?;532544 // Apply pruning.545 if config.prune {546 return ignore::WalkState::Skip;547 }533 if config.ls_colors.is_some() && config.is_printing() {534 let quit_flag = Arc::clone(&self.quit_flag);535 let interrupt_flag = Arc::clone(&self.interrupt_flag);536549 ignore::WalkState::Continue550 })551 });537 ctrlc::set_handler(move || {538 quit_flag.store(true, Ordering::Relaxed);539540 if interrupt_flag.fetch_or(true, Ordering::Relaxed) {541 // Ctrl-C has been pressed twice, exit NOW542 ExitCode::KilledBySigint.exit();543 }544 })545 .unwrap();546 }547548 // Channel capacity was chosen empircally to perform similarly to an unbounded channel549 let (tx, rx) = bounded(0x4000 * config.threads);550551 let exit_code = thread::scope(|scope| {552 // Spawn the receiver thread(s)553 let receiver = scope.spawn(|| self.receive(rx));554555 // Spawn the sender threads.556 self.spawn_senders(walker, tx);557558 receiver.join().unwrap()559 });560561 if self.interrupt_flag.load(Ordering::Relaxed) {562 Ok(ExitCode::KilledBySigint)563 } else {564 Ok(exit_code)565 }566 }567}568569/// Recursively scan the given search path for files / pathnames matching the patterns.570///571/// If the `--exec` argument was supplied, this will create a thread pool for executing572/// jobs in parallel from a given command line and the discovered paths. Otherwise, each573/// path will simply be written to standard output.574pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {575 WorkerState::new(patterns, config).scan(paths)576}