|
4 | 4 | import random
|
5 | 5 | import sys
|
6 | 6 | from contextlib import contextmanager
|
| 7 | +from pathlib import Path |
7 | 8 | from tempfile import NamedTemporaryFile
|
8 | 9 | from typing import Any, BinaryIO, Generator, List, Union, cast
|
9 | 10 |
|
10 | 11 | from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
|
11 | 12 |
|
| 13 | +from pip._internal.exceptions import PipError |
12 | 14 | from pip._internal.utils.compat import get_path_uid
|
13 | 15 | from pip._internal.utils.misc import format_size
|
14 | 16 |
|
@@ -151,3 +153,53 @@ def directory_size(path: str) -> Union[int, float]:
|
151 | 153 |
|
152 | 154 | def format_directory_size(path: str) -> str:
|
153 | 155 | return format_size(directory_size(path))
|
| 156 | + |
| 157 | + |
| 158 | +def _leaf_subdirs(path: Path) -> Generator[Path, None, None]: |
| 159 | + """Traverses the file tree, finding every empty directory.""" |
| 160 | + |
| 161 | + path_obj = Path(path) |
| 162 | + |
| 163 | + if not path_obj.exists(): |
| 164 | + return |
| 165 | + |
| 166 | + for item in path_obj.iterdir(): |
| 167 | + if not item.is_dir(): |
| 168 | + continue |
| 169 | + |
| 170 | + subitems = item.iterdir() |
| 171 | + |
| 172 | + # ASSUMPTION: Nothing in subitems will be None or False. |
| 173 | + if not any(subitems): |
| 174 | + yield item |
| 175 | + |
| 176 | + if not any(subitem.is_file() for subitem in subitems): |
| 177 | + yield from _leaf_subdirs(item) |
| 178 | + |
| 179 | + |
| 180 | +def _leaf_parents_without_files(path: Path, leaf: Path) -> Generator[str, None, None]: |
| 181 | + """Yields +leaf+ and each parent directory below +path+, until one of |
| 182 | + them includes a file (as opposed to directories or nothing).""" |
| 183 | + |
| 184 | + if not str(leaf).startswith(str(path)): |
| 185 | + # If +leaf+ is not a subdirectory of +path+, bail early to avoid |
| 186 | + # an endless loop. |
| 187 | + raise PipError("leaf is not a subdirectory of path") |
| 188 | + |
| 189 | + path = Path(path) |
| 190 | + leaf = Path(leaf) |
| 191 | + while leaf != path: |
| 192 | + if all(item.is_dir() for item in leaf.iterdir()): |
| 193 | + yield str(leaf) |
| 194 | + else: |
| 195 | + break |
| 196 | + leaf = leaf.parent |
| 197 | + |
| 198 | + |
| 199 | +def subdirs_with_no_files(path_str: str) -> Generator[str, None, None]: |
| 200 | + """Yields every subdirectory of +path_str+ that has no files under it.""" |
| 201 | + |
| 202 | + path = Path(path_str) |
| 203 | + |
| 204 | + for leaf in _leaf_subdirs(path): |
| 205 | + yield from _leaf_parents_without_files(path, leaf) |
0 commit comments