1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-29 20:17:45 +00:00

Merge pull request #2398 from youknowone/err-return

clean up returning Err
This commit is contained in:
Terts Diepraam 2021-06-12 00:14:28 +02:00 committed by GitHub
commit b7460a61a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 195 additions and 286 deletions

View file

@ -54,15 +54,13 @@ impl Config {
None => None, None => None,
}; };
let cols = match options.value_of(options::WRAP) { let cols = options
Some(num) => match num.parse::<usize>() { .value_of(options::WRAP)
Ok(n) => Some(n), .map(|num| {
Err(e) => { num.parse::<usize>()
return Err(format!("Invalid wrap size: {}: {}", num, e)); .map_err(|e| format!("Invalid wrap size: {}: {}", num, e))
} })
}, .transpose()?;
None => None,
};
Ok(Config { Ok(Config {
decode: options.is_present(options::DECODE), decode: options.is_present(options::DECODE),

View file

@ -278,37 +278,25 @@ fn parse_spec(spec: &str) -> Result<(Option<u32>, Option<u32>), String> {
let usr_only = args.len() == 1 && !args[0].is_empty(); let usr_only = args.len() == 1 && !args[0].is_empty();
let grp_only = args.len() == 2 && 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(); let usr_grp = args.len() == 2 && !args[0].is_empty() && !args[1].is_empty();
let uid = if usr_only || usr_grp {
if usr_only { Some(
Ok(( Passwd::locate(args[0])
Some(match Passwd::locate(args[0]) { .map_err(|_| format!("invalid user: {}", spec))?
Ok(v) => v.uid(), .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)),
}),
))
} else { } 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 { 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: "));
}
}

View file

@ -160,8 +160,7 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> {
let mut bytes = init_byte_array(); let mut bytes = init_byte_array();
loop { loop {
match rd.read(&mut bytes) { let num_bytes = rd.read(&mut bytes)?;
Ok(num_bytes) => {
if num_bytes == 0 { if num_bytes == 0 {
return Ok((crc_final(crc, size), size)); return Ok((crc_final(crc, size), size));
} }
@ -170,9 +169,6 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> {
} }
size += num_bytes; size += num_bytes;
} }
Err(err) => return Err(err),
}
}
} }
mod options { mod options {

View file

@ -709,27 +709,26 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec<S
return Err(format!("extra operand {:?}", paths[2]).into()); return Err(format!("extra operand {:?}", paths[2]).into());
} }
let (mut sources, target) = match options.target_dir { let target = match options.target_dir {
Some(ref target) => { Some(ref target) => {
// All path args are sources, and the target dir was // All path args are sources, and the target dir was
// specified separately // specified separately
(paths, PathBuf::from(target)) PathBuf::from(target)
} }
None => { None => {
// If there was no explicit target-dir, then use the last // If there was no explicit target-dir, then use the last
// path_arg // path_arg
let target = paths.pop().unwrap(); paths.pop().unwrap()
(paths, target)
} }
}; };
if options.strip_trailing_slashes { if options.strip_trailing_slashes {
for source in sources.iter_mut() { for source in paths.iter_mut() {
*source = source.components().as_path().to_owned() *source = source.components().as_path().to_owned()
} }
} }
Ok((sources, target)) Ok((paths, target))
} }
fn preserve_hardlinks( fn preserve_hardlinks(
@ -1271,15 +1270,15 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes
ReflinkMode::Always => unsafe { ReflinkMode::Always => unsafe {
let result = ficlone(dst_file.as_raw_fd(), src_file.as_raw_fd() as *const i32); let result = ficlone(dst_file.as_raw_fd(), src_file.as_raw_fd() as *const i32);
if result != 0 { if result != 0 {
return Err(format!( Err(format!(
"failed to clone {:?} from {:?}: {}", "failed to clone {:?} from {:?}: {}",
source, source,
dest, dest,
std::io::Error::last_os_error() std::io::Error::last_os_error()
) )
.into()); .into())
} else { } else {
return Ok(()); Ok(())
} }
}, },
ReflinkMode::Auto => unsafe { ReflinkMode::Auto => unsafe {
@ -1287,11 +1286,10 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes
if result != 0 { if result != 0 {
fs::copy(source, dest).context(&*context_for(source, dest))?; fs::copy(source, dest).context(&*context_for(source, dest))?;
} }
Ok(())
}, },
ReflinkMode::Never => unreachable!(), ReflinkMode::Never => unreachable!(),
} }
Ok(())
} }
/// Copies `source` to `dest` using copy-on-write if possible. /// Copies `source` to `dest` using copy-on-write if possible.

