Skip to content

Commit

Permalink
Merge exists() and islink() checks.
Browse files Browse the repository at this point in the history
  • Loading branch information
serhiy-storchaka committed Dec 3, 2023
1 parent 9b0eb77 commit 05c626f
Showing 1 changed file with 12 additions and 18 deletions.
30 changes: 12 additions & 18 deletions Lib/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,17 +590,13 @@ def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
dirs_exist_ok=dirs_exist_ok)

if hasattr(os.stat_result, 'st_file_attributes'):
def _rmtree_islink(path):
try:
st = os.lstat(path)
return (stat.S_ISLNK(st.st_mode) or
(st.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
and st.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT))
except OSError:
return False
def _rmtree_islink(st):
return (stat.S_ISLNK(st.st_mode) or
(st.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
and st.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT))
else:
def _rmtree_islink(path):
return os.path.islink(path)
def _rmtree_islink(st):
return stat.S_ISLNK(st.st_mode)

# version vulnerable to race conditions
def _rmtree_unsafe(path, onexc):
Expand Down Expand Up @@ -808,20 +804,18 @@ def onexc(*args):
if dir_fd is not None:
raise NotImplementedError("dir_fd unavailable on this platform")
try:
if _rmtree_islink(path):
st = os.lstat(path)
except OSError as err:
onexc(os.lstat, path, err)
return
try:
if _rmtree_islink(st):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError as err:
onexc(os.path.islink, path, err)
# can't continue even if onexc hook returns
return
try:
if not os.path.exists(path):
raise FileNotFoundError(errno.ENOENT,
"Cannot call rmtree on a non-existent path", path)
except OSError as err:
onexc(os.path.exists, path, err)
return
return _rmtree_unsafe(path, onexc)

# Allow introspection of whether or not the hardening against symlink
Expand Down

0 comments on commit 05c626f

Please sign in to comment.