Enable and fix unused_qualifications lint

Improve code readability
This commit is contained in:
Yuri Astrakhan
2025-04-10 16:54:18 -04:00
parent 4559e974ff
commit 9f56bf5f07
44 changed files with 214 additions and 237 deletions
+1 -1
View File
@@ -589,7 +589,7 @@ pedantic = { level = "deny", priority = -1 }
# Eventually the clippy settings from the `[lints]` section should be moved here.
# In order to use these, all crates have `[lints] workspace = true` section.
[workspace.lints.rust]
# unused_qualifications = "warn"
unused_qualifications = "warn"
[workspace.lints.clippy]
all = { level = "deny", priority = -1 }
+1 -1
View File
@@ -139,7 +139,7 @@ pub fn base_app(about: &'static str, usage: &str) -> Command {
.arg(
Arg::new(options::FILE)
.index(1)
.action(clap::ArgAction::Append)
.action(ArgAction::Append)
.value_hint(clap::ValueHint::FilePath),
)
}
+1 -1
View File
@@ -90,7 +90,7 @@ pub fn uu_app() -> Command {
)
.arg(
Arg::new(options::NAME)
.action(clap::ArgAction::Append)
.action(ArgAction::Append)
.value_hint(clap::ValueHint::AnyPath)
.hide(true)
.trailing_var_arg(true),
+5 -5
View File
@@ -86,7 +86,7 @@ impl LineNumber {
}
}
fn write(&self, writer: &mut impl Write) -> std::io::Result<()> {
fn write(&self, writer: &mut impl Write) -> io::Result<()> {
writer.write_all(&self.buf)
}
}
@@ -288,7 +288,7 @@ pub fn uu_app() -> Command {
.arg(
Arg::new(options::FILE)
.hide(true)
.action(clap::ArgAction::Append)
.action(ArgAction::Append)
.value_hint(clap::ValueHint::FilePath),
)
.arg(
@@ -377,7 +377,7 @@ fn cat_handle<R: FdReadable>(
/// Whether this process is appending to stdout.
#[cfg(unix)]
fn is_appending() -> bool {
let stdout = std::io::stdout();
let stdout = io::stdout();
let flags = match fcntl(stdout.as_raw_fd(), FcntlArg::F_GETFL) {
Ok(flags) => flags,
Err(_) => return false,
@@ -404,7 +404,7 @@ fn cat_path(
let in_info = FileInformation::from_file(&stdin)?;
let mut handle = InputHandle {
reader: stdin,
is_interactive: std::io::stdin().is_terminal(),
is_interactive: io::stdin().is_terminal(),
};
if let Some(out_info) = out_info {
if in_info == *out_info && is_appending() {
@@ -445,7 +445,7 @@ fn cat_path(
}
fn cat_files(files: &[String], options: &OutputOptions) -> UResult<()> {
let out_info = FileInformation::from_file(&std::io::stdout()).ok();
let out_info = FileInformation::from_file(&io::stdout()).ok();
let mut state = OutputState {
line_number: LineNumber::new(),
+1 -1
View File
@@ -312,7 +312,7 @@ struct Options {
files: Vec<PathBuf>,
}
fn parse_command_line(config: clap::Command, args: impl uucore::Args) -> Result<Options> {
fn parse_command_line(config: Command, args: impl uucore::Args) -> Result<Options> {
let matches = config.try_get_matches_from(args)?;
let verbose = matches.get_flag(options::VERBOSE);
+7 -7
View File
@@ -16,9 +16,9 @@ use crate::os_str_to_c_string;
#[derive(Debug)]
pub(crate) struct FTS {
fts: ptr::NonNull<fts_sys::FTS>,
fts: NonNull<fts_sys::FTS>,
entry: Option<ptr::NonNull<fts_sys::FTSENT>>,
entry: Option<NonNull<fts_sys::FTSENT>>,
_phantom_data: PhantomData<fts_sys::FTSENT>,
}
@@ -52,7 +52,7 @@ impl FTS {
// - `compar` is None.
let fts = unsafe { fts_sys::fts_open(path_argv.as_ptr().cast(), options, None) };
let fts = ptr::NonNull::new(fts)
let fts = NonNull::new(fts)
.ok_or_else(|| Error::from_io("fts_open()", io::Error::last_os_error()))?;
Ok(Self {
@@ -110,14 +110,14 @@ impl Drop for FTS {
#[derive(Debug)]
pub(crate) struct EntryRef<'fts> {
pub(crate) pointer: ptr::NonNull<fts_sys::FTSENT>,
pub(crate) pointer: NonNull<fts_sys::FTSENT>,
_fts: PhantomData<&'fts FTS>,
_phantom_data: PhantomData<fts_sys::FTSENT>,
}
impl<'fts> EntryRef<'fts> {
fn new(_fts: &'fts FTS, entry: ptr::NonNull<fts_sys::FTSENT>) -> Self {
fn new(_fts: &'fts FTS, entry: NonNull<fts_sys::FTSENT>) -> Self {
Self {
pointer: entry,
_fts: PhantomData,
@@ -174,7 +174,7 @@ impl<'fts> EntryRef<'fts> {
}
pub(crate) fn access_path(&self) -> Option<&Path> {
ptr::NonNull::new(self.as_ref().fts_accpath)
NonNull::new(self.as_ref().fts_accpath)
.map(|path_ptr| {
// SAFETY: `entry.fts_accpath` is a non-null pointer that is assumed to be valid.
unsafe { CStr::from_ptr(path_ptr.as_ptr()) }
@@ -184,7 +184,7 @@ impl<'fts> EntryRef<'fts> {
}
pub(crate) fn stat(&self) -> Option<&libc::stat> {
ptr::NonNull::new(self.as_ref().fts_statp).map(|stat_ptr| {
NonNull::new(self.as_ref().fts_statp).map(|stat_ptr| {
// SAFETY: `entry.fts_statp` is a non-null pointer that is assumed to be valid.
unsafe { stat_ptr.as_ref() }
})
+1 -1
View File
@@ -350,7 +350,7 @@ pub fn uu_app() -> Command {
.arg(
Arg::new(options::FILE)
.hide(true)
.action(clap::ArgAction::Append)
.action(ArgAction::Append)
.value_parser(ValueParser::os_string())
.value_hint(clap::ValueHint::FilePath),
)
+2 -2
View File
@@ -118,8 +118,8 @@ impl OrderChecker {
// Check if two files are identical by comparing their contents
pub fn are_files_identical(path1: &str, path2: &str) -> io::Result<bool> {
// First compare file sizes
let metadata1 = std::fs::metadata(path1)?;
let metadata2 = std::fs::metadata(path2)?;
let metadata1 = metadata(path1)?;
let metadata2 = metadata(path2)?;
if metadata1.len() != metadata2.len() {
return Ok(false);
+10 -13
View File
@@ -101,7 +101,7 @@ struct Context<'a> {
}
impl<'a> Context<'a> {
fn new(root: &'a Path, target: &'a Path) -> std::io::Result<Self> {
fn new(root: &'a Path, target: &'a Path) -> io::Result<Self> {
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("/.") {
@@ -181,7 +181,7 @@ impl Entry {
if no_target_dir {
let source_is_dir = source.is_dir();
if path_ends_with_terminator(context.target) && source_is_dir {
if let Err(e) = std::fs::create_dir_all(context.target) {
if let Err(e) = fs::create_dir_all(context.target) {
eprintln!("Failed to create directory: {e}");
}
} else {
@@ -305,9 +305,7 @@ fn copy_direntry(
false,
) {
Ok(_) => {}
Err(Error::IoErrContext(e, _))
if e.kind() == std::io::ErrorKind::PermissionDenied =>
{
Err(Error::IoErrContext(e, _)) if e.kind() == io::ErrorKind::PermissionDenied => {
show!(uio_error!(
e,
"cannot open {} for reading",
@@ -580,14 +578,13 @@ fn build_dir(
// we need to allow trivial casts here because some systems like linux have u32 constants in
// in libc while others don't.
#[allow(clippy::unnecessary_cast)]
let mut excluded_perms =
if matches!(options.attributes.ownership, crate::Preserve::Yes { .. }) {
libc::S_IRWXG | libc::S_IRWXO // exclude rwx for group and other
} else if matches!(options.attributes.mode, crate::Preserve::Yes { .. }) {
libc::S_IWGRP | libc::S_IWOTH //exclude w for group and other
} else {
0
} as u32;
let mut excluded_perms = if matches!(options.attributes.ownership, Preserve::Yes { .. }) {
libc::S_IRWXG | libc::S_IRWXO // exclude rwx for group and other
} else if matches!(options.attributes.mode, Preserve::Yes { .. }) {
libc::S_IWGRP | libc::S_IWOTH //exclude w for group and other
} else {
0
} as u32;
let umask = if copy_attributes_from.is_some()
&& matches!(options.attributes.mode, Preserve::Yes { .. })
+6 -6
View File
@@ -737,7 +737,7 @@ pub fn uu_app() -> Command {
Arg::new(options::PROGRESS_BAR)
.long(options::PROGRESS_BAR)
.short('g')
.action(clap::ArgAction::SetTrue)
.action(ArgAction::SetTrue)
.help(
"Display a progress bar. \n\
Note: this feature is not supported by GNU coreutils.",
@@ -2081,7 +2081,7 @@ fn handle_copy_mode(
CopyMode::Update => {
if dest.exists() {
match options.update {
update_control::UpdateMode::ReplaceAll => {
UpdateMode::ReplaceAll => {
copy_helper(
source,
dest,
@@ -2094,17 +2094,17 @@ fn handle_copy_mode(
source_is_stream,
)?;
}
update_control::UpdateMode::ReplaceNone => {
UpdateMode::ReplaceNone => {
if options.debug {
println!("skipped {}", dest.quote());
}
return Ok(PerformedAction::Skipped);
}
update_control::UpdateMode::ReplaceNoneFail => {
UpdateMode::ReplaceNoneFail => {
return Err(Error::Error(format!("not replacing '{}'", dest.display())));
}
update_control::UpdateMode::ReplaceIfOlder => {
UpdateMode::ReplaceIfOlder => {
let dest_metadata = fs::symlink_metadata(dest)?;
let src_time = source_metadata.modified()?;
@@ -2335,7 +2335,7 @@ fn copy_file(
&FileInformation::from_path(source, options.dereference(source_in_command_line))
.context(format!("cannot stat {}", source.quote()))?,
) {
std::fs::hard_link(new_source, dest)?;
fs::hard_link(new_source, dest)?;
if options.verbose {
print_verbose_output(options.parents, progress_bar, source, dest);
+2 -2
View File
@@ -43,7 +43,7 @@ mod options {
/// Command line options for csplit.
pub struct CsplitOptions {
split_name: crate::SplitName,
split_name: SplitName,
keep_files: bool,
quiet: bool,
elide_empty_files: bool,
@@ -661,7 +661,7 @@ pub fn uu_app() -> Command {
.arg(
Arg::new(options::PATTERN)
.hide(true)
.action(clap::ArgAction::Append)
.action(ArgAction::Append)
.required(true),
)
.after_help(AFTER_HELP)
+1 -1
View File
@@ -352,7 +352,7 @@ fn cut_files(mut filenames: Vec<String>, mode: &Mode) {
filenames.push("-".to_owned());
}
let mut out: Box<dyn Write> = if std::io::stdout().is_terminal() {
let mut out: Box<dyn Write> = if stdout().is_terminal() {
Box::new(stdout())
} else {
Box::new(BufWriter::new(stdout())) as Box<dyn Write>
+14 -14
View File
@@ -222,7 +222,7 @@ impl Source {
/// The length of the data source in number of bytes.
///
/// If it cannot be determined, then this function returns 0.
fn len(&self) -> std::io::Result<i64> {
fn len(&self) -> io::Result<i64> {
match self {
Self::File(f) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
_ => Ok(0),
@@ -260,7 +260,7 @@ impl Source {
Err(e) => Err(e),
}
}
Self::File(f) => f.seek(io::SeekFrom::Current(n.try_into().unwrap())),
Self::File(f) => f.seek(SeekFrom::Current(n.try_into().unwrap())),
#[cfg(unix)]
Self::Fifo(f) => io::copy(&mut f.take(n), &mut io::sink()),
}
@@ -470,7 +470,7 @@ impl Input<'_> {
/// Fills a given buffer.
/// Reads in increments of 'self.ibs'.
/// The start of each ibs-sized read follows the previous one.
fn fill_consecutive(&mut self, buf: &mut Vec<u8>) -> std::io::Result<ReadStat> {
fn fill_consecutive(&mut self, buf: &mut Vec<u8>) -> io::Result<ReadStat> {
let mut reads_complete = 0;
let mut reads_partial = 0;
let mut bytes_total = 0;
@@ -501,7 +501,7 @@ impl Input<'_> {
/// Fills a given buffer.
/// Reads in increments of 'self.ibs'.
/// The start of each ibs-sized read is aligned to multiples of ibs; remaining space is filled with the 'pad' byte.
fn fill_blocks(&mut self, buf: &mut Vec<u8>, pad: u8) -> std::io::Result<ReadStat> {
fn fill_blocks(&mut self, buf: &mut Vec<u8>, pad: u8) -> io::Result<ReadStat> {
let mut reads_complete = 0;
let mut reads_partial = 0;
let mut base_idx = 0;
@@ -612,7 +612,7 @@ impl Dest {
return Ok(len);
}
}
f.seek(io::SeekFrom::Current(n.try_into().unwrap()))
f.seek(SeekFrom::Current(n.try_into().unwrap()))
}
#[cfg(unix)]
Self::Fifo(f) => {
@@ -655,7 +655,7 @@ impl Dest {
/// The length of the data destination in number of bytes.
///
/// If it cannot be determined, then this function returns 0.
fn len(&self) -> std::io::Result<i64> {
fn len(&self) -> io::Result<i64> {
match self {
Self::File(f, _) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
_ => Ok(0),
@@ -676,7 +676,7 @@ impl Write for Dest {
.len()
.try_into()
.expect("Internal dd Error: Seek amount greater than signed 64-bit integer");
f.seek(io::SeekFrom::Current(seek_amt))?;
f.seek(SeekFrom::Current(seek_amt))?;
Ok(buf.len())
}
Self::File(f, _) => f.write(buf),
@@ -893,7 +893,7 @@ impl<'a> Output<'a> {
}
/// Flush the output to disk, if configured to do so.
fn sync(&mut self) -> std::io::Result<()> {
fn sync(&mut self) -> io::Result<()> {
if self.settings.oconv.fsync {
self.dst.fsync()
} else if self.settings.oconv.fdatasync {
@@ -905,7 +905,7 @@ impl<'a> Output<'a> {
}
/// Truncate the underlying file to the current stream position, if possible.
fn truncate(&mut self) -> std::io::Result<()> {
fn truncate(&mut self) -> io::Result<()> {
self.dst.truncate()
}
}
@@ -959,7 +959,7 @@ impl BlockWriter<'_> {
};
}
fn write_blocks(&mut self, buf: &[u8]) -> std::io::Result<WriteStat> {
fn write_blocks(&mut self, buf: &[u8]) -> io::Result<WriteStat> {
match self {
Self::Unbuffered(o) => o.write_blocks(buf),
Self::Buffered(o) => o.write_blocks(buf),
@@ -969,7 +969,7 @@ impl BlockWriter<'_> {
/// depending on the command line arguments, this function
/// informs the OS to flush/discard the caches for input and/or output file.
fn flush_caches_full_length(i: &Input, o: &Output) -> std::io::Result<()> {
fn flush_caches_full_length(i: &Input, o: &Output) -> io::Result<()> {
// TODO Better error handling for overflowing `len`.
if i.settings.iflags.nocache {
let offset = 0;
@@ -1001,7 +1001,7 @@ fn flush_caches_full_length(i: &Input, o: &Output) -> std::io::Result<()> {
///
/// If there is a problem reading from the input or writing to
/// this output.
fn dd_copy(mut i: Input, o: Output) -> std::io::Result<()> {
fn dd_copy(mut i: Input, o: Output) -> io::Result<()> {
// The read and write statistics.
//
// These objects are counters, initialized to zero. After each
@@ -1177,7 +1177,7 @@ fn finalize<T>(
prog_tx: &mpsc::Sender<ProgUpdate>,
output_thread: thread::JoinHandle<T>,
truncate: bool,
) -> std::io::Result<()> {
) -> io::Result<()> {
// Flush the output in case a partial write has been buffered but
// not yet written.
let wstat_update = output.flush()?;
@@ -1245,7 +1245,7 @@ fn make_linux_oflags(oflags: &OFlags) -> Option<libc::c_int> {
/// `conv=swab` or `conv=block` command-line arguments. This function
/// mutates the `buf` argument in-place. The returned [`ReadStat`]
/// indicates how many blocks were read.
fn read_helper(i: &mut Input, buf: &mut Vec<u8>, bsize: usize) -> std::io::Result<ReadStat> {
fn read_helper(i: &mut Input, buf: &mut Vec<u8>, bsize: usize) -> io::Result<ReadStat> {
// Local Helper Fns -------------------------------------------------
fn perform_swab(buf: &mut [u8]) {
for base in (1..buf.len()).step_by(2) {
+1 -1
View File
@@ -654,7 +654,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
files.collect()
} else {
// Deduplicate while preserving order
let mut seen = std::collections::HashSet::new();
let mut seen = HashSet::new();
files
.filter(|path| seen.insert(path.clone()))
.collect::<Vec<_>>()
+6 -6
View File
@@ -345,7 +345,7 @@ fn debug_print_args(args: &[OsString]) {
fn check_and_handle_string_args(
arg: &OsString,
prefix_to_test: &str,
all_args: &mut Vec<std::ffi::OsString>,
all_args: &mut Vec<OsString>,
do_debug_print_args: Option<&Vec<OsString>>,
) -> UResult<bool> {
let native_arg = NCvt::convert(arg);
@@ -386,8 +386,8 @@ impl EnvAppData {
fn process_all_string_arguments(
&mut self,
original_args: &Vec<OsString>,
) -> UResult<Vec<std::ffi::OsString>> {
let mut all_args: Vec<std::ffi::OsString> = Vec::new();
) -> UResult<Vec<OsString>> {
let mut all_args: Vec<OsString> = Vec::new();
for arg in original_args {
match arg {
b if check_and_handle_string_args(b, "--split-string", &mut all_args, None)? => {
@@ -454,7 +454,7 @@ impl EnvAppData {
uucore::show_error!("{s}");
}
uucore::show_error!("{ERROR_MSG_S_SHEBANG}");
uucore::error::ExitCode::new(125)
ExitCode::new(125)
}
}
})?;
@@ -751,7 +751,7 @@ fn apply_ignore_signal(opts: &Options<'_>) -> UResult<()> {
for &sig_value in &opts.ignore_signal {
let sig: Signal = (sig_value as i32)
.try_into()
.map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
.map_err(|e| io::Error::from_raw_os_error(e as i32))?;
ignore_signal(sig)?;
}
@@ -786,7 +786,7 @@ mod tests {
#[test]
fn test_split_string_environment_vars_test() {
unsafe { std::env::set_var("FOO", "BAR") };
unsafe { env::set_var("FOO", "BAR") };
assert_eq!(
NCvt::convert(vec!["FOO=bar", "sh", "-c", "echo xBARx =$FOO="]),
parse_args_from_str(&NCvt::convert(r#"FOO=bar sh -c "echo x${FOO}x =\$FOO=""#))
+2 -2
View File
@@ -27,10 +27,10 @@ mod options {
fn print_factors_str(
num_str: &str,
w: &mut io::BufWriter<impl io::Write>,
w: &mut io::BufWriter<impl Write>,
print_exponents: bool,
) -> UResult<()> {
let rx = num_str.trim().parse::<num_bigint::BigUint>();
let rx = num_str.trim().parse::<BigUint>();
let Ok(x) = rx else {
// return Ok(). it's non-fatal and we should try the next number.
show_warning!("{}: {}", num_str.maybe_quote(), rx.unwrap_err());
+20 -27
View File
@@ -7,7 +7,6 @@
use clap::{Arg, ArgAction, ArgMatches, Command};
use std::ffi::OsString;
#[cfg(unix)]
use std::fs::File;
use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
use std::num::TryFromIntError;
@@ -224,7 +223,7 @@ struct HeadOptions {
impl HeadOptions {
///Construct options from matches
pub fn get_from(matches: &clap::ArgMatches) -> Result<Self, String> {
pub fn get_from(matches: &ArgMatches) -> Result<Self, String> {
let mut options = Self::default();
options.quiet = matches.get_flag(options::QUIET_NAME);
@@ -251,12 +250,12 @@ fn wrap_in_stdout_error(err: io::Error) -> io::Error {
)
}
fn read_n_bytes(input: impl Read, n: u64) -> std::io::Result<u64> {
fn read_n_bytes(input: impl Read, n: u64) -> io::Result<u64> {
// Read the first `n` bytes from the `input` reader.
let mut reader = input.take(n);
// Write those bytes to `stdout`.
let stdout = std::io::stdout();
let stdout = io::stdout();
let mut stdout = stdout.lock();
let bytes_written = io::copy(&mut reader, &mut stdout).map_err(wrap_in_stdout_error)?;
@@ -269,12 +268,12 @@ fn read_n_bytes(input: impl Read, n: u64) -> std::io::Result<u64> {
Ok(bytes_written)
}
fn read_n_lines(input: &mut impl std::io::BufRead, n: u64, separator: u8) -> std::io::Result<u64> {
fn read_n_lines(input: &mut impl io::BufRead, n: u64, separator: u8) -> io::Result<u64> {
// Read the first `n` lines from the `input` reader.
let mut reader = take_lines(input, n, separator);
// Write those bytes to `stdout`.
let stdout = std::io::stdout();
let stdout = io::stdout();
let stdout = stdout.lock();
let mut writer = BufWriter::with_capacity(BUF_SIZE, stdout);
@@ -298,10 +297,10 @@ fn catch_too_large_numbers_in_backwards_bytes_or_lines(n: u64) -> Option<usize>
}
}
fn read_but_last_n_bytes(mut input: impl Read, n: u64) -> std::io::Result<u64> {
fn read_but_last_n_bytes(mut input: impl Read, n: u64) -> io::Result<u64> {
let mut bytes_written: u64 = 0;
if let Some(n) = catch_too_large_numbers_in_backwards_bytes_or_lines(n) {
let stdout = std::io::stdout();
let stdout = io::stdout();
let mut stdout = stdout.lock();
bytes_written = copy_all_but_n_bytes(&mut input, &mut stdout, n)
@@ -317,8 +316,8 @@ fn read_but_last_n_bytes(mut input: impl Read, n: u64) -> std::io::Result<u64> {
Ok(bytes_written)
}
fn read_but_last_n_lines(mut input: impl Read, n: u64, separator: u8) -> std::io::Result<u64> {
let stdout = std::io::stdout();
fn read_but_last_n_lines(mut input: impl Read, n: u64, separator: u8) -> io::Result<u64> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
if n == 0 {
return io::copy(&mut input, &mut stdout).map_err(wrap_in_stdout_error);
@@ -370,7 +369,7 @@ fn read_but_last_n_lines(mut input: impl Read, n: u64, separator: u8) -> std::io
/// assert_eq!(find_nth_line_from_end(&mut input, 4, false).unwrap(), 0);
/// assert_eq!(find_nth_line_from_end(&mut input, 1000, false).unwrap(), 0);
/// ```
fn find_nth_line_from_end<R>(input: &mut R, n: u64, separator: u8) -> std::io::Result<u64>
fn find_nth_line_from_end<R>(input: &mut R, n: u64, separator: u8) -> io::Result<u64>
where
R: Read + Seek,
{
@@ -408,14 +407,14 @@ where
}
}
fn is_seekable(input: &mut std::fs::File) -> bool {
fn is_seekable(input: &mut File) -> bool {
let current_pos = input.stream_position();
current_pos.is_ok()
&& input.seek(SeekFrom::End(0)).is_ok()
&& input.seek(SeekFrom::Start(current_pos.unwrap())).is_ok()
}
fn head_backwards_file(input: &mut std::fs::File, options: &HeadOptions) -> std::io::Result<u64> {
fn head_backwards_file(input: &mut File, options: &HeadOptions) -> io::Result<u64> {
let st = input.metadata()?;
let seekable = is_seekable(input);
let blksize_limit = uucore::fs::sane_blksize::sane_blksize_from_metadata(&st);
@@ -426,10 +425,7 @@ fn head_backwards_file(input: &mut std::fs::File, options: &HeadOptions) -> std:
}
}
fn head_backwards_without_seek_file(
input: &mut std::fs::File,
options: &HeadOptions,
) -> std::io::Result<u64> {
fn head_backwards_without_seek_file(input: &mut File, options: &HeadOptions) -> io::Result<u64> {
match options.mode {
Mode::AllButLastBytes(n) => read_but_last_n_bytes(input, n),
Mode::AllButLastLines(n) => read_but_last_n_lines(input, n, options.line_ending.into()),
@@ -437,10 +433,7 @@ fn head_backwards_without_seek_file(
}
}
fn head_backwards_on_seekable_file(
input: &mut std::fs::File,
options: &HeadOptions,
) -> std::io::Result<u64> {
fn head_backwards_on_seekable_file(input: &mut File, options: &HeadOptions) -> io::Result<u64> {
match options.mode {
Mode::AllButLastBytes(n) => {
let size = input.metadata()?.len();
@@ -458,11 +451,11 @@ fn head_backwards_on_seekable_file(
}
}
fn head_file(input: &mut std::fs::File, options: &HeadOptions) -> std::io::Result<u64> {
fn head_file(input: &mut File, options: &HeadOptions) -> io::Result<u64> {
match options.mode {
Mode::FirstBytes(n) => read_n_bytes(input, n),
Mode::FirstLines(n) => read_n_lines(
&mut std::io::BufReader::with_capacity(BUF_SIZE, input),
&mut io::BufReader::with_capacity(BUF_SIZE, input),
n,
options.line_ending.into(),
),
@@ -482,7 +475,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
}
println!("==> standard input <==");
}
let stdin = std::io::stdin();
let stdin = io::stdin();
#[cfg(unix)]
{
@@ -520,7 +513,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
Ok(())
}
(name, false) => {
let mut file = match std::fs::File::open(name) {
let mut file = match File::open(name) {
Ok(f) => f,
Err(err) => {
show!(err.map_err_context(|| format!(
@@ -575,8 +568,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
#[cfg(test)]
mod tests {
use io::Cursor;
use std::ffi::OsString;
use std::io::Cursor;
use super::*;
@@ -691,7 +684,7 @@ mod tests {
#[test]
fn read_early_exit() {
let mut empty = std::io::BufReader::new(std::io::Cursor::new(Vec::new()));
let mut empty = io::BufReader::new(Cursor::new(Vec::new()));
assert!(read_n_bytes(&mut empty, 0).is_ok());
assert!(read_n_lines(&mut empty, 0, b'\n').is_ok());
}
+4 -4
View File
@@ -675,7 +675,7 @@ fn chown_optional_user_group(path: &Path, b: &Behavior) -> UResult<()> {
return Ok(());
};
let meta = match fs::metadata(path) {
let meta = match metadata(path) {
Ok(meta) => meta,
Err(e) => return Err(InstallError::MetadataFailed(e).into()),
};
@@ -859,7 +859,7 @@ fn set_ownership_and_permissions(to: &Path, b: &Behavior) -> UResult<()> {
/// Returns an empty Result or an error in case of failure.
///
fn preserve_timestamps(from: &Path, to: &Path) -> UResult<()> {
let meta = match fs::metadata(from) {
let meta = match metadata(from) {
Ok(meta) => meta,
Err(e) => return Err(InstallError::MetadataFailed(e).into()),
};
@@ -940,14 +940,14 @@ fn copy(from: &Path, to: &Path, b: &Behavior) -> UResult<()> {
fn need_copy(from: &Path, to: &Path, b: &Behavior) -> UResult<bool> {
// Attempt to retrieve metadata for the source file.
// If this fails, assume the file needs to be copied.
let from_meta = match fs::metadata(from) {
let from_meta = match metadata(from) {
Ok(meta) => meta,
Err(_) => return Ok(true),
};
// Attempt to retrieve metadata for the destination file.
// If this fails, assume the file needs to be copied.
let to_meta = match fs::metadata(to) {
let to_meta = match metadata(to) {
Ok(meta) => meta,
Err(_) => return Ok(true),
};
+1 -1
View File
@@ -74,7 +74,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} else {
let sig = (sig as i32)
.try_into()
.map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
.map_err(|e| Error::from_raw_os_error(e as i32))?;
Some(sig)
};
+8 -8
View File
@@ -439,7 +439,7 @@ fn extract_format(options: &clap::ArgMatches) -> (Format, Option<&'static str>)
(Format::Commas, Some(options::format::COMMAS))
} else if options.get_flag(options::format::COLUMNS) {
(Format::Columns, Some(options::format::COLUMNS))
} else if std::io::stdout().is_terminal() {
} else if stdout().is_terminal() {
(Format::Columns, None)
} else {
(Format::OneLine, None)
@@ -559,7 +559,7 @@ fn extract_color(options: &clap::ArgMatches) -> bool {
None => options.contains_id(options::COLOR),
Some(val) => match val.as_str() {
"" | "always" | "yes" | "force" => true,
"auto" | "tty" | "if-tty" => std::io::stdout().is_terminal(),
"auto" | "tty" | "if-tty" => stdout().is_terminal(),
/* "never" | "no" | "none" | */ _ => false,
},
}
@@ -578,7 +578,7 @@ fn extract_hyperlink(options: &clap::ArgMatches) -> bool {
match hyperlink {
"always" | "yes" | "force" => true,
"auto" | "tty" | "if-tty" => std::io::stdout().is_terminal(),
"auto" | "tty" | "if-tty" => stdout().is_terminal(),
"never" | "no" | "none" => false,
_ => unreachable!("should be handled by clap"),
}
@@ -673,7 +673,7 @@ fn extract_quoting_style(options: &clap::ArgMatches, show_control: bool) -> Quot
// By default, `ls` uses Shell escape quoting style when writing to a terminal file
// descriptor and Literal otherwise.
if std::io::stdout().is_terminal() {
if stdout().is_terminal() {
QuotingStyle::Shell {
escape: true,
always_quote: false,
@@ -704,7 +704,7 @@ fn extract_indicator_style(options: &clap::ArgMatches) -> IndicatorStyle {
"never" | "no" | "none" => IndicatorStyle::None,
"always" | "yes" | "force" => IndicatorStyle::Classify,
"auto" | "tty" | "if-tty" => {
if std::io::stdout().is_terminal() {
if stdout().is_terminal() {
IndicatorStyle::Classify
} else {
IndicatorStyle::None
@@ -933,7 +933,7 @@ impl Config {
} else if options.get_flag(options::SHOW_CONTROL_CHARS) {
true
} else {
!std::io::stdout().is_terminal()
!stdout().is_terminal()
};
let mut quoting_style = extract_quoting_style(options, show_control);
@@ -2386,7 +2386,7 @@ fn get_metadata_with_deref_opt(p_buf: &Path, dereference: bool) -> std::io::Resu
fn display_dir_entry_size(
entry: &PathData,
config: &Config,
out: &mut BufWriter<std::io::Stdout>,
out: &mut BufWriter<Stdout>,
) -> (usize, usize, usize, usize, usize, usize) {
// TODO: Cache/memorize the display_* results so we don't have to recalculate them.
if let Some(md) = entry.get_metadata(out) {
@@ -3070,7 +3070,7 @@ fn get_system_time(md: &Metadata, config: &Config) -> Option<SystemTime> {
}
}
fn get_time(md: &Metadata, config: &Config) -> Option<chrono::DateTime<chrono::Local>> {
fn get_time(md: &Metadata, config: &Config) -> Option<DateTime<Local>> {
let time = get_system_time(md, config)?;
Some(time.into())
}

Some files were not shown because too many files have changed in this diff Show More