1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-30 12:37:49 +00:00

lint: Fix all issues in preparation for enabling clippy::if_not_else

This commit is contained in:
Kamil Ogórek 2023-03-26 20:25:38 +02:00
parent 74b54074e1
commit 68e90eacbb
41 changed files with 278 additions and 280 deletions

View file

@ -160,18 +160,7 @@ pub fn handle_input<R: Read>(
data = data.line_wrap(wrap); data = data.line_wrap(wrap);
} }
if !decode { if decode {
match data.encode() {
Ok(s) => {
wrap_print(&data, &s);
Ok(())
}
Err(_) => Err(USimpleError::new(
1,
"error: invalid input (length must be multiple of 4 characters)",
)),
}
} else {
match data.decode() { match data.decode() {
Ok(s) => { Ok(s) => {
// Silent the warning as we want to the error message // Silent the warning as we want to the error message
@ -184,5 +173,16 @@ pub fn handle_input<R: Read>(
} }
Err(_) => Err(USimpleError::new(1, "error: invalid input")), Err(_) => Err(USimpleError::new(1, "error: invalid input")),
} }
} else {
match data.encode() {
Ok(s) => {
wrap_print(&data, &s);
Ok(())
}
Err(_) => Err(USimpleError::new(
1,
"error: invalid input (length must be multiple of 4 characters)",
)),
}
} }
} }

View file

@ -274,10 +274,10 @@ impl Chmoder {
) )
)); ));
} }
if !self.recursive { if self.recursive {
r = self.chmod_file(file).and(r);
} else {
r = self.walk_dir(file); r = self.walk_dir(file);
} else {
r = self.chmod_file(file).and(r);
} }
} }
r r
@ -360,10 +360,10 @@ impl Chmoder {
naively_expected_new_mode = naive_mode; naively_expected_new_mode = naive_mode;
} }
Err(f) => { Err(f) => {
if !self.quiet { if self.quiet {
return Err(USimpleError::new(1, f));
} else {
return Err(ExitCode::new(1)); return Err(ExitCode::new(1));
} else {
return Err(USimpleError::new(1, f));
} }
} }
} }

View file

@ -198,7 +198,9 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
let user = args.next().unwrap_or(""); let user = args.next().unwrap_or("");
let group = args.next().unwrap_or(""); let group = args.next().unwrap_or("");
let uid = if !user.is_empty() { let uid = if user.is_empty() {
None
} else {
Some(match Passwd::locate(user) { Some(match Passwd::locate(user) {
Ok(u) => u.uid, // We have been able to get the uid Ok(u) => u.uid, // We have been able to get the uid
Err(_) => Err(_) =>
@ -225,10 +227,10 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
} }
} }
}) })
} else {
None
}; };
let gid = if !group.is_empty() { let gid = if group.is_empty() {
None
} else {
Some(match Group::locate(group) { Some(match Group::locate(group) {
Ok(g) => g.gid, Ok(g) => g.gid,
Err(_) => match group.parse() { Err(_) => match group.parse() {
@ -241,8 +243,6 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
} }
}, },
}) })
} else {
None
}; };
if user.chars().next().map(char::is_numeric).unwrap_or(false) if user.chars().next().map(char::is_numeric).unwrap_or(false)

View file

@ -414,10 +414,10 @@ fn set_system_datetime(date: DateTime<Utc>) -> UResult<()> {
let result = unsafe { clock_settime(CLOCK_REALTIME, &timespec) }; let result = unsafe { clock_settime(CLOCK_REALTIME, &timespec) };
if result != 0 { if result == 0 {
Err(std::io::Error::last_os_error().map_err_context(|| "cannot set date".to_string()))
} else {
Ok(()) Ok(())
} else {
Err(std::io::Error::last_os_error().map_err_context(|| "cannot set date".to_string()))
} }
} }

View file

@ -265,10 +265,10 @@ fn make_linux_iflags(iflags: &IFlags) -> Option<libc::c_int> {
flag |= libc::O_SYNC; flag |= libc::O_SYNC;
} }
if flag != 0 { if flag == 0 {
Some(flag)
} else {
None None
} else {
Some(flag)
} }
} }
@ -784,10 +784,10 @@ fn make_linux_oflags(oflags: &OFlags) -> Option<libc::c_int> {
flag |= libc::O_SYNC; flag |= libc::O_SYNC;
} }
if flag != 0 { if flag == 0 {
Some(flag)
} else {
None None
} else {
Some(flag)
} }
} }

View file

