walk.rs
This file
Path
src/walk.rs
500 lines · 17.9 KiB · Rust
Last changed by
Fix warningsharkdpbefore adoption3283a7b
History of this fileTake it
The walk stopped after 200 commits: lines older than acd4910 point at it.
Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
lines 1–2why, one step back1use std::borrow::Cow;2use std::ffi::OsStr;New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
line 3why, one step back3use std::fs::{FileType, Metadata};Update dependenciessharkdpbefore adoptionacd4910
line 4why, one step back4use std::io;New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
line 5why, one step back5use std::path::{Path, PathBuf};Update dependenciessharkdpbefore adoptionacd4910
lines 6–12why, one step back6use 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;12Proper error handling within walk.rssharkdpbefore adoption4590ae8
line 13why, one step back13use anyhow::{anyhow, Result};Update dependenciessharkdpbefore adoptionacd4910
lines 14–15why, one step back14use ignore::overrides::OverrideBuilder;15use ignore::{self, WalkBuilder};Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
line 16why, one step back16use regex::bytes::Regex;Update dependenciessharkdpbefore adoptionacd4910
line 17why, one step back17Proper error handling within walk.rssharkdpbefore adoption4590ae8
lines 18–24why, one step back18use crate::error::print_error;19use crate::exec;20use crate::exit_codes::{merge_exitcodes, ExitCode};21use crate::filesystem;22use crate::options::Options;23use crate::output;24Update dependenciessharkdpbefore adoptionacd4910
lines 25–39why, one step back25/// 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}Move MAX_BUFFER_LENGTHsharkdpbefore adoptionc79d163
lines 40–42why, one step back4041/// Maximum size of the output buffer before flushing results to the console42pub const MAX_BUFFER_LENGTH: usize = 1000;Update dependenciessharkdpbefore adoptionacd4910
lines 43–48why, one step back4344/// 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.Proper error handling within walk.rssharkdpbefore adoption4590ae8
line 49why, one step back49pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> Result<ExitCode> {Update dependenciessharkdpbefore adoptionacd4910
lines 50–58why, one step back50 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 {Proper error handling within walk.rssharkdpbefore adoption4590ae8
lines 59–61why, one step back59 override_builder60 .add(pattern)61 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;Update dependenciessharkdpbefore adoptionacd4910
line 62why, one step back62 }Proper error handling within walk.rssharkdpbefore adoption4590ae8
lines 63–65why, one step back63 let overrides = override_builder64 .build()65 .map_err(|_| anyhow!("Mismatch in exclude patterns"))?;Update dependenciessharkdpbefore adoptionacd4910
lines 66–76why, one step back6667 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)Restrict `--one-file-system` to supported systemsSimon Engmannbefore adoptiondea1fbe
lines 77–78why, one step back77 // No need to check for supported platforms, option is unavailable on unsupported ones78 .same_file_system(config.one_file_system)Update dependenciessharkdpbefore adoptionacd4910
lines 79–82why, one step back79 .max_depth(config.max_depth);8081 if config.read_fdignore {82 walker.add_custom_ignore_filename(".fdignore");Add global fdignore supportBobbie Soedirgobefore adoption79d5a5b
lines 83–86why, one step back83 }8485 if config.read_global_ignore {86 #[cfg(target_os = "macos")]Fix warningsharkdpbefore adoption3283a7b
line 87why, one step back87 let config_dir_op = std::env::var_os("XDG_CONFIG_HOME")Add global fdignore supportBobbie Soedirgobefore adoption79d5a5b
lines 88–110why, one step back88 .map(PathBuf::from)89 .filter(|p| p.is_absolute())90 .or_else(|| dirs::home_dir().map(|d| d.join(".config")));9192 #[cfg(not(target_os = "macos"))]93 let config_dir_op = dirs::config_dir();9495 if let Some(global_ignore_file) = config_dir_op96 .map(|p| p.join("fd").join("ignore"))97 .filter(|p| p.is_file())98 {99 let result = walker.add_ignore(global_ignore_file);100 match result {101 Some(ignore::Error::Partial(_)) => (),102 Some(err) => {103 print_error(format!(104 "Malformed pattern in global ignore file. {}.",105 err.to_string()106 ));107 }108 None => (),109 }110 }Update dependenciessharkdpbefore adoptionacd4910
lines 111–117why, one step back111 }112113 for ignore_file in &config.ignore_files {114 let result = walker.add_ignore(ignore_file);115 match result {116 Some(ignore::Error::Partial(_)) => (),117 Some(err) => {Proper error handling within walk.rssharkdpbefore adoption4590ae8
lines 118–121why, one step back118 print_error(format!(119 "Malformed pattern in custom ignore file. {}.",120 err.to_string()121 ));Update dependenciessharkdpbefore adoptionacd4910
lines 122–136why, one step back122 }123 None => (),124 }125 }126127 for path_entry in path_iter {128 walker.add(path_entry.as_path());129 }130131 let parallel_walker = walker.threads(config.threads).build_parallel();132133 let wants_to_quit = Arc::new(AtomicBool::new(false));134 if config.ls_colors.is_some() && config.command.is_none() {135 let wq = Arc::clone(&wants_to_quit);136 ctrlc::set_handler(move || {Exit immediately when Ctrl-C has been pressed twicesharkdpbefore adoption2545aaa
lines 137–142why, one step back137 if wq.load(Ordering::Relaxed) {138 // Ctrl-C has been pressed twice, exit NOW139 process::exit(ExitCode::KilledBySigint.into());140 } else {141 wq.store(true, Ordering::Relaxed);142 }Update dependenciessharkdpbefore adoptionacd4910
lines 143–153why, one step back143 })144 .unwrap();145 }146147 // Spawn the thread that receives all results through the channel.148 let receiver_thread = spawn_receiver(&config, &wants_to_quit, rx);149150 // Spawn the sender threads.151 spawn_senders(&config, &wants_to_quit, pattern, parallel_walker, tx);152153 // Wait for the receiver thread to print out all results.Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 154why, one step back154 let exit_code = receiver_thread.join().unwrap();Update dependenciessharkdpbefore adoptionacd4910
lines 155–156why, one step back155156 if wants_to_quit.load(Ordering::Relaxed) {Remove process::exit instancesharkdpbefore adoption4815ee4
lines 157–159why, one step back157 Ok(ExitCode::KilledBySigint)158 } else {159 Ok(exit_code)Update dependenciessharkdpbefore adoptionacd4910
lines 160–163why, one step back160 }161}162163fn spawn_receiver(Move FdOptions to Optionssharkdpbefore adoption65096a6
line 164why, one step back164 config: &Arc<Options>,Update dependenciessharkdpbefore adoptionacd4910
lines 165–166why, one step back165 wants_to_quit: &Arc<AtomicBool>,166 rx: Receiver<WorkerResult>,Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 167why, one step back167) -> thread::JoinHandle<ExitCode> {Update dependenciessharkdpbefore adoptionacd4910
lines 168–177why, one step back168 let config = Arc::clone(config);169 let wants_to_quit = Arc::clone(wants_to_quit);170171 let show_filesystem_errors = config.show_filesystem_errors;172 let threads = config.threads;173174 thread::spawn(move || {175 // This will be set to `Some` if the `--exec` argument was supplied.176 if let Some(ref cmd) = config.command {177 if cmd.in_batch_mode() {Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 178why, one step back178 exec::batch(rx, cmd, show_filesystem_errors)Update dependenciessharkdpbefore adoptionacd4910
lines 179–199why, one step back179 } else {180 let shared_rx = Arc::new(Mutex::new(rx));181182 let out_perm = Arc::new(Mutex::new(()));183184 // Each spawned job will store it's thread handle in here.185 let mut handles = Vec::with_capacity(threads);186 for _ in 0..threads {187 let rx = Arc::clone(&shared_rx);188 let cmd = Arc::clone(cmd);189 let out_perm = Arc::clone(&out_perm);190191 // Spawn a job thread that will listen for and execute inputs.192 let handle =193 thread::spawn(move || exec::job(rx, cmd, out_perm, show_filesystem_errors));194195 // Push the handle of the spawned thread into the vector for later joining.196 handles.push(handle);197 }198199 // Wait for all threads to exit before exiting the program.Add collection of job & thread exit codes + default to ExitCode::Error if any ExitCode::Errorfusillicodebefore adoption7213f5a
line 200why, one step back200 let mut results: Vec<ExitCode> = Vec::new();Update dependenciessharkdpbefore adoptionacd4910
line 201why, one step back201 for h in handles {Add collection of job & thread exit codes + default to ExitCode::Error if any ExitCode::Errorfusillicodebefore adoption7213f5a
line 202why, one step back202 results.push(h.join().unwrap());Update dependenciessharkdpbefore adoptionacd4910
line 203why, one step back203 }Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 204why, one step back204Clean up exit code handlingsharkdpbefore adoptione42ddda
line 205why, one step back205 merge_exitcodes(&results)Update dependenciessharkdpbefore adoptionacd4910
lines 206–222why, one step back206 }207 } else {208 let start = time::Instant::now();209210 let mut buffer = vec![];211212 // Start in buffering mode213 let mut mode = ReceiverMode::Buffering;214215 // Maximum time to wait before we start streaming to the console.216 let max_buffer_time = config217 .max_buffer_time218 .unwrap_or_else(|| time::Duration::from_millis(100));219220 let stdout = io::stdout();221 let mut stdout = stdout.lock();222Add --max-results=<count> optionsharkdpbefore adoptiond43827f
lines 223–224why, one step back223 let mut num_results = 0;224Update dependenciessharkdpbefore adoptionacd4910
line 225why, one step back225 for worker_result in rx {Revert back to master statesharkdpbefore adoptionbfc8c42
lines 226–227why, one step back226 match worker_result {227 WorkerResult::Entry(value) => {Update dependenciessharkdpbefore adoptionacd4910
lines 228–254why, one step back228 match mode {229 ReceiverMode::Buffering => {230 buffer.push(value);231232 // Have we reached the maximum buffer size or maximum buffering time?233 if buffer.len() > MAX_BUFFER_LENGTH234 || time::Instant::now() - start > max_buffer_time235 {236 // Flush the buffer237 for v in &buffer {238 output::print_entry(239 &mut stdout,240 v,241 &config,242 &wants_to_quit,243 );244 }245 buffer.clear();246247 // Start streaming248 mode = ReceiverMode::Streaming;249 }250 }251 ReceiverMode::Streaming => {252 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);253 }254 }Add --max-results=<count> optionsharkdpbefore adoptiond43827f
lines 255–256why, one step back255256 num_results += 1;Update dependenciessharkdpbefore adoptionacd4910
line 257why, one step back257 }Revert back to master statesharkdpbefore adoptionbfc8c42
line 258why, one step back258 WorkerResult::Error(err) => {Update dependenciessharkdpbefore adoptionacd4910
line 259why, one step back259 if show_filesystem_errors {Proper error handling within walk.rssharkdpbefore adoption4590ae8
line 260why, one step back260 print_error(err.to_string());Update dependenciessharkdpbefore adoptionacd4910
line 261why, one step back261 }Add --max-results=<count> optionsharkdpbefore adoptiond43827f
lines 262–267why, one step back262 }263 }264265 if let Some(max_results) = config.max_results {266 if num_results >= max_results {267 break;Update dependenciessharkdpbefore adoptionacd4910
lines 268–279why, one step back268 }269 }270 }271272 // If we have finished fast enough (faster than max_buffer_time), we haven't streamed273 // anything to the console, yet. In this case, sort the results and print them:274 if !buffer.is_empty() {275 buffer.sort();276 for value in buffer {277 output::print_entry(&mut stdout, &value, &config, &wants_to_quit);278 }279 }Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
lines 280–281why, one step back280281 ExitCode::SuccessUpdate dependenciessharkdpbefore adoptionacd4910
lines 282–285why, one step back282 }283 })284}285New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
lines 286–313why, one step back286pub enum DirEntry {287 Normal(ignore::DirEntry),288 BrokenSymlink(PathBuf),289}290291impl DirEntry {292 pub fn path(&self) -> &Path {293 match self {294 DirEntry::Normal(e) => e.path(),295 DirEntry::BrokenSymlink(pathbuf) => pathbuf.as_path(),296 }297 }298299 pub fn file_type(&self) -> Option<FileType> {300 match self {301 DirEntry::Normal(e) => e.file_type(),302 DirEntry::BrokenSymlink(pathbuf) => {303 pathbuf.symlink_metadata().map(|m| m.file_type()).ok()304 }305 }306 }307308 pub fn metadata(&self) -> Option<Metadata> {309 match self {310 DirEntry::Normal(e) => e.metadata().ok(),311 DirEntry::BrokenSymlink(_) => None,312 }313 }Add --min-depth and --exact-depthsharkdpbefore adoptiond63c63b
lines 314–320why, one step back314315 pub fn depth(&self) -> Option<usize> {316 match self {317 DirEntry::Normal(e) => Some(e.depth()),318 DirEntry::BrokenSymlink(_) => None,319 }320 }New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
lines 321–322why, one step back321}322Update dependenciessharkdpbefore adoptionacd4910
line 323why, one step back323fn spawn_senders(Move FdOptions to Optionssharkdpbefore adoption65096a6
line 324why, one step back324 config: &Arc<Options>,Update dependenciessharkdpbefore adoptionacd4910
lines 325–341why, one step back325 wants_to_quit: &Arc<AtomicBool>,326 pattern: Arc<Regex>,327 parallel_walker: ignore::WalkParallel,328 tx: Sender<WorkerResult>,329) {330 parallel_walker.run(|| {331 let config = Arc::clone(config);332 let pattern = Arc::clone(&pattern);333 let tx_thread = tx.clone();334 let wants_to_quit = Arc::clone(wants_to_quit);335336 Box::new(move |entry_o| {337 if wants_to_quit.load(Ordering::Relaxed) {338 return ignore::WalkState::Quit;339 }340341 let entry = match entry_o {Fix for older versions of Rustsharkdpbefore adoptiond05e717
line 342why, one step back342 Ok(ref e) if e.depth() == 0 => {New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
lines 343–350why, one step back343 // Skip the root directory entry.344 return ignore::WalkState::Continue;345 }346 Ok(e) => DirEntry::Normal(e),347 Err(ignore::Error::WithPath {348 path,349 err: inner_err,350 }) => match inner_err.as_ref() {Add additional check for symlinksharkdpbefore adoption81dee25
lines 351–354why, one step back351 ignore::Error::Io(io_error)352 if io_error.kind() == io::ErrorKind::NotFound353 && path354 .symlink_metadata()Fix for older versions of Rustsharkdpbefore adoptiond05e717
line 355why, one step back355 .ok()Add additional check for symlinksharkdpbefore adoption81dee25
lines 356–357why, one step back356 .map_or(false, |m| m.file_type().is_symlink()) =>357 {Solve clippy issuessharkdpbefore adoptionb9d0e72
line 358why, one step back358 DirEntry::BrokenSymlink(path)New implementation of broken-symlink handlingsharkdpbefore adoptionbbf0f1c
lines 359–369why, one step back359 }360 _ => {361 tx_thread362 .send(WorkerResult::Error(ignore::Error::WithPath {363 path,364 err: inner_err,365 }))366 .unwrap();367 return ignore::WalkState::Continue;368 }369 },Update dependenciessharkdpbefore adoptionacd4910
lines 370–374why, one step back370 Err(err) => {371 tx_thread.send(WorkerResult::Error(err)).unwrap();372 return ignore::WalkState::Continue;373 }374 };Add --min-depth and --exact-depthsharkdpbefore adoptiond63c63b
lines 375–380why, one step back375376 if let Some(min_depth) = config.min_depth {377 if entry.depth().map_or(true, |d| d < min_depth) {378 return ignore::WalkState::Continue;379 }380 }Update dependenciessharkdpbefore adoptionacd4910
line 381why, one step back381Check the pattern before anything else, since it doesn't require metadataTavian Barnesbefore adoption5cbd840
lines 382–384why, one step back382 // Check the name first, since it doesn't require metadata383 let entry_path = entry.path();384Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
line 385why, one step back385 let search_str: Cow<OsStr> = if config.search_full_path {Proper error handling within walk.rssharkdpbefore adoption4590ae8
lines 386–388why, one step back386 let path_abs_buf = filesystem::path_absolute_form(entry_path)387 .expect("Retrieving absolute path succeeds");388 Cow::Owned(path_abs_buf.as_os_str().to_os_string())Check the pattern before anything else, since it doesn't require metadataTavian Barnesbefore adoption5cbd840
line 389why, one step back389 } else {Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
lines 390–397why, one step back390 match entry_path.file_name() {391 Some(filename) => Cow::Borrowed(filename),392 None => unreachable!(393 "Encountered file system entry without a file name. This should only \394 happen for paths like 'foo/bar/..' or '/' which are not supposed to \395 appear in a file system traversal."396 ),397 }Check the pattern before anything else, since it doesn't require metadataTavian Barnesbefore adoption5cbd840
lines 398–399why, one step back398 };399Rename fshelper to filesystemsharkdpbefore adoptionb415d72
line 400why, one step back400 if !pattern.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())) {Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
line 401why, one step back401 return ignore::WalkState::Continue;Check the pattern before anything else, since it doesn't require metadataTavian Barnesbefore adoption5cbd840
lines 402–405why, one step back402 }403404 // Filter out unwanted extensions.405 if let Some(ref exts_regex) = config.extensions {Use regex::bytes::* instead of regex::*sharkdpbefore adoption641594c
line 406why, one step back406 if let Some(path_str) = entry_path.file_name() {Rename fshelper to filesystemsharkdpbefore adoptionb415d72
line 407why, one step back407 if !exts_regex.is_match(&filesystem::osstr_to_bytes(path_str)) {Check the pattern before anything else, since it doesn't require metadataTavian Barnesbefore adoption5cbd840
lines 408–414why, one step back408 return ignore::WalkState::Continue;409 }410 } else {411 return ignore::WalkState::Continue;412 }413 }414Update dependenciessharkdpbefore adoptionacd4910
lines 415–420why, one step back415 // Filter out unwanted file types.416 if let Some(ref file_types) = config.file_types {417 if let Some(ref entry_type) = entry.file_type() {418 if (!file_types.files && entry_type.is_file())419 || (!file_types.directories && entry_type.is_dir())420 || (!file_types.symlinks && entry_type.is_symlink())Add new `--type socket` and `--type pipe` filterssharkdpbefore adoptioncb56add
lines 421–422why, one step back421 || (!file_types.sockets && filesystem::is_socket(entry_type))422 || (!file_types.pipes && filesystem::is_pipe(entry_type))Update dependenciessharkdpbefore adoptionacd4910
lines 423–425why, one step back423 || (file_types.executables_only424 && !entry425 .metadata()Rename fshelper to filesystemsharkdpbefore adoptionb415d72
line 426why, one step back426 .map(|m| filesystem::is_executable(&m))Update dependenciessharkdpbefore adoptionacd4910
line 427why, one step back427 .unwrap_or(false))Rename fshelper to filesystemsharkdpbefore adoptionb415d72
line 428why, one step back428 || (file_types.empty_only && !filesystem::is_empty(&entry))Add new `--type socket` and `--type pipe` filterssharkdpbefore adoptioncb56add
lines 429–433why, one step back429 || !(entry_type.is_file()430 || entry_type.is_dir()431 || entry_type.is_symlink()432 || filesystem::is_socket(entry_type)433 || filesystem::is_pipe(entry_type))Update dependenciessharkdpbefore adoptionacd4910
lines 434–441why, one step back434 {435 return ignore::WalkState::Continue;436 }437 } else {438 return ignore::WalkState::Continue;439 }440 }441[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 442–454why, one step back442 #[cfg(unix)]443 {444 if let Some(ref owner_constraint) = config.owner_constraint {445 if let Ok(ref metadata) = entry_path.metadata() {446 if !owner_constraint.matches(&metadata) {447 return ignore::WalkState::Continue;448 }449 } else {450 return ignore::WalkState::Continue;451 }452 }453 }454Update dependenciessharkdpbefore adoptionacd4910
lines 455–477why, one step back455 // Filter out unwanted sizes if it is a file and we have been given size constraints.456 if !config.size_constraints.is_empty() {457 if entry_path.is_file() {458 if let Ok(metadata) = entry_path.metadata() {459 let file_size = metadata.len();460 if config461 .size_constraints462 .iter()463 .any(|sc| !sc.is_within(file_size))464 {465 return ignore::WalkState::Continue;466 }467 } else {468 return ignore::WalkState::Continue;469 }470 } else {471 return ignore::WalkState::Continue;472 }473 }474475 // Filter out unwanted modification times476 if !config.time_constraints.is_empty() {477 let mut matched = false;Make --changed-within/before work for directoriessharkdpbefore adoption08fcd7c
lines 478–483why, one step back478 if let Ok(metadata) = entry_path.metadata() {479 if let Ok(modified) = metadata.modified() {480 matched = config481 .time_constraints482 .iter()483 .all(|tf| tf.applies_to(&modified));Update dependenciessharkdpbefore adoptionacd4910
lines 484–490why, one step back484 }485 }486 if !matched {487 return ignore::WalkState::Continue;488 }489 }490Formattingsharkdpbefore adoptionf7d1938
line 491why, one step back491 let send_result = tx_thread.send(WorkerResult::Entry(entry_path.to_owned()));Quit immediately if the channel::send call failedsharkdpbefore adoption0f27485
line 492why, one step back492Solve clippy issuessharkdpbefore adoptionb9d0e72
line 493why, one step back493 if send_result.is_err() {Quit immediately if the channel::send call failedsharkdpbefore adoption0f27485
lines 494–495why, one step back494 return ignore::WalkState::Quit;495 }Update dependenciessharkdpbefore adoptionacd4910
lines 496–500why, one step back496497 ignore::WalkState::Continue498 })499 });500}