1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-30 12:37:49 +00:00

chore: simplify return in multi-branch

It is usually easier to reason about the code if the return is used in one place rather than in every branch of the match or if statements.
This commit is contained in:
Yuri Astrakhan 2025-04-11 00:23:55 -04:00
parent 5bfbc30fba
commit b5ed4a4acf
12 changed files with 61 additions and 66 deletions

View file

@ -357,24 +357,24 @@ impl Chmoder {
Ok(meta) => meta.mode() & 0o7777, Ok(meta) => meta.mode() & 0o7777,
Err(err) => { Err(err) => {
// Handle dangling symlinks or other errors // Handle dangling symlinks or other errors
if file.is_symlink() && !self.dereference { return if file.is_symlink() && !self.dereference {
if self.verbose { if self.verbose {
println!( println!(
"neither symbolic link {} nor referent has been changed", "neither symbolic link {} nor referent has been changed",
file.quote() file.quote()
); );
} }
return Ok(()); // Skip dangling symlinks Ok(()) // Skip dangling symlinks
} else if err.kind() == std::io::ErrorKind::PermissionDenied { } else if err.kind() == std::io::ErrorKind::PermissionDenied {
// These two filenames would normally be conditionally // These two filenames would normally be conditionally
// quoted, but GNU's tests expect them to always be quoted // quoted, but GNU's tests expect them to always be quoted
return Err(USimpleError::new( Err(USimpleError::new(
1, 1,
format!("{}: Permission denied", file.quote()), format!("{}: Permission denied", file.quote()),
)); ))
} else { } else {
return Err(USimpleError::new(1, format!("{}: {err}", file.quote()))); Err(USimpleError::new(1, format!("{}: {err}", file.quote())))
} };
} }
}; };

View file

@ -251,15 +251,15 @@ fn copy_direntry(
&& !ends_with_slash_dot(&source_absolute) && !ends_with_slash_dot(&source_absolute)
&& !local_to_target.exists() && !local_to_target.exists()
{ {
if target_is_file { return if target_is_file {
return Err("cannot overwrite non-directory with directory".into()); Err("cannot overwrite non-directory with directory".into())
} else { } else {
build_dir(&local_to_target, false, options, Some(&source_absolute))?; build_dir(&local_to_target, false, options, Some(&source_absolute))?;
if options.verbose { if options.verbose {
println!("{}", context_for(&source_relative, &local_to_target)); println!("{}", context_for(&source_relative, &local_to_target));
} }
return Ok(()); Ok(())
} };
} }
// If the source is not a directory, then we need to copy the file. // If the source is not a directory, then we need to copy the file.

View file

@ -2451,10 +2451,10 @@ fn handle_no_preserve_mode(options: &Options, org_mode: u32) -> u32 {
{ {
const MODE_RW_UGO: u32 = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; const MODE_RW_UGO: u32 = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
const S_IRWXUGO: u32 = S_IRWXU | S_IRWXG | S_IRWXO; const S_IRWXUGO: u32 = S_IRWXU | S_IRWXG | S_IRWXO;
if is_explicit_no_preserve_mode { return if is_explicit_no_preserve_mode {
return MODE_RW_UGO; MODE_RW_UGO
} else { } else {
return org_mode & S_IRWXUGO; org_mode & S_IRWXUGO
}; };
} }

View file

@ -184,11 +184,7 @@ pub(crate) fn read_block_size(matches: &ArgMatches) -> Result<BlockSize, ParseSi
fn block_size_from_env() -> Option<u64> { fn block_size_from_env() -> Option<u64> {
for env_var in ["DF_BLOCK_SIZE", "BLOCK_SIZE", "BLOCKSIZE"] { for env_var in ["DF_BLOCK_SIZE", "BLOCK_SIZE", "BLOCKSIZE"] {
if let Ok(env_size) = env::var(env_var) { if let Ok(env_size) = env::var(env_var) {
if let Ok(size) = parse_size_u64(&env_size) { return parse_size_u64(&env_size).ok();
return Some(size);
} else {
return None;
}
} }
} }

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

@ -581,19 +581,21 @@ impl EnvAppData {
} }
return Err(exit.code().unwrap().into()); return Err(exit.code().unwrap().into());
} }
Err(ref err) => match err.kind() { Err(ref err) => {
return match err.kind() {
io::ErrorKind::NotFound | io::ErrorKind::InvalidInput => { io::ErrorKind::NotFound | io::ErrorKind::InvalidInput => {
return Err(self.make_error_no_such_file_or_dir(prog.deref())); Err(self.make_error_no_such_file_or_dir(prog.deref()))
} }
io::ErrorKind::PermissionDenied => { io::ErrorKind::PermissionDenied => {
uucore::show_error!("{}: Permission denied", prog.quote()); uucore::show_error!("{}: Permission denied", prog.quote());
return Err(126.into()); Err(126.into())
} }
_ => { _ => {
uucore::show_error!("unknown error: {err:?}"); uucore::show_error!("unknown error: {err:?}");
return Err(126.into()); Err(126.into())
}
};
} }
},
Ok(_) => (), Ok(_) => (),
} }
Ok(()) Ok(())

View file

