Skip to content

Commit 5808786

Browse files
authored
Merge pull request #8302 from nyurik/map_unwrap_or
chore: cleanup `map_unwrap_or` lint
2 parents 2f16b14 + e54d9bd commit 5808786

File tree

13 files changed

+74
-94
lines changed

13 files changed

+74
-94
lines changed

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,6 @@ cast_sign_loss = "allow" # 70
642642
struct_excessive_bools = "allow" # 68
643643
single_match_else = "allow" # 66
644644
redundant_else = "allow" # 58
645-
map_unwrap_or = "allow" # 54
646645
cast_precision_loss = "allow" # 52
647646
unnested_or_patterns = "allow" # 40
648647
unnecessary_wraps = "allow" # 37

src/uu/chown/src/chown.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,10 +229,7 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
229229
let uid = parse_uid(user, spec, sep)?;
230230
let gid = parse_gid(group, spec)?;
231231

232-
if user.chars().next().map(char::is_numeric).unwrap_or(false)
233-
&& group.is_empty()
234-
&& spec != user
235-
{
232+
if user.chars().next().is_some_and(char::is_numeric) && group.is_empty() && spec != user {
236233
// if the arg starts with an id numeric value, the group isn't set but the separator is provided,
237234
// we should fail with an error
238235
return Err(USimpleError::new(

src/uu/dir/src/dir.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
5353

5454
let locs = matches
5555
.get_many::<OsString>(options::PATHS)
56-
.map(|v| v.map(Path::new).collect())
57-
.unwrap_or_else(|| vec![Path::new(".")]);
56+
.map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
5857

5958
uu_ls::list(locs, &config)
6059
}

src/uu/id/src/id.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -243,14 +243,17 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
243243
return Ok(());
244244
}
245245

246-
let (uid, gid) = possible_pw.as_ref().map(|p| (p.uid, p.gid)).unwrap_or({
247-
let use_effective = !state.rflag && (state.uflag || state.gflag || state.gsflag);
248-
if use_effective {
249-
(geteuid(), getegid())
250-
} else {
251-
(getuid(), getgid())
252-
}
253-
});
246+
let (uid, gid) = possible_pw.as_ref().map_or(
247+
{
248+
let use_effective = !state.rflag && (state.uflag || state.gflag || state.gsflag);
249+
if use_effective {
250+
(geteuid(), getegid())
251+
} else {
252+
(getuid(), getgid())
253+
}
254+
},
255+
|p| (p.uid, p.gid),
256+
);
254257
state.ids = Some(Ids {
255258
uid,
256259
gid,

src/uu/install/src/install.rs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
376376

377377
let owner = matches
378378
.get_one::<String>(OPT_OWNER)
379-
.map(|s| s.as_str())
380-
.unwrap_or("")
379+
.map_or("", |s| s.as_str())
381380
.to_string();
382381

383382
let owner_id = if owner.is_empty() {
@@ -391,8 +390,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
391390

392391
let group = matches
393392
.get_one::<String>(OPT_GROUP)
394-
.map(|s| s.as_str())
395-
.unwrap_or("")
393+
.map_or("", |s| s.as_str())
396394
.to_string();
397395

398396
let group_id = if group.is_empty() {
@@ -420,8 +418,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
420418
strip_program: String::from(
421419
matches
422420
.get_one::<String>(OPT_STRIP_PROGRAM)
423-
.map(|s| s.as_str())
424-
.unwrap_or(DEFAULT_STRIP_PROGRAM),
421+
.map_or(DEFAULT_STRIP_PROGRAM, |s| s.as_str()),
425422
),
426423
create_leading: matches.get_flag(OPT_CREATE_LEADING),
427424
target_dir,
@@ -503,8 +500,7 @@ fn directory(paths: &[String], b: &Behavior) -> UResult<()> {
503500
/// created immediately
504501
fn is_new_file_path(path: &Path) -> bool {
505502
!path.exists()
506-
&& (path.parent().map(Path::is_dir).unwrap_or(true)
507-
|| path.parent().unwrap().as_os_str().is_empty()) // In case of a simple file
503+
&& (path.parent().is_none_or(Path::is_dir) || path.parent().unwrap().as_os_str().is_empty()) // In case of a simple file
508504
}
509505

510506
/// 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 {
10271023
.parent()
10281024
.and_then(|parent| metadata(parent).ok())
10291025
.filter(|parent_meta| parent_meta.mode() & 0o2000 != 0)
1030-
.map(|parent_meta| parent_meta.gid())
1031-
.unwrap_or(getegid());
1026+
.map_or(getegid(), |parent_meta| parent_meta.gid());
10321027

10331028
to_meta.gid() != expected_gid
10341029
}

src/uu/ls/src/ls.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,8 +1160,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
11601160

11611161
let locs = matches
11621162
.get_many::<OsString>(options::PATHS)
1163-
.map(|v| v.map(Path::new).collect())
1164-
.unwrap_or_else(|| vec![Path::new(".")]);
1163+
.map_or_else(|| vec![Path::new(".")], |v| v.map(Path::new).collect());
11651164

11661165
list(locs, &config)
11671166
}
@@ -2135,7 +2134,7 @@ fn sort_entries(entries: &mut [PathData], config: &Config, out: &mut BufWriter<S
21352134
)
21362135
}),
21372136
Sort::Size => {
2138-
entries.sort_by_key(|k| Reverse(k.get_metadata(out).map(|md| md.len()).unwrap_or(0)));
2137+
entries.sort_by_key(|k| Reverse(k.get_metadata(out).map_or(0, |md| md.len())));
21392138
}
21402139
// The default sort in GNU ls is case insensitive
21412140
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 {
21942193
file_path
21952194
.file_name()
21962195
.to_str()
2197-
.map(|res| res.starts_with('.'))
2198-
.unwrap_or(false)
2196+
.is_some_and(|res| res.starts_with('.'))
21992197
}
22002198
}
22012199

src/uu/mv/src/hardlink.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,7 @@ impl HardlinkTracker {
146146
let has_hardlinks = scanner
147147
.hardlink_groups
148148
.get(&key)
149-
.map(|group| group.len() > 1)
150-
.unwrap_or(false);
149+
.is_some_and(|group| group.len() > 1);
151150

152151
if has_hardlinks {
153152
if options.verbose {

src/uu/pr/src/pr.rs

Lines changed: 39 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -432,12 +432,14 @@ fn build_options(
432432

433433
let header = matches
434434
.get_one::<String>(options::HEADER)
435-
.map(|s| s.as_str())
436-
.unwrap_or(if is_merge_mode || paths[0] == FILE_STDIN {
437-
""
438-
} else {
439-
paths[0]
440-
})
435+
.map_or(
436+
if is_merge_mode || paths[0] == FILE_STDIN {
437+
""
438+
} else {
439+
paths[0]
440+
},
441+
|s| s.as_str(),
442+
)
441443
.to_string();
442444

443445
let default_first_number = NumberingMode::default().first_number;
@@ -604,8 +606,7 @@ fn build_options(
604606
Some(x) => Some(x),
605607
None => matches.get_one::<String>(options::COLUMN_CHAR_SEPARATOR),
606608
}
607-
.map(ToString::to_string)
608-
.unwrap_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string());
609+
.map_or_else(|| DEFAULT_COLUMN_SEPARATOR.to_string(), ToString::to_string);
609610

610611
let default_column_width = if matches.contains_id(options::COLUMN_WIDTH)
611612
&& matches.contains_id(options::COLUMN_CHAR_SEPARATOR)
@@ -659,26 +660,25 @@ fn build_options(
659660
let offset_spaces = " ".repeat(parse_usize(matches, options::INDENT).unwrap_or(Ok(0))?);
660661
let join_lines = matches.get_flag(options::JOIN_LINES);
661662

662-
let col_sep_for_printing = column_mode_options
663-
.as_ref()
664-
.map(|i| i.column_separator.clone())
665-
.unwrap_or_else(|| {
663+
let col_sep_for_printing = column_mode_options.as_ref().map_or_else(
664+
|| {
666665
merge_files_print
667666
.map(|_k| DEFAULT_COLUMN_SEPARATOR.to_string())
668667
.unwrap_or_default()
669-
});
668+
},
669+
|i| i.column_separator.clone(),
670+
);
670671

671-
let columns_to_print = merge_files_print
672-
.unwrap_or_else(|| column_mode_options.as_ref().map(|i| i.columns).unwrap_or(1));
672+
let columns_to_print =
673+
merge_files_print.unwrap_or_else(|| column_mode_options.as_ref().map_or(1, |i| i.columns));
673674

674675
let line_width = if join_lines {
675676
None
676677
} else if columns_to_print > 1 {
677678
Some(
678679
column_mode_options
679680
.as_ref()
680-
.map(|i| i.width)
681-
.unwrap_or(DEFAULT_COLUMN_WIDTH),
681+
.map_or(DEFAULT_COLUMN_WIDTH, |i| i.width),
682682
)
683683
} else {
684684
page_width
@@ -712,8 +712,13 @@ fn open(path: &str) -> Result<Box<dyn Read>, PrError> {
712712
return Ok(Box::new(stdin) as Box<dyn Read>);
713713
}
714714

715-
metadata(path)
716-
.map(|i| {
715+
metadata(path).map_or_else(
716+
|_| {
717+
Err(PrError::NotExists {
718+
file: path.to_string(),
719+
})
720+
},
721+
|i| {
717722
let path_string = path.to_string();
718723
match i.file_type() {
719724
#[cfg(unix)]
@@ -733,17 +738,19 @@ fn open(path: &str) -> Result<Box<dyn Read>, PrError> {
733738
}
734739
_ => Err(PrError::UnknownFiletype { file: path_string }),
735740
}
736-
})
737-
.unwrap_or_else(|_| {
738-
Err(PrError::NotExists {
739-
file: path.to_string(),
740-
})
741-
})
741+
},
742+
)
742743
}
743744

744745
fn split_lines_if_form_feed(file_content: Result<String, std::io::Error>) -> Vec<FileLine> {
745-
file_content
746-
.map(|content| {
746+
file_content.map_or_else(
747+
|e| {
748+
vec![FileLine {
749+
line_content: Err(e),
750+
..FileLine::default()
751+
}]
752+
},
753+
|content| {
747754
let mut lines = Vec::new();
748755
let mut f_occurred = 0;
749756
let mut chunk = Vec::new();
@@ -772,13 +779,8 @@ fn split_lines_if_form_feed(file_content: Result<String, std::io::Error>) -> Vec
772779
});
773780

774781
lines
775-
})
776-
.unwrap_or_else(|e| {
777-
vec![FileLine {
778-
line_content: Err(e),
779-
..FileLine::default()
780-
}]
781-
})
782+
},
783+
)
782784
}
783785

784786
fn pr(path: &str, options: &OutputOptions) -> Result<i32, PrError> {
@@ -975,8 +977,7 @@ fn write_columns(
975977
let across_mode = options
976978
.column_mode_options
977979
.as_ref()
978-
.map(|i| i.across_mode)
979-
.unwrap_or(false);
980+
.is_some_and(|i| i.across_mode);
980981

981982
let mut filled_lines = Vec::new();
982983
if options.merge_files_print.is_some() {
@@ -1165,7 +1166,7 @@ fn trailer_content(options: &OutputOptions) -> Vec<String> {
11651166
/// If -N is specified the first line number changes otherwise
11661167
/// default is 1.
11671168
fn get_start_line_number(opts: &OutputOptions) -> usize {
1168-
opts.number.as_ref().map(|i| i.first_number).unwrap_or(1)
1169+
opts.number.as_ref().map_or(1, |i| i.first_number)
11691170
}
11701171

11711172
/// 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 {
11831184

11841185
/// Returns number of columns to output
11851186
fn get_columns(opts: &OutputOptions) -> usize {
1186-
opts.column_mode_options
1187-
.as_ref()
1188-
.map(|i| i.columns)
1189-
.unwrap_or(1)
1187+
opts.column_mode_options.as_ref().map_or(1, |i| i.columns)
11901188
}

src/uu/sort/src/sort.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1219,8 +1219,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
12191219
// "0" is default - threads = num of cores
12201220
settings.threads = matches
12211221
.get_one::<String>(options::PARALLEL)
1222-
.map(String::from)
1223-
.unwrap_or_else(|| "0".to_string());
1222+
.map_or_else(|| "0".to_string(), String::from);
12241223
unsafe {
12251224
env::set_var("RAYON_NUM_THREADS", &settings.threads);
12261225
}
@@ -1238,8 +1237,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
12381237
let mut tmp_dir = TmpDirWrapper::new(
12391238
matches
12401239
.get_one::<String>(options::TMP_DIR)
1241-
.map(PathBuf::from)
1242-
.unwrap_or_else(env::temp_dir),
1240+
.map_or_else(env::temp_dir, PathBuf::from),
12431241
);
12441242

12451243
settings.compress_prog = matches

src/uu/stat/src/stat.rs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -186,8 +186,7 @@ impl ScanUtil for str {
186186
let count = chars
187187
.next()
188188
.filter(|&c| c.is_ascii_digit() || c == '-' || c == '+')
189-
.map(|_| 1 + chars.take_while(char::is_ascii_digit).count())
190-
.unwrap_or(0);
189+
.map_or(0, |_| 1 + chars.take_while(char::is_ascii_digit).count());
191190

192191
if count > 0 {
193192
F::from_str(&self[..count]).ok().map(|x| (x, count))
@@ -643,8 +642,7 @@ impl Stater {
643642
format_str
644643
.char_indices()
645644
.nth(char_index)
646-
.map(|(byte_idx, _)| byte_idx)
647-
.unwrap_or(format_str.len())
645+
.map_or(format_str.len(), |(byte_idx, _)| byte_idx)
648646
}
649647

650648
fn handle_percent_case(
@@ -847,8 +845,7 @@ impl Stater {
847845
} else {
848846
matches
849847
.get_one::<String>(options::FORMAT)
850-
.map(|s| s.as_str())
851-
.unwrap_or("")
848+
.map_or("", |s| s.as_str())
852849
};
853850

854851
let use_printf = matches.contains_id(options::PRINTF);
@@ -1025,11 +1022,11 @@ impl Stater {
10251022
}
10261023

10271024
// time of file birth, human-readable; - if unknown
1028-
'w' => OutputType::Str(
1029-
meta.birth()
1030-
.map(|(sec, nsec)| pretty_time(sec as i64, nsec as i64))
1031-
.unwrap_or(String::from("-")),
1032-
),
1025+
'w' => {
1026+
OutputType::Str(meta.birth().map_or(String::from("-"), |(sec, nsec)| {
1027+
pretty_time(sec as i64, nsec as i64)
1028+
}))
1029+
}
10331030

10341031
// time of file birth, seconds since Epoch; 0 if unknown
10351032
'W' => OutputType::Unsigned(meta.birth().unwrap_or_default().0),

0 commit comments

Comments
 (0)