Skip to content

Commit a067b58

Browse files
authored
Merge pull request uutils#7716 from nyurik/clippy-all
fix low-count lints in all crates
2 parents c1d2a07 + 6e22b69 commit a067b58

File tree

31 files changed

+145
-85
lines changed

31 files changed

+145
-85
lines changed

Cargo.toml

Lines changed: 72 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# coreutils (uutils)
22
# * see the repository LICENSE, README, and CONTRIBUTING files for more information
33

4-
# spell-checker:ignore (libs) bigdecimal datetime serde bincode fundu gethostid kqueue libselinux mangen memmap procfs uuhelp
4+
# spell-checker:ignore (libs) bigdecimal datetime serde bincode fundu gethostid kqueue libselinux mangen memmap procfs uuhelp startswith constness expl
55

66
[package]
77
name = "coreutils"
@@ -599,13 +599,74 @@ pedantic = { level = "deny", priority = -1 }
599599
unused_qualifications = "warn"
600600

601601
[workspace.lints.clippy]
602-
all = { level = "deny", priority = -1 }
603-
#cargo = { level = "warn", priority = -1 }
604-
cognitive_complexity = "warn"
605-
default_trait_access = "warn"
606-
implicit_clone = "warn"
607-
manual_string_new = "warn"
608-
match_bool = "warn"
609-
range-plus-one = "warn"
610-
redundant-clone = "warn"
611-
ref_option = "warn"
602+
# The counts were generated with this command:
603+
# cargo clippy --all-targets --workspace --message-format=json --quiet \
604+
# | jq -r '.message.code.code | select(. != null and startswith("clippy::"))' \
605+
# | sort | uniq -c | sort -h -r
606+
#
607+
# TODO:
608+
# remove large_stack_arrays when https://github.com/rust-lang/rust-clippy/issues/13774 is fixed
609+
#
610+
all = { level = "warn", priority = -1 }
611+
cargo = { level = "warn", priority = -1 }
612+
pedantic = { level = "warn", priority = -1 }
613+
cargo_common_metadata = "allow" # 3240
614+
multiple_crate_versions = "allow" # 2314
615+
missing_errors_doc = "allow" # 1504
616+
missing_panics_doc = "allow" # 946
617+
must_use_candidate = "allow" # 322
618+
doc_markdown = "allow" # 267
619+
match_same_arms = "allow" # 212
620+
unnecessary_semicolon = "allow" # 156
621+
redundant_closure_for_method_calls = "allow" # 133
622+
cast_possible_truncation = "allow" # 118
623+
too_many_lines = "allow" # 81
624+
cast_possible_wrap = "allow" # 76
625+
trivially_copy_pass_by_ref = "allow" # 74
626+
cast_sign_loss = "allow" # 70
627+
struct_excessive_bools = "allow" # 68
628+
single_match_else = "allow" # 66
629+
redundant_else = "allow" # 58
630+
map_unwrap_or = "allow" # 54
631+
cast_precision_loss = "allow" # 52
632+
unnested_or_patterns = "allow" # 40
633+
inefficient_to_string = "allow" # 38
634+
unnecessary_wraps = "allow" # 37
635+
cast_lossless = "allow" # 33
636+
ignored_unit_patterns = "allow" # 29
637+
needless_continue = "allow" # 28
638+
items_after_statements = "allow" # 22
639+
similar_names = "allow" # 20
640+
wildcard_imports = "allow" # 18
641+
used_underscore_binding = "allow" # 16
642+
large_stack_arrays = "allow" # 14
643+
float_cmp = "allow" # 12
644+
# semicolon_if_nothing_returned = "allow" # 9
645+
used_underscore_items = "allow" # 8
646+
return_self_not_must_use = "allow" # 8
647+
needless_pass_by_value = "allow" # 8
648+
# manual_let_else = "allow" # 8
649+
# needless_raw_string_hashes = "allow" # 7
650+
match_on_vec_items = "allow" # 6
651+
inline_always = "allow" # 6
652+
# format_push_string = "allow" # 6
653+
fn_params_excessive_bools = "allow" # 6
654+
# single_char_pattern = "allow" # 4
655+
# ptr_cast_constness = "allow" # 4
656+
# match_wildcard_for_single_variants = "allow" # 4
657+
# manual_is_variant_and = "allow" # 4
658+
# explicit_deref_methods = "allow" # 4
659+
# enum_glob_use = "allow" # 3
660+
# unnecessary_literal_bound = "allow" # 2
661+
# stable_sort_primitive = "allow" # 2
662+
should_panic_without_expect = "allow" # 2
663+
# ptr_as_ptr = "allow" # 2
664+
# needless_for_each = "allow" # 2
665+
if_not_else = "allow" # 2
666+
expl_impl_clone_on_copy = "allow" # 2
667+
# cloned_instead_of_copied = "allow" # 2
668+
# borrow_as_ptr = "allow" # 2
669+
bool_to_int_with_if = "allow" # 2
670+
# ref_as_ptr = "allow" # 2
671+
# unreadable_literal = "allow" # 1
672+
uninlined_format_args = "allow" # ?

