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
single_match_else = "allow" # 66
redundant_else = "allow" # 58
map_unwrap_or = "allow" # 54
cast_precision_loss = "allow" # 52
unnested_or_patterns = "allow" # 40
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 gid = parse_gid(group, spec)?;
if user.chars().next().map(char::is_numeric).unwrap_or(false)
&& group.is_empty()
&& spec != user
{
if user.chars().next().is_some_and(char::is_numeric) && group.is_empty() && spec != user {
// 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
return Err(USimpleError::new(

View file

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

View file

@ -243,14 +243,17 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
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 {
(geteuid(), getegid())
} else {
(getuid(), getgid())
}
});
},
|p| (p.uid, p.gid),
);
state.ids = Some(Ids {
uid,
gid,

View file

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

View file

@ -1160,8 +1160,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let locs = matches
.get_many::<OsString>(options::PATHS)
.map(|v| v.map(Path::new).collect())
.unwrap_or_else(|| vec![Path::new(".")]);
.map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
list(locs, &config)
}
@ -2135,7 +2134,7 @@ fn sort_entries(entries: &mut [PathData], config: &Config, out: &mut BufWriter<S
)
}),
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
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_name()
.to_str()
.map(|res| res.starts_with('.'))
.unwrap_or(false)
.is_some_and(|res| res.starts_with('.'))
}
}

View file

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

View file

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

View file

@ -1219,8 +1219,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// "0" is default - threads = num of cores
settings.threads = matches
.get_one::<String>(options::PARALLEL)
.map(String::from)
.unwrap_or_else(|| "0".to_string());
.map_or_else(|| "0".to_string(), String::from);
unsafe {
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(
matches
.get_one::<String>(options::TMP_DIR)
.map(PathBuf::from)
.unwrap_or_else(env::temp_dir),
.map_or_else(env::temp_dir, PathBuf::from),
);
settings.compress_prog = matches

View file

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

View file

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

View file

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