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.
 
 
 
 

453 rivejä
16 KiB

  1. """Utility functions to expand configuration directives or special values
  2. (such glob patterns).
  3. We can split the process of interpreting configuration files into 2 steps:
  4. 1. The parsing the file contents from strings to value objects
  5. that can be understand by Python (for example a string with a comma
  6. separated list of keywords into an actual Python list of strings).
  7. 2. The expansion (or post-processing) of these values according to the
  8. semantics ``setuptools`` assign to them (for example a configuration field
  9. with the ``file:`` directive should be expanded from a list of file paths to
  10. a single string with the contents of those files concatenated)
  11. This module focus on the second step, and therefore allow sharing the expansion
  12. functions among several configuration file formats.
  13. **PRIVATE MODULE**: API reserved for setuptools internal usage only.
  14. """
  15. from __future__ import annotations
  16. import ast
  17. import importlib
  18. import os
  19. import pathlib
  20. import sys
  21. from collections.abc import Iterable, Iterator, Mapping
  22. from configparser import ConfigParser
  23. from glob import iglob
  24. from importlib.machinery import ModuleSpec, all_suffixes
  25. from itertools import chain
  26. from pathlib import Path
  27. from types import ModuleType, TracebackType
  28. from typing import TYPE_CHECKING, Any, Callable, TypeVar
  29. from .. import _static
  30. from .._path import StrPath, same_path as _same_path
  31. from ..discovery import find_package_path
  32. from ..warnings import SetuptoolsWarning
  33. from distutils.errors import DistutilsOptionError
  34. if TYPE_CHECKING:
  35. from typing_extensions import Self
  36. from setuptools.dist import Distribution
  37. _K = TypeVar("_K")
  38. _V_co = TypeVar("_V_co", covariant=True)
  39. class StaticModule:
  40. """Proxy to a module object that avoids executing arbitrary code."""
  41. def __init__(self, name: str, spec: ModuleSpec) -> None:
  42. module = ast.parse(pathlib.Path(spec.origin).read_bytes()) # type: ignore[arg-type] # Let it raise an error on None
  43. vars(self).update(locals())
  44. del self.self
  45. def _find_assignments(self) -> Iterator[tuple[ast.AST, ast.AST]]:
  46. for statement in self.module.body:
  47. if isinstance(statement, ast.Assign):
  48. yield from ((target, statement.value) for target in statement.targets)
  49. elif isinstance(statement, ast.AnnAssign) and statement.value:
  50. yield (statement.target, statement.value)
  51. def __getattr__(self, attr: str):
  52. """Attempt to load an attribute "statically", via :func:`ast.literal_eval`."""
  53. try:
  54. return next(
  55. ast.literal_eval(value)
  56. for target, value in self._find_assignments()
  57. if isinstance(target, ast.Name) and target.id == attr
  58. )
  59. except Exception as e:
  60. raise AttributeError(f"{self.name} has no attribute {attr}") from e
  61. def glob_relative(
  62. patterns: Iterable[str], root_dir: StrPath | None = None
  63. ) -> list[str]:
  64. """Expand the list of glob patterns, but preserving relative paths.
  65. :param list[str] patterns: List of glob patterns
  66. :param str root_dir: Path to which globs should be relative
  67. (current directory by default)
  68. :rtype: list
  69. """
  70. glob_characters = {'*', '?', '[', ']', '{', '}'}
  71. expanded_values = []
  72. root_dir = root_dir or os.getcwd()
  73. for value in patterns:
  74. # Has globby characters?
  75. if any(char in value for char in glob_characters):
  76. # then expand the glob pattern while keeping paths *relative*:
  77. glob_path = os.path.abspath(os.path.join(root_dir, value))
  78. expanded_values.extend(
  79. sorted(
  80. os.path.relpath(path, root_dir).replace(os.sep, "/")
  81. for path in iglob(glob_path, recursive=True)
  82. )
  83. )
  84. else:
  85. # take the value as-is
  86. path = os.path.relpath(value, root_dir).replace(os.sep, "/")
  87. expanded_values.append(path)
  88. return expanded_values
  89. def read_files(
  90. filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None
  91. ) -> str:
  92. """Return the content of the files concatenated using ``\n`` as str
  93. This function is sandboxed and won't reach anything outside ``root_dir``
  94. (By default ``root_dir`` is the current directory).
  95. """
  96. from more_itertools import always_iterable
  97. root_dir = os.path.abspath(root_dir or os.getcwd())
  98. _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))
  99. return '\n'.join(
  100. _read_file(path)
  101. for path in _filter_existing_files(_filepaths)
  102. if _assert_local(path, root_dir)
  103. )
  104. def _filter_existing_files(filepaths: Iterable[StrPath]) -> Iterator[StrPath]:
  105. for path in filepaths:
  106. if os.path.isfile(path):
  107. yield path
  108. else:
  109. SetuptoolsWarning.emit(f"File {path!r} cannot be found")
  110. def _read_file(filepath: bytes | StrPath) -> str:
  111. with open(filepath, encoding='utf-8') as f:
  112. return f.read()
  113. def _assert_local(filepath: StrPath, root_dir: str):
  114. if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:
  115. msg = f"Cannot access {filepath!r} (or anything outside {root_dir!r})"
  116. raise DistutilsOptionError(msg)
  117. return True
  118. def read_attr(
  119. attr_desc: str,
  120. package_dir: Mapping[str, str] | None = None,
  121. root_dir: StrPath | None = None,
  122. ) -> Any:
  123. """Reads the value of an attribute from a module.
  124. This function will try to read the attributed statically first
  125. (via :func:`ast.literal_eval`), and only evaluate the module if it fails.
  126. Examples:
  127. read_attr("package.attr")
  128. read_attr("package.module.attr")
  129. :param str attr_desc: Dot-separated string describing how to reach the
  130. attribute (see examples above)
  131. :param dict[str, str] package_dir: Mapping of package names to their
  132. location in disk (represented by paths relative to ``root_dir``).
  133. :param str root_dir: Path to directory containing all the packages in
  134. ``package_dir`` (current directory by default).
  135. :rtype: str
  136. """
  137. root_dir = root_dir or os.getcwd()
  138. attrs_path = attr_desc.strip().split('.')
  139. attr_name = attrs_path.pop()
  140. module_name = '.'.join(attrs_path)
  141. module_name = module_name or '__init__'
  142. path = _find_module(module_name, package_dir, root_dir)
  143. spec = _find_spec(module_name, path)
  144. try:
  145. value = getattr(StaticModule(module_name, spec), attr_name)
  146. # XXX: Is marking as static contents coming from modules too optimistic?
  147. return _static.attempt_conversion(value)
  148. except Exception:
  149. # fallback to evaluate module
  150. module = _load_spec(spec, module_name)
  151. return getattr(module, attr_name)
  152. def _find_spec(module_name: str, module_path: StrPath | None) -> ModuleSpec:
  153. spec = importlib.util.spec_from_file_location(module_name, module_path)
  154. spec = spec or importlib.util.find_spec(module_name)
  155. if spec is None:
  156. raise ModuleNotFoundError(module_name)
  157. return spec
  158. def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:
  159. name = getattr(spec, "__name__", module_name)
  160. if name in sys.modules:
  161. return sys.modules[name]
  162. module = importlib.util.module_from_spec(spec)
  163. sys.modules[name] = module # cache (it also ensures `==` works on loaded items)
  164. assert spec.loader is not None
  165. spec.loader.exec_module(module)
  166. return module
  167. def _find_module(
  168. module_name: str, package_dir: Mapping[str, str] | None, root_dir: StrPath
  169. ) -> str | None:
  170. """Find the path to the module named ``module_name``,
  171. considering the ``package_dir`` in the build configuration and ``root_dir``.
  172. >>> tmp = getfixture('tmpdir')
  173. >>> _ = tmp.ensure("a/b/c.py")
  174. >>> _ = tmp.ensure("a/b/d/__init__.py")
  175. >>> r = lambda x: x.replace(str(tmp), "tmp").replace(os.sep, "/")
  176. >>> r(_find_module("a.b.c", None, tmp))
  177. 'tmp/a/b/c.py'
  178. >>> r(_find_module("f.g.h", {"": "1", "f": "2", "f.g": "3", "f.g.h": "a/b/d"}, tmp))
  179. 'tmp/a/b/d/__init__.py'
  180. """
  181. path_start = find_package_path(module_name, package_dir or {}, root_dir)
  182. candidates = chain.from_iterable(
  183. (f"{path_start}{ext}", os.path.join(path_start, f"__init__{ext}"))
  184. for ext in all_suffixes()
  185. )
  186. return next((x for x in candidates if os.path.isfile(x)), None)
  187. def resolve_class(
  188. qualified_class_name: str,
  189. package_dir: Mapping[str, str] | None = None,
  190. root_dir: StrPath | None = None,
  191. ) -> Callable:
  192. """Given a qualified class name, return the associated class object"""
  193. root_dir = root_dir or os.getcwd()
  194. idx = qualified_class_name.rfind('.')
  195. class_name = qualified_class_name[idx + 1 :]
  196. pkg_name = qualified_class_name[:idx]
  197. path = _find_module(pkg_name, package_dir, root_dir)
  198. module = _load_spec(_find_spec(pkg_name, path), pkg_name)
  199. return getattr(module, class_name)
  200. def cmdclass(
  201. values: dict[str, str],
  202. package_dir: Mapping[str, str] | None = None,
  203. root_dir: StrPath | None = None,
  204. ) -> dict[str, Callable]:
  205. """Given a dictionary mapping command names to strings for qualified class
  206. names, apply :func:`resolve_class` to the dict values.
  207. """
  208. return {k: resolve_class(v, package_dir, root_dir) for k, v in values.items()}
  209. def find_packages(
  210. *,
  211. namespaces=True,
  212. fill_package_dir: dict[str, str] | None = None,
  213. root_dir: StrPath | None = None,
  214. **kwargs,
  215. ) -> list[str]:
  216. """Works similarly to :func:`setuptools.find_packages`, but with all
  217. arguments given as keyword arguments. Moreover, ``where`` can be given
  218. as a list (the results will be simply concatenated).
  219. When the additional keyword argument ``namespaces`` is ``True``, it will
  220. behave like :func:`setuptools.find_namespace_packages`` (i.e. include
  221. implicit namespaces as per :pep:`420`).
  222. The ``where`` argument will be considered relative to ``root_dir`` (or the current
  223. working directory when ``root_dir`` is not given).
  224. If the ``fill_package_dir`` argument is passed, this function will consider it as a
  225. similar data structure to the ``package_dir`` configuration parameter add fill-in
  226. any missing package location.
  227. :rtype: list
  228. """
  229. from more_itertools import always_iterable, unique_everseen
  230. from setuptools.discovery import construct_package_dir
  231. # check "not namespaces" first due to python/mypy#6232
  232. if not namespaces:
  233. from setuptools.discovery import PackageFinder
  234. else:
  235. from setuptools.discovery import PEP420PackageFinder as PackageFinder
  236. root_dir = root_dir or os.curdir
  237. where = kwargs.pop('where', ['.'])
  238. packages: list[str] = []
  239. fill_package_dir = {} if fill_package_dir is None else fill_package_dir
  240. search = list(unique_everseen(always_iterable(where)))
  241. if len(search) == 1 and all(not _same_path(search[0], x) for x in (".", root_dir)):
  242. fill_package_dir.setdefault("", search[0])
  243. for path in search:
  244. package_path = _nest_path(root_dir, path)
  245. pkgs = PackageFinder.find(package_path, **kwargs)
  246. packages.extend(pkgs)
  247. if pkgs and not (
  248. fill_package_dir.get("") == path or os.path.samefile(package_path, root_dir)
  249. ):
  250. fill_package_dir.update(construct_package_dir(pkgs, path))
  251. return packages
  252. def _nest_path(parent: StrPath, path: StrPath) -> str:
  253. path = parent if path in {".", ""} else os.path.join(parent, path)
  254. return os.path.normpath(path)
  255. def version(value: Callable | Iterable[str | int] | str) -> str:
  256. """When getting the version directly from an attribute,
  257. it should be normalised to string.
  258. """
  259. _value = value() if callable(value) else value
  260. if isinstance(_value, str):
  261. return _value
  262. if hasattr(_value, '__iter__'):
  263. return '.'.join(map(str, _value))
  264. return f'{_value}'
  265. def canonic_package_data(package_data: dict) -> dict:
  266. if "*" in package_data:
  267. package_data[""] = package_data.pop("*")
  268. return package_data
  269. def canonic_data_files(
  270. data_files: list | dict, root_dir: StrPath | None = None
  271. ) -> list[tuple[str, list[str]]]:
  272. """For compatibility with ``setup.py``, ``data_files`` should be a list
  273. of pairs instead of a dict.
  274. This function also expands glob patterns.
  275. """
  276. if isinstance(data_files, list):
  277. return data_files
  278. return [
  279. (dest, glob_relative(patterns, root_dir))
  280. for dest, patterns in data_files.items()
  281. ]
  282. def entry_points(
  283. text: str, text_source: str = "entry-points"
  284. ) -> dict[str, dict[str, str]]:
  285. """Given the contents of entry-points file,
  286. process it into a 2-level dictionary (``dict[str, dict[str, str]]``).
  287. The first level keys are entry-point groups, the second level keys are
  288. entry-point names, and the second level values are references to objects
  289. (that correspond to the entry-point value).
  290. """
  291. # Using undocumented behaviour, see python/typeshed#12700
  292. parser = ConfigParser(default_section=None, delimiters=("=",)) # type: ignore[call-overload]
  293. parser.optionxform = str # case sensitive
  294. parser.read_string(text, text_source)
  295. groups = {k: dict(v.items()) for k, v in parser.items()}
  296. groups.pop(parser.default_section, None)
  297. return groups
  298. class EnsurePackagesDiscovered:
  299. """Some expand functions require all the packages to already be discovered before
  300. they run, e.g. :func:`read_attr`, :func:`resolve_class`, :func:`cmdclass`.
  301. Therefore in some cases we will need to run autodiscovery during the evaluation of
  302. the configuration. However, it is better to postpone calling package discovery as
  303. much as possible, because some parameters can influence it (e.g. ``package_dir``),
  304. and those might not have been processed yet.
  305. """
  306. def __init__(self, distribution: Distribution) -> None:
  307. self._dist = distribution
  308. self._called = False
  309. def __call__(self):
  310. """Trigger the automatic package discovery, if it is still necessary."""
  311. if not self._called:
  312. self._called = True
  313. self._dist.set_defaults(name=False) # Skip name, we can still be parsing
  314. def __enter__(self) -> Self:
  315. return self
  316. def __exit__(
  317. self,
  318. exc_type: type[BaseException] | None,
  319. exc_value: BaseException | None,
  320. traceback: TracebackType | None,
  321. ):
  322. if self._called:
  323. self._dist.set_defaults.analyse_name() # Now we can set a default name
  324. def _get_package_dir(self) -> Mapping[str, str]:
  325. self()
  326. pkg_dir = self._dist.package_dir
  327. return {} if pkg_dir is None else pkg_dir
  328. @property
  329. def package_dir(self) -> Mapping[str, str]:
  330. """Proxy to ``package_dir`` that may trigger auto-discovery when used."""
  331. return LazyMappingProxy(self._get_package_dir)
  332. class LazyMappingProxy(Mapping[_K, _V_co]):
  333. """Mapping proxy that delays resolving the target object, until really needed.
  334. >>> def obtain_mapping():
  335. ... print("Running expensive function!")
  336. ... return {"key": "value", "other key": "other value"}
  337. >>> mapping = LazyMappingProxy(obtain_mapping)
  338. >>> mapping["key"]
  339. Running expensive function!
  340. 'value'
  341. >>> mapping["other key"]
  342. 'other value'
  343. """
  344. def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None:
  345. self._obtain = obtain_mapping_value
  346. self._value: Mapping[_K, _V_co] | None = None
  347. def _target(self) -> Mapping[_K, _V_co]:
  348. if self._value is None:
  349. self._value = self._obtain()
  350. return self._value
  351. def __getitem__(self, key: _K) -> _V_co:
  352. return self._target()[key]
  353. def __len__(self) -> int:
  354. return len(self._target())
  355. def __iter__(self) -> Iterator[_K]:
  356. return iter(self._target())