@ -83,9 +83,7 @@ where
impl Filesystem { impl Filesystem {
// TODO: resolve uuid in `mount_info.dev_name` if exists // TODO: resolve uuid in `mount_info.dev_name` if exists
pub(crate) fn new(mount_info: MountInfo, file: Option<String>) -> Option<Self> { pub(crate) fn new(mount_info: MountInfo, file: Option<String>) -> Option<Self> {
let _stat_path = if !mount_info.mount_dir.is_empty() { let _stat_path = if mount_info.mount_dir.is_empty() {
mount_info.mount_dir.clone()
} else {
#[cfg(unix)] #[cfg(unix)]
{ {
mount_info.dev_name.clone() mount_info.dev_name.clone()
@ -95,6 +93,8 @@ impl Filesystem {
// On windows, we expect the volume id // On windows, we expect the volume id
mount_info.dev_id.clone() mount_info.dev_id.clone()
} }
} else {
mount_info.mount_dir.clone()
}; };
#[cfg(unix)] #[cfg(unix)]
let usage = FsUsage::new(statfs(_stat_path).ok()?); let usage = FsUsage::new(statfs(_stat_path).ok()?);

View file

@ -38,7 +38,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|s| s.to_owned()) .map(|s| s.to_owned())
.collect(); .collect();
if !dirnames.is_empty() { if dirnames.is_empty() {
return Err(UUsageError::new(1, "missing operand"));
} else {
for path in &dirnames { for path in &dirnames {
let p = Path::new(path); let p = Path::new(path);
match p.parent() { match p.parent() {
@ -59,8 +61,6 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
print!("{separator}"); print!("{separator}");
} }
} else {
return Err(UUsageError::new(1, "missing operand"));
} }
Ok(()) Ok(())

View file

@ -299,7 +299,10 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {
env::set_var(name, val); env::set_var(name, val);
} }
if !opts.program.is_empty() { if opts.program.is_empty() {
// no program provided, so just dump all env vars to stdout
print_env(opts.null);
} else {
// we need to execute a command // we need to execute a command
let (prog, args) = build_command(&mut opts.program); let (prog, args) = build_command(&mut opts.program);
@ -344,9 +347,6 @@ fn run_env(args: impl uucore::Args) -> UResult<()> {
Err(_) => return Err(126.into()), Err(_) => return Err(126.into()),
Ok(_) => (), Ok(_) => (),
} }
} else {
// no program provided, so just dump all env vars to stdout
print_env(opts.null);
} }
Ok(()) Ok(())

View file

@ -185,14 +185,14 @@ pub fn tokens_to_ast(
maybe_dump_rpn(&out_stack); maybe_dump_rpn(&out_stack);
let result = ast_from_rpn(&mut out_stack); let result = ast_from_rpn(&mut out_stack);
if !out_stack.is_empty() { if out_stack.is_empty() {
maybe_dump_ast(&result);
result
} else {
Err( Err(
"syntax error (first RPN token does not represent the root of the expression AST)" "syntax error (first RPN token does not represent the root of the expression AST)"
.to_owned(), .to_owned(),
) )
} else {
maybe_dump_ast(&result);
result
} }
}) })
} }

View file

