Proper error handling in main.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 af9d808 · Browse files · 4 files·+110 added−94 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+110 added−94 removed
- other:+110 added−94 removed
Provenance
- Commit
bce9527- Tree
a90d91e- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
af9d808
4 files changed+110 added−94 removed
modified:src/exec/mod.rs+6 added-3 removed
7 unmodified lines8 use std::path::{Path, PathBuf};9 use std::process::{Command, Stdio};10 use std::sync::{Arc, Mutex};11 12+use anyhow::{anyhow, Result};13 use lazy_static::lazy_static;14 use regex::Regex;15 16 use crate::exit_codes::ExitCode;30 unmodified lines47 {48 Self::build(input, ExecutionMode::OneByOne)49 }50 50- pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>51+ pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate>52 where53 I: IntoIterator<Item = S>,54 S: AsRef<str>,55 {56 let cmd = Self::build(input, ExecutionMode::Batch);57 if cmd.number_of_tokens() > 1 {57- return Err("Only one placeholder allowed for batch commands");58+ return Err(anyhow!("Only one placeholder allowed for batch commands"));59 }60 if cmd.args[0].has_tokens() {60- return Err("First argument of exec-batch is expected to be a fixed executable");61+ return Err(anyhow!(62+ "First argument of exec-batch is expected to be a fixed executable"63+ ));64 }65 Ok(cmd)66 }67 279 unmodified linesmodified:src/main.rs+96 added-91 removed
16 unmodified lines17 use std::process;18 use std::sync::Arc;19 use std::time;20 21+use anyhow::{anyhow, Context, Result};22 use atty::Stream;23 use globset::Glob;24 use lscolors::LsColors;25 use regex::bytes::{RegexBuilder, RegexSetBuilder};26 27 use crate::exec::CommandTemplate;28+use crate::exit_codes::ExitCode;29 use crate::filetypes::FileTypes;30 use crate::filter::{SizeFilter, TimeFilter};31 use crate::options::Options;32 use crate::regex_helper::pattern_has_uppercase_char;2 unmodified lines35 #[cfg(all(not(windows), not(target_env = "musl")))]36 #[global_allocator]37 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;38 37-fn main() {39+fn run() -> Result<ExitCode> {40 let matches = app::build_app().get_matches_from(env::args_os());41 42 // Set the current working directory of the process43 if let Some(base_directory) = matches.value_of("base-directory") {44 let base_directory = Path::new(base_directory);45 if !filesystem::is_dir(base_directory) {44- print_error_and_exit!(45- "The '--base-directory' path ('{}') is not a directory.",46+ return Err(anyhow!(47+ "The '--base-directory' path '{}' is not a directory.",48 base_directory.to_string_lossy()47- );49+ ));50 }49- if let Err(e) = env::set_current_dir(base_directory) {50- print_error_and_exit!(51- "Could not set '{}' as the current working directory: {}",52- base_directory.to_string_lossy(),53- e54- );55- }51+ env::set_current_dir(base_directory).with_context(|| {52+ format!(53+ "Could not set '{}' as the current working directory.",54+ base_directory.to_string_lossy()55+ )56+ })?;57 }58 59 let current_directory = Path::new(".");60 if !filesystem::is_dir(current_directory) {60- print_error_and_exit!("Could not retrieve current directory (has it been deleted?).");61+ return Err(anyhow!(62+ "Could not retrieve current directory (has it been deleted?)."63+ ));64 }65 66 // Get the search pattern67 let pattern = matches.value_of("pattern").unwrap_or("");5 unmodified lines73 {74 Some(paths) => paths75 .map(|path| {76 let path_buffer = PathBuf::from(path);74- if !filesystem::is_dir(&path_buffer) {75- print_error_and_exit!(76- "'{}' is not a directory.",77+ if filesystem::is_dir(&path_buffer) {78+ Ok(path_buffer)79+ } else {80+ Err(anyhow!(81+ "Search path '{}' is not a directory.",82 path_buffer.to_string_lossy()78- );83+ ))84 }80- path_buffer85 })82- .collect::<Vec<_>>(),86+ .collect::<Result<Vec<_>>>()?,87 None => vec![current_directory.to_path_buf()],88 };89 90 if matches.is_present("absolute-path") {12 unmodified lines103 if !matches.is_present("full-path")104 && pattern.contains(std::path::MAIN_SEPARATOR)105 && filesystem::is_dir(Path::new(pattern))106 {103- print_error_and_exit!(107+ return Err(anyhow!(108 "The search pattern '{pattern}' contains a path-separation character ('{sep}') \109 and will not lead to any search results.\n\n\110 If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \111 fd . '{pattern}'\n\n\108- Instead, if you want to search for the pattern in the full path, use:\n\n \112+ Instead, if you want your pattern to match the full file path, use:\n\n \113 fd --full-path '{pattern}'",114 pattern = pattern,115 sep = std::path::MAIN_SEPARATOR,112- );116+ ));117 }118 119 let pattern_regex = if matches.is_present("glob") {116- let glob = match Glob::new(pattern) {117- Ok(glob) => glob,118- Err(e) => {119- print_error_and_exit!("{}", e);120- }121- };120+ let glob = Glob::new(pattern)?;121 glob.regex().to_owned()122 } else if matches.is_present("fixed-strings") {123 // Treat pattern as literal string if '--fixed-strings' is used124 regex::escape(pattern)22 unmodified lines147 } else {148 None149 };150 152- let command = matches153- .values_of("exec")154- .map(CommandTemplate::new)155- .or_else(|| {156- matches.values_of("exec-batch").map(|m| {157- CommandTemplate::new_batch(m).unwrap_or_else(|e| {158- print_error_and_exit!("{}", e);159- })160- })161- })162- .or_else(|| {163- if matches.is_present("list-details") {164- let color = matches.value_of("color").unwrap_or("auto");165- let color_arg = ["--color=", color].concat();151+ let command = if let Some(args) = matches.values_of("exec") {152+ Some(CommandTemplate::new(args))153+ } else if let Some(args) = matches.values_of("exec-batch") {154+ Some(CommandTemplate::new_batch(args)?)155+ } else if matches.is_present("list-details") {156+ let color = matches.value_of("color").unwrap_or("auto");157+ let color_arg = ["--color=", color].concat();158 167- Some(168- CommandTemplate::new_batch(&[169- "ls",170- "-l", // long listing format171- "--human-readable", // human readable file sizes172- "--directory", // list directories themselves, not their contents173- &color_arg, // enable colorized output, if enabled174- ])175- .unwrap(),176- )177- } else {178- None179- }180- });159+ Some(160+ CommandTemplate::new_batch(&[161+ "ls",162+ "-l", // long listing format163+ "--human-readable", // human readable file sizes164+ "--directory", // list directories themselves, not their contents165+ &color_arg, // enable colorized output, if enabled166+ ])167+ .unwrap(),168+ )169+ } else {170+ None171+ };172 182- let size_limits: Vec<SizeFilter> = matches183- .values_of("size")184- .map(|v| {185- v.map(|sf| {186- if let Some(f) = SizeFilter::from_string(sf) {187- return f;188- }189- print_error_and_exit!("'{}' is not a valid size constraint. See 'fd --help'.", sf);190- })191- .collect()173+ let size_limits = if let Some(vs) = matches.values_of("size") {174+ vs.map(|sf| {175+ SizeFilter::from_string(sf).ok_or(anyhow!(176+ "'{}' is not a valid size constraint. See 'fd --help'.",177+ sf178+ ))179 })193- .unwrap_or_else(|| vec![]);180+ .collect::<Result<Vec<_>>>()?181+ } else {182+ vec![]183+ };184 185 let now = time::SystemTime::now();186 let mut time_constraints: Vec<TimeFilter> = Vec::new();187 if let Some(t) = matches.value_of("changed-within") {188 if let Some(f) = TimeFilter::after(&now, t) {189 time_constraints.push(f);190 } else {201- print_error_and_exit!("'{}' is not a valid date or duration. See 'fd --help'.", t);191+ return Err(anyhow!(192+ "'{}' is not a valid date or duration. See 'fd --help'.",193+ t194+ ));195 }196 }197 if let Some(t) = matches.value_of("changed-before") {198 if let Some(f) = TimeFilter::before(&now, t) {199 time_constraints.push(f);200 } else {208- print_error_and_exit!("'{}' is not a valid date or duration. See 'fd --help'.", t);201+ return Err(anyhow!(202+ "'{}' is not a valid date or duration. See 'fd --help'.",203+ t204+ ));205 }206 }207 208 let config = Options {50 unmodified lines259 }260 261 file_types262 }),267- extensions: matches.values_of("extension").map(|exts| {268- let patterns = exts269- .map(|e| e.trim_start_matches('.'))270- .map(|e| format!(r".\.{}$", regex::escape(e)));271- match RegexSetBuilder::new(patterns)272- .case_insensitive(true)273- .build()274- {275- Ok(re) => re,276- Err(err) => {277- print_error_and_exit!("{}", err.to_string());278- }279- }280- }),263+ extensions: matches264+ .values_of("extension")265+ .map(|exts| {266+ let patterns = exts267+ .map(|e| e.trim_start_matches('.'))268+ .map(|e| format!(r".\.{}$", regex::escape(e)));269+ RegexSetBuilder::new(patterns)270+ .case_insensitive(true)271+ .build()272+ })273+ .transpose()?,274 command: command.map(Arc::new),275 exclude_patterns: matches276 .values_of("exclude")277 .map(|v| v.map(|p| String::from("!") + p).collect())11 unmodified lines289 .and_then(|n| usize::from_str_radix(n, 10).ok())290 .filter(|&n| n != 0),291 };292 300- match RegexBuilder::new(&pattern_regex)293+ let re = RegexBuilder::new(&pattern_regex)294 .case_insensitive(!config.case_sensitive)295 .dot_matches_new_line(true)296 .build()304- {305- Ok(re) => {306- let exit_code = walk::scan(&dir_vec, Arc::new(re), Arc::new(config));297+ .map_err(|e| {298+ anyhow!(299+ "{}\n\nNote: You can use the '--fixed-strings' option to search for a \300+ literal string instead of a regular expression. Alternatively, you can \301+ also use the '--glob' option to match on a glob pattern.",302+ 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)309+}310+311+fn main() {312+ let result = run();313+ match result {314+ Ok(exit_code) => {315 process::exit(exit_code.into());316 }317 Err(err) => {310- print_error_and_exit!(311- "{}\nHint: You can use the '--fixed-strings' option to search for a \312- literal string instead of a regular expression",313- err.to_string()314- );318+ eprintln!("[fd error]: {}", err);319+ process::exit(1);320 }321 }322 }modified:Cargo.lock+7 added
23 unmodified lines24 "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",25 ]26 27 [[package]]28+name = "anyhow"29+version = "1.0.28"30+source = "registry+https://github.com/rust-lang/crates.io-index"31+32+[[package]]33 name = "atty"34 version = "0.2.14"35 source = "registry+https://github.com/rust-lang/crates.io-index"36 dependencies = [82 unmodified lines119 name = "fd-find"120 version = "7.5.0"121 dependencies = [122 "ansi_term 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)",123+ "anyhow 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)",124 "atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)",125 "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)",126 "ctrlc 3.1.4 (registry+https://github.com/rust-lang/crates.io-index)",127 "diff 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",347 unmodified lines475 [metadata]476 "checksum aho-corasick 0.7.10 (registry+https://github.com/rust-lang/crates.io-index)" = "8716408b8bc624ed7f65d223ddb9ac2d044c0547b6fa4b0d554f3a9540496ada"477 "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"478 "checksum ansi_term 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"479+"checksum anyhow 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)" = "d9a60d744a80c30fcb657dfe2c1b22bcb3e814c1a1e3674f32bf5820b570fbff"480 "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"481 "checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"482 "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"483 "checksum bstr 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)" = "2889e6d50f394968c8bf4240dc3f2a7eb4680844d27308f798229ac9d4725f41"51 unmodified linesmodified:Cargo.toml+1 added
43 unmodified lines44454647484950515215 unmodified lines43 unmodified linesctrlc = "3.1"humantime = "2.0"lscolors = "0.7"globset = "0.4"anyhow = "1.0"
[dependencies.clap]version = "2.31.2"features = ["suggestions", "color", "wrap_help"]15 unmodified lines