discovery.py 20 KB

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