_apply_pyprojecttoml.py 14 KB

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