Skip to content
Myr

Proper error handling within walk.rs

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

authored by sharkdp · committed by David Peter · parent bce9527 · Browse files · 5 files+38 added−48 removed
This commit

State

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

Diff stats

5 files+38 added−48 removed

  • other:+38 added−48 removed

5 files+38 added−48 removed

modified:src/exec/command.rs+3 added-2 removed
1 unmodified line
2use std::io::Write;3use std::process::Command;4use std::sync::Mutex;56use crate::error::print_error;7use crate::exit_codes::ExitCode;89/// Executes a command.10pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) -> ExitCode {
19 unmodified lines
30 ExitCode::GeneralError31 }32 }33 Err(ref why) if why.kind() == io::ErrorKind::NotFound => {33 print_error!("Command not found: {:?}", cmd);34 print_error(format!("Command not found: {:?}", cmd));35 ExitCode::GeneralError36 }37 Err(why) => {37 print_error!("Problem while executing command: {}", why);38 print_error(format!("Problem while executing command: {}", why));39 ExitCode::GeneralError40 }41 }42}
modified:src/exec/job.rs+8 added-5 removed
1use super::CommandTemplate;2use crate::exit_codes::{merge_exitcodes, ExitCode};3use crate::walk::WorkerResult;1use std::path::PathBuf;2use std::sync::mpsc::Receiver;3use std::sync::{Arc, Mutex};45use crate::error::print_error;6use crate::exit_codes::{merge_exitcodes, ExitCode};7use crate::walk::WorkerResult;89use super::CommandTemplate;1011/// An event loop that listens for inputs from the `rx` receiver. Each received input will12/// generate a command with the supplied command template. The generated command will then13/// be executed, and this process will continue until the receiver's sender has closed.14pub fn job(
12 unmodified lines
27 let value: PathBuf = match lock.recv() {28 Ok(WorkerResult::Entry(val)) => val,29 Ok(WorkerResult::Error(err)) => {30 if show_filesystem_errors {28 print_error!("{}", err);31 print_error(err.to_string());32 }33 continue;34 }35 Err(_) => break,
16 unmodified lines
52 let paths = rx.iter().filter_map(|value| match value {53 WorkerResult::Entry(val) => Some(val),54 WorkerResult::Error(err) => {55 if show_filesystem_errors {53 print_error!("{}", err);56 print_error(err.to_string());57 }58 None59 }60 });
2 unmodified lines
modified:src/error.rs+2 added-9 removed
1macro_rules! print_error {2 ($($arg:tt)*) => (eprintln!("[fd error]: {}", format!($($arg)*)))1pub fn print_error(msg: impl Into<String>) {2 eprintln!("[fd error]: {}", msg.into());3}45macro_rules! print_error_and_exit {6 ($($arg:tt)*) => {7 print_error!($($arg)*);8 ::std::process::exit(1);9 };10}
modified:src/main.rs+1 added-3 removed
301 unmodified lines
302 e.to_string()303 )304 })?;305306 let exit_code = walk::scan(&dir_vec, Arc::new(re), Arc::new(config));307308 Ok(exit_code)306 walk::scan(&dir_vec, Arc::new(re), Arc::new(config))307}308309fn main() {310 let result = run();
10 unmodified lines
modified:src/walk.rs+24 added-29 removed
1use crate::exec;2use crate::exit_codes::{merge_exitcodes, ExitCode};3use crate::filesystem;4use crate::options::Options;5use crate::output;61use std::borrow::Cow;2use std::ffi::OsStr;3use std::fs::{FileType, Metadata};4use std::io;
4 unmodified lines
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.
16 unmodified lines
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.47pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> ExitCode {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");
1 unmodified line
5556 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());5758 for pattern in &config.exclude_patterns {57 let res = override_builder.add(pattern);58 if res.is_err() {59 print_error_and_exit!("Malformed exclude pattern '{}'", pattern);60 }59 override_builder60 .add(pattern)61 .map_err(|e| anyhow!("Malformed exclude pattern: {}", e))?;62 }62 let overrides = override_builder.build().unwrap_or_else(|_| {63 print_error_and_exit!("Mismatch in exclude patterns");64 });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)
16 unmodified lines
86 let result = walker.add_ignore(ignore_file);87 match result {88 Some(ignore::Error::Partial(_)) => (),89 Some(err) => {89 print_error!(90 "{}",91 format!(92 "Malformed pattern in custom ignore file. {}.",93 err.to_string()94 )90 print_error(format!(91 "Malformed pattern in custom ignore file. {}.",92 err.to_string()93 ));95 );94 }95 None => (),96 }97 }
30 unmodified lines
128 if wants_to_quit.load(Ordering::Relaxed) {129 process::exit(ExitCode::KilledBySigint.into());130 }131134 exit_code132 Ok(exit_code)133}134135fn spawn_receiver(136 config: &Arc<Options>,
91 unmodified lines
228 num_results += 1;229 }230 WorkerResult::Error(err) => {231 if show_filesystem_errors {234 print_error!("{}", err);232 print_error(err.to_string());233 }234 }235 }236
104 unmodified lines
341 // Check the name first, since it doesn't require metadata342 let entry_path = entry.path();343344 let search_str: Cow<OsStr> = if config.search_full_path {347 match filesystem::path_absolute_form(entry_path) {348 Ok(path_abs_buf) => Cow::Owned(path_abs_buf.as_os_str().to_os_string()),349 Err(_) => {350 print_error_and_exit!("Unable to retrieve absolute path.");351 }352 }345 let path_abs_buf = filesystem::path_absolute_form(entry_path)346 .expect("Retrieving absolute path succeeds");347 Cow::Owned(path_abs_buf.as_os_str().to_os_string())348 } else {349 match entry_path.file_name() {350 Some(filename) => Cow::Borrowed(filename),351 None => unreachable!(
89 unmodified lines