walk.rs
This file
Path
src/walk.rs
459 lines · 16.5 KiB · Rust
Last changed by
Add new `--type socket` and `--type pipe` filterssharkdpbefore adoptioncb56add
History of this fileTake it
1use std::borrow::Cow;2use std::ffi::OsStr;3use std::fs::{FileType, Metadata};4use std::io;5use std::path::{Path, PathBuf};6use std::process;7use std::sync::atomic::{AtomicBool, Ordering};8use std::sync::mpsc::{channel, Receiver, Sender};9use std::sync::{Arc, Mutex};10use std::thread;11use std::time;1213use anyhow::{anyhow, Result};14use ignore::overrides::OverrideBuilder;15use ignore::{self, WalkBuilder};16use regex::bytes::Regex;1718use crate::error::print_error;19use crate::exec;20use crate::exit_codes::{merge_exitcodes, ExitCode};21use crate::filesystem;22use crate::options::Options;23use crate::output;2425/// The receiver thread can either be buffering results or directly streaming to the console.26enum ReceiverMode {27 /// Receiver is still buffering in order to sort the results, if the search finishes fast28 /// enough.29 Buffering,3031 /// Receiver is directly printing results to the output.32 Streaming,33}3435/// The Worker threads can result in a valid entry having PathBuf or an error.36pub enum WorkerResult {37 Entry(PathBuf),38 Error(ignore::Error),39}4041/// Maximum size of the output buffer before flushing results to the console42pub const MAX_BUFFER_LENGTH: usize = 1000;4344/// Recursively scan the given search path for files / pathnames matching the pattern.45///46/// If the `--exec` argument was supplied, this will create a thread pool for executing47/// jobs in parallel from a given command line and the discovered paths. Otherwise, each48/// path will simply be written to standard output.49pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> Result<ExitCode> {50 let mut path_iter = path_vec.iter();51 let first_path_buf = path_iter52 .next()53 .expect("Error: Path vector can not be empty");54 let (tx, rx) = channel();5556 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());5758 for pattern in &config.exclude_patterns {59 override_builder60 .add(pattern)61 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;62 }63 let overrides = override_builder64 .build()65 .map_err(|_| anyhow!("Mismatch in exclude patterns"))?;6667 let mut walker = WalkBuilder::new(first_path_buf.as_path());68 walker69 .hidden(config.ignore_hidden)70 .ignore(config.read_fdignore)71 .parents(config.read_fdignore || config.read_vcsignore)72 .git_ignore(config.read_vcsignore)73 .git_global(config.read_vcsignore)74 .git_exclude(config.read_vcsignore)75 .overrides(overrides)76 .follow_links(config.follow_links)77 // No need to check for supported platforms, option is unavailable on unsupported ones78 .same_file_system(config.one_file_system)79 .max_depth(config.max_depth);8081 if config.read_fdignore {82 walker.add_custom_ignore_filename(".fdignore");83 }8485 for ignore_file in &config.ignore_files {86 let result = walker.add_ignore(ignore_file);87 match result {88 Some(ignore::Error::Partial(_)) => (),89 Some(err) => {90 print_error(format!(91 "Malformed pattern in custom ignore file. {}.",92 err.to_string()93 ));94 }95 None => (),96 }97 }9899 for path_entry in path_iter {100 walker.add(path_entry.as_path());101 }102103 let parallel_walker = walker.threads(config.threads).build_parallel();104105 let wants_to_quit = Arc::new(AtomicBool::new(false));106 if config.ls_colors.is_some() && config.command.is_none() {107 let wq = Arc::clone(&wants_to_quit);108 ctrlc::set_handler(move || {109 if wq.load(Ordering::Relaxed) {110 // Ctrl-C has been pressed twice, exit NOW111 process::exit(ExitCode::KilledBySigint.into());112 } else {113 wq.store(true, Ordering::Relaxed);114 }115 })116 .unwrap();117 }118119 // Spawn the thread that receives all results through the channel.120 let receiver_thread = spawn_receiver(&config, &wants_to_quit, rx);121122 // Spawn the sender threads.123 spawn_senders(&config, &wants_to_quit, pattern, parallel_walker, tx);124125 // Wait for the receiver thread to print out all results.126 let exit_code = receiver_thread.join().unwrap();127128 if wants_to_quit.load(Ordering::Relaxed) {129 Ok(ExitCode::KilledBySigint)130 } else {131 Ok(exit_code)132 }133}134135fn spawn_receiver(136 config: &Arc<Options>,137 wants_to_quit: &Arc<AtomicBool>,138 rx: Receiver<WorkerResult>,139) -> thread::JoinHandle<ExitCode> {140 let config = Arc::clone(config);141 let wants_to_quit = Arc::clone(wants_to_quit);142143 let show_filesystem_errors = config.show_filesystem_errors;144 let threads = config.threads;145146 thread::spawn(move || {147 // This will be set to `Some` if the `--exec` argument was supplied.148 if let Some(ref cmd) = config.command {149 if cmd.in_batch_mode() {150 exec::batch(rx, cmd, show_filesystem_errors)151 } else {152 let shared_rx = Arc::new(Mutex::new(rx));153154 let out_perm = Arc::new(Mutex::new(()));155156 // Each spawned job will store it's thread handle in here.157 let mut handles = Vec::with_capacity(threads);158 for _ in 0..threads {159 let rx = Arc::clone(&shared_rx);160 let cmd = Arc::clone(cmd);161 let out_perm = Arc::clone(&out_perm);162163 // Spawn a job thread that will listen for and execute inputs.164 let handle =165 thread::spawn(move || exec::job(rx, cmd, out_perm, show_filesystem_errors));166167 // Push the handle of the spawned thread into the vector for later joining.168 handles.push(handle);169 }170171 // Wait for all threads to exit before exiting the program.172 let mut results: Vec<ExitCode> = Vec::new();173 for h in handles {174 results.push(h.join().unwrap());175 }176177 merge_exitcodes(&results)178 }179 } else {180 let start = time::Instant::now();181182 let mut buffer = vec![];183184 // Start in buffering mode185 let mut mode = ReceiverMode::Buffering;186187 // Maximum time to wait before we start streaming to the console.188 let max_buffer_time = config189 .max_buffer_time190 .unwrap_or_else(|| time::Duration::from_millis(100));191192 let stdout = io::stdout();193 let mut stdout = stdout.lock();194195 let mut num_results = 0;196197 for worker_result in rx {198 match worker_result {199 WorkerResult::Entry(value) => {200 match mode {201 ReceiverMode::Buffering => {202 buffer.push(value);203204 // Have we reached the maximum buffer size or maximum buffering time?205 if buffer.len() > MAX_BUFFER_LENGTH206 || time::Instant::now() - start > max_buffer_time207 {208 // Flush the buffer209 for v in &buffer {210 output::print_entry(211 &mut stdout,212 v,213 &config,214 &wants_to_quit,215 );216 }217 buffer.clear();218219 // Start streaming220 mode = ReceiverMode::Streaming;221 }222 }223 ReceiverMode::Streaming => {224 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);225 }226 }227228 num_results += 1;229 }230 WorkerResult::Error(err) => {231 if show_filesystem_errors {232 print_error(err.to_string());233 }234 }235 }236237 if let Some(max_results) = config.max_results {238 if num_results >= max_results {239 break;240 }241 }242 }243244 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed245 // anything to the console, yet. In this case, sort the results and print them:246 if !buffer.is_empty() {247 buffer.sort();248 for value in buffer {249 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);250 }251 }252253 ExitCode::Success254 }255 })256}257258pub enum DirEntry {259 Normal(ignore::DirEntry),260 BrokenSymlink(PathBuf),261}262263impl DirEntry {264 pub fn path(&self) -> &Path {265 match self {266 DirEntry::Normal(e) => e.path(),267 DirEntry::BrokenSymlink(pathbuf) => pathbuf.as_path(),268 }269 }270271 pub fn file_type(&self) -> Option<FileType> {272 match self {273 DirEntry::Normal(e) => e.file_type(),274 DirEntry::BrokenSymlink(pathbuf) => {275 pathbuf.symlink_metadata().map(|m| m.file_type()).ok()276 }277 }278 }279280 pub fn metadata(&self) -> Option<Metadata> {281 match self {282 DirEntry::Normal(e) => e.metadata().ok(),283 DirEntry::BrokenSymlink(_) => None,284 }285 }286287 pub fn depth(&self) -> Option<usize> {288 match self {289 DirEntry::Normal(e) => Some(e.depth()),290 DirEntry::BrokenSymlink(_) => None,291 }292 }293}294295fn spawn_senders(296 config: &Arc<Options>,297 wants_to_quit: &Arc<AtomicBool>,298 pattern: Arc<Regex>,299 parallel_walker: ignore::WalkParallel,300 tx: Sender<WorkerResult>,301) {302 parallel_walker.run(|| {303 let config = Arc::clone(config);304 let pattern = Arc::clone(&pattern);305 let tx_thread = tx.clone();306 let wants_to_quit = Arc::clone(wants_to_quit);307308 Box::new(move |entry_o| {309 if wants_to_quit.load(Ordering::Relaxed) {310 return ignore::WalkState::Quit;311 }312313 let entry = match entry_o {314 Ok(ref e) if e.depth() == 0 => {315 // Skip the root directory entry.316 return ignore::WalkState::Continue;317 }318 Ok(e) => DirEntry::Normal(e),319 Err(ignore::Error::WithPath {320 path,321 err: inner_err,322 }) => match inner_err.as_ref() {323 ignore::Error::Io(io_error)324 if io_error.kind() == io::ErrorKind::NotFound325 && path326 .symlink_metadata()327 .ok()328 .map_or(false, |m| m.file_type().is_symlink()) =>329 {330 DirEntry::BrokenSymlink(path)331 }332 _ => {333 tx_thread334 .send(WorkerResult::Error(ignore::Error::WithPath {335 path,336 err: inner_err,337 }))338 .unwrap();339 return ignore::WalkState::Continue;340 }341 },342 Err(err) => {343 tx_thread.send(WorkerResult::Error(err)).unwrap();344 return ignore::WalkState::Continue;345 }346 };347348 if let Some(min_depth) = config.min_depth {349 if entry.depth().map_or(true, |d| d < min_depth) {350 return ignore::WalkState::Continue;351 }352 }353354 // Check the name first, since it doesn't require metadata355 let entry_path = entry.path();356357 let search_str: Cow<OsStr> = if config.search_full_path {358 let path_abs_buf = filesystem::path_absolute_form(entry_path)359 .expect("Retrieving absolute path succeeds");360 Cow::Owned(path_abs_buf.as_os_str().to_os_string())361 } else {362 match entry_path.file_name() {363 Some(filename) => Cow::Borrowed(filename),364 None => unreachable!(365 "Encountered file system entry without a file name. This should only \366 happen for paths like 'foo/bar/..' or '/' which are not supposed to \367 appear in a file system traversal."368 ),369 }370 };371372 if !pattern.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())) {373 return ignore::WalkState::Continue;374 }375376 // Filter out unwanted extensions.377 if let Some(ref exts_regex) = config.extensions {378 if let Some(path_str) = entry_path.file_name() {379 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {380 return ignore::WalkState::Continue;381 }382 } else {383 return ignore::WalkState::Continue;384 }385 }386387 // Filter out unwanted file types.388 if let Some(ref file_types) = config.file_types {389 if let Some(ref entry_type) = entry.file_type() {390 if (!file_types.files && entry_type.is_file())391 || (!file_types.directories && entry_type.is_dir())392 || (!file_types.symlinks && entry_type.is_symlink())393 || (!file_types.sockets && filesystem::is_socket(entry_type))394 || (!file_types.pipes && filesystem::is_pipe(entry_type))395 || (file_types.executables_only396 && !entry397 .metadata()398 .map(|m| filesystem::is_executable(&m))399 .unwrap_or(false))400 || (file_types.empty_only && !filesystem::is_empty(&entry))401 || !(entry_type.is_file()402 || entry_type.is_dir()403 || entry_type.is_symlink()404 || filesystem::is_socket(entry_type)405 || filesystem::is_pipe(entry_type))406 {407 return ignore::WalkState::Continue;408 }409 } else {410 return ignore::WalkState::Continue;411 }412 }413414 // Filter out unwanted sizes if it is a file and we have been given size constraints.415 if !config.size_constraints.is_empty() {416 if entry_path.is_file() {417 if let Ok(metadata) = entry_path.metadata() {418 let file_size = metadata.len();419 if config420 .size_constraints421 .iter()422 .any(|sc| !sc.is_within(file_size))423 {424 return ignore::WalkState::Continue;425 }426 } else {427 return ignore::WalkState::Continue;428 }429 } else {430 return ignore::WalkState::Continue;431 }432 }433434 // Filter out unwanted modification times435 if !config.time_constraints.is_empty() {436 let mut matched = false;437 if let Ok(metadata) = entry_path.metadata() {438 if let Ok(modified) = metadata.modified() {439 matched = config440 .time_constraints441 .iter()442 .all(|tf| tf.applies_to(&modified));443 }444 }445 if !matched {446 return ignore::WalkState::Continue;447 }448 }449450 let send_result = tx_thread.send(WorkerResult::Entry(entry_path.to_owned()));451452 if send_result.is_err() {453 return ignore::WalkState::Quit;454 }455456 ignore::WalkState::Continue457 })458 });459}