diff --git a/src/uu/base32/src/base_common.rs b/src/uu/base32/src/base_common.rs index ee5fe8675..256b674e2 100644 --- a/src/uu/base32/src/base_common.rs +++ b/src/uu/base32/src/base_common.rs @@ -54,15 +54,13 @@ impl Config { None => None, }; - let cols = match options.value_of(options::WRAP) { - Some(num) => match num.parse::() { - Ok(n) => Some(n), - Err(e) => { - return Err(format!("Invalid wrap size: ‘{}’: {}", num, e)); - } - }, - None => None, - }; + let cols = options + .value_of(options::WRAP) + .map(|num| { + num.parse::() + .map_err(|e| format!("Invalid wrap size: ‘{}’: {}", num, e)) + }) + .transpose()?; Ok(Config { decode: options.is_present(options::DECODE), diff --git a/src/uu/chown/src/chown.rs b/src/uu/chown/src/chown.rs index 649300d83..ab9f10dba 100644 --- a/src/uu/chown/src/chown.rs +++ b/src/uu/chown/src/chown.rs @@ -278,37 +278,25 @@ fn parse_spec(spec: &str) -> Result<(Option, Option), String> { let usr_only = args.len() == 1 && !args[0].is_empty(); let grp_only = args.len() == 2 && args[0].is_empty(); let usr_grp = args.len() == 2 && !args[0].is_empty() && !args[1].is_empty(); - - if usr_only { - Ok(( - Some(match Passwd::locate(args[0]) { - Ok(v) => v.uid(), - _ => return Err(format!("invalid user: ‘{}’", spec)), - }), - None, - )) - } else if grp_only { - Ok(( - None, - Some(match Group::locate(args[1]) { - Ok(v) => v.gid(), - _ => return Err(format!("invalid group: ‘{}’", spec)), - }), - )) - } else if usr_grp { - Ok(( - Some(match Passwd::locate(args[0]) { - Ok(v) => v.uid(), - _ => return Err(format!("invalid user: ‘{}’", spec)), - }), - Some(match Group::locate(args[1]) { - Ok(v) => v.gid(), - _ => return Err(format!("invalid group: ‘{}’", spec)), - }), - )) + let uid = if usr_only || usr_grp { + Some( + Passwd::locate(args[0]) + .map_err(|_| format!("invalid user: ‘{}’", spec))? + .uid(), + ) } else { - Ok((None, None)) - } + None + }; + let gid = if grp_only || usr_grp { + Some( + Group::locate(args[1]) + .map_err(|_| format!("invalid group: ‘{}’", spec))? + .gid(), + ) + } else { + None + }; + Ok((uid, gid)) } enum IfFrom { @@ -497,3 +485,17 @@ impl Chowner { } } } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_spec() { + assert_eq!(parse_spec(":"), Ok((None, None))); + assert!(parse_spec("::") + .err() + .unwrap() + .starts_with("invalid group: ")); + } +} diff --git a/src/uu/cksum/src/cksum.rs b/src/uu/cksum/src/cksum.rs index 49c0536f5..6a812c186 100644 --- a/src/uu/cksum/src/cksum.rs +++ b/src/uu/cksum/src/cksum.rs @@ -160,18 +160,14 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> { let mut bytes = init_byte_array(); loop { - match rd.read(&mut bytes) { - Ok(num_bytes) => { - if num_bytes == 0 { - return Ok((crc_final(crc, size), size)); - } - for &b in bytes[..num_bytes].iter() { - crc = crc_update(crc, b); - } - size += num_bytes; - } - Err(err) => return Err(err), + let num_bytes = rd.read(&mut bytes)?; + if num_bytes == 0 { + return Ok((crc_final(crc, size), size)); } + for &b in bytes[..num_bytes].iter() { + crc = crc_update(crc, b); + } + size += num_bytes; } } diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index cc0103044..a87e86b98 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -709,27 +709,26 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec { // All path args are sources, and the target dir was // specified separately - (paths, PathBuf::from(target)) + PathBuf::from(target) } None => { // If there was no explicit target-dir, then use the last // path_arg - let target = paths.pop().unwrap(); - (paths, target) + paths.pop().unwrap() } }; if options.strip_trailing_slashes { - for source in sources.iter_mut() { + for source in paths.iter_mut() { *source = source.components().as_path().to_owned() } } - Ok((sources, target)) + Ok((paths, target)) } fn preserve_hardlinks( @@ -1271,15 +1270,15 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes ReflinkMode::Always => unsafe { let result = ficlone(dst_file.as_raw_fd(), src_file.as_raw_fd() as *const i32); if result != 0 { - return Err(format!( + Err(format!( "failed to clone {:?} from {:?}: {}", source, dest, std::io::Error::last_os_error() ) - .into()); + .into()) } else { - return Ok(()); + Ok(()) } }, ReflinkMode::Auto => unsafe { @@ -1287,11 +1286,10 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes if result != 0 { fs::copy(source, dest).context(&*context_for(source, dest))?; } + Ok(()) }, ReflinkMode::Never => unreachable!(), } - - Ok(()) } /// Copies `source` to `dest` using copy-on-write if possible. diff --git a/src/uu/csplit/src/patterns.rs b/src/uu/csplit/src/patterns.rs index 5621d18a3..4ab7862ac 100644 --- a/src/uu/csplit/src/patterns.rs +++ b/src/uu/csplit/src/patterns.rs @@ -133,20 +133,12 @@ fn extract_patterns(args: &[String]) -> Result, CsplitError> { Some(m) => m.as_str().parse().unwrap(), }; if let Some(up_to_match) = captures.name("UPTO") { - let pattern = match Regex::new(up_to_match.as_str()) { - Err(_) => { - return Err(CsplitError::InvalidPattern(arg.to_string())); - } - Ok(reg) => reg, - }; + let pattern = Regex::new(up_to_match.as_str()) + .map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?; patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes)); } else if let Some(skip_to_match) = captures.name("SKIPTO") { - let pattern = match Regex::new(skip_to_match.as_str()) { - Err(_) => { - return Err(CsplitError::InvalidPattern(arg.to_string())); - } - Ok(reg) => reg, - }; + let pattern = Regex::new(skip_to_match.as_str()) + .map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?; patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes)); } } else if let Ok(line_number) = arg.parse::() { diff --git a/src/uu/csplit/src/split_name.rs b/src/uu/csplit/src/split_name.rs index 6db781e9b..758216414 100644 --- a/src/uu/csplit/src/split_name.rs +++ b/src/uu/csplit/src/split_name.rs @@ -33,13 +33,13 @@ impl SplitName { // get the prefix let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); // the width for the split offset - let n_digits = match n_digits_opt { - None => 2, - Some(opt) => match opt.parse::() { - Ok(digits) => digits, - Err(_) => return Err(CsplitError::InvalidNumber(opt)), - }, - }; + let n_digits = n_digits_opt + .map(|opt| { + opt.parse::() + .map_err(|_| CsplitError::InvalidNumber(opt)) + }) + .transpose()? + .unwrap_or(2); // translate the custom format into a function let fn_split_name: Box String> = match format_opt { None => Box::new(move |n: usize| -> String { diff --git a/src/uu/env/src/env.rs b/src/uu/env/src/env.rs index e20f047b7..0ea66d7e9 100644 --- a/src/uu/env/src/env.rs +++ b/src/uu/env/src/env.rs @@ -82,13 +82,10 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> { Ini::load_from_file(file) }; - let conf = match conf { - Ok(config) => config, - Err(error) => { - eprintln!("env: error: \"{}\": {}", file, error); - return Err(1); - } - }; + let conf = conf.map_err(|error| { + eprintln!("env: error: \"{}\": {}", file, error); + 1 + })?; for (_, prop) in &conf { // ignore all INI section lines (treat them as comments) @@ -256,13 +253,10 @@ fn run_env(args: impl uucore::Args) -> Result<(), i32> { // FIXME: this should just use execvp() (no fork()) on Unix-like systems match Command::new(&*prog).args(args).status() { - Ok(exit) => { - if !exit.success() { - return Err(exit.code().unwrap()); - } - } + Ok(exit) if !exit.success() => return Err(exit.code().unwrap()), Err(ref err) if err.kind() == io::ErrorKind::NotFound => return Err(127), Err(_) => return Err(126), + Ok(_) => (), } } else { // no program provided, so just dump all env vars to stdout diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index ba477414e..ff49ea57e 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -160,10 +160,8 @@ impl AstNode { if let AstNode::Node { operands, .. } = self { let mut out = Vec::with_capacity(operands.len()); for operand in operands { - match operand.evaluate() { - Ok(value) => out.push(value), - Err(reason) => return Err(reason), - } + let value = operand.evaluate()?; + out.push(value); } Ok(out) } else { @@ -252,10 +250,8 @@ fn maybe_ast_node( ) -> Result, String> { let mut operands = Vec::with_capacity(arity); for _ in 0..arity { - match ast_from_rpn(rpn) { - Err(reason) => return Err(reason), - Ok(operand) => operands.push(operand), - } + let operand = ast_from_rpn(rpn)?; + operands.push(operand); } operands.reverse(); Ok(AstNode::new_node(token_idx, op_type, operands)) @@ -399,10 +395,12 @@ fn move_till_match_paren( op_stack: &mut TokenStack, ) -> Result<(), String> { loop { - match op_stack.pop() { - None => return Err("syntax error (Mismatched close-parenthesis)".to_string()), - Some((_, Token::ParOpen)) => return Ok(()), - Some(other) => out_stack.push(other), + let op = op_stack + .pop() + .ok_or_else(|| "syntax error (Mismatched close-parenthesis)".to_string())?; + match op { + (_, Token::ParOpen) => return Ok(()), + other => out_stack.push(other), } } } @@ -462,22 +460,17 @@ fn infix_operator_and(values: &[String]) -> String { fn operator_match(values: &[String]) -> Result { assert!(values.len() == 2); - let re = match Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep()) - { - Ok(m) => m, - Err(err) => return Err(err.description().to_string()), - }; - if re.captures_len() > 0 { - Ok(match re.captures(&values[0]) { - Some(captures) => captures.at(1).unwrap().to_string(), - None => "".to_string(), - }) + let re = Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep()) + .map_err(|err| err.description().to_string())?; + Ok(if re.captures_len() > 0 { + re.captures(&values[0]) + .map(|captures| captures.at(1).unwrap()) + .unwrap_or("") + .to_string() } else { - Ok(match re.find(&values[0]) { - Some((start, end)) => (end - start).to_string(), - None => "0".to_string(), - }) - } + re.find(&values[0]) + .map_or("0".to_string(), |(start, end)| (end - start).to_string()) + }) } fn prefix_operator_length(values: &[String]) -> String { diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 28710e1fe..c6d2f98bd 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -176,19 +176,11 @@ impl HeadOptions { options.zeroed = matches.is_present(options::ZERO_NAME); let mode_and_from_end = if let Some(v) = matches.value_of(options::BYTES_NAME) { - match parse_mode(v, Modes::Bytes) { - Ok(v) => v, - Err(err) => { - return Err(format!("invalid number of bytes: {}", err)); - } - } + parse_mode(v, Modes::Bytes) + .map_err(|err| format!("invalid number of bytes: {}", err))? } else if let Some(v) = matches.value_of(options::LINES_NAME) { - match parse_mode(v, Modes::Lines) { - Ok(v) => v, - Err(err) => { - return Err(format!("invalid number of lines: {}", err)); - } - } + parse_mode(v, Modes::Lines) + .map_err(|err| format!("invalid number of lines: {}", err))? } else { (Modes::Lines(10), false) }; diff --git a/src/uu/head/src/parse.rs b/src/uu/head/src/parse.rs index f1c97561d..c04962f1b 100644 --- a/src/uu/head/src/parse.rs +++ b/src/uu/head/src/parse.rs @@ -94,17 +94,15 @@ pub fn parse_obsolete(src: &str) -> Option /// the bool specifies whether to read from the end pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> { let mut num_start = 0; - let mut chars = src.char_indices(); - let (mut chars, all_but_last) = match chars.next() { - Some((_, c)) => { - if c == '-' { - num_start += 1; - (chars, true) - } else { - (src.char_indices(), false) - } + let (mut chars, all_but_last) = { + let mut chars = src.char_indices(); + let (_, c) = chars.next().ok_or(ParseError::Syntax)?; + if c == '-' { + num_start += 1; + (chars, true) + } else { + (src.char_indices(), false) } - None => return Err(ParseError::Syntax), }; let mut num_end = 0usize; let mut last_char = 0 as char; @@ -120,10 +118,11 @@ pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> { } let num = if num_count > 0 { - match src[num_start..=num_end].parse::() { - Ok(n) => Some(n), - Err(_) => return Err(ParseError::Overflow), - } + Some( + src[num_start..=num_end] + .parse::() + .map_err(|_| ParseError::Overflow)?, + ) } else { None }; @@ -168,10 +167,7 @@ pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> { 'y' => base.pow(8), _ => return Err(ParseError::Syntax), }; - let mul = match usize::try_from(mul) { - Ok(n) => n, - Err(_) => return Err(ParseError::Overflow), - }; + let mul = usize::try_from(mul).map_err(|_| ParseError::Overflow)?; match num.unwrap_or(1).checked_mul(mul) { Some(n) => Ok((n, all_but_last)), None => Err(ParseError::Overflow), diff --git a/src/uu/install/src/install.rs b/src/uu/install/src/install.rs index bcfe1a396..ad5ea694c 100644 --- a/src/uu/install/src/install.rs +++ b/src/uu/install/src/install.rs @@ -299,29 +299,17 @@ fn behavior(matches: &ArgMatches) -> Result { let considering_dir: bool = MainFunction::Directory == main_function; let specified_mode: Option = if matches.is_present(OPT_MODE) { - match matches.value_of(OPT_MODE) { - Some(x) => match mode::parse(x, considering_dir) { - Ok(y) => Some(y), - Err(err) => { - show_error!("Invalid mode string: {}", err); - return Err(1); - } - }, - None => { - return Err(1); - } - } + let x = matches.value_of(OPT_MODE).ok_or(1)?; + Some(mode::parse(x, considering_dir).map_err(|err| { + show_error!("Invalid mode string: {}", err); + 1 + })?) } else { None }; let backup_suffix = if matches.is_present(OPT_SUFFIX) { - match matches.value_of(OPT_SUFFIX) { - Some(x) => x, - None => { - return Err(1); - } - } + matches.value_of(OPT_SUFFIX).ok_or(1)? } else { "~" }; diff --git a/src/uu/nl/src/nl.rs b/src/uu/nl/src/nl.rs index 41750259f..a3181e11f 100644 --- a/src/uu/nl/src/nl.rs +++ b/src/uu/nl/src/nl.rs @@ -247,7 +247,7 @@ fn nl(reader: &mut BufReader, settings: &Settings) { let mut line_filter: fn(&str, ®ex::Regex) -> bool = pass_regex; for mut l in reader.lines().map(|r| r.unwrap()) { // Sanitize the string. We want to print the newline ourselves. - if l.chars().last() == Some('\n') { + if l.ends_with('\n') { l.pop(); } // Next we iterate through the individual chars to see if this diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index 1e7b4533a..642618cac 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -128,36 +128,27 @@ impl OdOptions { } }; - let mut skip_bytes = match matches.value_of(options::SKIP_BYTES) { - None => 0, - Some(s) => match parse_number_of_bytes(s) { - Ok(i) => i, - Err(_) => { - return Err(format!("Invalid argument --skip-bytes={}", s)); - } - }, - }; + let mut skip_bytes = matches + .value_of(options::SKIP_BYTES) + .map(|s| { + parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --skip-bytes={}", s)) + }) + .transpose()? + .unwrap_or(0); let mut label: Option = None; - let input_strings = match parse_inputs(&matches) { - Ok(CommandLineInputs::FileNames(v)) => v, - Ok(CommandLineInputs::FileAndOffset((f, s, l))) => { + let parsed_input = parse_inputs(&matches).map_err(|e| format!("Invalid inputs: {}", e))?; + let input_strings = match parsed_input { + CommandLineInputs::FileNames(v) => v, + CommandLineInputs::FileAndOffset((f, s, l)) => { skip_bytes = s; label = l; vec![f] } - Err(e) => { - return Err(format!("Invalid inputs: {}", e)); - } }; - let formats = match parse_format_flags(&args) { - Ok(f) => f, - Err(e) => { - return Err(e); - } - }; + let formats = parse_format_flags(&args)?; let mut line_bytes = match matches.value_of(options::WIDTH) { None => 16, @@ -174,15 +165,12 @@ impl OdOptions { let output_duplicates = matches.is_present(options::OUTPUT_DUPLICATES); - let read_bytes = match matches.value_of(options::READ_BYTES) { - None => None, - Some(s) => match parse_number_of_bytes(s) { - Ok(i) => Some(i), - Err(_) => { - return Err(format!("Invalid argument --read-bytes={}", s)); - } - }, - }; + let read_bytes = matches + .value_of(options::READ_BYTES) + .map(|s| { + parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --read-bytes={}", s)) + }) + .transpose()?; let radix = match matches.value_of(options::ADDRESS_RADIX) { None => Radix::Octal, diff --git a/src/uu/od/src/parse_formats.rs b/src/uu/od/src/parse_formats.rs index fca908016..f5b150d61 100644 --- a/src/uu/od/src/parse_formats.rs +++ b/src/uu/od/src/parse_formats.rs @@ -108,10 +108,8 @@ pub fn parse_format_flags(args: &[String]) -> Result formats.extend(v.into_iter()), - Err(e) => return Err(e), - } + let v = parse_type_string(arg)?; + formats.extend(v.into_iter()); expect_type_string = false; } else if arg.starts_with("--") { if arg.len() == 2 { @@ -119,10 +117,8 @@ pub fn parse_format_flags(args: &[String]) -> Result Result formats.extend(v.into_iter()), - Err(e) => return Err(e), - } + let v = parse_type_string(&format_spec)?; + formats.extend(v.into_iter()); expect_type_string = false; } } diff --git a/src/uu/od/src/partialreader.rs b/src/uu/od/src/partialreader.rs index ee3588830..f155a7bd2 100644 --- a/src/uu/od/src/partialreader.rs +++ b/src/uu/od/src/partialreader.rs @@ -36,16 +36,15 @@ impl Read for PartialReader { while self.skip > 0 { let skip_count = cmp::min(self.skip, MAX_SKIP_BUFFER); - match self.inner.read(&mut bytes[..skip_count]) { - Ok(0) => { + match self.inner.read(&mut bytes[..skip_count])? { + 0 => { // this is an error as we still have more to skip return Err(io::Error::new( io::ErrorKind::UnexpectedEof, "tried to skip past end of input", )); } - Ok(n) => self.skip -= n, - Err(e) => return Err(e), + n => self.skip -= n, } } } diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index d7b95d215..239a0970f 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -671,8 +671,7 @@ fn build_options( if start_page > end_page { return Err(PrError::EncounteredErrors(format!( "invalid --pages argument '{}:{}'", - start_page, - end_page + start_page, end_page ))); } } @@ -999,8 +998,8 @@ fn mpr(paths: &[String], options: &OutputOptions) -> Result { for (_key, file_line_group) in file_line_groups.into_iter() { for file_line in file_line_group { - if file_line.line_content.is_err() { - return Err(file_line.line_content.unwrap_err().into()); + if let Err(e) = file_line.line_content { + return Err(e.into()); } let new_page_number = file_line.page_number; if page_counter != new_page_number { diff --git a/src/uu/rmdir/src/rmdir.rs b/src/uu/rmdir/src/rmdir.rs index 05cc66d51..fc22cca09 100644 --- a/src/uu/rmdir/src/rmdir.rs +++ b/src/uu/rmdir/src/rmdir.rs @@ -109,17 +109,14 @@ fn remove(dirs: Vec, ignore: bool, parents: bool, verbose: bool) -> Resu } fn remove_dir(path: &Path, ignore: bool, verbose: bool) -> Result<(), i32> { - let mut read_dir = match fs::read_dir(path) { - Ok(m) => m, - Err(e) if e.raw_os_error() == Some(ENOTDIR) => { + let mut read_dir = fs::read_dir(path).map_err(|e| { + if e.raw_os_error() == Some(ENOTDIR) { show_error!("failed to remove '{}': Not a directory", path.display()); - return Err(1); - } - Err(e) => { + } else { show_error!("reading directory '{}': {}", path.display(), e); - return Err(1); } - }; + 1 + })?; let mut r = Ok(()); diff --git a/src/uu/shuf/src/shuf.rs b/src/uu/shuf/src/shuf.rs index 88a47585f..2d1f558de 100644 --- a/src/uu/shuf/src/shuf.rs +++ b/src/uu/shuf/src/shuf.rs @@ -285,14 +285,12 @@ fn parse_range(input_range: &str) -> Result<(usize, usize), String> { if split.len() != 2 { Err(format!("invalid input range: '{}'", input_range)) } else { - let begin = match split[0].parse::() { - Ok(m) => m, - Err(_) => return Err(format!("invalid input range: '{}'", split[0])), - }; - let end = match split[1].parse::() { - Ok(m) => m, - Err(_) => return Err(format!("invalid input range: '{}'", split[1])), - }; + let begin = split[0] + .parse::() + .map_err(|_| format!("invalid input range: '{}'", split[0]))?; + let end = split[1] + .parse::() + .map_err(|_| format!("invalid input range: '{}'", split[1]))?; Ok((begin, end + 1)) } } diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index 5baff4825..a69e0c2c5 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -152,10 +152,8 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result { - let size = match parse_size(x) { - Some(m) => m, - None => return Err(ProgramOptionsError(format!("invalid mode {}", x))), - }; + let size = parse_size(x) + .ok_or_else(|| ProgramOptionsError(format!("invalid mode {}", x)))?; Ok(BufferType::Size(size)) } }, diff --git a/src/uucore/src/lib/features/entries.rs b/src/uucore/src/lib/features/entries.rs index 477fac470..bc4166346 100644 --- a/src/uucore/src/lib/features/entries.rs +++ b/src/uucore/src/lib/features/entries.rs @@ -101,6 +101,7 @@ pub fn get_groups_gnu(arg_id: Option) -> IOResult> { Ok(sort_groups(groups, egid)) } +#[cfg(all(unix, feature = "process"))] fn sort_groups(mut groups: Vec, egid: gid_t) -> Vec { if let Some(index) = groups.iter().position(|&x| x == egid) { groups[..=index].rotate_right(1); diff --git a/src/uucore/src/lib/features/fs.rs b/src/uucore/src/lib/features/fs.rs index 525f305e3..36bdbfed0 100644 --- a/src/uucore/src/lib/features/fs.rs +++ b/src/uucore/src/lib/features/fs.rs @@ -113,22 +113,14 @@ fn resolve>(original: P) -> IOResult { )); } - match fs::symlink_metadata(&result) { - Err(e) => return Err(e), - Ok(ref m) if !m.file_type().is_symlink() => break, - Ok(..) => { - followed += 1; - match fs::read_link(&result) { - Ok(path) => { - result.pop(); - result.push(path); - } - Err(e) => { - return Err(e); - } - } - } + if !fs::symlink_metadata(&result)?.file_type().is_symlink() { + break; } + + followed += 1; + let path = fs::read_link(&result)?; + result.pop(); + result.push(path); } Ok(result) } @@ -193,10 +185,8 @@ pub fn canonicalize>(original: P, can_mode: CanonicalizeMode) -> } match resolve(&result) { - Err(e) => match can_mode { - CanonicalizeMode::Missing => continue, - _ => return Err(e), - }, + Err(_) if can_mode == CanonicalizeMode::Missing => continue, + Err(e) => return Err(e), Ok(path) => { result.pop(); result.push(path); @@ -211,15 +201,14 @@ pub fn canonicalize>(original: P, can_mode: CanonicalizeMode) -> } match resolve(&result) { - Err(e) => { - if can_mode == CanonicalizeMode::Existing { - return Err(e); - } + Err(e) if can_mode == CanonicalizeMode::Existing => { + return Err(e); } Ok(path) => { result.pop(); result.push(path); } + Err(_) => (), } } Ok(result) diff --git a/src/uucore/src/lib/features/mode.rs b/src/uucore/src/lib/features/mode.rs index 4fb5a6509..fe109d73d 100644 --- a/src/uucore/src/lib/features/mode.rs +++ b/src/uucore/src/lib/features/mode.rs @@ -89,19 +89,19 @@ fn parse_levels(mode: &str) -> (u32, usize) { } fn parse_op(mode: &str, default: Option) -> Result<(char, usize), String> { - match mode.chars().next() { - Some(ch) => match ch { - '+' | '-' | '=' => Ok((ch, 1)), - _ => match default { - Some(ch) => Ok((ch, 0)), - None => Err(format!( - "invalid operator (expected +, -, or =, but found {})", - ch - )), - }, - }, - None => Err("unexpected end of mode".to_owned()), - } + let ch = mode + .chars() + .next() + .ok_or_else(|| "unexpected end of mode".to_owned())?; + Ok(match ch { + '+' | '-' | '=' => (ch, 1), + _ => { + let ch = default.ok_or_else(|| { + format!("invalid operator (expected +, -, or =, but found {})", ch) + })?; + (ch, 0) + } + }) } fn parse_change(mode: &str, fperm: u32, considering_dir: bool) -> (u32, usize) { diff --git a/src/uucore/src/lib/features/parse_time.rs b/src/uucore/src/lib/features/parse_time.rs index 8e822685b..fdf43b727 100644 --- a/src/uucore/src/lib/features/parse_time.rs +++ b/src/uucore/src/lib/features/parse_time.rs @@ -20,20 +20,18 @@ pub fn from_str(string: &str) -> Result { 'm' | 'M' => (slice, 60), 'h' | 'H' => (slice, 60 * 60), 'd' | 'D' => (slice, 60 * 60 * 24), - val => { - if !val.is_alphabetic() { - (string, 1) - } else if string == "inf" || string == "infinity" { + val if !val.is_alphabetic() => (string, 1), + _ => { + if string == "inf" || string == "infinity" { ("inf", 1) } else { return Err(format!("invalid time interval '{}'", string)); } } }; - let num = match numstr.parse::() { - Ok(m) => m, - Err(e) => return Err(format!("invalid time interval '{}': {}", string, e)), - }; + let num = numstr + .parse::() + .map_err(|e| format!("invalid time interval '{}': {}", string, e))?; const NANOS_PER_SEC: u32 = 1_000_000_000; let whole_secs = num.trunc(); diff --git a/src/uucore/src/lib/mods/ranges.rs b/src/uucore/src/lib/mods/ranges.rs index d4a6bf601..9e1e67d5a 100644 --- a/src/uucore/src/lib/mods/ranges.rs +++ b/src/uucore/src/lib/mods/ranges.rs @@ -85,10 +85,9 @@ impl Range { let mut ranges: Vec = vec![]; for item in list.split(',') { - match FromStr::from_str(item) { - Ok(range_item) => ranges.push(range_item), - Err(e) => return Err(format!("range '{}' was invalid: {}", item, e)), - } + let range_item = FromStr::from_str(item) + .map_err(|e| format!("range '{}' was invalid: {}", item, e))?; + ranges.push(range_item); } ranges.sort();