GH-73991: Rework pathlib.Path.copytree() into copy() (#122369)

Rename `pathlib.Path.copy()` to `_copy_file()` (i.e. make it private.)

Rename `pathlib.Path.copytree()` to `copy()`, and add support for copying
non-directories. This simplifies the interface for users, and nicely
complements the upcoming `move()` and `delete()` methods (which will also
accept any type of file.)

Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
This commit is contained in:
Barney Gale 2024-08-11 22:43:18 +01:00 committed by GitHub
parent ea70439bd2
commit a6644d4464
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 141 additions and 197 deletions

View file

@ -18,9 +18,9 @@ try:
except ImportError:
grp = None
from ._os import (UnsupportedOperation, copyfile, file_metadata_keys,
read_file_metadata, write_file_metadata)
from ._abc import PurePathBase, PathBase
from pathlib._os import (copyfile, file_metadata_keys, read_file_metadata,
write_file_metadata)
from pathlib._abc import UnsupportedOperation, PurePathBase, PathBase
__all__ = [
@ -788,25 +788,18 @@ class Path(PathBase, PurePath):
_write_metadata = write_file_metadata
if copyfile:
def copy(self, target, *, follow_symlinks=True, preserve_metadata=False):
def _copy_file(self, 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.
Copy the contents of this file to the given target.
"""
try:
target = os.fspath(target)
except TypeError:
if not isinstance(target, PathBase):
raise
PathBase._copy_file(self, target)
else:
try:
copyfile(os.fspath(self), target, follow_symlinks)
return
except UnsupportedOperation:
pass # Fall through to generic code.
PathBase.copy(self, target, follow_symlinks=follow_symlinks,
preserve_metadata=preserve_metadata)
copyfile(os.fspath(self), target)
def chmod(self, mode, *, follow_symlinks=True):
"""
@ -894,6 +887,14 @@ class Path(PathBase, PurePath):
"""
os.symlink(target, self, target_is_directory)
if os.name == 'nt':
def _symlink_to_target_of(self, link):
"""
Make this path a symlink with the same target as the given link.
This is used by copy().
"""
self.symlink_to(link.readlink(), link.is_dir())
if hasattr(os, "link"):
def hardlink_to(self, target):
"""