@ -82,10 +82,10 @@ impl<T: DoubleInt> Montgomery<T> {
// (x + n*m) / R // (x + n*m) / R
// in case of overflow, this is (2¹²⁸ + xnm)/2⁶⁴ - n = xnm/2⁶⁴ + (2⁶⁴ - n) // in case of overflow, this is (2¹²⁸ + xnm)/2⁶⁴ - n = xnm/2⁶⁴ + (2⁶⁴ - n)
let y = T::from_double_width(xnm >> t_bits) let y = T::from_double_width(xnm >> t_bits)
+ if !overflow { + if overflow {
T::zero()
} else {
n.wrapping_neg() n.wrapping_neg()
} else {
T::zero()
}; };
if y >= *n { if y >= *n {
@ -132,10 +132,10 @@ impl<T: DoubleInt> Arithmetic for Montgomery<T> {
let (r, overflow) = a.overflowing_add(&b); let (r, overflow) = a.overflowing_add(&b);
// In case of overflow, a+b = 2⁶⁴ + r = (2⁶⁴ - n) + r (working mod n) // In case of overflow, a+b = 2⁶⁴ + r = (2⁶⁴ - n) + r (working mod n)
let r = if !overflow { let r = if overflow {
r
} else {
r + self.n.wrapping_neg() r + self.n.wrapping_neg()
} else {
r
}; };
// Normalize to [0; n[ // Normalize to [0; n[

View file

@ -580,11 +580,11 @@ impl<'a> Iterator for WordSplit<'a> {
// points to whitespace character OR end of string // points to whitespace character OR end of string
let mut word_nchars = 0; let mut word_nchars = 0;
self.position = match self.string[word_start..].find(|x: char| { self.position = match self.string[word_start..].find(|x: char| {
if !x.is_whitespace() { if x.is_whitespace() {
true
} else {
word_nchars += char_width(x); word_nchars += char_width(x);
false false
} else {
true
} }
}) { }) {
None => self.length, None => self.length,

View file

@ -41,10 +41,10 @@ mod wsa {
let mut data = std::mem::MaybeUninit::<WSADATA>::uninit(); let mut data = std::mem::MaybeUninit::<WSADATA>::uninit();
WSAStartup(0x0202, data.as_mut_ptr()) WSAStartup(0x0202, data.as_mut_ptr())
}; };
if err != 0 { if err == 0 {
Err(io::Error::from_raw_os_error(err))
} else {
Ok(WsaHandle(())) Ok(WsaHandle(()))
} else {
Err(io::Error::from_raw_os_error(err))
} }
} }

View file

@ -203,9 +203,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
for i in 0..=users.len() { for i in 0..=users.len() {
let possible_pw = if !state.user_specified { let possible_pw = if state.user_specified {
None
} else {
match Passwd::locate(users[i].as_str()) { match Passwd::locate(users[i].as_str()) {
Ok(p) => Some(p), Ok(p) => Some(p),
Err(_) => { Err(_) => {
@ -218,6 +216,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
} }
} }
} else {
None
}; };
// GNU's `id` does not support the flags: -p/-P/-A. // GNU's `id` does not support the flags: -p/-P/-A.

View file

@ -399,13 +399,13 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
.unwrap_or("") .unwrap_or("")
.to_string(); .to_string();
let owner_id = if !owner.is_empty() { let owner_id = if owner.is_empty() {
None
} else {
match usr2uid(&owner) { match usr2uid(&owner) {
Ok(u) => Some(u), Ok(u) => Some(u),
Err(_) => return Err(InstallError::InvalidUser(owner.clone()).into()), Err(_) => return Err(InstallError::InvalidUser(owner.clone()).into()),
} }
} else {
None
}; };
let group = matches let group = matches
@ -414,13 +414,13 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
.unwrap_or("") .unwrap_or("")
.to_string(); .to_string();
let group_id = if !group.is_empty() { let group_id = if group.is_empty() {
None
} else {
match grp2gid(&group) { match grp2gid(&group) {
Ok(g) => Some(g), Ok(g) => Some(g),
Err(_) => return Err(InstallError::InvalidGroup(group.clone()).into()), Err(_) => return Err(InstallError::InvalidGroup(group.clone()).into()),
} }
} else {
None
}; };
Ok(Behavior { Ok(Behavior {

View file

@ -2008,16 +2008,16 @@ fn enter_directory(
continue; continue;
} }
Ok(rd) => { Ok(rd) => {
if !listed_ancestors if listed_ancestors
.insert(FileInformation::from_path(&e.p_buf, e.must_dereference)?) .insert(FileInformation::from_path(&e.p_buf, e.must_dereference)?)
{ {
out.flush()?;
show!(LsError::AlreadyListedError(e.p_buf.clone()));
} else {
writeln!(out, "\n{}:", e.p_buf.display())?; writeln!(out, "\n{}:", e.p_buf.display())?;
enter_directory(e, rd, config, out, listed_ancestors)?; enter_directory(e, rd, config, out, listed_ancestors)?;
listed_ancestors listed_ancestors
.remove(&FileInformation::from_path(&e.p_buf, e.must_dereference)?); .remove(&FileInformation::from_path(&e.p_buf, e.must_dereference)?);
} else {
out.flush()?;
show!(LsError::AlreadyListedError(e.p_buf.clone()));
} }
} }
} }
@ -2867,10 +2867,10 @@ fn display_file_name(
// to get correct alignment from later calls to`display_grid()`. // to get correct alignment from later calls to`display_grid()`.
if config.context { if config.context {
if let Some(pad_count) = prefix_context { if let Some(pad_count) = prefix_context {
let security_context = if !matches!(config.format, Format::Commas) { let security_context = if matches!(config.format, Format::Commas) {
pad_left(&path.security_context, pad_count)
} else {
path.security_context.to_owned() path.security_context.to_owned()
} else {
pad_left(&path.security_context, pad_count)
}; };
name = format!("{security_context} {name}"); name = format!("{security_context} {name}");
width += security_context.len() + 1; width += security_context.len() + 1;

View file

@ -55,7 +55,7 @@ impl<'a> Iterator for WhitespaceSplitter<'a> {
.unwrap_or(field.len()), .unwrap_or(field.len()),
); );
self.s = if !rest.is_empty() { Some(rest) } else { None }; self.s = if rest.is_empty() { None } else { Some(rest) };
Some((prefix, field)) Some((prefix, field))
} }

View file

@ -190,14 +190,12 @@ impl FromStr for FormatOptions {
} }
} }
if !precision.is_empty() { if precision.is_empty() {
if let Ok(p) = precision.parse() {
options.precision = Some(p);
} else {
return Err(format!("invalid precision in format '{s}'"));
}
} else {
options.precision = Some(0); options.precision = Some(0);
} else if let Ok(p) = precision.parse() {
options.precision = Some(p);
} else {
return Err(format!("invalid precision in format '{s}'"));
} }
} }

View file

@ -171,12 +171,7 @@ impl OdOptions {
None => Radix::Octal, None => Radix::Octal,
Some(s) => { Some(s) => {
let st = s.as_bytes(); let st = s.as_bytes();
if st.len() != 1 { if st.len() == 1 {
return Err(USimpleError::new(
1,
"Radix must be one of [d, o, n, x]".to_string(),
));
} else {
let radix: char = *(st let radix: char = *(st
.first() .first()
.expect("byte string of length 1 lacks a 0th elem")) .expect("byte string of length 1 lacks a 0th elem"))
@ -193,6 +188,11 @@ impl OdOptions {
)) ))
} }
} }
} else {
return Err(USimpleError::new(
1,
"Radix must be one of [d, o, n, x]".to_string(),
));
} }
} }
}; };

View file

