Skip to content

Commit fe286fa

Browse files
authored
Merge pull request #2749 from thomasqueirozb/utils_uresult
basename+date+fold+nl+nproc+shuf+uname: use UResult
2 parents 1d794e1 + ed3e6b5 commit fe286fa

File tree

7 files changed

+145
-123
lines changed

7 files changed

+145
-123
lines changed

src/uu/basename/src/basename.rs

+17-16
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,10 @@
77

88
// spell-checker:ignore (ToDO) fullname
99

10-
#[macro_use]
11-
extern crate uucore;
12-
1310
use clap::{crate_version, App, Arg};
1411
use std::path::{is_separator, PathBuf};
12+
use uucore::display::Quotable;
13+
use uucore::error::{UResult, UUsageError};
1514
use uucore::InvalidEncodingHandling;
1615

1716
static SUMMARY: &str = "Print NAME with any leading directory components removed
@@ -32,7 +31,8 @@ pub mod options {
3231
pub static ZERO: &str = "zero";
3332
}
3433

35-
pub fn uumain(args: impl uucore::Args) -> i32 {
34+
#[uucore_procs::gen_uumain]
35+
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
3636
let args = args
3737
.collect_str(InvalidEncodingHandling::ConvertLossy)
3838
.accept_any();
@@ -44,12 +44,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
4444

4545
// too few arguments
4646
if !matches.is_present(options::NAME) {
47-
crash!(
48-
1,
49-
"{1}\nTry '{0} --help' for more information.",
50-
uucore::execution_phrase(),
51-
"missing operand"
52-
);
47+
return Err(UUsageError::new(1, "missing operand".to_string()));
5348
}
5449

5550
let opt_suffix = matches.is_present(options::SUFFIX);
@@ -58,12 +53,18 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
5853
let multiple_paths = opt_suffix || opt_multiple;
5954
// too many arguments
6055
if !multiple_paths && matches.occurrences_of(options::NAME) > 2 {
61-
crash!(
56+
return Err(UUsageError::new(
6257
1,
63-
"extra operand '{1}'\nTry '{0} --help' for more information.",
64-
uucore::execution_phrase(),
65-
matches.values_of(options::NAME).unwrap().nth(2).unwrap()
66-
);
58+
format!(
59+
"extra operand {}",
60+
matches
61+
.values_of(options::NAME)
62+
.unwrap()
63+
.nth(2)
64+
.unwrap()
65+
.quote()
66+
),
67+
));
6768
}
6869

6970
let suffix = if opt_suffix {
@@ -89,7 +90,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
8990
print!("{}{}", basename(path, suffix), line_ending);
9091
}
9192

92-
0
93+
Ok(())
9394
}
9495

9596
pub fn uu_app() -> App<'static, 'static> {

src/uu/date/src/date.rs

+32-26
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ use std::fs::File;
1818
use std::io::{BufRead, BufReader};
1919
use std::path::PathBuf;
2020
use uucore::display::Quotable;
21+
#[cfg(not(any(target_os = "macos", target_os = "redox")))]
22+
use uucore::error::FromIo;
23+
use uucore::error::{UResult, USimpleError};
2124
use uucore::show_error;
2225
#[cfg(windows)]
2326
use winapi::{
@@ -137,7 +140,8 @@ impl<'a> From<&'a str> for Rfc3339Format {
137140
}
138141
}
139142

140-
pub fn uumain(args: impl uucore::Args) -> i32 {
143+
#[uucore_procs::gen_uumain]
144+
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
141145
let syntax = format!(
142146
"{0} [OPTION]... [+FORMAT]...
143147
{0} [OPTION]... [MMDDhhmm[[CC]YY][.ss]]",
@@ -147,8 +151,10 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
147151

148152
let format = if let Some(form) = matches.value_of(OPT_FORMAT) {
149153
if !form.starts_with('+') {
150-
show_error!("invalid date {}", form.quote());
151-
return 1;
154+
return Err(USimpleError::new(
155+
1,
156+
format!("invalid date {}", form.quote()),
157+
));
152158
}
153159
let form = form[1..].to_string();
154160
Format::Custom(form)
@@ -176,8 +182,10 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
176182
let set_to = match matches.value_of(OPT_SET).map(parse_date) {
177183
None => None,
178184
Some(Err((input, _err))) => {
179-
show_error!("invalid date {}", input.quote());
180-
return 1;
185+
return Err(USimpleError::new(
186+
1,
187+
format!("invalid date {}", input.quote()),
188+
));
181189
}
182190
Some(Ok(date)) => Some(date),
183191
};
@@ -241,14 +249,12 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
241249
let formatted = date.format(format_string).to_string().replace("%f", "%N");
242250
println!("{}", formatted);
243251
}
244-
Err((input, _err)) => {
245-
show_error!("invalid date {}", input.quote());
246-
}
252+
Err((input, _err)) => show_error!("invalid date {}", input.quote()),
247253
}
248254
}
249255
}
250256

