expand.py 16 KB

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