@ -218,10 +218,10 @@ impl Capitalize for str {
fn capitalize(&self) -> String { fn capitalize(&self) -> String {
self.char_indices() self.char_indices()
.fold(String::with_capacity(self.len()), |mut acc, x| { .fold(String::with_capacity(self.len()), |mut acc, x| {
if x.0 != 0 { if x.0 == 0 {
acc.push(x.1);
} else {
acc.push(x.1.to_ascii_uppercase()); acc.push(x.1.to_ascii_uppercase());
} else {
acc.push(x.1);
} }
acc acc
}) })
@ -281,10 +281,10 @@ impl Pinky {
match pts_path.metadata() { match pts_path.metadata() {
#[allow(clippy::unnecessary_cast)] #[allow(clippy::unnecessary_cast)]
Ok(meta) => { Ok(meta) => {
mesg = if meta.mode() & S_IWGRP as u32 != 0 { mesg = if meta.mode() & S_IWGRP as u32 == 0 {
' '
} else {
'*' '*'
} else {
' '
}; };
last_change = meta.atime(); last_change = meta.atime();
} }
@ -312,10 +312,10 @@ impl Pinky {
print!(" {}{:<8.*}", mesg, utmpx::UT_LINESIZE, ut.tty_device()); print!(" {}{:<8.*}", mesg, utmpx::UT_LINESIZE, ut.tty_device());
if self.include_idle { if self.include_idle {
if last_change != 0 { if last_change == 0 {
print!(" {:<6}", idle_string(last_change));
} else {
print!(" {:<6}", "?????"); print!(" {:<6}", "?????");
} else {
print!(" {:<6}", idle_string(last_change));
} }
} }

View file

@ -257,14 +257,14 @@ fn remove(files: &[String], options: &Options) -> bool {
// TODO: When the error is not about missing files // TODO: When the error is not about missing files
// (e.g., permission), even rm -f should fail with // (e.g., permission), even rm -f should fail with
// outputting the error, but there's no easy eay. // outputting the error, but there's no easy eay.
if !options.force { if options.force {
false
} else {
show_error!( show_error!(
"cannot remove {}: No such file or directory", "cannot remove {}: No such file or directory",
filename.quote() filename.quote()
); );
true true
} else {
false
} }
} }
} }

View file

@ -362,16 +362,16 @@ impl<'a> Compare<MergeableFile> for FileComparator<'a> {
// Wait for the child to exit and check its exit code. // Wait for the child to exit and check its exit code.
fn check_child_success(mut child: Child, program: &str) -> UResult<()> { fn check_child_success(mut child: Child, program: &str) -> UResult<()> {
if !matches!( if matches!(
child.wait().map(|e| e.code()), child.wait().map(|e| e.code()),
Ok(Some(0)) | Ok(None) | Err(_) Ok(Some(0)) | Ok(None) | Err(_)
) { ) {
Ok(())
} else {
Err(SortError::CompressProgTerminatedAbnormally { Err(SortError::CompressProgTerminatedAbnormally {
prog: program.to_owned(), prog: program.to_owned(),
} }
.into()) .into())
} else {
Ok(())
} }
} }

View file

@ -198,15 +198,13 @@ pub fn human_numeric_str_cmp(
let a_unit = get_unit(a.chars().next_back()); let a_unit = get_unit(a.chars().next_back());
let b_unit = get_unit(b.chars().next_back()); let b_unit = get_unit(b.chars().next_back());
let ordering = a_unit.cmp(&b_unit); let ordering = a_unit.cmp(&b_unit);
if ordering != Ordering::Equal { if ordering == Ordering::Equal {
if a_info.sign == Sign::Negative {
ordering.reverse()
} else {
ordering
}
} else {
// 3. Number // 3. Number
numeric_str_cmp((a, a_info), (b, b_info)) numeric_str_cmp((a, a_info), (b, b_info))
} else if a_info.sign == Sign::Negative {
ordering.reverse()
} else {
ordering
} }
} }

View file

@ -185,7 +185,9 @@ impl Display for SortError {
line, line,
silent, silent,
} => { } => {
if !silent { if *silent {
Ok(())
} else {
write!( write!(
f, f,
"{}:{}: disorder: {}", "{}:{}: disorder: {}",
@ -193,8 +195,6 @@ impl Display for SortError {
line_number, line_number,
line line
) )
} else {
Ok(())
} }
} }
Self::OpenFailed { path, error } => { Self::OpenFailed { path, error } => {
@ -582,7 +582,15 @@ impl<'a> Line<'a> {
selection.start += num_range.start; selection.start += num_range.start;
selection.end = selection.start + num_range.len(); selection.end = selection.start + num_range.len();
if num_range != (0..0) { if num_range == (0..0) {
// This was not a valid number.
// Report no match at the first non-whitespace character.
let leading_whitespace = self.line[selection.clone()]
.find(|c: char| !c.is_whitespace())
.unwrap_or(0);
selection.start += leading_whitespace;
selection.end += leading_whitespace;
} else {
// include a trailing si unit // include a trailing si unit
if selector.settings.mode == SortMode::HumanNumeric if selector.settings.mode == SortMode::HumanNumeric
&& self.line[selection.end..initial_selection.end] && self.line[selection.end..initial_selection.end]
@ -597,14 +605,6 @@ impl<'a> Line<'a> {
{ {
selection.start -= 1; selection.start -= 1;
} }
} else {
// This was not a valid number.
// Report no match at the first non-whitespace character.
let leading_whitespace = self.line[selection.clone()]
.find(|c: char| !c.is_whitespace())
.unwrap_or(0);
selection.start += leading_whitespace;
selection.end += leading_whitespace;
} }
} }
SortMode::GeneralNumeric => { SortMode::GeneralNumeric => {
@ -1572,10 +1572,7 @@ fn compare_by<'a>(
let mut num_info_index = 0; let mut num_info_index = 0;
let mut parsed_float_index = 0; let mut parsed_float_index = 0;
for selector in &global_settings.selectors { for selector in &global_settings.selectors {
let (a_str, b_str) = if !selector.needs_selection { let (a_str, b_str) = if selector.needs_selection {
// We can select the whole line.
(a.line, b.line)
} else {
let selections = ( let selections = (
a_line_data.selections a_line_data.selections
[a.index * global_settings.precomputed.selections_per_line + selection_index], [a.index * global_settings.precomputed.selections_per_line + selection_index],
@ -1584,6 +1581,9 @@ fn compare_by<'a>(
); );
selection_index += 1; selection_index += 1;
selections selections
} else {
// We can select the whole line.
(a.line, b.line)
}; };
let settings = &selector.settings; let settings = &selector.settings;

View file

@ -200,10 +200,10 @@ impl FixedWidthNumber {
break; break;
} }
} }
if suffix_start != 0 { if suffix_start == 0 {
Err(Overflow)
} else {
Ok(Self { radix, digits }) Ok(Self { radix, digits })
} else {
Err(Overflow)
} }
} }

View file

@ -375,9 +375,7 @@ impl Stater {
}); });
} }
'\\' => { '\\' => {
if !use_printf { if use_printf {
tokens.push(Token::Char('\\'));
} else {
i += 1; i += 1;
if i >= bound { if i >= bound {
show_warning!("backslash at end of format"); show_warning!("backslash at end of format");
@ -414,6 +412,8 @@ impl Stater {
tokens.push(Token::Char(c)); tokens.push(Token::Char(c));
} }
} }
} else {
tokens.push(Token::Char('\\'));
} }
} }
@ -519,7 +519,67 @@ impl Stater {
OsString::from(file) OsString::from(file)
}; };
if !self.show_fs { if self.show_fs {
#[cfg(unix)]
let p = file.as_bytes();
#[cfg(not(unix))]
let p = file.into_string().unwrap();
match statfs(p) {
Ok(meta) => {
let tokens = &self.default_tokens;
for t in tokens.iter() {
match *t {
Token::Char(c) => print!("{c}"),
Token::Directive {
flag,
width,
precision,
format,
} => {
let output = match format {
// free blocks available to non-superuser
'a' => OutputType::Unsigned(meta.avail_blocks()),
// total data blocks in file system
'b' => OutputType::Unsigned(meta.total_blocks()),
// total file nodes in file system
'c' => OutputType::Unsigned(meta.total_file_nodes()),
// free file nodes in file system
'd' => OutputType::Unsigned(meta.free_file_nodes()),
// free blocks in file system
'f' => OutputType::Unsigned(meta.free_blocks()),
// file system ID in hex
'i' => OutputType::UnsignedHex(meta.fsid()),
// maximum length of filenames
'l' => OutputType::Unsigned(meta.namelen()),
// file name
'n' => OutputType::Str(display_name.to_string()),
// block size (for faster transfers)
's' => OutputType::Unsigned(meta.io_size()),
// fundamental block size (for block counts)
'S' => OutputType::Integer(meta.block_size()),
// file system type in hex
't' => OutputType::UnsignedHex(meta.fs_type() as u64),
// file system type in human readable form
'T' => OutputType::Str(pretty_fstype(meta.fs_type()).into()),
_ => OutputType::Unknown,
};
print_it(&output, flag, width, precision);
}
}
}
}
Err(e) => {
show_error!(
"cannot read file system information for {}: {}",
display_name.quote(),
e
);
return 1;
}
}
} else {
let result = if self.follow || stdin_is_fifo && display_name == "-" { let result = if self.follow || stdin_is_fifo && display_name == "-" {
fs::metadata(&file) fs::metadata(&file)
} else { } else {
@ -660,66 +720,6 @@ impl Stater {
return 1; return 1;
} }
} }
} else {
#[cfg(unix)]
let p = file.as_bytes();
#[cfg(not(unix))]
let p = file.into_string().unwrap();
match statfs(p) {
Ok(meta) => {
let tokens = &self.default_tokens;
for t in tokens.iter() {
match *t {
Token::Char(c) => print!("{c}"),
Token::Directive {
flag,
width,
precision,
format,
} => {
let output = match format {
// free blocks available to non-superuser
'a' => OutputType::Unsigned(meta.avail_blocks()),
// total data blocks in file system
'b' => OutputType::Unsigned(meta.total_blocks()),
// total file nodes in file system
'c' => OutputType::Unsigned(meta.total_file_nodes()),
// free file nodes in file system
'd' => OutputType::Unsigned(meta.free_file_nodes()),
// free blocks in file system
'f' => OutputType::Unsigned(meta.free_blocks()),
// file system ID in hex
'i' => OutputType::UnsignedHex(meta.fsid()),
// maximum length of filenames
'l' => OutputType::Unsigned(meta.namelen()),
// file name
'n' => OutputType::Str(display_name.to_string()),
// block size (for faster transfers)
's' => OutputType::Unsigned(meta.io_size()),
// fundamental block size (for block counts)
'S' => OutputType::Integer(meta.block_size()),
// file system type in hex
't' => OutputType::UnsignedHex(meta.fs_type() as u64),
// file system type in human readable form
'T' => OutputType::Str(pretty_fstype(meta.fs_type()).into()),
_ => OutputType::Unknown,
};
print_it(&output, flag, width, precision);
}
}
}
}
Err(e) => {
show_error!(
"cannot read file system information for {}: {}",
display_name.quote(),
e
);
return 1;
}
}
} }
0 0
} }

