1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-27 11:07:44 +00:00

chore: cleanup map_unwrap_or lint

Used this command and fixed a few remaining manual ones.

```sh
__CARGO_FIX_YOLO=1 cargo clippy --fix --all-targets --workspace --allow-dirty
```
This commit is contained in:
Yuri Astrakhan 2025-07-02 23:31:11 -04:00
parent 931d388664
commit e54d9bd76d
13 changed files with 74 additions and 94 deletions

View file

@ -642,7 +642,6 @@ cast_sign_loss = "allow" # 70
struct_excessive_bools = "allow" # 68 struct_excessive_bools = "allow" # 68
single_match_else = "allow" # 66 single_match_else = "allow" # 66
redundant_else = "allow" # 58 redundant_else = "allow" # 58
map_unwrap_or = "allow" # 54
cast_precision_loss = "allow" # 52 cast_precision_loss = "allow" # 52
unnested_or_patterns = "allow" # 40 unnested_or_patterns = "allow" # 40
inefficient_to_string = "allow" # 38 inefficient_to_string = "allow" # 38

View file

@ -229,10 +229,7 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
let uid = parse_uid(user, spec, sep)?; let uid = parse_uid(user, spec, sep)?;
let gid = parse_gid(group, spec)?; let gid = parse_gid(group, spec)?;
if user.chars().next().map(char::is_numeric).unwrap_or(false) if user.chars().next().is_some_and(char::is_numeric) && group.is_empty() && spec != user {
&& group.is_empty()
&& spec != user
{
// if the arg starts with an id numeric value, the group isn't set but the separator is provided, // if the arg starts with an id numeric value, the group isn't set but the separator is provided,
// we should fail with an error // we should fail with an error
return Err(USimpleError::new( return Err(USimpleError::new(

View file

@ -53,8 +53,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let locs = matches let locs = matches
.get_many::<OsString>(options::PATHS) .get_many::<OsString>(options::PATHS)
.map(|v| v.map(Path::new).collect()) .map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
.unwrap_or_else(|| vec![Path::new(".")]);
uu_ls::list(locs, &config) uu_ls::list(locs, &config)
} }

View file

@ -243,14 +243,17 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
return Ok(()); return Ok(());
} }
let (uid, gid) = possible_pw.as_ref().map(|p| (p.uid, p.gid)).unwrap_or({ let (uid, gid) = possible_pw.as_ref().map_or(
let use_effective = !state.rflag && (state.uflag || state.gflag || state.gsflag); {
if use_effective { let use_effective = !state.rflag && (state.uflag || state.gflag || state.gsflag);
(geteuid(), getegid()) if use_effective {
} else { (geteuid(), getegid())
(getuid(), getgid()) } else {
} (getuid(), getgid())
}); }
},
|p| (p.uid, p.gid),
);
state.ids = Some(Ids { state.ids = Some(Ids {
uid, uid,
gid, gid,

View file

@ -376,8 +376,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
let owner = matches let owner = matches
.get_one::<String>(OPT_OWNER) .get_one::<String>(OPT_OWNER)
.map(|s| s.as_str()) .map_or("", |s| s.as_str())
.unwrap_or("")
.to_string(); .to_string();
let owner_id = if owner.is_empty() { let owner_id = if owner.is_empty() {
@ -391,8 +390,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
let group = matches let group = matches
.get_one::<String>(OPT_GROUP) .get_one::<String>(OPT_GROUP)
.map(|s| s.as_str()) .map_or("", |s| s.as_str())
.unwrap_or("")
.to_string(); .to_string();
let group_id = if group.is_empty() { let group_id = if group.is_empty() {
@ -420,8 +418,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
strip_program: String::from( strip_program: String::from(
matches matches
.get_one::<String>(OPT_STRIP_PROGRAM) .get_one::<String>(OPT_STRIP_PROGRAM)
.map(|s| s.as_str()) .map_or(DEFAULT_STRIP_PROGRAM, |s| s.as_str()),
.unwrap_or(DEFAULT_STRIP_PROGRAM),
), ),
create_leading: matches.get_flag(OPT_CREATE_LEADING), create_leading: matches.get_flag(OPT_CREATE_LEADING),
target_dir, target_dir,
@ -503,8 +500,7 @@ fn directory(paths: &[String], b: &Behavior) -> UResult<()> {
/// created immediately /// created immediately
fn is_new_file_path(path: &Path) -> bool { fn is_new_file_path(path: &Path) -> bool {
!path.exists() !path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true) && (path.parent().is_none_or(Path::is_dir) || path.parent().unwrap().as_os_str().is_empty()) // In case of a simple file
|| path.parent().unwrap().as_os_str().is_empty()) // In case of a simple file
} }
/// Test if the path is an existing directory or ends with a trailing separator. /// Test if the path is an existing directory or ends with a trailing separator.
@ -1027,8 +1023,7 @@ fn needs_copy_for_ownership(to: &Path, to_meta: &fs::Metadata) -> bool {
.parent() .parent()
.and_then(|parent| metadata(parent).ok()) .and_then(|parent| metadata(parent).ok())
.filter(|parent_meta| parent_meta.mode() & 0o2000 != 0) .filter(|parent_meta| parent_meta.mode() & 0o2000 != 0)
.map(|parent_meta| parent_meta.gid()) .map_or(getegid(), |parent_meta| parent_meta.gid());
.unwrap_or(getegid());
to_meta.gid() != expected_gid to_meta.gid() != expected_gid
} }

View file

@ -1160,8 +1160,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let locs = matches let locs = matches
.get_many::<OsString>(options::PATHS) .get_many::<OsString>(options::PATHS)
.map(|v| v.map(Path::new).collect()) .map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
.unwrap_or_else(|| vec![Path::new(".")]);
list(locs, &config) list(locs, &config)
} }
@ -2135,7 +2134,7 @@ fn sort_entries(entries: &mut [PathData], config: &Config, out: &mut BufWriter<S
) )
}), }),
Sort::Size => { Sort::Size => {
entries.sort_by_key(|k| Reverse(k.get_metadata(out).map(|md| md.len()).unwrap_or(0))); entries.sort_by_key(|k| Reverse(k.get_metadata(out).map_or(0, |md| md.len())));
} }
// The default sort in GNU ls is case insensitive // The default sort in GNU ls is case insensitive
Sort::Name => entries.sort_by(|a, b| a.display_name.cmp(&b.display_name)), Sort::Name => entries.sort_by(|a, b| a.display_name.cmp(&b.display_name)),
@ -2194,8 +2193,7 @@ fn is_hidden(file_path: &DirEntry) -> bool {
file_path file_path
.file_name() .file_name()
.to_str() .to_str()
.map(|res| res.starts_with('.')) .is_some_and(|res| res.starts_with('.'))
.unwrap_or(false)
} }
} }

