expand.py 16 KB

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