Add print_error macros to replace functions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This patch replaces the `print_error` and `print_error_and_exit` functions with equivalent macros.
authored by Josh Leeb-du Toit · committed by David Peter · parent abe8aa5 · Browse files · 5 files·+45 added−39 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+45 added−39 removed
- other:+45 added−39 removed
Provenance
- Commit
984f04f- Tree
d5b2e40- Author
Josh Leeb-du Toit <josh.leebdutoit@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
abe8aa5
5 files changed+45 added−39 removed
modified:src/exec/command.rs+2 added-2 removed
28 unmodified lines29 let _ = stdout.lock().write_all(&output.stdout);30 let _ = stderr.lock().write_all(&output.stderr);31 }32 Err(ref why) if why.kind() == io::ErrorKind::NotFound => {33- eprintln!("fd: execution error: command not found");33+ print_error!("fd: execution error: command not found");34 }35 Err(why) => {36- eprintln!("fd: execution error: {}", why);36+ print_error!("fd: execution error: {}", why);37 }38 }39 }modified:src/exec/job.rs+1 added-2 removed
5 unmodified lines6 // notice may not be copied, modified, or distributed except7 // according to those terms.8 9 use super::CommandTemplate;10-use internal::print_error;10 use std::path::PathBuf;11 use std::sync::mpsc::Receiver;12 use std::sync::{Arc, Mutex};13 use walk::WorkerResult;14 unmodified lines28 // has closed, exit from the loop29 let value: PathBuf = match lock.recv() {30 Ok(WorkerResult::Entry(val)) => val,31 Ok(WorkerResult::Error(err)) => {33- print_error(&format!("{}", err));32+ print_error!("{}", err);33 continue;34 }35 Err(_) => break,36 };7 unmodified linesmodified:src/internal.rs+7 added-8 removed
6 unmodified lines7 // according to those terms.8 9 use std::ffi::OsString;10 use std::path::PathBuf;11-use std::process;11 use std::time::{self, SystemTime};12 13 use exec::CommandTemplate;14 use lscolors::LsColors;182 unmodified lines197 /// Constraints on last modification time of files198 pub time_constraints: Vec<TimeFilter>,199 }200 202-/// Print error message to stderr.203-pub fn print_error(message: &str) {204- eprintln!("{}", message);201+macro_rules! print_error {202+ ($($arg:tt)*) => (eprintln!($($arg)*))203 }204 207-/// Print error message to stderr and exit with status `1`.208-pub fn print_error_and_exit(message: &str) -> ! {209- print_error(message);210- process::exit(1);205+macro_rules! print_error_and_exit {206+ ($($arg:tt)*) => {207+ print_error!($($arg)*);208+ ::std::process::exit(1);209+ };210 }211 212 /// Determine if a regex pattern contains a literal uppercase character.213 pub fn pattern_has_uppercase_char(pattern: &str) -> bool {355 unmodified linesmodified:src/main.rs+20 added-17 removed
18 unmodified lines19 extern crate num_cpus;20 extern crate regex;21 extern crate regex_syntax;22 23+#[macro_use]24+mod internal;25+26 mod app;27 mod exec;28 mod exit_codes;29 pub mod fshelper;27-mod internal;30 pub mod lscolors;31 mod output;32 mod walk;33 7 unmodified lines41 use regex::{RegexBuilder, RegexSetBuilder};42 43 use exec::CommandTemplate;44 use internal::{43- pattern_has_uppercase_char, print_error_and_exit, transform_args_with_exec, FdOptions,44- FileTypes, SizeFilter, TimeFilter,45+ pattern_has_uppercase_char, transform_args_with_exec, FdOptions, FileTypes, SizeFilter,46+ TimeFilter,47 };48 use lscolors::LsColors;49 50 fn main() {5 unmodified lines56 57 // Get the current working directory58 let current_dir = Path::new(".");59 if !fshelper::is_dir(current_dir) {58- print_error_and_exit("Error: could not get current directory.");60+ print_error_and_exit!("Error: could not get current directory.");61 }62 63 // Get one or more root directories to search.64 let mut dir_vec: Vec<_> = match matches.values_of("path") {65 Some(paths) => paths66 .map(|path| {67 let path_buffer = PathBuf::from(path);68 if !fshelper::is_dir(&path_buffer) {67- print_error_and_exit(&format!(69+ print_error_and_exit!(70 "Error: '{}' is not a directory.",71 path_buffer.to_string_lossy()70- ));72+ );73 }74 path_buffer75 })76 .collect::<Vec<_>>(),16 unmodified lines93 if !matches.is_present("full-path")94 && pattern.contains(std::path::MAIN_SEPARATOR)95 && fshelper::is_dir(Path::new(pattern))96 {95- print_error_and_exit(&format!(97+ print_error_and_exit!(98 "Error: The search pattern '{pattern}' contains a path-separation character ('{sep}') \99 and will not lead to any search results.\n\n\100 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \101 fd . '{pattern}'\n\n\102 Instead, if you want to search for the pattern in the full path, use:\n\n \103 fd --full-path '{pattern}'",104 pattern = pattern,105 sep = std::path::MAIN_SEPARATOR,104- ));106+ );107 }108 109 // Treat pattern as literal string if '--fixed-strings' is used110 let pattern_regex = if matches.is_present("fixed-strings") {35 unmodified lines146 v.map(|sf| {147 if let Some(f) = SizeFilter::from_string(sf) {148 return f;149 }148- print_error_and_exit(&format!("Error: {} is not a valid size constraint.", sf));150+ print_error_and_exit!("Error: {} is not a valid size constraint.", sf);151 })152 .collect()153 })154 .unwrap_or_else(|| vec![]);3 unmodified lines158 if let Some(t) = matches.value_of("changed-within") {159 if let Some(f) = TimeFilter::after(&now, t) {160 time_constraints.push(f);161 } else {160- print_error_and_exit(&format!("Error: {} is not a valid time.", t));162+ print_error_and_exit!("Error: {} is not a valid time.", t);163 }164 }165 if let Some(t) = matches.value_of("changed-before") {166 if let Some(f) = TimeFilter::before(&now, t) {167 time_constraints.push(f);168 } else {167- print_error_and_exit(&format!("Error: {} is not a valid time.", t));169+ print_error_and_exit!("Error: {} is not a valid time.", t);170 }171 }172 173 let config = FdOptions {58 unmodified lines232 .case_insensitive(true)233 .build()234 {235 Ok(re) => re,234- Err(err) => print_error_and_exit(err.description()),236+ Err(err) => {237+ print_error_and_exit!("{}", err.description());238+ }239 }240 }),241 command,242 exclude_patterns: matches13 unmodified lines256 .dot_matches_new_line(true)257 .build()258 {259 Ok(re) => walk::scan(&dir_vec, Arc::new(re), Arc::new(config)),256- Err(err) => print_error_and_exit(257- format!(260+ Err(err) => {261+ print_error_and_exit!(262 "{}\nHint: You can use the '--fixed-strings' option to search for a \263 literal string instead of a regular expression",264 err.description()261- )262- .as_str(),263- ),265+ );266+ }267 }268 }modified:src/walk.rs+15 added-10 removed
9 unmodified lines10 11 use exec;12 use exit_codes::ExitCode;13 use fshelper;14-use internal::{print_error, print_error_and_exit, FdOptions, MAX_BUFFER_LENGTH};14+use internal::{FdOptions, MAX_BUFFER_LENGTH};15 use output;16 17 use std::error::Error;18 use std::path::PathBuf;41 unmodified lines60 61 for pattern in &config.exclude_patterns {62 let res = override_builder.add(pattern);63 if res.is_err() {64- print_error_and_exit(&format!("Error: malformed exclude pattern '{}'", pattern));64+ print_error_and_exit!("Error: malformed exclude pattern '{}'", pattern);65 }66 }67 let overrides = override_builder.build().unwrap_or_else(|_| {68- print_error_and_exit("Mismatch in exclude patterns");68+ print_error_and_exit!("Mismatch in exclude patterns");69 });70 71 let mut walker = WalkBuilder::new(first_path_buf.as_path());72 walker16 unmodified lines89 if let Some(err) = result {90 match err {91 ignore::Error::Partial(_) => (),92 _ => {93+ print_error!(94+ "{}",93- print_error(&format!(94- "Error while parsing custom ignore file '{}': {}.",95- ignore_file.to_string_lossy(),96- err.description()97- ));95+ format!(96+ "Error while parsing custom ignore file '{}': {}.",97+ ignore_file.to_string_lossy(),98+ err.description()99+ )100+ );101 }102 }103 }104 }87 unmodified lines192 }193 }194 }195 WorkerResult::Error(err) => {193- print_error(&format!("{}", err));196+ print_error!("{}", err);197 }198 }199 }200 111 unmodified lines312 313 let search_str_o = if config.search_full_path {314 match fshelper::path_absolute_form(entry_path) {315 Ok(path_abs_buf) => Some(path_abs_buf.to_string_lossy().into_owned().into()),313- Err(_) => print_error_and_exit("Error: unable to get full path."),316+ Err(_) => {317+ print_error_and_exit!("Error: unable to get full path.");318+ }319 }320 } else {321 entry_path.file_name().map(|f| f.to_string_lossy())322 };25 unmodified lines