View file

@ -579,16 +579,16 @@ impl LinesChunkBuffer {
} }
} }
if !&self.chunks.is_empty() { if self.chunks.is_empty() {
// chunks is empty when a file is empty so quitting early here
return Ok(());
} else {
let length = &self.chunks.len(); let length = &self.chunks.len();
let last = &mut self.chunks[length - 1]; let last = &mut self.chunks[length - 1];
if !last.get_buffer().ends_with(&[self.delimiter]) { if !last.get_buffer().ends_with(&[self.delimiter]) {
last.lines += 1; last.lines += 1;
self.lines += 1; self.lines += 1;
} }
} else {
// chunks is empty when a file is empty so quitting early here
return Ok(());
} }
// skip unnecessary chunks and save the first chunk which may hold some lines we have to // skip unnecessary chunks and save the first chunk which may hold some lines we have to

View file

@ -125,10 +125,10 @@ fn tail_file(
show_error!("error reading '{}': {}", input.display_name, err_msg); show_error!("error reading '{}': {}", input.display_name, err_msg);
if settings.follow.is_some() { if settings.follow.is_some() {
let msg = if !settings.retry { let msg = if settings.retry {
"; giving up on this name"
} else {
"" ""
} else {
"; giving up on this name"
}; };
show_error!( show_error!(
"{}: cannot follow end of this type of file{}", "{}: cannot follow end of this type of file{}",
@ -215,11 +215,7 @@ fn tail_stdin(
// pipe // pipe
None => { None => {
header_printer.print_input(input); header_printer.print_input(input);
if !paths::stdin_is_bad_fd() { if paths::stdin_is_bad_fd() {
let mut reader = BufReader::new(stdin());
unbounded_tail(&mut reader, settings)?;
observer.add_stdin(input.display_name.as_str(), Some(Box::new(reader)), true)?;
} else {
set_exit_code(1); set_exit_code(1);
show_error!( show_error!(
"cannot fstat {}: {}", "cannot fstat {}: {}",
@ -233,6 +229,10 @@ fn tail_stdin(
text::BAD_FD text::BAD_FD
); );
} }
} else {
let mut reader = BufReader::new(stdin());
unbounded_tail(&mut reader, settings)?;
observer.add_stdin(input.display_name.as_str(), Some(Box::new(reader)), true)?;
} }
} }
}; };

View file

@ -261,11 +261,11 @@ fn process_error(
Err(f) Err(f)
} }
Some(OutputErrorMode::ExitNoPipe) => { Some(OutputErrorMode::ExitNoPipe) => {
if f.kind() != ErrorKind::BrokenPipe { if f.kind() == ErrorKind::BrokenPipe {
Ok(())
} else {
show_error!("{}: {}", writer.name.maybe_quote(), f); show_error!("{}: {}", writer.name.maybe_quote(), f);
Err(f) Err(f)
} else {
Ok(())
} }
} }
} }

