Skip to content
Myr

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

5 files+45 added−39 removed

modified:src/exec/command.rs+2 added-2 removed
28 unmodified lines
29 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 lines
6// notice may not be copied, modified, or distributed except7// according to those terms.89use super::CommandTemplate;10use internal::print_error;10use std::path::PathBuf;11use std::sync::mpsc::Receiver;12use std::sync::{Arc, Mutex};13use walk::WorkerResult;
14 unmodified lines
28 // 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 lines
modified:src/internal.rs+7 added-8 removed
6 unmodified lines
7// according to those terms.89use std::ffi::OsString;10use std::path::PathBuf;11use std::process;11use std::time::{self, SystemTime};1213use exec::CommandTemplate;14use lscolors::LsColors;
182 unmodified lines
197 /// Constraints on last modification time of files198 pub time_constraints: Vec<TimeFilter>,199}200202/// Print error message to stderr.203pub fn print_error(message: &str) {204 eprintln!("{}", message);201macro_rules! print_error {202 ($($arg:tt)*) => (eprintln!($($arg)*))203}204207/// Print error message to stderr and exit with status `1`.208pub fn print_error_and_exit(message: &str) -> ! {209 print_error(message);210 process::exit(1);205macro_rules! print_error_and_exit {206 ($($arg:tt)*) => {207 print_error!($($arg)*);208 ::std::process::exit(1);209 };210}211212/// Determine if a regex pattern contains a literal uppercase character.213pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
355 unmodified lines
modified:src/main.rs+20 added-17 removed
18 unmodified lines
19extern crate num_cpus;20extern crate regex;21extern crate regex_syntax;2223#[macro_use]24mod internal;2526mod app;27mod exec;28mod exit_codes;29pub mod fshelper;27mod internal;30pub mod lscolors;31mod output;32mod walk;33
7 unmodified lines
41use regex::{RegexBuilder, RegexSetBuilder};4243use exec::CommandTemplate;44use 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};48use lscolors::LsColors;4950fn main() {
5 unmodified lines
5657 // 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 }6263 // 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 lines
93 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 }108109 // Treat pattern as literal string if '--fixed-strings' is used110 let pattern_regex = if matches.is_present("fixed-strings") {
35 unmodified lines
146 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 lines
158 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 }172173 let config = FdOptions {
58 unmodified lines
232 .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: matches
13 unmodified lines
256 .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 lines
1011use exec;12use exit_codes::ExitCode;13use fshelper;14use internal::{print_error, print_error_and_exit, FdOptions, MAX_BUFFER_LENGTH};14use internal::{FdOptions, MAX_BUFFER_LENGTH};15use output;1617use std::error::Error;18use std::path::PathBuf;
41 unmodified lines
6061 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 });7071 let mut walker = WalkBuilder::new(first_path_buf.as_path());72 walker
16 unmodified lines
89 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 lines
192 }193 }194 }195 WorkerResult::Error(err) => {193 print_error(&format!("{}", err));196 print_error!("{}", err);197 }198 }199 }200
111 unmodified lines
312313 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