Skip to content

Commit

Permalink
Merge pull request #3972 from jfinkels/cp-symbolic-link-loop
Browse files Browse the repository at this point in the history
cp: allow removing symbolic link loop destination
  • Loading branch information
sylvestre authored Oct 10, 2022
2 parents 46ceea0 + 349320a commit d205823
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1372,6 +1372,15 @@ fn handle_existing_dest(
Ok(())
}

/// Decide whether the given path exists.
fn file_or_link_exists(path: &Path) -> bool {
// Using `Path.exists()` or `Path.try_exists()` is not sufficient,
// because if `path` is a symbolic link and there are too many
// levels of symbolic link, then those methods will return false
// or an OS error.
path.symlink_metadata().is_ok()
}

/// Copy the a file from `source` to `dest`. `source` will be dereferenced if
/// `options.dereference` is set to true. `dest` will be dereferenced only if
/// the source was not a symlink.
Expand All @@ -1389,7 +1398,7 @@ fn copy_file(
symlinked_files: &mut HashSet<FileInformation>,
source_in_command_line: bool,
) -> CopyResult<()> {
if dest.exists() {
if file_or_link_exists(dest) {
handle_existing_dest(source, dest, options, source_in_command_line)?;
}

Expand Down
13 changes: 13 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2096,6 +2096,19 @@ fn test_cp_mode_hardlink_no_dereference() {
assert_eq!(at.read_symlink("z"), "slink");
}

#[test]
fn test_remove_destination_symbolic_link_loop() {
let (at, mut ucmd) = at_and_ucmd!();
at.symlink_file("loop", "loop");
at.plus("loop");
at.touch("f");
ucmd.args(&["--remove-destination", "f", "loop"])
.succeeds()
.no_stdout()
.no_stderr();
assert!(at.file_exists("loop"));
}

/// Test that copying a directory to itself is disallowed.
#[test]
fn test_copy_directory_to_itself_disallowed() {
Expand Down

0 comments on commit d205823

Please sign in to comment.