File size: 10,187 Bytes
71687cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Disk utility functions for deleting files and folders."""
from __future__ import annotations
import fnmatch
import os
import shutil
import sys
from logging import getLogger
from os.path import (
abspath,
basename,
dirname,
exists,
isdir,
isfile,
join,
normpath,
split,
)
from subprocess import STDOUT, CalledProcessError, check_output
from ...base.constants import CONDA_TEMP_EXTENSION
from ...base.context import context
from ...common.compat import on_win
from ...common.constants import TRACE
from . import MAX_TRIES
from .link import islink, lexists
from .permissions import make_writable
if not on_win:
from shutil import which
log = getLogger(__name__)
def rmtree(path):
# subprocessing to delete large folders can be quite a bit faster
path = normpath(path)
if on_win:
try:
# the fastest way seems to be using DEL to recursively delete files
# https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/
# However, this is not entirely safe, as it can end up following symlinks to folders
# https://superuser.com/a/306618/184799
# so, we stick with the slower, but hopefully safer way. Maybe if we figured out how
# to scan for any possible symlinks, we could do the faster way.
# out = check_output('DEL /F/Q/S *.* > NUL 2> NUL'.format(path), shell=True,
# stderr=STDOUT, cwd=path)
out = check_output(
f'RD /S /Q "{path}" > NUL 2> NUL', shell=True, stderr=STDOUT
)
except:
try:
# Try to delete in Unicode
name = None
from ...auxlib.compat import Utf8NamedTemporaryFile
from ...utils import quote_for_shell
with Utf8NamedTemporaryFile(
mode="w", suffix=".bat", delete=False
) as batch_file:
batch_file.write(f"RD /S {quote_for_shell(path)}\n")
batch_file.write("chcp 65001\n")
batch_file.write(f"RD /S {quote_for_shell(path)}\n")
batch_file.write("EXIT 0\n")
name = batch_file.name
# If the above is bugged we can end up deleting hard-drives, so we check
# that 'path' appears in it. This is not bulletproof but it could save you (me).
with open(name) as contents:
content = contents.read()
if path not in content:
raise RuntimeError(f"Path {path} not listed in file {name}")
comspec = os.getenv("COMSPEC")
CREATE_NO_WINDOW = 0x08000000
# It is essential that we `pass stdout=None, stderr=None, stdin=None` here because
# if we do not, then the standard console handles get attached and chcp affects the
# parent process (and any which share those console handles!)
out = check_output(
[comspec, "/d", "/c", name],
shell=False,
stdout=None,
stderr=None,
stdin=None,
creationflags=CREATE_NO_WINDOW,
)
except CalledProcessError as e:
if e.returncode != 5:
log.error(
f"Removing folder {name} the fast way failed. Output was: {out}"
)
raise
else:
log.debug(
f"removing dir contents the fast way failed. Output was: {out}"
)
else:
try:
os.makedirs(".empty")
except:
pass
# yes, this looks strange. See
# https://unix.stackexchange.com/a/79656/34459
# https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html
if isdir(".empty"):
rsync = which("rsync")
if rsync:
try:
out = check_output(
[
rsync,
"-a",
"--force",
"--delete",
join(os.getcwd(), ".empty") + "/",
path + "/",
],
stderr=STDOUT,
)
except CalledProcessError:
log.debug(
f"removing dir contents the fast way failed. Output was: {out}"
)
shutil.rmtree(".empty")
shutil.rmtree(path)
def unlink_or_rename_to_trash(path):
"""If files are in use, especially on windows, we can't remove them.
The fallback path is to rename them (but keep their folder the same),
which maintains the file handle validity. See comments at:
https://serverfault.com/a/503769
"""
try:
make_writable(path)
os.unlink(path)
except OSError:
try:
os.rename(path, path + ".conda_trash")
except OSError:
if on_win:
# on windows, it is important to use the rename program, as just using python's
# rename leads to permission errors when files are in use.
condabin_dir = join(context.conda_prefix, "condabin")
trash_script = join(condabin_dir, "rename_tmp.bat")
if exists(trash_script):
_dirname, _fn = split(path)
dest_fn = path + ".conda_trash"
counter = 1
while isfile(dest_fn):
dest_fn = dest_fn.splitext[0] + f".conda_trash_{counter}"
counter += 1
out = "< empty >"
try:
out = check_output(
[
"cmd.exe",
"/C",
trash_script,
_dirname,
_fn,
basename(dest_fn),
],
stderr=STDOUT,
)
except CalledProcessError:
log.debug(
f"renaming file path {path} to trash failed. Output was: {out}"
)
else:
log.debug(
f"{trash_script} is missing. Conda was not installed correctly or has been "
"corrupted. Please file an issue on the conda github repo."
)
log.warning(
f"Could not remove or rename {path}. Please remove this file manually (you "
"may need to reboot to free file handles)"
)
def remove_empty_parent_paths(path):
# recurse to clean up empty folders that were created to have a nested hierarchy
parent_path = dirname(path)
while isdir(parent_path) and not next(os.scandir(parent_path), None):
os.rmdir(parent_path)
parent_path = dirname(parent_path)
def rm_rf(path: str | os.PathLike, clean_empty_parents: bool = False) -> bool:
"""
Completely delete path
max_retries is the number of times to retry on failure. The default is 5. This only applies
to deleting a directory.
If removing path fails and trash is True, files will be moved to the trash directory.
"""
path = abspath(path)
log.log(TRACE, "rm_rf %s", path)
# attempt to delete the path
if isdir(path) and not islink(path):
backoff_rmdir(path)
elif lexists(path):
unlink_or_rename_to_trash(path)
else:
log.log(TRACE, "rm_rf failed. Not a link, file, or directory: %s", path)
# post-processing to clean up trash and empty parent paths
if isdir(path) and not islink(path):
delete_trash(path)
if clean_empty_parents:
remove_empty_parent_paths(path)
if lexists(path):
log.info("rm_rf failed for %s", path)
return False
return True
def delete_trash(prefix):
if not prefix:
prefix = sys.prefix
exclude = {"envs", "pkgs"}
for root, dirs, files in os.walk(prefix, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
for fn in files:
if fnmatch.fnmatch(fn, "*.conda_trash*") or fnmatch.fnmatch(
fn, "*" + CONDA_TEMP_EXTENSION
):
filename = join(root, fn)
try:
os.unlink(filename)
remove_empty_parent_paths(filename)
except OSError as e:
log.debug("%r errno %d\nCannot unlink %s.", e, e.errno, filename)
def backoff_rmdir(dirpath, max_tries=MAX_TRIES):
if not isdir(dirpath):
return
try:
rmtree(dirpath)
except:
# we don't really care about errors that much. We'll catch remaining files
# with slower python logic.
pass
for root, dirs, files in os.walk(dirpath, topdown=False):
for file in files:
unlink_or_rename_to_trash(join(root, file))
def path_is_clean(path):
"""Sometimes we can't completely remove a path because files are considered in use
by python (hardlinking confusion). For our tests, it is sufficient that either the
folder doesn't exist, or nothing but temporary file copies are left.
"""
clean = not exists(path)
if not clean:
for root, dirs, fns in os.walk(path):
for fn in fns:
if not (
fnmatch.fnmatch(fn, "*.conda_trash*")
or fnmatch.fnmatch(fn, "*" + CONDA_TEMP_EXTENSION)
):
return False
return True
|