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