src/uu/cat/src/cat.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,8 @@ fn cat_handle<R: FdReadable>(
378378
#[cfg(unix)]
379379
fn is_appending() -> bool {
380380
let stdout = io::stdout();
381-
let flags = match fcntl(stdout.as_raw_fd(), FcntlArg::F_GETFL) {
382-
Ok(flags) => flags,
383-
Err(_) => return false,
381+
let Ok(flags) = fcntl(stdout.as_raw_fd(), FcntlArg::F_GETFL) else {
382+
return false;
384383
};
385384
// TODO Replace `1 << 10` with `nix::fcntl::Oflag::O_APPEND`.
386385
let o_append = 1 << 10;
@@ -814,7 +813,7 @@ mod tests {
814813
}
815814
assert_eq!(b" 100\t", incrementing_string.buf.as_slice());
816815
// Run through until we overflow the original size.
817-
for _ in 101..=1000000 {
816+
for _ in 101..=1_000_000 {
818817
incrementing_string.increment();
819818
}
820819
// Confirm that the buffer expands when we overflow the original size.

src/uu/chroot/src/chroot.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ fn parse_userspec(spec: &str) -> UResult<UserSpec> {
7474

7575
// Pre-condition: `list_str` is non-empty.
7676
fn parse_group_list(list_str: &str) -> Result<Vec<String>, ChrootError> {
77-
let split: Vec<&str> = list_str.split(",").collect();
77+
let split: Vec<&str> = list_str.split(',').collect();
7878
if split.len() == 1 {
7979
let name = split[0].trim();
8080
if name.is_empty() {
@@ -444,7 +444,8 @@ fn enter_chroot(root: &Path, skip_chdir: bool) -> UResult<()> {
444444
CString::new(root.as_os_str().as_bytes().to_vec())
445445
.unwrap()
446446
.as_bytes_with_nul()
447-
.as_ptr() as *const libc::c_char,
447+
.as_ptr()
448+
.cast::<libc::c_char>(),
448449
)
449450
};
450451

src/uu/cp/src/copydir.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ fn adjust_canonicalization(p: &Path) -> Cow<Path> {
4242
.components()
4343
.next()
4444
.and_then(|comp| comp.as_os_str().to_str())
45-
.map(|p_str| p_str.starts_with(VERBATIM_PREFIX) || p_str.starts_with(DEVICE_NS_PREFIX))
46-
.unwrap_or_default();
45+
.is_some_and(|p_str| {
46+
p_str.starts_with(VERBATIM_PREFIX) || p_str.starts_with(DEVICE_NS_PREFIX)
47+
});
4748

4849
if has_prefix {
4950
p.into()

src/uu/dd/src/dd.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ impl Source {
223223
///
224224
/// If it cannot be determined, then this function returns 0.
225225
fn len(&self) -> io::Result<i64> {
226+
#[allow(clippy::match_wildcard_for_single_variants)]
226227
match self {
227228
Self::File(f) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
228229
_ => Ok(0),
@@ -274,6 +275,7 @@ impl Source {
274275
/// then this function returns an error.
275276
#[cfg(target_os = "linux")]
276277
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) -> nix::Result<()> {
278+
#[allow(clippy::match_wildcard_for_single_variants)]
277279
match self {
278280
Self::File(f) => {
279281
let advice = PosixFadviseAdvice::POSIX_FADV_DONTNEED;
@@ -451,7 +453,7 @@ impl Input<'_> {
451453
/// the input file is no longer needed. If not possible, then this
452454
/// function prints an error message to stderr and sets the exit
453455
/// status code to 1.
454-
#[allow(unused_variables)]
456+
#[cfg_attr(not(target_os = "linux"), allow(clippy::unused_self, unused_variables))]
455457
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) {
456458
#[cfg(target_os = "linux")]
457459
{
@@ -626,6 +628,7 @@ impl Dest {
626628

627629
/// Truncate the underlying file to the current stream position, if possible.
628630
fn truncate(&mut self) -> io::Result<()> {
631+
#[allow(clippy::match_wildcard_for_single_variants)]
629632
match self {
630633
Self::File(f, _) => {
631634
let pos = f.stream_position()?;
@@ -656,6 +659,7 @@ impl Dest {
656659
///
657660
/// If it cannot be determined, then this function returns 0.
658661
fn len(&self) -> io::Result<i64> {
662+
#[allow(clippy::match_wildcard_for_single_variants)]
659663
match self {
660664
Self::File(f, _) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
661665
_ => Ok(0),
@@ -824,15 +828,15 @@ impl<'a> Output<'a> {
824828
/// the output file is no longer needed. If not possible, then
825829
/// this function prints an error message to stderr and sets the
826830
/// exit status code to 1.
827-
#[allow(unused_variables)]
831+
#[cfg_attr(not(target_os = "linux"), allow(clippy::unused_self, unused_variables))]
828832
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) {
829833
#[cfg(target_os = "linux")]
830834
{
831835
show_if_err!(self.dst.discard_cache(offset, len).map_err_context(|| {
832836
"failed to discard cache for: 'standard output'".to_string()
833837
}));
834838
}
835-
#[cfg(target_os = "linux")]
839+
#[cfg(not(target_os = "linux"))]
836840
{
837841
// TODO Is there a way to discard filesystem cache on
838842
// these other operating systems?

src/uu/dircolors/src/dircolors.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
use std::borrow::Borrow;
99
use std::env;
10+
use std::fmt::Write as _;
1011
use std::fs::File;
1112
use std::io::{BufRead, BufReader};
1213
use std::path::Path;
@@ -506,7 +507,7 @@ pub fn generate_dircolors_config() -> String {
506507
);
507508
config.push_str("COLORTERM ?*\n");
508509
for term in TERMS {
509-
config.push_str(&format!("TERM {term}\n"));
510+
let _ = writeln!(config, "TERM {term}");
510511
}
511512

512513
config.push_str(
@@ -527,14 +528,14 @@ pub fn generate_dircolors_config() -> String {
527528
);
528529

529530
for (name, _, code) in FILE_TYPES {
530-
config.push_str(&format!("{name} {code}\n"));
531+
let _ = writeln!(config, "{name} {code}");
531532
}
532533

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

536537
for (ext, color) in FILE_COLORS {
537-
config.push_str(&format!("{ext} {color}\n"));
538+
let _ = writeln!(config, "{ext} {color}");
538539
}
539540
config.push_str("# Subsequent TERM or COLORTERM entries, can be used to add / override\n");
540541
config.push_str("# config specific to those matching environment variables.");

src/uu/du/src/du.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -227,9 +227,8 @@ fn get_size_on_disk(path: &Path) -> u64 {
227227

228228
// bind file so it stays in scope until end of function
229229
// if it goes out of scope the handle below becomes invalid
230-
let file = match File::open(path) {
231-
Ok(file) => file,
232-
Err(_) => return size_on_disk, // opening directories will fail
230+
let Ok(file) = File::open(path) else {
231+
return size_on_disk; // opening directories will fail
233232
};
234233

235234
unsafe {
@@ -239,7 +238,7 @@ fn get_size_on_disk(path: &Path) -> u64 {
239238
let success = GetFileInformationByHandleEx(
240239
file.as_raw_handle() as HANDLE,
241240
FileStandardInfo,
242-
file_info_ptr as _,
241+
file_info_ptr.cast(),
243242
size_of::<FILE_STANDARD_INFO>() as u32,
244243
);
245244

@@ -255,9 +254,8 @@ fn get_size_on_disk(path: &Path) -> u64 {
255254
fn get_file_info(path: &Path) -> Option<FileInfo> {
256255
let mut result = None;
257256

258-
let file = match File::open(path) {
259-
Ok(file) => file,
260-
Err(_) => return result,
257+
let Ok(file) = File::open(path) else {
258+
return result;
261259
};
262260

263261
unsafe {
@@ -267,7 +265,7 @@ fn get_file_info(path: &Path) -> Option<FileInfo> {
267265
let success = GetFileInformationByHandleEx(
268266
file.as_raw_handle() as HANDLE,
269267
FileIdInfo,
270-
file_info_ptr as _,
268+
file_info_ptr.cast(),
271269
size_of::<FILE_ID_INFO>() as u32,
272270
);
273271

src/uu/env/src/env.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ use std::borrow::Cow;
2525
use std::env;
2626
use std::ffi::{OsStr, OsString};
2727
use std::io::{self, Write};
28-
use std::ops::Deref;
2928

3029
#[cfg(unix)]
3130
use std::os::unix::ffi::OsStrExt;
@@ -159,11 +158,11 @@ fn parse_signal_opt<'a>(opts: &mut Options<'a>, opt: &'a OsStr) -> UResult<()> {
159158
.collect();
160159

161160
let mut sig_vec = Vec::with_capacity(signals.len());
162-
signals.into_iter().for_each(|sig| {
161+
for sig in signals {
163162
if !sig.is_empty() {
164163
sig_vec.push(sig);
165164
}
166-
});
165+
}
167166
for sig in sig_vec {
168167
let Some(sig_str) = sig.to_str() else {
169168
return Err(USimpleError::new(
@@ -584,7 +583,7 @@ impl EnvAppData {
584583
Err(ref err) => {
585584
return match err.kind() {
586585
io::ErrorKind::NotFound | io::ErrorKind::InvalidInput => {
587-
Err(self.make_error_no_such_file_or_dir(prog.deref()))
586+
Err(self.make_error_no_such_file_or_dir(&prog))
588587
}
589588
io::ErrorKind::PermissionDenied => {
590589
uucore::show_error!("{}: Permission denied", prog.quote());
@@ -804,16 +803,16 @@ mod tests {
804803
);
805804
assert_eq!(
806805
NCvt::convert(vec!["A=B", "FOO=AR", "sh", "-c", "echo $A$FOO"]),
807-
parse_args_from_str(&NCvt::convert(r#"A=B FOO=AR sh -c 'echo $A$FOO'"#)).unwrap()
806+
parse_args_from_str(&NCvt::convert(r"A=B FOO=AR sh -c 'echo $A$FOO'")).unwrap()
808807
);
809808
assert_eq!(
810809
NCvt::convert(vec!["A=B", "FOO=AR", "sh", "-c", "echo $A$FOO"]),
811-
parse_args_from_str(&NCvt::convert(r#"A=B FOO=AR sh -c 'echo $A$FOO'"#)).unwrap()
810+
parse_args_from_str(&NCvt::convert(r"A=B FOO=AR sh -c 'echo $A$FOO'")).unwrap()
812811
);
813812

814813
assert_eq!(
815814
NCvt::convert(vec!["-i", "A=B ' C"]),
816-
parse_args_from_str(&NCvt::convert(r#"-i A='B \' C'"#)).unwrap()
815+
parse_args_from_str(&NCvt::convert(r"-i A='B \' C'")).unwrap()
817816
);
818817
}
819818

@@ -854,7 +853,7 @@ mod tests {
854853
);
855854

856855
// Test variable-related errors
857-
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO"#));
856+
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO"));
858857
assert!(result.is_err());
859858
assert!(
860859
result
@@ -863,7 +862,7 @@ mod tests {
863862
.contains("variable name issue (at 10): Missing closing brace")
864863
);
865864

866-
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO:-value"#));
865+
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO:-value"));
867866
assert!(result.is_err());
868867
assert!(
869868
result
@@ -872,11 +871,11 @@ mod tests {
872871
.contains("variable name issue (at 17): Missing closing brace after default value")
873872
);
874873

875-
let result = parse_args_from_str(&NCvt::convert(r#"echo ${1FOO}"#));
874+
let result = parse_args_from_str(&NCvt::convert(r"echo ${1FOO}"));
876875
assert!(result.is_err());
877876
assert!(result.unwrap_err().to_string().contains("variable name issue (at 7): Unexpected character: '1', expected variable name must not start with 0..9"));
878877

879-
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO?}"#));
878+
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO?}"));
880879
assert!(result.is_err());
881880
assert!(result.unwrap_err().to_string().contains("variable name issue (at 10): Unexpected character: '?', expected a closing brace ('}') or colon (':')"));
882881
}

src/uu/env/src/string_expander.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
use std::{
77
ffi::{OsStr, OsString},
88
mem,
9-
ops::Deref,
109
};
1110

1211
use crate::{
@@ -79,7 +78,7 @@ impl<'a> StringExpander<'a> {
7978

8079
pub fn put_string<S: AsRef<OsStr>>(&mut self, os_str: S) {
8180
let native = to_native_int_representation(os_str.as_ref());
82-
self.output.extend(native.deref());
81+
self.output.extend(&*native);
8382
}
8483

8584
pub fn put_native_string(&mut self, n_str: &NativeIntStr) {

src/uu/expand/src/expand.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ fn expand_line(
356356
tabstops: &[usize],
357357
options: &Options,
358358
) -> std::io::Result<()> {
359-
use self::CharType::*;
359+
use self::CharType::{Backspace, Other, Tab};
360360

361361
let mut col = 0;
362362
let mut byte = 0;

src/uu/expr/src/expr.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
102102
if args.len() == 1 && args[0] == "--help" {
103103
let _ = uu_app().print_help();
104104
} else if args.len() == 1 && args[0] == "--version" {
105-
println!("{} {}", uucore::util_name(), uucore::crate_version!())
105+
println!("{} {}", uucore::util_name(), uucore::crate_version!());
106106
} else {
107107
// The first argument may be "--" and should be be ignored.
108108
let args = if !args.is_empty() && args[0] == "--" {

0 commit comments

Comments
 (0)