GH-73991: Add follow_symlinks argument to pathlib.Path.copy() (#120519)

Add support for not following symlinks in `pathlib.Path.copy()`.

On Windows we add the `COPY_FILE_COPY_SYMLINK` flag is following symlinks is disabled. If the source is symlink to a directory, this call will fail with `ERROR_ACCESS_DENIED`. In this case we add `COPY_FILE_DIRECTORY` to the flags and retry. This can fail on old Windowses, which we note in the docs.

No news as `copy()` was only just added.
This commit is contained in:
Barney Gale 2024-06-19 01:59:54 +01:00 committed by GitHub
parent 9f741e55c1
commit 20d5b84f57
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 86 additions and 11 deletions

View file

@ -790,14 +790,19 @@ class PathBase(PurePathBase):
"""
raise UnsupportedOperation(self._unsupported_msg('mkdir()'))
def copy(self, target):
def copy(self, target, follow_symlinks=True):
"""
Copy the contents of this file to the given target.
Copy the contents of this file to the given target. If this file is a
symlink and follow_symlinks is false, a symlink will be created at the
target.
"""
if not isinstance(target, PathBase):
target = self.with_segments(target)
if self._samefile_safe(target):
raise OSError(f"{self!r} and {target!r} are the same file")
if not follow_symlinks and self.is_symlink():
target.symlink_to(self.readlink())
return
with self.open('rb') as source_f:
try:
with target.open('wb') as target_f: