Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clippy Pendantic #6720

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion src/uu/chgrp/src/chgrp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ fn parse_gid_and_uid(matches: &ArgMatches) -> UResult<GidUidOwnerFilter> {
} else {
let group = matches
.get_one::<String>(options::ARG_GROUP)
.map(|s| s.as_str())
.map(std::string::String::as_str)
.unwrap_or_default();
raw_group = group.to_string();
if group.is_empty() {
Expand Down
5 changes: 1 addition & 4 deletions src/uu/chown/src/chown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,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(
Expand Down
8 changes: 4 additions & 4 deletions src/uu/chroot/src/chroot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}

let commands = match matches.get_many::<String>(options::COMMAND) {
Some(v) => v.map(|s| s.as_str()).collect(),
Some(v) => v.map(std::string::String::as_str).collect(),
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would prefer just
String::as_str
and have an import

repeating std::string isn't providing much value

None => vec![],
};

Expand Down Expand Up @@ -179,15 +179,15 @@ fn set_context(root: &Path, options: &clap::ArgMatches) -> UResult<()> {
let userspec_str = options.get_one::<String>(options::USERSPEC);
let user_str = options
.get_one::<String>(options::USER)
.map(|s| s.as_str())
.map(std::string::String::as_str)
.unwrap_or_default();
let group_str = options
.get_one::<String>(options::GROUP)
.map(|s| s.as_str())
.map(std::string::String::as_str)
.unwrap_or_default();
let groups_str = options
.get_one::<String>(options::GROUPS)
.map(|s| s.as_str())
.map(std::string::String::as_str)
.unwrap_or_default();
let skip_chdir = options.contains_id(options::SKIP_CHDIR);
let userspec = match userspec_str {
Expand Down
4 changes: 2 additions & 2 deletions src/uu/cksum/src/cksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,13 @@ where
}
}
};
print!("{}", before_filename);
print!("{before_filename}");
if should_print_filename {
// The filename might not be valid UTF-8, and filename.display() would mangle the names.
// Therefore, emit the bytes directly to stdout, without any attempt at encoding them.
let _dropped_result = stdout().write_all(os_str_as_bytes(filename.as_os_str())?);
}
println!("{}", after_filename);
println!("{after_filename}");
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion src/uu/comm/src/comm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ struct LineReader {

impl LineReader {
fn new(input: Input, line_ending: LineEnding) -> Self {
Self { input, line_ending }
Self { line_ending, input }
}

fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
Expand Down
4 changes: 2 additions & 2 deletions src/uu/cp/src/copydir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
let current_dir = env::current_dir()?;
let root_path = current_dir.join(root);
let root_parent = if target.exists() && !root.to_str().unwrap().ends_with("/.") {
root_path.parent().map(|p| p.to_path_buf())
root_path.parent().map(std::path::Path::to_path_buf)
Copy link
Sponsor Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment about Path

Suggested change
root_path.parent().map(std::path::Path::to_path_buf)
root_path.parent().map(Path::to_path_buf)

} else {
Some(root_path)
};
Expand Down Expand Up @@ -175,7 +175,7 @@
let source_is_dir = direntry.path().is_dir();
if path_ends_with_terminator(context.target) && source_is_dir {
if let Err(e) = std::fs::create_dir_all(context.target) {
eprintln!("Failed to create directory: {}", e);
eprintln!("Failed to create directory: {e}");

Check warning on line 178 in src/uu/cp/src/copydir.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/cp/src/copydir.rs#L178

Added line #L178 was not covered by tests
}
} else {
descendant = descendant.strip_prefix(context.root)?.to_path_buf();
Expand Down
2 changes: 1 addition & 1 deletion src/uu/csplit/src/csplit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let patterns: Vec<String> = matches
.get_many::<String>(options::PATTERN)
.unwrap()
.map(|s| s.to_string())
.map(std::string::ToString::to_string)
.collect();
let options = CsplitOptions::new(&matches);
if file_name == "-" {
Expand Down
6 changes: 3 additions & 3 deletions src/uu/csplit/src/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ mod tests {
fn up_to_line_pattern() {
let input: Vec<String> = vec!["24", "42", "{*}", "50", "{4}"]
.into_iter()
.map(|v| v.to_string())
.map(std::string::ToString::to_string)
.collect();
let patterns = get_patterns(input.as_slice()).unwrap();
assert_eq!(patterns.len(), 3);
Expand Down Expand Up @@ -223,7 +223,7 @@ mod tests {
"/test5.*end$/-3",
]
.into_iter()
.map(|v| v.to_string())
.map(std::string::ToString::to_string)
.collect();
let patterns = get_patterns(input.as_slice()).unwrap();
assert_eq!(patterns.len(), 5);
Expand Down Expand Up @@ -277,7 +277,7 @@ mod tests {
"%test5.*end$%-3",
]
.into_iter()
.map(|v| v.to_string())
.map(std::string::ToString::to_string)
.collect();
let patterns = get_patterns(input.as_slice()).unwrap();
assert_eq!(patterns.len(), 5);
Expand Down
5 changes: 1 addition & 4 deletions src/uu/cut/src/cut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,10 +476,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Options {
out_delimiter,
line_ending,
field_opts: Some(FieldOptions {
only_delimited,
delimiter,
})},
field_opts: Some(FieldOptions { delimiter, only_delimited })},
)
}),
(2.., _, _, _) => Err(
Expand Down
2 changes: 1 addition & 1 deletion src/uu/date/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@
None => {
return Err(USimpleError::new(
1,
format!("invalid date {}", relative_time),
format!("invalid date {relative_time}"),

Check warning on line 240 in src/uu/date/src/date.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/date/src/date.rs#L240

Added line #L240 was not covered by tests
));
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/uu/dd/src/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@ const SPACE: u8 = b' ';
/// all-spaces block at the end. Otherwise, remove the last block if
/// it is all spaces.
fn block(buf: &[u8], cbs: usize, sync: bool, rstat: &mut ReadStat) -> Vec<Vec<u8>> {
let mut blocks = buf
.split(|&e| e == NEWLINE)
.map(|split| split.to_vec())
.fold(Vec::new(), |mut blocks, mut split| {
let mut blocks = buf.split(|&e| e == NEWLINE).map(<[u8]>::to_vec).fold(
Vec::new(),
|mut blocks, mut split| {
if split.len() > cbs {
rstat.records_truncated += 1;
}
split.resize(cbs, SPACE);
blocks.push(split);

blocks
});
},
);

// If `sync` is true and there has been at least one partial
// record read from the input, then leave the all-spaces block at
Expand Down
2 changes: 1 addition & 1 deletion src/uu/dd/src/dd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1409,7 +1409,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
&matches
.get_many::<String>(options::OPERANDS)
.unwrap_or_default()
.map(|s| s.as_ref())
.map(std::convert::AsRef::as_ref)
.collect::<Vec<_>>()[..],
)?;

Expand Down
2 changes: 1 addition & 1 deletion src/uu/df/src/columns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl Column {
let names = matches
.get_many::<String>(OPT_OUTPUT)
.unwrap()
.map(|s| s.as_str());
.map(std::string::String::as_str);
let mut seen: Vec<&str> = vec![];
let mut columns = vec![];
for name in names {
Expand Down
4 changes: 2 additions & 2 deletions src/uu/df/src/df.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@
None => {
let filesystems = get_all_filesystems(&opt).map_err(|e| {
let context = "cannot read table of mounted file systems";
USimpleError::new(e.code(), format!("{}: {}", context, e))
USimpleError::new(e.code(), format!("{context}: {e}"))

Check warning on line 447 in src/uu/df/src/df.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/df/src/df.rs#L447

Added line #L447 was not covered by tests
})?;

if filesystems.is_empty() {
Expand All @@ -457,7 +457,7 @@
let paths: Vec<_> = paths.collect();
let filesystems = get_named_filesystems(&paths, &opt).map_err(|e| {
let context = "cannot read table of mounted file systems";
USimpleError::new(e.code(), format!("{}: {}", context, e))
USimpleError::new(e.code(), format!("{context}: {e}"))

Check warning on line 460 in src/uu/df/src/df.rs

View check run for this annotation

Codecov / codecov/patch

src/uu/df/src/df.rs#L460

Added line #L460 was not covered by tests
})?;

// This can happen if paths are given as command-line arguments
Expand Down
4 changes: 3 additions & 1 deletion src/uu/df/src/filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,15 @@ impl Filesystem {
mount_info.mount_dir.clone()
};
#[cfg(unix)]
#[allow(clippy::used_underscore_binding)]
let usage = FsUsage::new(statfs(_stat_path).ok()?);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there are reason to keep this as an underscore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I change it to not an underscore, then I would have to add #[allow(unused_variables)] to the windows side of things.

Copy link
Contributor Author

@dcampbell24 dcampbell24 Sep 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh. in this case I was worried about the possibility of other #[cfg(system)]s existing, like one for browsers, or some other unknown system.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If that's not the case, then why isn't it #[cfg(unix)] and #[cfg(not(unix))].

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably should be yeah!

#[cfg(windows)]
#[allow(clippy::used_underscore_binding)]
let usage = FsUsage::new(Path::new(&_stat_path)).ok()?;
Some(Self {
file,
mount_info,
usage,
file,
})
}

Expand Down
18 changes: 9 additions & 9 deletions src/uu/df/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,12 +841,12 @@ mod tests {
},
usage: crate::table::FsUsage {
blocksize: 4096,
blocks: 244029695,
bfree: 125085030,
bavail: 125085030,
blocks: 244_029_695,
bfree: 125_085_030,
bavail: 125_085_030,
bavail_top_bit_set: false,
files: 999,
ffree: 1000000,
ffree: 1_000_000,
},
};

Expand All @@ -871,12 +871,12 @@ mod tests {
},
usage: crate::table::FsUsage {
blocksize: 4096,
blocks: 244029695,
bfree: 125085030,
bavail: 125085030,
blocks: 244_029_695,
bfree: 125_085_030,
bavail: 125_085_030,
bavail_top_bit_set: false,
files: 99999999999,
ffree: 999999,
files: 99_999_999_999,
ffree: 999_999,
},
};

Expand Down
3 changes: 1 addition & 2 deletions src/uu/dir/src/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,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)
}
Expand Down
19 changes: 9 additions & 10 deletions src/uu/dircolors/src/dircolors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,14 @@ pub fn generate_type_output(fmt: &OutputFmt) -> String {
match fmt {
OutputFmt::Display => FILE_TYPES
.iter()
.map(|&(_, key, val)| format!("\x1b[{}m{}\t{}\x1b[0m", val, key, val))
.map(|&(_, key, val)| format!("\x1b[{val}m{key}\t{val}\x1b[0m"))
.collect::<Vec<String>>()
.join("\n"),
_ => {
// Existing logic for other formats
FILE_TYPES
.iter()
.map(|&(_, v1, v2)| format!("{}={}", v1, v2))
.map(|&(_, v1, v2)| format!("{v1}={v2}"))
.collect::<Vec<String>>()
.join(":")
}
Expand All @@ -100,8 +100,7 @@ fn generate_ls_colors(fmt: &OutputFmt, sep: &str) -> String {
display_parts.push(type_output);
for &(extension, code) in FILE_COLORS {
let prefix = if extension.starts_with('*') { "" } else { "*" };
let formatted_extension =
format!("\x1b[{}m{}{}\t{}\x1b[0m", code, prefix, extension, code);
let formatted_extension = format!("\x1b[{code}m{prefix}{extension}\t{code}\x1b[0m");
display_parts.push(formatted_extension);
}
display_parts.join("\n")
Expand All @@ -111,8 +110,8 @@ fn generate_ls_colors(fmt: &OutputFmt, sep: &str) -> String {
let mut parts = vec![];
for &(extension, code) in FILE_COLORS {
let prefix = if extension.starts_with('*') { "" } else { "*" };
let formatted_extension = format!("{}{}", prefix, extension);
parts.push(format!("{}={}", formatted_extension, code));
let formatted_extension = format!("{prefix}{extension}");
parts.push(format!("{formatted_extension}={code}"));
}
let (prefix, suffix) = get_colors_format_strings(fmt);
let ls_colors = parts.join(sep);
Expand All @@ -133,7 +132,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {

let files = matches
.get_many::<String>(options::FILE)
.map_or(vec![], |file_values| file_values.collect());
.map_or(vec![], std::iter::Iterator::collect);

// clap provides .conflicts_with / .conflicts_with_all, but we want to
// manually handle conflicts so we can match the output of GNU coreutils
Expand Down Expand Up @@ -493,7 +492,7 @@ pub fn generate_dircolors_config() -> String {
);
config.push_str("COLORTERM ?*\n");
for term in TERMS {
config.push_str(&format!("TERM {}\n", term));
config.push_str(&format!("TERM {term}\n"));
}

config.push_str(
Expand All @@ -514,14 +513,14 @@ pub fn generate_dircolors_config() -> String {
);

for (name, _, code) in FILE_TYPES {
config.push_str(&format!("{} {}\n", name, code));
config.push_str(&format!("{name} {code}\n"));
}

config.push_str("# List any file extensions like '.gz' or '.tar' that you would like ls\n");
config.push_str("# to color below. Put the extension, a space, and the color init string.\n");

for (ext, color) in FILE_COLORS {
config.push_str(&format!("{} {}\n", ext, color));
config.push_str(&format!("{ext} {color}\n"));
}
config.push_str("# Subsequent TERM or COLORTERM entries, can be used to add / override\n");
config.push_str("# config specific to those matching environment variables.");
Expand Down
16 changes: 9 additions & 7 deletions src/uu/du/src/du.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ fn read_files_from(file_name: &str) -> Result<Vec<PathBuf>, std::io::Error> {
if path.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("{}: read error: Is a directory", file_name),
format!("{file_name}: read error: Is a directory"),
));
}

Expand All @@ -604,10 +604,7 @@ fn read_files_from(file_name: &str) -> Result<Vec<PathBuf>, std::io::Error> {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"cannot open '{}' for reading: No such file or directory",
file_name
),
format!("cannot open '{file_name}' for reading: No such file or directory"),
))
}
Err(e) => return Err(e),
Expand Down Expand Up @@ -644,7 +641,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let max_depth = parse_depth(
matches
.get_one::<String>(options::MAX_DEPTH)
.map(|s| s.as_str()),
.map(std::string::String::as_str),
summarize,
)?;

Expand Down Expand Up @@ -717,7 +714,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
};

let time_format = if time.is_some() {
parse_time_style(matches.get_one::<String>("time-style").map(|s| s.as_str()))?.to_string()
parse_time_style(
matches
.get_one::<String>("time-style")
.map(std::string::String::as_str),
)?
.to_string()
} else {
"%Y-%m-%d %H:%M".to_string()
};
Expand Down
2 changes: 1 addition & 1 deletion src/uu/echo/src/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let no_newline = matches.get_flag(options::NO_NEWLINE);
let escaped = matches.get_flag(options::ENABLE_BACKSLASH_ESCAPE);
let values: Vec<String> = match matches.get_many::<String>(options::STRING) {
Some(s) => s.map(|s| s.to_string()).collect(),
Some(s) => s.map(std::string::ToString::to_string).collect(),
None => vec![String::new()],
};

Expand Down
Loading
Loading