View file

@ -133,20 +133,12 @@ fn extract_patterns(args: &[String]) -> Result<Vec<Pattern>, CsplitError> {
Some(m) => m.as_str().parse().unwrap(), Some(m) => m.as_str().parse().unwrap(),
}; };
if let Some(up_to_match) = captures.name("UPTO") { if let Some(up_to_match) = captures.name("UPTO") {
let pattern = match Regex::new(up_to_match.as_str()) { let pattern = Regex::new(up_to_match.as_str())
Err(_) => { .map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?;
return Err(CsplitError::InvalidPattern(arg.to_string()));
}
Ok(reg) => reg,
};
patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes)); patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes));
} else if let Some(skip_to_match) = captures.name("SKIPTO") { } else if let Some(skip_to_match) = captures.name("SKIPTO") {
let pattern = match Regex::new(skip_to_match.as_str()) { let pattern = Regex::new(skip_to_match.as_str())
Err(_) => { .map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?;
return Err(CsplitError::InvalidPattern(arg.to_string()));
}
Ok(reg) => reg,
};
patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes)); patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes));
} }
} else if let Ok(line_number) = arg.parse::<usize>() { } else if let Ok(line_number) = arg.parse::<usize>() {

View file

@ -33,13 +33,13 @@ impl SplitName {
// get the prefix // get the prefix
let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string());
// the width for the split offset // the width for the split offset
let n_digits = match n_digits_opt { let n_digits = n_digits_opt
None => 2, .map(|opt| {
Some(opt) => match opt.parse::<usize>() { opt.parse::<usize>()
Ok(digits) => digits, .map_err(|_| CsplitError::InvalidNumber(opt))
Err(_) => return Err(CsplitError::InvalidNumber(opt)), })
}, .transpose()?
}; .unwrap_or(2);
// translate the custom format into a function // translate the custom format into a function
let fn_split_name: Box<dyn Fn(usize) -> String> = match format_opt { let fn_split_name: Box<dyn Fn(usize) -> String> = match format_opt {
None => Box::new(move |n: usize| -> String { None => Box::new(move |n: usize| -> String {

16
src/uu/env/src/env.rs vendored
View file

@ -82,13 +82,10 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> {
Ini::load_from_file(file) Ini::load_from_file(file)
}; };
let conf = match conf { let conf = conf.map_err(|error| {
Ok(config) => config,
Err(error) => {
eprintln!("env: error: \"{}\": {}", file, error); eprintln!("env: error: \"{}\": {}", file, error);
return Err(1); 1
} })?;
};
for (_, prop) in &conf { for (_, prop) in &conf {
// ignore all INI section lines (treat them as comments) // 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 // FIXME: this should just use execvp() (no fork()) on Unix-like systems
match Command::new(&*prog).args(args).status() { match Command::new(&*prog).args(args).status() {
Ok(exit) => { Ok(exit) if !exit.success() => return Err(exit.code().unwrap()),
if !exit.success() {
return Err(exit.code().unwrap());
}
}
Err(ref err) if err.kind() == io::ErrorKind::NotFound => return Err(127), Err(ref err) if err.kind() == io::ErrorKind::NotFound => return Err(127),
Err(_) => return Err(126), Err(_) => return Err(126),
Ok(_) => (),
} }
} else { } else {
// no program provided, so just dump all env vars to stdout // no program provided, so just dump all env vars to stdout

View file

@ -160,10 +160,8 @@ impl AstNode {
if let AstNode::Node { operands, .. } = self { if let AstNode::Node { operands, .. } = self {
let mut out = Vec::with_capacity(operands.len()); let mut out = Vec::with_capacity(operands.len());
for operand in operands { for operand in operands {
match operand.evaluate() { let value = operand.evaluate()?;
Ok(value) => out.push(value), out.push(value);
Err(reason) => return Err(reason),
}
} }
Ok(out) Ok(out)
} else { } else {
@ -252,10 +250,8 @@ fn maybe_ast_node(
) -> Result<Box<AstNode>, String> { ) -> Result<Box<AstNode>, String> {
let mut operands = Vec::with_capacity(arity); let mut operands = Vec::with_capacity(arity);
for _ in 0..arity { for _ in 0..arity {
match ast_from_rpn(rpn) { let operand = ast_from_rpn(rpn)?;
Err(reason) => return Err(reason), operands.push(operand);
Ok(operand) => operands.push(operand),
}
} }
operands.reverse(); operands.reverse();
Ok(AstNode::new_node(token_idx, op_type, operands)) Ok(AstNode::new_node(token_idx, op_type, operands))
@ -399,10 +395,12 @@ fn move_till_match_paren(
op_stack: &mut TokenStack, op_stack: &mut TokenStack,
) -> Result<(), String> { ) -> Result<(), String> {
loop { loop {
match op_stack.pop() { let op = op_stack
None => return Err("syntax error (Mismatched close-parenthesis)".to_string()), .pop()
Some((_, Token::ParOpen)) => return Ok(()), .ok_or_else(|| "syntax error (Mismatched close-parenthesis)".to_string())?;
Some(other) => out_stack.push(other), match op {
(_, Token::ParOpen) => return Ok(()),
other => out_stack.push(other),
} }
} }
} }
@ -462,23 +460,18 @@ fn infix_operator_and(values: &[String]) -> String {
fn operator_match(values: &[String]) -> Result<String, String> { fn operator_match(values: &[String]) -> Result<String, String> {
assert!(values.len() == 2); assert!(values.len() == 2);
let re = match Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep()) let re = Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep())
{ .map_err(|err| err.description().to_string())?;
Ok(m) => m, Ok(if re.captures_len() > 0 {
Err(err) => return Err(err.description().to_string()), re.captures(&values[0])
}; .map(|captures| captures.at(1).unwrap())
if re.captures_len() > 0 { .unwrap_or("")
Ok(match re.captures(&values[0]) { .to_string()
Some(captures) => captures.at(1).unwrap().to_string(),
None => "".to_string(),
})
} else { } else {
Ok(match re.find(&values[0]) { re.find(&values[0])
Some((start, end)) => (end - start).to_string(), .map_or("0".to_string(), |(start, end)| (end - start).to_string())
None => "0".to_string(),
}) })
} }
}
fn prefix_operator_length(values: &[String]) -> String { fn prefix_operator_length(values: &[String]) -> String {
assert!(values.len() == 1); assert!(values.len() == 1);

View file

@ -176,19 +176,11 @@ impl HeadOptions {
options.zeroed = matches.is_present(options::ZERO_NAME); options.zeroed = matches.is_present(options::ZERO_NAME);
let mode_and_from_end = if let Some(v) = matches.value_of(options::BYTES_NAME) { let mode_and_from_end = if let Some(v) = matches.value_of(options::BYTES_NAME) {
match parse_mode(v, Modes::Bytes) { parse_mode(v, Modes::Bytes)
Ok(v) => v, .map_err(|err| format!("invalid number of bytes: {}", err))?
Err(err) => {
return Err(format!("invalid number of bytes: {}", err));
}
}
} else if let Some(v) = matches.value_of(options::LINES_NAME) { } else if let Some(v) = matches.value_of(options::LINES_NAME) {
match parse_mode(v, Modes::Lines) { parse_mode(v, Modes::Lines)
Ok(v) => v, .map_err(|err| format!("invalid number of lines: {}", err))?
Err(err) => {
return Err(format!("invalid number of lines: {}", err));
}
}
} else { } else {
(Modes::Lines(10), false) (Modes::Lines(10), false)
}; };

View file

@ -94,17 +94,15 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
/// the bool specifies whether to read from the end /// the bool specifies whether to read from the end
pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> { pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> {
let mut num_start = 0; let mut num_start = 0;
let (mut chars, all_but_last) = {
let mut chars = src.char_indices(); let mut chars = src.char_indices();
let (mut chars, all_but_last) = match chars.next() { let (_, c) = chars.next().ok_or(ParseError::Syntax)?;
Some((_, c)) => {
if c == '-' { if c == '-' {
num_start += 1; num_start += 1;
(chars, true) (chars, true)
} else { } else {
(src.char_indices(), false) (src.char_indices(), false)
} }
}
None => return Err(ParseError::Syntax),
}; };
let mut num_end = 0usize; let mut num_end = 0usize;
let mut last_char = 0 as char; 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 { let num = if num_count > 0 {
match src[num_start..=num_end].parse::<usize>() { Some(
Ok(n) => Some(n), src[num_start..=num_end]
Err(_) => return Err(ParseError::Overflow), .parse::<usize>()
} .map_err(|_| ParseError::Overflow)?,
)
} else { } else {
None None
}; };
@ -168,10 +167,7 @@ pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> {
'y' => base.pow(8), 'y' => base.pow(8),
_ => return Err(ParseError::Syntax), _ => return Err(ParseError::Syntax),
}; };
let mul = match usize::try_from(mul) { let mul = usize::try_from(mul).map_err(|_| ParseError::Overflow)?;
Ok(n) => n,
Err(_) => return Err(ParseError::Overflow),
};
match num.unwrap_or(1).checked_mul(mul) { match num.unwrap_or(1).checked_mul(mul) {
Some(n) => Ok((n, all_but_last)), Some(n) => Ok((n, all_but_last)),
None => Err(ParseError::Overflow), None => Err(ParseError::Overflow),

View file

@ -299,29 +299,17 @@ fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let considering_dir: bool = MainFunction::Directory == main_function; let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) { let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) { let x = matches.value_of(OPT_MODE).ok_or(1)?;
Some(x) => match mode::parse(x, considering_dir) { Some(mode::parse(x, considering_dir).map_err(|err| {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err); show_error!("Invalid mode string: {}", err);
return Err(1); 1
} })?)
},
None => {
return Err(1);
}
}
} else { } else {
None None
}; };
let backup_suffix = if matches.is_present(OPT_SUFFIX) { let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) { matches.value_of(OPT_SUFFIX).ok_or(1)?
Some(x) => x,
None => {
return Err(1);
}
}
} else { } else {
"~" "~"
}; };

View file

@ -247,7 +247,7 @@ fn nl<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
let mut line_filter: fn(&str, &regex::Regex) -> bool = pass_regex; let mut line_filter: fn(&str, &regex::Regex) -> bool = pass_regex;
for mut l in reader.lines().map(|r| r.unwrap()) { for mut l in reader.lines().map(|r| r.unwrap()) {
// Sanitize the string. We want to print the newline ourselves. // Sanitize the string. We want to print the newline ourselves.
if l.chars().last() == Some('\n') { if l.ends_with('\n') {
l.pop(); l.pop();
} }
// Next we iterate through the individual chars to see if this // Next we iterate through the individual chars to see if this

View file

@ -128,36 +128,27 @@ impl OdOptions {
} }
}; };
let mut skip_bytes = match matches.value_of(options::SKIP_BYTES) { let mut skip_bytes = matches
None => 0, .value_of(options::SKIP_BYTES)
Some(s) => match parse_number_of_bytes(s) { .map(|s| {
Ok(i) => i, parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --skip-bytes={}", s))
Err(_) => { })
return Err(format!("Invalid argument --skip-bytes={}", s)); .transpose()?
} .unwrap_or(0);
},
};
let mut label: Option<usize> = None; let mut label: Option<usize> = None;
let input_strings = match parse_inputs(&matches) { let parsed_input = parse_inputs(&matches).map_err(|e| format!("Invalid inputs: {}", e))?;
Ok(CommandLineInputs::FileNames(v)) => v, let input_strings = match parsed_input {
Ok(CommandLineInputs::FileAndOffset((f, s, l))) => { CommandLineInputs::FileNames(v) => v,
CommandLineInputs::FileAndOffset((f, s, l)) => {
skip_bytes = s; skip_bytes = s;
label = l; label = l;
vec![f] vec![f]
} }
Err(e) => {
return Err(format!("Invalid inputs: {}", e));
}
}; };
let formats = match parse_format_flags(&args) { let formats = parse_format_flags(&args)?;
Ok(f) => f,
Err(e) => {
return Err(e);
}
};
let mut line_bytes = match matches.value_of(options::WIDTH) { let mut line_bytes = match matches.value_of(options::WIDTH) {
None => 16, None => 16,
@ -174,15 +165,12 @@ impl OdOptions {
let output_duplicates = matches.is_present(options::OUTPUT_DUPLICATES); let output_duplicates = matches.is_present(options::OUTPUT_DUPLICATES);
let read_bytes = match matches.value_of(options::READ_BYTES) { let read_bytes = matches
None => None, .value_of(options::READ_BYTES)
Some(s) => match parse_number_of_bytes(s) { .map(|s| {
Ok(i) => Some(i), parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --read-bytes={}", s))
Err(_) => { })
return Err(format!("Invalid argument --read-bytes={}", s)); .transpose()?;
}
},
};
let radix = match matches.value_of(options::ADDRESS_RADIX) { let radix = match matches.value_of(options::ADDRESS_RADIX) {
None => Radix::Octal, None => Radix::Octal,

View file

@ -108,10 +108,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
for arg in arg_iter { for arg in arg_iter {
if expect_type_string { if expect_type_string {
match parse_type_string(arg) { let v = parse_type_string(arg)?;
Ok(v) => formats.extend(v.into_iter()), formats.extend(v.into_iter());
Err(e) => return Err(e),
}
expect_type_string = false; expect_type_string = false;
} else if arg.starts_with("--") { } else if arg.starts_with("--") {
if arg.len() == 2 { if arg.len() == 2 {
@ -119,10 +117,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
} }
if arg.starts_with("--format=") { if arg.starts_with("--format=") {
let params: String = arg.chars().skip_while(|c| *c != '=').skip(1).collect(); let params: String = arg.chars().skip_while(|c| *c != '=').skip(1).collect();
match parse_type_string(&params) { let v = parse_type_string(&params)?;
Ok(v) => formats.extend(v.into_iter()), formats.extend(v.into_iter());
Err(e) => return Err(e),
}
} }
if arg == "--format" { if arg == "--format" {
expect_type_string = true; expect_type_string = true;
@ -145,10 +141,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
} }
} }
if !format_spec.is_empty() { if !format_spec.is_empty() {
match parse_type_string(&format_spec) { let v = parse_type_string(&format_spec)?;
Ok(v) => formats.extend(v.into_iter()), formats.extend(v.into_iter());
Err(e) => return Err(e),
}
expect_type_string = false; expect_type_string = false;
} }
} }

View file

@ -36,16 +36,15 @@ impl<R: Read> Read for PartialReader<R> {
while self.skip > 0 { while self.skip > 0 {
let skip_count = cmp::min(self.skip, MAX_SKIP_BUFFER); let skip_count = cmp::min(self.skip, MAX_SKIP_BUFFER);
match self.inner.read(&mut bytes[..skip_count]) { match self.inner.read(&mut bytes[..skip_count])? {
Ok(0) => { 0 => {
// this is an error as we still have more to skip // this is an error as we still have more to skip
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::UnexpectedEof, io::ErrorKind::UnexpectedEof,
"tried to skip past end of input", "tried to skip past end of input",
)); ));
} }
Ok(n) => self.skip -= n, n => self.skip -= n,
Err(e) => return Err(e),
} }
} }
} }

View file

@ -671,8 +671,7 @@ fn build_options(
if start_page > end_page { if start_page > end_page {
return Err(PrError::EncounteredErrors(format!( return Err(PrError::EncounteredErrors(format!(
"invalid --pages argument '{}:{}'", "invalid --pages argument '{}:{}'",
start_page, start_page, end_page
end_page
))); )));
} }
} }
@ -999,8 +998,8 @@ fn mpr(paths: &[String], options: &OutputOptions) -> Result<i32, PrError> {
for (_key, file_line_group) in file_line_groups.into_iter() { for (_key, file_line_group) in file_line_groups.into_iter() {
for file_line in file_line_group { for file_line in file_line_group {
if file_line.line_content.is_err() { if let Err(e) = file_line.line_content {
return Err(file_line.line_content.unwrap_err().into()); return Err(e.into());
} }
let new_page_number = file_line.page_number; let new_page_number = file_line.page_number;
if page_counter != new_page_number { if page_counter != new_page_number {

View file

@ -109,17 +109,14 @@ fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Resu
} }
fn remove_dir(path: &Path, ignore: bool, verbose: bool) -> Result<(), i32> { fn remove_dir(path: &Path, ignore: bool, verbose: bool) -> Result<(), i32> {
let mut read_dir = match fs::read_dir(path) { let mut read_dir = fs::read_dir(path).map_err(|e| {
Ok(m) => m, if e.raw_os_error() == Some(ENOTDIR) {
Err(e) if e.raw_os_error() == Some(ENOTDIR) => {
show_error!("failed to remove '{}': Not a directory", path.display()); show_error!("failed to remove '{}': Not a directory", path.display());
return Err(1); } else {
}
Err(e) => {
show_error!("reading directory '{}': {}", path.display(), e); show_error!("reading directory '{}': {}", path.display(), e);
return Err(1);
} }
}; 1
})?;
let mut r = Ok(()); let mut r = Ok(());

View file

@ -285,14 +285,12 @@ fn parse_range(input_range: &str) -> Result<(usize, usize), String> {
if split.len() != 2 { if split.len() != 2 {
Err(format!("invalid input range: '{}'", input_range)) Err(format!("invalid input range: '{}'", input_range))
} else { } else {
let begin = match split[0].parse::<usize>() { let begin = split[0]
Ok(m) => m, .parse::<usize>()
Err(_) => return Err(format!("invalid input range: '{}'", split[0])), .map_err(|_| format!("invalid input range: '{}'", split[0]))?;
}; let end = split[1]
let end = match split[1].parse::<usize>() { .parse::<usize>()
Ok(m) => m, .map_err(|_| format!("invalid input range: '{}'", split[1]))?;
Err(_) => return Err(format!("invalid input range: '{}'", split[1])),
};
Ok((begin, end + 1)) Ok((begin, end + 1))
} }
} }

View file

@ -152,10 +152,8 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result<BufferType, ProgramO
} }
} }
x => { x => {
let size = match parse_size(x) { let size = parse_size(x)
Some(m) => m, .ok_or_else(|| ProgramOptionsError(format!("invalid mode {}", x)))?;
None => return Err(ProgramOptionsError(format!("invalid mode {}", x))),
};
Ok(BufferType::Size(size)) Ok(BufferType::Size(size))
} }
}, },

View file

@ -101,6 +101,7 @@ pub fn get_groups_gnu(arg_id: Option<u32>) -> IOResult<Vec<gid_t>> {
Ok(sort_groups(groups, egid)) Ok(sort_groups(groups, egid))
} }
#[cfg(all(unix, feature = "process"))]
fn sort_groups(mut groups: Vec<gid_t>, egid: gid_t) -> Vec<gid_t> { fn sort_groups(mut groups: Vec<gid_t>, egid: gid_t) -> Vec<gid_t> {
if let Some(index) = groups.iter().position(|&x| x == egid) { if let Some(index) = groups.iter().position(|&x| x == egid) {
groups[..=index].rotate_right(1); groups[..=index].rotate_right(1);

View file

@ -113,23 +113,15 @@ fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> {
)); ));
} }
match fs::symlink_metadata(&result) { if !fs::symlink_metadata(&result)?.file_type().is_symlink() {
Err(e) => return Err(e), break;
Ok(ref m) if !m.file_type().is_symlink() => break, }
Ok(..) => {
followed += 1; followed += 1;
match fs::read_link(&result) { let path = fs::read_link(&result)?;
Ok(path) => {
result.pop(); result.pop();
result.push(path); result.push(path);
} }
Err(e) => {
return Err(e);
}
}
}
}
}
Ok(result) Ok(result)
} }
@ -193,10 +185,8 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
} }
match resolve(&result) { match resolve(&result) {
Err(e) => match can_mode { Err(_) if can_mode == CanonicalizeMode::Missing => continue,
CanonicalizeMode::Missing => continue, Err(e) => return Err(e),
_ => return Err(e),
},
Ok(path) => { Ok(path) => {
result.pop(); result.pop();
result.push(path); result.push(path);
@ -211,15 +201,14 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
} }
match resolve(&result) { match resolve(&result) {
Err(e) => { Err(e) if can_mode == CanonicalizeMode::Existing => {
if can_mode == CanonicalizeMode::Existing {
return Err(e); return Err(e);
} }
}
Ok(path) => { Ok(path) => {
result.pop(); result.pop();
result.push(path); result.push(path);
} }
Err(_) => (),
} }
} }
Ok(result) Ok(result)

