Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't panic when calling cp -a with a nonexistent file #2960

Merged
merged 2 commits into from
Jan 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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) =
Expand Down Expand Up @@ -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(),
Expand Down
15 changes: 15 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ static TEST_MOUNT_COPY_FROM_FOLDER: &str = "dir_with_mount";
static TEST_MOUNT_MOUNTPOINT: &str = "mount";
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
static TEST_MOUNT_OTHER_FILESYSTEM_FILE: &str = "mount/DO_NOT_copy_me.txt";
#[cfg(unix)]
static TEST_NONEXISTENT_FILE: &str = "nonexistent_file.txt";

#[test]
fn test_cp_cp() {
Expand Down Expand Up @@ -1429,3 +1431,16 @@ 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)",
);
}