From ee8a0c94779f4d136488b2d58f97557887ad71f2 Mon Sep 17 00:00:00 2001 From: Kangaxx-0 <85712372+Kangaxx-0@users.noreply.github.com> Date: Tue, 31 May 2022 16:24:33 -0700 Subject: [PATCH] Fix cp bug (#5642) --- crates/nu-command/src/filesystem/cp.rs | 19 ++++++++++++++++--- crates/nu-command/tests/commands/cp.rs | 13 +++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/nu-command/src/filesystem/cp.rs b/crates/nu-command/src/filesystem/cp.rs index 5ea92f7cb2..92b0b5c940 100644 --- a/crates/nu-command/src/filesystem/cp.rs +++ b/crates/nu-command/src/filesystem/cp.rs @@ -81,7 +81,6 @@ impl Command for Cp { let source = current_dir_path.join(src.item.as_str()); let destination = current_dir_path.join(dst.item.as_str()); - // check if destination is a dir and it exists let path_last_char = destination.as_os_str().to_string_lossy().chars().last(); let is_directory = path_last_char == Some('/') || path_last_char == Some('\\'); if is_directory && !destination.exists() { @@ -159,7 +158,22 @@ impl Command for Cp { for (src, dst) in sources { if src.is_file() { - let res = if interactive && dst.exists() { + let dst = + canonicalize_with(dst.as_path(), ¤t_dir_path).unwrap_or(dst); + let res = if src == dst { + let message = format!( + "src {:?} and dst {:?} are identical(not copied)", + source, destination + ); + + return Err(ShellError::GenericError( + "Copy aborted".into(), + message, + Some(span), + None, + Vec::new(), + )); + } else if interactive && dst.exists() { interactive_copy(interactive, src, dst, span, copy_file) } else { copy_file(src, dst, span) @@ -240,7 +254,6 @@ impl Command for Cp { ) })?; } - if s.is_symlink() && not_follow_symlink { let res = if interactive && d.exists() { interactive_copy(interactive, s, d, span, copy_symlink) diff --git a/crates/nu-command/tests/commands/cp.rs b/crates/nu-command/tests/commands/cp.rs index fc6c82b424..b12ec132d5 100644 --- a/crates/nu-command/tests/commands/cp.rs +++ b/crates/nu-command/tests/commands/cp.rs @@ -318,3 +318,16 @@ fn copy_dir_symlink_file_body_not_changed() { assert!(actual.contains("hello_data")); }); } + +#[test] +fn copy_identical_file() { + Playground::setup("cp_test_15", |_dirs, sandbox| { + sandbox.with_files(vec![EmptyFile("same.txt")]); + + let actual = nu!( + cwd: sandbox.cwd(), + "cp same.txt same.txt", + ); + assert!(actual.err.contains("Copy aborted")); + }); +}