View file

@ -41,10 +41,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|v| v.map(AsRef::as_ref).collect()) .map(|v| v.map(AsRef::as_ref).collect())
.unwrap_or_default(); .unwrap_or_default();
let filename = if !files.is_empty() { let filename = if files.is_empty() {
files[0]
} else {
utmpx::DEFAULT_FILE.as_ref() utmpx::DEFAULT_FILE.as_ref()
} else {
files[0]
}; };
let mut users = Utmpx::iter_all_records_from(filename) let mut users = Utmpx::iter_all_records_from(filename)

View file

@ -316,13 +316,13 @@ fn time_string(ut: &Utmpx) -> String {
fn current_tty() -> String { fn current_tty() -> String {
unsafe { unsafe {
let res = ttyname(STDIN_FILENO); let res = ttyname(STDIN_FILENO);
if !res.is_null() { if res.is_null() {
String::new()
} else {
CStr::from_ptr(res as *const _) CStr::from_ptr(res as *const _)
.to_string_lossy() .to_string_lossy()
.trim_start_matches("/dev/") .trim_start_matches("/dev/")
.to_owned() .to_owned()
} else {
String::new()
} }
} }
} }
@ -402,7 +402,7 @@ impl Who {
&time_string(ut), &time_string(ut),
"", "",
"", "",
if !last.is_control() { &comment } else { "" }, if last.is_control() { "" } else { &comment },
"", "",
); );
} }
@ -482,7 +482,7 @@ impl Who {
let iwgrp = S_IWGRP; let iwgrp = S_IWGRP;
#[cfg(any(target_os = "android", target_os = "freebsd", target_vendor = "apple"))] #[cfg(any(target_os = "android", target_os = "freebsd", target_vendor = "apple"))]
let iwgrp = S_IWGRP as u32; let iwgrp = S_IWGRP as u32;
mesg = if meta.mode() & iwgrp != 0 { '+' } else { '-' }; mesg = if meta.mode() & iwgrp == 0 { '-' } else { '+' };
last_change = meta.atime(); last_change = meta.atime();
} }
_ => { _ => {
@ -491,10 +491,10 @@ impl Who {
} }
} }
let idle = if last_change != 0 { let idle = if last_change == 0 {
idle_string(last_change, 0)
} else {
" ?".into() " ?".into()
} else {
idle_string(last_change, 0)
}; };
let s = if self.do_lookup { let s = if self.do_lookup {

View file

@ -67,10 +67,10 @@ pub fn encode(f: Format, input: &[u8]) -> Result<String, EncodeError> {
Z85 => { Z85 => {
// According to the spec we should not accept inputs whose len is not a multiple of 4. // According to the spec we should not accept inputs whose len is not a multiple of 4.
// However, the z85 crate implements a padded encoding and accepts such inputs. We have to manually check for them. // However, the z85 crate implements a padded encoding and accepts such inputs. We have to manually check for them.
if input.len() % 4 != 0 { if input.len() % 4 == 0 {
return Err(EncodeError::Z85InputLenNotMultipleOf4);
} else {
z85::encode(input) z85::encode(input)
} else {
return Err(EncodeError::Z85InputLenNotMultipleOf4);
} }
} }
}) })

