1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

Merge branch 'main' into cp-backup-force

This commit is contained in:
Sylvestre Ledru 2022-11-06 07:24:48 +01:00 committed by GitHub
commit 446df9da5a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
71 changed files with 856 additions and 258 deletions

View file

@ -897,7 +897,7 @@ jobs:
- uses: Swatinem/rust-cache@v1 - uses: Swatinem/rust-cache@v1
- name: Prepare, build and test - name: Prepare, build and test
## spell-checker:ignore (ToDO) sshfs usesh vmactions ## spell-checker:ignore (ToDO) sshfs usesh vmactions
uses: vmactions/freebsd-vm@v0.2.9 uses: vmactions/freebsd-vm@v0.3.0
with: with:
usesh: true usesh: true
# sync: sshfs # sync: sshfs

View file

@ -6,8 +6,13 @@ on:
types: types:
- completed - completed
permissions: {}
jobs: jobs:
post-comment: post-comment:
permissions:
actions: read # to list workflow runs artifacts
pull-requests: write # to comment on pr
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: > if: >
github.event.workflow_run.event == 'pull_request' github.event.workflow_run.event == 'pull_request'

46
Cargo.lock generated
View file

@ -100,9 +100,9 @@ dependencies = [
[[package]] [[package]]
name = "binary-heap-plus" name = "binary-heap-plus"
version = "0.4.1" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f068638f8ff9e118a9361e66a411eff410e7fb3ecaa23bf9272324f8fc606d7" checksum = "e4551d8382e911ecc0d0f0ffb602777988669be09447d536ff4388d1def11296"
dependencies = [ dependencies = [
"compare", "compare",
] ]
@ -190,10 +190,11 @@ checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d"
[[package]] [[package]]
name = "byte-unit" name = "byte-unit"
version = "4.0.14" version = "4.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95ebf10dda65f19ff0f42ea15572a359ed60d7fc74fdc984d90310937be0014b" checksum = "581ad4b3d627b0c09a0ccb2912148f839acaca0b93cf54cbe42b6c674e86079c"
dependencies = [ dependencies = [
"serde",
"utf8-width", "utf8-width",
] ]
@ -285,9 +286,9 @@ dependencies = [
[[package]] [[package]]
name = "clap_complete" name = "clap_complete"
version = "4.0.2" version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11cba7abac9b56dfe2f035098cdb3a43946f276e6db83b72c4e692343f9aab9a" checksum = "dfe581a2035db4174cdbdc91265e1aba50f381577f0510d0ad36c7bc59cc84a3"
dependencies = [ dependencies = [
"clap 4.0.18", "clap 4.0.18",
] ]
@ -1145,9 +1146,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.135" version = "0.2.137"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c" checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89"
[[package]] [[package]]
name = "libloading" name = "libloading"
@ -1342,9 +1343,9 @@ dependencies = [
[[package]] [[package]]
name = "num_cpus" name = "num_cpus"
version = "1.13.1" version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5"
dependencies = [ dependencies = [
"hermit-abi", "hermit-abi",
"libc", "libc",
@ -2076,21 +2077,32 @@ dependencies = [
[[package]] [[package]]
name = "time" name = "time"
version = "0.3.15" version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d634a985c4d4238ec39cacaed2e7ae552fbd3c476b552c1deac3021b7d7eaf0c" checksum = "0fab5c8b9980850e06d92ddbe3ab839c062c801f3927c0fb8abd6fc8e918fbca"
dependencies = [ dependencies = [
"itoa", "itoa",
"libc", "libc",
"num_threads", "num_threads",
"serde",
"time-core",
"time-macros", "time-macros",
] ]
[[package]] [[package]]
name = "time-macros" name = "time-core"
version = "0.2.4" version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792" checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
[[package]]
name = "time-macros"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65bb801831d812c562ae7d2bfb531f26e66e4e1f6b17307ba4149c5064710e5b"
dependencies = [
"time-core",
]
[[package]] [[package]]
name = "typenum" name = "typenum"
@ -2347,7 +2359,6 @@ name = "uu_dir"
version = "0.0.16" version = "0.0.16"
dependencies = [ dependencies = [
"clap 4.0.18", "clap 4.0.18",
"selinux",
"uu_ls", "uu_ls",
"uucore", "uucore",
] ]
@ -2357,7 +2368,6 @@ name = "uu_dircolors"
version = "0.0.16" version = "0.0.16"
dependencies = [ dependencies = [
"clap 4.0.18", "clap 4.0.18",
"glob",
"uucore", "uucore",
] ]
@ -2807,6 +2817,7 @@ name = "uu_rm"
version = "0.0.16" version = "0.0.16"
dependencies = [ dependencies = [
"clap 4.0.18", "clap 4.0.18",
"libc",
"remove_dir_all 0.7.0", "remove_dir_all 0.7.0",
"uucore", "uucore",
"walkdir", "walkdir",
@ -3124,7 +3135,6 @@ name = "uu_vdir"
version = "0.0.16" version = "0.0.16"
dependencies = [ dependencies = [
"clap 4.0.18", "clap 4.0.18",
"selinux",
"uu_ls", "uu_ls",
"uucore", "uucore",
] ]

View file

@ -100,7 +100,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
CommandLineMode::ContextBased { context } => { CommandLineMode::ContextBased { context } => {
let c_context = match os_str_to_c_string(&context) { let c_context = match os_str_to_c_string(context) {
Ok(context) => context, Ok(context) => context,
Err(_r) => { Err(_r) => {
@ -198,7 +198,7 @@ pub fn uu_app() -> Command {
.long(options::REFERENCE) .long(options::REFERENCE)
.value_name("RFILE") .value_name("RFILE")
.value_hint(clap::ValueHint::FilePath) .value_hint(clap::ValueHint::FilePath)
.conflicts_with_all(&[options::USER, options::ROLE, options::TYPE, options::RANGE]) .conflicts_with_all([options::USER, options::ROLE, options::TYPE, options::RANGE])
.help( .help(
"Use security context of RFILE, rather than specifying \ "Use security context of RFILE, rather than specifying \
a CONTEXT value.", a CONTEXT value.",
@ -249,7 +249,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sym_links::FOLLOW_ARG_DIR_SYM_LINK) Arg::new(options::sym_links::FOLLOW_ARG_DIR_SYM_LINK)
.short('H') .short('H')
.requires(options::RECURSIVE) .requires(options::RECURSIVE)
.overrides_with_all(&[ .overrides_with_all([
options::sym_links::FOLLOW_DIR_SYM_LINKS, options::sym_links::FOLLOW_DIR_SYM_LINKS,
options::sym_links::NO_FOLLOW_SYM_LINKS, options::sym_links::NO_FOLLOW_SYM_LINKS,
]) ])
@ -263,7 +263,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sym_links::FOLLOW_DIR_SYM_LINKS) Arg::new(options::sym_links::FOLLOW_DIR_SYM_LINKS)
.short('L') .short('L')
.requires(options::RECURSIVE) .requires(options::RECURSIVE)
.overrides_with_all(&[ .overrides_with_all([
options::sym_links::FOLLOW_ARG_DIR_SYM_LINK, options::sym_links::FOLLOW_ARG_DIR_SYM_LINK,
options::sym_links::NO_FOLLOW_SYM_LINKS, options::sym_links::NO_FOLLOW_SYM_LINKS,
]) ])
@ -277,7 +277,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sym_links::NO_FOLLOW_SYM_LINKS) Arg::new(options::sym_links::NO_FOLLOW_SYM_LINKS)
.short('P') .short('P')
.requires(options::RECURSIVE) .requires(options::RECURSIVE)
.overrides_with_all(&[ .overrides_with_all([
options::sym_links::FOLLOW_ARG_DIR_SYM_LINK, options::sym_links::FOLLOW_ARG_DIR_SYM_LINK,
options::sym_links::FOLLOW_DIR_SYM_LINKS, options::sym_links::FOLLOW_DIR_SYM_LINKS,
]) ])

View file

@ -146,7 +146,7 @@ pub fn uu_app() -> Command {
Arg::new(options::traverse::NO_TRAVERSE) Arg::new(options::traverse::NO_TRAVERSE)
.short(options::traverse::NO_TRAVERSE.chars().next().unwrap()) .short(options::traverse::NO_TRAVERSE.chars().next().unwrap())
.help("do not traverse any symbolic links (default)") .help("do not traverse any symbolic links (default)")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::EVERY]) .overrides_with_all([options::traverse::TRAVERSE, options::traverse::EVERY])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(

View file

@ -16,7 +16,7 @@ path = "src/chmod.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs", "mode"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs", "mode"] }
[[bin]] [[bin]]

View file

@ -156,21 +156,21 @@ pub fn uu_app() -> Command {
Arg::new(options::traverse::TRAVERSE) Arg::new(options::traverse::TRAVERSE)
.short(options::traverse::TRAVERSE.chars().next().unwrap()) .short(options::traverse::TRAVERSE.chars().next().unwrap())
.help("if a command line argument is a symbolic link to a directory, traverse it") .help("if a command line argument is a symbolic link to a directory, traverse it")
.overrides_with_all(&[options::traverse::EVERY, options::traverse::NO_TRAVERSE]) .overrides_with_all([options::traverse::EVERY, options::traverse::NO_TRAVERSE])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
Arg::new(options::traverse::EVERY) Arg::new(options::traverse::EVERY)
.short(options::traverse::EVERY.chars().next().unwrap()) .short(options::traverse::EVERY.chars().next().unwrap())
.help("traverse every symbolic link to a directory encountered") .help("traverse every symbolic link to a directory encountered")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::NO_TRAVERSE]) .overrides_with_all([options::traverse::TRAVERSE, options::traverse::NO_TRAVERSE])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
Arg::new(options::traverse::NO_TRAVERSE) Arg::new(options::traverse::NO_TRAVERSE)
.short(options::traverse::NO_TRAVERSE.chars().next().unwrap()) .short(options::traverse::NO_TRAVERSE.chars().next().unwrap())
.help("do not traverse any symbolic links (default)") .help("do not traverse any symbolic links (default)")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::EVERY]) .overrides_with_all([options::traverse::TRAVERSE, options::traverse::EVERY])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
@ -246,6 +246,19 @@ fn parse_spec(spec: &str, sep: char) -> UResult<(Option<u32>, Option<u32>)> {
} else { } else {
None None
}; };
if user.chars().next().map(char::is_numeric).unwrap_or(false)
&& group.is_empty()
&& spec != user
{
// if the arg starts with an id numeric value, the group isn't set but the separator is provided,
// we should fail with an error
return Err(USimpleError::new(
1,
format!("invalid spec: {}", spec.quote()),
));
}
Ok((uid, gid)) Ok((uid, gid))
} }

View file

@ -21,7 +21,7 @@ path = "src/cp.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
filetime = "0.2" filetime = "0.2"
libc = "0.2.135" libc = "0.2.137"
quick-error = "2.0.1" quick-error = "2.0.1"
selinux = { version="0.3", optional=true } selinux = { version="0.3", optional=true }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs", "perms", "mode"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs", "perms", "mode"] }

View file

@ -66,7 +66,7 @@ fn get_local_to_root_parent(
adjust_canonicalization(path), adjust_canonicalization(path),
adjust_canonicalization(parent), adjust_canonicalization(parent),
); );
let path = path.strip_prefix(&parent)?; let path = path.strip_prefix(parent)?;
Ok(path.to_path_buf()) Ok(path.to_path_buf())
} }
None => Ok(path.to_path_buf()), None => Ok(path.to_path_buf()),

View file

@ -427,7 +427,7 @@ pub fn uu_app() -> Command {
)) ))
.num_args(0..) .num_args(0..)
.value_name("ATTR_LIST") .value_name("ATTR_LIST")
.overrides_with_all(&[ .overrides_with_all([
options::ARCHIVE, options::ARCHIVE,
options::PRESERVE_DEFAULT_ATTRIBUTES, options::PRESERVE_DEFAULT_ATTRIBUTES,
options::NO_PRESERVE, options::NO_PRESERVE,
@ -443,7 +443,7 @@ pub fn uu_app() -> Command {
Arg::new(options::PRESERVE_DEFAULT_ATTRIBUTES) Arg::new(options::PRESERVE_DEFAULT_ATTRIBUTES)
.short('p') .short('p')
.long(options::PRESERVE_DEFAULT_ATTRIBUTES) .long(options::PRESERVE_DEFAULT_ATTRIBUTES)
.overrides_with_all(&[options::PRESERVE, options::NO_PRESERVE, options::ARCHIVE]) .overrides_with_all([options::PRESERVE, options::NO_PRESERVE, options::ARCHIVE])
.help("same as --preserve=mode,ownership(unix only),timestamps") .help("same as --preserve=mode,ownership(unix only),timestamps")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -451,7 +451,7 @@ pub fn uu_app() -> Command {
Arg::new(options::NO_PRESERVE) Arg::new(options::NO_PRESERVE)
.long(options::NO_PRESERVE) .long(options::NO_PRESERVE)
.value_name("ATTR_LIST") .value_name("ATTR_LIST")
.overrides_with_all(&[ .overrides_with_all([
options::PRESERVE_DEFAULT_ATTRIBUTES, options::PRESERVE_DEFAULT_ATTRIBUTES,
options::PRESERVE, options::PRESERVE,
options::ARCHIVE, options::ARCHIVE,
@ -492,7 +492,7 @@ pub fn uu_app() -> Command {
Arg::new(options::ARCHIVE) Arg::new(options::ARCHIVE)
.short('a') .short('a')
.long(options::ARCHIVE) .long(options::ARCHIVE)
.overrides_with_all(&[ .overrides_with_all([
options::PRESERVE_DEFAULT_ATTRIBUTES, options::PRESERVE_DEFAULT_ATTRIBUTES,
options::PRESERVE, options::PRESERVE,
options::NO_PRESERVE, options::NO_PRESERVE,
@ -677,7 +677,6 @@ fn add_all_attributes() -> Vec<Attribute> {
impl Options { impl Options {
fn from_matches(matches: &ArgMatches) -> CopyResult<Self> { fn from_matches(matches: &ArgMatches) -> CopyResult<Self> {
let not_implemented_opts = vec![ let not_implemented_opts = vec![
options::COPY_CONTENTS,
#[cfg(not(any(windows, unix)))] #[cfg(not(any(windows, unix)))]
options::ONE_FILE_SYSTEM, options::ONE_FILE_SYSTEM,
options::CONTEXT, options::CONTEXT,
@ -1289,8 +1288,10 @@ fn copy_file(
symlinked_files: &mut HashSet<FileInformation>, symlinked_files: &mut HashSet<FileInformation>,
source_in_command_line: bool, source_in_command_line: bool,
) -> CopyResult<()> { ) -> CopyResult<()> {
if file_or_link_exists(dest) { if options.update && options.overwrite == OverwriteMode::Interactive(ClobberMode::Standard) {
handle_existing_dest(source, dest, options, source_in_command_line)?; // `cp -i --update old new` when `new` exists doesn't copy anything
// and exit with 0
return Ok(());
} }
// Fail if dest is a dangling symlink or a symlink this program created previously // Fail if dest is a dangling symlink or a symlink this program created previously
@ -1306,7 +1307,13 @@ fn copy_file(
))); )));
} }
let copy_contents = options.dereference(source_in_command_line) || !source.is_symlink(); let copy_contents = options.dereference(source_in_command_line) || !source.is_symlink();
if copy_contents && !dest.exists() { if copy_contents
&& !dest.exists()
&& !matches!(
options.overwrite,
OverwriteMode::Clobber(ClobberMode::RemoveDestination)
)
{
return Err(Error::Error(format!( return Err(Error::Error(format!(
"not writing through dangling symlink '{}'", "not writing through dangling symlink '{}'",
dest.display() dest.display()
@ -1314,6 +1321,10 @@ fn copy_file(
} }
} }
if file_or_link_exists(dest) {
handle_existing_dest(source, dest, options, source_in_command_line)?;
}
if options.verbose { if options.verbose {
println!("{}", context_for(source, dest)); println!("{}", context_for(source, dest));
} }
@ -1470,7 +1481,7 @@ fn copy_helper(
* https://github.com/rust-lang/rust/issues/79390 * https://github.com/rust-lang/rust/issues/79390
*/ */
File::create(dest).context(dest.display().to_string())?; File::create(dest).context(dest.display().to_string())?;
} else if source_is_fifo && options.recursive { } else if source_is_fifo && options.recursive && !options.copy_contents {
#[cfg(unix)] #[cfg(unix)]
copy_fifo(dest, options.overwrite)?; copy_fifo(dest, options.overwrite)?;
} else if source_is_symlink { } else if source_is_symlink {
@ -1482,6 +1493,8 @@ fn copy_helper(
options.reflink_mode, options.reflink_mode,
options.sparse_mode, options.sparse_mode,
context, context,
#[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
source_is_fifo,
)?; )?;
} }

View file

@ -21,29 +21,39 @@ macro_rules! FICLONE {
}; };
} }
/// The fallback behavior for [`clone`] on failed system call.
#[derive(Clone, Copy)]
enum CloneFallback {
/// Raise an error.
Error,
/// Use [`std::io::copy`].
IOCopy,
/// Use [`std::fs::copy`].
FSCopy,
}
/// Use the Linux `ioctl_ficlone` API to do a copy-on-write clone. /// Use the Linux `ioctl_ficlone` API to do a copy-on-write clone.
/// ///
/// If `fallback` is true and there is a failure performing the clone, /// `fallback` controls what to do if the system call fails.
/// then this function performs a standard [`std::fs::copy`]. Otherwise,
/// this function returns an error.
#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg(any(target_os = "linux", target_os = "android"))]
fn clone<P>(source: P, dest: P, fallback: bool) -> std::io::Result<()> fn clone<P>(source: P, dest: P, fallback: CloneFallback) -> std::io::Result<()>
where where
P: AsRef<Path>, P: AsRef<Path>,
{ {
let src_file = File::open(&source)?; let mut src_file = File::open(&source)?;
let dst_file = File::create(&dest)?; let mut dst_file = File::create(&dest)?;
let src_fd = src_file.as_raw_fd(); let src_fd = src_file.as_raw_fd();
let dst_fd = dst_file.as_raw_fd(); let dst_fd = dst_file.as_raw_fd();
let result = unsafe { libc::ioctl(dst_fd, FICLONE!(), src_fd) }; let result = unsafe { libc::ioctl(dst_fd, FICLONE!(), src_fd) };
if result != 0 { if result == 0 {
if fallback { return Ok(());
std::fs::copy(source, dest).map(|_| ()) }
} else { match fallback {
Err(std::io::Error::last_os_error()) CloneFallback::Error => Err(std::io::Error::last_os_error()),
} CloneFallback::IOCopy => std::io::copy(&mut src_file, &mut dst_file).map(|_| ()),
} else { CloneFallback::FSCopy => std::fs::copy(source, dest).map(|_| ()),
Ok(())
} }
} }
@ -89,18 +99,31 @@ where
} }
/// Copies `source` to `dest` using copy-on-write if possible. /// Copies `source` to `dest` using copy-on-write if possible.
///
/// The `source_is_fifo` flag must be set to `true` if and only if
/// `source` is a FIFO (also known as a named pipe). In this case,
/// copy-on-write is not possible, so we copy the contents using
/// [`std::io::copy`].
pub(crate) fn copy_on_write( pub(crate) fn copy_on_write(
source: &Path, source: &Path,
dest: &Path, dest: &Path,
reflink_mode: ReflinkMode, reflink_mode: ReflinkMode,
sparse_mode: SparseMode, sparse_mode: SparseMode,
context: &str, context: &str,
source_is_fifo: bool,
) -> CopyResult<()> { ) -> CopyResult<()> {
let result = match (reflink_mode, sparse_mode) { let result = match (reflink_mode, sparse_mode) {
(ReflinkMode::Never, _) => std::fs::copy(source, dest).map(|_| ()), (ReflinkMode::Never, _) => std::fs::copy(source, dest).map(|_| ()),
(ReflinkMode::Auto, SparseMode::Always) => sparse_copy(source, dest), (ReflinkMode::Auto, SparseMode::Always) => sparse_copy(source, dest),
(ReflinkMode::Auto, _) => clone(source, dest, true),
(ReflinkMode::Always, SparseMode::Auto) => clone(source, dest, false), (ReflinkMode::Auto, _) => {
if source_is_fifo {
clone(source, dest, CloneFallback::IOCopy)
} else {
clone(source, dest, CloneFallback::FSCopy)
}
}
(ReflinkMode::Always, SparseMode::Auto) => clone(source, dest, CloneFallback::Error),
(ReflinkMode::Always, _) => { (ReflinkMode::Always, _) => {
return Err("`--reflink=always` can be used only with --sparse=auto".into()) return Err("`--reflink=always` can be used only with --sparse=auto".into())
} }

View file

@ -4,7 +4,8 @@
// * file that was distributed with this source code. // * file that was distributed with this source code.
// spell-checker:ignore reflink // spell-checker:ignore reflink
use std::ffi::CString; use std::ffi::CString;
use std::fs; use std::fs::{self, File};
use std::io;
use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStrExt;
use std::path::Path; use std::path::Path;
@ -13,12 +14,16 @@ use quick_error::ResultExt;
use crate::{CopyResult, ReflinkMode, SparseMode}; use crate::{CopyResult, ReflinkMode, SparseMode};
/// Copies `source` to `dest` using copy-on-write if possible. /// Copies `source` to `dest` using copy-on-write if possible.
///
/// The `source_is_fifo` flag must be set to `true` if and only if
/// `source` is a FIFO (also known as a named pipe).
pub(crate) fn copy_on_write( pub(crate) fn copy_on_write(
source: &Path, source: &Path,
dest: &Path, dest: &Path,
reflink_mode: ReflinkMode, reflink_mode: ReflinkMode,
sparse_mode: SparseMode, sparse_mode: SparseMode,
context: &str, context: &str,
source_is_fifo: bool,
) -> CopyResult<()> { ) -> CopyResult<()> {
if sparse_mode != SparseMode::Auto { if sparse_mode != SparseMode::Auto {
return Err("--sparse is only supported on linux".to_string().into()); return Err("--sparse is only supported on linux".to_string().into());
@ -65,8 +70,15 @@ pub(crate) fn copy_on_write(
format!("failed to clone {:?} from {:?}: {}", source, dest, error).into(), format!("failed to clone {:?} from {:?}: {}", source, dest, error).into(),
) )
} }
ReflinkMode::Auto => fs::copy(source, dest).context(context)?, _ => {
ReflinkMode::Never => fs::copy(source, dest).context(context)?, if source_is_fifo {
let mut src_file = File::open(source)?;
let mut dst_file = File::create(dest)?;
io::copy(&mut src_file, &mut dst_file).context(context)?
} else {
fs::copy(source, dest).context(context)?
}
}
}; };
} }

View file

@ -86,7 +86,7 @@ fn unimplemented_flags_should_error() {
fn test_status_level_absent() { fn test_status_level_absent() {
let args = &["if=foo.file", "of=bar.file"]; let args = &["if=foo.file", "of=bar.file"];
assert_eq!(Parser::new().parse(args).unwrap().status, None) assert_eq!(Parser::new().parse(args).unwrap().status, None);
} }
#[test] #[test]
@ -96,7 +96,7 @@ fn test_status_level_none() {
assert_eq!( assert_eq!(
Parser::new().parse(args).unwrap().status, Parser::new().parse(args).unwrap().status,
Some(StatusLevel::None) Some(StatusLevel::None)
) );
} }
#[test] #[test]

View file

@ -509,7 +509,7 @@ pub fn uu_app() -> Command {
.short('B') .short('B')
.long("block-size") .long("block-size")
.value_name("SIZE") .value_name("SIZE")
.overrides_with_all(&[OPT_KILO, OPT_BLOCKSIZE]) .overrides_with_all([OPT_KILO, OPT_BLOCKSIZE])
.help( .help(
"scale sizes by SIZE before printing them; e.g.\ "scale sizes by SIZE before printing them; e.g.\
'-BM' prints sizes in units of 1,048,576 bytes", '-BM' prints sizes in units of 1,048,576 bytes",
@ -526,7 +526,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_HUMAN_READABLE_BINARY) Arg::new(OPT_HUMAN_READABLE_BINARY)
.short('h') .short('h')
.long("human-readable") .long("human-readable")
.overrides_with_all(&[OPT_HUMAN_READABLE_DECIMAL, OPT_HUMAN_READABLE_BINARY]) .overrides_with_all([OPT_HUMAN_READABLE_DECIMAL, OPT_HUMAN_READABLE_BINARY])
.help("print sizes in human readable format (e.g., 1K 234M 2G)") .help("print sizes in human readable format (e.g., 1K 234M 2G)")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -534,7 +534,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_HUMAN_READABLE_DECIMAL) Arg::new(OPT_HUMAN_READABLE_DECIMAL)
.short('H') .short('H')
.long("si") .long("si")
.overrides_with_all(&[OPT_HUMAN_READABLE_BINARY, OPT_HUMAN_READABLE_DECIMAL]) .overrides_with_all([OPT_HUMAN_READABLE_BINARY, OPT_HUMAN_READABLE_DECIMAL])
.help("likewise, but use powers of 1000 not 1024") .help("likewise, but use powers of 1000 not 1024")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -550,7 +550,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_KILO) Arg::new(OPT_KILO)
.short('k') .short('k')
.help("like --block-size=1K") .help("like --block-size=1K")
.overrides_with_all(&[OPT_BLOCKSIZE, OPT_KILO]) .overrides_with_all([OPT_BLOCKSIZE, OPT_KILO])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
@ -564,7 +564,7 @@ pub fn uu_app() -> Command {
.arg( .arg(
Arg::new(OPT_NO_SYNC) Arg::new(OPT_NO_SYNC)
.long("no-sync") .long("no-sync")
.overrides_with_all(&[OPT_SYNC, OPT_NO_SYNC]) .overrides_with_all([OPT_SYNC, OPT_NO_SYNC])
.help("do not invoke sync before getting usage info (default)") .help("do not invoke sync before getting usage info (default)")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -577,9 +577,9 @@ pub fn uu_app() -> Command {
.require_equals(true) .require_equals(true)
.use_value_delimiter(true) .use_value_delimiter(true)
.value_parser(OUTPUT_FIELD_LIST) .value_parser(OUTPUT_FIELD_LIST)
.default_missing_values(&OUTPUT_FIELD_LIST) .default_missing_values(OUTPUT_FIELD_LIST)
.default_values(&["source", "size", "used", "avail", "pcent", "target"]) .default_values(["source", "size", "used", "avail", "pcent", "target"])
.conflicts_with_all(&[OPT_INODES, OPT_PORTABILITY, OPT_PRINT_TYPE]) .conflicts_with_all([OPT_INODES, OPT_PORTABILITY, OPT_PRINT_TYPE])
.help( .help(
"use the output format defined by FIELD_LIST, \ "use the output format defined by FIELD_LIST, \
or print all fields if FIELD_LIST is omitted.", or print all fields if FIELD_LIST is omitted.",
@ -596,7 +596,7 @@ pub fn uu_app() -> Command {
.arg( .arg(
Arg::new(OPT_SYNC) Arg::new(OPT_SYNC)
.long("sync") .long("sync")
.overrides_with_all(&[OPT_NO_SYNC, OPT_SYNC]) .overrides_with_all([OPT_NO_SYNC, OPT_SYNC])
.help("invoke sync before getting usage info (non-windows only)") .help("invoke sync before getting usage info (non-windows only)")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )

View file

@ -17,7 +17,6 @@ path = "src/dir.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] } clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs"] }
selinux = { version = "0.3", optional = true }
uu_ls = { version = ">=0.0.16", path="../ls"} uu_ls = { version = ">=0.0.16", path="../ls"}
[[bin]] [[bin]]

View file

@ -16,7 +16,6 @@ path = "src/dircolors.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
glob = "0.3.0"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }
[[bin]] [[bin]]

View file

@ -64,6 +64,9 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
let mut buffer = ['\\'; 2]; let mut buffer = ['\\'; 2];
// TODO `cargo +nightly clippy` complains that `.peek()` is never
// called on `iter`. However, `peek()` is called inside the
// `parse_code()` function that borrows `iter`.
let mut iter = input.chars().peekable(); let mut iter = input.chars().peekable();
while let Some(mut c) = iter.next() { while let Some(mut c) = iter.next() {
let mut start = 1; let mut start = 1;

View file

@ -278,8 +278,8 @@ pub fn uumain(mut args: impl uucore::Args) -> UResult<()> {
let tag = matches.get_flag("tag"); let tag = matches.get_flag("tag");
let nonames = *matches let nonames = *matches
.try_get_one("no-names") .try_get_one("no-names")
.unwrap_or(Some(&false)) .unwrap_or(None)
.unwrap(); .unwrap_or(&false);
let status = matches.get_flag("status"); let status = matches.get_flag("status");
let quiet = matches.get_flag("quiet") || status; let quiet = matches.get_flag("quiet") || status;
let strict = matches.get_flag("strict"); let strict = matches.get_flag("strict");

View file

@ -59,7 +59,7 @@ pub fn uu_app() -> Command {
NUM bytes of each file\ NUM bytes of each file\
", ",
) )
.overrides_with_all(&[options::BYTES_NAME, options::LINES_NAME]) .overrides_with_all([options::BYTES_NAME, options::LINES_NAME])
.allow_hyphen_values(true), .allow_hyphen_values(true),
) )
.arg( .arg(
@ -74,7 +74,7 @@ pub fn uu_app() -> Command {
NUM lines of each file\ NUM lines of each file\
", ",
) )
.overrides_with_all(&[options::LINES_NAME, options::BYTES_NAME]) .overrides_with_all([options::LINES_NAME, options::BYTES_NAME])
.allow_hyphen_values(true), .allow_hyphen_values(true),
) )
.arg( .arg(
@ -83,7 +83,7 @@ pub fn uu_app() -> Command {
.long("quiet") .long("quiet")
.visible_alias("silent") .visible_alias("silent")
.help("never print headers giving file names") .help("never print headers giving file names")
.overrides_with_all(&[options::VERBOSE_NAME, options::QUIET_NAME]) .overrides_with_all([options::VERBOSE_NAME, options::QUIET_NAME])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
@ -91,7 +91,7 @@ pub fn uu_app() -> Command {
.short('v') .short('v')
.long("verbose") .long("verbose")
.help("always print headers giving file names") .help("always print headers giving file names")
.overrides_with_all(&[options::QUIET_NAME, options::VERBOSE_NAME]) .overrides_with_all([options::QUIET_NAME, options::VERBOSE_NAME])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(

View file

@ -16,7 +16,7 @@ path = "src/hostid.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }
[[bin]] [[bin]]

View file

@ -81,7 +81,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_DOMAIN) Arg::new(OPT_DOMAIN)
.short('d') .short('d')
.long("domain") .long("domain")
.overrides_with_all(&[OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT]) .overrides_with_all([OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT])
.help("Display the name of the DNS domain if possible") .help("Display the name of the DNS domain if possible")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -89,7 +89,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_IP_ADDRESS) Arg::new(OPT_IP_ADDRESS)
.short('i') .short('i')
.long("ip-address") .long("ip-address")
.overrides_with_all(&[OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT]) .overrides_with_all([OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT])
.help("Display the network address(es) of the host") .help("Display the network address(es) of the host")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -97,7 +97,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_FQDN) Arg::new(OPT_FQDN)
.short('f') .short('f')
.long("fqdn") .long("fqdn")
.overrides_with_all(&[OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT]) .overrides_with_all([OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT])
.help("Display the FQDN (Fully Qualified Domain Name) (default)") .help("Display the FQDN (Fully Qualified Domain Name) (default)")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -105,7 +105,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_SHORT) Arg::new(OPT_SHORT)
.short('s') .short('s')
.long("short") .long("short")
.overrides_with_all(&[OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT]) .overrides_with_all([OPT_DOMAIN, OPT_IP_ADDRESS, OPT_FQDN, OPT_SHORT])
.help("Display the short hostname (the portion before the first dot) if possible") .help("Display the short hostname (the portion before the first dot) if possible")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )

View file

@ -348,7 +348,7 @@ pub fn uu_app() -> Command {
.arg( .arg(
Arg::new(options::OPT_AUDIT) Arg::new(options::OPT_AUDIT)
.short('A') .short('A')
.conflicts_with_all(&[ .conflicts_with_all([
options::OPT_GROUP, options::OPT_GROUP,
options::OPT_EFFECTIVE_USER, options::OPT_EFFECTIVE_USER,
options::OPT_HUMAN_READABLE, options::OPT_HUMAN_READABLE,
@ -382,7 +382,7 @@ pub fn uu_app() -> Command {
Arg::new(options::OPT_GROUPS) Arg::new(options::OPT_GROUPS)
.short('G') .short('G')
.long(options::OPT_GROUPS) .long(options::OPT_GROUPS)
.conflicts_with_all(&[ .conflicts_with_all([
options::OPT_GROUP, options::OPT_GROUP,
options::OPT_EFFECTIVE_USER, options::OPT_EFFECTIVE_USER,
options::OPT_CONTEXT, options::OPT_CONTEXT,
@ -443,7 +443,7 @@ pub fn uu_app() -> Command {
Arg::new(options::OPT_CONTEXT) Arg::new(options::OPT_CONTEXT)
.short('Z') .short('Z')
.long(options::OPT_CONTEXT) .long(options::OPT_CONTEXT)
.conflicts_with_all(&[options::OPT_GROUP, options::OPT_EFFECTIVE_USER]) .conflicts_with_all([options::OPT_GROUP, options::OPT_EFFECTIVE_USER])
.help(CONTEXT_HELP_TEXT) .help(CONTEXT_HELP_TEXT)
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )

View file

@ -15,7 +15,7 @@ edition = "2021"
path = "src/logname.rs" path = "src/logname.rs"
[dependencies] [dependencies]
libc = "0.2.135" libc = "0.2.137"
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }

View file

@ -981,7 +981,7 @@ pub fn uu_app() -> Command {
]) ])
.hide_possible_values(true) .hide_possible_values(true)
.require_equals(true) .require_equals(true)
.overrides_with_all(&[ .overrides_with_all([
options::FORMAT, options::FORMAT,
options::format::COLUMNS, options::format::COLUMNS,
options::format::LONG, options::format::LONG,
@ -993,7 +993,7 @@ pub fn uu_app() -> Command {
Arg::new(options::format::COLUMNS) Arg::new(options::format::COLUMNS)
.short('C') .short('C')
.help("Display the files in columns.") .help("Display the files in columns.")
.overrides_with_all(&[ .overrides_with_all([
options::FORMAT, options::FORMAT,
options::format::COLUMNS, options::format::COLUMNS,
options::format::LONG, options::format::LONG,
@ -1007,7 +1007,7 @@ pub fn uu_app() -> Command {
.short('l') .short('l')
.long(options::format::LONG) .long(options::format::LONG)
.help("Display detailed information.") .help("Display detailed information.")
.overrides_with_all(&[ .overrides_with_all([
options::FORMAT, options::FORMAT,
options::format::COLUMNS, options::format::COLUMNS,
options::format::LONG, options::format::LONG,
@ -1020,7 +1020,7 @@ pub fn uu_app() -> Command {
Arg::new(options::format::ACROSS) Arg::new(options::format::ACROSS)
.short('x') .short('x')
.help("List entries in rows instead of in columns.") .help("List entries in rows instead of in columns.")
.overrides_with_all(&[ .overrides_with_all([
options::FORMAT, options::FORMAT,
options::format::COLUMNS, options::format::COLUMNS,
options::format::LONG, options::format::LONG,
@ -1042,7 +1042,7 @@ pub fn uu_app() -> Command {
Arg::new(options::format::COMMAS) Arg::new(options::format::COMMAS)
.short('m') .short('m')
.help("List entries separated by commas.") .help("List entries separated by commas.")
.overrides_with_all(&[ .overrides_with_all([
options::FORMAT, options::FORMAT,
options::format::COLUMNS, options::format::COLUMNS,
options::format::LONG, options::format::LONG,
@ -1114,7 +1114,7 @@ pub fn uu_app() -> Command {
"c", "c",
"escape", "escape",
]) ])
.overrides_with_all(&[ .overrides_with_all([
options::QUOTING_STYLE, options::QUOTING_STYLE,
options::quoting::LITERAL, options::quoting::LITERAL,
options::quoting::ESCAPE, options::quoting::ESCAPE,
@ -1126,7 +1126,7 @@ pub fn uu_app() -> Command {
.short('N') .short('N')
.long(options::quoting::LITERAL) .long(options::quoting::LITERAL)
.help("Use literal quoting style. Equivalent to `--quoting-style=literal`") .help("Use literal quoting style. Equivalent to `--quoting-style=literal`")
.overrides_with_all(&[ .overrides_with_all([
options::QUOTING_STYLE, options::QUOTING_STYLE,
options::quoting::LITERAL, options::quoting::LITERAL,
options::quoting::ESCAPE, options::quoting::ESCAPE,
@ -1139,7 +1139,7 @@ pub fn uu_app() -> Command {
.short('b') .short('b')
.long(options::quoting::ESCAPE) .long(options::quoting::ESCAPE)
.help("Use escape quoting style. Equivalent to `--quoting-style=escape`") .help("Use escape quoting style. Equivalent to `--quoting-style=escape`")
.overrides_with_all(&[ .overrides_with_all([
options::QUOTING_STYLE, options::QUOTING_STYLE,
options::quoting::LITERAL, options::quoting::LITERAL,
options::quoting::ESCAPE, options::quoting::ESCAPE,
@ -1152,7 +1152,7 @@ pub fn uu_app() -> Command {
.short('Q') .short('Q')
.long(options::quoting::C) .long(options::quoting::C)
.help("Use C quoting style. Equivalent to `--quoting-style=c`") .help("Use C quoting style. Equivalent to `--quoting-style=c`")
.overrides_with_all(&[ .overrides_with_all([
options::QUOTING_STYLE, options::QUOTING_STYLE,
options::quoting::LITERAL, options::quoting::LITERAL,
options::quoting::ESCAPE, options::quoting::ESCAPE,
@ -1166,14 +1166,14 @@ pub fn uu_app() -> Command {
.short('q') .short('q')
.long(options::HIDE_CONTROL_CHARS) .long(options::HIDE_CONTROL_CHARS)
.help("Replace control characters with '?' if they are not escaped.") .help("Replace control characters with '?' if they are not escaped.")
.overrides_with_all(&[options::HIDE_CONTROL_CHARS, options::SHOW_CONTROL_CHARS]) .overrides_with_all([options::HIDE_CONTROL_CHARS, options::SHOW_CONTROL_CHARS])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
Arg::new(options::SHOW_CONTROL_CHARS) Arg::new(options::SHOW_CONTROL_CHARS)
.long(options::SHOW_CONTROL_CHARS) .long(options::SHOW_CONTROL_CHARS)
.help("Show control characters 'as is' if they are not escaped.") .help("Show control characters 'as is' if they are not escaped.")
.overrides_with_all(&[options::HIDE_CONTROL_CHARS, options::SHOW_CONTROL_CHARS]) .overrides_with_all([options::HIDE_CONTROL_CHARS, options::SHOW_CONTROL_CHARS])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
// Time arguments // Time arguments
@ -1192,7 +1192,7 @@ pub fn uu_app() -> Command {
]) ])
.hide_possible_values(true) .hide_possible_values(true)
.require_equals(true) .require_equals(true)
.overrides_with_all(&[options::TIME, options::time::ACCESS, options::time::CHANGE]), .overrides_with_all([options::TIME, options::time::ACCESS, options::time::CHANGE]),
) )
.arg( .arg(
Arg::new(options::time::CHANGE) Arg::new(options::time::CHANGE)
@ -1203,7 +1203,7 @@ pub fn uu_app() -> Command {
time. When explicitly sorting by time (--sort=time or -t) or when not \ time. When explicitly sorting by time (--sort=time or -t) or when not \
using a long listing format, sort according to the status change time.", using a long listing format, sort according to the status change time.",
) )
.overrides_with_all(&[options::TIME, options::time::ACCESS, options::time::CHANGE]) .overrides_with_all([options::TIME, options::time::ACCESS, options::time::CHANGE])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(
@ -1215,7 +1215,7 @@ pub fn uu_app() -> Command {
sorting by time (--sort=time or -t) or when not using a long listing \ sorting by time (--sort=time or -t) or when not using a long listing \
format, sort according to the access time.", format, sort according to the access time.",
) )
.overrides_with_all(&[options::TIME, options::time::ACCESS, options::time::CHANGE]) .overrides_with_all([options::TIME, options::time::ACCESS, options::time::CHANGE])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
// Hide and ignore // Hide and ignore
@ -1251,7 +1251,7 @@ pub fn uu_app() -> Command {
.value_name("field") .value_name("field")
.value_parser(["name", "none", "time", "size", "version", "extension"]) .value_parser(["name", "none", "time", "size", "version", "extension"])
.require_equals(true) .require_equals(true)
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1264,7 +1264,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sort::SIZE) Arg::new(options::sort::SIZE)
.short('S') .short('S')
.help("Sort by file size, largest first.") .help("Sort by file size, largest first.")
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1278,7 +1278,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sort::TIME) Arg::new(options::sort::TIME)
.short('t') .short('t')
.help("Sort by modification time (the 'mtime' in the inode), newest first.") .help("Sort by modification time (the 'mtime' in the inode), newest first.")
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1292,7 +1292,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sort::VERSION) Arg::new(options::sort::VERSION)
.short('v') .short('v')
.help("Natural sort of (version) numbers in the filenames.") .help("Natural sort of (version) numbers in the filenames.")
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1306,7 +1306,7 @@ pub fn uu_app() -> Command {
Arg::new(options::sort::EXTENSION) Arg::new(options::sort::EXTENSION)
.short('X') .short('X')
.help("Sort alphabetically by entry extension.") .help("Sort alphabetically by entry extension.")
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1324,7 +1324,7 @@ pub fn uu_app() -> Command {
directory. This is especially useful when listing very large directories, \ directory. This is especially useful when listing very large directories, \
since not doing any sorting can be noticeably faster.", since not doing any sorting can be noticeably faster.",
) )
.overrides_with_all(&[ .overrides_with_all([
options::SORT, options::SORT,
options::sort::SIZE, options::sort::SIZE,
options::sort::TIME, options::sort::TIME,
@ -1343,7 +1343,7 @@ pub fn uu_app() -> Command {
"When showing file information for a symbolic link, show information for the \ "When showing file information for a symbolic link, show information for the \
file the link references rather than the link itself.", file the link references rather than the link itself.",
) )
.overrides_with_all(&[ .overrides_with_all([
options::dereference::ALL, options::dereference::ALL,
options::dereference::DIR_ARGS, options::dereference::DIR_ARGS,
options::dereference::ARGS, options::dereference::ARGS,
@ -1357,7 +1357,7 @@ pub fn uu_app() -> Command {
"Do not dereference symlinks except when they link to directories and are \ "Do not dereference symlinks except when they link to directories and are \
given as command line arguments.", given as command line arguments.",
) )
.overrides_with_all(&[ .overrides_with_all([
options::dereference::ALL, options::dereference::ALL,
options::dereference::DIR_ARGS, options::dereference::DIR_ARGS,
options::dereference::ARGS, options::dereference::ARGS,
@ -1369,7 +1369,7 @@ pub fn uu_app() -> Command {
.short('H') .short('H')
.long(options::dereference::ARGS) .long(options::dereference::ARGS)
.help("Do not dereference symlinks except when given as command line arguments.") .help("Do not dereference symlinks except when given as command line arguments.")
.overrides_with_all(&[ .overrides_with_all([
options::dereference::ALL, options::dereference::ALL,
options::dereference::DIR_ARGS, options::dereference::DIR_ARGS,
options::dereference::ARGS, options::dereference::ARGS,
@ -1509,7 +1509,7 @@ pub fn uu_app() -> Command {
none (default), slash (-p), file-type (--file-type), classify (-F)", none (default), slash (-p), file-type (--file-type), classify (-F)",
) )
.value_parser(["none", "slash", "file-type", "classify"]) .value_parser(["none", "slash", "file-type", "classify"])
.overrides_with_all(&[ .overrides_with_all([
options::indicator_style::FILE_TYPE, options::indicator_style::FILE_TYPE,
options::indicator_style::SLASH, options::indicator_style::SLASH,
options::indicator_style::CLASSIFY, options::indicator_style::CLASSIFY,
@ -1545,7 +1545,7 @@ pub fn uu_app() -> Command {
.default_missing_value("always") .default_missing_value("always")
.require_equals(true) .require_equals(true)
.num_args(0..=1) .num_args(0..=1)
.overrides_with_all(&[ .overrides_with_all([
options::indicator_style::FILE_TYPE, options::indicator_style::FILE_TYPE,
options::indicator_style::SLASH, options::indicator_style::SLASH,
options::indicator_style::CLASSIFY, options::indicator_style::CLASSIFY,
@ -1556,7 +1556,7 @@ pub fn uu_app() -> Command {
Arg::new(options::indicator_style::FILE_TYPE) Arg::new(options::indicator_style::FILE_TYPE)
.long(options::indicator_style::FILE_TYPE) .long(options::indicator_style::FILE_TYPE)
.help("Same as --classify, but do not append '*'") .help("Same as --classify, but do not append '*'")
.overrides_with_all(&[ .overrides_with_all([
options::indicator_style::FILE_TYPE, options::indicator_style::FILE_TYPE,
options::indicator_style::SLASH, options::indicator_style::SLASH,
options::indicator_style::CLASSIFY, options::indicator_style::CLASSIFY,
@ -1568,7 +1568,7 @@ pub fn uu_app() -> Command {
Arg::new(options::indicator_style::SLASH) Arg::new(options::indicator_style::SLASH)
.short('p') .short('p')
.help("Append / indicator to directories.") .help("Append / indicator to directories.")
.overrides_with_all(&[ .overrides_with_all([
options::indicator_style::FILE_TYPE, options::indicator_style::FILE_TYPE,
options::indicator_style::SLASH, options::indicator_style::SLASH,
options::indicator_style::CLASSIFY, options::indicator_style::CLASSIFY,
@ -1584,7 +1584,7 @@ pub fn uu_app() -> Command {
.value_name("TIME_STYLE") .value_name("TIME_STYLE")
.env("TIME_STYLE") .env("TIME_STYLE")
.value_parser(NonEmptyStringValueParser::new()) .value_parser(NonEmptyStringValueParser::new())
.overrides_with_all(&[options::TIME_STYLE]), .overrides_with_all([options::TIME_STYLE]),
) )
.arg( .arg(
Arg::new(options::FULL_TIME) Arg::new(options::FULL_TIME)

View file

@ -16,7 +16,7 @@ path = "src/mkfifo.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }
[[bin]] [[bin]]

View file

@ -17,7 +17,7 @@ path = "src/mknod.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "^0.2.135" libc = "^0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["mode"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["mode"] }
[[bin]] [[bin]]

View file

@ -440,6 +440,9 @@ pub fn uu_app() -> Command {
may contain slashes, but mktemp creates only the final component", may contain slashes, but mktemp creates only the final component",
) )
.value_name("DIR") .value_name("DIR")
// Allows use of default argument just by setting --tmpdir. Else,
// use provided input to generate tmpdir
.num_args(0..=1)
.value_hint(clap::ValueHint::DirPath), .value_hint(clap::ValueHint::DirPath),
) )
.arg( .arg(

View file

@ -371,6 +371,12 @@ fn rename(from: &Path, to: &Path, b: &Behavior) -> io::Result<()> {
let mut backup_path = None; let mut backup_path = None;
if to.exists() { if to.exists() {
if b.update && b.overwrite == OverwriteMode::Interactive {
// `mv -i --update old new` when `new` exists doesn't move anything
// and exit with 0
return Ok(());
}
match b.overwrite { match b.overwrite {
OverwriteMode::NoClobber => return Ok(()), OverwriteMode::NoClobber => return Ok(()),
OverwriteMode::Interactive => { OverwriteMode::Interactive => {
@ -469,11 +475,11 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> {
{ {
if path_symlink_points_to.exists() { if path_symlink_points_to.exists() {
if path_symlink_points_to.is_dir() { if path_symlink_points_to.is_dir() {
windows::fs::symlink_dir(&path_symlink_points_to, &to)?; windows::fs::symlink_dir(&path_symlink_points_to, to)?;
} else { } else {
windows::fs::symlink_file(&path_symlink_points_to, &to)?; windows::fs::symlink_file(&path_symlink_points_to, to)?;
} }
fs::remove_file(&from)?; fs::remove_file(from)?;
} else { } else {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::NotFound, io::ErrorKind::NotFound,

View file

@ -16,7 +16,7 @@ path = "src/nice.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
nix = { version = "0.25", default-features = false } nix = { version = "0.25", default-features = false }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }

View file

@ -16,7 +16,7 @@ path = "src/nohup.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
atty = "0.2" atty = "0.2"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] }

View file

@ -15,8 +15,8 @@ edition = "2021"
path = "src/nproc.rs" path = "src/nproc.rs"
[dependencies] [dependencies]
libc = "0.2.135" libc = "0.2.137"
num_cpus = "1.10" num_cpus = "1.14"
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] }

View file

@ -272,14 +272,13 @@ fn transform_to(
let (i2, s) = consider_suffix(s, &opts.to, round_method, precision)?; let (i2, s) = consider_suffix(s, &opts.to, round_method, precision)?;
let i2 = i2 / (opts.to_unit as f64); let i2 = i2 / (opts.to_unit as f64);
Ok(match s { Ok(match s {
None if precision > 0 => { None => {
format!( format!(
"{:.precision$}", "{:.precision$}",
round_with_precision(i2, round_method, precision), round_with_precision(i2, round_method, precision),
precision = precision precision = precision
) )
} }
None => format!("{}", i2),
Some(s) if precision > 0 => { Some(s) if precision > 0 => {
format!( format!(
"{:.precision$}{}", "{:.precision$}{}",

View file

@ -158,12 +158,15 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
Ok(0) Ok(0)
}?; }?;
let fields = match args.get_one::<String>(options::FIELD).unwrap().as_str() { let fields = args.get_one::<String>(options::FIELD).unwrap().as_str();
"-" => vec![Range { // a lone "-" means "all fields", even as part of a list of fields
let fields = if fields.split(&[',', ' ']).any(|x| x == "-") {
vec![Range {
low: 1, low: 1,
high: std::usize::MAX, high: std::usize::MAX,
}], }]
v => Range::from_list(v)?, } else {
Range::from_list(fields)?
}; };
let format = match args.get_one::<String>(options::FORMAT) { let format = match args.get_one::<String>(options::FORMAT) {
@ -275,6 +278,7 @@ pub fn uu_app() -> Command {
.long(options::FIELD) .long(options::FIELD)
.help("replace the numbers in these input fields; see FIELDS below") .help("replace the numbers in these input fields; see FIELDS below")
.value_name("FIELDS") .value_name("FIELDS")
.allow_hyphen_values(true)
.default_value(options::FIELD_DEFAULT), .default_value(options::FIELD_DEFAULT),
) )
.arg( .arg(

View file

@ -16,7 +16,7 @@ path = "src/pathchk.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }
[[bin]] [[bin]]

View file

@ -126,7 +126,10 @@ fn logical_path() -> io::Result<PathBuf> {
#[uucore::main] #[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> { pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?; let matches = uu_app().try_get_matches_from(args)?;
let cwd = if matches.get_flag(OPT_LOGICAL) { // if POSIXLY_CORRECT is set, we want to a logical resolution.
// This produces a different output when doing mkdir -p a/b && ln -s a/b c && cd c && pwd
// We should get c in this case instead of a/b at the end of the path
let cwd = if matches.get_flag(OPT_LOGICAL) || env::var("POSIXLY_CORRECT").is_ok() {
logical_path() logical_path()
} else { } else {
physical_path() physical_path()

View file

@ -130,7 +130,7 @@ pub fn uu_app() -> Command {
Arg::new(OPT_PHYSICAL) Arg::new(OPT_PHYSICAL)
.short('P') .short('P')
.long(OPT_PHYSICAL) .long(OPT_PHYSICAL)
.overrides_with_all(&[OPT_STRIP, OPT_LOGICAL]) .overrides_with_all([OPT_STRIP, OPT_LOGICAL])
.help("resolve symlinks as encountered (default)") .help("resolve symlinks as encountered (default)")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )

View file

@ -20,6 +20,9 @@ walkdir = "2.2"
remove_dir_all = "0.7.0" remove_dir_all = "0.7.0"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2.137"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.42.0", default-features = false, features = ["Win32_Storage_FileSystem"] } windows-sys = { version = "0.42.0", default-features = false, features = ["Win32_Storage_FileSystem"] }

View file

@ -10,13 +10,11 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use clap::{crate_version, Arg, ArgAction, Command}; use clap::{crate_version, parser::ValueSource, Arg, ArgAction, Command};
use remove_dir_all::remove_dir_all; use remove_dir_all::remove_dir_all;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fs; use std::fs::{self, File, Metadata};
use std::fs::File; use std::io::{stderr, stdin, BufRead, ErrorKind, Write};
use std::io::ErrorKind;
use std::io::{stderr, stdin, BufRead, Write};
use std::ops::BitOr; use std::ops::BitOr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use uucore::display::Quotable; use uucore::display::Quotable;
@ -87,17 +85,30 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|v| v.map(ToString::to_string).collect()) .map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default(); .unwrap_or_default();
let force = matches.get_flag(OPT_FORCE); let force_flag = matches.get_flag(OPT_FORCE);
if files.is_empty() && !force { // If -f(--force) is before any -i (or variants) we want prompts else no prompts
let force_prompt_never: bool = force_flag && {
let force_index = matches.index_of(OPT_FORCE).unwrap_or(0);
![OPT_PROMPT, OPT_PROMPT_MORE, OPT_INTERACTIVE]
.iter()
.any(|flag| {
matches.value_source(flag) == Some(ValueSource::CommandLine)
&& matches.index_of(flag).unwrap_or(0) > force_index
})
};
if files.is_empty() && !force_flag {
// Still check by hand and not use clap // Still check by hand and not use clap
// Because "rm -f" is a thing // Because "rm -f" is a thing
return Err(UUsageError::new(1, "missing operand")); return Err(UUsageError::new(1, "missing operand"));
} else { } else {
let options = Options { let options = Options {
force, force: force_flag,
interactive: { interactive: {
if matches.get_flag(OPT_PROMPT) { if force_prompt_never {
InteractiveMode::Never
} else if matches.get_flag(OPT_PROMPT) {
InteractiveMode::Always InteractiveMode::Always
} else if matches.get_flag(OPT_PROMPT_MORE) { } else if matches.get_flag(OPT_PROMPT_MORE) {
InteractiveMode::Once InteractiveMode::Once
@ -159,12 +170,17 @@ pub fn uu_app() -> Command {
Arg::new(OPT_PROMPT) Arg::new(OPT_PROMPT)
.short('i') .short('i')
.help("prompt before every removal") .help("prompt before every removal")
.overrides_with_all([OPT_PROMPT_MORE, OPT_INTERACTIVE])
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(OPT_PROMPT_MORE)
.short('I')
.help("prompt once before removing more than three files, or when removing recursively. \
Less intrusive than -i, while still giving some protection against most mistakes")
.overrides_with_all([OPT_PROMPT, OPT_INTERACTIVE])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg(Arg::new(OPT_PROMPT_MORE).short('I').help(
"prompt once before removing more than three files, or when removing recursively. \
Less intrusive than -i, while still giving some protection against most mistakes",
).action(ArgAction::SetTrue))
.arg( .arg(
Arg::new(OPT_INTERACTIVE) Arg::new(OPT_INTERACTIVE)
.long(OPT_INTERACTIVE) .long(OPT_INTERACTIVE)
@ -172,7 +188,8 @@ pub fn uu_app() -> Command {
"prompt according to WHEN: never, once (-I), or always (-i). Without WHEN, \ "prompt according to WHEN: never, once (-I), or always (-i). Without WHEN, \
prompts always", prompts always",
) )
.value_name("WHEN"), .value_name("WHEN")
.overrides_with_all([OPT_PROMPT, OPT_PROMPT_MORE]),
) )
.arg( .arg(
Arg::new(OPT_ONE_FILE_SYSTEM) Arg::new(OPT_ONE_FILE_SYSTEM)
@ -361,12 +378,7 @@ fn handle_dir(path: &Path, options: &Options) -> bool {
} }
fn remove_dir(path: &Path, options: &Options) -> bool { fn remove_dir(path: &Path, options: &Options) -> bool {
let response = if options.interactive == InteractiveMode::Always { if prompt_file(path, options, true) {
prompt_file(path, true)
} else {
true
};
if response {
if let Ok(mut read_dir) = fs::read_dir(path) { if let Ok(mut read_dir) = fs::read_dir(path) {
if options.dir || options.recursive { if options.dir || options.recursive {
if read_dir.next().is_none() { if read_dir.next().is_none() {
@ -411,12 +423,7 @@ fn remove_dir(path: &Path, options: &Options) -> bool {
} }
fn remove_file(path: &Path, options: &Options) -> bool { fn remove_file(path: &Path, options: &Options) -> bool {
let response = if options.interactive == InteractiveMode::Always { if prompt_file(path, options, false) {
prompt_file(path, false)
} else {
true
};
if response && prompt_write_protected(path, false, options) {
match fs::remove_file(path) { match fs::remove_file(path) {
Ok(_) => { Ok(_) => {
if options.verbose { if options.verbose {
@ -438,46 +445,138 @@ fn remove_file(path: &Path, options: &Options) -> bool {
false false
} }
fn prompt_write_protected(path: &Path, is_dir: bool, options: &Options) -> bool { fn prompt_file(path: &Path, options: &Options, is_dir: bool) -> bool {
// If interactive is Never we never want to send prompts
if options.interactive == InteractiveMode::Never { if options.interactive == InteractiveMode::Never {
return true; return true;
} }
match File::open(path) { // If interactive is Always we want to check if the file is symlink to prompt the right message
Ok(_) => true, if options.interactive == InteractiveMode::Always {
Err(err) => { if let Ok(metadata) = fs::symlink_metadata(path) {
if err.kind() == ErrorKind::PermissionDenied { if metadata.is_symlink() {
if is_dir { return prompt(&(format!("remove symbolic link {}? ", path.quote())));
prompt(&(format!("rm: remove write-protected directory {}? ", path.quote()))) }
} else { }
if fs::metadata(path).unwrap().len() == 0 { }
return prompt( if is_dir {
&(format!( // We can't use metadata.permissions.readonly for directories because it only works on files
"rm: remove write-protected regular empty file {}? ", // So we have to handle wether a directory is writable on not manually
path.quote() if let Ok(metadata) = fs::metadata(path) {
)), handle_writable_directory(path, options, &metadata)
); } else {
true
}
} else {
// File::open(path) doesn't open the file in write mode so we need to use file options to open it in also write mode to check if it can written too
match File::options().read(true).write(true).open(path) {
Ok(file) => {
if let Ok(metadata) = file.metadata() {
if metadata.permissions().readonly() {
if metadata.len() == 0 {
prompt(
&(format!(
"remove write-protected regular empty file {}? ",
path.quote()
)),
)
} else {
prompt(
&(format!(
"remove write-protected regular file {}? ",
path.quote()
)),
)
}
} else if options.interactive == InteractiveMode::Always {
if metadata.len() == 0 {
prompt(&(format!("remove regular empty file {}? ", path.quote())))
} else {
prompt(&(format!("remove file {}? ", path.quote())))
}
} else {
true
} }
prompt(&(format!("rm: remove write-protected regular file {}? ", path.quote()))) } else {
true
}
}
Err(err) => {
if err.kind() == ErrorKind::PermissionDenied {
if let Ok(metadata) = fs::metadata(path) {
if metadata.len() == 0 {
prompt(
&(format!(
"remove write-protected regular empty file {}? ",
path.quote()
)),
)
} else {
prompt(
&(format!(
"remove write-protected regular file {}? ",
path.quote()
)),
)
}
} else {
prompt(&(format!("remove write-protected regular file {}? ", path.quote())))
}
} else {
true
} }
} else {
true
} }
} }
} }
} }
fn prompt_descend(path: &Path) -> bool { // For directories finding if they are writable or not is a hassle. In Unix we can use the built-in rust crate to to check mode bits. But other os don't have something similar afaik
prompt(&(format!("rm: descend into directory {}? ", path.quote()))) // Most cases are covered by keep eye out for edge cases
#[cfg(unix)]
fn handle_writable_directory(path: &Path, options: &Options, metadata: &Metadata) -> bool {
use std::os::unix::fs::PermissionsExt;
let mode = metadata.permissions().mode();
// Check if directory has user write permissions
// Why is S_IWUSR showing up as a u16 on macos?
let user_writable = (mode & (libc::S_IWUSR as u32)) != 0;
if !user_writable {
prompt(&(format!("remove write-protected directory {}? ", path.quote())))
} else if options.interactive == InteractiveMode::Always {
prompt(&(format!("remove directory {}? ", path.quote())))
} else {
true
}
} }
fn prompt_file(path: &Path, is_dir: bool) -> bool { // For windows we can use windows metadata trait and file attributes to see if a directory is readonly
if is_dir { #[cfg(windows)]
prompt(&(format!("rm: remove directory {}? ", path.quote()))) fn handle_writable_directory(path: &Path, options: &Options, metadata: &Metadata) -> bool {
use std::os::windows::prelude::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_READONLY;
let not_user_writable = (metadata.file_attributes() & FILE_ATTRIBUTE_READONLY) != 0;
if not_user_writable {
prompt(&(format!("remove write-protected directory {}? ", path.quote())))
} else if options.interactive == InteractiveMode::Always {
prompt(&(format!("remove directory {}? ", path.quote())))
} else { } else {
prompt(&(format!("rm: remove file {}? ", path.quote()))) true
} }
} }
// I have this here for completeness but it will always return "remove directory {}" because metadata.permissions().readonly() only works for file not directories
#[cfg(not(windows))]
#[cfg(not(unix))]
fn handle_writable_directory(path: &Path, options: &Options, metadata: &Metadata) -> bool {
if options.interactive == InteractiveMode::Always {
prompt(&(format!("remove directory {}? ", path.quote())))
} else {
true
}
}
fn prompt_descend(path: &Path) -> bool {
prompt(&(format!("descend into directory {}? ", path.quote())))
}
fn normalize(path: &Path) -> PathBuf { fn normalize(path: &Path) -> PathBuf {
// copied from https://github.com/rust-lang/cargo/blob/2e4cfc2b7d43328b207879228a2ca7d427d188bb/src/cargo/util/paths.rs#L65-L90 // copied from https://github.com/rust-lang/cargo/blob/2e4cfc2b7d43328b207879228a2ca7d427d188bb/src/cargo/util/paths.rs#L65-L90
// both projects are MIT https://github.com/rust-lang/cargo/blob/master/LICENSE-MIT // both projects are MIT https://github.com/rust-lang/cargo/blob/master/LICENSE-MIT
@ -487,7 +586,7 @@ fn normalize(path: &Path) -> PathBuf {
} }
fn prompt(msg: &str) -> bool { fn prompt(msg: &str) -> bool {
let _ = stderr().write_all(msg.as_bytes()); let _ = stderr().write_all(format!("{}: {}", uucore::util_name(), msg).as_bytes());
let _ = stderr().flush(); let _ = stderr().flush();
let mut buf = Vec::new(); let mut buf = Vec::new();
@ -501,15 +600,13 @@ fn prompt(msg: &str) -> bool {
} }
#[cfg(not(windows))] #[cfg(not(windows))]
fn is_symlink_dir(_metadata: &fs::Metadata) -> bool { fn is_symlink_dir(_metadata: &Metadata) -> bool {
false false
} }
#[cfg(windows)] #[cfg(windows)]
use std::os::windows::prelude::MetadataExt; fn is_symlink_dir(metadata: &Metadata) -> bool {
use std::os::windows::prelude::MetadataExt;
#[cfg(windows)]
fn is_symlink_dir(metadata: &fs::Metadata) -> bool {
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY;
metadata.file_type().is_symlink() metadata.file_type().is_symlink()

View file

@ -17,7 +17,7 @@ path = "src/rmdir.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["fs"] }
libc = "0.2.135" libc = "0.2.137"
[[bin]] [[bin]]
name = "rmdir" name = "rmdir"

View file

@ -15,7 +15,7 @@ edition = "2021"
path = "src/sort.rs" path = "src/sort.rs"
[dependencies] [dependencies]
binary-heap-plus = "0.4.1" binary-heap-plus = "0.5.0"
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
compare = "0.1.0" compare = "0.1.0"
ctrlc = { version = "3.0", features = ["termination"] } ctrlc = { version = "3.0", features = ["termination"] }

View file

@ -1336,7 +1336,7 @@ pub fn uu_app() -> Command {
"version", "version",
"random", "random",
]) ])
.conflicts_with_all(&options::modes::ALL_SORT_MODES), .conflicts_with_all(options::modes::ALL_SORT_MODES),
) )
.arg(make_sort_mode_arg( .arg(make_sort_mode_arg(
options::modes::HUMAN_NUMERIC, options::modes::HUMAN_NUMERIC,
@ -1373,7 +1373,7 @@ pub fn uu_app() -> Command {
.short('d') .short('d')
.long(options::DICTIONARY_ORDER) .long(options::DICTIONARY_ORDER)
.help("consider only blanks and alphanumeric characters") .help("consider only blanks and alphanumeric characters")
.conflicts_with_all(&[ .conflicts_with_all([
options::modes::NUMERIC, options::modes::NUMERIC,
options::modes::GENERAL_NUMERIC, options::modes::GENERAL_NUMERIC,
options::modes::HUMAN_NUMERIC, options::modes::HUMAN_NUMERIC,
@ -1425,7 +1425,7 @@ pub fn uu_app() -> Command {
.short('i') .short('i')
.long(options::IGNORE_NONPRINTING) .long(options::IGNORE_NONPRINTING)
.help("ignore nonprinting characters") .help("ignore nonprinting characters")
.conflicts_with_all(&[ .conflicts_with_all([
options::modes::NUMERIC, options::modes::NUMERIC,
options::modes::GENERAL_NUMERIC, options::modes::GENERAL_NUMERIC,
options::modes::HUMAN_NUMERIC, options::modes::HUMAN_NUMERIC,

View file

@ -16,7 +16,7 @@ path = "src/sync.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["wide"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["wide"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]

View file

@ -18,6 +18,8 @@ use nix::fcntl::{open, OFlag};
use nix::sys::stat::Mode; use nix::sys::stat::Mode;
use std::path::Path; use std::path::Path;
use uucore::display::Quotable; use uucore::display::Quotable;
#[cfg(any(target_os = "linux", target_os = "android"))]
use uucore::error::FromIo;
use uucore::error::{UResult, USimpleError}; use uucore::error::{UResult, USimpleError};
use uucore::format_usage; use uucore::format_usage;
@ -170,29 +172,14 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Use the Nix open to be able to set the NONBLOCK flags for fifo files // Use the Nix open to be able to set the NONBLOCK flags for fifo files
#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg(any(target_os = "linux", target_os = "android"))]
{ {
match open(Path::new(&f), OFlag::O_NONBLOCK, Mode::empty()) { let path = Path::new(&f);
Ok(_) => {} if let Err(e) = open(path, OFlag::O_NONBLOCK, Mode::empty()) {
Err(e) => { if e != Errno::EACCES || (e == Errno::EACCES && path.is_dir()) {
if e == Errno::ENOENT { return e.map_err_context(|| format!("cannot stat {}", f.quote()))?;
return Err(USimpleError::new(
1,
format!("cannot stat {}: No such file or directory", f.quote()),
));
}
if e == Errno::EACCES {
if Path::new(&f).is_dir() {
return Err(USimpleError::new(
1,
format!("error opening {}: Permission denied", f.quote()),
));
} else {
// ignore the issue
// ./target/debug/coreutils sync --data file
}
}
} }
} }
} }
#[cfg(not(any(target_os = "linux", target_os = "android")))] #[cfg(not(any(target_os = "linux", target_os = "android")))]
{ {
if !Path::new(&f).exists() { if !Path::new(&f).exists() {

View file

@ -17,7 +17,7 @@ path = "src/tail.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
memchr = "2.5.0" memchr = "2.5.0"
notify = { version = "=5.0.0", features=["macos_kqueue"]} notify = { version = "=5.0.0", features=["macos_kqueue"]}
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["ringbuffer", "lines"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["ringbuffer", "lines"] }

View file

@ -334,7 +334,7 @@ pub fn uu_app() -> Command {
.short('c') .short('c')
.long(options::BYTES) .long(options::BYTES)
.allow_hyphen_values(true) .allow_hyphen_values(true)
.overrides_with_all(&[options::BYTES, options::LINES]) .overrides_with_all([options::BYTES, options::LINES])
.help("Number of bytes to print"), .help("Number of bytes to print"),
) )
.arg( .arg(
@ -352,7 +352,7 @@ pub fn uu_app() -> Command {
.short('n') .short('n')
.long(options::LINES) .long(options::LINES)
.allow_hyphen_values(true) .allow_hyphen_values(true)
.overrides_with_all(&[options::BYTES, options::LINES]) .overrides_with_all([options::BYTES, options::LINES])
.help("Number of lines to print"), .help("Number of lines to print"),
) )
.arg( .arg(
@ -366,7 +366,7 @@ pub fn uu_app() -> Command {
.short('q') .short('q')
.long(options::verbosity::QUIET) .long(options::verbosity::QUIET)
.visible_alias("silent") .visible_alias("silent")
.overrides_with_all(&[options::verbosity::QUIET, options::verbosity::VERBOSE]) .overrides_with_all([options::verbosity::QUIET, options::verbosity::VERBOSE])
.help("Never output headers giving file names") .help("Never output headers giving file names")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -392,7 +392,7 @@ pub fn uu_app() -> Command {
Arg::new(options::verbosity::VERBOSE) Arg::new(options::verbosity::VERBOSE)
.short('v') .short('v')
.long(options::verbosity::VERBOSE) .long(options::verbosity::VERBOSE)
.overrides_with_all(&[options::verbosity::QUIET, options::verbosity::VERBOSE]) .overrides_with_all([options::verbosity::QUIET, options::verbosity::VERBOSE])
.help("Always output headers giving file names") .help("Always output headers giving file names")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -421,7 +421,7 @@ pub fn uu_app() -> Command {
Arg::new(options::FOLLOW_RETRY) Arg::new(options::FOLLOW_RETRY)
.short('F') .short('F')
.help("Same as --follow=name --retry") .help("Same as --follow=name --retry")
.overrides_with_all(&[options::RETRY, options::FOLLOW]) .overrides_with_all([options::RETRY, options::FOLLOW])
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
.arg( .arg(

View file

@ -16,7 +16,7 @@ path = "src/tee.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
retain_mut = "=0.1.7" # ToDO: [2021-01-01; rivy; maint/MinSRV] ~ v0.1.5 uses const generics which aren't stabilized until rust v1.51.0 retain_mut = "=0.1.7" # ToDO: [2021-01-01; rivy; maint/MinSRV] ~ v0.1.5 uses const generics which aren't stabilized until rust v1.51.0
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["libc"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["libc"] }

View file

@ -16,7 +16,7 @@ path = "src/test.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore" } uucore = { version=">=0.0.16", package="uucore", path="../../uucore" }
[target.'cfg(target_os = "redox")'.dependencies] [target.'cfg(target_os = "redox")'.dependencies]

View file

@ -452,18 +452,18 @@ mod tests {
fn test_integer_op() { fn test_integer_op() {
let a = OsStr::new("18446744073709551616"); let a = OsStr::new("18446744073709551616");
let b = OsStr::new("0"); let b = OsStr::new("0");
assert_eq!(integers(a, b, OsStr::new("-lt")).unwrap(), false); assert!(!integers(a, b, OsStr::new("-lt")).unwrap());
let a = OsStr::new("18446744073709551616"); let a = OsStr::new("18446744073709551616");
let b = OsStr::new("0"); let b = OsStr::new("0");
assert_eq!(integers(a, b, OsStr::new("-gt")).unwrap(), true); assert!(integers(a, b, OsStr::new("-gt")).unwrap());
let a = OsStr::new("-1"); let a = OsStr::new("-1");
let b = OsStr::new("0"); let b = OsStr::new("0");
assert_eq!(integers(a, b, OsStr::new("-lt")).unwrap(), true); assert!(integers(a, b, OsStr::new("-lt")).unwrap());
let a = OsStr::new("42"); let a = OsStr::new("42");
let b = OsStr::new("42"); let b = OsStr::new("42");
assert_eq!(integers(a, b, OsStr::new("-eq")).unwrap(), true); assert!(integers(a, b, OsStr::new("-eq")).unwrap());
let a = OsStr::new("42"); let a = OsStr::new("42");
let b = OsStr::new("42"); let b = OsStr::new("42");
assert_eq!(integers(a, b, OsStr::new("-ne")).unwrap(), false); assert!(!integers(a, b, OsStr::new("-ne")).unwrap());
} }
} }

View file

@ -16,7 +16,7 @@ path = "src/timeout.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
nix = { version = "0.25", default-features = false, features = ["signal"] } nix = { version = "0.25", default-features = false, features = ["signal"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["process", "signals"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["process", "signals"] }

View file

@ -254,7 +254,7 @@ pub fn uu_app() -> Command {
.value_parser(ValueParser::os_string()) .value_parser(ValueParser::os_string())
.value_hint(clap::ValueHint::AnyPath), .value_hint(clap::ValueHint::AnyPath),
) )
.group(ArgGroup::new(options::SOURCES).args(&[ .group(ArgGroup::new(options::SOURCES).args([
options::sources::CURRENT, options::sources::CURRENT,
options::sources::DATE, options::sources::DATE,
options::sources::REFERENCE, options::sources::REFERENCE,

View file

@ -336,7 +336,7 @@ pub fn uu_app() -> Command {
.num_args(0..=1) .num_args(0..=1)
.default_missing_value("separate") .default_missing_value("separate")
.require_equals(true) .require_equals(true)
.conflicts_with_all(&[ .conflicts_with_all([
options::REPEATED, options::REPEATED,
options::ALL_REPEATED, options::ALL_REPEATED,
options::UNIQUE, options::UNIQUE,

View file

@ -17,7 +17,6 @@ path = "src/vdir.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] } clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] }
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["entries", "fs"] }
selinux = { version="0.3", optional = true }
uu_ls = { version = ">=0.0.16", path="../ls"} uu_ls = { version = ">=0.0.16", path="../ls"}
[[bin]] [[bin]]

View file

@ -250,7 +250,7 @@ pub fn uu_app() -> Command {
.long(options::MESG) .long(options::MESG)
.short('T') .short('T')
.visible_short_alias('w') .visible_short_alias('w')
.visible_aliases(&["message", "writable"]) .visible_aliases(["message", "writable"])
.help("add user's message status as +, - or ?") .help("add user's message status as +, - or ?")
.action(ArgAction::SetTrue), .action(ArgAction::SetTrue),
) )
@ -350,7 +350,7 @@ impl Who {
println!("{}", users.join(" ")); println!("{}", users.join(" "));
println!("# users={}", users.len()); println!("# users={}", users.len());
} else { } else {
let records = Utmpx::iter_all_records_from(f).peekable(); let records = Utmpx::iter_all_records_from(f);
if self.include_heading { if self.include_heading {
self.print_heading(); self.print_heading();

View file

@ -22,7 +22,7 @@ uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=[
windows-sys = { version = "0.42.0", default-features = false, features = ["Win32_NetworkManagement_NetManagement", "Win32_System_WindowsProgramming", "Win32_Foundation"] } windows-sys = { version = "0.42.0", default-features = false, features = ["Win32_NetworkManagement_NetManagement", "Win32_System_WindowsProgramming", "Win32_Foundation"] }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2.135" libc = "0.2.137"
[[bin]] [[bin]]
name = "whoami" name = "whoami"

View file

@ -16,7 +16,7 @@ path = "src/yes.rs"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo"] } clap = { version = "4.0", features = ["wrap_help", "cargo"] }
libc = "0.2.135" libc = "0.2.137"
uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["pipes"] } uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features=["pipes"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]

View file

@ -32,13 +32,13 @@ time = { version="0.3", optional=true, features = ["formatting", "local-offset",
data-encoding = { version="2.1", optional=true } data-encoding = { version="2.1", optional=true }
data-encoding-macro = { version="0.1.12", optional=true } data-encoding-macro = { version="0.1.12", optional=true }
z85 = { version="3.0.5", optional=true } z85 = { version="3.0.5", optional=true }
libc = { version="0.2.135", optional=true } libc = { version="0.2.137", optional=true }
once_cell = "1.13.1" once_cell = "1.13.1"
os_display = "0.1.3" os_display = "0.1.3"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
walkdir = { version="2.3.2", optional=true } walkdir = { version="2.3.2", optional=true }
nix = { version = "0.25", optional = true, default-features = false, features = ["fs", "uio", "zerocopy"] } nix = { version = "0.25", default-features = false, features = ["fs", "uio", "zerocopy"] }
[dev-dependencies] [dev-dependencies]
clap = "4.0" clap = "4.0"
@ -53,8 +53,8 @@ default = []
# * non-default features # * non-default features
encoding = ["data-encoding", "data-encoding-macro", "z85", "thiserror"] encoding = ["data-encoding", "data-encoding-macro", "z85", "thiserror"]
entries = ["libc"] entries = ["libc"]
fs = ["libc", "nix", "winapi-util", "windows-sys"] fs = ["libc", "winapi-util", "windows-sys"]
fsext = ["libc", "nix", "time", "windows-sys"] fsext = ["libc", "time", "windows-sys"]
lines = [] lines = []
memo = ["itertools"] memo = ["itertools"]
mode = ["libc"] mode = ["libc"]
@ -65,4 +65,4 @@ signals = []
utf8 = [] utf8 = []
utmpx = ["time", "time/macros", "libc", "dns-lookup"] utmpx = ["time", "time/macros", "libc", "dns-lookup"]
wide = [] wide = []
pipes = ["nix"] pipes = []

View file

@ -303,7 +303,7 @@ impl MountInfo {
let mut mn_info = Self { let mut mn_info = Self {
dev_id: volume_name, dev_id: volume_name,
dev_name, dev_name,
fs_type: fs_type.unwrap_or_else(|| "".to_string()), fs_type: fs_type.unwrap_or_default(),
mount_root, mount_root,
mount_dir: "".to_string(), mount_dir: "".to_string(),
mount_option: "".to_string(), mount_option: "".to_string(),

View file

@ -508,6 +508,60 @@ impl From<std::io::Error> for Box<dyn UError> {
} }
} }
/// Enables the conversion from [`Result<T, nix::Error>`] to [`UResult<T>`].
///
/// # Examples
///
/// ```
/// use uucore::error::FromIo;
/// use nix::errno::Errno;
///
/// let nix_err = Err::<(), nix::Error>(Errno::EACCES);
/// let uio_result = nix_err.map_err_context(|| String::from("fix me please!"));
///
/// // prints "fix me please!: Permission denied"
/// println!("{}", uio_result.unwrap_err());
/// ```
#[cfg(any(target_os = "linux", target_os = "android"))]
impl<T> FromIo<UResult<T>> for Result<T, nix::Error> {
fn map_err_context(self, context: impl FnOnce() -> String) -> UResult<T> {
self.map_err(|e| {
Box::new(UIoError {
context: Some((context)()),
inner: std::io::Error::from_raw_os_error(e as i32),
}) as Box<dyn UError>
})
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl<T> FromIo<UResult<T>> for nix::Error {
fn map_err_context(self, context: impl FnOnce() -> String) -> UResult<T> {
Err(Box::new(UIoError {
context: Some((context)()),
inner: std::io::Error::from_raw_os_error(self as i32),
}) as Box<dyn UError>)
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl From<nix::Error> for UIoError {
fn from(f: nix::Error) -> Self {
Self {
context: None,
inner: std::io::Error::from_raw_os_error(f as i32),
}
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl From<nix::Error> for Box<dyn UError> {
fn from(f: nix::Error) -> Self {
let u_error: UIoError = f.into();
Box::new(u_error) as Self
}
}
/// Shorthand to construct [`UIoError`]-instances. /// Shorthand to construct [`UIoError`]-instances.
/// ///
/// This macro serves as a convenience call to quickly construct instances of /// This macro serves as a convenience call to quickly construct instances of
@ -693,3 +747,30 @@ impl Display for ClapErrorWrapper {
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod tests {
#[test]
#[cfg(any(target_os = "linux", target_os = "android"))]
fn test_nix_error_conversion() {
use super::{FromIo, UIoError};
use nix::errno::Errno;
use std::io::ErrorKind;
for (nix_error, expected_error_kind) in [
(Errno::EACCES, ErrorKind::PermissionDenied),
(Errno::ENOENT, ErrorKind::NotFound),
(Errno::EEXIST, ErrorKind::AlreadyExists),
] {
let error = UIoError::from(nix_error);
assert_eq!(expected_error_kind, error.inner.kind());
}
assert_eq!(
"test: Permission denied",
Err::<(), nix::Error>(Errno::EACCES)
.map_err_context(|| String::from("test"))
.unwrap_err()
.to_string()
)
}
}

View file

@ -75,7 +75,7 @@ impl Range {
pub fn from_list(list: &str) -> Result<Vec<Self>, String> { pub fn from_list(list: &str) -> Result<Vec<Self>, String> {
let mut ranges = Vec::new(); let mut ranges = Vec::new();
for item in list.split(',') { for item in list.split(&[',', ' ']) {
let range_item = FromStr::from_str(item) let range_item = FromStr::from_str(item)
.map_err(|e| format!("range {} was invalid: {}", item.quote(), e))?; .map_err(|e| format!("range {} was invalid: {}", item.quote(), e))?;
ranges.push(range_item); ranges.push(range_item);

View file

@ -423,6 +423,38 @@ fn test_chown_only_user_id() {
.stderr_contains("failed to change"); .stderr_contains("failed to change");
} }
#[test]
fn test_chown_fail_id() {
// test chown 1111. file.txt
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let result = scene.cmd_keepenv("id").arg("-u").run();
if skipping_test_is_okay(&result, "id: cannot find name for group ID") {
return;
}
let user_id = String::from(result.stdout_str().trim());
assert!(!user_id.is_empty());
let file1 = "test_chown_file1";
at.touch(file1);
scene
.ucmd()
.arg(format!("{}:", user_id))
.arg(file1)
.fails()
.stderr_contains("invalid spec");
scene
.ucmd()
.arg(format!("{}.", user_id))
.arg(file1)
.fails()
.stderr_contains("invalid spec");
}
/// Test for setting the owner to a user ID for a user that does not exist. /// Test for setting the owner to a user ID for a user that does not exist.
/// ///
/// For example: /// For example:
@ -708,7 +740,7 @@ fn test_chown_file_notexisting() {
.fails(); .fails();
// TODO: uncomment once "failed to change ownership of '{}' to {}" added to stdout // TODO: uncomment once "failed to change ownership of '{}' to {}" added to stdout
// result.stderr_contains(&"retained as"); // result.stderr_contains("retained as");
// TODO: uncomment once message changed from "cannot dereference" to "cannot access" // TODO: uncomment once message changed from "cannot dereference" to "cannot access"
// result.stderr_contains(&"cannot access 'not_existing': No such file or directory"); // result.stderr_contains("cannot access 'not_existing': No such file or directory");
} }

View file

@ -1,4 +1,4 @@
// spell-checker:ignore (flags) reflink (fs) tmpfs (linux) rlimit Rlim NOFILE clob btrfs ROOTDIR USERDIR procfs // spell-checker:ignore (flags) reflink (fs) tmpfs (linux) rlimit Rlim NOFILE clob btrfs ROOTDIR USERDIR procfs outfile
use crate::common::util::*; use crate::common::util::*;
#[cfg(not(windows))] #[cfg(not(windows))]
@ -215,6 +215,18 @@ fn test_cp_target_directory_is_file() {
.stderr_contains(format!("'{}' is not a directory", TEST_HOW_ARE_YOU_SOURCE)); .stderr_contains(format!("'{}' is not a directory", TEST_HOW_ARE_YOU_SOURCE));
} }
#[test]
fn test_cp_arg_update_interactive() {
new_ucmd!()
.arg(TEST_HELLO_WORLD_SOURCE)
.arg(TEST_HOW_ARE_YOU_SOURCE)
.arg("-i")
.arg("--update")
.succeeds()
.no_stdout()
.no_stderr();
}
#[test] #[test]
fn test_cp_arg_interactive() { fn test_cp_arg_interactive() {
let (at, mut ucmd) = at_and_ucmd!(); let (at, mut ucmd) = at_and_ucmd!();
@ -1827,6 +1839,19 @@ fn test_copy_through_dangling_symlink_no_dereference_2() {
.stderr_only("cp: not writing through dangling symlink 'target'"); .stderr_only("cp: not writing through dangling symlink 'target'");
} }
/// Test that copy through a dangling symbolic link fails, even with --force.
#[test]
#[cfg(not(windows))]
fn test_copy_through_dangling_symlink_force() {
let (at, mut ucmd) = at_and_ucmd!();
at.touch("src");
at.symlink_file("no-such-file", "dest");
ucmd.args(&["--force", "src", "dest"])
.fails()
.stderr_only("cp: not writing through dangling symlink 'dest'");
assert!(!at.file_exists("dest"));
}
#[test] #[test]
#[cfg(unix)] #[cfg(unix)]
fn test_cp_archive_on_nonexistent_file() { fn test_cp_archive_on_nonexistent_file() {
@ -2269,3 +2294,32 @@ fn test_same_file_force_backup() {
.no_stderr(); .no_stderr();
assert!(at.file_exists("f~")); assert!(at.file_exists("f~"));
} }
/// Test for copying the contents of a FIFO as opposed to the FIFO object itself.
#[cfg(unix)]
#[test]
fn test_copy_contents_fifo() {
let scenario = TestScenario::new(util_name!());
let at = &scenario.fixtures;
// Start the `cp` process, reading the contents of `fifo` and
// writing to regular file `outfile`.
at.mkfifo("fifo");
let mut ucmd = scenario.ucmd();
let child = ucmd
.args(&["--copy-contents", "fifo", "outfile"])
.run_no_wait();
// Write some bytes to the `fifo`. We expect these bytes to get
// copied through to `outfile`.
std::fs::write(at.plus("fifo"), "foo").unwrap();
// At this point the child process should have terminated
// successfully with no output. The `outfile` should have the
// contents of `fifo` copied into it.
let output = child.wait_with_output().unwrap();
assert!(output.status.success());
assert!(output.stdout.is_empty());
assert!(output.stderr.is_empty());
assert_eq!(at.read("outfile"), "foo");
}

View file

@ -220,7 +220,7 @@ fn test_change_directory() {
let out = scene let out = scene
.ucmd() .ucmd()
.arg("--chdir") .arg("--chdir")
.arg(&temporary_path) .arg(temporary_path)
.args(&pwd) .args(&pwd)
.succeeds() .succeeds()
.stdout_move_str(); .stdout_move_str();

View file

@ -1863,7 +1863,7 @@ fn test_ls_recursive() {
#[cfg(not(windows))] #[cfg(not(windows))]
result.stdout_contains("a/b:\nb"); result.stdout_contains("a/b:\nb");
#[cfg(windows)] #[cfg(windows)]
result.stdout_contains(&"a\\b:\nb"); result.stdout_contains("a\\b:\nb");
} }
#[test] #[test]
@ -2093,13 +2093,13 @@ fn test_ls_indicator_style() {
.ucmd() .ucmd()
.arg(format!("--indicator-style={}", opt)) .arg(format!("--indicator-style={}", opt))
.succeeds() .succeeds()
.stdout_contains(&"/"); .stdout_contains("/");
} }
// Same test as above, but with the alternate flags. // Same test as above, but with the alternate flags.
let options = vec!["--classify", "--file-type", "-p"]; let options = vec!["--classify", "--file-type", "-p"];
for opt in options { for opt in options {
scene.ucmd().arg(opt).succeeds().stdout_contains(&"/"); scene.ucmd().arg(opt).succeeds().stdout_contains("/");
} }
// Classify and File-Type all contain indicators for pipes and links. // Classify and File-Type all contain indicators for pipes and links.
@ -2110,7 +2110,7 @@ fn test_ls_indicator_style() {
.ucmd() .ucmd()
.arg(format!("--indicator-style={}", opt)) .arg(format!("--indicator-style={}", opt))
.succeeds() .succeeds()
.stdout_contains(&"@"); .stdout_contains("@");
} }
} }
@ -3195,7 +3195,7 @@ fn test_ls_context_format() {
] { ] {
let format = format!("--format={}", word); let format = format!("--format={}", word);
ts.ucmd() ts.ucmd()
.args(&[&"-Z", &format.as_str(), &"/"]) .args(&["-Z", format.as_str(), "/"])
.succeeds() .succeeds()
.stdout_only( .stdout_only(
unwrap_or_return!(expected_result(&ts, &["-Z", format.as_str(), "/"])).stdout_str(), unwrap_or_return!(expected_result(&ts, &["-Z", format.as_str(), "/"])).stdout_str(),

View file

@ -825,3 +825,9 @@ fn test_nonexistent_dir_prefix() {
); );
} }
} }
#[test]
fn test_default_missing_value() {
let scene = TestScenario::new(util_name!());
scene.ucmd().arg("-d").arg("--tmpdir").succeeds();
}

View file

@ -184,6 +184,25 @@ fn test_mv_interactive() {
assert!(at.file_exists(file_b)); assert!(at.file_exists(file_b));
} }
#[test]
fn test_mv_arg_update_interactive() {
let (at, mut ucmd) = at_and_ucmd!();
let file_a = "test_mv_replace_file_a";
let file_b = "test_mv_replace_file_b";
at.touch(file_a);
at.touch(file_b);
ucmd.arg(file_a)
.arg(file_b)
.arg("-i")
.arg("--update")
.succeeds()
.no_stdout()
.no_stderr();
}
#[test] #[test]
fn test_mv_no_clobber() { fn test_mv_no_clobber() {
let (at, mut ucmd) = at_and_ucmd!(); let (at, mut ucmd) = at_and_ucmd!();

View file

@ -373,6 +373,19 @@ fn test_format_selected_fields() {
.args(&["--from=auto", "--field", "1,4,3", "1K 2K 3K 4K 5K 6K"]) .args(&["--from=auto", "--field", "1,4,3", "1K 2K 3K 4K 5K 6K"])
.succeeds() .succeeds()
.stdout_only("1000 2K 3000 4000 5K 6K\n"); .stdout_only("1000 2K 3000 4000 5K 6K\n");
new_ucmd!()
.args(&["--from=auto", "--field", "1,4 3", "1K 2K 3K 4K 5K 6K"])
.succeeds()
.stdout_only("1000 2K 3000 4000 5K 6K\n");
}
#[test]
fn test_format_implied_range_and_field() {
new_ucmd!()
.args(&["--from=auto", "--field", "-2,4", "1K 2K 3K 4K 5K 6K"])
.succeeds()
.stdout_only("1000 2000 3K 4000 5K 6K\n");
} }
#[test] #[test]
@ -391,6 +404,18 @@ fn test_format_selected_field_range() {
.stdout_only("1K 2000 3000 4000 5000 6K\n"); .stdout_only("1K 2000 3000 4000 5000 6K\n");
} }
#[test]
fn test_format_all_fields() {
let all_fields_patterns = vec!["-", "-,3", "3,-", "1,-,3", "- 3"];
for pattern in all_fields_patterns {
new_ucmd!()
.args(&["--from=auto", "--field", pattern, "1K 2K 3K 4K 5K 6K"])
.succeeds()
.stdout_only("1000 2000 3000 4000 5000 6000\n");
}
}
#[test] #[test]
fn test_should_succeed_if_range_out_of_bounds() { fn test_should_succeed_if_range_out_of_bounds() {
new_ucmd!() new_ucmd!()
@ -530,7 +555,7 @@ fn test_round() {
new_ucmd!() new_ucmd!()
.args(&[ .args(&[
"--to=si", "--to=si",
&format!("--round={}", method), &format!("--round={method}"),
"--", "--",
"9001", "9001",
"-9001", "-9001",
@ -542,6 +567,32 @@ fn test_round() {
} }
} }
#[test]
fn test_round_with_to_unit() {
for (method, exp) in [
("from-zero", ["6", "-6", "5.9", "-5.9", "5.86", "-5.86"]),
("towards-zero", ["5", "-5", "5.8", "-5.8", "5.85", "-5.85"]),
("up", ["6", "-5", "5.9", "-5.8", "5.86", "-5.85"]),
("down", ["5", "-6", "5.8", "-5.9", "5.85", "-5.86"]),
("nearest", ["6", "-6", "5.9", "-5.9", "5.86", "-5.86"]),
] {
new_ucmd!()
.args(&[
"--to-unit=1024",
&format!("--round={method}"),
"--",
"6000",
"-6000",
"6000.0",
"-6000.0",
"6000.00",
"-6000.00",
])
.succeeds()
.stdout_only(exp.join("\n") + "\n");
}
}
#[test] #[test]
fn test_suffix_is_added_if_not_supplied() { fn test_suffix_is_added_if_not_supplied() {
new_ucmd!() new_ucmd!()

View file

@ -90,6 +90,35 @@ fn test_symlinked_default() {
env.ucmd.succeeds().stdout_is(env.subdir + "\n"); env.ucmd.succeeds().stdout_is(env.subdir + "\n");
} }
#[test]
fn test_symlinked_default_posix() {
let mut env = symlinked_env();
env.ucmd
.env("POSIXLY_CORRECT", "1")
.succeeds()
.stdout_is(env.symdir.clone() + "\n");
}
#[test]
fn test_symlinked_default_posix_l() {
let mut env = symlinked_env();
env.ucmd
.env("POSIXLY_CORRECT", "1")
.arg("-L")
.succeeds()
.stdout_is(env.symdir + "\n");
}
#[test]
fn test_symlinked_default_posix_p() {
let mut env = symlinked_env();
env.ucmd
.env("POSIXLY_CORRECT", "1")
.arg("-P")
.succeeds()
.stdout_is(env.symdir + "\n");
}
#[cfg(not(windows))] #[cfg(not(windows))]
pub mod untrustworthy_pwd_var { pub mod untrustworthy_pwd_var {
use std::path::Path; use std::path::Path;

View file

@ -400,6 +400,151 @@ fn test_rm_descend_directory() {
assert!(!at.file_exists(file_2)); assert!(!at.file_exists(file_2));
} }
#[cfg(feature = "chmod")]
#[test]
fn test_rm_prompts() {
use std::io::Write;
use std::process::Child;
// Needed for talking with stdin on platforms where CRLF or LF matters
const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
let mut answers = vec![
"rm: descend into directory 'a'?",
"rm: remove write-protected regular empty file 'a/empty-no-write'?",
"rm: remove symbolic link 'a/slink'?",
"rm: remove symbolic link 'a/slink-dot'?",
"rm: remove write-protected regular file 'a/f-no-write'?",
"rm: remove regular empty file 'a/empty'?",
"rm: remove directory 'a/b'?",
"rm: remove write-protected directory 'a/b-no-write'?",
"rm: remove directory 'a'?",
];
answers.sort();
let yes = format!("y{}", END_OF_LINE);
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
at.mkdir("a/");
let file_1 = "a/empty";
let file_2 = "a/empty-no-write";
let file_3 = "a/f-no-write";
at.touch(file_1);
at.touch(file_2);
at.make_file(file_3)
.write_all(b"not-empty")
.expect("Couldn't write to a/f-no-write");
at.symlink_dir("a/empty-f", "a/slink");
at.symlink_dir(".", "a/slink-dot");
let dir_1 = "a/b/";
let dir_2 = "a/b-no-write/";
at.mkdir(dir_1);
at.mkdir(dir_2);
scene
.ccmd("chmod")
.arg("u-w")
.arg(file_3)
.arg(dir_2)
.arg(file_2)
.succeeds();
let mut child: Child = scene.ucmd().arg("-ri").arg("a").run_no_wait();
let mut child_stdin = child.stdin.take().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
let output = child.wait_with_output().unwrap();
let mut trimmed_output = Vec::new();
for string in String::from_utf8(output.stderr)
.expect("Couldn't convert output.stderr to string")
.split("rm: ")
{
if !string.is_empty() {
let trimmed_string = format!("rm: {}", string).trim().to_string();
trimmed_output.push(trimmed_string);
}
}
trimmed_output.sort();
assert!(trimmed_output.len() == answers.len());
for (i, checking_string) in trimmed_output.iter().enumerate() {
assert!(checking_string == answers[i]);
}
assert!(!at.dir_exists("a"));
}
#[test]
fn test_rm_force_prompts_order() {
use std::io::Write;
use std::process::Child;
// Needed for talking with stdin on platforms where CRLF or LF matters
const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
let yes = format!("y{}", END_OF_LINE);
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;
let empty_file = "empty";
at.touch(empty_file);
// This should cause rm to prompt to remove regular empty file
let mut child: Child = scene.ucmd().arg("-fi").arg(empty_file).run_no_wait();
let mut child_stdin = child.stdin.take().unwrap();
child_stdin.write_all(yes.as_bytes()).unwrap();
child_stdin.flush().unwrap();
let output = child.wait_with_output().unwrap();
let string_output =
String::from_utf8(output.stderr).expect("Couldn't convert output.stderr to string");
assert!(string_output.trim() == "rm: remove regular empty file 'empty'?");
assert!(!at.file_exists(empty_file));
at.touch(empty_file);
// This should not cause rm to prompt to remove regular empty file
scene
.ucmd()
.arg("-if")
.arg(empty_file)
.succeeds()
.no_stderr();
assert!(!at.file_exists(empty_file));
}
#[test] #[test]
#[ignore = "issue #3722"] #[ignore = "issue #3722"]
fn test_rm_directory_rights_rm1() { fn test_rm_directory_rights_rm1() {

View file

@ -64,9 +64,9 @@ fn test_sync_no_permission_dir() {
ts.ccmd("chmod").arg("0").arg(dir).succeeds(); ts.ccmd("chmod").arg("0").arg(dir).succeeds();
let result = ts.ucmd().arg("--data").arg(dir).fails(); let result = ts.ucmd().arg("--data").arg(dir).fails();
result.stderr_contains("sync: error opening 'foo': Permission denied"); result.stderr_contains("sync: cannot stat 'foo': Permission denied");
let result = ts.ucmd().arg(dir).fails(); let result = ts.ucmd().arg(dir).fails();
result.stderr_contains("sync: error opening 'foo': Permission denied"); result.stderr_contains("sync: cannot stat 'foo': Permission denied");
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]

View file

@ -58,11 +58,11 @@ impl Distribution<u8> for AlphanumericNewline {
/// use rand::distributions::Alphanumeric; /// use rand::distributions::Alphanumeric;
/// ///
/// // generates a 100 byte string with characters from AlphanumericNewline /// // generates a 100 byte string with characters from AlphanumericNewline
/// let random_string = RandomString::generate(&AlphanumericNewline, 100); /// let random_string = RandomString::generate(AlphanumericNewline, 100);
/// assert_eq!(100, random_string.len()); /// assert_eq!(100, random_string.len());
/// ///
/// // generates a 100 byte string with 10 newline characters not ending with a newline /// // generates a 100 byte string with 10 newline characters not ending with a newline
/// let string = RandomString::generate_with_delimiter(&Alphanumeric, b'\n', 10, false, 100); /// let string = RandomString::generate_with_delimiter(Alphanumeric, b'\n', 10, false, 100);
/// assert_eq!(100, random_string.len()); /// assert_eq!(100, random_string.len());
/// ``` /// ```
pub struct RandomString; pub struct RandomString;
@ -108,7 +108,7 @@ impl RandomString {
/// use crate::common::random::{AlphanumericNewline, RandomString}; /// use crate::common::random::{AlphanumericNewline, RandomString};
/// ///
/// // generates a 100 byte string with 10 '\0' byte characters not ending with a '\0' byte /// // generates a 100 byte string with 10 '\0' byte characters not ending with a '\0' byte
/// let string = RandomString::generate_with_delimiter(&AlphanumericNewline, 0, 10, false, 100); /// let string = RandomString::generate_with_delimiter(AlphanumericNewline, 0, 10, false, 100);
/// assert_eq!(100, random_string.len()); /// assert_eq!(100, random_string.len());
/// assert_eq!( /// assert_eq!(
/// 10, /// 10,

View file

@ -218,6 +218,9 @@ sed -i -e "s/ginstall: creating directory/install: creating directory/g" tests/i
# disable this test case # disable this test case
sed -i -Ez "s/\n([^\n#]*pad-3\.2[^\n]*)\n([^\n]*)\n([^\n]*)/\n# uutils\/numfmt supports padding = LONG_MIN\n#\1\n#\2\n#\3/" tests/misc/numfmt.pl sed -i -Ez "s/\n([^\n#]*pad-3\.2[^\n]*)\n([^\n]*)\n([^\n]*)/\n# uutils\/numfmt supports padding = LONG_MIN\n#\1\n#\2\n#\3/" tests/misc/numfmt.pl
# Update the GNU error message to match the one generated by clap
sed -i -e "s/\$prog: multiple field specifications/error: The argument '--field <FIELDS>' was provided more than once, but cannot be used multiple times\n\nUsage: numfmt [OPTION]... [NUMBER]...\n\n\nFor more information try '--help'/g" tests/misc/numfmt.pl
# GNU doesn't support width > INT_MAX # GNU doesn't support width > INT_MAX
# disable these test cases # disable these test cases
sed -i -E "s|^([^#]*2_31.*)$|#\1|g" tests/misc/printf-cov.pl sed -i -E "s|^([^#]*2_31.*)$|#\1|g" tests/misc/printf-cov.pl