discovery.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. """Automatic discovery of Python modules and packages (for inclusion in the
  2. distribution) and other config values.
  3. For the purposes of this module, the following nomenclature is used:
  4. - "src-layout": a directory representing a Python project that contains a "src"
  5. folder. Everything under the "src" folder is meant to be included in the
  6. distribution when packaging the project. Example::
  7. .
  8. ├── tox.ini
  9. ├── pyproject.toml
  10. └── src/
  11. └── mypkg/
  12. ├── __init__.py
  13. ├── mymodule.py
  14. └── my_data_file.txt
  15. - "flat-layout": a Python project that does not use "src-layout" but instead
  16. have a directory under the project root for each package::
  17. .
  18. ├── tox.ini
  19. ├── pyproject.toml
  20. └── mypkg/
  21. ├── __init__.py
  22. ├── mymodule.py
  23. └── my_data_file.txt
  24. - "single-module": a project that contains a single Python script direct under
  25. the project root (no directory used)::
  26. .
  27. ├── tox.ini
  28. ├── pyproject.toml
  29. └── mymodule.py
  30. """
  31. import itertools
  32. import os
  33. from fnmatch import fnmatchcase
  34. from glob import glob
  35. from pathlib import Path
  36. from typing import (
  37. TYPE_CHECKING,
  38. Dict,
  39. Iterable,
  40. Iterator,
  41. List,
  42. Mapping,
  43. Optional,
  44. Tuple,
  45. Union,
  46. )
  47. import _distutils_hack.override # noqa: F401
  48. from distutils import log
  49. from distutils.util import convert_path
  50. _Path = Union[str, os.PathLike]
  51. StrIter = Iterator[str]
  52. chain_iter = itertools.chain.from_iterable
  53. if TYPE_CHECKING:
  54. from setuptools import Distribution # noqa
  55. def _valid_name(path: _Path) -> bool:
  56. # Ignore invalid names that cannot be imported directly
  57. return os.path.basename(path).isidentifier()
  58. class _Filter:
  59. """
  60. Given a list of patterns, create a callable that will be true only if
  61. the input matches at least one of the patterns.
  62. """
  63. def __init__(self, *patterns: str):
  64. self._patterns = dict.fromkeys(patterns)
  65. def __call__(self, item: str) -> bool:
  66. return any(fnmatchcase(item, pat) for pat in self._patterns)
  67. def __contains__(self, item: str) -> bool:
  68. return item in self._patterns
  69. class _Finder:
  70. """Base class that exposes functionality for module/package finders"""
  71. ALWAYS_EXCLUDE: Tuple[str, ...] = ()
  72. DEFAULT_EXCLUDE: Tuple[str, ...] = ()
  73. @classmethod
  74. def find(
  75. cls,
  76. where: _Path = '.',
  77. exclude: Iterable[str] = (),
  78. include: Iterable[str] = ('*',),
  79. ) -> List[str]:
  80. """Return a list of all Python items (packages or modules, depending on
  81. the finder implementation) found within directory 'where'.
  82. 'where' is the root directory which will be searched.
  83. It should be supplied as a "cross-platform" (i.e. URL-style) path;
  84. it will be converted to the appropriate local path syntax.
  85. 'exclude' is a sequence of names to exclude; '*' can be used
  86. as a wildcard in the names.
  87. When finding packages, 'foo.*' will exclude all subpackages of 'foo'
  88. (but not 'foo' itself).
  89. 'include' is a sequence of names to include.
  90. If it's specified, only the named items will be included.
  91. If it's not specified, all found items will be included.
  92. 'include' can contain shell style wildcard patterns just like
  93. 'exclude'.
  94. """
  95. exclude = exclude or cls.DEFAULT_EXCLUDE
  96. return list(
  97. cls._find_iter(
  98. convert_path(str(where)),
  99. _Filter(*cls.ALWAYS_EXCLUDE, *exclude),
  100. _Filter(*include),
  101. )
  102. )
  103. @classmethod
  104. def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
  105. raise NotImplementedError
  106. class PackageFinder(_Finder):
  107. """
  108. Generate a list of all Python packages found within a directory
  109. """
  110. ALWAYS_EXCLUDE = ("ez_setup", "*__pycache__")
  111. @classmethod
  112. def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
  113. """
  114. All the packages found in 'where' that pass the 'include' filter, but
  115. not the 'exclude' filter.
  116. """
  117. for root, dirs, files in os.walk(str(where), followlinks=True):
  118. # Copy dirs to iterate over it, then empty dirs.
  119. all_dirs = dirs[:]
  120. dirs[:] = []
  121. for dir in all_dirs:
  122. full_path = os.path.join(root, dir)
  123. rel_path = os.path.relpath(full_path, where)
  124. package = rel_path.replace(os.path.sep, '.')
  125. # Skip directory trees that are not valid packages
  126. if '.' in dir or not cls._looks_like_package(full_path, package):
  127. continue
  128. # Should this package be included?
  129. if include(package) and not exclude(package):
  130. yield package
  131. # Early pruning if there is nothing else to be scanned
  132. if f"{package}*" in exclude or f"{package}.*" in exclude:
  133. continue
  134. # Keep searching subdirectories, as there may be more packages
  135. # down there, even if the parent was excluded.
  136. dirs.append(dir)
  137. @staticmethod
  138. def _looks_like_package(path: _Path, _package_name: str) -> bool:
  139. """Does a directory look like a package?"""
  140. return os.path.isfile(os.path.join(path, '__init__.py'))
  141. class PEP420PackageFinder(PackageFinder):
  142. @staticmethod
  143. def _looks_like_package(_path: _Path, _package_name: str) -> bool:
  144. return True
  145. class ModuleFinder(_Finder):
  146. """Find isolated Python modules.
  147. This function will **not** recurse subdirectories.
  148. """
  149. @classmethod
  150. def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:
  151. for file in glob(os.path.join(where, "*.py")):
  152. module, _ext = os.path.splitext(os.path.basename(file))
  153. if not cls._looks_like_module(module):
  154. continue
  155. if include(module) and not exclude(module):
  156. yield module
  157. _looks_like_module = staticmethod(_valid_name)
  158. # We have to be extra careful in the case of flat layout to not include files
  159. # and directories not meant for distribution (e.g. tool-related)
  160. class FlatLayoutPackageFinder(PEP420PackageFinder):
  161. _EXCLUDE = (
  162. "ci",
  163. "bin",
  164. "debian",
  165. "doc",
  166. "docs",
  167. "documentation",
  168. "manpages",
  169. "news",
  170. "newsfragments",
  171. "changelog",
  172. "test",
  173. "tests",
  174. "unit_test",
  175. "unit_tests",
  176. "example",
  177. "examples",
  178. "scripts",
  179. "tools",
  180. "util",
  181. "utils",
  182. "python",
  183. "build",
  184. "dist",
  185. "venv",
  186. "env",
  187. "requirements",
  188. # ---- Task runners / Build tools ----
  189. "tasks", # invoke
  190. "fabfile", # fabric
  191. "site_scons", # SCons
  192. # ---- Other tools ----
  193. "benchmark",
  194. "benchmarks",
  195. "exercise",
  196. "exercises",
  197. "htmlcov", # Coverage.py
  198. # ---- Hidden directories/Private packages ----
  199. "[._]*",
  200. )
  201. DEFAULT_EXCLUDE = tuple(chain_iter((p, f"{p}.*") for p in _EXCLUDE))
  202. """Reserved package names"""
  203. @staticmethod
  204. def _looks_like_package(_path: _Path, package_name: str) -> bool:
  205. names = package_name.split('.')
  206. # Consider PEP 561
  207. root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs")
  208. return root_pkg_is_valid and all(name.isidentifier() for name in names[1:])
  209. class FlatLayoutModuleFinder(ModuleFinder):
  210. DEFAULT_EXCLUDE = (
  211. "setup",
  212. "conftest",
  213. "test",
  214. "tests",
  215. "example",
  216. "examples",
  217. "build",
  218. # ---- Task runners ----
  219. "toxfile",
  220. "noxfile",
  221. "pavement",
  222. "dodo",
  223. "tasks",
  224. "fabfile",
  225. # ---- Other tools ----
  226. "[Ss][Cc]onstruct", # SCons
  227. "conanfile", # Connan: C/C++ build tool
  228. "manage", # Django
  229. "benchmark",
  230. "benchmarks",
  231. "exercise",
  232. "exercises",
  233. # ---- Hidden files/Private modules ----
  234. "[._]*",
  235. )
  236. """Reserved top-level module names"""
  237. def _find_packages_within(root_pkg: str, pkg_dir: _Path) -> List[str]:
  238. nested = PEP420PackageFinder.find(pkg_dir)
  239. return [root_pkg] + [".".join((root_pkg, n)) for n in nested]
  240. class ConfigDiscovery:
  241. """Fill-in metadata and options that can be automatically derived
  242. (from other metadata/options, the file system or conventions)
  243. """
  244. def __init__(self, distribution: "Distribution"):
  245. self.dist = distribution
  246. self._called = False
  247. self._disabled = False
  248. self._skip_ext_modules = False
  249. def _disable(self):
  250. """Internal API to disable automatic discovery"""
  251. self._disabled = True
  252. def _ignore_ext_modules(self):
  253. """Internal API to disregard ext_modules.
  254. Normally auto-discovery would not be triggered if ``ext_modules`` are set
  255. (this is done for backward compatibility with existing packages relying on
  256. ``setup.py`` or ``setup.cfg``). However, ``setuptools`` can call this function
  257. to ignore given ``ext_modules`` and proceed with the auto-discovery if
  258. ``packages`` and ``py_modules`` are not given (e.g. when using pyproject.toml
  259. metadata).
  260. """
  261. self._skip_ext_modules = True
  262. @property
  263. def _root_dir(self) -> _Path:
  264. # The best is to wait until `src_root` is set in dist, before using _root_dir.
  265. return self.dist.src_root or os.curdir
  266. @property
  267. def _package_dir(self) -> Dict[str, str]:
  268. if self.dist.package_dir is None:
  269. return {}
  270. return self.dist.package_dir
  271. def __call__(self, force=False, name=True, ignore_ext_modules=False):
  272. """Automatically discover missing configuration fields
  273. and modifies the given ``distribution`` object in-place.
  274. Note that by default this will only have an effect the first time the
  275. ``ConfigDiscovery`` object is called.
  276. To repeatedly invoke automatic discovery (e.g. when the project
  277. directory changes), please use ``force=True`` (or create a new
  278. ``ConfigDiscovery`` instance).
  279. """
  280. if force is False and (self._called or self._disabled):
  281. # Avoid overhead of multiple calls
  282. return
  283. self._analyse_package_layout(ignore_ext_modules)
  284. if name:
  285. self.analyse_name() # depends on ``packages`` and ``py_modules``
  286. self._called = True
  287. def _explicitly_specified(self, ignore_ext_modules: bool) -> bool:
  288. """``True`` if the user has specified some form of package/module listing"""
  289. ignore_ext_modules = ignore_ext_modules or self._skip_ext_modules
  290. ext_modules = not (self.dist.ext_modules is None or ignore_ext_modules)
  291. return (
  292. self.dist.packages is not None
  293. or self.dist.py_modules is not None
  294. or ext_modules
  295. or hasattr(self.dist, "configuration")
  296. and self.dist.configuration
  297. # ^ Some projects use numpy.distutils.misc_util.Configuration
  298. )
  299. def _analyse_package_layout(self, ignore_ext_modules: bool) -> bool:
  300. if self._explicitly_specified(ignore_ext_modules):
  301. # For backward compatibility, just try to find modules/packages
  302. # when nothing is given
  303. return True
  304. log.debug(
  305. "No `packages` or `py_modules` configuration, performing "
  306. "automatic discovery."
  307. )
  308. return (
  309. self._analyse_explicit_layout()
  310. or self._analyse_src_layout()
  311. # flat-layout is the trickiest for discovery so it should be last
  312. or self._analyse_flat_layout()
  313. )
  314. def _analyse_explicit_layout(self) -> bool:
  315. """The user can explicitly give a package layout via ``package_dir``"""
  316. package_dir = self._package_dir.copy() # don't modify directly
  317. package_dir.pop("", None) # This falls under the "src-layout" umbrella
  318. root_dir = self._root_dir
  319. if not package_dir:
  320. return False
  321. log.debug(f"`explicit-layout` detected -- analysing {package_dir}")
  322. pkgs = chain_iter(
  323. _find_packages_within(pkg, os.path.join(root_dir, parent_dir))
  324. for pkg, parent_dir in package_dir.items()
  325. )
  326. self.dist.packages = list(pkgs)
  327. log.debug(f"discovered packages -- {self.dist.packages}")
  328. return True
  329. def _analyse_src_layout(self) -> bool:
  330. """Try to find all packages or modules under the ``src`` directory
  331. (or anything pointed by ``package_dir[""]``).
  332. The "src-layout" is relatively safe for automatic discovery.
  333. We assume that everything within is meant to be included in the
  334. distribution.
  335. If ``package_dir[""]`` is not given, but the ``src`` directory exists,
  336. this function will set ``package_dir[""] = "src"``.
  337. """
  338. package_dir = self._package_dir
  339. src_dir = os.path.join(self._root_dir, package_dir.get("", "src"))
  340. if not os.path.isdir(src_dir):
  341. return False
  342. log.debug(f"`src-layout` detected -- analysing {src_dir}")
  343. package_dir.setdefault("", os.path.basename(src_dir))
  344. self.dist.package_dir = package_dir # persist eventual modifications
  345. self.dist.packages = PEP420PackageFinder.find(src_dir)
  346. self.dist.py_modules = ModuleFinder.find(src_dir)
  347. log.debug(f"discovered packages -- {self.dist.packages}")
  348. log.debug(f"discovered py_modules -- {self.dist.py_modules}")
  349. return True
  350. def _analyse_flat_layout(self) -> bool:
  351. """Try to find all packages and modules under the project root.
  352. Since the ``flat-layout`` is more dangerous in terms of accidentally including
  353. extra files/directories, this function is more conservative and will raise an
  354. error if multiple packages or modules are found.
  355. This assumes that multi-package dists are uncommon and refuse to support that
  356. use case in order to be able to prevent unintended errors.
  357. """
  358. log.debug(f"`flat-layout` detected -- analysing {self._root_dir}")
  359. return self._analyse_flat_packages() or self._analyse_flat_modules()
  360. def _analyse_flat_packages(self) -> bool:
  361. self.dist.packages = FlatLayoutPackageFinder.find(self._root_dir)
  362. top_level = remove_nested_packages(remove_stubs(self.dist.packages))
  363. log.debug(f"discovered packages -- {self.dist.packages}")
  364. self._ensure_no_accidental_inclusion(top_level, "packages")
  365. return bool(top_level)
  366. def _analyse_flat_modules(self) -> bool:
  367. self.dist.py_modules = FlatLayoutModuleFinder.find(self._root_dir)
  368. log.debug(f"discovered py_modules -- {self.dist.py_modules}")
  369. self._ensure_no_accidental_inclusion(self.dist.py_modules, "modules")
  370. return bool(self.dist.py_modules)
  371. def _ensure_no_accidental_inclusion(self, detected: List[str], kind: str):
  372. if len(detected) > 1:
  373. from inspect import cleandoc
  374. from setuptools.errors import PackageDiscoveryError
  375. msg = f"""Multiple top-level {kind} discovered in a flat-layout: {detected}.
  376. To avoid accidental inclusion of unwanted files or directories,
  377. setuptools will not proceed with this build.
  378. If you are trying to create a single distribution with multiple {kind}
  379. on purpose, you should not rely on automatic discovery.
  380. Instead, consider the following options:
  381. 1. set up custom discovery (`find` directive with `include` or `exclude`)
  382. 2. use a `src-layout`
  383. 3. explicitly set `py_modules` or `packages` with a list of names
  384. To find more information, look for "package discovery" on setuptools docs.
  385. """
  386. raise PackageDiscoveryError(cleandoc(msg))
  387. def analyse_name(self):
  388. """The packages/modules are the essential contribution of the author.
  389. Therefore the name of the distribution can be derived from them.
  390. """
  391. if self.dist.metadata.name or self.dist.name:
  392. # get_name() is not reliable (can return "UNKNOWN")
  393. return None
  394. log.debug("No `name` configuration, performing automatic discovery")
  395. name = (
  396. self._find_name_single_package_or_module()
  397. or self._find_name_from_packages()
  398. )
  399. if name:
  400. self.dist.metadata.name = name
  401. def _find_name_single_package_or_module(self) -> Optional[str]:
  402. """Exactly one module or package"""
  403. for field in ('packages', 'py_modules'):
  404. items = getattr(self.dist, field, None) or []
  405. if items and len(items) == 1:
  406. log.debug(f"Single module/package detected, name: {items[0]}")
  407. return items[0]
  408. return None
  409. def _find_name_from_packages(self) -> Optional[str]:
  410. """Try to find the root package that is not a PEP 420 namespace"""
  411. if not self.dist.packages:
  412. return None
  413. packages = remove_stubs(sorted(self.dist.packages, key=len))
  414. package_dir = self.dist.package_dir or {}
  415. parent_pkg = find_parent_package(packages, package_dir, self._root_dir)
  416. if parent_pkg:
  417. log.debug(f"Common parent package detected, name: {parent_pkg}")
  418. return parent_pkg
  419. log.warn("No parent package detected, impossible to derive `name`")
  420. return None
  421. def remove_nested_packages(packages: List[str]) -> List[str]:
  422. """Remove nested packages from a list of packages.
  423. >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
  424. ['a']
  425. >>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"])
  426. ['a', 'b', 'c.d', 'g.h']
  427. """
  428. pkgs = sorted(packages, key=len)
  429. top_level = pkgs[:]
  430. size = len(pkgs)
  431. for i, name in enumerate(reversed(pkgs)):
  432. if any(name.startswith(f"{other}.") for other in top_level):
  433. top_level.pop(size - i - 1)
  434. return top_level
  435. def remove_stubs(packages: List[str]) -> List[str]:
  436. """Remove type stubs (:pep:`561`) from a list of packages.
  437. >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"])
  438. ['a', 'a.b', 'b']
  439. """
  440. return [pkg for pkg in packages if not pkg.split(".")[0].endswith("-stubs")]
  441. def find_parent_package(
  442. packages: List[str], package_dir: Mapping[str, str], root_dir: _Path
  443. ) -> Optional[str]:
  444. """Find the parent package that is not a namespace."""
  445. packages = sorted(packages, key=len)
  446. common_ancestors = []
  447. for i, name in enumerate(packages):
  448. if not all(n.startswith(f"{name}.") for n in packages[i + 1 :]):
  449. # Since packages are sorted by length, this condition is able
  450. # to find a list of all common ancestors.
  451. # When there is divergence (e.g. multiple root packages)
  452. # the list will be empty
  453. break
  454. common_ancestors.append(name)
  455. for name in common_ancestors:
  456. pkg_path = find_package_path(name, package_dir, root_dir)
  457. init = os.path.join(pkg_path, "__init__.py")
  458. if os.path.isfile(init):
  459. return name
  460. return None
  461. def find_package_path(
  462. name: str, package_dir: Mapping[str, str], root_dir: _Path
  463. ) -> str:
  464. """Given a package name, return the path where it should be found on
  465. disk, considering the ``package_dir`` option.
  466. >>> path = find_package_path("my.pkg", {"": "root/is/nested"}, ".")
  467. >>> path.replace(os.sep, "/")
  468. './root/is/nested/my/pkg'
  469. >>> path = find_package_path("my.pkg", {"my": "root/is/nested"}, ".")
  470. >>> path.replace(os.sep, "/")
  471. './root/is/nested/pkg'
  472. >>> path = find_package_path("my.pkg", {"my.pkg": "root/is/nested"}, ".")
  473. >>> path.replace(os.sep, "/")
  474. './root/is/nested'
  475. >>> path = find_package_path("other.pkg", {"my.pkg": "root/is/nested"}, ".")
  476. >>> path.replace(os.sep, "/")
  477. './other/pkg'
  478. """
  479. parts = name.split(".")
  480. for i in range(len(parts), 0, -1):
  481. # Look backwards, the most specific package_dir first
  482. partial_name = ".".join(parts[:i])
  483. if partial_name in package_dir:
  484. parent = package_dir[partial_name]
  485. return os.path.join(root_dir, parent, *parts[i:])
  486. parent = package_dir.get("") or ""
  487. return os.path.join(root_dir, *parent.split("/"), *parts)
  488. def construct_package_dir(packages: List[str], package_path: _Path) -> Dict[str, str]:
  489. parent_pkgs = remove_nested_packages(packages)
  490. prefix = Path(package_path).parts
  491. return {pkg: "/".join([*prefix, *pkg.split(".")]) for pkg in parent_pkgs}