expand.py 16 KB

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