find_sources.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """Routines for finding the sources that mypy will check"""
  2. from __future__ import annotations
  3. import functools
  4. import os
  5. from typing import Final, Sequence
  6. from mypy.fscache import FileSystemCache
  7. from mypy.modulefinder import PYTHON_EXTENSIONS, BuildSource, matches_exclude, mypy_path
  8. from mypy.options import Options
  9. PY_EXTENSIONS: Final = tuple(PYTHON_EXTENSIONS)
  10. class InvalidSourceList(Exception):
  11. """Exception indicating a problem in the list of sources given to mypy."""
  12. def create_source_list(
  13. paths: Sequence[str],
  14. options: Options,
  15. fscache: FileSystemCache | None = None,
  16. allow_empty_dir: bool = False,
  17. ) -> list[BuildSource]:
  18. """From a list of source files/directories, makes a list of BuildSources.
  19. Raises InvalidSourceList on errors.
  20. """
  21. fscache = fscache or FileSystemCache()
  22. finder = SourceFinder(fscache, options)
  23. sources = []
  24. for path in paths:
  25. path = os.path.normpath(path)
  26. if path.endswith(PY_EXTENSIONS):
  27. # Can raise InvalidSourceList if a directory doesn't have a valid module name.
  28. name, base_dir = finder.crawl_up(path)
  29. sources.append(BuildSource(path, name, None, base_dir))
  30. elif fscache.isdir(path):
  31. sub_sources = finder.find_sources_in_dir(path)
  32. if not sub_sources and not allow_empty_dir:
  33. raise InvalidSourceList(f"There are no .py[i] files in directory '{path}'")
  34. sources.extend(sub_sources)
  35. else:
  36. mod = os.path.basename(path) if options.scripts_are_modules else None
  37. sources.append(BuildSource(path, mod, None))
  38. return sources
  39. def keyfunc(name: str) -> tuple[bool, int, str]:
  40. """Determines sort order for directory listing.
  41. The desirable properties are:
  42. 1) foo < foo.pyi < foo.py
  43. 2) __init__.py[i] < foo
  44. """
  45. base, suffix = os.path.splitext(name)
  46. for i, ext in enumerate(PY_EXTENSIONS):
  47. if suffix == ext:
  48. return (base != "__init__", i, base)
  49. return (base != "__init__", -1, name)
  50. def normalise_package_base(root: str) -> str:
  51. if not root:
  52. root = os.curdir
  53. root = os.path.abspath(root)
  54. if root.endswith(os.sep):
  55. root = root[:-1]
  56. return root
  57. def get_explicit_package_bases(options: Options) -> list[str] | None:
  58. """Returns explicit package bases to use if the option is enabled, or None if disabled.
  59. We currently use MYPYPATH and the current directory as the package bases. In the future,
  60. when --namespace-packages is the default could also use the values passed with the
  61. --package-root flag, see #9632.
  62. Values returned are normalised so we can use simple string comparisons in
  63. SourceFinder.is_explicit_package_base
  64. """
  65. if not options.explicit_package_bases:
  66. return None
  67. roots = mypy_path() + options.mypy_path + [os.getcwd()]
  68. return [normalise_package_base(root) for root in roots]
  69. class SourceFinder:
  70. def __init__(self, fscache: FileSystemCache, options: Options) -> None:
  71. self.fscache = fscache
  72. self.explicit_package_bases = get_explicit_package_bases(options)
  73. self.namespace_packages = options.namespace_packages
  74. self.exclude = options.exclude
  75. self.verbosity = options.verbosity
  76. def is_explicit_package_base(self, path: str) -> bool:
  77. assert self.explicit_package_bases
  78. return normalise_package_base(path) in self.explicit_package_bases
  79. def find_sources_in_dir(self, path: str) -> list[BuildSource]:
  80. sources = []
  81. seen: set[str] = set()
  82. names = sorted(self.fscache.listdir(path), key=keyfunc)
  83. for name in names:
  84. # Skip certain names altogether
  85. if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."):
  86. continue
  87. subpath = os.path.join(path, name)
  88. if matches_exclude(subpath, self.exclude, self.fscache, self.verbosity >= 2):
  89. continue
  90. if self.fscache.isdir(subpath):
  91. sub_sources = self.find_sources_in_dir(subpath)
  92. if sub_sources:
  93. seen.add(name)
  94. sources.extend(sub_sources)
  95. else:
  96. stem, suffix = os.path.splitext(name)
  97. if stem not in seen and suffix in PY_EXTENSIONS:
  98. seen.add(stem)
  99. module, base_dir = self.crawl_up(subpath)
  100. sources.append(BuildSource(subpath, module, None, base_dir))
  101. return sources
  102. def crawl_up(self, path: str) -> tuple[str, str]:
  103. """Given a .py[i] filename, return module and base directory.
  104. For example, given "xxx/yyy/foo/bar.py", we might return something like:
  105. ("foo.bar", "xxx/yyy")
  106. If namespace packages is off, we crawl upwards until we find a directory without
  107. an __init__.py
  108. If namespace packages is on, we crawl upwards until the nearest explicit base directory.
  109. Failing that, we return one past the highest directory containing an __init__.py
  110. We won't crawl past directories with invalid package names.
  111. The base directory returned is an absolute path.
  112. """
  113. path = os.path.abspath(path)
  114. parent, filename = os.path.split(path)
  115. module_name = strip_py(filename) or filename
  116. parent_module, base_dir = self.crawl_up_dir(parent)
  117. if module_name == "__init__":
  118. return parent_module, base_dir
  119. # Note that module_name might not actually be a valid identifier, but that's okay
  120. # Ignoring this possibility sidesteps some search path confusion
  121. module = module_join(parent_module, module_name)
  122. return module, base_dir
  123. def crawl_up_dir(self, dir: str) -> tuple[str, str]:
  124. return self._crawl_up_helper(dir) or ("", dir)
  125. @functools.lru_cache # noqa: B019
  126. def _crawl_up_helper(self, dir: str) -> tuple[str, str] | None:
  127. """Given a directory, maybe returns module and base directory.
  128. We return a non-None value if we were able to find something clearly intended as a base
  129. directory (as adjudicated by being an explicit base directory or by containing a package
  130. with __init__.py).
  131. This distinction is necessary for namespace packages, so that we know when to treat
  132. ourselves as a subpackage.
  133. """
  134. # stop crawling if we're an explicit base directory
  135. if self.explicit_package_bases is not None and self.is_explicit_package_base(dir):
  136. return "", dir
  137. parent, name = os.path.split(dir)
  138. if name.endswith("-stubs"):
  139. name = name[:-6] # PEP-561 stub-only directory
  140. # recurse if there's an __init__.py
  141. init_file = self.get_init_file(dir)
  142. if init_file is not None:
  143. if not name.isidentifier():
  144. # in most cases the directory name is invalid, we'll just stop crawling upwards
  145. # but if there's an __init__.py in the directory, something is messed up
  146. raise InvalidSourceList(f"{name} is not a valid Python package name")
  147. # we're definitely a package, so we always return a non-None value
  148. mod_prefix, base_dir = self.crawl_up_dir(parent)
  149. return module_join(mod_prefix, name), base_dir
  150. # stop crawling if we're out of path components or our name is an invalid identifier
  151. if not name or not parent or not name.isidentifier():
  152. return None
  153. # stop crawling if namespace packages is off (since we don't have an __init__.py)
  154. if not self.namespace_packages:
  155. return None
  156. # at this point: namespace packages is on, we don't have an __init__.py and we're not an
  157. # explicit base directory
  158. result = self._crawl_up_helper(parent)
  159. if result is None:
  160. # we're not an explicit base directory and we don't have an __init__.py
  161. # and none of our parents are either, so return
  162. return None
  163. # one of our parents was an explicit base directory or had an __init__.py, so we're
  164. # definitely a subpackage! chain our name to the module.
  165. mod_prefix, base_dir = result
  166. return module_join(mod_prefix, name), base_dir
  167. def get_init_file(self, dir: str) -> str | None:
  168. """Check whether a directory contains a file named __init__.py[i].
  169. If so, return the file's name (with dir prefixed). If not, return None.
  170. This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS).
  171. """
  172. for ext in PY_EXTENSIONS:
  173. f = os.path.join(dir, "__init__" + ext)
  174. if self.fscache.isfile(f):
  175. return f
  176. if ext == ".py" and self.fscache.init_under_package_root(f):
  177. return f
  178. return None
  179. def module_join(parent: str, child: str) -> str:
  180. """Join module ids, accounting for a possibly empty parent."""
  181. if parent:
  182. return parent + "." + child
  183. return child
  184. def strip_py(arg: str) -> str | None:
  185. """Strip a trailing .py or .pyi suffix.
  186. Return None if no such suffix is found.
  187. """
  188. for ext in PY_EXTENSIONS:
  189. if arg.endswith(ext):
  190. return arg[: -len(ext)]
  191. return None