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
Provenance
- Commit
4590ae8- Tree
7fb4f18- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
bce9527
5 files changed+38 added−48 removed
modified:src/exec/command.rs+3 added-2 removed
1 unmodified line2 use std::io::Write;3 use std::process::Command;4 use std::sync::Mutex;5 6+use crate::error::print_error;7 use crate::exit_codes::ExitCode;8 9 /// Executes a command.10 pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) -> ExitCode {19 unmodified lines30 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
1-use super::CommandTemplate;2-use crate::exit_codes::{merge_exitcodes, ExitCode};3-use crate::walk::WorkerResult;1 use std::path::PathBuf;2 use std::sync::mpsc::Receiver;3 use std::sync::{Arc, Mutex};4 5+use crate::error::print_error;6+use crate::exit_codes::{merge_exitcodes, ExitCode};7+use crate::walk::WorkerResult;8+9+use super::CommandTemplate;10+11 /// 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.14 pub fn job(12 unmodified lines27 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 lines52 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 linesmodified:src/error.rs+2 added-9 removed
1-macro_rules! print_error {2- ($($arg:tt)*) => (eprintln!("[fd error]: {}", format!($($arg)*)))1+pub fn print_error(msg: impl Into<String>) {2+ eprintln!("[fd error]: {}", msg.into());3 }4-5-macro_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 lines302 e.to_string()303 )304 })?;305 306- let exit_code = walk::scan(&dir_vec, Arc::new(re), Arc::new(config));307-308- Ok(exit_code)306+ walk::scan(&dir_vec, Arc::new(re), Arc::new(config))307 }308 309 fn main() {310 let result = run();10 unmodified linesmodified:src/walk.rs+24 added-29 removed
1-use crate::exec;2-use crate::exit_codes::{merge_exitcodes, ExitCode};3-use crate::filesystem;4-use crate::options::Options;5-use crate::output;6-1 use std::borrow::Cow;2 use std::ffi::OsStr;3 use std::fs::{FileType, Metadata};4 use std::io;4 unmodified lines9 use std::sync::{Arc, Mutex};10 use std::thread;11 use std::time;12 13+use anyhow::{anyhow, Result};14 use ignore::overrides::OverrideBuilder;15 use ignore::{self, WalkBuilder};16 use regex::bytes::Regex;17 18+use crate::error::print_error;19+use crate::exec;20+use crate::exit_codes::{merge_exitcodes, ExitCode};21+use crate::filesystem;22+use crate::options::Options;23+use crate::output;24+25 /// The receiver thread can either be buffering results or directly streaming to the console.26 enum ReceiverMode {27 /// Receiver is still buffering in order to sort the results, if the search finishes fast28 /// enough.16 unmodified lines45 ///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.47-pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Options>) -> ExitCode {49+pub 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 line55 56 let mut override_builder = OverrideBuilder::new(first_path_buf.as_path());57 58 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"))?;66 67 let mut walker = WalkBuilder::new(first_path_buf.as_path());68 walker69 .hidden(config.ignore_hidden)16 unmodified lines86 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 lines128 if wants_to_quit.load(Ordering::Relaxed) {129 process::exit(ExitCode::KilledBySigint.into());130 }131 134- exit_code132+ Ok(exit_code)133 }134 135 fn spawn_receiver(136 config: &Arc<Options>,91 unmodified lines228 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 lines341 // Check the name first, since it doesn't require metadata342 let entry_path = entry.path();343 344 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