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
3 changes: 2 additions & 1 deletion Lib/pathlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1303,7 +1303,8 @@ def copy(self, target, **kwargs):
if not hasattr(target, 'with_segments'):
target = self.with_segments(target)
ensure_distinct_paths(self, target)
target._copy_from(self, **kwargs)
# Use fresh paths to avoid stale cached file information.
target.joinpath()._copy_from(self.joinpath(), **kwargs)
return target.joinpath() # Empty join to ensure fresh metadata.

def copy_into(self, target_dir, **kwargs):
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_pathlib/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,34 @@ def test_copy_file_preserve_metadata(self):
if hasattr(source_st, 'st_flags'):
self.assertEqual(source_st.st_flags, target_st.st_flags)

@os_helper.skip_unless_hardlink
def test_copy_file_to_hardlink_with_stale_info(self):
base = self.cls(self.base)
source = base / 'fileA'
target = base / 'copyA'
source.write_bytes(b'original data')
target.write_bytes(b'old backup')
target.info.is_file()
target.unlink()
target.hardlink_to(source)
self.assertTrue(source.samefile(target))
self.assertRaises(OSError, source.copy, target)
self.assertEqual(source.read_bytes(), b'original data')

@os_helper.skip_unless_hardlink
def test_copy_file_from_hardlink_with_stale_info(self):
base = self.cls(self.base)
source = base / 'fileA'
target = base / 'copyA'
target.write_bytes(b'original data')
source.write_bytes(b'old backup')
source.info.is_file()
source.unlink()
source.hardlink_to(target)
self.assertTrue(source.samefile(target))
self.assertRaises(OSError, source.copy, target)
self.assertEqual(target.read_bytes(), b'original data')

@needs_symlinks
def test_copy_file_to_existing_symlink(self):
base = self.cls(self.base)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :meth:`pathlib.Path.copy` to correctly detect when the source and target
refer to the same file, even when cached path information is stale.
Previously, copying between hard links to the same file could empty the
source file and lose its data without raising an error.
Loading