Re-enable unused_qualifications lint (#10571)

This commit is contained in:
✿ Fleur de Blue
2026-02-04 04:55:21 +08:00
committed by GitHub
parent a3eab5cc98
commit 2a2cafdbd4
51 changed files with 157 additions and 185 deletions
+2
View File
@@ -21,3 +21,5 @@ lib*.a
### direnv ###
/.direnv/
*.code-workspace
+1 -1
View File
@@ -641,7 +641,7 @@ unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(fuzzing)',
'cfg(target_os, values("cygwin"))',
] }
#unused_qualifications = "warn" // TODO: fix warnings in uucore, then re-enable this lint
unused_qualifications = "warn"
[workspace.lints.clippy]
# The counts were generated with this command:
+1 -1
View File
@@ -66,7 +66,7 @@ pub fn main() {
\n\
#[allow(clippy::too_many_lines)]
#[allow(clippy::unreadable_literal)]
fn util_map<T: uucore::Args>() -> UtilityMap<T> {\n"
fn util_map<T: Args>() -> UtilityMap<T> {\n"
.as_bytes(),
)
.unwrap();
+1
View File
@@ -10,6 +10,7 @@ use std::cmp;
use std::ffi::OsString;
use std::io::{self, Write};
use std::process;
use uucore::Args;
const VERSION: &str = env!("CARGO_PKG_VERSION");
+7 -7
View File
@@ -45,8 +45,8 @@ fn usage<T: Args>(utils: &UtilityMap<T>) {
}
/// Generates the coreutils app for the utility map
fn gen_coreutils_app<T: Args>(util_map: &UtilityMap<T>) -> clap::Command {
let mut command = clap::Command::new("coreutils");
fn gen_coreutils_app<T: Args>(util_map: &UtilityMap<T>) -> Command {
let mut command = Command::new("coreutils");
for (name, (_, sub_app)) in util_map {
// Recreate a small subcommand with only the relevant info
// (name & short description)
@@ -54,7 +54,7 @@ fn gen_coreutils_app<T: Args>(util_map: &UtilityMap<T>) -> clap::Command {
.get_about()
.expect("Could not get the 'about'")
.to_string();
let sub_app = clap::Command::new(name).about(about);
let sub_app = Command::new(name).about(about);
command = command.subcommand(sub_app);
}
command
@@ -172,7 +172,7 @@ fn main() -> io::Result<()> {
}
let utils = util_map::<Box<dyn Iterator<Item = OsString>>>();
match std::fs::create_dir("docs/src/utils/") {
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
x => x,
}?;
@@ -202,7 +202,7 @@ fn main() -> io::Result<()> {
let mut map = HashMap::new();
for platform in ["unix", "macos", "windows", "unix_android"] {
let platform_utils: Vec<String> = String::from_utf8(
std::process::Command::new("./util/show-utils.sh")
process::Command::new("./util/show-utils.sh")
.arg(format!("--features=feat_os_{platform}"))
.output()?
.stdout,
@@ -217,7 +217,7 @@ fn main() -> io::Result<()> {
// Linux is a special case because it can support selinux
let platform_utils: Vec<String> = String::from_utf8(
std::process::Command::new("./util/show-utils.sh")
process::Command::new("./util/show-utils.sh")
.arg("--features=feat_os_unix feat_selinux")
.output()?
.stdout,
@@ -547,7 +547,7 @@ fn write_zip_examples(
};
match format_examples(content, output_markdown) {
Err(e) => Err(std::io::Error::other(format!(
Err(e) => Err(io::Error::other(format!(
"Failed to format the tldr examples of {name}: {e}"
))),
Ok(s) => Ok(s),
+1 -1
View File
@@ -925,7 +925,7 @@ fn format_read_error(error: &io::Error) -> String {
/// Determines if the input buffer contains any padding ('=') ignoring trailing whitespace.
#[cfg(test)]
fn read_and_has_padding<R: std::io::Read>(input: &mut R) -> UResult<(bool, Vec<u8>)> {
fn read_and_has_padding<R: io::Read>(input: &mut R) -> UResult<(bool, Vec<u8>)> {
let mut buf = Vec::new();
input
.read_to_end(&mut buf)
+2 -2
View File
@@ -17,7 +17,7 @@ use crate::bufferedoutput::BufferedOutput;
use blocks::conv_block_unblock_helper;
use datastructures::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
use nix::fcntl::FcntlArg::F_SETFL;
use nix::fcntl::FcntlArg;
#[cfg(any(target_os = "linux", target_os = "android"))]
use nix::fcntl::OFlag;
use parseargs::Parser;
@@ -897,7 +897,7 @@ impl<'a> Output<'a> {
if let Some(libc_flags) = make_linux_oflags(&settings.oflags) {
nix::fcntl::fcntl(
fx.as_raw().as_fd(),
F_SETFL(OFlag::from_bits_retain(libc_flags)),
FcntlArg::F_SETFL(OFlag::from_bits_retain(libc_flags)),
)?;
}
+2 -4
View File
@@ -1027,11 +1027,9 @@ where
// Set environment variable to communicate to Rust child processes
// that SIGPIPE should be default (not ignored)
if matches!(action_kind, SignalActionKind::Default)
&& sig_value == nix::libc::SIGPIPE as usize
{
if matches!(action_kind, SignalActionKind::Default) && sig_value == libc::SIGPIPE as usize {
unsafe {
std::env::set_var("RUST_SIGPIPE", "default");
env::set_var("RUST_SIGPIPE", "default");
}
}
+1 -1
View File
@@ -514,7 +514,7 @@ fn process_utf8_chars<W: Write>(line: &str, ctx: &mut FoldContext<'_, W>) -> URe
// not coalesce zero-width scalars there.
if ctx.mode == WidthMode::Columns {
while let Some(&(_, next_ch)) = iter.peek() {
if unicode_width::UnicodeWidthChar::width(next_ch).unwrap_or(1) == 0 {
if UnicodeWidthChar::width(next_ch).unwrap_or(1) == 0 {
iter.next();
} else {
break;
+2 -2
View File
@@ -478,7 +478,7 @@ impl<'a> StyleManager<'a> {
}
#[cfg(unix)]
fn indicator_for_special_file(&self, file_type: &std::fs::FileType) -> Option<Indicator> {
fn indicator_for_special_file(&self, file_type: &fs::FileType) -> Option<Indicator> {
if file_type.is_fifo() && self.has_indicator_style(Indicator::FIFO) {
return Some(Indicator::FIFO);
}
@@ -495,7 +495,7 @@ impl<'a> StyleManager<'a> {
}
#[cfg(not(unix))]
fn indicator_for_special_file(&self, _file_type: &std::fs::FileType) -> Option<Indicator> {
fn indicator_for_special_file(&self, _file_type: &fs::FileType) -> Option<Indicator> {
None
}
+1 -1
View File
@@ -3574,7 +3574,7 @@ fn get_security_context<'a>(
// For SMACK, use the path to get the label
// If must_dereference is true, we follow the symlink
let target_path = if must_dereference {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
} else {
path.to_path_buf()
};
+1 -3
View File
@@ -88,9 +88,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let set_security_context = matches.get_flag(options::SECURITY_CONTEXT);
let context = matches.get_one::<String>(options::CONTEXT);
if set_security_context || context.is_some() {
uucore::smack::set_smack_label_and_cleanup(&f, context, |p| {
std::fs::remove_file(p)
})?;
uucore::smack::set_smack_label_and_cleanup(&f, context, |p| fs::remove_file(p))?;
}
}
}
+2 -2
View File
@@ -431,7 +431,7 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()>
OverwriteMode::Force => {}
OverwriteMode::Default => {
let (writable, mode) = is_writable(target);
if !writable && std::io::stdin().is_terminal() {
if !writable && io::stdin().is_terminal() {
prompt_overwrite(target, mode)?;
}
}
@@ -741,7 +741,7 @@ fn rename(
OverwriteMode::Default => {
// GNU mv prompts when stdin is a TTY and target is not writable
let (writable, mode) = is_writable(to);
if !writable && std::io::stdin().is_terminal() {
if !writable && io::stdin().is_terminal() {
prompt_overwrite(to, mode)?;
}
}
+1 -1
View File
@@ -591,7 +591,7 @@ fn extract_strings_from_input(
// Apply skip_bytes by reading and discarding
let mut skipped = 0u64;
while skipped < skip_bytes {
let to_skip = std::cmp::min(8192, skip_bytes - skipped);
let to_skip = cmp::min(8192, skip_bytes - skipped);
let mut skip_buf = vec![0u8; to_skip as usize];
match mf.read(&mut skip_buf) {
Ok(0) => break, // EOF reached
+1 -1
View File
@@ -72,7 +72,7 @@ fn verbose_removed_directory(path: &Path, options: &Options) {
}
/// Helper function to show error with context and return error status
fn show_removal_error(error: std::io::Error, path: &Path) -> bool {
fn show_removal_error(error: io::Error, path: &Path) -> bool {
if error.kind() == io::ErrorKind::PermissionDenied {
show_error!("cannot remove {}: Permission denied", path.quote());
} else {
+1 -1
View File
@@ -67,7 +67,7 @@ impl SeededRng {
hasher.update(seed.as_bytes());
let seed = hasher.finalize();
let seed = seed.as_slice().try_into().unwrap();
Self(Box::new(rand_chacha::ChaCha12Rng::from_seed(seed)))
Self(Box::new(ChaCha12Rng::from_seed(seed)))
}
#[allow(clippy::many_single_char_names)] // use original lemire names for easy comparison
+7 -7
View File
@@ -7,7 +7,7 @@
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{BufReader, BufWriter, Error, Read, Write, stdin, stdout};
use std::io::{self, BufReader, BufWriter, Read, Write, stdin, stdout};
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::str::FromStr;
@@ -149,7 +149,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
|| translate!("shuf-error-failed-to-open-random-source", "file" => r.quote()),
)?;
let file = BufReader::new(file);
WrappedRng::File(compat_random_source::RandomSourceAdapter::new(file))
WrappedRng::File(RandomSourceAdapter::new(file))
}
};
@@ -362,24 +362,24 @@ impl Shufable for RangeInclusive<u64> {
}
trait Writable {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), Error>;
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), io::Error>;
}
impl Writable for &[u8] {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), Error> {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), io::Error> {
output.write_all(self)
}
}
impl Writable for &OsStr {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), Error> {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), io::Error> {
output.write_all_os(self)
}
}
impl Writable for u64 {
#[inline]
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), Error> {
fn write_all_to(&self, output: &mut impl OsWrite) -> Result<(), io::Error> {
// The itoa crate is surprisingly much more efficient than a formatted write.
// It speeds up `shuf -r -n1000000 -i1-1024` by 1.8×.
let mut buf = itoa::Buffer::new();
@@ -389,7 +389,7 @@ impl Writable for u64 {
#[cold]
#[inline(never)]
fn handle_write_error(e: std::io::Error) -> Box<dyn uucore::error::UError> {
fn handle_write_error(e: io::Error) -> Box<dyn uucore::error::UError> {
use uucore::error::FromIo;
let ctx = translate!("shuf-error-write-failed");
e.map_err_context(move || ctx)
+6 -10
View File
@@ -6,10 +6,6 @@
//! Heuristics for determining buffer size for external sorting.
use std::ffi::OsString;
use crate::{
FALLBACK_AUTOMATIC_BUF_SIZE, MAX_AUTOMATIC_BUF_SIZE, MIN_AUTOMATIC_BUF_SIZE, STDIN_FILE,
};
// Heuristics to size the external sort buffer without overcommit memory.
pub(crate) fn automatic_buffer_size(files: &[OsString]) -> usize {
let file_hint = file_size_hint(files);
@@ -20,7 +16,7 @@ pub(crate) fn automatic_buffer_size(files: &[OsString]) -> usize {
(Some(file), Some(mem)) => file.min(mem),
(Some(file), None) => file,
(None, Some(mem)) => mem,
(None, None) => FALLBACK_AUTOMATIC_BUF_SIZE,
(None, None) => crate::FALLBACK_AUTOMATIC_BUF_SIZE,
}
}
@@ -29,7 +25,7 @@ fn file_size_hint(files: &[OsString]) -> Option<usize> {
let mut total_bytes: u128 = 0;
for file in files {
if file == STDIN_FILE {
if file == crate::STDIN_FILE {
continue;
}
@@ -43,7 +39,7 @@ fn file_size_hint(files: &[OsString]) -> Option<usize> {
total_bytes = total_bytes.saturating_add(metadata.len() as u128);
if total_bytes >= (MAX_AUTOMATIC_BUF_SIZE as u128) * 8 {
if total_bytes >= (crate::MAX_AUTOMATIC_BUF_SIZE as u128) * 8 {
break;
}
}
@@ -66,8 +62,8 @@ fn available_memory_hint() -> Option<usize> {
}
fn clamp_hint(bytes: u128) -> usize {
let min = MIN_AUTOMATIC_BUF_SIZE as u128;
let max = MAX_AUTOMATIC_BUF_SIZE as u128;
let min = crate::MIN_AUTOMATIC_BUF_SIZE as u128;
let max = crate::MAX_AUTOMATIC_BUF_SIZE as u128;
let clamped = bytes.clamp(min, max);
clamped.min(usize::MAX as u128) as usize
}
@@ -77,7 +73,7 @@ fn desired_file_buffer_bytes(total_bytes: u128) -> u128 {
return 0;
}
let max = MAX_AUTOMATIC_BUF_SIZE as u128;
let max = crate::MAX_AUTOMATIC_BUF_SIZE as u128;
if total_bytes <= max {
return total_bytes.saturating_mul(12).clamp(total_bytes, max);
+1 -1
View File
@@ -24,7 +24,7 @@ use crate::{
};
const MAX_TOKEN_BUFFER_BYTES: usize = 4 * 1024 * 1024;
const MAX_TOKEN_BUFFER_ELEMS: usize = MAX_TOKEN_BUFFER_BYTES / std::mem::size_of::<Range<usize>>();
const MAX_TOKEN_BUFFER_ELEMS: usize = MAX_TOKEN_BUFFER_BYTES / size_of::<Range<usize>>();
self_cell!(
/// The chunk that is passed around between threads.
+1 -1
View File
@@ -2306,7 +2306,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Initialize locale collation if needed (UTF-8 locales)
// This MUST happen before init_precomputed() to avoid the performance regression
#[cfg(feature = "i18n-collator")]
let needs_locale_collation = uucore::i18n::collator::init_locale_collation();
let needs_locale_collation = i18n::collator::init_locale_collation();
#[cfg(not(feature = "i18n-collator"))]
let needs_locale_collation = false;
+1 -1
View File
@@ -210,7 +210,7 @@ fn tail_file(
/// After opening, we clear O_NONBLOCK so subsequent reads block normally.
/// Without `--pid`, FIFOs block on open() until a writer connects (GNU behavior).
#[cfg(unix)]
fn open_file(path: &Path, use_nonblock_for_fifo: bool) -> std::io::Result<File> {
fn open_file(path: &Path, use_nonblock_for_fifo: bool) -> io::Result<File> {
use nix::fcntl::{FcntlArg, OFlag, fcntl};
use std::fs::OpenOptions;
use std::os::fd::AsFd;
+1 -1
View File
@@ -188,7 +188,7 @@ fn install_sigchld() {
/// We should terminate child process when receiving termination signals.
static SIGNALED: AtomicBool = AtomicBool::new(false);
/// Track which signal was received (0 = none/timeout expired naturally).
static RECEIVED_SIGNAL: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
static RECEIVED_SIGNAL: atomic::AtomicI32 = atomic::AtomicI32::new(0);
/// Install signal handlers for termination signals.
fn install_signal_handlers(term_signal: usize) {
+1 -1
View File
@@ -151,7 +151,7 @@ enum TsortError {
/// Wrapper for bubbling up IO errors
#[error("{0}")]
IO(#[from] std::io::Error),
IO(#[from] io::Error),
}
// Auxiliary struct, just for printing loop nodes via show! macro
+7 -7
View File
@@ -65,7 +65,7 @@ pub fn main() -> Result<(), Box<dyn std::error::Error>> {
/// or if the current directory structure does not allow determining the project root.
fn project_root() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let manifest_dir = env::var("CARGO_MANIFEST_DIR")?;
let uucore_path = std::path::Path::new(&manifest_dir);
let uucore_path = Path::new(&manifest_dir);
// Navigate from src/uucore to project root
let project_root = uucore_path
@@ -100,7 +100,7 @@ fn detect_target_utility() -> Option<String> {
// Check for a build configuration file in the target directory
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
let config_path = std::path::Path::new(&target_dir).join("uucore_target_util.txt");
let config_path = Path::new(&target_dir).join("uucore_target_util.txt");
if let Ok(content) = fs::read_to_string(&config_path) {
let util_name = content.trim();
if !util_name.is_empty() && util_name != "multicall" {
@@ -131,7 +131,7 @@ fn detect_target_utility() -> Option<String> {
/// Returns an error if the locales for `util_name` or `uucore` cannot be found
/// or if writing to the `embedded_file` fails.
fn embed_single_utility_locale(
embedded_file: &mut std::fs::File,
embedded_file: &mut File,
project_root: &Path,
util_name: &str,
locales_to_embed: &(String, Option<String>),
@@ -168,7 +168,7 @@ fn embed_single_utility_locale(
/// Returns an error if the `src/uu` directory cannot be read, if any utility
/// locales cannot be embedded, or if flushing the `embedded_file` fails.
fn embed_all_utility_locales(
embedded_file: &mut std::fs::File,
embedded_file: &mut File,
project_root: &Path,
locales_to_embed: &(String, Option<String>),
) -> Result<(), Box<dyn std::error::Error>> {
@@ -219,7 +219,7 @@ fn embed_all_utility_locales(
/// Returns an error if the directory containing the crate cannot be read or
/// if writing to the `embedded_file` fails.
fn embed_static_utility_locales(
embedded_file: &mut std::fs::File,
embedded_file: &mut File,
locales_to_embed: &(String, Option<String>),
) -> Result<(), Box<dyn std::error::Error>> {
use std::env;
@@ -312,7 +312,7 @@ where
/// Returns an error if the file at `locale_path` cannot be read or if
/// writing to `embedded_file` fails.
fn embed_locale_file(
embedded_file: &mut std::fs::File,
embedded_file: &mut File,
locale_path: &Path,
locale_key: &str,
locale: &str,
@@ -348,7 +348,7 @@ fn embed_locale_file(
/// Returns an error if `for_each_locale` fails, which typically happens if
/// reading a locale file or writing to the `embedded_file` fails.
fn embed_component_locales<F>(
embedded_file: &mut std::fs::File,
embedded_file: &mut File,
locales: &(String, Option<String>),
component_name: &str,
path_builder: F,
@@ -211,7 +211,7 @@ pub mod arguments {
clap::Arg::new(OPT_BACKUP)
.long("backup")
.help("make a backup of each existing destination file")
.action(clap::ArgAction::Set)
.action(ArgAction::Set)
.require_equals(true)
.num_args(0..=1)
.value_name("CONTROL")
@@ -231,7 +231,7 @@ pub mod arguments {
.short('S')
.long("suffix")
.help("override the usual backup suffix")
.action(clap::ArgAction::Set)
.action(ArgAction::Set)
.value_name("SUFFIX")
.allow_hyphen_values(true)
}
@@ -505,7 +505,7 @@ mod tests {
// Environment variable for "VERSION_CONTROL"
static ENV_VERSION_CONTROL: &str = "VERSION_CONTROL";
fn make_app() -> clap::Command {
fn make_app() -> Command {
Command::new("command")
.arg(arguments::backup())
.arg(arguments::backup_no_args())
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn create_test_file(data: &[u8], temp_dir: &Path) -> PathBuf {
writer.write_all(data).unwrap();
writer.flush().unwrap();
// Ensure data is fully written to disk before returning
std::mem::drop(writer);
drop(writer);
File::open(&file_path).unwrap().sync_all().unwrap();
file_path
}
+1 -1
View File
@@ -437,7 +437,7 @@ pub fn digest_reader<T: Read>(
// "\n". But when "\r" is the last character read, we need to force
// it to be written.)
let mut digest_writer = DigestWriter::new(digest, binary);
let output_size = std::io::copy(reader, &mut digest_writer)? as usize;
let output_size = io::copy(reader, &mut digest_writer)? as usize;
digest_writer.finalize();
Ok((digest.result(), output_size))
@@ -535,7 +535,7 @@ fn get_file_to_check(
let filename_bytes = os_str_as_bytes(filename).map_err(|e| LineCheckError::UError(e.into()))?;
if filename == "-" {
Ok(Box::new(io::stdin())) // Use stdin if "-" is specified in the checksum file
Ok(Box::new(stdin())) // Use stdin if "-" is specified in the checksum file
} else {
let failed_open = || {
write_file_report(
@@ -692,7 +692,7 @@ fn compute_and_check_digest_from_file(
}));
write_file_report(
std::io::stdout(),
io::stdout(),
filename,
FileChecksumResult::CantOpen,
prefix,
@@ -709,7 +709,7 @@ fn compute_and_check_digest_from_file(
DigestOutput::U16(n) => n.to_be_bytes() == expected_checksum,
};
write_file_report(
std::io::stdout(),
io::stdout(),
filename,
FileChecksumResult::from_bool(checksum_correct),
prefix,
+5 -6
View File
@@ -843,7 +843,7 @@ pub fn make_fifo(path: &Path) -> std::io::Result<()> {
let name = CString::new(path.to_str().unwrap()).unwrap();
let err = unsafe { mkfifo(name.as_ptr(), 0o666) };
if err == -1 {
Err(std::io::Error::from_raw_os_error(err))
Err(Error::from_raw_os_error(err))
} else {
Ok(())
}
@@ -957,8 +957,7 @@ mod tests {
let path = Path::new(test.path);
let normalized = normalize_path(path);
assert_eq!(
test.test
.replace('/', std::path::MAIN_SEPARATOR.to_string().as_str()),
test.test.replace('/', MAIN_SEPARATOR.to_string().as_str()),
normalized.to_str().expect("Path is not valid utf-8!")
);
}
@@ -1153,7 +1152,7 @@ mod tests {
assert!(make_fifo(&path).is_ok());
// Check that it is indeed a FIFO.
assert!(std::fs::metadata(&path).unwrap().file_type().is_fifo());
assert!(fs::metadata(&path).unwrap().file_type().is_fifo());
// Check that we can write to it and read from it.
//
@@ -1161,7 +1160,7 @@ mod tests {
// otherwise `write` would block indefinitely while waiting
// for the `read`.
let path2 = path.clone();
std::thread::spawn(move || assert!(std::fs::write(&path2, b"foo").is_ok()));
assert_eq!(std::fs::read(&path).unwrap(), b"foo");
std::thread::spawn(move || assert!(fs::write(&path2, b"foo").is_ok()));
assert_eq!(fs::read(&path).unwrap(), b"foo");
}
}
+2 -4
View File
@@ -586,8 +586,7 @@ impl FsUsage {
blocks: statvfs.f_blocks,
bfree: statvfs.f_bfree,
bavail: statvfs.f_bavail.try_into().unwrap(),
bavail_top_bit_set: ((std::convert::TryInto::<u64>::try_into(statvfs.f_bavail)
.unwrap())
bavail_top_bit_set: ((TryInto::<u64>::try_into(statvfs.f_bavail).unwrap())
& (1u64.rotate_right(1)))
!= 0,
files: statvfs.f_files,
@@ -599,8 +598,7 @@ impl FsUsage {
blocks: statvfs.f_blocks,
bfree: statvfs.f_bfree,
bavail: statvfs.f_bavail.try_into().unwrap(),
bavail_top_bit_set: ((std::convert::TryInto::<u64>::try_into(statvfs.f_bavail)
.unwrap())
bavail_top_bit_set: ((TryInto::<u64>::try_into(statvfs.f_bavail).unwrap())
& (1u64.rotate_right(1)))
!= 0,
files: statvfs.f_files,
+1 -1
View File
@@ -890,7 +890,7 @@ pub fn chown_base(
.action(clap::ArgAction::Append)
.required(true)
.num_args(1..)
.value_parser(clap::value_parser!(std::ffi::OsString)),
.value_parser(clap::value_parser!(OsString)),
);
let matches = crate::clap_localization::handle_clap_result(command, args)?;
+2 -2
View File
@@ -479,7 +479,7 @@ mod tests {
#[test]
fn test_thread_ids() {
let main_tid = unsafe { crate::libc::gettid() };
let main_tid = unsafe { libc::gettid() };
std::thread::spawn(move || {
let mut pid_entry = ProcessInformation::try_new(
PathBuf::from_str(&format!("/proc/{}", current_pid())).unwrap(),
@@ -489,7 +489,7 @@ mod tests {
assert!(thread_ids.contains(&(main_tid as usize)));
let new_thread_tid = unsafe { crate::libc::gettid() };
let new_thread_tid = unsafe { libc::gettid() };
assert!(thread_ids.contains(&(new_thread_tid as usize)));
})
.join()
@@ -780,7 +780,7 @@ mod tests {
#[test]
fn test_path_with_null_byte() {
let path_with_null = std::ffi::OsString::from_vec(b"test\0file".to_vec());
let path_with_null = OsString::from_vec(b"test\0file".to_vec());
let temp_dir = TempDir::new().unwrap();
let dir_fd = DirFd::open(temp_dir.path()).unwrap();
+2 -2
View File
@@ -274,8 +274,8 @@ pub fn contexts_differ(from_path: &Path, to_path: &Path) -> bool {
// Check if SELinux contexts differ
match (
selinux::SecurityContext::of_path(from_path, false, false),
selinux::SecurityContext::of_path(to_path, false, false),
SecurityContext::of_path(from_path, false, false),
SecurityContext::of_path(to_path, false, false),
) {
(Ok(Some(from_ctx)), Ok(Some(to_ctx))) => {
// Convert contexts to CString and compare
+4 -4
View File
@@ -34,7 +34,7 @@ pub enum DigestOutput {
}
impl DigestOutput {
pub fn write_raw(&self, mut w: impl std::io::Write) -> io::Result<()> {
pub fn write_raw(&self, mut w: impl Write) -> io::Result<()> {
match self {
Self::Vec(buf) => w.write_all(buf),
// For legacy outputs, print them in big endian
@@ -468,13 +468,13 @@ impl<'a> DigestWriter<'a> {
impl Write for DigestWriter<'_> {
#[cfg(not(windows))]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.digest.hash_update(buf);
Ok(buf.len())
}
#[cfg(windows)]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.binary {
self.digest.hash_update(buf);
return Ok(buf.len());
@@ -524,7 +524,7 @@ impl Write for DigestWriter<'_> {
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
+11 -12
View File
@@ -17,7 +17,6 @@ use std::mem::MaybeUninit;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{UResult, USimpleError};
use crate::utmpx;
/// FFI bindings for libsystemd login and D-Bus functions
mod ffi {
@@ -304,18 +303,18 @@ impl SystemdLoginRecord {
}
/// Get login time as time::OffsetDateTime compatible with utmpx
pub fn login_time_offset(&self) -> utmpx::time::OffsetDateTime {
pub fn login_time_offset(&self) -> time::OffsetDateTime {
let duration = self
.login_time
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0);
let local_offset = utmpx::time::OffsetDateTime::now_local()
.map_or_else(|_| utmpx::time::UtcOffset::UTC, |v| v.offset());
utmpx::time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
let local_offset =
time::OffsetDateTime::now_local().map_or_else(|_| time::UtcOffset::UTC, |v| v.offset());
time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
.unwrap_or_else(|_| {
utmpx::time::OffsetDateTime::now_local()
.unwrap_or_else(|_| utmpx::time::OffsetDateTime::now_utc())
time::OffsetDateTime::now_local()
.unwrap_or_else(|_| time::OffsetDateTime::now_utc())
})
.to_offset(local_offset)
}
@@ -566,7 +565,7 @@ impl SystemdUtmpxCompat {
}
/// Login time
pub fn login_time(&self) -> utmpx::time::OffsetDateTime {
pub fn login_time(&self) -> time::OffsetDateTime {
self.record.login_time_offset()
}
@@ -681,7 +680,7 @@ mod tests {
seat_or_tty: "tty1".to_string(),
raw_device: "tty1".to_string(),
host: "host1".to_string(),
login_time: std::time::UNIX_EPOCH,
login_time: UNIX_EPOCH,
pid: 1234,
session_leader_pid: 1234,
record_type: SystemdRecordType::UserProcess,
@@ -692,7 +691,7 @@ mod tests {
seat_or_tty: "pts/0".to_string(),
raw_device: "pts/0".to_string(),
host: "host2".to_string(),
login_time: std::time::UNIX_EPOCH,
login_time: UNIX_EPOCH,
pid: 5678,
session_leader_pid: 5678,
record_type: SystemdRecordType::UserProcess,
@@ -729,7 +728,7 @@ mod tests {
seat_or_tty: "tty1".to_string(),
raw_device: "tty1".to_string(),
host: "host1".to_string(),
login_time: std::time::UNIX_EPOCH,
login_time: UNIX_EPOCH,
pid: 1234,
session_leader_pid: 1234,
record_type: SystemdRecordType::UserProcess,
@@ -753,7 +752,7 @@ mod tests {
seat_or_tty: "seat0".to_string(),
raw_device: "seat0".to_string(),
host: "localhost".to_string(),
login_time: std::time::UNIX_EPOCH + std::time::Duration::from_secs(1000),
login_time: UNIX_EPOCH + std::time::Duration::from_secs(1000),
pid: 9999,
session_leader_pid: 9999,
record_type: SystemdRecordType::UserProcess,
@@ -83,7 +83,7 @@ pub mod arguments {
.default_missing_value("older")
.require_equals(true)
.overrides_with("update")
.action(clap::ArgAction::Set)
.action(ArgAction::Set)
}
/// `-u` argument
+10 -10
View File
@@ -239,7 +239,7 @@ macro_rules! crate_version {
/// as `{0}`.
pub fn format_usage(s: &str) -> String {
let s = s.replace('\n', &format!("\n{}", " ".repeat(7)));
s.replace("{}", crate::execution_phrase())
s.replace("{}", execution_phrase())
}
/// Creates a localized help template for clap commands.
@@ -288,7 +288,7 @@ pub fn localized_help_template_with_colors(
use std::fmt::Write;
// Ensure localization is initialized for this utility
let _ = crate::locale::setup_localization(util_name);
let _ = locale::setup_localization(util_name);
// Get the localized "Usage" label
let usage_label = crate::locale::translate!("common-usage");
@@ -319,13 +319,13 @@ pub fn localized_help_template_with_colors(
/// Used to check if the utility is the second argument.
/// Used to check if we were called as a multicall binary (`coreutils <utility>`)
pub fn get_utility_is_second_arg() -> bool {
crate::macros::UTILITY_IS_SECOND_ARG.load(Ordering::SeqCst)
macros::UTILITY_IS_SECOND_ARG.load(Ordering::SeqCst)
}
/// Change the value of `UTILITY_IS_SECOND_ARG` to true
/// Used to specify that the utility is the second argument.
pub fn set_utility_is_second_arg() {
crate::macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst);
macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst);
}
// args_os() can be expensive to call, it copies all of argv before iterating.
@@ -467,13 +467,13 @@ pub fn os_str_as_bytes_lossy(os_string: &OsStr) -> Cow<'_, [u8]> {
///
/// This always succeeds on unix platforms,
/// and fails on other platforms if the bytes can't be parsed as UTF-8.
pub fn os_str_from_bytes(bytes: &[u8]) -> mods::error::UResult<Cow<'_, OsStr>> {
pub fn os_str_from_bytes(bytes: &[u8]) -> error::UResult<Cow<'_, OsStr>> {
#[cfg(unix)]
return Ok(Cow::Borrowed(OsStr::from_bytes(bytes)));
#[cfg(not(unix))]
Ok(Cow::Owned(OsString::from(str::from_utf8(bytes).map_err(
|_| mods::error::UUsageError::new(1, "Unable to transform bytes into OsStr"),
|_| error::UUsageError::new(1, "Unable to transform bytes into OsStr"),
)?)))
}
@@ -481,13 +481,13 @@ pub fn os_str_from_bytes(bytes: &[u8]) -> mods::error::UResult<Cow<'_, OsStr>> {
///
/// This always succeeds on unix platforms,
/// and fails on other platforms if the bytes can't be parsed as UTF-8.
pub fn os_string_from_vec(vec: Vec<u8>) -> mods::error::UResult<OsString> {
pub fn os_string_from_vec(vec: Vec<u8>) -> error::UResult<OsString> {
#[cfg(unix)]
return Ok(OsString::from_vec(vec));
#[cfg(not(unix))]
Ok(OsString::from(String::from_utf8(vec).map_err(|_| {
mods::error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
})?))
}
@@ -495,14 +495,14 @@ pub fn os_string_from_vec(vec: Vec<u8>) -> mods::error::UResult<OsString> {
///
/// This always succeeds on unix platforms,
/// and fails on other platforms if the bytes can't be parsed as UTF-8.
pub fn os_string_to_vec(s: OsString) -> mods::error::UResult<Vec<u8>> {
pub fn os_string_to_vec(s: OsString) -> error::UResult<Vec<u8>> {
#[cfg(unix)]
let v = s.into_vec();
#[cfg(not(unix))]
let v = s
.into_string()
.map_err(|_| {
mods::error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
})?
.into();
+3 -3
View File
@@ -141,11 +141,11 @@ fn create_bundle(
// Disable Unicode directional isolate characters
bundle.set_use_isolating(false);
let mut try_add_resource_from = |dir_opt: Option<std::path::PathBuf>| {
let mut try_add_resource_from = |dir_opt: Option<PathBuf>| {
if let Some(resource) = dir_opt
.map(|dir| dir.join(format!("{locale}.ftl")))
.and_then(|locale_path| fs::read_to_string(locale_path).ok())
.and_then(|ftl| fluent_bundle::FluentResource::try_new(ftl).ok())
.and_then(|ftl| FluentResource::try_new(ftl).ok())
{
bundle.add_resource_overriding(resource);
}
@@ -1339,7 +1339,7 @@ invalid-syntax = This is { $missing
std::thread::spawn(|| {
// Force English locale for this test
unsafe {
std::env::set_var("LANG", "en-US");
env::set_var("LANG", "en-US");
}
// Test with a utility name that has embedded locales
+2 -2
View File
@@ -32,7 +32,7 @@ fn test_cat_broken_pipe_nonzero_and_message() {
// Close the read end to simulate a broken pipe on stdout
let read_end = File::from_raw_fd(fds[0]);
// Explicitly drop the read-end so writers see EPIPE instead of blocking on a full pipe
std::mem::drop(read_end);
drop(read_end);
let write_end = File::from_raw_fd(fds[1]);
let content = (0..10000).map(|_| "x").collect::<String>();
@@ -592,7 +592,7 @@ fn test_dev_full_show_all() {
#[cfg(target_os = "linux")]
fn test_write_fast_fallthrough_uses_flush() {
const PROC_INIT_CMDLINE: &str = "/proc/1/cmdline";
let cmdline = std::fs::read_to_string(PROC_INIT_CMDLINE).unwrap();
let cmdline = read_to_string(PROC_INIT_CMDLINE).unwrap();
new_ucmd!()
.args(&[PROC_INIT_CMDLINE, "alpha.txt"])
+2 -2
View File
@@ -7502,7 +7502,7 @@ fn test_cp_to_existing_file_permissions() {
let mut src_permissions = std::fs::metadata(&src_path).unwrap().permissions();
src_permissions.set_readonly(true);
std::fs::set_permissions(&src_path, src_permissions).unwrap();
set_permissions(&src_path, src_permissions).unwrap();
let dst_mode = std::fs::metadata(&dst_path).unwrap().permissions().mode();
@@ -7531,7 +7531,7 @@ fn test_cp_xattr_enotsup_handling() {
}
// Check if /dev/shm exists
if !std::path::Path::new("/dev/shm").exists() {
if !Path::new("/dev/shm").exists() {
return; // Skip: /dev/shm not available
}
+5 -9
View File
@@ -25,7 +25,8 @@ use std::path::PathBuf;
not(target_os = "freebsd"),
feature = "printf"
))]
use std::process::{Command, Stdio};
use std::process::Command;
use std::process::Stdio;
#[cfg(not(windows))]
use std::thread::sleep;
#[cfg(not(windows))]
@@ -674,7 +675,6 @@ fn test_skip_beyond_file() {
fn test_skip_beyond_file_seekable_stdin() {
// When stdin is a seekable file, dd should use seek to skip bytes.
// This tests that skipping beyond the file size issues a warning.
use std::process::Stdio;
// Test cases: (bs, skip) pairs that skip beyond a 4-byte file
let test_cases = [
@@ -1478,7 +1478,7 @@ fn test_sparse() {
// On common Linux filesystems, setting the length to one megabyte
// should cause the file to become a sparse file, but it depends
// on the system.
std::fs::File::create(at.plus("infile"))
File::create(at.plus("infile"))
.unwrap()
.set_len(1024 * 1024)
.unwrap();
@@ -1734,7 +1734,7 @@ fn test_iflag_directory_fails_when_file_is_passed_via_std_in() {
let filename = at.plus_as_string("input");
new_ucmd!()
.args(&["iflag=directory", "count=0"])
.set_stdin(std::process::Stdio::from(File::open(filename).unwrap()))
.set_stdin(Stdio::from(File::open(filename).unwrap()))
.fails()
.stderr_only("dd: setting flags for 'standard input': Not a directory\n");
}
@@ -1744,7 +1744,7 @@ fn test_iflag_directory_fails_when_file_is_passed_via_std_in() {
fn test_iflag_directory_passes_when_dir_is_redirected() {
new_ucmd!()
.args(&["iflag=directory", "count=0"])
.set_stdin(std::process::Stdio::from(File::open(".").unwrap()))
.set_stdin(Stdio::from(File::open(".").unwrap()))
.succeeds();
}
@@ -1760,8 +1760,6 @@ fn test_iflag_directory_fails_when_file_is_piped_via_std_in() {
#[test]
fn test_stdin_stdout_not_rewound_even_when_connected_to_seekable_file() {
use std::process::Stdio;
let ts = TestScenario::new(util_name!());
let at = &ts.fixtures;
@@ -1821,8 +1819,6 @@ fn test_wrong_number_err_msg() {
#[test]
#[cfg(unix)]
fn test_no_dropped_writes() {
use std::process::Stdio;
const BLK_SIZE: usize = 0x4000;
const COUNT: usize = 1000;
const NUM_BYTES: usize = BLK_SIZE * COUNT;
+5 -5
View File
@@ -11,7 +11,7 @@ use std::fs;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
#[cfg(not(windows))]
use std::process::Command;
use std::process;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::thread::sleep;
use uucore::process::{getegid, geteuid};
@@ -777,7 +777,7 @@ fn test_install_and_strip() {
.succeeds()
.no_stderr();
let output = Command::new(SYMBOL_DUMP_PROGRAM)
let output = process::Command::new(SYMBOL_DUMP_PROGRAM)
.arg("-t")
.arg(at.plus(STRIP_TARGET_FILE))
.output()
@@ -804,7 +804,7 @@ fn test_install_and_strip_with_program() {
.succeeds()
.no_stderr();
let output = Command::new(SYMBOL_DUMP_PROGRAM)
let output = process::Command::new(SYMBOL_DUMP_PROGRAM)
.arg("-t")
.arg(at.plus(STRIP_TARGET_FILE))
.output()
@@ -1937,7 +1937,7 @@ fn test_install_compare_group_ownership() {
at.write(source, "test content");
let user_group = std::process::Command::new("id")
let user_group = process::Command::new("id")
.arg("-nrg")
.output()
.map_or_else(
@@ -2498,7 +2498,7 @@ fn test_install_non_utf8_paths() {
let source_filename = std::ffi::OsString::from_vec(vec![0xFF, 0xFE]);
let dest_dir = "target_dir";
std::fs::write(at.plus(&source_filename), b"test content").unwrap();
fs::write(at.plus(&source_filename), b"test content").unwrap();
at.mkdir(dest_dir);
ucmd.arg(&source_filename).arg(dest_dir).succeeds();
+2 -2
View File
@@ -550,8 +550,8 @@ fn test_join_non_utf8_paths() {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let file1_name = std::ffi::OsStr::from_bytes(file1_bytes);
let file2_name = std::ffi::OsStr::from_bytes(file2_bytes);
let file1_name = OsStr::from_bytes(file1_bytes);
let file2_name = OsStr::from_bytes(file2_bytes);
let mut file1 = File::create(test_dir.join(file1_name)).unwrap();
file1.write_all(b"a 1\n").unwrap();
+26 -41
View File
@@ -1921,7 +1921,7 @@ fn test_move_should_not_fallback_to_copy() {
#[cfg(target_os = "linux")]
mod inter_partition_copying {
use std::fs::{read_to_string, set_permissions, write};
use std::fs::{self, set_permissions, write};
use std::os::unix::fs::{PermissionsExt, symlink};
use tempfile::TempDir;
use uutests::util::TestScenario;
@@ -1964,13 +1964,13 @@ mod inter_partition_copying {
// make sure that file contents in other_fs_file didn't change.
assert_eq!(
read_to_string(&other_fs_file_path).expect("Unable to read other_fs_file"),
fs::read_to_string(&other_fs_file_path).expect("Unable to read other_fs_file"),
"other fs file contents"
);
// make sure that src file contents got copied into new file created in symlink_path
assert_eq!(
read_to_string(&symlink_path).expect("Unable to read other_fs_file"),
fs::read_to_string(&symlink_path).expect("Unable to read other_fs_file"),
"src contents"
);
}
@@ -2011,7 +2011,7 @@ mod inter_partition_copying {
#[test]
#[cfg(unix)]
pub(crate) fn test_mv_preserves_hardlinks_across_partitions() {
use std::fs::metadata;
use std::fs;
use std::os::unix::fs::MetadataExt;
use tempfile::TempDir;
use uutests::util::TestScenario;
@@ -2022,8 +2022,8 @@ mod inter_partition_copying {
at.write("file1", "test content");
at.hard_link("file1", "file2");
let metadata1 = metadata(at.plus("file1")).expect("Failed to get metadata for file1");
let metadata2 = metadata(at.plus("file2")).expect("Failed to get metadata for file2");
let metadata1 = fs::metadata(at.plus("file1")).expect("Failed to get metadata for file1");
let metadata2 = fs::metadata(at.plus("file2")).expect("Failed to get metadata for file2");
assert_eq!(
metadata1.ino(),
metadata2.ino(),
@@ -2055,9 +2055,9 @@ mod inter_partition_copying {
assert!(moved_file2.exists(), "file2 should exist in destination");
let moved_metadata1 =
metadata(&moved_file1).expect("Failed to get metadata for moved file1");
fs::metadata(&moved_file1).expect("Failed to get metadata for moved file1");
let moved_metadata2 =
metadata(&moved_file2).expect("Failed to get metadata for moved file2");
fs::metadata(&moved_file2).expect("Failed to get metadata for moved file2");
assert_eq!(
moved_metadata1.ino(),
@@ -2072,11 +2072,11 @@ mod inter_partition_copying {
// Verify content is preserved
assert_eq!(
std::fs::read_to_string(&moved_file1).expect("Failed to read moved file1"),
fs::read_to_string(&moved_file1).expect("Failed to read moved file1"),
"test content"
);
assert_eq!(
std::fs::read_to_string(&moved_file2).expect("Failed to read moved file2"),
fs::read_to_string(&moved_file2).expect("Failed to read moved file2"),
"test content"
);
}
@@ -2186,24 +2186,12 @@ mod inter_partition_copying {
"Single file should still have nlink=1"
);
assert_eq!(fs::read_to_string(&moved_g1f1).unwrap(), "content group 1");
assert_eq!(fs::read_to_string(&moved_g1f2).unwrap(), "content group 1");
assert_eq!(fs::read_to_string(&moved_g2f1).unwrap(), "content group 2");
assert_eq!(fs::read_to_string(&moved_g2f2).unwrap(), "content group 2");
assert_eq!(
std::fs::read_to_string(&moved_g1f1).unwrap(),
"content group 1"
);
assert_eq!(
std::fs::read_to_string(&moved_g1f2).unwrap(),
"content group 1"
);
assert_eq!(
std::fs::read_to_string(&moved_g2f1).unwrap(),
"content group 2"
);
assert_eq!(
std::fs::read_to_string(&moved_g2f2).unwrap(),
"content group 2"
);
assert_eq!(
std::fs::read_to_string(&moved_single).unwrap(),
fs::read_to_string(&moved_single).unwrap(),
"single file content"
);
}
@@ -2296,14 +2284,14 @@ mod inter_partition_copying {
"a/1 should have nlink=2 after move"
);
assert_eq!(std::fs::read_to_string(&moved_f).unwrap(), "file content");
assert_eq!(std::fs::read_to_string(&moved_g).unwrap(), "file content");
assert_eq!(fs::read_to_string(&moved_f).unwrap(), "file content");
assert_eq!(fs::read_to_string(&moved_g).unwrap(), "file content");
assert_eq!(
std::fs::read_to_string(&moved_dir_a_file).unwrap(),
fs::read_to_string(&moved_dir_a_file).unwrap(),
"directory file content"
);
assert_eq!(
std::fs::read_to_string(&moved_dir_second_file).unwrap(),
fs::read_to_string(&moved_dir_second_file).unwrap(),
"directory file content"
);
}
@@ -2436,26 +2424,23 @@ mod inter_partition_copying {
"nested file group should still have nlink=2"
);
assert_eq!(std::fs::read_to_string(&moved_file_a).unwrap(), "content A");
assert_eq!(fs::read_to_string(&moved_file_a).unwrap(), "content A");
assert_eq!(
std::fs::read_to_string(&moved_file_a_link1).unwrap(),
fs::read_to_string(&moved_file_a_link1).unwrap(),
"content A"
);
assert_eq!(
std::fs::read_to_string(&moved_file_a_link2).unwrap(),
fs::read_to_string(&moved_file_a_link2).unwrap(),
"content A"
);
assert_eq!(std::fs::read_to_string(&moved_file_b).unwrap(), "content B");
assert_eq!(fs::read_to_string(&moved_file_b).unwrap(), "content B");
assert_eq!(
std::fs::read_to_string(&moved_file_b_hardlink).unwrap(),
fs::read_to_string(&moved_file_b_hardlink).unwrap(),
"content B"
);
assert_eq!(fs::read_to_string(&moved_nested).unwrap(), "nested content");
assert_eq!(
std::fs::read_to_string(&moved_nested).unwrap(),
"nested content"
);
assert_eq!(
std::fs::read_to_string(&moved_nested_link).unwrap(),
fs::read_to_string(&moved_nested_link).unwrap(),
"nested content"
);
}
+2 -2
View File
@@ -329,7 +329,7 @@ fn test_echo_multi() {
.stdout_str()
.split('\n')
.filter(|x| !x.is_empty())
.map(std::convert::Into::into)
.map(Into::into)
.collect();
result_seq.sort_unstable();
assert_eq!(result_seq, ["a", "b", "c"], "Output is not a permutation");
@@ -344,7 +344,7 @@ fn test_echo_postfix() {
.stdout_str()
.split('\n')
.filter(|x| !x.is_empty())
.map(std::convert::Into::into)
.map(Into::into)
.collect();
result_seq.sort_unstable();
assert_eq!(result_seq, ["a", "b", "c"], "Output is not a permutation");
+5 -5
View File
@@ -14,7 +14,7 @@ use std::env;
use std::os::unix::ffi::OsStringExt;
use std::path::Path;
use std::{
fs::{File, read_dir},
fs::{self, File},
io::{BufWriter, Read, Write},
};
use uutests::util::{AtPath, TestScenario};
@@ -48,7 +48,7 @@ impl Glob {
/// Get all files in `self.directory` that match `self.regex`
fn collect(&self) -> Vec<String> {
read_dir(Path::new(&self.directory.subdir))
fs::read_dir(Path::new(&self.directory.subdir))
.unwrap()
.filter_map(|entry| {
let path = entry.unwrap().path();
@@ -2011,7 +2011,7 @@ fn test_split_non_utf8_paths() {
let (at, mut ucmd) = at_and_ucmd!();
let filename = std::ffi::OsString::from_vec(vec![0xFF, 0xFE]);
std::fs::write(at.plus(&filename), b"line1\nline2\nline3\nline4\nline5\n").unwrap();
fs::write(at.plus(&filename), b"line1\nline2\nline3\nline4\nline5\n").unwrap();
ucmd.arg(&filename).succeeds();
@@ -2032,7 +2032,7 @@ fn test_split_non_utf8_prefix() {
// Check that split files were created (functionality works)
// The actual filename may be converted due to lossy conversion, but the command should succeed
let entries: Vec<_> = std::fs::read_dir(at.as_string()).unwrap().collect();
let entries: Vec<_> = fs::read_dir(at.as_string()).unwrap().collect();
let split_files = entries
.iter()
.filter_map(|e| e.as_ref().ok())
@@ -2063,7 +2063,7 @@ fn test_split_non_utf8_additional_suffix() {
// Check that split files were created (functionality works)
// The actual filename may be converted due to lossy conversion, but the command should succeed
let entries: Vec<_> = std::fs::read_dir(at.as_string()).unwrap().collect();
let entries: Vec<_> = fs::read_dir(at.as_string()).unwrap().collect();
let split_files = entries
.iter()
.filter_map(|e| e.as_ref().ok())
+2 -2
View File
@@ -1237,7 +1237,7 @@ fn test_saved_state_invalid_formats() {
let (path, _controller, _replica) = pty_path();
let (_at, ts) = at_and_ts!();
let num_cc = nix::libc::NCCS;
let num_cc = libc::NCCS;
// Build test strings with platform-specific counts
let cc_zeros = vec!["0"; num_cc].join(":");
@@ -1540,7 +1540,7 @@ fn test_saved_state_with_control_chars() {
let (_at, ts) = at_and_ts!();
// Build a valid saved state with platform-specific number of control characters
let num_cc = nix::libc::NCCS;
let num_cc = libc::NCCS;
let cc_values: Vec<String> = (1..=num_cc).map(|_| format!("{:x}", 0)).collect();
let saved_state = format!("500:5:4bf:8a3b:{}", cc_values.join(":"));
+1 -1
View File
@@ -5049,7 +5049,7 @@ fn test_child_when_run_with_stderr_to_stdout() {
fn test_failed_write_is_reported() {
new_ucmd!()
.pipe_in("hello")
.set_stdout(std::fs::File::create("/dev/full").unwrap())
.set_stdout(File::create("/dev/full").unwrap())
.fails()
.stderr_is("tail: No space left on device\n");
}
+2 -2
View File
@@ -20,7 +20,7 @@ pub const TESTS_BINARY: &str = env!("CARGO_BIN_EXE_coreutils");
fn init() {
// No need for unsafe here
unsafe {
std::env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY);
env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY);
}
// Print for debugging
eprintln!("Setting UUTESTS_BINARY_PATH={TESTS_BINARY}");
@@ -223,7 +223,7 @@ fn util_version() {
assert_eq!(output.status.code(), Some(0));
assert_eq!(output.stderr, b"");
let output_str = String::from_utf8(output.stdout).unwrap();
let ver = std::env::var("CARGO_PKG_VERSION").unwrap();
let ver = env::var("CARGO_PKG_VERSION").unwrap();
assert_eq!(format!("coreutils {ver} (multi-call binary)\n"), output_str);
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ pub const TESTS_BINARY: &str = env!("CARGO_BIN_EXE_coreutils");
fn init() {
unsafe {
// Necessary for uutests to be able to find the binary
std::env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY);
env::set_var("UUTESTS_BINARY_PATH", TESTS_BINARY);
}
}