@ -145,14 +145,14 @@ fn tabstops_parse(s: &str) -> Result<(RemainingMode, Vec<usize>), ParseError> {
} }
let s = s.trim_start_matches(char::is_numeric); let s = s.trim_start_matches(char::is_numeric);
if s.starts_with('/') || s.starts_with('+') { return if s.starts_with('/') || s.starts_with('+') {
return Err(ParseError::SpecifierNotAtStartOfNumber( Err(ParseError::SpecifierNotAtStartOfNumber(
s[0..1].to_string(), s[0..1].to_string(),
s.to_string(), s.to_string(),
)); ))
} else { } else {
return Err(ParseError::InvalidCharacter(s.to_string())); Err(ParseError::InvalidCharacter(s.to_string()))
} };
} }
} }
} }

View file

@ -270,14 +270,14 @@ fn extract_files(matches: &ArgMatches) -> UResult<Vec<String>> {
fn extract_width(matches: &ArgMatches) -> UResult<Option<usize>> { fn extract_width(matches: &ArgMatches) -> UResult<Option<usize>> {
let width_opt = matches.get_one::<String>(options::WIDTH); let width_opt = matches.get_one::<String>(options::WIDTH);
if let Some(width_str) = width_opt { if let Some(width_str) = width_opt {
if let Ok(width) = width_str.parse::<usize>() { return if let Ok(width) = width_str.parse::<usize>() {
return Ok(Some(width)); Ok(Some(width))
} else { } else {
return Err(USimpleError::new( Err(USimpleError::new(
1, 1,
format!("invalid width: {}", width_str.quote()), format!("invalid width: {}", width_str.quote()),
)); ))
} };
} }
if let Some(1) = matches.index_of(options::FILES_OR_WIDTH) { if let Some(1) = matches.index_of(options::FILES_OR_WIDTH) {

View file

@ -176,7 +176,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let line_ending = LineEnding::from_zero_flag(state.zflag); let line_ending = LineEnding::from_zero_flag(state.zflag);
if state.cflag { if state.cflag {
if state.selinux_supported { return if state.selinux_supported {
// print SElinux context and exit // print SElinux context and exit
#[cfg(all(any(target_os = "linux", target_os = "android"), feature = "selinux"))] #[cfg(all(any(target_os = "linux", target_os = "android"), feature = "selinux"))]
if let Ok(context) = selinux::SecurityContext::current(false) { if let Ok(context) = selinux::SecurityContext::current(false) {
@ -186,13 +186,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// print error because `cflag` was explicitly requested // print error because `cflag` was explicitly requested
return Err(USimpleError::new(1, "can't get process context")); return Err(USimpleError::new(1, "can't get process context"));
} }
return Ok(()); Ok(())
} else { } else {
return Err(USimpleError::new( Err(USimpleError::new(
1, 1,
"--context (-Z) works only on an SELinux-enabled kernel", "--context (-Z) works only on an SELinux-enabled kernel",
)); ))
} };
} }
for i in 0..=users.len() { for i in 0..=users.len() {

View file

@ -84,15 +84,15 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
show(&path, line_ending).map_err_context(String::new)?; show(&path, line_ending).map_err_context(String::new)?;
} }
Err(err) => { Err(err) => {
if verbose { return if verbose {
return Err(USimpleError::new( Err(USimpleError::new(
1, 1,
err.map_err_context(move || f.maybe_quote().to_string()) err.map_err_context(move || f.maybe_quote().to_string())
.to_string(), .to_string(),
)); ))
} else { } else {
return Err(1.into()); Err(1.into())
} };
} }
} }
} }

View file

@ -162,14 +162,15 @@ impl FileHandling {
pub fn needs_header(&self, path: &Path, verbose: bool) -> bool { pub fn needs_header(&self, path: &Path, verbose: bool) -> bool {
if verbose { if verbose {
if let Some(ref last) = self.last { if let Some(ref last) = self.last {
return !last.eq(&path); !last.eq(&path)
} else { } else {
return true; true
}
} }
} else {
false false
} }
} }
}
/// Data structure to keep a handle on the BufReader, Metadata /// Data structure to keep a handle on the BufReader, Metadata
/// and the display_name (header_name) of files that are being followed. /// and the display_name (header_name) of files that are being followed.

View file

@ -44,14 +44,14 @@ fn tabstops_parse(s: &str) -> Result<Vec<usize>, ParseError> {
for word in words { for word in words {
match word.parse::<usize>() { match word.parse::<usize>() {
Ok(num) => nums.push(num), Ok(num) => nums.push(num),
Err(e) => match e.kind() { Err(e) => {
IntErrorKind::PosOverflow => return Err(ParseError::TabSizeTooLarge), return match e.kind() {
_ => { IntErrorKind::PosOverflow => Err(ParseError::TabSizeTooLarge),
return Err(ParseError::InvalidCharacter( _ => Err(ParseError::InvalidCharacter(
word.trim_start_matches(char::is_numeric).to_string(), word.trim_start_matches(char::is_numeric).to_string(),
)); )),
};
} }
},
} }
} }

View file

@ -350,11 +350,7 @@ pub static ALL_SIGNALS: [&str; 37] = [
pub fn signal_by_name_or_value(signal_name_or_value: &str) -> Option<usize> { pub fn signal_by_name_or_value(signal_name_or_value: &str) -> Option<usize> {
let signal_name_upcase = signal_name_or_value.to_uppercase(); let signal_name_upcase = signal_name_or_value.to_uppercase();
if let Ok(value) = signal_name_upcase.parse() { if let Ok(value) = signal_name_upcase.parse() {
if is_signal(value) { return if is_signal(value) { Some(value) } else { None };
return Some(value);
} else {
return None;
}
} }
let signal_name = signal_name_upcase.trim_start_matches("SIG"); let signal_name = signal_name_upcase.trim_start_matches("SIG");