View file

@ -168,10 +168,10 @@ pub struct Passwd {
/// SAFETY: ptr must point to a valid C string. /// SAFETY: ptr must point to a valid C string.
/// Returns None if ptr is null. /// Returns None if ptr is null.
unsafe fn cstr2string(ptr: *const c_char) -> Option<String> { unsafe fn cstr2string(ptr: *const c_char) -> Option<String> {
if !ptr.is_null() { if ptr.is_null() {
Some(CStr::from_ptr(ptr).to_string_lossy().into_owned())
} else {
None None
} else {
Some(CStr::from_ptr(ptr).to_string_lossy().into_owned())
} }
} }

View file

@ -455,6 +455,8 @@ pub fn display_permissions(metadata: &fs::Metadata, display_file_type: bool) ->
display_permissions_unix(mode, display_file_type) display_permissions_unix(mode, display_file_type)
} }
// The logic below is more readable written this way.
#[allow(clippy::if_not_else)]
#[cfg(unix)] #[cfg(unix)]
/// Display the permissions of a file on a unix like system /// Display the permissions of a file on a unix like system
pub fn display_permissions_unix(mode: mode_t, display_file_type: bool) -> String { pub fn display_permissions_unix(mode: mode_t, display_file_type: bool) -> String {

View file

@ -295,10 +295,10 @@ impl MountInfo {
fs_type_buf.len() as u32, fs_type_buf.len() as u32,
) )
}; };
let fs_type = if 0 != success { let fs_type = if 0 == success {
Some(LPWSTR2String(&fs_type_buf))
} else {
None None
} else {
Some(LPWSTR2String(&fs_type_buf))
}; };
let mut mn_info = Self { let mut mn_info = Self {
dev_id: volume_name, dev_id: volume_name,
@ -862,10 +862,10 @@ pub fn pretty_time(sec: i64, nsec: i64) -> String {
pub fn pretty_filetype<'a>(mode: mode_t, size: u64) -> &'a str { pub fn pretty_filetype<'a>(mode: mode_t, size: u64) -> &'a str {
match mode & S_IFMT { match mode & S_IFMT {
S_IFREG => { S_IFREG => {
if size != 0 { if size == 0 {
"regular file"
} else {
"regular empty file" "regular empty file"
} else {
"regular file"
} }
} }
S_IFDIR => "directory", S_IFDIR => "directory",

View file

@ -263,10 +263,10 @@ impl ChownExecutor {
0 0
}; };
if !self.recursive { if self.recursive {
ret
} else {
ret | self.dive_into(&root) ret | self.dive_into(&root)
} else {
ret
} }
} }

View file

@ -58,10 +58,10 @@ pub trait ChildExt {
impl ChildExt for Child { impl ChildExt for Child {
fn send_signal(&mut self, signal: usize) -> io::Result<()> { fn send_signal(&mut self, signal: usize) -> io::Result<()> {
if unsafe { libc::kill(self.id() as pid_t, signal as i32) } != 0 { if unsafe { libc::kill(self.id() as pid_t, signal as i32) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(()) Ok(())
} else {
Err(io::Error::last_os_error())
} }
} }
@ -70,10 +70,10 @@ impl ChildExt for Child {
if unsafe { libc::signal(signal as i32, libc::SIG_IGN) } != 0 { if unsafe { libc::signal(signal as i32, libc::SIG_IGN) } != 0 {
return Err(io::Error::last_os_error()); return Err(io::Error::last_os_error());
} }
if unsafe { libc::kill(0, signal as i32) } != 0 { if unsafe { libc::kill(0, signal as i32) } == 0 {
Err(io::Error::last_os_error())
} else {
Ok(()) Ok(())
} else {
Err(io::Error::last_os_error())
} }
} }

View file

@ -197,30 +197,7 @@ impl SubParser {
self.text_so_far.push(ch); self.text_so_far.push(ch);
match ch { match ch {
'-' | '*' | '0'..='9' => { '-' | '*' | '0'..='9' => {
if !self.past_decimal { if self.past_decimal {
if self.min_width_is_asterisk || self.specifiers_found {
return Err(SubError::InvalidSpec(self.text_so_far.clone()).into());
}
if self.min_width_tmp.is_none() {
self.min_width_tmp = Some(String::new());
}
match self.min_width_tmp.as_mut() {
Some(x) => {
if (ch == '-' || ch == '*') && !x.is_empty() {
return Err(
SubError::InvalidSpec(self.text_so_far.clone()).into()
);
}
if ch == '*' {
self.min_width_is_asterisk = true;
}
x.push(ch);
}
None => {
panic!("should be unreachable");
}
}
} else {
// second field should never have a // second field should never have a
// negative value // negative value
if self.second_field_is_asterisk || ch == '-' || self.specifiers_found { if self.second_field_is_asterisk || ch == '-' || self.specifiers_found {
@ -245,13 +222,36 @@ impl SubParser {
panic!("should be unreachable"); panic!("should be unreachable");
} }
} }
} else {
if self.min_width_is_asterisk || self.specifiers_found {
return Err(SubError::InvalidSpec(self.text_so_far.clone()).into());
}
if self.min_width_tmp.is_none() {
self.min_width_tmp = Some(String::new());
}
match self.min_width_tmp.as_mut() {
Some(x) => {
if (ch == '-' || ch == '*') && !x.is_empty() {
return Err(
SubError::InvalidSpec(self.text_so_far.clone()).into()
);
}
if ch == '*' {
self.min_width_is_asterisk = true;
}
x.push(ch);
}
None => {
panic!("should be unreachable");
}
}
} }
} }
'.' => { '.' => {
if !self.past_decimal { if self.past_decimal {
self.past_decimal = true;
} else {
return Err(SubError::InvalidSpec(self.text_so_far.clone()).into()); return Err(SubError::InvalidSpec(self.text_so_far.clone()).into());
} else {
self.past_decimal = true;
} }
} }
x if legal_fields.binary_search(&x).is_ok() => { x if legal_fields.binary_search(&x).is_ok() => {

View file

@ -135,13 +135,13 @@ impl UnescapedText {
} }
_ => {} _ => {}
} }
if !ignore { if ignore {
byte_vec.push(ch as u8);
} else {
let val = (Self::base_to_u32(min_len, max_len, base, it) % 256) as u8; let val = (Self::base_to_u32(min_len, max_len, base, it) % 256) as u8;
byte_vec.push(val); byte_vec.push(val);
let bvec = [val]; let bvec = [val];
flush_bytes(writer, &bvec); flush_bytes(writer, &bvec);
} else {
byte_vec.push(ch as u8);
} }
} }
e => { e => {

View file

@ -336,7 +336,9 @@ impl Iterator for UtmpxIter {
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
unsafe { unsafe {
let res = getutxent(); let res = getutxent();
if !res.is_null() { if res.is_null() {
None
} else {
// The data behind this pointer will be replaced by the next // The data behind this pointer will be replaced by the next
// call to getutxent(), so we have to read it now. // call to getutxent(), so we have to read it now.
// All the strings live inline in the struct as arrays, which // All the strings live inline in the struct as arrays, which
@ -344,8 +346,6 @@ impl Iterator for UtmpxIter {
Some(Utmpx { Some(Utmpx {
inner: ptr::read(res as *const _), inner: ptr::read(res as *const _),
}) })
} else {
None
} }
} }
} }

View file

@ -259,13 +259,13 @@ fn shell_with_escape(name: &str, quotes: Quotes) -> (String, bool) {
pub fn escape_name(name: &OsStr, style: &QuotingStyle) -> String { pub fn escape_name(name: &OsStr, style: &QuotingStyle) -> String {
match style { match style {
QuotingStyle::Literal { show_control } => { QuotingStyle::Literal { show_control } => {
if !show_control { if *show_control {
name.to_string_lossy().into_owned()
} else {
name.to_string_lossy() name.to_string_lossy()
.chars() .chars()
.flat_map(|c| EscapedChar::new_literal(c).hide_control()) .flat_map(|c| EscapedChar::new_literal(c).hide_control())
.collect() .collect()
} else {
name.to_string_lossy().into_owned()
} }
} }
QuotingStyle::C { quotes } => { QuotingStyle::C { quotes } => {

View file

@ -70,13 +70,13 @@ impl<'parser> Parser<'parser> {
// Get the numeric part of the size argument. For example, if the // Get the numeric part of the size argument. For example, if the
// argument is "123K", then the numeric part is "123". // argument is "123K", then the numeric part is "123".
let numeric_string: String = size.chars().take_while(|c| c.is_ascii_digit()).collect(); let numeric_string: String = size.chars().take_while(|c| c.is_ascii_digit()).collect();
let number: u64 = if !numeric_string.is_empty() { let number: u64 = if numeric_string.is_empty() {
1
} else {
match numeric_string.parse() { match numeric_string.parse() {
Ok(n) => n, Ok(n) => n,
Err(_) => return Err(ParseSizeError::parse_failure(size)), Err(_) => return Err(ParseSizeError::parse_failure(size)),
} }
} else {
1
}; };
// Get the alphabetic units part of the size argument and compute // Get the alphabetic units part of the size argument and compute