251-
0
257+
Ok(())
252258
}
253259

254260
pub fn uu_app() -> App<'static, 'static> {
@@ -348,20 +354,24 @@ fn parse_date<S: AsRef<str> + Clone>(
348354
}
349355

350356
#[cfg(not(any(unix, windows)))]
351-
fn set_system_datetime(_date: DateTime<Utc>) -> i32 {
357+
fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> {
352358
unimplemented!("setting date not implemented (unsupported target)");
353359
}
354360

355361
#[cfg(target_os = "macos")]
356-
fn set_system_datetime(_date: DateTime<Utc>) -> i32 {
357-
show_error!("setting the date is not supported by macOS");
358-
1
362+
fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> {
363+
Err(USimpleError::new(
364+
1,
365+
"setting the date is not supported by macOS".to_string(),
366+
))
359367
}
360368

361369
#[cfg(target_os = "redox")]
362-
fn set_system_datetime(_date: DateTime<Utc>) -> i32 {
363-
show_error!("setting the date is not supported by Redox");
364-
1
370+
fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> {
371+
Err(USimpleError::new(
372+
1,
373+
"setting the date is not supported by Redox".to_string(),
374+
))
365375
}
366376

367377
#[cfg(all(unix, not(target_os = "macos"), not(target_os = "redox")))]
@@ -370,7 +380,7 @@ fn set_system_datetime(_date: DateTime<Utc>) -> i32 {
370380
/// https://doc.rust-lang.org/libc/i686-unknown-linux-gnu/libc/fn.clock_settime.html
371381
/// https://linux.die.net/man/3/clock_settime
372382
/// https://www.gnu.org/software/libc/manual/html_node/Time-Types.html
373-
fn set_system_datetime(date: DateTime<Utc>) -> i32 {
383+
fn set_system_datetime(date: DateTime<Utc>) -> UResult<()> {
374384
let timespec = timespec {
375385
tv_sec: date.timestamp() as _,
376386
tv_nsec: date.timestamp_subsec_nanos() as _,
@@ -379,11 +389,9 @@ fn set_system_datetime(date: DateTime<Utc>) -> i32 {
379389
let result = unsafe { clock_settime(CLOCK_REALTIME, &timespec) };
380390

381391
if result != 0 {
382-
let error = std::io::Error::last_os_error();
383-
show_error!("cannot set date: {}", error);
384-
error.raw_os_error().unwrap()
392+
Err(std::io::Error::last_os_error().map_err_context(|| "cannot set date".to_string()))
385393
} else {
386-
0
394+
Ok(())
387395
}
388396
}
389397

@@ -392,7 +400,7 @@ fn set_system_datetime(date: DateTime<Utc>) -> i32 {
392400
/// See here for more:
393401
/// https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setsystemtime
394402
/// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime
395-
fn set_system_datetime(date: DateTime<Utc>) -> i32 {
403+
fn set_system_datetime(date: DateTime<Utc>) -> UResult<()> {
396404
let system_time = SYSTEMTIME {
397405
wYear: date.year() as WORD,
398406
wMonth: date.month() as WORD,
@@ -409,10 +417,8 @@ fn set_system_datetime(date: DateTime<Utc>) -> i32 {
409417
let result = unsafe { SetSystemTime(&system_time) };
410418

411419
if result == 0 {
412-
let error = std::io::Error::last_os_error();
413-
show_error!("cannot set date: {}", error);
414-
error.raw_os_error().unwrap()
420+
Err(std::io::Error::last_os_error().map_err_context(|| "cannot set date".to_string()))
415421
} else {
416-
0
422+
Ok(())
417423
}
418424
}

src/uu/fold/src/fold.rs

+32-19
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,12 @@
77

88
// spell-checker:ignore (ToDOs) ncount routput
99

10-
#[macro_use]
11-
extern crate uucore;
12-
1310
use clap::{crate_version, App, Arg};
1411
use std::fs::File;
1512
use std::io::{stdin, BufRead, BufReader, Read};
1613
use std::path::Path;
14+
use uucore::display::Quotable;
15+
use uucore::error::{FromIo, UResult, USimpleError};
1716
use uucore::InvalidEncodingHandling;
1817

1918
const TAB_WIDTH: usize = 8;
@@ -30,7 +29,8 @@ mod options {
3029
pub const FILE: &str = "file";
3130
}
3231

33-
pub fn uumain(args: impl uucore::Args) -> i32 {
32+
#[uucore_procs::gen_uumain]
33+
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
3434
let args = args
3535
.collect_str(InvalidEncodingHandling::ConvertLossy)
3636
.accept_any();
@@ -46,10 +46,12 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
4646
};
4747

4848
let width = match poss_width {
49-
Some(inp_width) => match inp_width.parse::<usize>() {
50-
Ok(width) => width,
51-
Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e),
52-
},
49+
Some(inp_width) => inp_width.parse::<usize>().map_err(|e| {
50+
USimpleError::new(
51+
1,
52+
format!("illegal width value ({}): {}", inp_width.quote(), e),
53+
)
54+
})?,
5355
None => 80,
5456
};
5557

@@ -58,9 +60,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
5860
None => vec!["-".to_owned()],
5961
};
6062

61-
fold(files, bytes, spaces, width);
62-
63-
0
63+
fold(files, bytes, spaces, width)
6464
}
6565

6666
pub fn uu_app() -> App<'static, 'static> {
@@ -110,7 +110,7 @@ fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
110110
(args.to_vec(), None)
111111
}
112112

113-
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
113+
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) -> UResult<()> {
114114
for filename in &filenames {
115115
let filename: &str = filename;
116116
let mut stdin_buf;
@@ -119,16 +119,17 @@ fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
119119
stdin_buf = stdin();
120120
&mut stdin_buf as &mut dyn Read
121121
} else {
122-
file_buf = crash_if_err!(1, File::open(Path::new(filename)));
122+
file_buf = File::open(Path::new(filename)).map_err_context(|| filename.to_string())?;
123123
&mut file_buf as &mut dyn Read
124124
});
125125

126126
if bytes {
127-
fold_file_bytewise(buffer, spaces, width);
127+
fold_file_bytewise(buffer, spaces, width)?;
128128
} else {
129-
fold_file(buffer, spaces, width);
129+
fold_file(buffer, spaces, width)?;
130130
}
131131
}
132+
Ok(())
132133
}
133134

134135
/// Fold `file` to fit `width` (number of columns), counting all characters as
@@ -139,11 +140,15 @@ fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
139140
/// to all other characters in the stream.
140141
///
141142
/// If `spaces` is `true`, attempt to break lines at whitespace boundaries.
142-
fn fold_file_bytewise<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) {
143+
fn fold_file_bytewise<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) -> UResult<()> {
143144
let mut line = String::new();
144145

145146
loop {
146-
if let Ok(0) = file.read_line(&mut line) {
147+
if file
148+
.read_line(&mut line)
149+
.map_err_context(|| "failed to read line".to_string())?
150+
== 0
151+
{
147152
break;
148153
}
149154

@@ -190,6 +195,8 @@ fn fold_file_bytewise<T: Read>(mut file: BufReader<T>, spaces: bool, width: usiz
190195

191196
line.truncate(0);
192197
}
198+
199+
Ok(())
193200
}
194201

195202
/// Fold `file` to fit `width` (number of columns).
@@ -200,7 +207,7 @@ fn fold_file_bytewise<T: Read>(mut file: BufReader<T>, spaces: bool, width: usiz
200207
///
201208
/// If `spaces` is `true`, attempt to break lines at whitespace boundaries.
202209
#[allow(unused_assignments)]
203-
fn fold_file<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) {
210+
fn fold_file<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) -> UResult<()> {
204211
let mut line = String::new();
205212
let mut output = String::new();
206213
let mut col_count = 0;
@@ -230,7 +237,11 @@ fn fold_file<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) {
230237
}
231238

232239
loop {
233-
if let Ok(0) = file.read_line(&mut line) {
240+
if file
241+
.read_line(&mut line)
242+
.map_err_context(|| "failed to read line".to_string())?
243+
== 0
244+
{
234245
break;
235246
}
236247

@@ -281,4 +292,6 @@ fn fold_file<T: Read>(mut file: BufReader<T>, spaces: bool, width: usize) {
281292

282293
line.truncate(0);
283294
}
295+
296+
Ok(())
284297
}

0 commit comments

Comments
 (0)