From b679c2a558cc259594a3548030315079242935d9 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Mon, 16 Nov 2026 22:41:09 +0800 Subject: [PATCH] Replace existing destinations when merging symbolic links --- newsfragments/263.bugfix.rst | 3 +++ path/__init__.py | 4 ++++ tests/test_path.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 newsfragments/263.bugfix.rst diff --git a/newsfragments/263.bugfix.rst b/newsfragments/263.bugfix.rst new file mode 100644 index 0000000..88d9b19 --- /dev/null +++ b/newsfragments/263.bugfix.rst @@ -0,0 +1,3 @@ +Allow repeated ``merge_tree(symlinks=True)`` calls to replace existing links, +files, and directories at a copied link's destination without following the +destination link. diff --git a/path/__init__.py b/path/__init__.py index 731e88e..66594d4 100644 --- a/path/__init__.py +++ b/path/__init__.py @@ -1660,6 +1660,10 @@ def ignored(item: Self) -> bool: dest = dst_path / source.name if symlinks and source.islink(): target = source.readlink() + if not dest.islink() and dest.is_dir(): + dest.rmtree() + else: + dest.remove_p() target.symlink(dest) elif source.is_dir(): source.merge_tree( diff --git a/tests/test_path.py b/tests/test_path.py index 55d733c..3662bfc 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -918,6 +918,41 @@ def test_with_nonexisting_dst_args(self): assert set(self.subdir_b.iterdir()) == expected self.check_link() + @pytest.mark.parametrize('existing', ['link', 'dangling', 'file', 'directory']) + def test_replace_existing_link_destination(self, existing): + dest = self.subdir_b / self.test_link.name + old_target = self.test_dir / 'old-target' + old_target.mkdir() + sentinel = old_target / 'keep.txt' + sentinel.write_text('keep', encoding='utf-8') + if existing == 'link': + dest.symlink_to(old_target, target_is_directory=True) + elif existing == 'dangling': + (self.test_dir / 'missing').symlink(dest) + elif existing == 'file': + dest.write_text('old', encoding='utf-8') + else: + dest.mkdir() + (dest / 'old.txt').write_text('old', encoding='utf-8') + + self.subdir_a.merge_tree(self.subdir_b, symlinks=True) + + assert dest.islink() + assert dest.readlink() == self.test_file + assert sentinel.read_text(encoding='utf-8') == 'keep' + + def test_repeated_merge_with_changed_link_target(self): + self.subdir_a.merge_tree(self.subdir_b, symlinks=True) + self.subdir_a.merge_tree(self.subdir_b, symlinks=True) + self.test_link.remove() + Path('relative-missing-target').symlink(self.test_link) + + self.subdir_a.merge_tree(self.subdir_b, symlinks=True) + + dest = self.subdir_b / self.test_link.name + assert dest.islink() + assert dest.readlink() == 'relative-missing-target' + def test_with_existing_dst(self): self.subdir_b.rmtree() self.subdir_a.copytree(self.subdir_b, True)