View file

@ -89,19 +89,19 @@ fn parse_levels(mode: &str) -> (u32, usize) {
} }
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> { fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() { let ch = mode
Some(ch) => match ch { .chars()
'+' | '-' | '=' => Ok((ch, 1)), .next()
_ => match default { .ok_or_else(|| "unexpected end of mode".to_owned())?;
Some(ch) => Ok((ch, 0)), Ok(match ch {
None => Err(format!( '+' | '-' | '=' => (ch, 1),
"invalid operator (expected +, -, or =, but found {})", _ => {
ch let ch = default.ok_or_else(|| {
)), format!("invalid operator (expected +, -, or =, but found {})", ch)
}, })?;
}, (ch, 0)
None => Err("unexpected end of mode".to_owned()),
} }
})
} }
fn parse_change(mode: &str, fperm: u32, considering_dir: bool) -> (u32, usize) { fn parse_change(mode: &str, fperm: u32, considering_dir: bool) -> (u32, usize) {

View file

@ -20,20 +20,18 @@ pub fn from_str(string: &str) -> Result<Duration, String> {
'm' | 'M' => (slice, 60), 'm' | 'M' => (slice, 60),
'h' | 'H' => (slice, 60 * 60), 'h' | 'H' => (slice, 60 * 60),
'd' | 'D' => (slice, 60 * 60 * 24), 'd' | 'D' => (slice, 60 * 60 * 24),
val => { val if !val.is_alphabetic() => (string, 1),
if !val.is_alphabetic() { _ => {
(string, 1) if string == "inf" || string == "infinity" {
} else if string == "inf" || string == "infinity" {
("inf", 1) ("inf", 1)
} else { } else {
return Err(format!("invalid time interval '{}'", string)); return Err(format!("invalid time interval '{}'", string));
} }
} }
}; };
let num = match numstr.parse::<f64>() { let num = numstr
Ok(m) => m, .parse::<f64>()
Err(e) => return Err(format!("invalid time interval '{}': {}", string, e)), .map_err(|e| format!("invalid time interval '{}': {}", string, e))?;
};
const NANOS_PER_SEC: u32 = 1_000_000_000; const NANOS_PER_SEC: u32 = 1_000_000_000;
let whole_secs = num.trunc(); let whole_secs = num.trunc();

View file

@ -85,10 +85,9 @@ impl Range {
let mut ranges: Vec<Range> = vec![]; let mut ranges: Vec<Range> = vec![];
for item in list.split(',') { for item in list.split(',') {
match FromStr::from_str(item) { let range_item = FromStr::from_str(item)
Ok(range_item) => ranges.push(range_item), .map_err(|e| format!("range '{}' was invalid: {}", item, e))?;
Err(e) => return Err(format!("range '{}' was invalid: {}", item, e)), ranges.push(range_item);
}
} }
ranges.sort(); ranges.sort();