Skip to content
Open
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
18 changes: 14 additions & 4 deletions src/uu/cp/src/copydir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use walkdir::{DirEntry, WalkDir};
use crate::set_selinux_context;
use crate::{
CopyMode, CopyResult, CpError, Options, aligned_ancestors, copy_attributes, copy_file,
create_parent_dirs, print_verbose_output, set_parent_dirs_attributes,
create_parent_dirs, parents_destination, print_verbose_output, set_parent_dirs_attributes,
};

/// Represents a directory that needs permission fixup after copying its contents.
Expand Down Expand Up @@ -402,11 +402,14 @@ pub(crate) fn copy_directory(
// a -> d/a
// a/b -> d/a/b
//
let parents_dest = options.parents.then(|| target.join(root));
let parents_dest = options
.parents
.then(|| parents_destination(root, target))
.transpose()?;
let mut parent_dirs = Vec::new();
let mut copy_tree = || -> CopyResult<()> {
let tmp = match (parents_dest.as_ref(), root.parent()) {
(Some(parents_dest), Some(parent)) => {
(Some(parents_dest), Some(_)) => {
create_parent_dirs(root, parents_dest, options, &mut parent_dirs)?;
if root
.components()
Expand All @@ -426,7 +429,14 @@ pub(crate) fn copy_directory(
println!("{} -> {}", x.display(), y.display());
}
}
target.join(parent)
if ends_with_dot_component(root) {
// strip_prefix elides a trailing `/.`. Restore it so looking up
// `dest/dir/.` still requires `dest/dir` to be a directory and
// verbose paths retain the spelling of the source operand.
parents_dest.join(".")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why join(".")? is it only for the verbose output?

} else {
parents_dest.parent().unwrap_or(target).to_path_buf()
}
}
_ => target.to_path_buf(),
};
Expand Down
42 changes: 26 additions & 16 deletions src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1561,6 +1561,14 @@ pub fn copy(sources: &[PathBuf], target: &Path, options: &Options) -> CopyResult
}
}

/// Map a full source operand underneath the target for `--parents`.
fn parents_destination(source: &Path, target: &Path) -> CopyResult<PathBuf> {
// Strip the filesystem root, including any Windows drive or UNC prefix,
// before joining. For a relative path the prefix is empty.
let root = source.ancestors().last().unwrap_or(source);
localize_to_target(root, source, target)
}

fn construct_dest_path(
source_path: &Path,
target: &Path,
Expand All @@ -1580,23 +1588,13 @@ fn construct_dest_path(
}

Ok(match target_type {
TargetType::Directory if options.parents => parents_destination(source_path, target)?,
TargetType::Directory => {
let root = if options.parents {
if source_path.has_root() && cfg!(unix) {
Path::new("/")
} else {
Path::new("")
}
} else {
if source_path == Path::new(".") && target.is_dir() {
// Special case: when copying current directory (.) to an existing directory,
// return the target path directly instead of trying to construct a path
// relative to the source's parent. This ensures we copy the contents of
// the current directory into the target directory, not create a subdirectory.
return Ok(target.to_path_buf());
}
source_path.parent().unwrap_or(source_path)
};
if source_path == Path::new(".") && target.is_dir() {
// Copy the contents of the current directory into the target.
return Ok(target.to_path_buf());
}
let root = source_path.parent().unwrap_or(source_path);
localize_to_target(root, source_path, target)?
}
TargetType::File => target.to_path_buf(),
Expand Down Expand Up @@ -3358,6 +3356,18 @@ mod tests {
assert_eq!(actual, expected);
}

#[cfg(windows)]
#[test]
fn test_parents_destination_strips_windows_roots() {
let target = Path::new(r"D:\backup");
for source in [r"C:\dir\file", r"\\server\share\dir\file", r"\dir\file"] {
assert_eq!(
super::parents_destination(Path::new(source), target).unwrap(),
target.join(r"dir\file")
);
}
}

#[test]
fn test_aligned_ancestors() {
let actual = aligned_ancestors(Path::new("a/b/c"), Path::new("d/a/b/c"));
Expand Down
39 changes: 39 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4722,6 +4722,45 @@ fn test_cp_parents_2_deep_dir() {
assert!(at.dir_exists("d/e/a/b/c"));
}

#[test]
fn test_cp_parents_recursive_source_ending_in_dot() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("reports");
at.mkdir_all("backup/reports");
at.write("reports/ledger.csv", "current");
at.write("backup/reports/ledger.csv", "stale");
at.write("backup/ledger.csv", "summary");

ucmd.args(&["-R", "--parents", "reports/.", "backup"])
.succeeds();

assert_eq!(at.read("backup/ledger.csv"), "summary");
assert_eq!(at.read("backup/reports/ledger.csv"), "current");
}

#[cfg(unix)]
#[uutests::wasi_ignore(HostPathsNotVisible)]
#[rstest]
#[case::directory("")]
#[case::contents("/.")]
fn test_cp_parents_recursive_absolute_source(#[case] suffix: &str) {
let (at, mut ucmd) = at_and_ucmd!();
let reports = format!("{}/reports", at.root_dir_resolved());
let dest = format!("backup{reports}");
let ledger = format!("{dest}/ledger.csv");
at.mkdir("reports");
at.write("reports/ledger.csv", "current");
at.mkdir_all(&dest);
at.write(&ledger, "stale");
at.write("backup/ledger.csv", "summary");

ucmd.args(&["-R", "--parents", &format!("{reports}{suffix}"), "backup"])
.succeeds();

assert_eq!(at.read("backup/ledger.csv"), "summary");
assert_eq!(at.read(ledger), "current");
}

#[cfg(not(windows))]
#[test]
fn test_cp_parents_recursive_source_ending_in_parent_dir() {
Expand Down
Loading