View file

@ -146,8 +146,7 @@ impl HardlinkTracker {
let has_hardlinks = scanner let has_hardlinks = scanner
.hardlink_groups .hardlink_groups
.get(&key) .get(&key)
.map(|group| group.len() > 1) .is_some_and(|group| group.len() > 1);
.unwrap_or(false);
if has_hardlinks { if has_hardlinks {
if options.verbose { if options.verbose {

View file

@ -432,12 +432,14 @@ fn build_options(
let header = matches let header = matches
.get_one::<String>(options::HEADER) .get_one::<String>(options::HEADER)
.map(|s| s.as_str()) .map_or(
.unwrap_or(if is_merge_mode || paths[0] == FILE_STDIN { if is_merge_mode || paths[0] == FILE_STDIN {
"" ""
} else { } else {
paths[0] paths[0]
}) },
|s| s.as_str(),
)
.to_string(); .to_string();
let default_first_number = NumberingMode::default().first_number; let default_first_number = NumberingMode::default().first_number;
@ -604,8 +606,7 @@ fn build_options(
Some(x) => Some(x), Some(x) => Some(x),
None => matches.get_one::<String>(options::COLUMN_CHAR_SEPARATOR), None => matches.get_one::<String>(options::COLUMN_CHAR_SEPARATOR),
} }
.map(ToString::to_string) .map_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string(), ToString::to_string);
.unwrap_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string());
let default_column_width = if matches.contains_id(options::COLUMN_WIDTH) let default_column_width = if matches.contains_id(options::COLUMN_WIDTH)
&& matches.contains_id(options::COLUMN_CHAR_SEPARATOR) && matches.contains_id(options::COLUMN_CHAR_SEPARATOR)
@ -659,17 +660,17 @@ fn build_options(
let offset_spaces = " ".repeat(parse_usize(matches, options::INDENT).unwrap_or(Ok(0))?); let offset_spaces = " ".repeat(parse_usize(matches, options::INDENT).unwrap_or(Ok(0))?);
let join_lines = matches.get_flag(options::JOIN_LINES); let join_lines = matches.get_flag(options::JOIN_LINES);
let col_sep_for_printing = column_mode_options let col_sep_for_printing = column_mode_options.as_ref().map_or_else(
.as_ref() || {
.map(|i| i.column_separator.clone())
.unwrap_or_else(|| {
merge_files_print merge_files_print
.map(|_k| DEFAULT_COLUMN_SEPARATOR.to_string()) .map(|_k| DEFAULT_COLUMN_SEPARATOR.to_string())
.unwrap_or_default() .unwrap_or_default()
}); },
|i| i.column_separator.clone(),
);
let columns_to_print = merge_files_print let columns_to_print =
.unwrap_or_else(|| column_mode_options.as_ref().map(|i| i.columns).unwrap_or(1)); merge_files_print.unwrap_or_else(|| column_mode_options.as_ref().map_or(1, |i| i.columns));
let line_width = if join_lines { let line_width = if join_lines {
None None
@ -677,8 +678,7 @@ fn build_options(
Some( Some(
column_mode_options column_mode_options
.as_ref() .as_ref()
.map(|i| i.width) .map_or(DEFAULT_COLUMN_WIDTH, |i| i.width),
.unwrap_or(DEFAULT_COLUMN_WIDTH),
) )
} else { } else {
page_width page_width
@ -712,8 +712,13 @@ fn open(path: &str) -> Result<Box<dyn Read>, PrError> {
return Ok(Box::new(stdin) as Box<dyn Read>); return Ok(Box::new(stdin) as Box<dyn Read>);
} }
metadata(path) metadata(path).map_or_else(
.map(|i| { |_| {
Err(PrError::NotExists {
file: path.to_string(),
})
},
|i| {
let path_string = path.to_string(); let path_string = path.to_string();
match i.file_type() { match i.file_type() {
#[cfg(unix)] #[cfg(unix)]
@ -733,17 +738,19 @@ fn open(path: &str) -> Result<Box<dyn Read>, PrError> {
} }
_ => Err(PrError::UnknownFiletype { file: path_string }), _ => Err(PrError::UnknownFiletype { file: path_string }),
} }
}) },
.unwrap_or_else(|_| { )
Err(PrError::NotExists {
file: path.to_string(),
})
})
} }
fn split_lines_if_form_feed(file_content: Result<String, std::io::Error>) -> Vec<FileLine> { fn split_lines_if_form_feed(file_content: Result<String, std::io::Error>) -> Vec<FileLine> {
file_content file_content.map_or_else(
.map(|content| { |e| {
vec![FileLine {
line_content: Err(e),
..FileLine::default()
}]
},
|content| {
let mut lines = Vec::new(); let mut lines = Vec::new();
let mut f_occurred = 0; let mut f_occurred = 0;
let mut chunk = Vec::new(); let mut chunk = Vec::new();
@ -772,13 +779,8 @@ fn split_lines_if_form_feed(file_content: Result<String, std::io::Error>) -> Vec
}); });
lines lines
}) },
.unwrap_or_else(|e| { )
vec![FileLine {
line_content: Err(e),
..FileLine::default()
}]
})
} }
fn pr(path: &str, options: &OutputOptions) -> Result<i32, PrError> { fn pr(path: &str, options: &OutputOptions) -> Result<i32, PrError> {
@ -975,8 +977,7 @@ fn write_columns(
let across_mode = options let across_mode = options
.column_mode_options .column_mode_options
.as_ref() .as_ref()
.map(|i| i.across_mode) .is_some_and(|i| i.across_mode);
.unwrap_or(false);
let mut filled_lines = Vec::new(); let mut filled_lines = Vec::new();
if options.merge_files_print.is_some() { if options.merge_files_print.is_some() {
@ -1165,7 +1166,7 @@ fn trailer_content(options: &OutputOptions) -> Vec<String> {
/// If -N is specified the first line number changes otherwise /// If -N is specified the first line number changes otherwise
/// default is 1. /// default is 1.
fn get_start_line_number(opts: &OutputOptions) -> usize { fn get_start_line_number(opts: &OutputOptions) -> usize {
opts.number.as_ref().map(|i| i.first_number).unwrap_or(1) opts.number.as_ref().map_or(1, |i| i.first_number)
} }
/// Returns number of lines to read from input for constructing one page of pr output. /// Returns number of lines to read from input for constructing one page of pr output.
@ -1183,8 +1184,5 @@ fn lines_to_read_for_page(opts: &OutputOptions) -> usize {
/// Returns number of columns to output /// Returns number of columns to output
fn get_columns(opts: &OutputOptions) -> usize { fn get_columns(opts: &OutputOptions) -> usize {
opts.column_mode_options opts.column_mode_options.as_ref().map_or(1, |i| i.columns)
.as_ref()
.map(|i| i.columns)
.unwrap_or(1)
} }

View file

@ -1219,8 +1219,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// "0" is default - threads = num of cores // "0" is default - threads = num of cores
settings.threads = matches settings.threads = matches
.get_one::<String>(options::PARALLEL) .get_one::<String>(options::PARALLEL)
.map(String::from) .map_or_else(|| "0".to_string(), String::from);
.unwrap_or_else(|| "0".to_string());
unsafe { unsafe {
env::set_var("RAYON_NUM_THREADS", &settings.threads); env::set_var("RAYON_NUM_THREADS", &settings.threads);
} }
@ -1238,8 +1237,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let mut tmp_dir = TmpDirWrapper::new( let mut tmp_dir = TmpDirWrapper::new(
matches matches
.get_one::<String>(options::TMP_DIR) .get_one::<String>(options::TMP_DIR)
.map(PathBuf::from) .map_or_else(env::temp_dir, PathBuf::from),
.unwrap_or_else(env::temp_dir),
); );
settings.compress_prog = matches settings.compress_prog = matches

View file

@ -186,8 +186,7 @@ impl ScanUtil for str {
let count = chars let count = chars
.next() .next()
.filter(|&c| c.is_ascii_digit() || c == '-' || c == '+') .filter(|&c| c.is_ascii_digit() || c == '-' || c == '+')
.map(|_| 1 + chars.take_while(char::is_ascii_digit).count()) .map_or(0, |_| 1 + chars.take_while(char::is_ascii_digit).count());
.unwrap_or(0);
if count > 0 { if count > 0 {
F::from_str(&self[..count]).ok().map(|x| (x, count)) F::from_str(&self[..count]).ok().map(|x| (x, count))
@ -643,8 +642,7 @@ impl Stater {
format_str format_str
.char_indices() .char_indices()
.nth(char_index) .nth(char_index)
.map(|(byte_idx, _)| byte_idx) .map_or(format_str.len(), |(byte_idx, _)| byte_idx)
.unwrap_or(format_str.len())
} }
fn handle_percent_case( fn handle_percent_case(
@ -847,8 +845,7 @@ impl Stater {
} else { } else {
matches matches
.get_one::<String>(options::FORMAT) .get_one::<String>(options::FORMAT)
.map(|s| s.as_str()) .map_or("", |s| s.as_str())
.unwrap_or("")
}; };
let use_printf = matches.contains_id(options::PRINTF); let use_printf = matches.contains_id(options::PRINTF);
@ -1025,11 +1022,11 @@ impl Stater {
} }
// time of file birth, human-readable; - if unknown // time of file birth, human-readable; - if unknown
'w' => OutputType::Str( 'w' => {
meta.birth() OutputType::Str(meta.birth().map_or(String::from("-"), |(sec, nsec)| {
.map(|(sec, nsec)| pretty_time(sec as i64, nsec as i64)) pretty_time(sec as i64, nsec as i64)
.unwrap_or(String::from("-")), }))
), }
// time of file birth, seconds since Epoch; 0 if unknown // time of file birth, seconds since Epoch; 0 if unknown
'W' => OutputType::Unsigned(meta.birth().unwrap_or_default().0), 'W' => OutputType::Unsigned(meta.birth().unwrap_or_default().0),

View file

@ -38,8 +38,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let regex = matches.get_flag(options::REGEX); let regex = matches.get_flag(options::REGEX);
let raw_separator = matches let raw_separator = matches
.get_one::<String>(options::SEPARATOR) .get_one::<String>(options::SEPARATOR)
.map(|s| s.as_str()) .map_or("\n", |s| s.as_str());
.unwrap_or("\n");
let separator = if raw_separator.is_empty() { let separator = if raw_separator.is_empty() {
"\0" "\0"
} else { } else {

View file

@ -295,8 +295,7 @@ impl Settings {
settings.inputs = matches settings.inputs = matches
.get_many::<OsString>(options::ARG_FILES) .get_many::<OsString>(options::ARG_FILES)
.map(|v| v.map(Input::from).collect()) .map_or_else(|| vec![Input::default()], |v| v.map(Input::from).collect());
.unwrap_or_else(|| vec![Input::default()]);
settings.verbose = (matches.get_flag(options::verbosity::VERBOSE) settings.verbose = (matches.get_flag(options::verbosity::VERBOSE)
|| settings.inputs.len() > 1) || settings.inputs.len() > 1)

View file

@ -52,8 +52,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let locs = matches let locs = matches
.get_many::<OsString>(options::PATHS) .get_many::<OsString>(options::PATHS)
.map(|v| v.map(Path::new).collect()) .map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
.unwrap_or_else(|| vec![Path::new(".")]);
uu_ls::list(locs, &config) uu_ls::list(locs, &config)
} }