You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

615 lines
21 KiB

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