Debian Codegraph @

mypy/modulefinder.py

raw ◀ ▶
1 Debian patch touch this file
1 """Low-level infrastructure to find modules.
2
3 This builds on fscache.py; find_sources.py builds on top of this.
4 """
5
6 from __future__ import annotations
7
8 import ast
9 import collections
10 import functools
11 import os
12 import re
13 import subprocess
14 import sys
15 from enum import Enum, unique
16 from typing import Final, TypeAlias as _TypeAlias
17
18 from pathspec import GitIgnoreSpec
19 from pathspec.patterns.gitignore import GitIgnorePatternError
20
21 from mypy import pyinfo
22 from mypy.errors import CompileError
23 from mypy.fscache import FileSystemCache
24 from mypy.nodes import MypyFile
25 from mypy.options import Options
26 from mypy.stubinfo import stub_distribution_name
27 from mypy.util import os_path_join
28
29
30 # Paths to be searched in find_module().
31 class SearchPaths:
32 def __init__(
33 self,
34 python_path: tuple[str, ...],
35 mypy_path: tuple[str, ...],
36 package_path: tuple[str, ...],
37 typeshed_path: tuple[str, ...],
38 ) -> None:
39 # where user code is found
40 self.python_path = tuple(map(os.path.abspath, python_path))
41 # from $MYPYPATH or config variable
42 self.mypy_path = tuple(map(os.path.abspath, mypy_path))
43 # from get_site_packages_dirs()
44 self.package_path = tuple(map(os.path.abspath, package_path))
45 # paths in typeshed
46 self.typeshed_path = tuple(map(os.path.abspath, typeshed_path))
47
48 def asdict(self) -> dict[str, tuple[str, ...]]:
49 return {
50 "python_path": self.python_path,
51 "mypy_path": self.mypy_path,
52 "package_path": self.package_path,
53 "typeshed_path": self.typeshed_path,
54 }
55
56
57 # Package dirs are a two-tuple of path to search and whether to verify the module
58 OnePackageDir = tuple[str, bool]
59 PackageDirs = list[OnePackageDir]
60
61 # Minimum and maximum Python versions for modules in stdlib as (major, minor)
62 StdlibVersions: _TypeAlias = dict[str, tuple[tuple[int, int], tuple[int, int] | None]]
63
64 PYTHON_EXTENSIONS: Final = [".pyi", ".py"]
65
66
67 # TODO: Consider adding more reasons here?
68 # E.g. if we deduce a module would likely be found if the user were
69 # to set the --namespace-packages flag.
70 @unique
71 class ModuleNotFoundReason(Enum):
72 # The module was not found: we found neither stubs nor a plausible code
73 # implementation (with or without a py.typed file).
74 NOT_FOUND = 0
75
76 # The implementation for this module plausibly exists (e.g. we
77 # found a matching folder or *.py file), but either the parent package
78 # did not contain a py.typed file or we were unable to find a
79 # corresponding *-stubs package.
80 FOUND_WITHOUT_TYPE_HINTS = 1
81
82 # The module was not found in the current working directory, but
83 # was able to be found in the parent directory.
84 WRONG_WORKING_DIRECTORY = 2
85
86 # Stub PyPI package (typically types-pkgname) known to exist but not installed.
87 APPROVED_STUBS_NOT_INSTALLED = 3
88
89 def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]:
90 doc_link = "See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports"
91 if self is ModuleNotFoundReason.NOT_FOUND:
92 msg = 'Cannot find implementation or library stub for module named "{module}"'
93 notes = [doc_link]
94 elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY:
95 msg = 'Cannot find implementation or library stub for module named "{module}"'
96 notes = [
97 "You may be running mypy in a subpackage, mypy should be run on the package root"
98 ]
99 elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:
100 msg = (
101 'Skipping analyzing "{module}": module is installed, but missing library stubs '
102 "or py.typed marker"
103 )
104 notes = [doc_link]
105 elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:
106 msg = 'Library stubs not installed for "{module}"'
•107 notes = ['Hint: On Debian systems, you can install the python3-typeshed package to '
108 'provide mypy with stubs for many popular libraries. '
109 'In virtual Python environments, you can instead run "python3 -m pip install {stub_dist}".']
110 if not daemon:
111 notes.append(
112 '(or run "mypy --install-types" to install all missing stub packages)'
113 )
114 notes.append(doc_link)
115 else:
116 assert False
117 return msg, notes
118
119
120 # If we found the module, returns the path to the module as a str.
121 # Otherwise, returns the reason why the module wasn't found.
122 ModuleSearchResult = str | ModuleNotFoundReason
123
124
125 class BuildSource:
126 """A single source file."""
127
128 def __init__(
129 self,
130 path: str | None,
131 module: str | None,
132 text: str | None = None,
133 base_dir: str | None = None,
134 followed: bool = False,
135 ) -> None:
136 self.path = path # File where it's found (e.g. 'xxx/yyy/foo/bar.py')
137 self.module = module or "__main__" # Module name (e.g. 'foo.bar')
138 self.text = text # Source code, if initially supplied, else None
139 self.base_dir = base_dir # Directory where the package is rooted (e.g. 'xxx/yyy')
140 self.followed = followed # Was this found by following imports?
141
142 def __repr__(self) -> str:
143 return (
144 "BuildSource(path={!r}, module={!r}, has_text={}, base_dir={!r}, followed={})".format(
145 self.path, self.module, self.text is not None, self.base_dir, self.followed
146 )
147 )
148
149
150 class BuildSourceSet:
151 """Helper to efficiently test a file's membership in a set of build sources."""
152
153 def __init__(self, sources: list[BuildSource]) -> None:
154 self.source_text_present = False
155 self.source_modules: dict[str, str] = {}
156 self.source_paths: set[str] = set()
157
158 for source in sources:
159 if source.text is not None:
160 self.source_text_present = True
161 if source.path:
162 self.source_paths.add(source.path)
163 if source.module:
164 self.source_modules[source.module] = source.path or ""
165
166 def is_source(self, file: MypyFile) -> bool:
167 return (
168 (file.path and file.path in self.source_paths)
169 or file._fullname in self.source_modules
170 or self.source_text_present
171 )
172
173
174 class FindModuleCache:
175 """Module finder with integrated cache.
176
177 Module locations and some intermediate results are cached internally
178 and can be cleared with the clear() method.
179
180 All file system accesses are performed through a FileSystemCache,
181 which is not ever cleared by this class. If necessary it must be
182 cleared by client code.
183 """
184
185 def __init__(
186 self,
187 search_paths: SearchPaths,
188 fscache: FileSystemCache | None,
189 options: Options | None,
190 stdlib_py_versions: StdlibVersions | None = None,
191 source_set: BuildSourceSet | None = None,
192 ) -> None:
193 self.search_paths = search_paths
194 self.source_set = source_set
195 self.fscache = fscache or FileSystemCache()
196 # Cache for get_toplevel_possibilities:
197 # search_paths -> (toplevel_id -> list(package_dirs))
198 self.initial_components: dict[tuple[str, ...], dict[str, list[str]]] = {}
199 # Cache find_module: id -> result
200 self.results: dict[str, ModuleSearchResult] = {}
201 self.ns_ancestors: dict[str, str] = {}
202 self.options = options
203 custom_typeshed_dir = None
204 if options:
205 custom_typeshed_dir = options.custom_typeshed_dir
206 self.stdlib_py_versions = stdlib_py_versions or load_stdlib_py_versions(
207 custom_typeshed_dir
208 )
209
210 def clear(self) -> None:
211 self.results.clear()
212 self.initial_components.clear()
213 self.ns_ancestors.clear()
214
215 def find_module_via_source_set(self, id: str) -> ModuleSearchResult | None:
216 """Fast path to find modules by looking through the input sources
217
218 This is only used when --fast-module-lookup is passed on the command line."""
219 if not self.source_set:
220 return None
221
222 p = self.source_set.source_modules.get(id, None)
223 if p and self.fscache.isfile(p):
224 # We need to make sure we still have __init__.py all the way up
225 # otherwise we might have false positives compared to slow path
226 # in case of deletion of init files, which is covered by some tests.
227 # TODO: are there some combination of flags in which this check should be skipped?
228 d = os.path.dirname(p)
229 for _ in range(id.count(".")):
230 if not any(
231 self.fscache.isfile(os_path_join(d, "__init__" + x)) for x in PYTHON_EXTENSIONS
232 ):
233 return None
234 d = os.path.dirname(d)
235 return p
236
237 idx = id.rfind(".")
238 if idx != -1:
239 # When we're looking for foo.bar.baz and can't find a matching module
240 # in the source set, look up for a foo.bar module.
241 parent = self.find_module_via_source_set(id[:idx])
242 if parent is None or not isinstance(parent, str):
243 return None
244
245 basename, ext = os.path.splitext(parent)
246 if not any(parent.endswith("__init__" + x) for x in PYTHON_EXTENSIONS) and (
247 ext in PYTHON_EXTENSIONS and not self.fscache.isdir(basename)
248 ):
249 # If we do find such a *module* (and crucially, we don't want a package,
250 # hence the filtering out of __init__ files, and checking for the presence
251 # of a folder with a matching name), then we can be pretty confident that
252 # 'baz' will either be a top-level variable in foo.bar, or will not exist.
253 #
254 # Either way, spelunking in other search paths for another 'foo.bar.baz'
255 # module should be avoided because:
256 # 1. in the unlikely event that one were found, it's highly likely that
257 # it would be unrelated to the source being typechecked and therefore
258 # more likely to lead to erroneous results
259 # 2. as described in _find_module, in some cases the search itself could
260 # potentially waste significant amounts of time
261 return ModuleNotFoundReason.NOT_FOUND
262 return None
263
264 def find_lib_path_dirs(self, id: str, lib_path: tuple[str, ...]) -> PackageDirs:
265 """Find which elements of a lib_path have the directory a module needs to exist."""
266 components = id.split(".")
267 dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar'
268
269 dirs = []
270 for pathitem in self.get_toplevel_possibilities(lib_path, components[0]):
271 # e.g., '/usr/lib/python3.4/foo/bar'
272 if dir_chain:
273 dir = os_path_join(pathitem, dir_chain)
274 else:
275 dir = pathitem
276 if self.fscache.isdir(dir):
277 dirs.append((dir, True))
278 return dirs
279
280 def get_toplevel_possibilities(self, lib_path: tuple[str, ...], id: str) -> list[str]:
281 """Find which elements of lib_path could contain a particular top-level module.
282
283 In practice, almost all modules can be routed to the correct entry in
284 lib_path by looking at just the first component of the module name.
285
286 We take advantage of this by enumerating the contents of all of the
287 directories on the lib_path and building a map of which entries in
288 the lib_path could contain each potential top-level module that appears.
289 """
290
291 if lib_path in self.initial_components:
292 return self.initial_components[lib_path].get(id, [])
293
294 # Enumerate all the files in the directories on lib_path and produce the map
295 components: dict[str, list[str]] = {}
296 for dir in lib_path:
297 try:
298 contents = self.fscache.listdir(dir)
299 except OSError:
300 contents = []
301 # False positives are fine for correctness here, since we will check
302 # precisely later, so we only look at the root of every filename without
303 # any concern for the exact details.
304 for name in contents:
305 name = os.path.splitext(name)[0]
306 components.setdefault(name, []).append(dir)
307
308 self.initial_components[lib_path] = components
309 return components.get(id, [])
310
311 def find_module(self, id: str, *, fast_path: bool = False) -> ModuleSearchResult:
312 """Return the path of the module source file or why it wasn't found.
313
314 If fast_path is True, prioritize performance over generating detailed
315 error descriptions.
316 """
317 if id not in self.results:
318 top_level = id.partition(".")[0]
319 use_typeshed = True
320 if id in self.stdlib_py_versions:
321 use_typeshed = self._typeshed_has_version(id)
322 elif top_level in self.stdlib_py_versions:
323 use_typeshed = self._typeshed_has_version(top_level)
324 result, should_cache = self._find_module(id, use_typeshed)
325 if should_cache:
326 if (
327 not (
328 fast_path or (self.options is not None and self.options.fast_module_lookup)
329 )
330 and result is ModuleNotFoundReason.NOT_FOUND
331 and self._can_find_module_in_parent_dir(id)
332 ):
333 self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY
334 else:
335 self.results[id] = result
336 return self.results[id]
337 else:
338 return result
339 return self.results[id]
340
341 def _typeshed_has_version(self, module: str) -> bool:
342 if not self.options:
343 return True
344 version = typeshed_py_version(self.options)
345 min_version, max_version = self.stdlib_py_versions[module]
346 return version >= min_version and (max_version is None or version <= max_version)
347
348 def _find_module_non_stub_helper(
349 self, id: str, pkg_dir: str
350 ) -> OnePackageDir | ModuleNotFoundReason:
351 plausible_match = False
352 dir_path = pkg_dir
353 components = id.split(".")
354 for index, component in enumerate(components):
355 dir_path = os_path_join(dir_path, component)
356 if self.fscache.isfile(os_path_join(dir_path, "py.typed")):
357 return os.path.join(pkg_dir, *components[:-1]), index == 0
358 elif not plausible_match and (
359 self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + ".py")
360 ):
361 plausible_match = True
362 # If this is not a directory then we can't traverse further into it
363 if not self.fscache.isdir(dir_path):
364 break
365 if plausible_match:
366 if self.options:
367 module_specific_options = self.options.clone_for_module(id)
368 if module_specific_options.follow_untyped_imports:
369 return os.path.join(pkg_dir, *components[:-1]), False
370 return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS
371 else:
372 return ModuleNotFoundReason.NOT_FOUND
373
374 def _update_ns_ancestors(self, components: list[str], match: tuple[str, bool]) -> None:
375 path, verify = match
376 for i in range(1, len(components)):
377 pkg_id = ".".join(components[:-i])
378 if pkg_id not in self.ns_ancestors and self.fscache.isdir(path):
379 self.ns_ancestors[pkg_id] = path
380 path = os.path.dirname(path)
381
382 def _can_find_module_in_parent_dir(self, id: str) -> bool:
383 """Test if a module can be found by checking the parent directories
384 of the current working directory.
385 """
386 working_dir = os.getcwd()
387 parent_search = FindModuleCache(
388 SearchPaths((), (), (), ()),
389 self.fscache,
390 self.options,
391 stdlib_py_versions=self.stdlib_py_versions,
392 )
393 while any(is_init_file(file) for file in os.listdir(working_dir)):
394 working_dir = os.path.dirname(working_dir)
395 parent_search.search_paths = SearchPaths((working_dir,), (), (), ())
396 if not isinstance(parent_search._find_module(id, False)[0], ModuleNotFoundReason):
397 return True
398 return False
399
400 def _find_module(self, id: str, use_typeshed: bool) -> tuple[ModuleSearchResult, bool]:
401 """Try to find a module in all available sources.
402
403 Returns:
404 ``(result, can_be_cached)`` pair.
405 """
406 fscache = self.fscache
407
408 # Fast path for any modules in the current source set.
409 # This is particularly important when there are a large number of search
410 # paths which share the first (few) component(s) due to the use of namespace
411 # packages, for instance:
412 # foo/
413 # company/
414 # __init__.py
415 # foo/
416 # bar/
417 # company/
418 # __init__.py
419 # bar/
420 # baz/
421 # company/
422 # __init__.py
423 # baz/
424 #
425 # mypy gets [foo/company/foo, bar/company/bar, baz/company/baz, ...] as input
426 # and computes [foo, bar, baz, ...] as the module search path.
427 #
428 # This would result in O(n) search for every import of company.*, leading to
429 # O(n**2) behavior in load_graph as such imports are unsurprisingly present
430 # at least once, and usually many more times than that, in each and every file
431 # being parsed.
432 #
433 # Thankfully, such cases are efficiently handled by looking up the module path
434 # via BuildSourceSet.
435 p = (
436 self.find_module_via_source_set(id)
437 if (self.options is not None and self.options.fast_module_lookup)
438 else None
439 )
440 if p:
441 return p, True
442
443 # If we're looking for a module like 'foo.bar.baz', it's likely that most of the
444 # many elements of lib_path don't even have a subdirectory 'foo/bar'. Discover
445 # that only once and cache it for when we look for modules like 'foo.bar.blah'
446 # that will require the same subdirectory.
447 components = id.split(".")
448 dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar'
449
450 # We have two sets of folders so that we collect *all* stubs folders and
451 # put them in the front of the search path
452 third_party_inline_dirs: PackageDirs = []
453 third_party_stubs_dirs: PackageDirs = []
454 found_possible_third_party_missing_type_hints = False
455 # Third-party stub/typed packages
456 candidate_package_dirs = {
457 package_dir[0]
458 for component in (components[0], components[0] + "-stubs")
459 for package_dir in self.find_lib_path_dirs(component, self.search_paths.package_path)
460 }
461 # Caching FOUND_WITHOUT_TYPE_HINTS is not always safe. That causes issues with
462 # typed subpackages in namespace packages.
463 can_cache_any_result = True
464 for pkg_dir in self.search_paths.package_path:
465 if pkg_dir not in candidate_package_dirs:
466 continue
467 stub_name = components[0] + "-stubs"
468 stub_dir = os_path_join(pkg_dir, stub_name)
469 if fscache.isdir(stub_dir):
470 stub_typed_file = os_path_join(stub_dir, "py.typed")
471 stub_components = [stub_name] + components[1:]
472 path = os.path.join(pkg_dir, *stub_components[:-1])
473 if fscache.isdir(path):
474 if fscache.isfile(stub_typed_file):
475 # Stub packages can have a py.typed file, which must include
476 # 'partial\n' to make the package partial.
477 # Partial here means that mypy should look at the runtime
478 # package if installed.
479 if fscache.read(stub_typed_file).decode().strip() == "partial":
480 runtime_path = os_path_join(pkg_dir, dir_chain)
481 third_party_inline_dirs.append((runtime_path, True))
482 # if the package is partial, we don't verify the module, as
483 # the partial stub package may not have a __init__.pyi
484 third_party_stubs_dirs.append((path, False))
485 else:
486 # handle the edge case where people put a py.typed file
487 # in a stub package, but it isn't partial
488 third_party_stubs_dirs.append((path, True))
489 else:
490 third_party_stubs_dirs.append((path, True))
491 non_stub_match = self._find_module_non_stub_helper(id, pkg_dir)
492 if isinstance(non_stub_match, ModuleNotFoundReason):
493 if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:
494 found_possible_third_party_missing_type_hints = True
495 can_cache_any_result = False
496 else:
497 third_party_inline_dirs.append(non_stub_match)
498 self._update_ns_ancestors(components, non_stub_match)
499
500 if self.options and self.options.use_builtins_fixtures:
501 # Everything should be in fixtures.
502 third_party_inline_dirs.clear()
503 third_party_stubs_dirs.clear()
504 found_possible_third_party_missing_type_hints = False
505 python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path
506 candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path)
507 if use_typeshed:
508 # Search for stdlib stubs in typeshed before installed
509 # stubs to avoid picking up backports (dataclasses, for
510 # example) when the library is included in stdlib.
511 candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path)
512 candidate_base_dirs += third_party_stubs_dirs + third_party_inline_dirs
513
514 # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now
515 # contains just the subdirectories 'foo/bar' that actually exist under the
516 # elements of lib_path. This is probably much shorter than lib_path itself.
517 # Now just look for 'baz.pyi', 'baz/__init__.py', etc., inside those directories.
518 seplast = os.sep + components[-1] # so e.g. '/baz'
519 sepinit = os.sep + "__init__"
520 near_misses = [] # Collect near misses for namespace mode (see below).
521 for base_dir, verify in candidate_base_dirs:
522 base_path = base_dir + seplast # so e.g. '/usr/lib/python3.4/foo/bar/baz'
523 has_init = False
524 dir_prefix = base_dir
525 for _ in range(len(components) - 1):
526 dir_prefix = os.path.dirname(dir_prefix)
527
528 # Stubs-only packages always take precedence over py.typed packages
529 path_stubs = f"{base_path}-stubs{sepinit}.pyi"
530 if fscache.isfile_case(path_stubs, dir_prefix):
531 if verify and not verify_module(fscache, id, path_stubs, dir_prefix):
532 near_misses.append((path_stubs, dir_prefix))
533 else:
534 return path_stubs, True
535
536 # Prefer package over module, i.e. baz/__init__.py* over baz.py*.
537 for extension in PYTHON_EXTENSIONS:
538 path = base_path + sepinit + extension
539 if fscache.isfile_case(path, dir_prefix):
540 has_init = True
541 if verify and not verify_module(fscache, id, path, dir_prefix):
542 near_misses.append((path, dir_prefix))
543 continue
544 return path, True
545
546 # In namespace mode, register a potential namespace package
547 if self.options and self.options.namespace_packages:
548 if (
549 not has_init
550 and fscache.exists_case(base_path, dir_prefix)
551 and not fscache.isfile_case(base_path, dir_prefix)
552 ):
553 near_misses.append((base_path, dir_prefix))
554
555 # No package, look for module.
556 for extension in PYTHON_EXTENSIONS:
557 path = base_path + extension
558 if fscache.isfile_case(path, dir_prefix):
559 if verify and not verify_module(fscache, id, path, dir_prefix):
560 near_misses.append((path, dir_prefix))
561 continue
562 return path, True
563
564 # In namespace mode, re-check those entries that had 'verify'.
565 # Assume search path entries xxx, yyy and zzz, and we're
566 # looking for foo.bar.baz. Suppose near_misses has:
567 #
568 # - xxx/foo/bar/baz.py
569 # - yyy/foo/bar/baz/__init__.py
570 # - zzz/foo/bar/baz.pyi
571 #
572 # If any of the foo directories has __init__.py[i], it wins.
573 # Else, we look for foo/bar/__init__.py[i], etc. If there are
574 # none, the first hit wins. Note that this does not take into
575 # account whether the lowest-level module is a file (baz.py),
576 # a package (baz/__init__.py), or a stub file (baz.pyi) -- for
577 # these the first one encountered along the search path wins.
578 #
579 # The helper function highest_init_level() returns an int that
580 # indicates the highest level at which a __init__.py[i] file
581 # is found; if no __init__ was found it returns 0, if we find
582 # only foo/bar/__init__.py it returns 1, and if we have
583 # foo/__init__.py it returns 2 (regardless of what's in
584 # foo/bar). It doesn't look higher than that.
585 if self.options and self.options.namespace_packages and near_misses:
586 levels = [
587 highest_init_level(fscache, id, path, dir_prefix)
588 for path, dir_prefix in near_misses
589 ]
590 index = levels.index(max(levels))
591 return near_misses[index][0], True
592
593 # Finally, we may be asked to produce an ancestor for an
594 # installed package with a py.typed marker that is a
595 # subpackage of a namespace package. We only fess up to these
596 # if we would otherwise return "not found".
597 ancestor = self.ns_ancestors.get(id)
598 if ancestor is not None:
599 return ancestor, True
600
601 approved_dist_name = stub_distribution_name(id)
602 if approved_dist_name:
603 if len(components) == 1:
604 return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True
605 # If we're a missing submodule of an already installed approved stubs, we don't want to
606 # error with APPROVED_STUBS_NOT_INSTALLED, but rather want to return NOT_FOUND.
607 for i in range(1, len(components)):
608 parent_id = ".".join(components[:i])
609 if stub_distribution_name(parent_id) == approved_dist_name:
610 break
611 else:
612 return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True
613 if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:
614 return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True
615 return ModuleNotFoundReason.NOT_FOUND, True
616
617 if found_possible_third_party_missing_type_hints:
618 return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS, can_cache_any_result
619 return ModuleNotFoundReason.NOT_FOUND, True
620
621 def find_modules_recursive(self, module: str) -> list[BuildSource]:
622 module_path = self.find_module(module, fast_path=True)
623 if isinstance(module_path, ModuleNotFoundReason):
624 return []
625 sources = [BuildSource(module_path, module, None)]
626
627 package_path = None
628 if is_init_file(module_path):
629 package_path = os.path.dirname(module_path)
630 elif self.fscache.isdir(module_path):
631 package_path = module_path
632 if package_path is None:
633 return sources
634
635 # This logic closely mirrors that in find_sources. One small but important difference is
636 # that we do not sort names with keyfunc. The recursive call to find_modules_recursive
637 # calls find_module, which will handle the preference between packages, pyi and py.
638 # Another difference is it doesn't handle nested search paths / package roots.
639
640 seen: set[str] = set()
641 names = sorted(self.fscache.listdir(package_path))
642 for name in names:
643 # Skip certain names altogether
644 if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."):
645 continue
646 subpath = os_path_join(package_path, name)
647
648 if self.options and matches_exclude(
649 subpath, self.options.exclude, self.fscache, self.options.verbosity >= 2
650 ):
651 continue
652 if (
653 self.options
654 and self.options.exclude_gitignore
655 and matches_gitignore(subpath, self.fscache, self.options.verbosity >= 2)
656 ):
657 continue
658
659 if self.fscache.isdir(subpath):
660 # Only recurse into packages
661 if (self.options and self.options.namespace_packages) or (
662 self.fscache.isfile(os_path_join(subpath, "__init__.py"))
663 or self.fscache.isfile(os_path_join(subpath, "__init__.pyi"))
664 ):
665 seen.add(name)
666 sources.extend(self.find_modules_recursive(module + "." + name))
667 else:
668 stem, suffix = os.path.splitext(name)
669 if stem == "__init__":
670 continue
671 if stem not in seen and "." not in stem and suffix in PYTHON_EXTENSIONS:
672 # (If we sorted names by keyfunc) we could probably just make the BuildSource
673 # ourselves, but this ensures compatibility with find_module / the cache
674 seen.add(stem)
675 sources.extend(self.find_modules_recursive(module + "." + stem))
676 return sources
677
678
679 def matches_exclude(
680 subpath: str, excludes: list[str], fscache: FileSystemCache, verbose: bool
681 ) -> bool:
682 if not excludes:
683 return False
684 subpath_str = os.path.relpath(subpath).replace(os.sep, "/")
685 if fscache.isdir(subpath):
686 subpath_str += "/"
687 for exclude in excludes:
688 try:
689 if re.search(exclude, subpath_str):
690 if verbose:
691 print(
692 f"TRACE: Excluding {subpath_str} (matches pattern {exclude})",
693 file=sys.stderr,
694 )
695 return True
696 except re.error as e:
697 print(
698 f"error: The exclude {exclude} is an invalid regular expression, because: {e}"
699 + (
700 "\n(Hint: use / as a path separator, even if you're on Windows!)"
701 if "\\" in exclude
702 else ""
703 )
704 + "\nFor more information on Python's flavor of regex, see:"
705 + " https://docs.python.org/3/library/re.html",
706 file=sys.stderr,
707 )
708 sys.exit(2)
709 return False
710
711
712 def matches_gitignore(subpath: str, fscache: FileSystemCache, verbose: bool) -> bool:
713 dir, _ = os.path.split(subpath)
714 for gi_path, gi_spec in find_gitignores(dir):
715 relative_path = os.path.relpath(subpath, gi_path)
716 if fscache.isdir(relative_path):
717 relative_path = relative_path + "/"
718 if gi_spec.match_file(relative_path):
719 if verbose:
720 print(
721 f"TRACE: Excluding {relative_path} (matches .gitignore) in {gi_path}",
722 file=sys.stderr,
723 )
724 return True
725 return False
726
727
728 @functools.lru_cache
729 def find_gitignores(dir: str) -> list[tuple[str, GitIgnoreSpec]]:
730 parent_dir = os.path.dirname(dir)
731 if parent_dir == dir or os.path.exists(os.path.join(dir, ".git")):
732 parent_gitignores = []
733 git_info_exclude = os.path.join(dir, ".git", "info", "exclude")
734 if os.path.isfile(git_info_exclude):
735 with open(git_info_exclude) as f:
736 exclude_lines = f.readlines()
737 try:
738 parent_gitignores = [(dir, GitIgnoreSpec.from_lines("gitignore", exclude_lines))]
739 except GitIgnorePatternError:
740 print(f"error: could not parse {git_info_exclude}", file=sys.stderr)
741 else:
742 parent_gitignores = find_gitignores(parent_dir)
743
744 gitignore = os.path.join(dir, ".gitignore")
745 if os.path.isfile(gitignore):
746 with open(gitignore) as f:
747 lines = f.readlines()
748 try:
749 return parent_gitignores + [(dir, GitIgnoreSpec.from_lines("gitignore", lines))]
750 except GitIgnorePatternError:
751 print(f"error: could not parse {gitignore}", file=sys.stderr)
752 return parent_gitignores
753 return parent_gitignores
754
755
756 def is_init_file(path: str) -> bool:
757 return os.path.basename(path) in ("__init__.py", "__init__.pyi")
758
759
760 def verify_module(fscache: FileSystemCache, id: str, path: str, prefix: str) -> bool:
761 """Check that all packages containing id have a __init__ file."""
762 if is_init_file(path):
763 path = os.path.dirname(path)
764 for i in range(id.count(".")):
765 path = os.path.dirname(path)
766 if not any(
767 fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix)
768 for extension in PYTHON_EXTENSIONS
769 ):
770 return False
771 return True
772
773
774 def highest_init_level(fscache: FileSystemCache, id: str, path: str, prefix: str) -> int:
775 """Compute the highest level where an __init__ file is found."""
776 if is_init_file(path):
777 path = os.path.dirname(path)
778 level = 0
779 for i in range(id.count(".")):
780 path = os.path.dirname(path)
781 if any(
782 fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix)
783 for extension in PYTHON_EXTENSIONS
784 ):
785 level = i + 1
786 return level
787
788
789 def mypy_path() -> list[str]:
790 path_env = os.getenv("MYPYPATH")
791 if not path_env:
792 return []
793 return path_env.split(os.pathsep)
794
795
796 def default_lib_path(
797 data_dir: str, pyversion: tuple[int, int], custom_typeshed_dir: str | None
798 ) -> list[str]:
799 """Return default standard library search paths. Guaranteed to be normalised."""
800
801 data_dir = os.path.abspath(data_dir)
802 path: list[str] = []
803
804 if custom_typeshed_dir:
805 custom_typeshed_dir = os.path.abspath(custom_typeshed_dir)
806 typeshed_dir = os.path.join(custom_typeshed_dir, "stdlib")
807 mypy_extensions_dir = os.path.join(custom_typeshed_dir, "stubs", "mypy-extensions")
808 librt_dir = os.path.join(custom_typeshed_dir, "stubs", "librt")
809 versions_file = os.path.join(typeshed_dir, "VERSIONS")
810 if not os.path.isdir(typeshed_dir) or not os.path.isfile(versions_file):
811 print(
812 "error: --custom-typeshed-dir does not point to a valid typeshed ({})".format(
813 custom_typeshed_dir
814 ),
815 file=sys.stderr,
816 )
817 sys.exit(2)
818 else:
819 auto = os.path.join(data_dir, "stubs-auto")
820 if os.path.isdir(auto):
821 data_dir = auto
822 typeshed_dir = os.path.join(data_dir, "typeshed", "stdlib")
823 mypy_extensions_dir = os.path.join(data_dir, "typeshed", "stubs", "mypy-extensions")
824 librt_dir = os.path.join(data_dir, "typeshed", "stubs", "librt")
825 path.append(typeshed_dir)
826
827 # Get mypy-extensions and librt stubs from typeshed, since we treat them as
828 # "internal" libraries, similar to typing and typing-extensions.
829 path.append(mypy_extensions_dir)
830 path.append(librt_dir)
831
832 # Add fallback path that can be used if we have a broken installation.
833 if sys.platform != "win32":
834 path.append("/usr/local/lib/mypy")
835 if not path:
836 print(
837 "Could not resolve typeshed subdirectories. Your mypy install is broken.\n"
838 "Python executable is located at {}.\nMypy located at {}".format(
839 sys.executable, data_dir
840 ),
841 file=sys.stderr,
842 )
843 sys.exit(1)
844 return path
845
846
847 @functools.cache
848 def get_search_dirs(python_executable: str | None) -> tuple[list[str], list[str]]:
849 """Find package directories for given python. Guaranteed to return absolute paths.
850
851 This runs a subprocess call, which generates a list of the directories in sys.path.
852 To avoid repeatedly calling a subprocess (which can be slow!) we
853 lru_cache the results.
854 """
855
856 if python_executable is None:
857 return ([], [])
858 elif python_executable == sys.executable:
859 # Use running Python's package dirs
860 sys_path, site_packages = pyinfo.getsearchdirs()
861 else:
862 # Use subprocess to get the package directory of given Python
863 # executable
864 env = {**dict(os.environ), "PYTHONSAFEPATH": "1"}
865 try:
866 sys_path, site_packages = ast.literal_eval(
867 subprocess.check_output(
868 [python_executable, pyinfo.__file__, "getsearchdirs"],
869 env=env,
870 stderr=subprocess.PIPE,
871 ).decode()
872 )
873 except subprocess.CalledProcessError as err:
874 print(err.stderr)
875 print(err.stdout)
876 raise
877 except OSError as err:
878 assert err.errno is not None
879 reason = os.strerror(err.errno)
880 raise CompileError(
881 [f"mypy: Invalid python executable '{python_executable}': {reason}"]
882 ) from err
883 return sys_path, site_packages
884
885
886 def compute_search_paths(
887 sources: list[BuildSource], options: Options, data_dir: str, alt_lib_path: str | None = None
888 ) -> SearchPaths:
889 """Compute the search paths as specified in PEP 561.
890
891 There are the following 4 members created:
892 - User code (from `sources`)
893 - MYPYPATH (set either via config or environment variable)
894 - installed package directories (which will later be split into stub-only and inline)
895 - typeshed
896 """
897 # Determine the default module search path.
898 lib_path = collections.deque(
899 default_lib_path(
900 data_dir, options.python_version, custom_typeshed_dir=options.custom_typeshed_dir
901 )
902 )
903
904 if options.use_builtins_fixtures:
905 # Use stub builtins (to speed up test cases and to make them easier to
906 # debug). This is a test-only feature, so assume our files are laid out
907 # as in the source tree.
908 # We also need to allow overriding where to look for it. Argh.
909 root_dir = os.getenv("MYPY_TEST_PREFIX", None)
910 if not root_dir:
911 root_dir = os.path.dirname(os.path.dirname(__file__))
912 root_dir = os.path.abspath(root_dir)
913 lib_path.appendleft(os.path.join(root_dir, "test-data", "unit", "lib-stub"))
914 # alt_lib_path is used by some tests to bypass the normal lib_path mechanics.
915 # If we don't have one, grab directories of source files.
916 python_path: list[str] = []
917 if not alt_lib_path:
918 for source in sources:
919 # Include directory of the program file in the module search path.
920 if source.base_dir:
921 dir = source.base_dir
922 if dir not in python_path:
923 python_path.append(dir)
924
925 # Do this even if running as a file, for sanity (mainly because with
926 # multiple builds, there could be a mix of files/modules, so its easier
927 # to just define the semantics that we always add the current director
928 # to the lib_path
929 # TODO: Don't do this in some cases; for motivation see see
930 # https://github.com/python/mypy/issues/4195#issuecomment-341915031
931 if options.bazel:
932 dir = "."
933 else:
934 dir = os.getcwd()
935 if dir not in lib_path:
936 python_path.insert(0, dir)
937
938 # Start with a MYPYPATH environment variable at the front of the mypy_path, if defined.
939 mypypath = mypy_path()
940
941 # Add a config-defined mypy path.
942 mypypath.extend(options.mypy_path)
943
944 # If provided, insert the caller-supplied extra module path to the
945 # beginning (highest priority) of the search path.
946 if alt_lib_path:
947 mypypath.insert(0, alt_lib_path)
948
949 sys_path, site_packages = get_search_dirs(options.python_executable)
950 # We only use site packages for this check
951 for site in site_packages:
952 assert site not in lib_path
953 if (
954 site in mypypath
955 or any(p.startswith(site + os.path.sep) for p in mypypath)
956 or (os.path.altsep and any(p.startswith(site + os.path.altsep) for p in mypypath))
957 ):
958 print(f"{site} is in the MYPYPATH. Please remove it.", file=sys.stderr)
959 print(
960 "See https://mypy.readthedocs.io/en/stable/running_mypy.html"
961 "#how-mypy-handles-imports for more info",
962 file=sys.stderr,
963 )
964 sys.exit(1)
965
966 return SearchPaths(
967 python_path=tuple(reversed(python_path)),
968 mypy_path=tuple(mypypath),
969 package_path=tuple(sys_path + site_packages),
970 typeshed_path=tuple(lib_path),
971 )
972
973
974 def load_stdlib_py_versions(custom_typeshed_dir: str | None) -> StdlibVersions:
975 """Return dict with minimum and maximum Python versions of stdlib modules.
976
977 The contents look like
978 {..., 'secrets': ((3, 6), None), 'symbol': ((2, 7), (3, 9)), ...}
979
980 None means there is no maximum version.
981 """
982 typeshed_dir = custom_typeshed_dir or os_path_join(os.path.dirname(__file__), "typeshed")
983 stdlib_dir = os_path_join(typeshed_dir, "stdlib")
984 result = {}
985
986 versions_path = os_path_join(stdlib_dir, "VERSIONS")
987 assert os.path.isfile(versions_path), (custom_typeshed_dir, versions_path, __file__)
988 with open(versions_path) as f:
989 for line in f:
990 line = line.split("#")[0].strip()
991 if line == "":
992 continue
993 module, version_range = line.split(":")
994 versions = version_range.split("-")
995 min_version = parse_version(versions[0])
996 max_version = (
997 parse_version(versions[1]) if len(versions) >= 2 and versions[1].strip() else None
998 )
999 result[module] = min_version, max_version
1000 return result
1001
1002
1003 def parse_version(version: str) -> tuple[int, int]:
1004 major, minor = version.strip().split(".")
1005 return int(major), int(minor)
1006
1007
1008 def typeshed_py_version(options: Options) -> tuple[int, int]:
1009 """Return Python version used for checking whether module supports typeshed."""
1010 return max(options.python_version, (3, 10))