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

Merge branch 'main' into refactor/add_nix_error_auto_conversion

This commit is contained in:
Sylvestre Ledru 2022-11-04 12:54:35 +01:00 committed by GitHub
commit 6bc68cdcdf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 385 additions and 88 deletions

View file

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

View file

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

21
Cargo.lock generated
View file

@ -100,9 +100,9 @@ dependencies = [
[[package]]
name = "binary-heap-plus"
version = "0.4.1"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f068638f8ff9e118a9361e66a411eff410e7fb3ecaa23bf9272324f8fc606d7"
checksum = "e4551d8382e911ecc0d0f0ffb602777988669be09447d536ff4388d1def11296"
dependencies = [
"compare",
]
@ -190,10 +190,11 @@ checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d"
[[package]]
name = "byte-unit"
version = "4.0.14"
version = "4.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95ebf10dda65f19ff0f42ea15572a359ed60d7fc74fdc984d90310937be0014b"
checksum = "581ad4b3d627b0c09a0ccb2912148f839acaca0b93cf54cbe42b6c674e86079c"
dependencies = [
"serde",
"utf8-width",
]
@ -285,9 +286,9 @@ dependencies = [
[[package]]
name = "clap_complete"
version = "4.0.2"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11cba7abac9b56dfe2f035098cdb3a43946f276e6db83b72c4e692343f9aab9a"
checksum = "dfe581a2035db4174cdbdc91265e1aba50f381577f0510d0ad36c7bc59cc84a3"
dependencies = [
"clap 4.0.18",
]
@ -1342,9 +1343,9 @@ dependencies = [
[[package]]
name = "num_cpus"
version = "1.13.1"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5"
dependencies = [
"hermit-abi",
"libc",
@ -2358,7 +2359,6 @@ name = "uu_dir"
version = "0.0.16"
dependencies = [
"clap 4.0.18",
"selinux",
"uu_ls",
"uucore",
]
@ -2368,7 +2368,6 @@ name = "uu_dircolors"
version = "0.0.16"
dependencies = [
"clap 4.0.18",
"glob",
"uucore",
]
@ -2818,6 +2817,7 @@ name = "uu_rm"
version = "0.0.16"
dependencies = [
"clap 4.0.18",
"libc",
"remove_dir_all 0.7.0",
"uucore",
"walkdir",
@ -3135,7 +3135,6 @@ name = "uu_vdir"
version = "0.0.16"
dependencies = [
"clap 4.0.18",
"selinux",
"uu_ls",
"uucore",
]

View file

@ -1270,10 +1270,6 @@ fn copy_file(
return Ok(());
}
if file_or_link_exists(dest) {
handle_existing_dest(source, dest, options, source_in_command_line)?;
}
// Fail if dest is a dangling symlink or a symlink this program created previously
if dest.is_symlink() {
if FileInformation::from_path(dest, false)
@ -1287,7 +1283,13 @@ fn copy_file(
)));
}
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!(
"not writing through dangling symlink '{}'",
dest.display()
@ -1295,6 +1297,10 @@ fn copy_file(
}
}
if file_or_link_exists(dest) {
handle_existing_dest(source, dest, options, source_in_command_line)?;
}
if options.verbose {
println!("{}", context_for(source, dest));
}

View file

@ -17,7 +17,6 @@ path = "src/dir.rs"
[dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] }
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"}
[[bin]]

View file

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

View file

@ -440,6 +440,9 @@ pub fn uu_app() -> Command {
may contain slashes, but mktemp creates only the final component",
)
.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),
)
.arg(

View file

@ -475,11 +475,11 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> {
{
if path_symlink_points_to.exists() {
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 {
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 {
return Err(io::Error::new(
io::ErrorKind::NotFound,

View file

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

View file

@ -158,12 +158,15 @@ fn parse_options(args: &ArgMatches) -> Result<NumfmtOptions> {
Ok(0)
}?;
let fields = match args.get_one::<String>(options::FIELD).unwrap().as_str() {
"-" => vec![Range {
let fields = args.get_one::<String>(options::FIELD).unwrap().as_str();
// 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,
high: std::usize::MAX,
}],
v => Range::from_list(v)?,
}]
} else {
Range::from_list(fields)?
};
let format = match args.get_one::<String>(options::FORMAT) {

View file

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

View file

@ -10,13 +10,11 @@
#[macro_use]
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 std::collections::VecDeque;
use std::fs;
use std::fs::File;
use std::io::ErrorKind;
use std::io::{stderr, stdin, BufRead, Write};
use std::fs::{self, File, Metadata};
use std::io::{stderr, stdin, BufRead, ErrorKind, Write};
use std::ops::BitOr;
use std::path::{Path, PathBuf};
use uucore::display::Quotable;
@ -87,17 +85,30 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|v| v.map(ToString::to_string).collect())
.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
// Because "rm -f" is a thing
return Err(UUsageError::new(1, "missing operand"));
} else {
let options = Options {
force,
force: force_flag,
interactive: {
if matches.get_flag(OPT_PROMPT) {
if force_prompt_never {
InteractiveMode::Never
} else if matches.get_flag(OPT_PROMPT) {
InteractiveMode::Always
} else if matches.get_flag(OPT_PROMPT_MORE) {
InteractiveMode::Once
@ -159,12 +170,17 @@ pub fn uu_app() -> Command {
Arg::new(OPT_PROMPT)
.short('i')
.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),
)
.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::new(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, \
prompts always",
)
.value_name("WHEN"),
.value_name("WHEN")
.overrides_with_all([OPT_PROMPT, OPT_PROMPT_MORE]),
)
.arg(
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 {
let response = if options.interactive == InteractiveMode::Always {
prompt_file(path, true)
} else {
true
};
if response {
if prompt_file(path, options, true) {
if let Ok(mut read_dir) = fs::read_dir(path) {
if options.dir || options.recursive {
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 {
let response = if options.interactive == InteractiveMode::Always {
prompt_file(path, false)
} else {
true
};
if response && prompt_write_protected(path, false, options) {
if prompt_file(path, options, false) {
match fs::remove_file(path) {
Ok(_) => {
if options.verbose {
@ -438,46 +445,138 @@ fn remove_file(path: &Path, options: &Options) -> bool {
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 {
return true;
}
match File::open(path) {
Ok(_) => true,
Err(err) => {
if err.kind() == ErrorKind::PermissionDenied {
if is_dir {
prompt(&(format!("rm: remove write-protected directory {}? ", path.quote())))
} else {
if fs::metadata(path).unwrap().len() == 0 {
return prompt(
&(format!(
"rm: remove write-protected regular empty file {}? ",
path.quote()
)),
);
// If interactive is Always we want to check if the file is symlink to prompt the right message
if options.interactive == InteractiveMode::Always {
if let Ok(metadata) = fs::symlink_metadata(path) {
if metadata.is_symlink() {
return prompt(&(format!("remove symbolic link {}? ", path.quote())));
}
}
}
if is_dir {
// We can't use metadata.permissions.readonly for directories because it only works on files
// So we have to handle wether a directory is writable on not manually
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 {
prompt(&(format!("rm: descend into directory {}? ", path.quote())))
// 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
// 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 {
if is_dir {
prompt(&(format!("rm: remove directory {}? ", path.quote())))
// For windows we can use windows metadata trait and file attributes to see if a directory is readonly
#[cfg(windows)]
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 {
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 {
// 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
@ -487,7 +586,7 @@ fn normalize(path: &Path) -> PathBuf {
}
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 mut buf = Vec::new();
@ -501,15 +600,13 @@ fn prompt(msg: &str) -> bool {
}
#[cfg(not(windows))]
fn is_symlink_dir(_metadata: &fs::Metadata) -> bool {
fn is_symlink_dir(_metadata: &Metadata) -> bool {
false
}
#[cfg(windows)]
use std::os::windows::prelude::MetadataExt;
#[cfg(windows)]
fn is_symlink_dir(metadata: &fs::Metadata) -> bool {
fn is_symlink_dir(metadata: &Metadata) -> bool {
use std::os::windows::prelude::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY;
metadata.file_type().is_symlink()

View file

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

View file

@ -17,7 +17,6 @@ path = "src/vdir.rs"
[dependencies]
clap = { version = "4.0", features = ["wrap_help", "cargo", "env"] }
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"}
[[bin]]

View file

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

View file

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

View file

@ -1839,6 +1839,19 @@ fn test_copy_through_dangling_symlink_no_dereference_2() {
.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]
#[cfg(unix)]
fn test_cp_archive_on_nonexistent_file() {

View file

@ -220,7 +220,7 @@ fn test_change_directory() {
let out = scene
.ucmd()
.arg("--chdir")
.arg(&temporary_path)
.arg(temporary_path)
.args(&pwd)
.succeeds()
.stdout_move_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

@ -373,6 +373,11 @@ fn test_format_selected_fields() {
.args(&["--from=auto", "--field", "1,4,3", "1K 2K 3K 4K 5K 6K"])
.succeeds()
.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]
@ -399,6 +404,18 @@ fn test_format_selected_field_range() {
.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]
fn test_should_succeed_if_range_out_of_bounds() {
new_ucmd!()

View file

@ -400,6 +400,151 @@ fn test_rm_descend_directory() {
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]
#[ignore = "issue #3722"]
fn test_rm_directory_rights_rm1() {

View file

@ -218,6 +218,9 @@ sed -i -e "s/ginstall: creating directory/install: creating directory/g" tests/i
# 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
# 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
# disable these test cases
sed -i -E "s|^([^#]*2_31.*)$|#\1|g" tests/misc/printf-cov.pl