From aa372068201c3f30c21117506fcafad4ce1253b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Valdelvira?= Date: Tue, 7 Jan 2025 00:05:25 +0100 Subject: [PATCH] uucore: Remove crash! macro --- src/uu/csplit/src/csplit.rs | 23 +++++------- src/uu/join/src/join.rs | 27 ++++++++------ src/uu/unexpand/src/unexpand.rs | 17 +++++---- src/uucore/src/lib/features/fsext.rs | 8 ---- src/uucore/src/lib/lib.rs | 5 ++- src/uucore/src/lib/macros.rs | 55 ---------------------------- 6 files changed, 39 insertions(+), 96 deletions(-) diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index 0602f0deec7..329b06d3681 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -16,7 +16,7 @@ use clap::{crate_version, Arg, ArgAction, ArgMatches, Command}; use regex::Regex; use uucore::display::Quotable; use uucore::error::{FromIo, UResult}; -use uucore::{crash_if_err, format_usage, help_about, help_section, help_usage}; +use uucore::{format_usage, help_about, help_section, help_usage}; mod csplit_error; mod patterns; @@ -51,26 +51,23 @@ pub struct CsplitOptions { } impl CsplitOptions { - fn new(matches: &ArgMatches) -> Self { + fn new(matches: &ArgMatches) -> Result { let keep_files = matches.get_flag(options::KEEP_FILES); let quiet = matches.get_flag(options::QUIET); let elide_empty_files = matches.get_flag(options::ELIDE_EMPTY_FILES); let suppress_matched = matches.get_flag(options::SUPPRESS_MATCHED); - Self { - split_name: crash_if_err!( - 1, - SplitName::new( - matches.get_one::(options::PREFIX).cloned(), - matches.get_one::(options::SUFFIX_FORMAT).cloned(), - matches.get_one::(options::DIGITS).cloned() - ) - ), + Ok(Self { + split_name: SplitName::new( + matches.get_one::(options::PREFIX).cloned(), + matches.get_one::(options::SUFFIX_FORMAT).cloned(), + matches.get_one::(options::DIGITS).cloned(), + )?, keep_files, quiet, elide_empty_files, suppress_matched, - } + }) } } @@ -561,7 +558,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .unwrap() .map(|s| s.to_string()) .collect(); - let options = CsplitOptions::new(&matches); + let options = CsplitOptions::new(&matches)?; if file_name == "-" { let stdin = io::stdin(); Ok(csplit(&options, &patterns, stdin.lock())?) diff --git a/src/uu/join/src/join.rs b/src/uu/join/src/join.rs index f01f75b71d5..01e1b40fc4a 100644 --- a/src/uu/join/src/join.rs +++ b/src/uu/join/src/join.rs @@ -20,7 +20,7 @@ use std::os::unix::ffi::OsStrExt; use uucore::display::Quotable; use uucore::error::{set_exit_code, FromIo, UError, UResult, USimpleError}; use uucore::line_ending::LineEnding; -use uucore::{crash_if_err, format_usage, help_about, help_usage}; +use uucore::{format_usage, help_about, help_usage}; const ABOUT: &str = help_about!("join.md"); const USAGE: &str = help_usage!("join.md"); @@ -587,15 +587,19 @@ impl<'a> State<'a> { !self.seq.is_empty() } - fn initialize(&mut self, read_sep: &Sep, autoformat: bool) -> usize { - if let Some(line) = crash_if_err!(1, self.read_line(read_sep)) { + fn initialize( + &mut self, + read_sep: &Sep, + autoformat: bool, + ) -> std::io::Result { + if let Some(line) = self.read_line(read_sep)? { self.seq.push(line); if autoformat { - return self.seq[0].field_ranges.len(); + return Ok(self.seq[0].field_ranges.len()); } } - 0 + Ok(0) } fn finalize( @@ -1008,20 +1012,21 @@ fn exec(file1: &str, file2: &str, settings: Settings, sep: Sep) let format = if settings.autoformat { let mut format = vec![Spec::Key]; - let mut initialize = |state: &mut State| { - let max_fields = state.initialize(&sep, settings.autoformat); + let mut initialize = |state: &mut State| -> UResult<()> { + let max_fields = state.initialize(&sep, settings.autoformat)?; for i in 0..max_fields { if i != state.key { format.push(Spec::Field(state.file_num, i)); } } + Ok(()) }; - initialize(&mut state1); - initialize(&mut state2); + initialize(&mut state1)?; + initialize(&mut state2)?; format } else { - state1.initialize(&sep, settings.autoformat); - state2.initialize(&sep, settings.autoformat); + state1.initialize(&sep, settings.autoformat)?; + state2.initialize(&sep, settings.autoformat)?; settings.format }; diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 7336376eb6c..1e8cede37dd 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -16,7 +16,7 @@ use std::str::from_utf8; use unicode_width::UnicodeWidthChar; use uucore::display::Quotable; use uucore::error::{FromIo, UError, UResult, USimpleError}; -use uucore::{crash_if_err, format_usage, help_about, help_usage, show}; +use uucore::{format_usage, help_about, help_usage, show}; const USAGE: &str = help_usage!("unexpand.md"); const ABOUT: &str = help_about!("unexpand.md"); @@ -244,7 +244,7 @@ fn write_tabs( prevtab: bool, init: bool, amode: bool, -) { +) -> UResult<()> { // This conditional establishes the following: // We never turn a single space before a non-blank into // a tab, unless it's at the start of the line. @@ -255,15 +255,16 @@ fn write_tabs( break; } - crash_if_err!(1, output.write_all(b"\t")); + output.write_all(b"\t")?; scol += nts; } } while col > scol { - crash_if_err!(1, output.write_all(b" ")); + output.write_all(b" ")?; scol += 1; } + Ok(()) } #[derive(PartialEq, Eq, Debug)] @@ -325,7 +326,7 @@ fn unexpand_line( options: &Options, lastcol: usize, ts: &[usize], -) -> std::io::Result<()> { +) -> UResult<()> { let mut byte = 0; // offset into the buffer let mut col = 0; // the current column let mut scol = 0; // the start col for the current span, i.e., the already-printed width @@ -335,7 +336,7 @@ fn unexpand_line( while byte < buf.len() { // when we have a finite number of columns, never convert past the last column if lastcol > 0 && col >= lastcol { - write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true); + write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true)?; output.write_all(&buf[byte..])?; scol = col; break; @@ -370,7 +371,7 @@ fn unexpand_line( pctype == CharType::Tab, init, options.aflag, - ); + )?; init = false; // no longer at the start of a line col = if ctype == CharType::Other { // use computed width @@ -391,7 +392,7 @@ fn unexpand_line( } // write out anything remaining - write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true); + write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true)?; output.flush()?; buf.truncate(0); // clear out the buffer diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index c161db39fc7..e7af62a657a 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -597,14 +597,6 @@ impl FsUsage { &mut total_number_of_clusters, ) }; - if 0 == success { - // Fails in case of CD for example - // crash!( - // EXIT_ERR, - // "GetDiskFreeSpaceW failed: {}", - // IOError::last_os_error() - // ); - } let bytes_per_cluster = sectors_per_cluster as u64 * bytes_per_sector as u64; Ok(Self { diff --git a/src/uucore/src/lib/lib.rs b/src/uucore/src/lib/lib.rs index 684de8f74e0..9516b5e1bf6 100644 --- a/src/uucore/src/lib/lib.rs +++ b/src/uucore/src/lib/lib.rs @@ -380,7 +380,10 @@ macro_rules! prompt_yes( eprint!("{}: ", uucore::util_name()); eprint!($($args)+); eprint!(" "); - uucore::crash_if_err!(1, std::io::stderr().flush()); + let res = std::io::stderr().flush().map_err(|err| { + $crate::error::USimpleError::new(1, err.to_string()) + }); + uucore::show_if_err!(res); uucore::read_yes() }) ); diff --git a/src/uucore/src/lib/macros.rs b/src/uucore/src/lib/macros.rs index 6fe60053886..e4e0ea325e3 100644 --- a/src/uucore/src/lib/macros.rs +++ b/src/uucore/src/lib/macros.rs @@ -31,7 +31,6 @@ //! - From custom messages: [`crate::show_error!`] //! - Print warnings: [`crate::show_warning!`] //! - Terminate util execution -//! - Crash program: [`crate::crash!`], [`crate::crash_if_err!`] // spell-checker:ignore sourcepath targetpath rustdoc @@ -189,57 +188,3 @@ macro_rules! show_warning_caps( eprintln!($($args)+); }) ); - -/// Display an error and [`std::process::exit`] -/// -/// Displays the provided error message using [`show_error!`], then invokes -/// [`std::process::exit`] with the provided exit code. -/// -/// # Examples -/// -/// ```should_panic -/// # #[macro_use] -/// # extern crate uucore; -/// # fn main() { -/// // outputs : Couldn't apply foo to bar -/// // and terminates execution -/// crash!(1, "Couldn't apply {} to {}", "foo", "bar"); -/// # } -/// ``` -#[macro_export] -macro_rules! crash( - ($exit_code:expr, $($args:tt)+) => ({ - $crate::show_error!($($args)+); - std::process::exit($exit_code); - }) -); - -/// Unwrap a [`std::result::Result`], crashing instead of panicking. -/// -/// If the result is an `Ok`-variant, returns the value contained inside. If it -/// is an `Err`-variant, invokes [`crash!`] with the formatted error instead. -/// -/// # Examples -/// -/// ```should_panic -/// # #[macro_use] -/// # extern crate uucore; -/// # fn main() { -/// let is_ok: Result = Ok(1); -/// // Does nothing -/// crash_if_err!(1, is_ok); -/// -/// let is_err: Result = Err("This didn't work..."); -/// // Calls `crash!` -/// crash_if_err!(1, is_err); -/// # } -/// ``` -#[macro_export] -macro_rules! crash_if_err( - ($exit_code:expr, $exp:expr) => ( - match $exp { - Ok(m) => m, - Err(f) => $crate::crash!($exit_code, "{}", f), - } - ) -);