Add an exit() method to ExitCode

This commit is contained in:
Tavian Barnes 2021-11-14 16:31:38 -05:00 committed by David Peter
parent cab31e280b
commit 2b1bf471b1
4 changed files with 14 additions and 12 deletions

View file

@ -1,3 +1,5 @@
use std::process;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ExitCode {
Success,
@ -21,6 +23,11 @@ impl ExitCode {
fn is_error(self) -> bool {
i32::from(self) != 0
}
/// Exit the process with the appropriate code.
pub fn exit(self) -> ! {
process::exit(self.into())
}
}
pub fn merge_exitcodes(results: impl IntoIterator<Item = ExitCode>) -> ExitCode {

View file

@ -12,7 +12,6 @@ mod walk;
use std::env;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::Arc;
use std::time;
@ -54,11 +53,11 @@ fn main() {
let result = run();
match result {
Ok(exit_code) => {
process::exit(exit_code.into());
exit_code.exit();
}
Err(err) => {
eprintln!("[fd error]: {:#}", err);
process::exit(ExitCode::GeneralError.into());
ExitCode::GeneralError.exit();
}
}
}

View file

@ -1,7 +1,6 @@
use std::borrow::Cow;
use std::io::{self, StdoutLock, Write};
use std::path::Path;
use std::process;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
@ -38,10 +37,10 @@ pub fn print_entry(
if let Err(e) = r {
if e.kind() == ::std::io::ErrorKind::BrokenPipe {
// Exit gracefully in case of a broken pipe (e.g. 'fd ... | head -n 3').
process::exit(0);
ExitCode::Success.exit();
} else {
print_error(format!("Could not write to output: {}", e));
process::exit(ExitCode::GeneralError.into());
ExitCode::GeneralError.exit();
}
}
}
@ -95,7 +94,7 @@ fn print_entry_colorized(
}
if wants_to_quit.load(Ordering::Relaxed) {
process::exit(ExitCode::KilledBySigint.into());
ExitCode::KilledBySigint.exit();
}
Ok(())

View file

@ -3,7 +3,6 @@ use std::ffi::OsStr;
use std::fs::{FileType, Metadata};
use std::io;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
@ -137,11 +136,9 @@ pub fn scan(path_vec: &[PathBuf], pattern: Arc<Regex>, config: Arc<Config>) -> R
if config.ls_colors.is_some() && config.command.is_none() {
let wq = Arc::clone(&wants_to_quit);
ctrlc::set_handler(move || {
if wq.load(Ordering::Relaxed) {
if wq.fetch_or(true, Ordering::Relaxed) {
// Ctrl-C has been pressed twice, exit NOW
process::exit(ExitCode::KilledBySigint.into());
} else {
wq.store(true, Ordering::Relaxed);
ExitCode::KilledBySigint.exit();
}
})
.unwrap();