Skip to content

Commit 72bdee0

Browse files
authored
Merge pull request #7084 from saulvaldelvira/main
Remove crash! macro
2 parents beb7685 + 6f35be4 commit 72bdee0

File tree

6 files changed

+41
-99
lines changed

6 files changed

+41
-99
lines changed

src/uu/csplit/src/csplit.rs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use clap::{crate_version, Arg, ArgAction, ArgMatches, Command};
1616
use regex::Regex;
1717
use uucore::display::Quotable;
1818
use uucore::error::{FromIo, UResult};
19-
use uucore::{crash_if_err, format_usage, help_about, help_section, help_usage};
19+
use uucore::{format_usage, help_about, help_section, help_usage};
2020

2121
mod csplit_error;
2222
mod patterns;
@@ -51,26 +51,23 @@ pub struct CsplitOptions {
5151
}
5252

5353
impl CsplitOptions {
54-
fn new(matches: &ArgMatches) -> Self {
54+
fn new(matches: &ArgMatches) -> Result<Self, CsplitError> {
5555
let keep_files = matches.get_flag(options::KEEP_FILES);
5656
let quiet = matches.get_flag(options::QUIET);
5757
let elide_empty_files = matches.get_flag(options::ELIDE_EMPTY_FILES);
5858
let suppress_matched = matches.get_flag(options::SUPPRESS_MATCHED);
5959

60-
Self {
61-
split_name: crash_if_err!(
62-
1,
63-
SplitName::new(
64-
matches.get_one::<String>(options::PREFIX).cloned(),
65-
matches.get_one::<String>(options::SUFFIX_FORMAT).cloned(),
66-
matches.get_one::<String>(options::DIGITS).cloned()
67-
)
68-
),
60+
Ok(Self {
61+
split_name: SplitName::new(
62+
matches.get_one::<String>(options::PREFIX).cloned(),
63+
matches.get_one::<String>(options::SUFFIX_FORMAT).cloned(),
64+
matches.get_one::<String>(options::DIGITS).cloned(),
65+
)?,
6966
keep_files,
7067
quiet,
7168
elide_empty_files,
7269
suppress_matched,
73-
}
70+
})
7471
}
7572
}
7673

@@ -561,7 +558,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
561558
.unwrap()
562559
.map(|s| s.to_string())
563560
.collect();
564-
let options = CsplitOptions::new(&matches);
561+
let options = CsplitOptions::new(&matches)?;
565562
if file_name == "-" {
566563
let stdin = io::stdin();
567564
Ok(csplit(&options, &patterns, stdin.lock())?)

src/uu/join/src/join.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use std::os::unix::ffi::OsStrExt;
2020
use uucore::display::Quotable;
2121
use uucore::error::{set_exit_code, FromIo, UError, UResult, USimpleError};
2222
use uucore::line_ending::LineEnding;
23-
use uucore::{crash_if_err, format_usage, help_about, help_usage};
23+
use uucore::{format_usage, help_about, help_usage};
2424

2525
const ABOUT: &str = help_about!("join.md");
2626
const USAGE: &str = help_usage!("join.md");
@@ -587,15 +587,19 @@ impl<'a> State<'a> {
587587
!self.seq.is_empty()
588588
}
589589

590-
fn initialize<Sep: Separator>(&mut self, read_sep: &Sep, autoformat: bool) -> usize {
591-
if let Some(line) = crash_if_err!(1, self.read_line(read_sep)) {
590+
fn initialize<Sep: Separator>(
591+
&mut self,
592+
read_sep: &Sep,
593+
autoformat: bool,
594+
) -> std::io::Result<usize> {
595+
if let Some(line) = self.read_line(read_sep)? {
592596
self.seq.push(line);
593597

594598
if autoformat {
595-
return self.seq[0].field_ranges.len();
599+
return Ok(self.seq[0].field_ranges.len());
596600
}
597601
}
598-
0
602+
Ok(0)
599603
}
600604

601605
fn finalize<Sep: Separator>(
@@ -1008,20 +1012,21 @@ fn exec<Sep: Separator>(file1: &str, file2: &str, settings: Settings, sep: Sep)
10081012

10091013
let format = if settings.autoformat {
10101014
let mut format = vec![Spec::Key];
1011-
let mut initialize = |state: &mut State| {
1012-
let max_fields = state.initialize(&sep, settings.autoformat);
1015+
let mut initialize = |state: &mut State| -> UResult<()> {
1016+
let max_fields = state.initialize(&sep, settings.autoformat)?;
10131017
for i in 0..max_fields {
10141018
if i != state.key {
10151019
format.push(Spec::Field(state.file_num, i));
10161020
}
10171021
}
1022+
Ok(())
10181023
};
1019-
initialize(&mut state1);
1020-
initialize(&mut state2);
1024+
initialize(&mut state1)?;
1025+
initialize(&mut state2)?;
10211026
format
10221027
} else {
1023-
state1.initialize(&sep, settings.autoformat);
1024-
state2.initialize(&sep, settings.autoformat);
1028+
state1.initialize(&sep, settings.autoformat)?;
1029+
state2.initialize(&sep, settings.autoformat)?;
10251030
settings.format
10261031
};
10271032

src/uu/unexpand/src/unexpand.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::str::from_utf8;
1616
use unicode_width::UnicodeWidthChar;
1717
use uucore::display::Quotable;
1818
use uucore::error::{FromIo, UError, UResult, USimpleError};
19-
use uucore::{crash_if_err, format_usage, help_about, help_usage, show};
19+
use uucore::{format_usage, help_about, help_usage, show};
2020

2121
const USAGE: &str = help_usage!("unexpand.md");
2222
const ABOUT: &str = help_about!("unexpand.md");
@@ -244,7 +244,7 @@ fn write_tabs(
244244
prevtab: bool,
245245
init: bool,
246246
amode: bool,
247-
) {
247+
) -> UResult<()> {
248248
// This conditional establishes the following:
249249
// We never turn a single space before a non-blank into
250250
// a tab, unless it's at the start of the line.
@@ -255,15 +255,16 @@ fn write_tabs(
255255
break;
256256
}
257257

258-
crash_if_err!(1, output.write_all(b"\t"));
258+
output.write_all(b"\t")?;
259259
scol += nts;
260260
}
261261
}
262262

263263
while col > scol {
264-
crash_if_err!(1, output.write_all(b" "));
264+
output.write_all(b" ")?;
265265
scol += 1;
266266
}
267+
Ok(())
267268
}
268269

269270
#[derive(PartialEq, Eq, Debug)]
@@ -325,7 +326,7 @@ fn unexpand_line(
325326
options: &Options,
326327
lastcol: usize,
327328
ts: &[usize],
328-
) -> std::io::Result<()> {
329+
) -> UResult<()> {
329330
let mut byte = 0; // offset into the buffer
330331
let mut col = 0; // the current column
331332
let mut scol = 0; // the start col for the current span, i.e., the already-printed width
@@ -335,7 +336,7 @@ fn unexpand_line(
335336
while byte < buf.len() {
336337
// when we have a finite number of columns, never convert past the last column
337338
if lastcol > 0 && col >= lastcol {
338-
write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true);
339+
write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true)?;
339340
output.write_all(&buf[byte..])?;
340341
scol = col;
341342
break;
@@ -370,7 +371,7 @@ fn unexpand_line(
370371
pctype == CharType::Tab,
371372
init,
372373
options.aflag,
373-
);
374+
)?;
374375
init = false; // no longer at the start of a line
375376
col = if ctype == CharType::Other {
376377
// use computed width
@@ -391,7 +392,7 @@ fn unexpand_line(
391392
}
392393

393394
// write out anything remaining
394-
write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true);
395+
write_tabs(output, ts, scol, col, pctype == CharType::Tab, init, true)?;
395396
output.flush()?;
396397
buf.truncate(0); // clear out the buffer
397398

src/uucore/src/lib/features/fsext.rs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -587,23 +587,15 @@ impl FsUsage {
587587
let mut number_of_free_clusters = 0;
588588
let mut total_number_of_clusters = 0;
589589

590-
let success = unsafe {
590+
unsafe {
591591
let path = to_nul_terminated_wide_string(path);
592592
GetDiskFreeSpaceW(
593593
path.as_ptr(),
594594
&mut sectors_per_cluster,
595595
&mut bytes_per_sector,
596596
&mut number_of_free_clusters,
597597
&mut total_number_of_clusters,
598-
)
599-
};
600-
if 0 == success {
601-
// Fails in case of CD for example
602-
// crash!(
603-
// EXIT_ERR,
604-
// "GetDiskFreeSpaceW failed: {}",
605-
// IOError::last_os_error()
606-
// );
598+
);
607599
}
608600

609601
let bytes_per_cluster = sectors_per_cluster as u64 * bytes_per_sector as u64;

src/uucore/src/lib/lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,10 @@ macro_rules! prompt_yes(
380380
eprint!("{}: ", uucore::util_name());
381381
eprint!($($args)+);
382382
eprint!(" ");
383-
uucore::crash_if_err!(1, std::io::stderr().flush());
383+
let res = std::io::stderr().flush().map_err(|err| {
384+
$crate::error::USimpleError::new(1, err.to_string())
385+
});
386+
uucore::show_if_err!(res);
384387
uucore::read_yes()
385388
})
386389
);

src/uucore/src/lib/macros.rs

Lines changed: 0 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@
3030
//! [`crate::show_if_err!`]
3131
//! - From custom messages: [`crate::show_error!`]
3232
//! - Print warnings: [`crate::show_warning!`]
33-
//! - Terminate util execution
34-
//! - Crash program: [`crate::crash!`], [`crate::crash_if_err!`]
3533
3634
// spell-checker:ignore sourcepath targetpath rustdoc
3735

@@ -189,57 +187,3 @@ macro_rules! show_warning_caps(
189187
eprintln!($($args)+);
190188
})
191189
);
192-
193-
/// Display an error and [`std::process::exit`]
194-
///
195-
/// Displays the provided error message using [`show_error!`], then invokes
196-
/// [`std::process::exit`] with the provided exit code.
197-
///
198-
/// # Examples
199-
///
200-
/// ```should_panic
201-
/// # #[macro_use]
202-
/// # extern crate uucore;
203-
/// # fn main() {
204-
/// // outputs <name>: Couldn't apply foo to bar
205-
/// // and terminates execution
206-
/// crash!(1, "Couldn't apply {} to {}", "foo", "bar");
207-
/// # }
208-
/// ```
209-
#[macro_export]
210-
macro_rules! crash(
211-
($exit_code:expr, $($args:tt)+) => ({
212-
$crate::show_error!($($args)+);
213-
std::process::exit($exit_code);
214-
})
215-
);
216-
217-
/// Unwrap a [`std::result::Result`], crashing instead of panicking.
218-
///
219-
/// If the result is an `Ok`-variant, returns the value contained inside. If it
220-
/// is an `Err`-variant, invokes [`crash!`] with the formatted error instead.
221-
///
222-
/// # Examples
223-
///
224-
/// ```should_panic
225-
/// # #[macro_use]
226-
/// # extern crate uucore;
227-
/// # fn main() {
228-
/// let is_ok: Result<u32, &str> = Ok(1);
229-
/// // Does nothing
230-
/// crash_if_err!(1, is_ok);
231-
///
232-
/// let is_err: Result<u32, &str> = Err("This didn't work...");
233-
/// // Calls `crash!`
234-
/// crash_if_err!(1, is_err);
235-
/// # }
236-
/// ```
237-
#[macro_export]
238-
macro_rules! crash_if_err(
239-
($exit_code:expr, $exp:expr) => (
240-
match $exp {
241-
Ok(m) => m,
242-
Err(f) => $crate::crash!($exit_code, "{}", f),
243-
}
244-
)
245-
);

0 commit comments

Comments
 (0)