_apply_pyprojecttoml.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. from __future__ import annotations
  9. import logging
  10. import os
  11. from collections.abc import Mapping
  12. from email.headerregistry import Address
  13. from functools import partial, reduce
  14. from inspect import cleandoc
  15. from itertools import chain
  16. from types import MappingProxyType
  17. from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
  18. from .. import _static
  19. from .._path import StrPath
  20. from ..errors import InvalidConfigError, RemovedConfigError
  21. from ..extension import Extension
  22. from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
  23. if TYPE_CHECKING:
  24. from typing_extensions import TypeAlias
  25. from setuptools._importlib import metadata
  26. from setuptools.dist import Distribution
  27. from distutils.dist import _OptionsList # Comes from typeshed
  28. EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
  29. _ProjectReadmeValue: TypeAlias = Union[str, dict[str, str]]
  30. _Correspondence: TypeAlias = Callable[["Distribution", Any, Union[StrPath, None]], None]
  31. _T = TypeVar("_T")
  32. _logger = logging.getLogger(__name__)
  33. def apply(dist: Distribution, config: dict, filename: StrPath) -> Distribution:
  34. """Apply configuration dict read with :func:`read_configuration`"""
  35. if not config:
  36. return dist # short-circuit unrelated pyproject.toml file
  37. root_dir = os.path.dirname(filename) or "."
  38. _apply_project_table(dist, config, root_dir)
  39. _apply_tool_table(dist, config, filename)
  40. current_directory = os.getcwd()
  41. os.chdir(root_dir)
  42. try:
  43. dist._finalize_requires()
  44. dist._finalize_license_expression()
  45. dist._finalize_license_files()
  46. finally:
  47. os.chdir(current_directory)
  48. return dist
  49. def _apply_project_table(dist: Distribution, config: dict, root_dir: StrPath):
  50. orig_config = config.get("project", {})
  51. if not orig_config:
  52. return # short-circuit
  53. project_table = {k: _static.attempt_conversion(v) for k, v in orig_config.items()}
  54. _handle_missing_dynamic(dist, project_table)
  55. _unify_entry_points(project_table)
  56. for field, value in project_table.items():
  57. norm_key = json_compatible_key(field)
  58. corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
  59. if callable(corresp):
  60. corresp(dist, value, root_dir)
  61. else:
  62. _set_config(dist, corresp, value)
  63. def _apply_tool_table(dist: Distribution, config: dict, filename: StrPath):
  64. tool_table = config.get("tool", {}).get("setuptools", {})
  65. if not tool_table:
  66. return # short-circuit
  67. if "license-files" in tool_table:
  68. if "license-files" in config.get("project", {}):
  69. # https://github.com/pypa/setuptools/pull/4837#discussion_r2004983349
  70. raise InvalidConfigError(
  71. "'project.license-files' is defined already. "
  72. "Remove 'tool.setuptools.license-files'."
  73. )
  74. pypa_guides = "guides/writing-pyproject-toml/#license-files"
  75. SetuptoolsDeprecationWarning.emit(
  76. "'tool.setuptools.license-files' is deprecated in favor of "
  77. "'project.license-files' (available on setuptools>=77.0.0).",
  78. see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
  79. due_date=(2027, 2, 18), # Warning introduced on 2025-02-18
  80. )
  81. for field, value in tool_table.items():
  82. norm_key = json_compatible_key(field)
  83. if norm_key in TOOL_TABLE_REMOVALS:
  84. suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
  85. msg = f"""
  86. The parameter `tool.setuptools.{field}` was long deprecated
  87. and has been removed from `pyproject.toml`.
  88. """
  89. raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
  90. norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
  91. corresp = TOOL_TABLE_CORRESPONDENCE.get(norm_key, norm_key)
  92. if callable(corresp):
  93. corresp(dist, value)
  94. else:
  95. _set_config(dist, corresp, value)
  96. _copy_command_options(config, dist, filename)
  97. def _handle_missing_dynamic(dist: Distribution, project_table: dict):
  98. """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
  99. dynamic = set(project_table.get("dynamic", []))
  100. for field, getter in _PREVIOUSLY_DEFINED.items():
  101. if not (field in project_table or field in dynamic):
  102. value = getter(dist)
  103. if value:
  104. _MissingDynamic.emit(field=field, value=value)
  105. project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
  106. def json_compatible_key(key: str) -> str:
  107. """As defined in :pep:`566#json-compatible-metadata`"""
  108. return key.lower().replace("-", "_")
  109. def _set_config(dist: Distribution, field: str, value: Any):
  110. val = _PREPROCESS.get(field, _noop)(dist, value)
  111. setter = getattr(dist.metadata, f"set_{field}", None)
  112. if setter:
  113. setter(val)
  114. elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
  115. setattr(dist.metadata, field, val)
  116. else:
  117. setattr(dist, field, val)
  118. _CONTENT_TYPES = {
  119. ".md": "text/markdown",
  120. ".rst": "text/x-rst",
  121. ".txt": "text/plain",
  122. }
  123. def _guess_content_type(file: str) -> str | None:
  124. _, ext = os.path.splitext(file.lower())
  125. if not ext:
  126. return None
  127. if ext in _CONTENT_TYPES:
  128. return _static.Str(_CONTENT_TYPES[ext])
  129. valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
  130. msg = f"only the following file extensions are recognized: {valid}."
  131. raise ValueError(f"Undefined content type for {file}, {msg}")
  132. def _long_description(
  133. dist: Distribution, val: _ProjectReadmeValue, root_dir: StrPath | None
  134. ):
  135. from setuptools.config import expand
  136. file: str | tuple[()]
  137. if isinstance(val, str):
  138. file = val
  139. text = expand.read_files(file, root_dir)
  140. ctype = _guess_content_type(file)
  141. else:
  142. file = val.get("file") or ()
  143. text = val.get("text") or expand.read_files(file, root_dir)
  144. ctype = val["content-type"]
  145. # XXX: Is it completely safe to assume static?
  146. _set_config(dist, "long_description", _static.Str(text))
  147. if ctype:
  148. _set_config(dist, "long_description_content_type", _static.Str(ctype))
  149. if file:
  150. dist._referenced_files.add(file)
  151. def _license(dist: Distribution, val: str | dict, root_dir: StrPath | None):
  152. from setuptools.config import expand
  153. if isinstance(val, str):
  154. if getattr(dist.metadata, "license", None):
  155. SetuptoolsWarning.emit("`license` overwritten by `pyproject.toml`")
  156. dist.metadata.license = None
  157. _set_config(dist, "license_expression", _static.Str(val))
  158. else:
  159. pypa_guides = "guides/writing-pyproject-toml/#license"
  160. SetuptoolsDeprecationWarning.emit(
  161. "`project.license` as a TOML table is deprecated",
  162. "Please use a simple string containing a SPDX expression for "
  163. "`project.license`. You can also use `project.license-files`. "
  164. "(Both options available on setuptools>=77.0.0).",
  165. see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
  166. due_date=(2027, 2, 18), # Introduced on 2025-02-18
  167. )
  168. if "file" in val:
  169. # XXX: Is it completely safe to assume static?
  170. value = expand.read_files([val["file"]], root_dir)
  171. _set_config(dist, "license", _static.Str(value))
  172. dist._referenced_files.add(val["file"])
  173. else:
  174. _set_config(dist, "license", _static.Str(val["text"]))
  175. def _people(dist: Distribution, val: list[dict], _root_dir: StrPath | None, kind: str):
  176. field = []
  177. email_field = []
  178. for person in val:
  179. if "name" not in person:
  180. email_field.append(person["email"])
  181. elif "email" not in person:
  182. field.append(person["name"])
  183. else:
  184. addr = Address(display_name=person["name"], addr_spec=person["email"])
  185. email_field.append(str(addr))
  186. if field:
  187. _set_config(dist, kind, _static.Str(", ".join(field)))
  188. if email_field:
  189. _set_config(dist, f"{kind}_email", _static.Str(", ".join(email_field)))
  190. def _project_urls(dist: Distribution, val: dict, _root_dir: StrPath | None):
  191. _set_config(dist, "project_urls", val)
  192. def _python_requires(dist: Distribution, val: str, _root_dir: StrPath | None):
  193. _set_config(dist, "python_requires", _static.SpecifierSet(val))
  194. def _dependencies(dist: Distribution, val: list, _root_dir: StrPath | None):
  195. if getattr(dist, "install_requires", []):
  196. msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
  197. SetuptoolsWarning.emit(msg)
  198. dist.install_requires = val
  199. def _optional_dependencies(dist: Distribution, val: dict, _root_dir: StrPath | None):
  200. if getattr(dist, "extras_require", None):
  201. msg = "`extras_require` overwritten in `pyproject.toml` (optional-dependencies)"
  202. SetuptoolsWarning.emit(msg)
  203. dist.extras_require = val
  204. def _ext_modules(dist: Distribution, val: list[dict]) -> list[Extension]:
  205. existing = dist.ext_modules or []
  206. args = ({k.replace("-", "_"): v for k, v in x.items()} for x in val)
  207. new = (Extension(**_adjust_ext_attrs(kw)) for kw in args)
  208. return [*existing, *new]
  209. def _adjust_ext_attrs(attrs: dict) -> dict:
  210. # https://github.com/pypa/setuptools/issues/4810
  211. # In TOML there is no differentiation between tuples and lists,
  212. # and distutils requires tuples...
  213. attrs["define_macros"] = list(map(tuple, attrs.get("define_macros") or []))
  214. return attrs
  215. def _noop(_dist: Distribution, val: _T) -> _T:
  216. return val
  217. def _identity(val: _T) -> _T:
  218. return val
  219. def _unify_entry_points(project_table: dict):
  220. project = project_table
  221. given = project.pop("entry-points", project.pop("entry_points", {}))
  222. entry_points = dict(given) # Avoid problems with static
  223. renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
  224. for key, value in list(project.items()): # eager to allow modifications
  225. norm_key = json_compatible_key(key)
  226. if norm_key in renaming:
  227. # Don't skip even if value is empty (reason: reset missing `dynamic`)
  228. entry_points[renaming[norm_key]] = project.pop(key)
  229. if entry_points:
  230. project["entry-points"] = {
  231. name: [f"{k} = {v}" for k, v in group.items()]
  232. for name, group in entry_points.items()
  233. if group # now we can skip empty groups
  234. }
  235. # Sometimes this will set `project["entry-points"] = {}`, and that is
  236. # intentional (for resetting configurations that are missing `dynamic`).
  237. def _copy_command_options(pyproject: dict, dist: Distribution, filename: StrPath):
  238. tool_table = pyproject.get("tool", {})
  239. cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
  240. valid_options = _valid_command_options(cmdclass)
  241. cmd_opts = dist.command_options
  242. for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
  243. cmd = json_compatible_key(cmd)
  244. valid = valid_options.get(cmd, set())
  245. cmd_opts.setdefault(cmd, {})
  246. for key, value in config.items():
  247. key = json_compatible_key(key)
  248. cmd_opts[cmd][key] = (str(filename), value)
  249. if key not in valid:
  250. # To avoid removing options that are specified dynamically we
  251. # just log a warn...
  252. _logger.warning(f"Command option {cmd}.{key} is not defined")
  253. def _valid_command_options(cmdclass: Mapping = EMPTY) -> dict[str, set[str]]:
  254. from setuptools.dist import Distribution
  255. from .._importlib import metadata
  256. valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
  257. unloaded_entry_points = metadata.entry_points(group='distutils.commands')
  258. loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
  259. entry_points = (ep for ep in loaded_entry_points if ep)
  260. for cmd, cmd_class in chain(entry_points, cmdclass.items()):
  261. opts = valid_options.get(cmd, set())
  262. opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
  263. valid_options[cmd] = opts
  264. return valid_options
  265. def _load_ep(ep: metadata.EntryPoint) -> tuple[str, type] | None:
  266. if ep.value.startswith("wheel.bdist_wheel"):
  267. # Ignore deprecated entrypoint from wheel and avoid warning pypa/wheel#631
  268. # TODO: remove check when `bdist_wheel` has been fully removed from pypa/wheel
  269. return None
  270. # Ignore all the errors
  271. try:
  272. return (ep.name, ep.load())
  273. except Exception as ex:
  274. msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
  275. _logger.warning(f"{msg}: {ex}")
  276. return None
  277. def _normalise_cmd_option_key(name: str) -> str:
  278. return json_compatible_key(name).strip("_=")
  279. def _normalise_cmd_options(desc: _OptionsList) -> set[str]:
  280. return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
  281. def _get_previous_entrypoints(dist: Distribution) -> dict[str, list]:
  282. ignore = ("console_scripts", "gui_scripts")
  283. value = getattr(dist, "entry_points", None) or {}
  284. return {k: v for k, v in value.items() if k not in ignore}
  285. def _get_previous_scripts(dist: Distribution) -> list | None:
  286. value = getattr(dist, "entry_points", None) or {}
  287. return value.get("console_scripts")
  288. def _get_previous_gui_scripts(dist: Distribution) -> list | None:
  289. value = getattr(dist, "entry_points", None) or {}
  290. return value.get("gui_scripts")
  291. def _set_static_list_metadata(attr: str, dist: Distribution, val: list) -> None:
  292. """Apply distutils metadata validation but preserve "static" behaviour"""
  293. meta = dist.metadata
  294. setter, getter = getattr(meta, f"set_{attr}"), getattr(meta, f"get_{attr}")
  295. setter(val)
  296. setattr(meta, attr, _static.List(getter()))
  297. def _attrgetter(attr):
  298. """
  299. Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
  300. >>> from types import SimpleNamespace
  301. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  302. >>> _attrgetter("a")(obj)
  303. 42
  304. >>> _attrgetter("b.c")(obj)
  305. 13
  306. >>> _attrgetter("d")(obj) is None
  307. True
  308. """
  309. return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
  310. def _some_attrgetter(*items):
  311. """
  312. Return the first "truth-y" attribute or None
  313. >>> from types import SimpleNamespace
  314. >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
  315. >>> _some_attrgetter("d", "a", "b.c")(obj)
  316. 42
  317. >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
  318. 13
  319. >>> _some_attrgetter("d", "e", "f")(obj) is None
  320. True
  321. """
  322. def _acessor(obj):
  323. values = (_attrgetter(i)(obj) for i in items)
  324. return next((i for i in values if i is not None), None)
  325. return _acessor
  326. PYPROJECT_CORRESPONDENCE: dict[str, _Correspondence] = {
  327. "readme": _long_description,
  328. "license": _license,
  329. "authors": partial(_people, kind="author"),
  330. "maintainers": partial(_people, kind="maintainer"),
  331. "urls": _project_urls,
  332. "dependencies": _dependencies,
  333. "optional_dependencies": _optional_dependencies,
  334. "requires_python": _python_requires,
  335. }
  336. TOOL_TABLE_RENAMES = {"script_files": "scripts"}
  337. TOOL_TABLE_REMOVALS = {
  338. "namespace_packages": """
  339. Please migrate to implicit native namespaces instead.
  340. See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
  341. """,
  342. }
  343. TOOL_TABLE_CORRESPONDENCE = {
  344. # Fields with corresponding core metadata need to be marked as static:
  345. "obsoletes": partial(_set_static_list_metadata, "obsoletes"),
  346. "provides": partial(_set_static_list_metadata, "provides"),
  347. "platforms": partial(_set_static_list_metadata, "platforms"),
  348. }
  349. SETUPTOOLS_PATCHES = {
  350. "long_description_content_type",
  351. "project_urls",
  352. "provides_extras",
  353. "license_file",
  354. "license_files",
  355. "license_expression",
  356. }
  357. _PREPROCESS = {
  358. "ext_modules": _ext_modules,
  359. }
  360. _PREVIOUSLY_DEFINED = {
  361. "name": _attrgetter("metadata.name"),
  362. "version": _attrgetter("metadata.version"),
  363. "description": _attrgetter("metadata.description"),
  364. "readme": _attrgetter("metadata.long_description"),
  365. "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
  366. "license": _some_attrgetter("metadata.license_expression", "metadata.license"),
  367. # XXX: `license-file` is currently not considered in the context of `dynamic`.
  368. # See TestPresetField.test_license_files_exempt_from_dynamic
  369. "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
  370. "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
  371. "keywords": _attrgetter("metadata.keywords"),
  372. "classifiers": _attrgetter("metadata.classifiers"),
  373. "urls": _attrgetter("metadata.project_urls"),
  374. "entry-points": _get_previous_entrypoints,
  375. "scripts": _get_previous_scripts,
  376. "gui-scripts": _get_previous_gui_scripts,
  377. "dependencies": _attrgetter("install_requires"),
  378. "optional-dependencies": _attrgetter("extras_require"),
  379. }
  380. _RESET_PREVIOUSLY_DEFINED: dict = {
  381. # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
  382. # Use "immutable" data structures to avoid in-place modification.
  383. # dict: pyproject name => value to which reset
  384. "license": "",
  385. # XXX: `license-file` is currently not considered in the context of `dynamic`.
  386. # See TestPresetField.test_license_files_exempt_from_dynamic
  387. "authors": _static.EMPTY_LIST,
  388. "maintainers": _static.EMPTY_LIST,
  389. "keywords": _static.EMPTY_LIST,
  390. "classifiers": _static.EMPTY_LIST,
  391. "urls": _static.EMPTY_DICT,
  392. "entry-points": _static.EMPTY_DICT,
  393. "scripts": _static.EMPTY_DICT,
  394. "gui-scripts": _static.EMPTY_DICT,
  395. "dependencies": _static.EMPTY_LIST,
  396. "optional-dependencies": _static.EMPTY_DICT,
  397. }
  398. class _MissingDynamic(SetuptoolsWarning):
  399. _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
  400. _DETAILS = """
  401. The following seems to be defined outside of `pyproject.toml`:
  402. `{field} = {value!r}`
  403. According to the spec (see the link below), however, setuptools CANNOT
  404. consider this value unless `{field}` is listed as `dynamic`.
  405. https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
  406. To prevent this problem, you can list `{field}` under `dynamic` or alternatively
  407. remove the `[project]` table from your file and rely entirely on other means of
  408. configuration.
  409. """
  410. # TODO: Consider removing this check in the future?
  411. # There is a trade-off here between improving "debug-ability" and the cost
  412. # of running/testing/maintaining these unnecessary checks...
  413. @classmethod
  414. def details(cls, field: str, value: Any) -> str:
  415. return cls._DETAILS.format(field=field, value=value)