_apply_pyprojecttoml.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. """Translation layer between pyproject config and setuptools distribution and
  2. metadata objects.
  3. The distribution and metadata objects are modeled after (an old version of)
  4. core metadata, therefore configs in the format specified for ``pyproject.toml``
  5. need to be processed before being applied.
  6. **PRIVATE MODULE**: API reserved for setuptools internal usage only.
  7. """
  8. import logging
  9. import os
  10. from collections.abc import Mapping
  11. from email.headerregistry import Address
  12. from functools import partial, reduce
  13. from inspect import cleandoc
  14. from itertools import chain
  15. from types import MappingProxyType
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Callable,
  20. Dict,
  21. List,
  22. Optional,
  23. Set,
  24. Tuple,
  25. Type,
  26. Union,
  27. cast,
  28. )
  29. from ..errors import RemovedConfigError
  30. from ..warnings import SetuptoolsWarning
  31. if TYPE_CHECKING:
  32. from setuptools._importlib import metadata # noqa
  33. from setuptools.dist import Distribution # noqa
  34. EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
  35. _Path = Union[os.PathLike, str]
  36. _DictOrStr = Union[dict, str]
  37. _CorrespFn = Callable[["Distribution", Any, _Path], None]
  38. _Correspondence = Union[str, _CorrespFn]
  39. _logger = logging.getLogger(__name__)
  40. def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution":
  41. """Apply configuration dict read with :func:`read_configuration`"""
  42. if not config:
  43. return dist # short-circuit unrelated pyproject.toml file
  44. root_dir = os.path.dirname(filename) or "."
  45. _apply_project_table(dist, config, root_dir)
  46. _apply_tool_table(dist, config, filename)
  47. current_directory = os.getcwd()
  48. os.chdir(root_dir)
  49. try:
  50. dist._finalize_requires()
  51. dist._finalize_license_files()
  52. finally:
  53. os.chdir(current_directory)
  54. return dist
  55. def _apply_project_table(dist: "Distribution", config: dict, root_dir: _Path):
  56. project_table = config.get("project", {}).copy()
  57. if not project_table:
  58. return # short-circuit
  59. _handle_missing_dynamic(dist, project_table)
  60. _unify_entry_points(project_table)
  61. for field, value in project_table.items():
  62. norm_key = json_compatible_key(field)
  63. corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
  64. if callable(corresp):
  65. corresp(dist, value, root_dir)
  66. else:
  67. _set_config(dist, corresp, value)
  68. def _apply_tool_table(dist: "Distribution", config: dict, filename: _Path):
  69. tool_table = config.get("tool", {}).get("setuptools", {})
  70. if not tool_table:
  71. return # short-circuit
  72. for field, value in tool_table.items():
  73. norm_key = json_compatible_key(field)
  74. if norm_key in TOOL_TABLE_REMOVALS:
  75. suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
  76. msg = f"""
  77. The parameter `tool.setuptools.{field}` was long deprecated
  78. and has been removed from `pyproject.toml`.
  79. """
  80. raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
  81. norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
  82. _set_config(dist, norm_key, value)
  83. _copy_command_options(config, dist, filename)
  84. def _handle_missing_dynamic(dist: "Distribution", project_table: dict):
  85. """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
  86. dynamic = set(project_table.get("dynamic", []))
  87. for field, getter in _PREVIOUSLY_DEFINED.items():
  88. if not (field in project_table or field in dynamic):
  89. value = getter(dist)
  90. if value:
  91. _MissingDynamic.emit(field=field, value=value)
  92. project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
  93. def json_compatible_key(key: str) -> str:
  94. """As defined in :pep:`566#json-compatible-metadata`"""
  95. return key.lower().replace("-", "_")
  96. def _set_config(dist: "Distribution", field: str, value: Any):
  97. setter = getattr(dist.metadata, f"set_{field}", None)
  98. if setter:
  99. setter(value)
  100. elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
  101. setattr(dist.metadata, field, value)
  102. else:
  103. setattr(dist, field, value)
  104. _CONTENT_TYPES = {
  105. ".md": "text/markdown",
  106. ".rst": "text/x-rst",
  107. ".txt": "text/plain",
  108. }
  109. def _guess_content_type(file: str) -> Optional[str]:
  110. _, ext = os.path.splitext(file.lower())
  111. if not ext:
  112. return None
  113. if ext in _CONTENT_TYPES:
  114. return _CONTENT_TYPES[ext]
  115. valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
  116. msg = f"only the following file extensions are recognized: {valid}."
  117. raise ValueError(f"Undefined content type for {file}, {msg}")
  118. def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: _Path):
  119. from setuptools.config import expand
  120. if isinstance(val, str):
  121. file: Union[str, list] = val
  122. text = expand.read_files(file, root_dir)
  123. ctype = _guess_content_type(val)
  124. else:
  125. file = val.get("file") or []
  126. text = val.get("text") or expand.read_files(file, root_dir)
  127. ctype = val["content-type"]
  128. _set_config(dist, "long_description", text)
  129. if ctype:
  130. _set_config(dist, "long_description_content_type", ctype)
  131. if file:
  132. dist._referenced_files.add(cast(str, file))
  133. def _license(dist: "Distribution", val: dict, root_dir: _Path):
  134. from setuptools.config import expand
  135. if "file" in val:
  136. _set_config(dist, "license", expand.read_files([val["file"]], root_dir))
  137. dist._referenced_files.add(val["file"])
  138. else:
  139. _set_config(dist, "license", val["text"])
  140. def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str):
  141. field = []
  142. email_field = []
  143. for person in val:
  144. if "name" not in person:
  145. email_field.append(person["email"])
  146. elif "email" not in person:
  147. field.append(person["name"])
  148. else:
  149. addr = Address(display_name=person["name"], addr_spec=person["email"])
  150. email_field.append(str(addr))
  151. if field:
  152. _set_config(dist, kind, ", ".join(field))
  153. if email_field:
  154. _set_config(dist, f"{kind}_email", ", ".join(email_field))
  155. def _project_urls(dist: "Distribution", val: dict, _root_dir):
  156. _set_config(dist, "project_urls", val)
  157. def _python_requires(dist: "Distribution", val: dict, _root_dir):
  158. from setuptools.extern.packaging.specifiers import SpecifierSet
  159. _set_config(dist, "python_requires", SpecifierSet(val))
  160. def _dependencies(dist: "Distribution", val: list, _root_dir):
  161. if getattr(dist, "install_requires", []):
  162. msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
  163. SetuptoolsWarning.emit(msg)
  164. dist.install_requires = val
  165. def _optional_dependencies(dist: "Distribution", val: dict, _root_dir):
  166. existing = getattr(dist, "extras_require", None) or {}
  167. dist.extras_require = {**existing, **val}
  168. def _unify_entry_points(project_table: dict):
  169. project = project_table
  170. entry_points = project.pop("entry-points", project.pop("entry_points", {}))
  171. renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
  172. for key, value in list(project.items()): # eager to allow modifications
  173. norm_key = json_compatible_key(key)
  174. if norm_key in renaming:
  175. # Don't skip even if value is empty (reason: reset missing `dynamic`)
  176. entry_points[renaming[norm_key]] = project.pop(key)
  177. if entry_points:
  178. project["entry-points"] = {
  179. name: [f"{k} = {v}" for k, v in group.items()]
  180. for name, group in entry_points.items()
  181. if group # now we can skip empty groups
  182. }
  183. # Sometimes this will set `project["entry-points"] = {}`, and that is
  184. # intentional (for reseting configurations that are missing `dynamic`).
  185. def _copy_command_options(pyproject: dict, dist: "Distribution", filename: _Path):
  186. tool_table = pyproject.get("tool", {})
  187. cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
  188. valid_options = _valid_command_options(cmdclass)
  189. cmd_opts = dist.command_options
  190. for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
  191. cmd = json_compatible_key(cmd)
  192. valid = valid_options.get(cmd, set())
  193. cmd_opts.setdefault(cmd, {})
  194. for key, value in config.items():
  195. key = json_compatible_key(key)
  196. cmd_opts[cmd][key] = (str(filename), value)
  197. if key not in valid:
  198. # To avoid removing options that are specified dynamically we
  199. # just log a warn...
  200. _logger.warning(f"Command option {cmd}.{key} is not defined")
  201. def _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]:
  202. from .._importlib import metadata
  203. from setuptools.dist import Distribution
  204. valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
  205. unloaded_entry_points = metadata.entry_points(group='distutils.commands')
  206. loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
  207. entry_points = (ep for ep in loaded_entry_points if ep)
  208. for cmd, cmd_class in chain(entry_points, cmdclass.items()):
  209. opts = valid_options.get(cmd, set())
  210. opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
  211. valid_options[cmd] = opts
  212. return valid_options
  213. def _load_ep(ep: "metadata.EntryPoint") -> Optional[Tuple[str, Type]]:
  214. # Ignore all the errors
  215. try:
  216. return (ep.name, ep.load())
  217. except Exception as ex:
  218. msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
  219. _logger.warning(f"{msg}: {ex}")
  220. return None
  221. def _normalise_cmd_option_key(name: str) -> str:
  222. return json_compatible_key(name).strip("_=")
  223. def _normalise_cmd_options(desc: List[Tuple[str, Optional[str], str]]) -> Set[str]:
  224. return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
  225. def _get_previous_entrypoints(dist: "Distribution") -> Dict[str, list]:
  226. ignore = ("console_scripts", "gui_scripts")
  227. value = getattr(dist, "entry_points", None) or {}
  228. return {k: v for k, v in value.items() if k not in ignore}
  229. def _get_previous_scripts(dist: "Distribution") -> Optional[list]:
  230. value = getattr(dist, "entry_points", None) or {}
  231. return value.get("console_scripts")
  232. def _get_previous_gui_scripts(dist: "Distribution") -> Optional[list]:
  233. value = getattr(dist, "entry_points", None) or {}
  234. return value.get("gui_scripts")
  235. def _attrgetter(attr):
  236. """
  237. Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
  238. >>> from types import SimpleNamespace
  239. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  240. >>> _attrgetter("a")(obj)
  241. 42
  242. >>> _attrgetter("b.c")(obj)
  243. 13
  244. >>> _attrgetter("d")(obj) is None
  245. True
  246. """
  247. return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
  248. def _some_attrgetter(*items):
  249. """
  250. Return the first "truth-y" attribute or None
  251. >>> from types import SimpleNamespace
  252. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  253. >>> _some_attrgetter("d", "a", "b.c")(obj)
  254. 42
  255. >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
  256. 13
  257. >>> _some_attrgetter("d", "e", "f")(obj) is None
  258. True
  259. """
  260. def _acessor(obj):
  261. values = (_attrgetter(i)(obj) for i in items)
  262. return next((i for i in values if i is not None), None)
  263. return _acessor
  264. PYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = {
  265. "readme": _long_description,
  266. "license": _license,
  267. "authors": partial(_people, kind="author"),
  268. "maintainers": partial(_people, kind="maintainer"),
  269. "urls": _project_urls,
  270. "dependencies": _dependencies,
  271. "optional_dependencies": _optional_dependencies,
  272. "requires_python": _python_requires,
  273. }
  274. TOOL_TABLE_RENAMES = {"script_files": "scripts"}
  275. TOOL_TABLE_REMOVALS = {
  276. "namespace_packages": """
  277. Please migrate to implicit native namespaces instead.
  278. See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
  279. """,
  280. }
  281. SETUPTOOLS_PATCHES = {
  282. "long_description_content_type",
  283. "project_urls",
  284. "provides_extras",
  285. "license_file",
  286. "license_files",
  287. }
  288. _PREVIOUSLY_DEFINED = {
  289. "name": _attrgetter("metadata.name"),
  290. "version": _attrgetter("metadata.version"),
  291. "description": _attrgetter("metadata.description"),
  292. "readme": _attrgetter("metadata.long_description"),
  293. "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
  294. "license": _attrgetter("metadata.license"),
  295. "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
  296. "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
  297. "keywords": _attrgetter("metadata.keywords"),
  298. "classifiers": _attrgetter("metadata.classifiers"),
  299. "urls": _attrgetter("metadata.project_urls"),
  300. "entry-points": _get_previous_entrypoints,
  301. "scripts": _get_previous_scripts,
  302. "gui-scripts": _get_previous_gui_scripts,
  303. "dependencies": _attrgetter("install_requires"),
  304. "optional-dependencies": _attrgetter("extras_require"),
  305. }
  306. _RESET_PREVIOUSLY_DEFINED: dict = {
  307. # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
  308. # dict: pyproject name => value to which reset
  309. "license": {},
  310. "authors": [],
  311. "maintainers": [],
  312. "keywords": [],
  313. "classifiers": [],
  314. "urls": {},
  315. "entry-points": {},
  316. "scripts": {},
  317. "gui-scripts": {},
  318. "dependencies": [],
  319. "optional-dependencies": [],
  320. }
  321. class _MissingDynamic(SetuptoolsWarning):
  322. _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
  323. _DETAILS = """
  324. The following seems to be defined outside of `pyproject.toml`:
  325. `{field} = {value!r}`
  326. According to the spec (see the link below), however, setuptools CANNOT
  327. consider this value unless `{field}` is listed as `dynamic`.
  328. https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
  329. To prevent this problem, you can list `{field}` under `dynamic` or alternatively
  330. remove the `[project]` table from your file and rely entirely on other means of
  331. configuration.
  332. """
  333. # TODO: Consider removing this check in the future?
  334. # There is a trade-off here between improving "debug-ability" and the cost
  335. # of running/testing/maintaining these unnecessary checks...
  336. @classmethod
  337. def details(cls, field: str, value: Any) -> str:
  338. return cls._DETAILS.format(field=field, value=value)