diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index cec38b32a24..490d54353a5 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -2438,8 +2438,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { }); } - if !(settings.merge || settings.check) { - check_inputs(&files)?; + // Creating the output first could make a missing merge input appear to exist. + if !settings.check { + check_inputs(&files, settings.merge)?; } let output = Output::new(matches.get_one::(options::OUTPUT))?; @@ -3352,17 +3353,17 @@ fn print_sorted<'a, T: Iterator>>( Ok(()) } -/// Check that all inputs are readable before sorting starts, like GNU sort's -/// `check_inputs`. The inputs are probed with `access(2)` rather than opened: +/// Check named inputs before creating the output, like GNU sort's +/// `check_inputs`. Where available, probe with `access(2)` rather than opening: /// opening a FIFO here would block until a writer appears and lose data on the /// reopen, and keeping every input open would be bounded by `RLIMIT_NOFILE`. -fn check_inputs(files: &[OsString]) -> UResult<()> { +fn check_inputs(files: &[OsString], merge: bool) -> UResult<()> { for file in files { if file == STDIN_FILE { continue; } let path = Path::new(file); - check_readable(path).map_err(|error| SortError::ReadFailed { + check_readable(path, merge).map_err(|error| SortError::ReadFailed { path: path.to_owned(), error, })?; @@ -3371,16 +3372,20 @@ fn check_inputs(files: &[OsString]) -> UResult<()> { } #[cfg(all(unix, not(target_os = "redox")))] -fn check_readable(path: &Path) -> std::io::Result<()> { +fn check_readable(path: &Path, _merge: bool) -> std::io::Result<()> { use rustix::fs::{Access, access}; access(path, Access::READ_OK).map_err(|e| std::io::Error::from_raw_os_error(e.raw_os_error())) } #[cfg(any(not(unix), target_os = "redox"))] -fn check_readable(path: &Path) -> std::io::Result<()> { - // No `rustix::fs::access` here, so open the file and close it right away. - File::open(path)?; +fn check_readable(path: &Path, merge: bool) -> std::io::Result<()> { + if merge { + // Check existence without opening a stream twice. The merge opens it for reading. + path.metadata()?; + } else { + File::open(path)?; + } Ok(()) } diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 7f63dcec076..20c68dd41d8 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -2388,6 +2388,18 @@ fn test_output_is_input() { assert_eq!(at.read("file"), input); } +#[test] +fn test_merge_missing_input_is_output() { + let (at, mut ucmd) = at_and_ucmd!(); + at.write("today", "TX-1042\n"); + + ucmd.args(&["-mu", "-o", "ledger", "ledger", "today"]) + .fails_with_code(2) + .no_stdout() + .stderr_contains("cannot read: ledger"); + assert!(!at.file_exists("ledger")); +} + #[rstest] #[case::newline('\n', &[])] #[case::newline_unique('\n', &["-u"])]