| 1 |
"""Interface for accessing the file system with automatic caching. |
| 2 |
|
| 3 |
The idea is to cache the results of any file system state reads during |
| 4 |
a single transaction. This has two main benefits: |
| 5 |
|
| 6 |
* This avoids redundant syscalls, as we won't perform the same OS |
| 7 |
operations multiple times. |
| 8 |
|
| 9 |
* This makes it easier to reason about concurrent FS updates, as different |
| 10 |
operations targeting the same paths can't report different state during |
| 11 |
a transaction. |
| 12 |
|
| 13 |
Note that this only deals with reading state, not writing. |
| 14 |
|
| 15 |
Properties maintained by the API: |
| 16 |
|
| 17 |
* The contents of the file are always from the same or later time compared |
| 18 |
to the reported mtime of the file, even if mtime is queried after reading |
| 19 |
a file. |
| 20 |
|
| 21 |
* Repeating an operation produces the same result as the first one during |
| 22 |
a transaction. |
| 23 |
|
| 24 |
* Call flush() to start a new transaction (flush the caches). |
| 25 |
|
| 26 |
The API is a bit limited. It's easy to add new cached operations, however. |
| 27 |
You should perform all file system reads through the API to actually take |
| 28 |
advantage of the benefits. |
| 29 |
""" |
| 30 |
|
| 31 |
from __future__ import annotations |
| 32 |
|
| 33 |
import os |
| 34 |
import stat |
| 35 |
|
| 36 |
from mypy_extensions import mypyc_attr |
| 37 |
|
| 38 |
from mypy.util import hash_digest |
| 39 |
|
| 40 |
|
| 41 |
@mypyc_attr(allow_interpreted_subclasses=True) # for tests |
| 42 |
class FileSystemCache: |
| 43 |
def __init__(self) -> None: |
| 44 |
# The package root is not flushed with the caches. |
| 45 |
# It is set by set_package_root() below. |
| 46 |
self.package_root: list[str] = [] |
| 47 |
self.flush() |
| 48 |
|
| 49 |
def set_package_root(self, package_root: list[str]) -> None: |
| 50 |
self.package_root = package_root |
| 51 |
|
| 52 |
def flush(self) -> None: |
| 53 |
"""Start another transaction and empty all caches.""" |
| 54 |
self.stat_or_none_cache: dict[str, os.stat_result | None] = {} |
| 55 |
|
| 56 |
self.listdir_cache: dict[str, list[str]] = {} |
| 57 |
self.listdir_error_cache: dict[str, OSError] = {} |
| 58 |
self.isfile_case_cache: dict[str, bool] = {} |
| 59 |
self.exists_case_cache: dict[str, bool] = {} |
| 60 |
self.read_cache: dict[str, bytes] = {} |
| 61 |
self.read_error_cache: dict[str, Exception] = {} |
| 62 |
self.hash_cache: dict[str, str] = {} |
| 63 |
self.fake_package_cache: set[str] = set() |
| 64 |
|
| 65 |
def stat_or_none(self, path: str) -> os.stat_result | None: |
| 66 |
if path in self.stat_or_none_cache: |
| 67 |
return self.stat_or_none_cache[path] |
| 68 |
|
| 69 |
st = None |
| 70 |
try: |
| 71 |
st = os.stat(path) |
| 72 |
except OSError: |
| 73 |
if self.init_under_package_root(path): |
| 74 |
try: |
| 75 |
st = self._fake_init(path) |
| 76 |
except OSError: |
| 77 |
pass |
| 78 |
|
| 79 |
self.stat_or_none_cache[path] = st |
| 80 |
return st |
| 81 |
|
| 82 |
def init_under_package_root(self, path: str) -> bool: |
| 83 |
"""Is this path an __init__.py under a package root? |
| 84 |
|
| 85 |
This is used to detect packages that don't contain __init__.py |
| 86 |
files, which is needed to support Bazel. The function should |
| 87 |
only be called for non-existing files. |
| 88 |
|
| 89 |
It will return True if it refers to a __init__.py file that |
| 90 |
Bazel would create, so that at runtime Python would think the |
| 91 |
directory containing it is a package. For this to work you |
| 92 |
must pass one or more package roots using the --package-root |
| 93 |
flag. |
| 94 |
|
| 95 |
As an exceptional case, any directory that is a package root |
| 96 |
itself will not be considered to contain a __init__.py file. |
| 97 |
This is different from the rules Bazel itself applies, but is |
| 98 |
necessary for mypy to properly distinguish packages from other |
| 99 |
directories. |
| 100 |
|
| 101 |
See https://docs.bazel.build/versions/master/be/python.html, |
| 102 |
where this behavior is described under legacy_create_init. |
| 103 |
""" |
| 104 |
if not self.package_root: |
| 105 |
return False |
| 106 |
dirname, basename = os.path.split(path) |
| 107 |
if basename != "__init__.py": |
| 108 |
return False |
| 109 |
if not os.path.basename(dirname).isidentifier(): |
| 110 |
# Can't put an __init__.py in a place that's not an identifier |
| 111 |
return False |
| 112 |
|
| 113 |
st = self.stat_or_none(dirname) |
| 114 |
if st is None: |
| 115 |
return False |
| 116 |
else: |
| 117 |
if not stat.S_ISDIR(st.st_mode): |
| 118 |
return False |
| 119 |
ok = False |
| 120 |
|
| 121 |
# skip if on a different drive |
| 122 |
current_drive, _ = os.path.splitdrive(os.getcwd()) |
| 123 |
drive, _ = os.path.splitdrive(path) |
| 124 |
if drive != current_drive: |
| 125 |
return False |
| 126 |
if os.path.isabs(path): |
| 127 |
path = os.path.relpath(path) |
| 128 |
path = os.path.normpath(path) |
| 129 |
for root in self.package_root: |
| 130 |
if path.startswith(root): |
| 131 |
if path == root + basename: |
| 132 |
# A package root itself is never a package. |
| 133 |
ok = False |
| 134 |
break |
| 135 |
else: |
| 136 |
ok = True |
| 137 |
return ok |
| 138 |
|
| 139 |
def _fake_init(self, path: str) -> os.stat_result: |
| 140 |
"""Prime the cache with a fake __init__.py file. |
| 141 |
|
| 142 |
This makes code that looks for path believe an empty file by |
| 143 |
that name exists. Should only be called after |
| 144 |
init_under_package_root() returns True. |
| 145 |
""" |
| 146 |
dirname, basename = os.path.split(path) |
| 147 |
assert basename == "__init__.py", path |
| 148 |
assert not os.path.exists(path), path # Not cached! |
| 149 |
dirname = os.path.normpath(dirname) |
| 150 |
st = os.stat(dirname) # May raise OSError |
| 151 |
# Get stat result as a list so we can modify it. |
| 152 |
seq: list[float] = list(st) |
| 153 |
seq[stat.ST_MODE] = stat.S_IFREG | 0o444 |
| 154 |
seq[stat.ST_INO] = 1 |
| 155 |
seq[stat.ST_NLINK] = 1 |
| 156 |
seq[stat.ST_SIZE] = 0 |
| 157 |
st = os.stat_result(seq) |
| 158 |
# Make listdir() and read() also pretend this file exists. |
| 159 |
self.fake_package_cache.add(dirname) |
| 160 |
return st |
| 161 |
|
| 162 |
def listdir(self, path: str) -> list[str]: |
| 163 |
path = os.path.normpath(path) |
| 164 |
if path in self.listdir_cache: |
| 165 |
res = self.listdir_cache[path] |
| 166 |
# Check the fake cache. |
| 167 |
if path in self.fake_package_cache and "__init__.py" not in res: |
| 168 |
res.append("__init__.py") # Updates the result as well as the cache |
| 169 |
return res |
| 170 |
if path in self.listdir_error_cache: |
| 171 |
raise copy_os_error(self.listdir_error_cache[path]) |
| 172 |
try: |
| 173 |
results = os.listdir(path) |
| 174 |
except OSError as err: |
| 175 |
# Like above, take a copy to reduce memory use. |
| 176 |
self.listdir_error_cache[path] = copy_os_error(err) |
| 177 |
raise err |
| 178 |
self.listdir_cache[path] = results |
| 179 |
# Check the fake cache. |
| 180 |
if path in self.fake_package_cache and "__init__.py" not in results: |
| 181 |
results.append("__init__.py") |
| 182 |
return results |
| 183 |
|
| 184 |
def isfile(self, path: str) -> bool: |
| 185 |
st = self.stat_or_none(path) |
| 186 |
if st is None: |
| 187 |
return False |
| 188 |
return stat.S_ISREG(st.st_mode) |
| 189 |
|
| 190 |
def isfile_case(self, path: str, prefix: str) -> bool: |
| 191 |
"""Return whether path exists and is a file. |
| 192 |
|
| 193 |
On case-insensitive filesystems (like Mac or Windows) this returns |
| 194 |
False if the case of path's last component does not exactly match |
| 195 |
the case found in the filesystem. |
| 196 |
|
| 197 |
We check also the case of other path components up to prefix. |
| 198 |
For example, if path is 'user-stubs/pack/mod.pyi' and prefix is 'user-stubs', |
| 199 |
we check that the case of 'pack' and 'mod.py' matches exactly, 'user-stubs' will be |
| 200 |
case insensitive on case insensitive filesystems. |
| 201 |
|
| 202 |
The caller must ensure that prefix is a valid file system prefix of path. |
| 203 |
""" |
| 204 |
if not self.isfile(path): |
| 205 |
# Fast path |
| 206 |
return False |
| 207 |
if path in self.isfile_case_cache: |
| 208 |
return self.isfile_case_cache[path] |
| 209 |
head, tail = os.path.split(path) |
| 210 |
if not tail: |
| 211 |
self.isfile_case_cache[path] = False |
| 212 |
return False |
| 213 |
try: |
| 214 |
names = self.listdir(head) |
| 215 |
# This allows one to check file name case sensitively in |
| 216 |
# case-insensitive filesystems. |
| 217 |
res = tail in names |
| 218 |
except OSError: |
| 219 |
res = False |
| 220 |
if res: |
| 221 |
# Also recursively check the other path components in case sensitive way. |
| 222 |
res = self.exists_case(head, prefix) |
| 223 |
self.isfile_case_cache[path] = res |
| 224 |
return res |
| 225 |
|
| 226 |
def exists_case(self, path: str, prefix: str) -> bool: |
| 227 |
"""Return whether path exists - checking path components in case sensitive |
| 228 |
fashion, up to prefix. |
| 229 |
""" |
| 230 |
if path in self.exists_case_cache: |
| 231 |
return self.exists_case_cache[path] |
| 232 |
head, tail = os.path.split(path) |
| 233 |
if not head.startswith(prefix) or not tail: |
| 234 |
# Only perform the check for paths under prefix. |
| 235 |
self.exists_case_cache[path] = True |
| 236 |
return True |
| 237 |
try: |
| 238 |
names = self.listdir(head) |
| 239 |
# This allows one to check file name case sensitively in |
| 240 |
# case-insensitive filesystems. |
| 241 |
res = tail in names |
| 242 |
except OSError: |
| 243 |
res = False |
| 244 |
if res: |
| 245 |
# Also recursively check other path components. |
| 246 |
res = self.exists_case(head, prefix) |
| 247 |
self.exists_case_cache[path] = res |
| 248 |
return res |
| 249 |
|
| 250 |
def isdir(self, path: str) -> bool: |
| 251 |
st = self.stat_or_none(path) |
| 252 |
if st is None: |
| 253 |
return False |
| 254 |
return stat.S_ISDIR(st.st_mode) |
| 255 |
|
| 256 |
def exists(self, path: str, real_only: bool = False) -> bool: |
| 257 |
st = self.stat_or_none(path) |
| 258 |
if st is None: |
| 259 |
return False |
| 260 |
if real_only: |
| 261 |
dirname = os.path.dirname(path) |
| 262 |
return dirname not in self.fake_package_cache |
| 263 |
return True |
| 264 |
|
| 265 |
def read(self, path: str) -> bytes: |
| 266 |
if path in self.read_cache: |
| 267 |
return self.read_cache[path] |
| 268 |
if path in self.read_error_cache: |
| 269 |
raise self.read_error_cache[path] |
| 270 |
|
| 271 |
# Need to stat first so that the contents of file are from no |
| 272 |
# earlier instant than the mtime reported by self.stat(). |
| 273 |
self.stat_or_none(path) |
| 274 |
|
| 275 |
dirname, basename = os.path.split(path) |
| 276 |
dirname = os.path.normpath(dirname) |
| 277 |
# Check the fake cache. |
| 278 |
if basename == "__init__.py" and dirname in self.fake_package_cache: |
| 279 |
data = b"" |
| 280 |
else: |
| 281 |
try: |
| 282 |
with open(path, "rb") as f: |
| 283 |
data = f.read() |
| 284 |
except OSError as err: |
| 285 |
self.read_error_cache[path] = err |
| 286 |
raise |
| 287 |
|
| 288 |
self.read_cache[path] = data |
| 289 |
self.hash_cache[path] = hash_digest(data) |
| 290 |
return data |
| 291 |
|
| 292 |
def hash_digest(self, path: str) -> str: |
| 293 |
if path not in self.hash_cache: |
| 294 |
self.read(path) |
| 295 |
return self.hash_cache[path] |
| 296 |
|
| 297 |
def samefile(self, f1: str, f2: str) -> bool: |
| 298 |
s1 = self.stat_or_none(f1) |
| 299 |
s2 = self.stat_or_none(f2) |
| 300 |
if s1 is None or s2 is None: |
| 301 |
return False |
| 302 |
return os.path.samestat(s1, s2) |
| 303 |
|
| 304 |
|
| 305 |
def copy_os_error(e: OSError) -> OSError: |
| 306 |
new = OSError(*e.args) |
| 307 |
new.errno = e.errno |
| 308 |
new.strerror = e.strerror |
| 309 |
new.filename = e.filename |
| 310 |
if e.filename2: |
| 311 |
new.filename2 = e.filename2 |
| 312 |
return new |