_apply_pyprojecttoml.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. import warnings
  11. from collections.abc import Mapping
  12. from email.headerregistry import Address
  13. from functools import partial, reduce
  14. from itertools import chain
  15. from types import MappingProxyType
  16. from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple,
  17. Type, Union)
  18. from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
  19. if TYPE_CHECKING:
  20. from setuptools._importlib import metadata # noqa
  21. from setuptools.dist import Distribution # noqa
  22. EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
  23. _Path = Union[os.PathLike, str]
  24. _DictOrStr = Union[dict, str]
  25. _CorrespFn = Callable[["Distribution", Any, _Path], None]
  26. _Correspondence = Union[str, _CorrespFn]
  27. _logger = logging.getLogger(__name__)
  28. def apply(dist: "Distribution", config: dict, filename: _Path) -> "Distribution":
  29. """Apply configuration dict read with :func:`read_configuration`"""
  30. if not config:
  31. return dist # short-circuit unrelated pyproject.toml file
  32. root_dir = os.path.dirname(filename) or "."
  33. _apply_project_table(dist, config, root_dir)
  34. _apply_tool_table(dist, config, filename)
  35. current_directory = os.getcwd()
  36. os.chdir(root_dir)
  37. try:
  38. dist._finalize_requires()
  39. dist._finalize_license_files()
  40. finally:
  41. os.chdir(current_directory)
  42. return dist
  43. def _apply_project_table(dist: "Distribution", config: dict, root_dir: _Path):
  44. project_table = config.get("project", {}).copy()
  45. if not project_table:
  46. return # short-circuit
  47. _handle_missing_dynamic(dist, project_table)
  48. _unify_entry_points(project_table)
  49. for field, value in project_table.items():
  50. norm_key = json_compatible_key(field)
  51. corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
  52. if callable(corresp):
  53. corresp(dist, value, root_dir)
  54. else:
  55. _set_config(dist, corresp, value)
  56. def _apply_tool_table(dist: "Distribution", config: dict, filename: _Path):
  57. tool_table = config.get("tool", {}).get("setuptools", {})
  58. if not tool_table:
  59. return # short-circuit
  60. for field, value in tool_table.items():
  61. norm_key = json_compatible_key(field)
  62. if norm_key in TOOL_TABLE_DEPRECATIONS:
  63. suggestion = TOOL_TABLE_DEPRECATIONS[norm_key]
  64. msg = f"The parameter `{norm_key}` is deprecated, {suggestion}"
  65. warnings.warn(msg, SetuptoolsDeprecationWarning)
  66. norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
  67. _set_config(dist, norm_key, value)
  68. _copy_command_options(config, dist, filename)
  69. def _handle_missing_dynamic(dist: "Distribution", project_table: dict):
  70. """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
  71. # TODO: Set fields back to `None` once the feature stabilizes
  72. dynamic = set(project_table.get("dynamic", []))
  73. for field, getter in _PREVIOUSLY_DEFINED.items():
  74. if not (field in project_table or field in dynamic):
  75. value = getter(dist)
  76. if value:
  77. msg = _WouldIgnoreField.message(field, value)
  78. warnings.warn(msg, _WouldIgnoreField)
  79. def json_compatible_key(key: str) -> str:
  80. """As defined in :pep:`566#json-compatible-metadata`"""
  81. return key.lower().replace("-", "_")
  82. def _set_config(dist: "Distribution", field: str, value: Any):
  83. setter = getattr(dist.metadata, f"set_{field}", None)
  84. if setter:
  85. setter(value)
  86. elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
  87. setattr(dist.metadata, field, value)
  88. else:
  89. setattr(dist, field, value)
  90. _CONTENT_TYPES = {
  91. ".md": "text/markdown",
  92. ".rst": "text/x-rst",
  93. ".txt": "text/plain",
  94. }
  95. def _guess_content_type(file: str) -> Optional[str]:
  96. _, ext = os.path.splitext(file.lower())
  97. if not ext:
  98. return None
  99. if ext in _CONTENT_TYPES:
  100. return _CONTENT_TYPES[ext]
  101. valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
  102. msg = f"only the following file extensions are recognized: {valid}."
  103. raise ValueError(f"Undefined content type for {file}, {msg}")
  104. def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: _Path):
  105. from setuptools.config import expand
  106. if isinstance(val, str):
  107. text = expand.read_files(val, root_dir)
  108. ctype = _guess_content_type(val)
  109. else:
  110. text = val.get("text") or expand.read_files(val.get("file", []), root_dir)
  111. ctype = val["content-type"]
  112. _set_config(dist, "long_description", text)
  113. if ctype:
  114. _set_config(dist, "long_description_content_type", ctype)
  115. def _license(dist: "Distribution", val: dict, root_dir: _Path):
  116. from setuptools.config import expand
  117. if "file" in val:
  118. _set_config(dist, "license", expand.read_files([val["file"]], root_dir))
  119. else:
  120. _set_config(dist, "license", val["text"])
  121. def _people(dist: "Distribution", val: List[dict], _root_dir: _Path, kind: str):
  122. field = []
  123. email_field = []
  124. for person in val:
  125. if "name" not in person:
  126. email_field.append(person["email"])
  127. elif "email" not in person:
  128. field.append(person["name"])
  129. else:
  130. addr = Address(display_name=person["name"], addr_spec=person["email"])
  131. email_field.append(str(addr))
  132. if field:
  133. _set_config(dist, kind, ", ".join(field))
  134. if email_field:
  135. _set_config(dist, f"{kind}_email", ", ".join(email_field))
  136. def _project_urls(dist: "Distribution", val: dict, _root_dir):
  137. _set_config(dist, "project_urls", val)
  138. def _python_requires(dist: "Distribution", val: dict, _root_dir):
  139. from setuptools.extern.packaging.specifiers import SpecifierSet
  140. _set_config(dist, "python_requires", SpecifierSet(val))
  141. def _dependencies(dist: "Distribution", val: list, _root_dir):
  142. if getattr(dist, "install_requires", []):
  143. msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
  144. warnings.warn(msg)
  145. _set_config(dist, "install_requires", val)
  146. def _optional_dependencies(dist: "Distribution", val: dict, _root_dir):
  147. existing = getattr(dist, "extras_require", {})
  148. _set_config(dist, "extras_require", {**existing, **val})
  149. def _unify_entry_points(project_table: dict):
  150. project = project_table
  151. entry_points = project.pop("entry-points", project.pop("entry_points", {}))
  152. renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
  153. for key, value in list(project.items()): # eager to allow modifications
  154. norm_key = json_compatible_key(key)
  155. if norm_key in renaming and value:
  156. entry_points[renaming[norm_key]] = project.pop(key)
  157. if entry_points:
  158. project["entry-points"] = {
  159. name: [f"{k} = {v}" for k, v in group.items()]
  160. for name, group in entry_points.items()
  161. }
  162. def _copy_command_options(pyproject: dict, dist: "Distribution", filename: _Path):
  163. tool_table = pyproject.get("tool", {})
  164. cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
  165. valid_options = _valid_command_options(cmdclass)
  166. cmd_opts = dist.command_options
  167. for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
  168. cmd = json_compatible_key(cmd)
  169. valid = valid_options.get(cmd, set())
  170. cmd_opts.setdefault(cmd, {})
  171. for key, value in config.items():
  172. key = json_compatible_key(key)
  173. cmd_opts[cmd][key] = (str(filename), value)
  174. if key not in valid:
  175. # To avoid removing options that are specified dynamically we
  176. # just log a warn...
  177. _logger.warning(f"Command option {cmd}.{key} is not defined")
  178. def _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]:
  179. from .._importlib import metadata
  180. from setuptools.dist import Distribution
  181. valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
  182. unloaded_entry_points = metadata.entry_points(group='distutils.commands')
  183. loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
  184. entry_points = (ep for ep in loaded_entry_points if ep)
  185. for cmd, cmd_class in chain(entry_points, cmdclass.items()):
  186. opts = valid_options.get(cmd, set())
  187. opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
  188. valid_options[cmd] = opts
  189. return valid_options
  190. def _load_ep(ep: "metadata.EntryPoint") -> Optional[Tuple[str, Type]]:
  191. # Ignore all the errors
  192. try:
  193. return (ep.name, ep.load())
  194. except Exception as ex:
  195. msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
  196. _logger.warning(f"{msg}: {ex}")
  197. return None
  198. def _normalise_cmd_option_key(name: str) -> str:
  199. return json_compatible_key(name).strip("_=")
  200. def _normalise_cmd_options(desc: List[Tuple[str, Optional[str], str]]) -> Set[str]:
  201. return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
  202. def _attrgetter(attr):
  203. """
  204. Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
  205. >>> from types import SimpleNamespace
  206. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  207. >>> _attrgetter("a")(obj)
  208. 42
  209. >>> _attrgetter("b.c")(obj)
  210. 13
  211. >>> _attrgetter("d")(obj) is None
  212. True
  213. """
  214. return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
  215. def _some_attrgetter(*items):
  216. """
  217. Return the first "truth-y" attribute or None
  218. >>> from types import SimpleNamespace
  219. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  220. >>> _some_attrgetter("d", "a", "b.c")(obj)
  221. 42
  222. >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
  223. 13
  224. >>> _some_attrgetter("d", "e", "f")(obj) is None
  225. True
  226. """
  227. def _acessor(obj):
  228. values = (_attrgetter(i)(obj) for i in items)
  229. return next((i for i in values if i is not None), None)
  230. return _acessor
  231. PYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = {
  232. "readme": _long_description,
  233. "license": _license,
  234. "authors": partial(_people, kind="author"),
  235. "maintainers": partial(_people, kind="maintainer"),
  236. "urls": _project_urls,
  237. "dependencies": _dependencies,
  238. "optional_dependencies": _optional_dependencies,
  239. "requires_python": _python_requires,
  240. }
  241. TOOL_TABLE_RENAMES = {"script_files": "scripts"}
  242. TOOL_TABLE_DEPRECATIONS = {
  243. "namespace_packages": "consider using implicit namespaces instead (PEP 420)."
  244. }
  245. SETUPTOOLS_PATCHES = {"long_description_content_type", "project_urls",
  246. "provides_extras", "license_file", "license_files"}
  247. _PREVIOUSLY_DEFINED = {
  248. "name": _attrgetter("metadata.name"),
  249. "version": _attrgetter("metadata.version"),
  250. "description": _attrgetter("metadata.description"),
  251. "readme": _attrgetter("metadata.long_description"),
  252. "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
  253. "license": _attrgetter("metadata.license"),
  254. "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
  255. "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
  256. "keywords": _attrgetter("metadata.keywords"),
  257. "classifiers": _attrgetter("metadata.classifiers"),
  258. "urls": _attrgetter("metadata.project_urls"),
  259. "entry-points": _attrgetter("entry_points"),
  260. "dependencies": _some_attrgetter("_orig_install_requires", "install_requires"),
  261. "optional-dependencies": _some_attrgetter("_orig_extras_require", "extras_require"),
  262. }
  263. class _WouldIgnoreField(UserWarning):
  264. """Inform users that ``pyproject.toml`` would overwrite previous metadata."""
  265. MESSAGE = """\
  266. {field!r} defined outside of `pyproject.toml` would be ignored.
  267. !!\n\n
  268. ##########################################################################
  269. # configuration would be ignored/result in error due to `pyproject.toml` #
  270. ##########################################################################
  271. The following seems to be defined outside of `pyproject.toml`:
  272. `{field} = {value!r}`
  273. According to the spec (see the link below), however, setuptools CANNOT
  274. consider this value unless {field!r} is listed as `dynamic`.
  275. https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
  276. For the time being, `setuptools` will still consider the given value (as a
  277. **transitional** measure), but please note that future releases of setuptools will
  278. follow strictly the standard.
  279. To prevent this warning, you can list {field!r} under `dynamic` or alternatively
  280. remove the `[project]` table from your file and rely entirely on other means of
  281. configuration.
  282. \n\n!!
  283. """
  284. @classmethod
  285. def message(cls, field, value):
  286. from inspect import cleandoc
  287. return cleandoc(cls.MESSAGE.format(field=field, value=value))