From 680e9081fe69d397a3ae7525231beefdd38fd12c Mon Sep 17 00:00:00 2001 From: Eli Youngs Date: Sat, 29 Jan 2022 22:59:53 -0800 Subject: [PATCH] Don't panic when calling cp -a with a nonexistent file --- src/uu/cp/src/cp.rs | 8 ++++---- tests/by-util/test_cp.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 8741646a3..d005bd718 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -768,8 +768,8 @@ fn preserve_hardlinks( let mut stat = mem::zeroed(); if libc::lstat(src_path.as_ptr(), &mut stat) < 0 { return Err(format!( - "cannot stat {:?}: {}", - src_path, + "cannot stat {}: {}", + source.quote(), std::io::Error::last_os_error() ) .into()); @@ -849,7 +849,7 @@ fn copy(sources: &[Source], target: &TargetSlice, options: &Options) -> CopyResu let mut found_hard_link = false; if preserve_hard_links { let dest = construct_dest_path(source, target, &target_type, options)?; - preserve_hardlinks(&mut hard_links, source, dest, &mut found_hard_link).unwrap(); + preserve_hardlinks(&mut hard_links, source, dest, &mut found_hard_link)?; } if !found_hard_link { if let Err(error) = @@ -1031,7 +1031,7 @@ fn copy_directory( let mut found_hard_link = false; let source = path.to_path_buf(); let dest = local_to_target.as_path().to_path_buf(); - preserve_hardlinks(&mut hard_links, &source, dest, &mut found_hard_link).unwrap(); + preserve_hardlinks(&mut hard_links, &source, dest, &mut found_hard_link)?; if !found_hard_link { match copy_file( path.as_path(), diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index 07597cf15..76f62d5e1 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -26,6 +26,7 @@ use std::thread::sleep; use std::time::Duration; static TEST_EXISTING_FILE: &str = "existing_file.txt"; +static TEST_NONEXISTENT_FILE: &str = "nonexistent_file.txt"; static TEST_HELLO_WORLD_SOURCE: &str = "hello_world.txt"; static TEST_HELLO_WORLD_SOURCE_SYMLINK: &str = "hello_world.txt.link"; static TEST_HELLO_WORLD_DEST: &str = "copy_of_hello_world.txt"; @@ -1429,3 +1430,14 @@ fn test_copy_through_dangling_symlink() { .fails() .stderr_only("cp: not writing through dangling symlink 'target'"); } + +#[test] +#[cfg(unix)] +fn test_cp_archive_on_nonexistent_file() { + new_ucmd!() + .arg("-a") + .arg(TEST_NONEXISTENT_FILE) + .arg(TEST_EXISTING_FILE) + .fails() + .stderr_only("cp: cannot stat 'nonexistent_file.txt': No such file or directory (os error 2)"); +}