|
6 | 6 | import stat
|
7 | 7 | import sys
|
8 | 8 | from contextlib import contextmanager
|
| 9 | +from pathlib import Path |
9 | 10 | from tempfile import NamedTemporaryFile
|
10 | 11 | from typing import Any, BinaryIO, Iterator, List, Union, cast
|
11 | 12 |
|
12 | 13 | from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
|
13 | 14 |
|
| 15 | +from pip._internal.exceptions import PipError |
14 | 16 | from pip._internal.utils.compat import get_path_uid
|
15 | 17 | from pip._internal.utils.misc import format_size
|
16 | 18 |
|
@@ -180,3 +182,50 @@ def directory_size(path: str) -> Union[int, float]:
|
180 | 182 |
|
181 | 183 | def format_directory_size(path: str) -> str:
|
182 | 184 | return format_size(directory_size(path))
|
| 185 | + |
| 186 | + |
| 187 | +def _leaf_subdirs(path): |
| 188 | + """Traverses the file tree, finding every empty directory.""" |
| 189 | + |
| 190 | + path_obj = Path(path) |
| 191 | + |
| 192 | + if not path_obj.exists(): |
| 193 | + return |
| 194 | + |
| 195 | + for item in path_obj.iterdir(): |
| 196 | + if not item.is_dir(): |
| 197 | + continue |
| 198 | + |
| 199 | + subitems = item.iterdir() |
| 200 | + |
| 201 | + # ASSUMPTION: Nothing in subitems will be None or False. |
| 202 | + if not any(subitems): |
| 203 | + yield item |
| 204 | + |
| 205 | + if not any(subitem.is_file() for subitem in subitems): |
| 206 | + yield from _leaf_subdirs(item) |
| 207 | + |
| 208 | + |
| 209 | +def _leaf_parents_without_files(path, leaf): |
| 210 | + """Yields +leaf+ and each parent directory below +path+, until one of |
| 211 | + them includes a file (as opposed to directories or nothing).""" |
| 212 | + |
| 213 | + if not str(leaf).startswith(str(path)): |
| 214 | + # If +leaf+ is not a subdirectory of +path+, bail early to avoid |
| 215 | + # an endless loop. |
| 216 | + raise PipError("leaf is not a subdirectory of path") |
| 217 | + |
| 218 | + path = Path(path) |
| 219 | + leaf = Path(leaf) |
| 220 | + while leaf != path: |
| 221 | + if all(item.is_dir() for item in leaf.iterdir()): |
| 222 | + yield str(leaf) |
| 223 | + else: |
| 224 | + break |
| 225 | + leaf = leaf.parent |
| 226 | + |
| 227 | + |
| 228 | +def subdirs_with_no_files(path): |
| 229 | + """Yields every subdirectory of +path+ that has no files under it.""" |
| 230 | + for leaf in _leaf_subdirs(path): |
| 231 | + yield from _leaf_parents_without_files(path, leaf) |
0 commit comments