codekingpro commited on
Commit
3c5df55
·
verified ·
1 Parent(s): a865e05

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/Lib/site-packages/setuptools/command/__init__.py +21 -0
  2. python/Lib/site-packages/setuptools/command/_requirestxt.py +131 -0
  3. python/Lib/site-packages/setuptools/command/bdist_rpm.py +42 -0
  4. python/Lib/site-packages/setuptools/command/bdist_wheel.py +603 -0
  5. python/Lib/site-packages/setuptools/command/build.py +135 -0
  6. python/Lib/site-packages/setuptools/command/build_clib.py +103 -0
  7. python/Lib/site-packages/setuptools/command/build_ext.py +470 -0
  8. python/Lib/site-packages/setuptools/command/build_py.py +403 -0
  9. python/Lib/site-packages/setuptools/command/develop.py +58 -0
  10. python/Lib/site-packages/setuptools/command/dist_info.py +103 -0
  11. python/Lib/site-packages/setuptools/command/easy_install.py +30 -0
  12. python/Lib/site-packages/setuptools/command/editable_wheel.py +914 -0
  13. python/Lib/site-packages/setuptools/command/egg_info.py +716 -0
  14. python/Lib/site-packages/setuptools/command/install.py +131 -0
  15. python/Lib/site-packages/setuptools/command/install_egg_info.py +57 -0
  16. python/Lib/site-packages/setuptools/command/install_lib.py +137 -0
  17. python/Lib/site-packages/setuptools/command/install_scripts.py +66 -0
  18. python/Lib/site-packages/setuptools/command/rotate.py +64 -0
  19. python/Lib/site-packages/setuptools/command/saveopts.py +21 -0
  20. python/Lib/site-packages/setuptools/command/sdist.py +218 -0
  21. python/Lib/site-packages/setuptools/command/setopt.py +139 -0
  22. python/Lib/site-packages/setuptools/command/test.py +47 -0
  23. python/Lib/site-packages/setuptools/compat/__init__.py +0 -0
  24. python/Lib/site-packages/setuptools/compat/py310.py +20 -0
  25. python/Lib/site-packages/setuptools/compat/py311.py +27 -0
  26. python/Lib/site-packages/setuptools/compat/py312.py +13 -0
  27. python/Lib/site-packages/setuptools/compat/py39.py +9 -0
  28. python/Lib/site-packages/setuptools/config/NOTICE +10 -0
  29. python/Lib/site-packages/setuptools/config/__init__.py +43 -0
  30. python/Lib/site-packages/setuptools/config/_apply_pyprojecttoml.py +534 -0
  31. python/Lib/site-packages/setuptools/config/distutils.schema.json +26 -0
  32. python/Lib/site-packages/setuptools/config/expand.py +452 -0
  33. python/Lib/site-packages/setuptools/config/pyprojecttoml.py +477 -0
  34. python/Lib/site-packages/setuptools/config/setupcfg.py +782 -0
  35. python/Lib/site-packages/setuptools/config/setuptools.schema.json +433 -0
  36. python/Lib/site-packages/setuptools/tests/contexts.py +131 -0
  37. python/Lib/site-packages/setuptools/tests/environment.py +95 -0
  38. python/Lib/site-packages/setuptools/tests/fixtures.py +406 -0
  39. python/Lib/site-packages/setuptools/tests/mod_with_constant.py +1 -0
  40. python/Lib/site-packages/setuptools/tests/namespaces.py +90 -0
  41. python/Lib/site-packages/setuptools/tests/script-with-bom.py +1 -0
  42. python/Lib/site-packages/setuptools/tests/test_archive_util.py +36 -0
  43. python/Lib/site-packages/setuptools/tests/test_bdist_deprecations.py +28 -0
  44. python/Lib/site-packages/setuptools/tests/test_bdist_egg.py +73 -0
  45. python/Lib/site-packages/setuptools/tests/test_bdist_wheel.py +708 -0
  46. python/Lib/site-packages/setuptools/tests/test_build.py +33 -0
  47. python/Lib/site-packages/setuptools/tests/test_build_clib.py +84 -0
  48. python/Lib/site-packages/setuptools/tests/test_build_ext.py +293 -0
  49. python/Lib/site-packages/setuptools/tests/test_build_meta.py +959 -0
  50. python/Lib/site-packages/setuptools/tests/test_build_py.py +480 -0
python/Lib/site-packages/setuptools/command/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable_error_code=call-overload
2
+ # pyright: reportCallIssue=false, reportArgumentType=false
3
+ # Can't disable on the exact line because distutils doesn't exists on Python 3.12
4
+ # and type-checkers aren't aware of distutils_hack,
5
+ # causing distutils.command.bdist.bdist.format_commands to be Any.
6
+
7
+ import sys
8
+
9
+ from distutils.command.bdist import bdist
10
+
11
+ if 'egg' not in bdist.format_commands:
12
+ try:
13
+ # format_commands is a dict in vendored distutils
14
+ # It used to be a list in older (stdlib) distutils
15
+ # We support both for backwards compatibility
16
+ bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
17
+ except TypeError:
18
+ bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
19
+ bdist.format_commands.append('egg')
20
+
21
+ del bdist, sys
python/Lib/site-packages/setuptools/command/_requirestxt.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper code used to generate ``requires.txt`` files in the egg-info directory.
2
+
3
+ The ``requires.txt`` file has an specific format:
4
+ - Environment markers need to be part of the section headers and
5
+ should not be part of the requirement spec itself.
6
+
7
+ See https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#requires-txt
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import io
13
+ from collections import defaultdict
14
+ from collections.abc import Mapping
15
+ from itertools import filterfalse
16
+ from typing import TypeVar
17
+
18
+ from jaraco.text import yield_lines
19
+ from packaging.requirements import Requirement
20
+
21
+ from .. import _reqs
22
+ from .._reqs import _StrOrIter
23
+
24
+ # dict can work as an ordered set
25
+ _T = TypeVar("_T")
26
+ _Ordered = dict[_T, None]
27
+
28
+
29
+ def _prepare(
30
+ install_requires: _StrOrIter, extras_require: Mapping[str, _StrOrIter]
31
+ ) -> tuple[list[str], dict[str, list[str]]]:
32
+ """Given values for ``install_requires`` and ``extras_require``
33
+ create modified versions in a way that can be written in ``requires.txt``
34
+ """
35
+ extras = _convert_extras_requirements(extras_require)
36
+ return _move_install_requirements_markers(install_requires, extras)
37
+
38
+
39
+ def _convert_extras_requirements(
40
+ extras_require: Mapping[str, _StrOrIter],
41
+ ) -> defaultdict[str, _Ordered[Requirement]]:
42
+ """
43
+ Convert requirements in `extras_require` of the form
44
+ `"extra": ["barbazquux; {marker}"]` to
45
+ `"extra:{marker}": ["barbazquux"]`.
46
+ """
47
+ output = defaultdict[str, _Ordered[Requirement]](dict)
48
+ for section, v in extras_require.items():
49
+ # Do not strip empty sections.
50
+ output[section]
51
+ for r in _reqs.parse(v):
52
+ output[section + _suffix_for(r)].setdefault(r)
53
+
54
+ return output
55
+
56
+
57
+ def _move_install_requirements_markers(
58
+ install_requires: _StrOrIter, extras_require: Mapping[str, _Ordered[Requirement]]
59
+ ) -> tuple[list[str], dict[str, list[str]]]:
60
+ """
61
+ The ``requires.txt`` file has an specific format:
62
+ - Environment markers need to be part of the section headers and
63
+ should not be part of the requirement spec itself.
64
+
65
+ Move requirements in ``install_requires`` that are using environment
66
+ markers ``extras_require``.
67
+ """
68
+
69
+ # divide the install_requires into two sets, simple ones still
70
+ # handled by install_requires and more complex ones handled by extras_require.
71
+
72
+ inst_reqs = list(_reqs.parse(install_requires))
73
+ simple_reqs = filter(_no_marker, inst_reqs)
74
+ complex_reqs = filterfalse(_no_marker, inst_reqs)
75
+ simple_install_requires = list(map(str, simple_reqs))
76
+
77
+ for r in complex_reqs:
78
+ extras_require[':' + str(r.marker)].setdefault(r)
79
+
80
+ expanded_extras = dict(
81
+ # list(dict.fromkeys(...)) ensures a list of unique strings
82
+ (k, list(dict.fromkeys(str(r) for r in map(_clean_req, v))))
83
+ for k, v in extras_require.items()
84
+ )
85
+
86
+ return simple_install_requires, expanded_extras
87
+
88
+
89
+ def _suffix_for(req):
90
+ """Return the 'extras_require' suffix for a given requirement."""
91
+ return ':' + str(req.marker) if req.marker else ''
92
+
93
+
94
+ def _clean_req(req):
95
+ """Given a Requirement, remove environment markers and return it"""
96
+ r = Requirement(str(req)) # create a copy before modifying
97
+ r.marker = None
98
+ return r
99
+
100
+
101
+ def _no_marker(req):
102
+ return not req.marker
103
+
104
+
105
+ def _write_requirements(stream, reqs):
106
+ lines = yield_lines(reqs or ())
107
+
108
+ def append_cr(line):
109
+ return line + '\n'
110
+
111
+ lines = map(append_cr, lines)
112
+ stream.writelines(lines)
113
+
114
+
115
+ def write_requirements(cmd, basename, filename):
116
+ dist = cmd.distribution
117
+ data = io.StringIO()
118
+ install_requires, extras_require = _prepare(
119
+ dist.install_requires or (), dist.extras_require or {}
120
+ )
121
+ _write_requirements(data, install_requires)
122
+ for extra in sorted(extras_require):
123
+ data.write('\n[{extra}]\n'.format(**vars()))
124
+ _write_requirements(data, extras_require[extra])
125
+ cmd.write_or_delete_file("requirements", filename, data.getvalue())
126
+
127
+
128
+ def write_setup_requirements(cmd, basename, filename):
129
+ data = io.StringIO()
130
+ _write_requirements(data, cmd.distribution.setup_requires)
131
+ cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
python/Lib/site-packages/setuptools/command/bdist_rpm.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..dist import Distribution
2
+ from ..warnings import SetuptoolsDeprecationWarning
3
+
4
+ import distutils.command.bdist_rpm as orig
5
+
6
+
7
+ class bdist_rpm(orig.bdist_rpm):
8
+ """
9
+ Override the default bdist_rpm behavior to do the following:
10
+
11
+ 1. Run egg_info to ensure the name and version are properly calculated.
12
+ 2. Always run 'install' using --single-version-externally-managed to
13
+ disable eggs in RPM distributions.
14
+ """
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def run(self) -> None:
19
+ SetuptoolsDeprecationWarning.emit(
20
+ "Deprecated command",
21
+ """
22
+ bdist_rpm is deprecated and will be removed in a future version.
23
+ Use bdist_wheel (wheel packages) instead.
24
+ """,
25
+ see_url="https://github.com/pypa/setuptools/issues/1988",
26
+ due_date=(2023, 10, 30), # Deprecation introduced in 22 Oct 2021.
27
+ )
28
+
29
+ # ensure distro name is up-to-date
30
+ self.run_command('egg_info')
31
+
32
+ orig.bdist_rpm.run(self)
33
+
34
+ def _make_spec_file(self):
35
+ spec = orig.bdist_rpm._make_spec_file(self)
36
+ return [
37
+ line.replace(
38
+ "setup.py install ",
39
+ "setup.py install --single-version-externally-managed ",
40
+ ).replace("%setup", "%setup -n %{name}-%{unmangled_version}")
41
+ for line in spec
42
+ ]
python/Lib/site-packages/setuptools/command/bdist_wheel.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a wheel (.whl) distribution.
3
+
4
+ A wheel is a built archive format.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import shutil
12
+ import struct
13
+ import sys
14
+ import sysconfig
15
+ import warnings
16
+ from collections.abc import Iterable, Sequence
17
+ from email.generator import BytesGenerator
18
+ from glob import iglob
19
+ from typing import Literal, cast
20
+ from zipfile import ZIP_DEFLATED, ZIP_STORED
21
+
22
+ from packaging import tags, version as _packaging_version
23
+ from wheel.wheelfile import WheelFile
24
+
25
+ from .. import Command, __version__, _shutil
26
+ from .._core_metadata import _safe_license_file
27
+ from .._normalization import safer_name
28
+ from ..warnings import SetuptoolsDeprecationWarning
29
+ from .egg_info import egg_info as egg_info_cls
30
+
31
+ from distutils import log
32
+
33
+
34
+ def safe_version(version: str) -> str:
35
+ """
36
+ Convert an arbitrary string to a standard version string
37
+ """
38
+ try:
39
+ # normalize the version
40
+ return str(_packaging_version.Version(version))
41
+ except _packaging_version.InvalidVersion:
42
+ version = version.replace(" ", ".")
43
+ return re.sub("[^A-Za-z0-9.]+", "-", version)
44
+
45
+
46
+ setuptools_major_version = int(__version__.split(".")[0])
47
+
48
+ PY_LIMITED_API_PATTERN = r"cp3\d"
49
+
50
+
51
+ def _is_32bit_interpreter() -> bool:
52
+ return struct.calcsize("P") == 4
53
+
54
+
55
+ def python_tag() -> str:
56
+ return f"py{sys.version_info.major}"
57
+
58
+
59
+ def get_platform(archive_root: str | None) -> str:
60
+ """Return our platform name 'win32', 'linux_x86_64'"""
61
+ result = sysconfig.get_platform()
62
+ if result.startswith("macosx") and archive_root is not None: # pragma: no cover
63
+ from wheel.macosx_libfile import calculate_macosx_platform_tag
64
+
65
+ result = calculate_macosx_platform_tag(archive_root, result)
66
+ elif _is_32bit_interpreter():
67
+ if result == "linux-x86_64":
68
+ # pip pull request #3497
69
+ result = "linux-i686"
70
+ elif result == "linux-aarch64":
71
+ # packaging pull request #234
72
+ # TODO armv8l, packaging pull request #690 => this did not land
73
+ # in pip/packaging yet
74
+ result = "linux-armv7l"
75
+
76
+ return result.replace("-", "_")
77
+
78
+
79
+ def get_flag(
80
+ var: str, fallback: bool, expected: bool = True, warn: bool = True
81
+ ) -> bool:
82
+ """Use a fallback value for determining SOABI flags if the needed config
83
+ var is unset or unavailable."""
84
+ val = sysconfig.get_config_var(var)
85
+ if val is None:
86
+ if warn:
87
+ warnings.warn(
88
+ f"Config variable '{var}' is unset, Python ABI tag may be incorrect",
89
+ RuntimeWarning,
90
+ stacklevel=2,
91
+ )
92
+ return fallback
93
+ return val == expected
94
+
95
+
96
+ def get_abi_tag() -> str | None:
97
+ """Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2)."""
98
+ soabi: str = sysconfig.get_config_var("SOABI")
99
+ impl = tags.interpreter_name()
100
+ if not soabi and impl in ("cp", "pp") and hasattr(sys, "maxunicode"):
101
+ d = ""
102
+ u = ""
103
+ if get_flag("Py_DEBUG", hasattr(sys, "gettotalrefcount"), warn=(impl == "cp")):
104
+ d = "d"
105
+
106
+ abi = f"{impl}{tags.interpreter_version()}{d}{u}"
107
+ elif soabi and impl == "cp" and soabi.startswith("cpython"):
108
+ # non-Windows
109
+ abi = "cp" + soabi.split("-")[1]
110
+ elif soabi and impl == "cp" and soabi.startswith("cp"):
111
+ # Windows
112
+ abi = soabi.split("-")[0]
113
+ if hasattr(sys, "gettotalrefcount"):
114
+ # using debug build; append "d" flag
115
+ abi += "d"
116
+ elif soabi and impl == "pp":
117
+ # we want something like pypy36-pp73
118
+ abi = "-".join(soabi.split("-")[:2])
119
+ abi = abi.replace(".", "_").replace("-", "_")
120
+ elif soabi and impl == "graalpy":
121
+ abi = "-".join(soabi.split("-")[:3])
122
+ abi = abi.replace(".", "_").replace("-", "_")
123
+ elif soabi:
124
+ abi = soabi.replace(".", "_").replace("-", "_")
125
+ else:
126
+ abi = None
127
+
128
+ return abi
129
+
130
+
131
+ def safer_version(version: str) -> str:
132
+ return safe_version(version).replace("-", "_")
133
+
134
+
135
+ class bdist_wheel(Command):
136
+ description = "create a wheel distribution"
137
+
138
+ supported_compressions = {
139
+ "stored": ZIP_STORED,
140
+ "deflated": ZIP_DEFLATED,
141
+ }
142
+
143
+ user_options = [
144
+ ("bdist-dir=", "b", "temporary directory for creating the distribution"),
145
+ (
146
+ "plat-name=",
147
+ "p",
148
+ "platform name to embed in generated filenames "
149
+ f"[default: {get_platform(None)}]",
150
+ ),
151
+ (
152
+ "keep-temp",
153
+ "k",
154
+ "keep the pseudo-installation tree around after "
155
+ "creating the distribution archive",
156
+ ),
157
+ ("dist-dir=", "d", "directory to put final built distributions in"),
158
+ ("skip-build", None, "skip rebuilding everything (for testing/debugging)"),
159
+ (
160
+ "relative",
161
+ None,
162
+ "build the archive using relative paths [default: false]",
163
+ ),
164
+ (
165
+ "owner=",
166
+ "u",
167
+ "Owner name used when creating a tar file [default: current user]",
168
+ ),
169
+ (
170
+ "group=",
171
+ "g",
172
+ "Group name used when creating a tar file [default: current group]",
173
+ ),
174
+ ("universal", None, "*DEPRECATED* make a universal wheel [default: false]"),
175
+ (
176
+ "compression=",
177
+ None,
178
+ f"zipfile compression (one of: {', '.join(supported_compressions)}) [default: 'deflated']",
179
+ ),
180
+ (
181
+ "python-tag=",
182
+ None,
183
+ f"Python implementation compatibility tag [default: '{python_tag()}']",
184
+ ),
185
+ (
186
+ "build-number=",
187
+ None,
188
+ "Build number for this particular version. "
189
+ "As specified in PEP-0427, this must start with a digit. "
190
+ "[default: None]",
191
+ ),
192
+ (
193
+ "py-limited-api=",
194
+ None,
195
+ "Python tag (cp32|cp33|cpNN) for abi3 wheel tag [default: false]",
196
+ ),
197
+ (
198
+ "dist-info-dir=",
199
+ None,
200
+ "directory where a pre-generated dist-info can be found (e.g. as a "
201
+ "result of calling the PEP517 'prepare_metadata_for_build_wheel' "
202
+ "method)",
203
+ ),
204
+ ]
205
+
206
+ boolean_options = ["keep-temp", "skip-build", "relative", "universal"]
207
+
208
+ def initialize_options(self) -> None:
209
+ self.bdist_dir: str | None = None
210
+ self.data_dir = ""
211
+ self.plat_name: str | None = None
212
+ self.plat_tag: str | None = None
213
+ self.format = "zip"
214
+ self.keep_temp = False
215
+ self.dist_dir: str | None = None
216
+ self.dist_info_dir = None
217
+ self.egginfo_dir: str | None = None
218
+ self.root_is_pure: bool | None = None
219
+ self.skip_build = False
220
+ self.relative = False
221
+ self.owner = None
222
+ self.group = None
223
+ self.universal = False
224
+ self.compression: str | int = "deflated"
225
+ self.python_tag = python_tag()
226
+ self.build_number: str | None = None
227
+ self.py_limited_api: str | Literal[False] = False
228
+ self.plat_name_supplied = False
229
+
230
+ def finalize_options(self) -> None:
231
+ if not self.bdist_dir:
232
+ bdist_base = self.get_finalized_command("bdist").bdist_base
233
+ self.bdist_dir = os.path.join(bdist_base, "wheel")
234
+
235
+ if self.dist_info_dir is None:
236
+ egg_info = cast(egg_info_cls, self.distribution.get_command_obj("egg_info"))
237
+ egg_info.ensure_finalized() # needed for correct `wheel_dist_name`
238
+
239
+ self.data_dir = self.wheel_dist_name + ".data"
240
+ self.plat_name_supplied = bool(self.plat_name)
241
+
242
+ need_options = ("dist_dir", "plat_name", "skip_build")
243
+
244
+ self.set_undefined_options("bdist", *zip(need_options, need_options))
245
+
246
+ self.root_is_pure = not (
247
+ self.distribution.has_ext_modules() or self.distribution.has_c_libraries()
248
+ )
249
+
250
+ self._validate_py_limited_api()
251
+
252
+ # Support legacy [wheel] section for setting universal
253
+ wheel = self.distribution.get_option_dict("wheel")
254
+ if "universal" in wheel: # pragma: no cover
255
+ # please don't define this in your global configs
256
+ log.warn("The [wheel] section is deprecated. Use [bdist_wheel] instead.")
257
+ val = wheel["universal"][1].strip()
258
+ if val.lower() in ("1", "true", "yes"):
259
+ self.universal = True
260
+
261
+ if self.universal:
262
+ SetuptoolsDeprecationWarning.emit(
263
+ "bdist_wheel.universal is deprecated",
264
+ """
265
+ With Python 2.7 end-of-life, support for building universal wheels
266
+ (i.e., wheels that support both Python 2 and Python 3)
267
+ is being obviated.
268
+ Please discontinue using this option, or if you still need it,
269
+ file an issue with pypa/setuptools describing your use case.
270
+ """,
271
+ due_date=(2025, 8, 30), # Introduced in 2024-08-30
272
+ )
273
+
274
+ if self.build_number is not None and not self.build_number[:1].isdigit():
275
+ raise ValueError("Build tag (build-number) must start with a digit.")
276
+
277
+ def _validate_py_limited_api(self) -> None:
278
+ if not self.py_limited_api:
279
+ return
280
+
281
+ if not re.match(PY_LIMITED_API_PATTERN, self.py_limited_api):
282
+ raise ValueError(f"py-limited-api must match '{PY_LIMITED_API_PATTERN}'")
283
+
284
+ if sysconfig.get_config_var("Py_GIL_DISABLED"):
285
+ raise ValueError(
286
+ f"`py_limited_api={self.py_limited_api!r}` not supported. "
287
+ "`Py_LIMITED_API` is currently incompatible with "
288
+ "`Py_GIL_DISABLED`. "
289
+ "See https://github.com/python/cpython/issues/111506."
290
+ )
291
+
292
+ @property
293
+ def wheel_dist_name(self) -> str:
294
+ """Return distribution full name with - replaced with _"""
295
+ components = [
296
+ safer_name(self.distribution.get_name()),
297
+ safer_version(self.distribution.get_version()),
298
+ ]
299
+ if self.build_number:
300
+ components.append(self.build_number)
301
+ return "-".join(components)
302
+
303
+ def get_tag(self) -> tuple[str, str, str]:
304
+ # bdist sets self.plat_name if unset, we should only use it for purepy
305
+ # wheels if the user supplied it.
306
+ if self.plat_name_supplied and self.plat_name:
307
+ plat_name = self.plat_name
308
+ elif self.root_is_pure:
309
+ plat_name = "any"
310
+ else:
311
+ # macosx contains system version in platform name so need special handle
312
+ if self.plat_name and not self.plat_name.startswith("macosx"):
313
+ plat_name = self.plat_name
314
+ else:
315
+ # on macosx always limit the platform name to comply with any
316
+ # c-extension modules in bdist_dir, since the user can specify
317
+ # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake
318
+
319
+ # on other platforms, and on macosx if there are no c-extension
320
+ # modules, use the default platform name.
321
+ plat_name = get_platform(self.bdist_dir)
322
+
323
+ if _is_32bit_interpreter():
324
+ if plat_name in ("linux-x86_64", "linux_x86_64"):
325
+ plat_name = "linux_i686"
326
+ if plat_name in ("linux-aarch64", "linux_aarch64"):
327
+ # TODO armv8l, packaging pull request #690 => this did not land
328
+ # in pip/packaging yet
329
+ plat_name = "linux_armv7l"
330
+
331
+ plat_name = (
332
+ plat_name.lower().replace("-", "_").replace(".", "_").replace(" ", "_")
333
+ )
334
+
335
+ if self.root_is_pure:
336
+ if self.universal:
337
+ impl = "py2.py3"
338
+ else:
339
+ impl = self.python_tag
340
+ tag = (impl, "none", plat_name)
341
+ else:
342
+ impl_name = tags.interpreter_name()
343
+ impl_ver = tags.interpreter_version()
344
+ impl = impl_name + impl_ver
345
+ # We don't work on CPython 3.1, 3.0.
346
+ if self.py_limited_api and (impl_name + impl_ver).startswith("cp3"):
347
+ impl = self.py_limited_api
348
+ abi_tag = "abi3"
349
+ else:
350
+ abi_tag = str(get_abi_tag()).lower()
351
+ tag = (impl, abi_tag, plat_name)
352
+ # issue gh-374: allow overriding plat_name
353
+ supported_tags = [
354
+ (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()
355
+ ]
356
+ assert tag in supported_tags, (
357
+ f"would build wheel with unsupported tag {tag}"
358
+ )
359
+ return tag
360
+
361
+ def run(self):
362
+ build_scripts = self.reinitialize_command("build_scripts")
363
+ build_scripts.executable = "python"
364
+ build_scripts.force = True
365
+
366
+ build_ext = self.reinitialize_command("build_ext")
367
+ build_ext.inplace = False
368
+
369
+ if not self.skip_build:
370
+ self.run_command("build")
371
+
372
+ install = self.reinitialize_command("install", reinit_subcommands=True)
373
+ install.root = self.bdist_dir
374
+ install.compile = False
375
+ install.skip_build = self.skip_build
376
+ install.warn_dir = False
377
+
378
+ # A wheel without setuptools scripts is more cross-platform.
379
+ # Use the (undocumented) `no_ep` option to setuptools'
380
+ # install_scripts command to avoid creating entry point scripts.
381
+ install_scripts = self.reinitialize_command("install_scripts")
382
+ install_scripts.no_ep = True
383
+
384
+ # Use a custom scheme for the archive, because we have to decide
385
+ # at installation time which scheme to use.
386
+ for key in ("headers", "scripts", "data", "purelib", "platlib"):
387
+ setattr(install, "install_" + key, os.path.join(self.data_dir, key))
388
+
389
+ basedir_observed = ""
390
+
391
+ if os.name == "nt":
392
+ # win32 barfs if any of these are ''; could be '.'?
393
+ # (distutils.command.install:change_roots bug)
394
+ basedir_observed = os.path.normpath(os.path.join(self.data_dir, ".."))
395
+ self.install_libbase = self.install_lib = basedir_observed
396
+
397
+ setattr(
398
+ install,
399
+ "install_purelib" if self.root_is_pure else "install_platlib",
400
+ basedir_observed,
401
+ )
402
+
403
+ log.info(f"installing to {self.bdist_dir}")
404
+
405
+ self.run_command("install")
406
+
407
+ impl_tag, abi_tag, plat_tag = self.get_tag()
408
+ archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
409
+ if not self.relative:
410
+ archive_root = self.bdist_dir
411
+ else:
412
+ archive_root = os.path.join(
413
+ self.bdist_dir, self._ensure_relative(install.install_base)
414
+ )
415
+
416
+ self.set_undefined_options("install_egg_info", ("target", "egginfo_dir"))
417
+ distinfo_dirname = (
418
+ f"{safer_name(self.distribution.get_name())}-"
419
+ f"{safer_version(self.distribution.get_version())}.dist-info"
420
+ )
421
+ distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)
422
+ if self.dist_info_dir:
423
+ # Use the given dist-info directly.
424
+ log.debug(f"reusing {self.dist_info_dir}")
425
+ shutil.copytree(self.dist_info_dir, distinfo_dir)
426
+ # Egg info is still generated, so remove it now to avoid it getting
427
+ # copied into the wheel.
428
+ _shutil.rmtree(self.egginfo_dir)
429
+ else:
430
+ # Convert the generated egg-info into dist-info.
431
+ self.egg2dist(self.egginfo_dir, distinfo_dir)
432
+
433
+ self.write_wheelfile(distinfo_dir)
434
+
435
+ # Make the archive
436
+ if not os.path.exists(self.dist_dir):
437
+ os.makedirs(self.dist_dir)
438
+
439
+ wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
440
+ with WheelFile(wheel_path, "w", self._zip_compression()) as wf:
441
+ wf.write_files(archive_root)
442
+
443
+ # Add to 'Distribution.dist_files' so that the "upload" command works
444
+ getattr(self.distribution, "dist_files", []).append((
445
+ "bdist_wheel",
446
+ f"{sys.version_info.major}.{sys.version_info.minor}",
447
+ wheel_path,
448
+ ))
449
+
450
+ if not self.keep_temp:
451
+ log.info(f"removing {self.bdist_dir}")
452
+ _shutil.rmtree(self.bdist_dir)
453
+
454
+ def write_wheelfile(
455
+ self, wheelfile_base: str, generator: str = f"setuptools ({__version__})"
456
+ ) -> None:
457
+ from email.message import Message
458
+
459
+ msg = Message()
460
+ msg["Wheel-Version"] = "1.0" # of the spec
461
+ msg["Generator"] = generator
462
+ msg["Root-Is-Purelib"] = str(self.root_is_pure).lower()
463
+ if self.build_number is not None:
464
+ msg["Build"] = self.build_number
465
+
466
+ # Doesn't work for bdist_wininst
467
+ impl_tag, abi_tag, plat_tag = self.get_tag()
468
+ for impl in impl_tag.split("."):
469
+ for abi in abi_tag.split("."):
470
+ for plat in plat_tag.split("."):
471
+ msg["Tag"] = "-".join((impl, abi, plat))
472
+
473
+ wheelfile_path = os.path.join(wheelfile_base, "WHEEL")
474
+ log.info(f"creating {wheelfile_path}")
475
+ with open(wheelfile_path, "wb") as f:
476
+ BytesGenerator(f, maxheaderlen=0).flatten(msg)
477
+
478
+ def _ensure_relative(self, path: str) -> str:
479
+ # copied from dir_util, deleted
480
+ drive, path = os.path.splitdrive(path)
481
+ if path[0:1] == os.sep:
482
+ path = drive + path[1:]
483
+ return path
484
+
485
+ @property
486
+ def license_paths(self) -> Iterable[str]:
487
+ if setuptools_major_version >= 57:
488
+ # Setuptools has resolved any patterns to actual file names
489
+ return self.distribution.metadata.license_files or ()
490
+
491
+ files = set[str]()
492
+ metadata = self.distribution.get_option_dict("metadata")
493
+ if setuptools_major_version >= 42:
494
+ # Setuptools recognizes the license_files option but does not do globbing
495
+ patterns = cast(Sequence[str], self.distribution.metadata.license_files)
496
+ else:
497
+ # Prior to those, wheel is entirely responsible for handling license files
498
+ if "license_files" in metadata:
499
+ patterns = metadata["license_files"][1].split()
500
+ else:
501
+ patterns = ()
502
+
503
+ if "license_file" in metadata:
504
+ warnings.warn(
505
+ 'The "license_file" option is deprecated. Use "license_files" instead.',
506
+ DeprecationWarning,
507
+ stacklevel=2,
508
+ )
509
+ files.add(metadata["license_file"][1])
510
+
511
+ if not files and not patterns and not isinstance(patterns, list):
512
+ patterns = ("LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*")
513
+
514
+ for pattern in patterns:
515
+ for path in iglob(pattern):
516
+ if path.endswith("~"):
517
+ log.debug(
518
+ f'ignoring license file "{path}" as it looks like a backup'
519
+ )
520
+ continue
521
+
522
+ if path not in files and os.path.isfile(path):
523
+ log.info(
524
+ f'adding license file "{path}" (matched pattern "{pattern}")'
525
+ )
526
+ files.add(path)
527
+
528
+ return files
529
+
530
+ def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None:
531
+ """Convert an .egg-info directory into a .dist-info directory"""
532
+
533
+ def adios(p: str) -> None:
534
+ """Appropriately delete directory, file or link."""
535
+ if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
536
+ _shutil.rmtree(p)
537
+ elif os.path.exists(p):
538
+ os.unlink(p)
539
+
540
+ adios(distinfo_path)
541
+
542
+ if not os.path.exists(egginfo_path):
543
+ # There is no egg-info. This is probably because the egg-info
544
+ # file/directory is not named matching the distribution name used
545
+ # to name the archive file. Check for this case and report
546
+ # accordingly.
547
+ import glob
548
+
549
+ pat = os.path.join(os.path.dirname(egginfo_path), "*.egg-info")
550
+ possible = glob.glob(pat)
551
+ err = f"Egg metadata expected at {egginfo_path} but not found"
552
+ if possible:
553
+ alt = os.path.basename(possible[0])
554
+ err += f" ({alt} found - possible misnamed archive file?)"
555
+
556
+ raise ValueError(err)
557
+
558
+ # .egg-info is a directory
559
+ pkginfo_path = os.path.join(egginfo_path, "PKG-INFO")
560
+
561
+ # ignore common egg metadata that is useless to wheel
562
+ shutil.copytree(
563
+ egginfo_path,
564
+ distinfo_path,
565
+ ignore=lambda x, y: {
566
+ "PKG-INFO",
567
+ "requires.txt",
568
+ "SOURCES.txt",
569
+ "not-zip-safe",
570
+ },
571
+ )
572
+
573
+ # delete dependency_links if it is only whitespace
574
+ dependency_links_path = os.path.join(distinfo_path, "dependency_links.txt")
575
+ with open(dependency_links_path, encoding="utf-8") as dependency_links_file:
576
+ dependency_links = dependency_links_file.read().strip()
577
+ if not dependency_links:
578
+ adios(dependency_links_path)
579
+
580
+ metadata_path = os.path.join(distinfo_path, "METADATA")
581
+ shutil.copy(pkginfo_path, metadata_path)
582
+
583
+ licenses_folder_path = os.path.join(distinfo_path, "licenses")
584
+ for license_path in self.license_paths:
585
+ safe_path = _safe_license_file(license_path)
586
+ dist_info_license_path = os.path.join(licenses_folder_path, safe_path)
587
+ os.makedirs(os.path.dirname(dist_info_license_path), exist_ok=True)
588
+ shutil.copy(license_path, dist_info_license_path)
589
+
590
+ adios(egginfo_path)
591
+
592
+ def _zip_compression(self) -> int:
593
+ if (
594
+ isinstance(self.compression, int)
595
+ and self.compression in self.supported_compressions.values()
596
+ ):
597
+ return self.compression
598
+
599
+ compression = self.supported_compressions.get(str(self.compression))
600
+ if compression is not None:
601
+ return compression
602
+
603
+ raise ValueError(f"Unsupported compression: {self.compression!r}")
python/Lib/site-packages/setuptools/command/build.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol
4
+
5
+ from ..dist import Distribution
6
+
7
+ from distutils.command.build import build as _build
8
+
9
+ _ORIGINAL_SUBCOMMANDS = {"build_py", "build_clib", "build_ext", "build_scripts"}
10
+
11
+
12
+ class build(_build):
13
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
14
+
15
+ # copy to avoid sharing the object with parent class
16
+ sub_commands = _build.sub_commands[:]
17
+
18
+
19
+ class SubCommand(Protocol):
20
+ """In order to support editable installations (see :pep:`660`) all
21
+ build subcommands **SHOULD** implement this protocol. They also **MUST** inherit
22
+ from ``setuptools.Command``.
23
+
24
+ When creating an :pep:`editable wheel <660>`, ``setuptools`` will try to evaluate
25
+ custom ``build`` subcommands using the following procedure:
26
+
27
+ 1. ``setuptools`` will set the ``editable_mode`` attribute to ``True``
28
+ 2. ``setuptools`` will execute the ``run()`` command.
29
+
30
+ .. important::
31
+ Subcommands **SHOULD** take advantage of ``editable_mode=True`` to adequate
32
+ its behaviour or perform optimisations.
33
+
34
+ For example, if a subcommand doesn't need to generate an extra file and
35
+ all it does is to copy a source file into the build directory,
36
+ ``run()`` **SHOULD** simply "early return".
37
+
38
+ Similarly, if the subcommand creates files that would be placed alongside
39
+ Python files in the final distribution, during an editable install
40
+ the command **SHOULD** generate these files "in place" (i.e. write them to
41
+ the original source directory, instead of using the build directory).
42
+ Note that ``get_output_mapping()`` should reflect that and include mappings
43
+ for "in place" builds accordingly.
44
+
45
+ 3. ``setuptools`` use any knowledge it can derive from the return values of
46
+ ``get_outputs()`` and ``get_output_mapping()`` to create an editable wheel.
47
+ When relevant ``setuptools`` **MAY** attempt to use file links based on the value
48
+ of ``get_output_mapping()``. Alternatively, ``setuptools`` **MAY** attempt to use
49
+ :doc:`import hooks <python:reference/import>` to redirect any attempt to import
50
+ to the directory with the original source code and other files built in place.
51
+
52
+ Please note that custom sub-commands **SHOULD NOT** rely on ``run()`` being
53
+ executed (or not) to provide correct return values for ``get_outputs()``,
54
+ ``get_output_mapping()`` or ``get_source_files()``. The ``get_*`` methods should
55
+ work independently of ``run()``.
56
+ """
57
+
58
+ editable_mode: bool = False
59
+ """Boolean flag that will be set to ``True`` when setuptools is used for an
60
+ editable installation (see :pep:`660`).
61
+ Implementations **SHOULD** explicitly set the default value of this attribute to
62
+ ``False``.
63
+ When subcommands run, they can use this flag to perform optimizations or change
64
+ their behaviour accordingly.
65
+ """
66
+
67
+ build_lib: str
68
+ """String representing the directory where the build artifacts should be stored,
69
+ e.g. ``build/lib``.
70
+ For example, if a distribution wants to provide a Python module named ``pkg.mod``,
71
+ then a corresponding file should be written to ``{build_lib}/package/module.py``.
72
+ A way of thinking about this is that the files saved under ``build_lib``
73
+ would be eventually copied to one of the directories in :obj:`site.PREFIXES`
74
+ upon installation.
75
+
76
+ A command that produces platform-independent files (e.g. compiling text templates
77
+ into Python functions), **CAN** initialize ``build_lib`` by copying its value from
78
+ the ``build_py`` command. On the other hand, a command that produces
79
+ platform-specific files **CAN** initialize ``build_lib`` by copying its value from
80
+ the ``build_ext`` command. In general this is done inside the ``finalize_options``
81
+ method with the help of the ``set_undefined_options`` command::
82
+
83
+ def finalize_options(self):
84
+ self.set_undefined_options("build_py", ("build_lib", "build_lib"))
85
+ ...
86
+ """
87
+
88
+ def initialize_options(self) -> None:
89
+ """(Required by the original :class:`setuptools.Command` interface)"""
90
+ ...
91
+
92
+ def finalize_options(self) -> None:
93
+ """(Required by the original :class:`setuptools.Command` interface)"""
94
+ ...
95
+
96
+ def run(self) -> None:
97
+ """(Required by the original :class:`setuptools.Command` interface)"""
98
+ ...
99
+
100
+ def get_source_files(self) -> list[str]:
101
+ """
102
+ Return a list of all files that are used by the command to create the expected
103
+ outputs.
104
+ For example, if your build command transpiles Java files into Python, you should
105
+ list here all the Java files.
106
+ The primary purpose of this function is to help populating the ``sdist``
107
+ with all the files necessary to build the distribution.
108
+ All files should be strings relative to the project root directory.
109
+ """
110
+ ...
111
+
112
+ def get_outputs(self) -> list[str]:
113
+ """
114
+ Return a list of files intended for distribution as they would have been
115
+ produced by the build.
116
+ These files should be strings in the form of
117
+ ``"{build_lib}/destination/file/path"``.
118
+
119
+ .. note::
120
+ The return value of ``get_output()`` should include all files used as keys
121
+ in ``get_output_mapping()`` plus files that are generated during the build
122
+ and don't correspond to any source file already present in the project.
123
+ """
124
+ ...
125
+
126
+ def get_output_mapping(self) -> dict[str, str]:
127
+ """
128
+ Return a mapping between destination files as they would be produced by the
129
+ build (dict keys) into the respective existing (source) files (dict values).
130
+ Existing (source) files should be represented as strings relative to the project
131
+ root directory.
132
+ Destination files should be strings in the form of
133
+ ``"{build_lib}/destination/file/path"``.
134
+ """
135
+ ...
python/Lib/site-packages/setuptools/command/build_clib.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..dist import Distribution
2
+ from ..modified import newer_pairwise_group
3
+
4
+ import distutils.command.build_clib as orig
5
+ from distutils import log
6
+ from distutils.errors import DistutilsSetupError
7
+
8
+
9
+ class build_clib(orig.build_clib):
10
+ """
11
+ Override the default build_clib behaviour to do the following:
12
+
13
+ 1. Implement a rudimentary timestamp-based dependency system
14
+ so 'compile()' doesn't run every time.
15
+ 2. Add more keys to the 'build_info' dictionary:
16
+ * obj_deps - specify dependencies for each object compiled.
17
+ this should be a dictionary mapping a key
18
+ with the source filename to a list of
19
+ dependencies. Use an empty string for global
20
+ dependencies.
21
+ * cflags - specify a list of additional flags to pass to
22
+ the compiler.
23
+ """
24
+
25
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
26
+
27
+ def build_libraries(self, libraries) -> None:
28
+ for lib_name, build_info in libraries:
29
+ sources = build_info.get('sources')
30
+ if sources is None or not isinstance(sources, (list, tuple)):
31
+ raise DistutilsSetupError(
32
+ f"in 'libraries' option (library '{lib_name}'), "
33
+ "'sources' must be present and must be "
34
+ "a list of source filenames"
35
+ )
36
+ sources = sorted(list(sources))
37
+
38
+ log.info("building '%s' library", lib_name)
39
+
40
+ # Make sure everything is the correct type.
41
+ # obj_deps should be a dictionary of keys as sources
42
+ # and a list/tuple of files that are its dependencies.
43
+ obj_deps = build_info.get('obj_deps', dict())
44
+ if not isinstance(obj_deps, dict):
45
+ raise DistutilsSetupError(
46
+ f"in 'libraries' option (library '{lib_name}'), "
47
+ "'obj_deps' must be a dictionary of "
48
+ "type 'source: list'"
49
+ )
50
+ dependencies = []
51
+
52
+ # Get the global dependencies that are specified by the '' key.
53
+ # These will go into every source's dependency list.
54
+ global_deps = obj_deps.get('', list())
55
+ if not isinstance(global_deps, (list, tuple)):
56
+ raise DistutilsSetupError(
57
+ f"in 'libraries' option (library '{lib_name}'), "
58
+ "'obj_deps' must be a dictionary of "
59
+ "type 'source: list'"
60
+ )
61
+
62
+ # Build the list to be used by newer_pairwise_group
63
+ # each source will be auto-added to its dependencies.
64
+ for source in sources:
65
+ src_deps = [source]
66
+ src_deps.extend(global_deps)
67
+ extra_deps = obj_deps.get(source, list())
68
+ if not isinstance(extra_deps, (list, tuple)):
69
+ raise DistutilsSetupError(
70
+ f"in 'libraries' option (library '{lib_name}'), "
71
+ "'obj_deps' must be a dictionary of "
72
+ "type 'source: list'"
73
+ )
74
+ src_deps.extend(extra_deps)
75
+ dependencies.append(src_deps)
76
+
77
+ expected_objects = self.compiler.object_filenames(
78
+ sources,
79
+ output_dir=self.build_temp,
80
+ )
81
+
82
+ if newer_pairwise_group(dependencies, expected_objects) != ([], []):
83
+ # First, compile the source code to object files in the library
84
+ # directory. (This should probably change to putting object
85
+ # files in a temporary build directory.)
86
+ macros = build_info.get('macros')
87
+ include_dirs = build_info.get('include_dirs')
88
+ cflags = build_info.get('cflags')
89
+ self.compiler.compile(
90
+ sources,
91
+ output_dir=self.build_temp,
92
+ macros=macros,
93
+ include_dirs=include_dirs,
94
+ extra_postargs=cflags,
95
+ debug=self.debug,
96
+ )
97
+
98
+ # Now "link" the object files together into a static library.
99
+ # (On Unix at least, this isn't really linking -- it just
100
+ # builds an archive. Whatever.)
101
+ self.compiler.create_static_lib(
102
+ expected_objects, lib_name, output_dir=self.build_clib, debug=self.debug
103
+ )
python/Lib/site-packages/setuptools/command/build_ext.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import operator
5
+ import os
6
+ import sys
7
+ import textwrap
8
+ from collections.abc import Iterator
9
+ from importlib.machinery import EXTENSION_SUFFIXES
10
+ from importlib.util import cache_from_source as _compiled_file_name
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING
13
+
14
+ from setuptools.dist import Distribution
15
+ from setuptools.errors import BaseError
16
+ from setuptools.extension import Extension, Library
17
+
18
+ from distutils import log
19
+ from distutils.ccompiler import new_compiler
20
+ from distutils.sysconfig import customize_compiler, get_config_var
21
+
22
+ if TYPE_CHECKING:
23
+ # Cython not installed on CI tests, causing _build_ext to be `Any`
24
+ from distutils.command.build_ext import build_ext as _build_ext
25
+ else:
26
+ try:
27
+ # Attempt to use Cython for building extensions, if available
28
+ from Cython.Distutils.build_ext import build_ext as _build_ext
29
+
30
+ # Additionally, assert that the compiler module will load
31
+ # also. Ref #1229.
32
+ __import__('Cython.Compiler.Main')
33
+ except ImportError:
34
+ from distutils.command.build_ext import build_ext as _build_ext
35
+
36
+ # make sure _config_vars is initialized
37
+ get_config_var("LDSHARED")
38
+ # Not publicly exposed in typeshed distutils stubs, but this is done on purpose
39
+ # See https://github.com/pypa/setuptools/pull/4228#issuecomment-1959856400
40
+ from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa: E402
41
+
42
+
43
+ def _customize_compiler_for_shlib(compiler):
44
+ if sys.platform == "darwin":
45
+ # building .dylib requires additional compiler flags on OSX; here we
46
+ # temporarily substitute the pyconfig.h variables so that distutils'
47
+ # 'customize_compiler' uses them before we build the shared libraries.
48
+ tmp = _CONFIG_VARS.copy()
49
+ try:
50
+ # XXX Help! I don't have any idea whether these are right...
51
+ _CONFIG_VARS['LDSHARED'] = (
52
+ "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup"
53
+ )
54
+ _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
55
+ _CONFIG_VARS['SO'] = ".dylib"
56
+ customize_compiler(compiler)
57
+ finally:
58
+ _CONFIG_VARS.clear()
59
+ _CONFIG_VARS.update(tmp)
60
+ else:
61
+ customize_compiler(compiler)
62
+
63
+
64
+ have_rtld = False
65
+ use_stubs = False
66
+ libtype = 'shared'
67
+
68
+ if sys.platform == "darwin":
69
+ use_stubs = True
70
+ elif os.name != 'nt':
71
+ try:
72
+ import dl # type: ignore[import-not-found] # https://github.com/python/mypy/issues/13002
73
+
74
+ use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
75
+ except ImportError:
76
+ pass
77
+
78
+
79
+ def get_abi3_suffix():
80
+ """Return the file extension for an abi3-compliant Extension()"""
81
+ for suffix in EXTENSION_SUFFIXES:
82
+ if '.abi3' in suffix: # Unix
83
+ return suffix
84
+ elif suffix == '.pyd': # Windows
85
+ return suffix
86
+ return None
87
+
88
+
89
+ class build_ext(_build_ext):
90
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
91
+ editable_mode = False
92
+ inplace = False
93
+
94
+ def run(self) -> None:
95
+ """Build extensions in build directory, then copy if --inplace"""
96
+ old_inplace, self.inplace = self.inplace, False
97
+ _build_ext.run(self)
98
+ self.inplace = old_inplace
99
+ if old_inplace:
100
+ self.copy_extensions_to_source()
101
+
102
+ def _get_inplace_equivalent(self, build_py, ext: Extension) -> tuple[str, str]:
103
+ fullname = self.get_ext_fullname(ext.name)
104
+ filename = self.get_ext_filename(fullname)
105
+ modpath = fullname.split('.')
106
+ package = '.'.join(modpath[:-1])
107
+ package_dir = build_py.get_package_dir(package)
108
+ inplace_file = os.path.join(package_dir, os.path.basename(filename))
109
+ regular_file = os.path.join(self.build_lib, filename)
110
+ return (inplace_file, regular_file)
111
+
112
+ def copy_extensions_to_source(self) -> None:
113
+ build_py = self.get_finalized_command('build_py')
114
+ for ext in self.extensions:
115
+ inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
116
+
117
+ # Always copy, even if source is older than destination, to ensure
118
+ # that the right extensions for the current Python/platform are
119
+ # used.
120
+ if os.path.exists(regular_file) or not ext.optional:
121
+ self.copy_file(regular_file, inplace_file, level=self.verbose)
122
+
123
+ if ext._needs_stub:
124
+ inplace_stub = self._get_equivalent_stub(ext, inplace_file)
125
+ self._write_stub_file(inplace_stub, ext, compile=True)
126
+ # Always compile stub and remove the original (leave the cache behind)
127
+ # (this behaviour was observed in previous iterations of the code)
128
+
129
+ def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str:
130
+ dir_ = os.path.dirname(output_file)
131
+ _, _, name = ext.name.rpartition(".")
132
+ return f"{os.path.join(dir_, name)}.py"
133
+
134
+ def _get_output_mapping(self) -> Iterator[tuple[str, str]]:
135
+ if not self.inplace:
136
+ return
137
+
138
+ build_py = self.get_finalized_command('build_py')
139
+ opt = self.get_finalized_command('install_lib').optimize or ""
140
+
141
+ for ext in self.extensions:
142
+ inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)
143
+ yield (regular_file, inplace_file)
144
+
145
+ if ext._needs_stub:
146
+ # This version of `build_ext` always builds artifacts in another dir,
147
+ # when "inplace=True" is given it just copies them back.
148
+ # This is done in the `copy_extensions_to_source` function, which
149
+ # always compile stub files via `_compile_and_remove_stub`.
150
+ # At the end of the process, a `.pyc` stub file is created without the
151
+ # corresponding `.py`.
152
+
153
+ inplace_stub = self._get_equivalent_stub(ext, inplace_file)
154
+ regular_stub = self._get_equivalent_stub(ext, regular_file)
155
+ inplace_cache = _compiled_file_name(inplace_stub, optimization=opt)
156
+ output_cache = _compiled_file_name(regular_stub, optimization=opt)
157
+ yield (output_cache, inplace_cache)
158
+
159
+ def get_ext_filename(self, fullname: str) -> str:
160
+ so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
161
+ if so_ext:
162
+ filename = os.path.join(*fullname.split('.')) + so_ext
163
+ else:
164
+ filename = _build_ext.get_ext_filename(self, fullname)
165
+ ext_suffix = get_config_var('EXT_SUFFIX')
166
+ if not isinstance(ext_suffix, str):
167
+ raise OSError(
168
+ "Configuration variable EXT_SUFFIX not found for this platform "
169
+ "and environment variable SETUPTOOLS_EXT_SUFFIX is missing"
170
+ )
171
+ so_ext = ext_suffix
172
+
173
+ if fullname in self.ext_map:
174
+ ext = self.ext_map[fullname]
175
+ abi3_suffix = get_abi3_suffix()
176
+ if ext.py_limited_api and abi3_suffix: # Use abi3
177
+ filename = filename[: -len(so_ext)] + abi3_suffix
178
+ if isinstance(ext, Library):
179
+ fn, ext = os.path.splitext(filename)
180
+ return self.shlib_compiler.library_filename(fn, libtype)
181
+ elif use_stubs and ext._links_to_dynamic:
182
+ d, fn = os.path.split(filename)
183
+ return os.path.join(d, 'dl-' + fn)
184
+ return filename
185
+
186
+ def initialize_options(self):
187
+ _build_ext.initialize_options(self)
188
+ self.shlib_compiler = None
189
+ self.shlibs = []
190
+ self.ext_map = {}
191
+ self.editable_mode = False
192
+
193
+ def finalize_options(self) -> None:
194
+ _build_ext.finalize_options(self)
195
+ self.extensions = self.extensions or []
196
+ self.check_extensions_list(self.extensions)
197
+ self.shlibs = [ext for ext in self.extensions if isinstance(ext, Library)]
198
+ if self.shlibs:
199
+ self.setup_shlib_compiler()
200
+ for ext in self.extensions:
201
+ ext._full_name = self.get_ext_fullname(ext.name)
202
+ for ext in self.extensions:
203
+ fullname = ext._full_name
204
+ self.ext_map[fullname] = ext
205
+
206
+ # distutils 3.1 will also ask for module names
207
+ # XXX what to do with conflicts?
208
+ self.ext_map[fullname.split('.')[-1]] = ext
209
+
210
+ ltd = self.shlibs and self.links_to_dynamic(ext) or False
211
+ ns = ltd and use_stubs and not isinstance(ext, Library)
212
+ ext._links_to_dynamic = ltd
213
+ ext._needs_stub = ns
214
+ filename = ext._file_name = self.get_ext_filename(fullname)
215
+ libdir = os.path.dirname(os.path.join(self.build_lib, filename))
216
+ if ltd and libdir not in ext.library_dirs:
217
+ ext.library_dirs.append(libdir)
218
+ if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
219
+ ext.runtime_library_dirs.append(os.curdir)
220
+
221
+ if self.editable_mode:
222
+ self.inplace = True
223
+
224
+ def setup_shlib_compiler(self) -> None:
225
+ compiler = self.shlib_compiler = new_compiler(
226
+ compiler=self.compiler, force=self.force
227
+ )
228
+ _customize_compiler_for_shlib(compiler)
229
+
230
+ if self.include_dirs is not None:
231
+ compiler.set_include_dirs(self.include_dirs)
232
+ if self.define is not None:
233
+ # 'define' option is a list of (name,value) tuples
234
+ for name, value in self.define:
235
+ compiler.define_macro(name, value)
236
+ if self.undef is not None:
237
+ for macro in self.undef:
238
+ compiler.undefine_macro(macro)
239
+ if self.libraries is not None:
240
+ compiler.set_libraries(self.libraries)
241
+ if self.library_dirs is not None:
242
+ compiler.set_library_dirs(self.library_dirs)
243
+ if self.rpath is not None:
244
+ compiler.set_runtime_library_dirs(self.rpath)
245
+ if self.link_objects is not None:
246
+ compiler.set_link_objects(self.link_objects)
247
+
248
+ # hack so distutils' build_extension() builds a library instead
249
+ compiler.link_shared_object = link_shared_object.__get__(compiler) # type: ignore[method-assign]
250
+
251
+ def get_export_symbols(self, ext):
252
+ if isinstance(ext, Library):
253
+ return ext.export_symbols
254
+ return _build_ext.get_export_symbols(self, ext)
255
+
256
+ def build_extension(self, ext) -> None:
257
+ ext._convert_pyx_sources_to_lang()
258
+ _compiler = self.compiler
259
+ try:
260
+ if isinstance(ext, Library):
261
+ self.compiler = self.shlib_compiler
262
+ _build_ext.build_extension(self, ext)
263
+ if ext._needs_stub:
264
+ build_lib = self.get_finalized_command('build_py').build_lib
265
+ self.write_stub(build_lib, ext)
266
+ finally:
267
+ self.compiler = _compiler
268
+
269
+ def links_to_dynamic(self, ext):
270
+ """Return true if 'ext' links to a dynamic lib in the same package"""
271
+ # XXX this should check to ensure the lib is actually being built
272
+ # XXX as dynamic, and not just using a locally-found version or a
273
+ # XXX static-compiled version
274
+ libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
275
+ pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
276
+ return any(pkg + libname in libnames for libname in ext.libraries)
277
+
278
+ def get_source_files(self) -> list[str]:
279
+ return [*_build_ext.get_source_files(self), *self._get_internal_depends()]
280
+
281
+ def _get_internal_depends(self) -> Iterator[str]:
282
+ """Yield ``ext.depends`` that are contained by the project directory"""
283
+ project_root = Path(self.distribution.src_root or os.curdir).resolve()
284
+ depends = (dep for ext in self.extensions for dep in ext.depends)
285
+
286
+ def skip(orig_path: str, reason: str) -> None:
287
+ log.info(
288
+ "dependency %s won't be automatically "
289
+ "included in the manifest: the path %s",
290
+ orig_path,
291
+ reason,
292
+ )
293
+
294
+ for dep in depends:
295
+ path = Path(dep)
296
+
297
+ if path.is_absolute():
298
+ skip(dep, "must be relative")
299
+ continue
300
+
301
+ if ".." in path.parts:
302
+ skip(dep, "can't have `..` segments")
303
+ continue
304
+
305
+ try:
306
+ resolved = (project_root / path).resolve(strict=True)
307
+ except OSError:
308
+ skip(dep, "doesn't exist")
309
+ continue
310
+
311
+ try:
312
+ resolved.relative_to(project_root)
313
+ except ValueError:
314
+ skip(dep, "must be inside the project root")
315
+ continue
316
+
317
+ yield path.as_posix()
318
+
319
+ def get_outputs(self) -> list[str]:
320
+ if self.inplace:
321
+ return list(self.get_output_mapping().keys())
322
+ return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs())
323
+
324
+ def get_output_mapping(self) -> dict[str, str]:
325
+ """See :class:`setuptools.commands.build.SubCommand`"""
326
+ mapping = self._get_output_mapping()
327
+ return dict(sorted(mapping, key=operator.itemgetter(0)))
328
+
329
+ def __get_stubs_outputs(self):
330
+ # assemble the base name for each extension that needs a stub
331
+ ns_ext_bases = (
332
+ os.path.join(self.build_lib, *ext._full_name.split('.'))
333
+ for ext in self.extensions
334
+ if ext._needs_stub
335
+ )
336
+ # pair each base with the extension
337
+ pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
338
+ return list(base + fnext for base, fnext in pairs)
339
+
340
+ def __get_output_extensions(self):
341
+ yield '.py'
342
+ yield '.pyc'
343
+ if self.get_finalized_command('build_py').optimize:
344
+ yield '.pyo'
345
+
346
+ def write_stub(self, output_dir, ext, compile=False) -> None:
347
+ stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py'
348
+ self._write_stub_file(stub_file, ext, compile)
349
+
350
+ def _write_stub_file(self, stub_file: str, ext: Extension, compile=False):
351
+ log.info("writing stub loader for %s to %s", ext._full_name, stub_file)
352
+ if compile and os.path.exists(stub_file):
353
+ raise BaseError(stub_file + " already exists! Please delete.")
354
+ with open(stub_file, 'w', encoding="utf-8") as f:
355
+ content = (
356
+ textwrap
357
+ .dedent(f"""
358
+ def __bootstrap__():
359
+ global __bootstrap__, __file__, __loader__
360
+ import sys, os, importlib.resources as irs, importlib.util
361
+ #rtld import dl
362
+ with irs.files(__name__).joinpath(
363
+ {os.path.basename(ext._file_name)!r}) as __file__:
364
+ del __bootstrap__
365
+ if '__loader__' in globals():
366
+ del __loader__
367
+ #rtld old_flags = sys.getdlopenflags()
368
+ old_dir = os.getcwd()
369
+ try:
370
+ os.chdir(os.path.dirname(__file__))
371
+ #rtld sys.setdlopenflags(dl.RTLD_NOW)
372
+ spec = importlib.util.spec_from_file_location(
373
+ __name__, __file__)
374
+ mod = importlib.util.module_from_spec(spec)
375
+ spec.loader.exec_module(mod)
376
+ finally:
377
+ #rtld sys.setdlopenflags(old_flags)
378
+ os.chdir(old_dir)
379
+ __bootstrap__()
380
+ """)
381
+ .lstrip()
382
+ .replace('#rtld', '#rtld' * (not have_rtld))
383
+ )
384
+ f.write(content)
385
+ if compile:
386
+ self._compile_and_remove_stub(stub_file)
387
+
388
+ def _compile_and_remove_stub(self, stub_file: str):
389
+ from distutils.util import byte_compile
390
+
391
+ byte_compile([stub_file], optimize=0, force=True)
392
+ optimize = self.get_finalized_command('install_lib').optimize
393
+ if optimize > 0:
394
+ byte_compile(
395
+ [stub_file],
396
+ optimize=optimize,
397
+ force=True,
398
+ )
399
+ if os.path.exists(stub_file):
400
+ os.unlink(stub_file)
401
+
402
+
403
+ if use_stubs or os.name == 'nt':
404
+ # Build shared libraries
405
+ #
406
+ def link_shared_object(
407
+ self,
408
+ objects,
409
+ output_libname,
410
+ output_dir=None,
411
+ libraries=None,
412
+ library_dirs=None,
413
+ runtime_library_dirs=None,
414
+ export_symbols=None,
415
+ debug: bool = False,
416
+ extra_preargs=None,
417
+ extra_postargs=None,
418
+ build_temp=None,
419
+ target_lang=None,
420
+ ) -> None:
421
+ self.link(
422
+ self.SHARED_LIBRARY,
423
+ objects,
424
+ output_libname,
425
+ output_dir,
426
+ libraries,
427
+ library_dirs,
428
+ runtime_library_dirs,
429
+ export_symbols,
430
+ debug,
431
+ extra_preargs,
432
+ extra_postargs,
433
+ build_temp,
434
+ target_lang,
435
+ )
436
+
437
+ else:
438
+ # Build static libraries everywhere else
439
+ libtype = 'static'
440
+
441
+ def link_shared_object(
442
+ self,
443
+ objects,
444
+ output_libname,
445
+ output_dir=None,
446
+ libraries=None,
447
+ library_dirs=None,
448
+ runtime_library_dirs=None,
449
+ export_symbols=None,
450
+ debug: bool = False,
451
+ extra_preargs=None,
452
+ extra_postargs=None,
453
+ build_temp=None,
454
+ target_lang=None,
455
+ ) -> None:
456
+ # XXX we need to either disallow these attrs on Library instances,
457
+ # or warn/abort here if set, or something...
458
+ # libraries=None, library_dirs=None, runtime_library_dirs=None,
459
+ # export_symbols=None, extra_preargs=None, extra_postargs=None,
460
+ # build_temp=None
461
+
462
+ assert output_dir is None # distutils build_ext doesn't pass this
463
+ output_dir, filename = os.path.split(output_libname)
464
+ basename, _ext = os.path.splitext(filename)
465
+ if self.library_filename("x").startswith('lib'):
466
+ # strip 'lib' prefix; this is kludgy if some platform uses
467
+ # a different prefix
468
+ basename = basename[3:]
469
+
470
+ self.create_static_lib(objects, basename, output_dir, debug, target_lang)
python/Lib/site-packages/setuptools/command/build_py.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import fnmatch
4
+ import itertools
5
+ import operator
6
+ import os
7
+ import stat
8
+ import textwrap
9
+ from collections.abc import Iterable, Iterator
10
+ from functools import partial
11
+ from glob import glob
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from more_itertools import unique_everseen
16
+
17
+ from .._path import StrPath, StrPathT
18
+ from ..dist import Distribution
19
+ from ..warnings import SetuptoolsDeprecationWarning
20
+
21
+ import distutils.command.build_py as orig
22
+ import distutils.errors
23
+ from distutils.util import convert_path
24
+
25
+ _IMPLICIT_DATA_FILES = ('*.pyi', 'py.typed')
26
+
27
+
28
+ def make_writable(target) -> None:
29
+ os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
30
+
31
+
32
+ class build_py(orig.build_py):
33
+ """Enhanced 'build_py' command that includes data files with packages
34
+
35
+ The data files are specified via a 'package_data' argument to 'setup()'.
36
+ See 'setuptools.dist.Distribution' for more details.
37
+
38
+ Also, this version of the 'build_py' command allows you to specify both
39
+ 'py_modules' and 'packages' in the same setup operation.
40
+ """
41
+
42
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
43
+ editable_mode: bool = False
44
+ existing_egg_info_dir: StrPath | None = None #: Private API, internal use only.
45
+
46
+ def finalize_options(self) -> None:
47
+ orig.build_py.finalize_options(self)
48
+ self.package_data = self.distribution.package_data
49
+ self.exclude_package_data = self.distribution.exclude_package_data or {}
50
+ if 'data_files' in self.__dict__:
51
+ del self.__dict__['data_files']
52
+
53
+ def copy_file( # type: ignore[override] # No overload, no bytes support
54
+ self,
55
+ infile: StrPath,
56
+ outfile: StrPathT,
57
+ preserve_mode: bool = True,
58
+ preserve_times: bool = True,
59
+ link: str | None = None,
60
+ level: object = 1,
61
+ ) -> tuple[StrPathT | str, bool]:
62
+ # Overwrite base class to allow using links
63
+ if link:
64
+ infile = str(Path(infile).resolve())
65
+ outfile = str(Path(outfile).resolve()) # type: ignore[assignment] # Re-assigning a str when outfile is StrPath is ok
66
+ return super().copy_file( # pyright: ignore[reportReturnType] # pypa/distutils#309
67
+ infile, outfile, preserve_mode, preserve_times, link, level
68
+ )
69
+
70
+ def run(self) -> None:
71
+ """Build modules, packages, and copy data files to build directory"""
72
+ if not (self.py_modules or self.packages) or self.editable_mode:
73
+ return
74
+
75
+ if self.py_modules:
76
+ self.build_modules()
77
+
78
+ if self.packages:
79
+ self.build_packages()
80
+ self.build_package_data()
81
+
82
+ # Only compile actual .py files, using our base class' idea of what our
83
+ # output files are.
84
+ self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=False))
85
+
86
+ # Should return "list[tuple[str, str, str, list[str]]] | Any" but can't do without typed distutils on Python 3.12+
87
+ def __getattr__(self, attr: str) -> Any:
88
+ "lazily compute data files"
89
+ if attr == 'data_files':
90
+ self.data_files = self._get_data_files()
91
+ return self.data_files
92
+ return orig.build_py.__getattr__(self, attr)
93
+
94
+ def _get_data_files(self):
95
+ """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
96
+ self.analyze_manifest()
97
+ return list(map(self._get_pkg_data_files, self.packages or ()))
98
+
99
+ def get_data_files_without_manifest(self) -> list[tuple[str, str, str, list[str]]]:
100
+ """
101
+ Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,
102
+ but without triggering any attempt to analyze or build the manifest.
103
+ """
104
+ # Prevent eventual errors from unset `manifest_files`
105
+ # (that would otherwise be set by `analyze_manifest`)
106
+ self.__dict__.setdefault('manifest_files', {})
107
+ return list(map(self._get_pkg_data_files, self.packages or ()))
108
+
109
+ def _get_pkg_data_files(self, package: str) -> tuple[str, str, str, list[str]]:
110
+ # Locate package source directory
111
+ src_dir = self.get_package_dir(package)
112
+
113
+ # Compute package build directory
114
+ build_dir = os.path.join(*([self.build_lib] + package.split('.')))
115
+
116
+ # Strip directory from globbed filenames
117
+ filenames = [
118
+ os.path.relpath(file, src_dir)
119
+ for file in self.find_data_files(package, src_dir)
120
+ ]
121
+ return package, src_dir, build_dir, filenames
122
+
123
+ def find_data_files(self, package, src_dir):
124
+ """Return filenames for package's data files in 'src_dir'"""
125
+ patterns = self._get_platform_patterns(
126
+ self.package_data,
127
+ package,
128
+ src_dir,
129
+ extra_patterns=_IMPLICIT_DATA_FILES,
130
+ )
131
+ globs_expanded = map(partial(glob, recursive=True), patterns)
132
+ # flatten the expanded globs into an iterable of matches
133
+ globs_matches = itertools.chain.from_iterable(globs_expanded)
134
+ glob_files = filter(os.path.isfile, globs_matches)
135
+ files = itertools.chain(
136
+ self.manifest_files.get(package, []),
137
+ glob_files,
138
+ )
139
+ return self.exclude_data_files(package, src_dir, files)
140
+
141
+ def get_outputs(self, include_bytecode: bool = True) -> list[str]: # type: ignore[override] # Using a real boolean instead of 0|1
142
+ """See :class:`setuptools.commands.build.SubCommand`"""
143
+ if self.editable_mode:
144
+ return list(self.get_output_mapping().keys())
145
+ return super().get_outputs(include_bytecode)
146
+
147
+ def get_output_mapping(self) -> dict[str, str]:
148
+ """See :class:`setuptools.commands.build.SubCommand`"""
149
+ mapping = itertools.chain(
150
+ self._get_package_data_output_mapping(),
151
+ self._get_module_mapping(),
152
+ )
153
+ return dict(sorted(mapping, key=operator.itemgetter(0)))
154
+
155
+ def _get_module_mapping(self) -> Iterator[tuple[str, str]]:
156
+ """Iterate over all modules producing (dest, src) pairs."""
157
+ for package, module, module_file in self.find_all_modules():
158
+ package = package.split('.')
159
+ filename = self.get_module_outfile(self.build_lib, package, module)
160
+ yield (filename, module_file)
161
+
162
+ def _get_package_data_output_mapping(self) -> Iterator[tuple[str, str]]:
163
+ """Iterate over package data producing (dest, src) pairs."""
164
+ for package, src_dir, build_dir, filenames in self.data_files:
165
+ for filename in filenames:
166
+ target = os.path.join(build_dir, filename)
167
+ srcfile = os.path.join(src_dir, filename)
168
+ yield (target, srcfile)
169
+
170
+ def build_package_data(self) -> None:
171
+ """Copy data files into build directory"""
172
+ for target, srcfile in self._get_package_data_output_mapping():
173
+ self.mkpath(os.path.dirname(target))
174
+ _outf, _copied = self.copy_file(srcfile, target)
175
+ make_writable(target)
176
+
177
+ def analyze_manifest(self) -> None:
178
+ self.manifest_files: dict[str, list[str]] = {}
179
+ if not self.distribution.include_package_data:
180
+ return
181
+ src_dirs: dict[str, str] = {}
182
+ for package in self.packages or ():
183
+ # Locate package source directory
184
+ src_dirs[assert_relative(self.get_package_dir(package))] = package
185
+
186
+ if (
187
+ self.existing_egg_info_dir
188
+ and Path(self.existing_egg_info_dir, "SOURCES.txt").exists()
189
+ ):
190
+ egg_info_dir = self.existing_egg_info_dir
191
+ manifest = Path(egg_info_dir, "SOURCES.txt")
192
+ files = manifest.read_text(encoding="utf-8").splitlines()
193
+ else:
194
+ self.run_command('egg_info')
195
+ ei_cmd = self.get_finalized_command('egg_info')
196
+ egg_info_dir = ei_cmd.egg_info
197
+ files = ei_cmd.filelist.files
198
+
199
+ check = _IncludePackageDataAbuse()
200
+ for path in self._filter_build_files(files, egg_info_dir):
201
+ d, f = os.path.split(assert_relative(path))
202
+ prev = None
203
+ oldf = f
204
+ while d and d != prev and d not in src_dirs:
205
+ prev = d
206
+ d, df = os.path.split(d)
207
+ f = os.path.join(df, f)
208
+ if d in src_dirs:
209
+ if f == oldf:
210
+ if check.is_module(f):
211
+ continue # it's a module, not data
212
+ else:
213
+ importable = check.importable_subpackage(src_dirs[d], f)
214
+ if importable:
215
+ check.warn(importable)
216
+ self.manifest_files.setdefault(src_dirs[d], []).append(path)
217
+
218
+ def _filter_build_files(
219
+ self, files: Iterable[str], egg_info: StrPath
220
+ ) -> Iterator[str]:
221
+ """
222
+ ``build_meta`` may try to create egg_info outside of the project directory,
223
+ and this can be problematic for certain plugins (reported in issue #3500).
224
+
225
+ Extensions might also include between their sources files created on the
226
+ ``build_lib`` and ``build_temp`` directories.
227
+
228
+ This function should filter this case of invalid files out.
229
+ """
230
+ build = self.get_finalized_command("build")
231
+ build_dirs = (egg_info, self.build_lib, build.build_temp, build.build_base)
232
+ norm_dirs = [os.path.normpath(p) for p in build_dirs if p]
233
+
234
+ for file in files:
235
+ norm_path = os.path.normpath(file)
236
+ if not os.path.isabs(file) or all(d not in norm_path for d in norm_dirs):
237
+ yield file
238
+
239
+ def get_data_files(self) -> None:
240
+ pass # Lazily compute data files in _get_data_files() function.
241
+
242
+ def check_package(self, package, package_dir):
243
+ """Check namespace packages' __init__ for declare_namespace"""
244
+ try:
245
+ return self.packages_checked[package]
246
+ except KeyError:
247
+ pass
248
+
249
+ init_py = orig.build_py.check_package(self, package, package_dir)
250
+ self.packages_checked[package] = init_py
251
+
252
+ if not init_py or not self.distribution.namespace_packages:
253
+ return init_py
254
+
255
+ for pkg in self.distribution.namespace_packages:
256
+ if pkg == package or pkg.startswith(package + '.'):
257
+ break
258
+ else:
259
+ return init_py
260
+
261
+ with open(init_py, 'rb') as f:
262
+ contents = f.read()
263
+ if b'declare_namespace' not in contents:
264
+ raise distutils.errors.DistutilsError(
265
+ f"Namespace package problem: {package} is a namespace package, but "
266
+ "its\n__init__.py does not call declare_namespace()! Please "
267
+ 'fix it.\n(See the setuptools manual under '
268
+ '"Namespace Packages" for details.)\n"'
269
+ )
270
+ return init_py
271
+
272
+ def initialize_options(self):
273
+ self.packages_checked = {}
274
+ orig.build_py.initialize_options(self)
275
+ self.editable_mode = False
276
+ self.existing_egg_info_dir = None
277
+
278
+ def get_package_dir(self, package: str) -> str:
279
+ res = orig.build_py.get_package_dir(self, package)
280
+ if self.distribution.src_root is not None:
281
+ return os.path.join(self.distribution.src_root, res)
282
+ return res
283
+
284
+ def exclude_data_files(self, package, src_dir, files):
285
+ """Filter filenames for package's data files in 'src_dir'"""
286
+ files = list(files)
287
+ patterns = self._get_platform_patterns(
288
+ self.exclude_package_data,
289
+ package,
290
+ src_dir,
291
+ )
292
+ match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)
293
+ # flatten the groups of matches into an iterable of matches
294
+ matches = itertools.chain.from_iterable(match_groups)
295
+ bad = set(matches)
296
+ keepers = (fn for fn in files if fn not in bad)
297
+ # ditch dupes
298
+ return list(unique_everseen(keepers))
299
+
300
+ @staticmethod
301
+ def _get_platform_patterns(spec, package, src_dir, extra_patterns=()):
302
+ """
303
+ yield platform-specific path patterns (suitable for glob
304
+ or fn_match) from a glob-based spec (such as
305
+ self.package_data or self.exclude_package_data)
306
+ matching package in src_dir.
307
+ """
308
+ raw_patterns = itertools.chain(
309
+ extra_patterns,
310
+ spec.get('', []),
311
+ spec.get(package, []),
312
+ )
313
+ return (
314
+ # Each pattern has to be converted to a platform-specific path
315
+ os.path.join(src_dir, convert_path(pattern))
316
+ for pattern in raw_patterns
317
+ )
318
+
319
+
320
+ def assert_relative(path):
321
+ if not os.path.isabs(path):
322
+ return path
323
+ from distutils.errors import DistutilsSetupError
324
+
325
+ msg = (
326
+ textwrap.dedent(
327
+ """
328
+ Error: setup script specifies an absolute path:
329
+
330
+ %s
331
+
332
+ setup() arguments must *always* be /-separated paths relative to the
333
+ setup.py directory, *never* absolute paths.
334
+ """
335
+ ).lstrip()
336
+ % path
337
+ )
338
+ raise DistutilsSetupError(msg)
339
+
340
+
341
+ class _IncludePackageDataAbuse:
342
+ """Inform users that package or module is included as 'data file'"""
343
+
344
+ class _Warning(SetuptoolsDeprecationWarning):
345
+ _SUMMARY = """
346
+ Package {importable!r} is absent from the `packages` configuration.
347
+ """
348
+
349
+ _DETAILS = """
350
+ ############################
351
+ # Package would be ignored #
352
+ ############################
353
+ Python recognizes {importable!r} as an importable package[^1],
354
+ but it is absent from setuptools' `packages` configuration.
355
+
356
+ This leads to an ambiguous overall configuration. If you want to distribute this
357
+ package, please make sure that {importable!r} is explicitly added
358
+ to the `packages` configuration field.
359
+
360
+ Alternatively, you can also rely on setuptools' discovery methods
361
+ (for example by using `find_namespace_packages(...)`/`find_namespace:`
362
+ instead of `find_packages(...)`/`find:`).
363
+
364
+ You can read more about "package discovery" on setuptools documentation page:
365
+
366
+ - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html
367
+
368
+ If you don't want {importable!r} to be distributed and are
369
+ already explicitly excluding {importable!r} via
370
+ `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`,
371
+ you can try to use `exclude_package_data`, or `include-package-data=False` in
372
+ combination with a more fine grained `package-data` configuration.
373
+
374
+ You can read more about "package data files" on setuptools documentation page:
375
+
376
+ - https://setuptools.pypa.io/en/latest/userguide/datafiles.html
377
+
378
+
379
+ [^1]: For Python, any directory (with suitable naming) can be imported,
380
+ even if it does not contain any `.py` files.
381
+ On the other hand, currently there is no concept of package data
382
+ directory, all directories are treated like packages.
383
+ """
384
+ # _DUE_DATE: still not defined as this is particularly controversial.
385
+ # Warning initially introduced in May 2022. See issue #3340 for discussion.
386
+
387
+ def __init__(self) -> None:
388
+ self._already_warned = set[str]()
389
+
390
+ def is_module(self, file):
391
+ return file.endswith(".py") and file[: -len(".py")].isidentifier()
392
+
393
+ def importable_subpackage(self, parent, file):
394
+ pkg = Path(file).parent
395
+ parts = list(itertools.takewhile(str.isidentifier, pkg.parts))
396
+ if parts:
397
+ return ".".join([parent, *parts])
398
+ return None
399
+
400
+ def warn(self, importable):
401
+ if importable not in self._already_warned:
402
+ self._Warning.emit(importable=importable)
403
+ self._already_warned.add(importable)
python/Lib/site-packages/setuptools/command/develop.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import site
2
+ import subprocess
3
+ import sys
4
+ from typing import cast
5
+
6
+ from setuptools import Command
7
+ from setuptools.warnings import SetuptoolsDeprecationWarning
8
+
9
+
10
+ class develop(Command):
11
+ """Set up package for development"""
12
+
13
+ user_options = [
14
+ ("install-dir=", "d", "install package to DIR"),
15
+ ('no-deps', 'N', "don't install dependencies"),
16
+ ('user', None, f"install in user site-package '{site.USER_SITE}'"),
17
+ ('prefix=', None, "installation prefix"),
18
+ ("index-url=", "i", "base URL of Python Package Index"),
19
+ ]
20
+ boolean_options = [
21
+ 'no-deps',
22
+ 'user',
23
+ ]
24
+
25
+ install_dir = None
26
+ no_deps = False
27
+ user = False
28
+ prefix = None
29
+ index_url = None
30
+
31
+ def run(self) -> None:
32
+ # Casting because mypy doesn't understand bool mult conditionals
33
+ cmd = cast(
34
+ list[str],
35
+ [sys.executable, '-m', 'pip', 'install', '-e', '.', '--use-pep517']
36
+ + ['--target', self.install_dir] * bool(self.install_dir)
37
+ + ['--no-deps'] * self.no_deps
38
+ + ['--user'] * self.user
39
+ + ['--prefix', self.prefix] * bool(self.prefix)
40
+ + ['--index-url', self.index_url] * bool(self.index_url),
41
+ )
42
+ subprocess.check_call(cmd)
43
+
44
+ def initialize_options(self) -> None:
45
+ DevelopDeprecationWarning.emit()
46
+
47
+ def finalize_options(self) -> None:
48
+ pass
49
+
50
+
51
+ class DevelopDeprecationWarning(SetuptoolsDeprecationWarning):
52
+ _SUMMARY = "develop command is deprecated."
53
+ _DETAILS = """
54
+ Please avoid running ``setup.py`` and ``develop``.
55
+ Instead, use standards-based tools like pip or uv.
56
+ """
57
+ _SEE_URL = "https://github.com/pypa/setuptools/issues/917"
58
+ _DUE_DATE = 2025, 10, 31
python/Lib/site-packages/setuptools/command/dist_info.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a dist_info directory
3
+ As defined in the wheel specification
4
+ """
5
+
6
+ import os
7
+ import shutil
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import cast
11
+
12
+ from .. import _normalization
13
+ from .._shutil import rmdir as _rm
14
+ from .egg_info import egg_info as egg_info_cls
15
+
16
+ from distutils import log
17
+ from distutils.core import Command
18
+
19
+
20
+ class dist_info(Command):
21
+ """
22
+ This command is private and reserved for internal use of setuptools,
23
+ users should rely on ``setuptools.build_meta`` APIs.
24
+ """
25
+
26
+ description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create .dist-info directory"
27
+
28
+ user_options = [
29
+ (
30
+ 'output-dir=',
31
+ 'o',
32
+ "directory inside of which the .dist-info will be"
33
+ "created [default: top of the source tree]",
34
+ ),
35
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
36
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
37
+ ('no-date', 'D', "Don't include date stamp [default]"),
38
+ ('keep-egg-info', None, "*TRANSITIONAL* will be removed in the future"),
39
+ ]
40
+
41
+ boolean_options = ['tag-date', 'keep-egg-info']
42
+ negative_opt = {'no-date': 'tag-date'}
43
+
44
+ def initialize_options(self):
45
+ self.output_dir = None
46
+ self.name = None
47
+ self.dist_info_dir = None
48
+ self.tag_date = None
49
+ self.tag_build = None
50
+ self.keep_egg_info = False
51
+
52
+ def finalize_options(self) -> None:
53
+ dist = self.distribution
54
+ project_dir = dist.src_root or os.curdir
55
+ self.output_dir = Path(self.output_dir or project_dir)
56
+
57
+ egg_info = cast(egg_info_cls, self.reinitialize_command("egg_info"))
58
+ egg_info.egg_base = str(self.output_dir)
59
+
60
+ if self.tag_date:
61
+ egg_info.tag_date = self.tag_date
62
+ else:
63
+ self.tag_date = egg_info.tag_date
64
+
65
+ if self.tag_build:
66
+ egg_info.tag_build = self.tag_build
67
+ else:
68
+ self.tag_build = egg_info.tag_build
69
+
70
+ egg_info.finalize_options()
71
+ self.egg_info = egg_info
72
+
73
+ name = _normalization.safer_name(dist.get_name())
74
+ version = _normalization.safer_best_effort_version(dist.get_version())
75
+ self.name = f"{name}-{version}"
76
+ self.dist_info_dir = os.path.join(self.output_dir, f"{self.name}.dist-info")
77
+
78
+ @contextmanager
79
+ def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):
80
+ if requires_bkp:
81
+ bkp_name = f"{dir_path}.__bkp__"
82
+ _rm(bkp_name, ignore_errors=True)
83
+ shutil.copytree(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)
84
+ try:
85
+ yield
86
+ finally:
87
+ _rm(dir_path, ignore_errors=True)
88
+ shutil.move(bkp_name, dir_path)
89
+ else:
90
+ yield
91
+
92
+ def run(self) -> None:
93
+ self.output_dir.mkdir(parents=True, exist_ok=True)
94
+ self.egg_info.run()
95
+ egg_info_dir = self.egg_info.egg_info
96
+ assert os.path.isdir(egg_info_dir), ".egg-info dir should have been created"
97
+
98
+ log.info(f"creating '{os.path.abspath(self.dist_info_dir)}'")
99
+ bdist_wheel = self.get_finalized_command('bdist_wheel')
100
+
101
+ # TODO: if bdist_wheel if merged into setuptools, just add "keep_egg_info" there
102
+ with self._maybe_bkp_dir(egg_info_dir, self.keep_egg_info):
103
+ bdist_wheel.egg2dist(egg_info_dir, self.dist_info_dir)
python/Lib/site-packages/setuptools/command/easy_install.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import types
4
+
5
+ from setuptools import Command
6
+
7
+ from .. import _scripts, warnings
8
+
9
+
10
+ class easy_install(Command):
11
+ """Stubbed command for temporary pbr compatibility."""
12
+
13
+
14
+ def __getattr__(name):
15
+ attr = getattr(
16
+ types.SimpleNamespace(
17
+ ScriptWriter=_scripts.ScriptWriter,
18
+ sys_executable=os.environ.get(
19
+ "__PYVENV_LAUNCHER__", os.path.normpath(sys.executable)
20
+ ),
21
+ ),
22
+ name,
23
+ )
24
+ warnings.SetuptoolsDeprecationWarning.emit(
25
+ summary="easy_install module is deprecated",
26
+ details="Avoid accessing attributes of setuptools.command.easy_install.",
27
+ due_date=(2025, 10, 31),
28
+ see_url="https://github.com/pypa/setuptools/issues/4976",
29
+ )
30
+ return attr
python/Lib/site-packages/setuptools/command/editable_wheel.py ADDED
@@ -0,0 +1,914 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Create a wheel that, when installed, will make the source package 'editable'
3
+ (add it to the interpreter's path, including metadata) per PEP 660. Replaces
4
+ 'setup.py develop'.
5
+
6
+ .. note::
7
+ One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is
8
+ to create a separated directory inside ``build`` and use a .pth file to point to that
9
+ directory. In the context of this file such directory is referred as
10
+ *auxiliary build directory* or ``auxiliary_dir``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import logging
17
+ import operator
18
+ import os
19
+ import shutil
20
+ import traceback
21
+ from collections.abc import Iterable, Iterator, Mapping
22
+ from contextlib import suppress
23
+ from enum import Enum
24
+ from inspect import cleandoc
25
+ from itertools import chain, starmap
26
+ from pathlib import Path
27
+ from tempfile import TemporaryDirectory
28
+ from types import TracebackType
29
+ from typing import TYPE_CHECKING, Protocol, TypeVar, cast
30
+
31
+ from .. import Command, _normalization, _path, _shutil, errors, namespaces
32
+ from .._path import StrPath
33
+ from ..compat import py310, py312
34
+ from ..discovery import find_package_path
35
+ from ..dist import Distribution
36
+ from ..warnings import InformationOnly, SetuptoolsDeprecationWarning
37
+ from .build import build as build_cls
38
+ from .build_py import build_py as build_py_cls
39
+ from .dist_info import dist_info as dist_info_cls
40
+ from .egg_info import egg_info as egg_info_cls
41
+ from .install import install as install_cls
42
+ from .install_scripts import install_scripts as install_scripts_cls
43
+
44
+ if TYPE_CHECKING:
45
+ from typing_extensions import Self
46
+
47
+ from .._vendor.wheel.wheelfile import WheelFile
48
+
49
+ _P = TypeVar("_P", bound=StrPath)
50
+ _logger = logging.getLogger(__name__)
51
+
52
+
53
+ class _EditableMode(Enum):
54
+ """
55
+ Possible editable installation modes:
56
+ `lenient` (new files automatically added to the package - DEFAULT);
57
+ `strict` (requires a new installation when files are added/removed); or
58
+ `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).
59
+ """
60
+
61
+ STRICT = "strict"
62
+ LENIENT = "lenient"
63
+ COMPAT = "compat" # TODO: Remove `compat` after Dec/2022.
64
+
65
+ @classmethod
66
+ def convert(cls, mode: str | None) -> _EditableMode:
67
+ if not mode:
68
+ return _EditableMode.LENIENT # default
69
+
70
+ _mode = mode.upper()
71
+ if _mode not in _EditableMode.__members__:
72
+ raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.")
73
+
74
+ if _mode == "COMPAT":
75
+ SetuptoolsDeprecationWarning.emit(
76
+ "Compat editable installs",
77
+ """
78
+ The 'compat' editable mode is transitional and will be removed
79
+ in future versions of `setuptools`.
80
+ Please adapt your code accordingly to use either the 'strict' or the
81
+ 'lenient' modes.
82
+ """,
83
+ see_docs="userguide/development_mode.html",
84
+ # TODO: define due_date
85
+ # There is a series of shortcomings with the available editable install
86
+ # methods, and they are very controversial. This is something that still
87
+ # needs work.
88
+ # Moreover, `pip` is still hiding this warning, so users are not aware.
89
+ )
90
+
91
+ return _EditableMode[_mode]
92
+
93
+
94
+ _STRICT_WARNING = """
95
+ New or renamed files may not be automatically picked up without a new installation.
96
+ """
97
+
98
+ _LENIENT_WARNING = """
99
+ Options like `package-data`, `include/exclude-package-data` or
100
+ `packages.find.exclude/include` may have no effect.
101
+ """
102
+
103
+
104
+ class editable_wheel(Command):
105
+ """Build 'editable' wheel for development.
106
+ This command is private and reserved for internal use of setuptools,
107
+ users should rely on ``setuptools.build_meta`` APIs.
108
+ """
109
+
110
+ description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
111
+
112
+ user_options = [
113
+ ("dist-dir=", "d", "directory to put final built distributions in"),
114
+ ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"),
115
+ ("mode=", None, cleandoc(_EditableMode.__doc__ or "")),
116
+ ]
117
+
118
+ def initialize_options(self):
119
+ self.dist_dir = None
120
+ self.dist_info_dir = None
121
+ self.project_dir = None
122
+ self.mode = None
123
+
124
+ def finalize_options(self) -> None:
125
+ dist = self.distribution
126
+ self.project_dir = dist.src_root or os.curdir
127
+ self.package_dir = dist.package_dir or {}
128
+ self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist"))
129
+
130
+ def run(self) -> None:
131
+ try:
132
+ self.dist_dir.mkdir(exist_ok=True)
133
+ self._ensure_dist_info()
134
+
135
+ # Add missing dist_info files
136
+ self.reinitialize_command("bdist_wheel")
137
+ bdist_wheel = self.get_finalized_command("bdist_wheel")
138
+ bdist_wheel.write_wheelfile(self.dist_info_dir)
139
+
140
+ self._create_wheel_file(bdist_wheel)
141
+ except Exception as ex:
142
+ project = self.distribution.name or self.distribution.get_name()
143
+ py310.add_note(
144
+ ex,
145
+ f"An error occurred when building editable wheel for {project}.\n"
146
+ "See debugging tips in: "
147
+ "https://setuptools.pypa.io/en/latest/userguide/development_mode.html#debugging-tips",
148
+ )
149
+ raise
150
+
151
+ def _ensure_dist_info(self):
152
+ if self.dist_info_dir is None:
153
+ dist_info = cast(dist_info_cls, self.reinitialize_command("dist_info"))
154
+ dist_info.output_dir = self.dist_dir
155
+ dist_info.ensure_finalized()
156
+ dist_info.run()
157
+ self.dist_info_dir = dist_info.dist_info_dir
158
+ else:
159
+ assert str(self.dist_info_dir).endswith(".dist-info")
160
+ assert Path(self.dist_info_dir, "METADATA").exists()
161
+
162
+ def _install_namespaces(self, installation_dir, pth_prefix):
163
+ # XXX: Only required to support the deprecated namespace practice
164
+ dist = self.distribution
165
+ if not dist.namespace_packages:
166
+ return
167
+
168
+ src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve()
169
+ installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)
170
+ installer.install_namespaces()
171
+
172
+ def _find_egg_info_dir(self) -> str | None:
173
+ parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()
174
+ candidates = map(str, parent_dir.glob("*.egg-info"))
175
+ return next(candidates, None)
176
+
177
+ def _configure_build(
178
+ self, name: str, unpacked_wheel: StrPath, build_lib: StrPath, tmp_dir: StrPath
179
+ ):
180
+ """Configure commands to behave in the following ways:
181
+
182
+ - Build commands can write to ``build_lib`` if they really want to...
183
+ (but this folder is expected to be ignored and modules are expected to live
184
+ in the project directory...)
185
+ - Binary extensions should be built in-place (editable_mode = True)
186
+ - Data/header/script files are not part of the "editable" specification
187
+ so they are written directly to the unpacked_wheel directory.
188
+ """
189
+ # Non-editable files (data, headers, scripts) are written directly to the
190
+ # unpacked_wheel
191
+
192
+ dist = self.distribution
193
+ wheel = str(unpacked_wheel)
194
+ build_lib = str(build_lib)
195
+ data = str(Path(unpacked_wheel, f"{name}.data", "data"))
196
+ headers = str(Path(unpacked_wheel, f"{name}.data", "headers"))
197
+ scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts"))
198
+
199
+ # egg-info may be generated again to create a manifest (used for package data)
200
+ egg_info = cast(
201
+ egg_info_cls, dist.reinitialize_command("egg_info", reinit_subcommands=True)
202
+ )
203
+ egg_info.egg_base = str(tmp_dir)
204
+ egg_info.ignore_egg_info_in_manifest = True
205
+
206
+ build = cast(
207
+ build_cls, dist.reinitialize_command("build", reinit_subcommands=True)
208
+ )
209
+ install = cast(
210
+ install_cls, dist.reinitialize_command("install", reinit_subcommands=True)
211
+ )
212
+
213
+ build.build_platlib = build.build_purelib = build.build_lib = build_lib
214
+ install.install_purelib = install.install_platlib = install.install_lib = wheel
215
+ install.install_scripts = build.build_scripts = scripts
216
+ install.install_headers = headers
217
+ install.install_data = data
218
+
219
+ # For portability, ensure scripts are built with #!python shebang
220
+ # pypa/setuptools#4863
221
+ build_scripts = dist.get_command_obj("build_scripts")
222
+ build_scripts.executable = 'python'
223
+
224
+ install_scripts = cast(
225
+ install_scripts_cls, dist.get_command_obj("install_scripts")
226
+ )
227
+ install_scripts.no_ep = True
228
+
229
+ build.build_temp = str(tmp_dir)
230
+
231
+ build_py = cast(build_py_cls, dist.get_command_obj("build_py"))
232
+ build_py.compile = False
233
+ build_py.existing_egg_info_dir = self._find_egg_info_dir()
234
+
235
+ self._set_editable_mode()
236
+
237
+ build.ensure_finalized()
238
+ install.ensure_finalized()
239
+
240
+ def _set_editable_mode(self):
241
+ """Set the ``editable_mode`` flag in the build sub-commands"""
242
+ dist = self.distribution
243
+ build = dist.get_command_obj("build")
244
+ for cmd_name in build.get_sub_commands():
245
+ cmd = dist.get_command_obj(cmd_name)
246
+ if hasattr(cmd, "editable_mode"):
247
+ cmd.editable_mode = True
248
+ elif hasattr(cmd, "inplace"):
249
+ cmd.inplace = True # backward compatibility with distutils
250
+
251
+ def _collect_build_outputs(self) -> tuple[list[str], dict[str, str]]:
252
+ files: list[str] = []
253
+ mapping: dict[str, str] = {}
254
+ build = self.get_finalized_command("build")
255
+
256
+ for cmd_name in build.get_sub_commands():
257
+ cmd = self.get_finalized_command(cmd_name)
258
+ if hasattr(cmd, "get_outputs"):
259
+ files.extend(cmd.get_outputs() or [])
260
+ if hasattr(cmd, "get_output_mapping"):
261
+ mapping.update(cmd.get_output_mapping() or {})
262
+
263
+ return files, mapping
264
+
265
+ def _run_build_commands(
266
+ self,
267
+ dist_name: str,
268
+ unpacked_wheel: StrPath,
269
+ build_lib: StrPath,
270
+ tmp_dir: StrPath,
271
+ ) -> tuple[list[str], dict[str, str]]:
272
+ self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)
273
+ self._run_build_subcommands()
274
+ files, mapping = self._collect_build_outputs()
275
+ self._run_install("headers")
276
+ self._run_install("scripts")
277
+ self._run_install("data")
278
+ return files, mapping
279
+
280
+ def _run_build_subcommands(self) -> None:
281
+ """
282
+ Issue #3501 indicates that some plugins/customizations might rely on:
283
+
284
+ 1. ``build_py`` not running
285
+ 2. ``build_py`` always copying files to ``build_lib``
286
+
287
+ However both these assumptions may be false in editable_wheel.
288
+ This method implements a temporary workaround to support the ecosystem
289
+ while the implementations catch up.
290
+ """
291
+ # TODO: Once plugins/customizations had the chance to catch up, replace
292
+ # `self._run_build_subcommands()` with `self.run_command("build")`.
293
+ # Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.
294
+ build = self.get_finalized_command("build")
295
+ for name in build.get_sub_commands():
296
+ cmd = self.get_finalized_command(name)
297
+ if name == "build_py" and type(cmd) is not build_py_cls:
298
+ self._safely_run(name)
299
+ else:
300
+ self.run_command(name)
301
+
302
+ def _safely_run(self, cmd_name: str):
303
+ try:
304
+ return self.run_command(cmd_name)
305
+ except Exception:
306
+ SetuptoolsDeprecationWarning.emit(
307
+ "Customization incompatible with editable install",
308
+ f"""
309
+ {traceback.format_exc()}
310
+
311
+ If you are seeing this warning it is very likely that a setuptools
312
+ plugin or customization overrides the `{cmd_name}` command, without
313
+ taking into consideration how editable installs run build steps
314
+ starting from setuptools v64.0.0.
315
+
316
+ Plugin authors and developers relying on custom build steps are
317
+ encouraged to update their `{cmd_name}` implementation considering the
318
+ information about editable installs in
319
+ https://setuptools.pypa.io/en/latest/userguide/extension.html.
320
+
321
+ For the time being `setuptools` will silence this error and ignore
322
+ the faulty command, but this behavior will change in future versions.
323
+ """,
324
+ # TODO: define due_date
325
+ # There is a series of shortcomings with the available editable install
326
+ # methods, and they are very controversial. This is something that still
327
+ # needs work.
328
+ )
329
+
330
+ def _create_wheel_file(self, bdist_wheel):
331
+ from wheel.wheelfile import WheelFile
332
+
333
+ dist_info = self.get_finalized_command("dist_info")
334
+ dist_name = dist_info.name
335
+ tag = "-".join(bdist_wheel.get_tag())
336
+ build_tag = "0.editable" # According to PEP 427 needs to start with digit
337
+ archive_name = f"{dist_name}-{build_tag}-{tag}.whl"
338
+ wheel_path = Path(self.dist_dir, archive_name)
339
+ if wheel_path.exists():
340
+ wheel_path.unlink()
341
+
342
+ unpacked_wheel = TemporaryDirectory(suffix=archive_name)
343
+ build_lib = TemporaryDirectory(suffix=".build-lib")
344
+ build_tmp = TemporaryDirectory(suffix=".build-temp")
345
+
346
+ with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:
347
+ unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)
348
+ shutil.copytree(self.dist_info_dir, unpacked_dist_info)
349
+ self._install_namespaces(unpacked, dist_name)
350
+ files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)
351
+ strategy = self._select_strategy(dist_name, tag, lib)
352
+ with strategy, WheelFile(wheel_path, "w") as wheel_obj:
353
+ strategy(wheel_obj, files, mapping)
354
+ wheel_obj.write_files(unpacked)
355
+
356
+ return wheel_path
357
+
358
+ def _run_install(self, category: str):
359
+ has_category = getattr(self.distribution, f"has_{category}", None)
360
+ if has_category and has_category():
361
+ _logger.info(f"Installing {category} as non editable")
362
+ self.run_command(f"install_{category}")
363
+
364
+ def _select_strategy(
365
+ self,
366
+ name: str,
367
+ tag: str,
368
+ build_lib: StrPath,
369
+ ) -> EditableStrategy:
370
+ """Decides which strategy to use to implement an editable installation."""
371
+ build_name = f"__editable__.{name}-{tag}"
372
+ project_dir = Path(self.project_dir)
373
+ mode = _EditableMode.convert(self.mode)
374
+
375
+ if mode is _EditableMode.STRICT:
376
+ auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name))
377
+ return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)
378
+
379
+ packages = _find_packages(self.distribution)
380
+ has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)
381
+ is_compat_mode = mode is _EditableMode.COMPAT
382
+ if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode:
383
+ # src-layout(ish) is relatively safe for a simple pth file
384
+ src_dir = self.package_dir.get("", ".")
385
+ return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])
386
+
387
+ # Use a MetaPathFinder to avoid adding accidental top-level packages/modules
388
+ return _TopLevelFinder(self.distribution, name)
389
+
390
+
391
+ class EditableStrategy(Protocol):
392
+ def __call__(
393
+ self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
394
+ ) -> object: ...
395
+ def __enter__(self) -> Self: ...
396
+ def __exit__(
397
+ self,
398
+ _exc_type: type[BaseException] | None,
399
+ _exc_value: BaseException | None,
400
+ _traceback: TracebackType | None,
401
+ ) -> object: ...
402
+
403
+
404
+ class _StaticPth:
405
+ def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None:
406
+ self.dist = dist
407
+ self.name = name
408
+ self.path_entries = path_entries
409
+
410
+ def __call__(
411
+ self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
412
+ ) -> None:
413
+ entries = "\n".join(str(p.resolve()) for p in self.path_entries)
414
+ contents = _encode_pth(f"{entries}\n")
415
+ wheel.writestr(f"__editable__.{self.name}.pth", contents)
416
+
417
+ def __enter__(self) -> Self:
418
+ msg = f"""
419
+ Editable install will be performed using .pth file to extend `sys.path` with:
420
+ {list(map(os.fspath, self.path_entries))!r}
421
+ """
422
+ _logger.warning(msg + _LENIENT_WARNING)
423
+ return self
424
+
425
+ def __exit__(
426
+ self,
427
+ _exc_type: object,
428
+ _exc_value: object,
429
+ _traceback: object,
430
+ ) -> None:
431
+ pass
432
+
433
+
434
+ class _LinkTree(_StaticPth):
435
+ """
436
+ Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.
437
+
438
+ This strategy will only link files (not dirs), so it can be implemented in
439
+ any OS, even if that means using hardlinks instead of symlinks.
440
+
441
+ By collocating ``auxiliary_dir`` and the original source code, limitations
442
+ with hardlinks should be avoided.
443
+ """
444
+
445
+ def __init__(
446
+ self,
447
+ dist: Distribution,
448
+ name: str,
449
+ auxiliary_dir: StrPath,
450
+ build_lib: StrPath,
451
+ ) -> None:
452
+ self.auxiliary_dir = Path(auxiliary_dir)
453
+ self.build_lib = Path(build_lib).resolve()
454
+ self._file = dist.get_command_obj("build_py").copy_file
455
+ super().__init__(dist, name, [self.auxiliary_dir])
456
+
457
+ def __call__(
458
+ self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
459
+ ) -> None:
460
+ self._create_links(files, mapping)
461
+ super().__call__(wheel, files, mapping)
462
+
463
+ def _normalize_output(self, file: str) -> str | None:
464
+ # Files relative to build_lib will be normalized to None
465
+ with suppress(ValueError):
466
+ path = Path(file).resolve().relative_to(self.build_lib)
467
+ return str(path).replace(os.sep, '/')
468
+ return None
469
+
470
+ def _create_file(self, relative_output: str, src_file: str, link=None):
471
+ dest = self.auxiliary_dir / relative_output
472
+ if not dest.parent.is_dir():
473
+ dest.parent.mkdir(parents=True)
474
+ self._file(src_file, dest, link=link)
475
+
476
+ def _create_links(self, outputs, output_mapping: Mapping[str, str]):
477
+ self.auxiliary_dir.mkdir(parents=True, exist_ok=True)
478
+ link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard"
479
+ normalised = ((self._normalize_output(k), v) for k, v in output_mapping.items())
480
+ # remove files that are not relative to build_lib
481
+ mappings = {k: v for k, v in normalised if k is not None}
482
+
483
+ for output in outputs:
484
+ relative = self._normalize_output(output)
485
+ if relative and relative not in mappings:
486
+ self._create_file(relative, output)
487
+
488
+ for relative, src in mappings.items():
489
+ self._create_file(relative, src, link=link_type)
490
+
491
+ def __enter__(self) -> Self:
492
+ msg = "Strict editable install will be performed using a link tree.\n"
493
+ _logger.warning(msg + _STRICT_WARNING)
494
+ return self
495
+
496
+ def __exit__(
497
+ self,
498
+ _exc_type: object,
499
+ _exc_value: object,
500
+ _traceback: object,
501
+ ) -> None:
502
+ msg = f"""\n
503
+ Strict editable installation performed using the auxiliary directory:
504
+ {self.auxiliary_dir}
505
+
506
+ Please be careful to not remove this directory, otherwise you might not be able
507
+ to import/use your package.
508
+ """
509
+ InformationOnly.emit("Editable installation.", msg)
510
+
511
+
512
+ class _TopLevelFinder:
513
+ def __init__(self, dist: Distribution, name: str) -> None:
514
+ self.dist = dist
515
+ self.name = name
516
+
517
+ def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]:
518
+ src_root = self.dist.src_root or os.curdir
519
+ top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))
520
+ package_dir = self.dist.package_dir or {}
521
+ roots = _find_package_roots(top_level, package_dir, src_root)
522
+
523
+ namespaces_ = dict(
524
+ chain(
525
+ _find_namespaces(self.dist.packages or [], roots),
526
+ ((ns, []) for ns in _find_virtual_namespaces(roots)),
527
+ )
528
+ )
529
+
530
+ legacy_namespaces = {
531
+ pkg: find_package_path(pkg, roots, self.dist.src_root or "")
532
+ for pkg in self.dist.namespace_packages or []
533
+ }
534
+
535
+ mapping = {**roots, **legacy_namespaces}
536
+ # ^-- We need to explicitly add the legacy_namespaces to the mapping to be
537
+ # able to import their modules even if another package sharing the same
538
+ # namespace is installed in a conventional (non-editable) way.
539
+
540
+ name = f"__editable__.{self.name}.finder"
541
+ finder = _normalization.safe_identifier(name)
542
+ return finder, name, mapping, namespaces_
543
+
544
+ def get_implementation(self) -> Iterator[tuple[str, bytes]]:
545
+ finder, name, mapping, namespaces_ = self.template_vars()
546
+
547
+ content = bytes(_finder_template(name, mapping, namespaces_), "utf-8")
548
+ yield (f"{finder}.py", content)
549
+
550
+ content = _encode_pth(f"import {finder}; {finder}.install()")
551
+ yield (f"__editable__.{self.name}.pth", content)
552
+
553
+ def __call__(
554
+ self, wheel: WheelFile, files: list[str], mapping: Mapping[str, str]
555
+ ) -> None:
556
+ for file, content in self.get_implementation():
557
+ wheel.writestr(file, content)
558
+
559
+ def __enter__(self) -> Self:
560
+ msg = "Editable install will be performed using a meta path finder.\n"
561
+ _logger.warning(msg + _LENIENT_WARNING)
562
+ return self
563
+
564
+ def __exit__(
565
+ self,
566
+ _exc_type: object,
567
+ _exc_value: object,
568
+ _traceback: object,
569
+ ) -> None:
570
+ msg = """\n
571
+ Please be careful with folders in your working directory with the same
572
+ name as your package as they may take precedence during imports.
573
+ """
574
+ InformationOnly.emit("Editable installation.", msg)
575
+
576
+
577
+ def _encode_pth(content: str) -> bytes:
578
+ """
579
+ Prior to Python 3.13 (see https://github.com/python/cpython/issues/77102),
580
+ .pth files are always read with 'locale' encoding, the recommendation
581
+ from the cpython core developers is to write them as ``open(path, "w")``
582
+ and ignore warnings (see python/cpython#77102, pypa/setuptools#3937).
583
+ This function tries to simulate this behavior without having to create an
584
+ actual file, in a way that supports a range of active Python versions.
585
+ (There seems to be some variety in the way different version of Python handle
586
+ ``encoding=None``, not all of them use ``locale.getpreferredencoding(False)``
587
+ or ``locale.getencoding()``).
588
+ """
589
+ with io.BytesIO() as buffer:
590
+ wrapper = io.TextIOWrapper(buffer, encoding=py312.PTH_ENCODING)
591
+ # TODO: Python 3.13 replace the whole function with `bytes(content, "utf-8")`
592
+ wrapper.write(content)
593
+ wrapper.flush()
594
+ buffer.seek(0)
595
+ return buffer.read()
596
+
597
+
598
+ def _can_symlink_files(base_dir: Path) -> bool:
599
+ with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:
600
+ path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt")
601
+ path1.write_text("file1", encoding="utf-8")
602
+ with suppress(AttributeError, NotImplementedError, OSError):
603
+ os.symlink(path1, path2)
604
+ if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1":
605
+ return True
606
+
607
+ try:
608
+ os.link(path1, path2) # Ensure hard links can be created
609
+ except Exception as ex:
610
+ msg = (
611
+ "File system does not seem to support either symlinks or hard links. "
612
+ "Strict editable installs require one of them to be supported."
613
+ )
614
+ raise LinksNotSupported(msg) from ex
615
+ return False
616
+
617
+
618
+ def _simple_layout(
619
+ packages: Iterable[str], package_dir: dict[str, str], project_dir: StrPath
620
+ ) -> bool:
621
+ """Return ``True`` if:
622
+ - all packages are contained by the same parent directory, **and**
623
+ - all packages become importable if the parent directory is added to ``sys.path``.
624
+
625
+ >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj")
626
+ True
627
+ >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj")
628
+ True
629
+ >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj")
630
+ True
631
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj")
632
+ True
633
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".")
634
+ True
635
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".")
636
+ False
637
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj")
638
+ False
639
+ >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".")
640
+ False
641
+ >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj")
642
+ False
643
+ >>> # Special cases, no packages yet:
644
+ >>> _simple_layout([], {"": "src"}, "/tmp/myproj")
645
+ True
646
+ >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj")
647
+ False
648
+ """
649
+ layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
650
+ if not layout:
651
+ return set(package_dir) in ({}, {""})
652
+ parent = os.path.commonpath(starmap(_parent_path, layout.items()))
653
+ return all(
654
+ _path.same_path(Path(parent, *key.split('.')), value)
655
+ for key, value in layout.items()
656
+ )
657
+
658
+
659
+ def _parent_path(pkg, pkg_path):
660
+ """Infer the parent path containing a package, that if added to ``sys.path`` would
661
+ allow importing that package.
662
+ When ``pkg`` is directly mapped into a directory with a different name, return its
663
+ own path.
664
+ >>> _parent_path("a", "src/a")
665
+ 'src'
666
+ >>> _parent_path("b", "src/c")
667
+ 'src/c'
668
+ """
669
+ parent = pkg_path.removesuffix(pkg)
670
+ return parent.rstrip("/" + os.sep)
671
+
672
+
673
+ def _find_packages(dist: Distribution) -> Iterator[str]:
674
+ yield from iter(dist.packages or [])
675
+
676
+ py_modules = dist.py_modules or []
677
+ nested_modules = [mod for mod in py_modules if "." in mod]
678
+ if dist.ext_package:
679
+ yield dist.ext_package
680
+ else:
681
+ ext_modules = dist.ext_modules or []
682
+ nested_modules += [x.name for x in ext_modules if "." in x.name]
683
+
684
+ for module in nested_modules:
685
+ package, _, _ = module.rpartition(".")
686
+ yield package
687
+
688
+
689
+ def _find_top_level_modules(dist: Distribution) -> Iterator[str]:
690
+ py_modules = dist.py_modules or []
691
+ yield from (mod for mod in py_modules if "." not in mod)
692
+
693
+ if not dist.ext_package:
694
+ ext_modules = dist.ext_modules or []
695
+ yield from (x.name for x in ext_modules if "." not in x.name)
696
+
697
+
698
+ def _find_package_roots(
699
+ packages: Iterable[str],
700
+ package_dir: Mapping[str, str],
701
+ src_root: StrPath,
702
+ ) -> dict[str, str]:
703
+ pkg_roots: dict[str, str] = {
704
+ pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))
705
+ for pkg in sorted(packages)
706
+ }
707
+
708
+ return _remove_nested(pkg_roots)
709
+
710
+
711
+ def _absolute_root(path: StrPath) -> str:
712
+ """Works for packages and top-level modules"""
713
+ path_ = Path(path)
714
+ parent = path_.parent
715
+
716
+ if path_.exists():
717
+ return str(path_.resolve())
718
+ else:
719
+ return str(parent.resolve() / path_.name)
720
+
721
+
722
+ def _find_virtual_namespaces(pkg_roots: dict[str, str]) -> Iterator[str]:
723
+ """By carefully designing ``package_dir``, it is possible to implement the logical
724
+ structure of PEP 420 in a package without the corresponding directories.
725
+
726
+ Moreover a parent package can be purposefully/accidentally skipped in the discovery
727
+ phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included
728
+ by ``mypkg`` itself is not).
729
+ We consider this case to also be a virtual namespace (ignoring the original
730
+ directory) to emulate a non-editable installation.
731
+
732
+ This function will try to find these kinds of namespaces.
733
+ """
734
+ for pkg in pkg_roots:
735
+ if "." not in pkg:
736
+ continue
737
+ parts = pkg.split(".")
738
+ for i in range(len(parts) - 1, 0, -1):
739
+ partial_name = ".".join(parts[:i])
740
+ path = Path(find_package_path(partial_name, pkg_roots, ""))
741
+ if not path.exists() or partial_name not in pkg_roots:
742
+ # partial_name not in pkg_roots ==> purposefully/accidentally skipped
743
+ yield partial_name
744
+
745
+
746
+ def _find_namespaces(
747
+ packages: list[str], pkg_roots: dict[str, str]
748
+ ) -> Iterator[tuple[str, list[str]]]:
749
+ for pkg in packages:
750
+ path = find_package_path(pkg, pkg_roots, "")
751
+ if Path(path).exists() and not Path(path, "__init__.py").exists():
752
+ yield (pkg, [path])
753
+
754
+
755
+ def _remove_nested(pkg_roots: dict[str, str]) -> dict[str, str]:
756
+ output = dict(pkg_roots.copy())
757
+
758
+ for pkg, path in reversed(list(pkg_roots.items())):
759
+ if any(
760
+ pkg != other and _is_nested(pkg, path, other, other_path)
761
+ for other, other_path in pkg_roots.items()
762
+ ):
763
+ output.pop(pkg)
764
+
765
+ return output
766
+
767
+
768
+ def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:
769
+ """
770
+ Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the
771
+ file system.
772
+ >>> _is_nested("a.b", "path/a/b", "a", "path/a")
773
+ True
774
+ >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a")
775
+ False
776
+ >>> _is_nested("a.b", "path/a/b", "c", "path/c")
777
+ False
778
+ >>> _is_nested("a.a", "path/a/a", "a", "path/a")
779
+ True
780
+ >>> _is_nested("b.a", "path/b/a", "a", "path/a")
781
+ False
782
+ """
783
+ norm_pkg_path = _path.normpath(pkg_path)
784
+ rest = pkg.replace(parent, "", 1).strip(".").split(".")
785
+ return pkg.startswith(parent) and norm_pkg_path == _path.normpath(
786
+ Path(parent_path, *rest)
787
+ )
788
+
789
+
790
+ def _empty_dir(dir_: _P) -> _P:
791
+ """Create a directory ensured to be empty. Existing files may be removed."""
792
+ _shutil.rmtree(dir_, ignore_errors=True)
793
+ os.makedirs(dir_)
794
+ return dir_
795
+
796
+
797
+ class _NamespaceInstaller(namespaces.Installer):
798
+ def __init__(self, distribution, installation_dir, editable_name, src_root) -> None:
799
+ self.distribution = distribution
800
+ self.src_root = src_root
801
+ self.installation_dir = installation_dir
802
+ self.editable_name = editable_name
803
+ self.outputs: list[str] = []
804
+
805
+ def _get_nspkg_file(self):
806
+ """Installation target."""
807
+ return os.path.join(self.installation_dir, self.editable_name + self.nspkg_ext)
808
+
809
+ def _get_root(self):
810
+ """Where the modules/packages should be loaded from."""
811
+ return repr(str(self.src_root))
812
+
813
+
814
+ _FINDER_TEMPLATE = """\
815
+ from __future__ import annotations
816
+ import sys
817
+ from importlib.machinery import ModuleSpec, PathFinder
818
+ from importlib.machinery import all_suffixes as module_suffixes
819
+ from importlib.util import spec_from_file_location
820
+ from itertools import chain
821
+ from pathlib import Path
822
+
823
+ MAPPING: dict[str, str] = {mapping!r}
824
+ NAMESPACES: dict[str, list[str]] = {namespaces!r}
825
+ PATH_PLACEHOLDER = {name!r} + ".__path_hook__"
826
+
827
+
828
+ class _EditableFinder: # MetaPathFinder
829
+ @classmethod
830
+ def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None: # type: ignore
831
+ # Top-level packages and modules (we know these exist in the FS)
832
+ if fullname in MAPPING:
833
+ pkg_path = MAPPING[fullname]
834
+ return cls._find_spec(fullname, Path(pkg_path))
835
+
836
+ # Handle immediate children modules (required for namespaces to work)
837
+ # To avoid problems with case sensitivity in the file system we delegate
838
+ # to the importlib.machinery implementation.
839
+ parent, _, child = fullname.rpartition(".")
840
+ if parent and parent in MAPPING:
841
+ return PathFinder.find_spec(fullname, path=[MAPPING[parent]])
842
+
843
+ # Other levels of nesting should be handled automatically by importlib
844
+ # using the parent path.
845
+ return None
846
+
847
+ @classmethod
848
+ def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
849
+ init = candidate_path / "__init__.py"
850
+ candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
851
+ for candidate in chain([init], candidates):
852
+ if candidate.exists():
853
+ return spec_from_file_location(fullname, candidate)
854
+ return None
855
+
856
+
857
+ class _EditableNamespaceFinder: # PathEntryFinder
858
+ @classmethod
859
+ def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
860
+ if path == PATH_PLACEHOLDER:
861
+ return cls
862
+ raise ImportError
863
+
864
+ @classmethod
865
+ def _paths(cls, fullname: str) -> list[str]:
866
+ paths = NAMESPACES[fullname]
867
+ if not paths and fullname in MAPPING:
868
+ paths = [MAPPING[fullname]]
869
+ # Always add placeholder, for 2 reasons:
870
+ # 1. __path__ cannot be empty for the spec to be considered namespace.
871
+ # 2. In the case of nested namespaces, we need to force
872
+ # import machinery to query _EditableNamespaceFinder again.
873
+ return [*paths, PATH_PLACEHOLDER]
874
+
875
+ @classmethod
876
+ def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None: # type: ignore
877
+ if fullname in NAMESPACES:
878
+ spec = ModuleSpec(fullname, None, is_package=True)
879
+ spec.submodule_search_locations = cls._paths(fullname)
880
+ return spec
881
+ return None
882
+
883
+ @classmethod
884
+ def find_module(cls, _fullname) -> None:
885
+ return None
886
+
887
+
888
+ def install():
889
+ if not any(finder == _EditableFinder for finder in sys.meta_path):
890
+ sys.meta_path.append(_EditableFinder)
891
+
892
+ if not NAMESPACES:
893
+ return
894
+
895
+ if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
896
+ # PathEntryFinder is needed to create NamespaceSpec without private APIS
897
+ sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
898
+ if PATH_PLACEHOLDER not in sys.path:
899
+ sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook
900
+ """
901
+
902
+
903
+ def _finder_template(
904
+ name: str, mapping: Mapping[str, str], namespaces: dict[str, list[str]]
905
+ ) -> str:
906
+ """Create a string containing the code for the``MetaPathFinder`` and
907
+ ``PathEntryFinder``.
908
+ """
909
+ mapping = dict(sorted(mapping.items(), key=operator.itemgetter(0)))
910
+ return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)
911
+
912
+
913
+ class LinksNotSupported(errors.FileError):
914
+ """File system does not seem to support either symlinks or hard links."""
python/Lib/site-packages/setuptools/command/egg_info.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """setuptools.command.egg_info
2
+
3
+ Create a distribution's .egg-info directory and contents"""
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import os
9
+ import re
10
+ import sys
11
+ import time
12
+ from collections.abc import Callable
13
+
14
+ import packaging
15
+ import packaging.requirements
16
+ import packaging.version
17
+
18
+ import setuptools.unicode_utils as unicode_utils
19
+ from setuptools import Command
20
+ from setuptools.command import bdist_egg
21
+ from setuptools.command.sdist import sdist, walk_revctrl
22
+ from setuptools.command.setopt import edit_config
23
+ from setuptools.glob import glob
24
+
25
+ from .. import _entry_points, _normalization
26
+ from .._importlib import metadata
27
+ from ..warnings import SetuptoolsDeprecationWarning
28
+ from . import _requirestxt
29
+
30
+ import distutils.errors
31
+ import distutils.filelist
32
+ from distutils import log
33
+ from distutils.errors import DistutilsInternalError
34
+ from distutils.filelist import FileList as _FileList
35
+ from distutils.util import convert_path
36
+
37
+ PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
38
+
39
+
40
+ def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
41
+ """
42
+ Translate a file path glob like '*.txt' in to a regular expression.
43
+ This differs from fnmatch.translate which allows wildcards to match
44
+ directory separators. It also knows about '**/' which matches any number of
45
+ directories.
46
+ """
47
+ pat = ''
48
+
49
+ # This will split on '/' within [character classes]. This is deliberate.
50
+ chunks = glob.split(os.path.sep)
51
+
52
+ sep = re.escape(os.sep)
53
+ valid_char = f'[^{sep}]'
54
+
55
+ for c, chunk in enumerate(chunks):
56
+ last_chunk = c == len(chunks) - 1
57
+
58
+ # Chunks that are a literal ** are globstars. They match anything.
59
+ if chunk == '**':
60
+ if last_chunk:
61
+ # Match anything if this is the last component
62
+ pat += '.*'
63
+ else:
64
+ # Match '(name/)*'
65
+ pat += f'(?:{valid_char}+{sep})*'
66
+ continue # Break here as the whole path component has been handled
67
+
68
+ # Find any special characters in the remainder
69
+ i = 0
70
+ chunk_len = len(chunk)
71
+ while i < chunk_len:
72
+ char = chunk[i]
73
+ if char == '*':
74
+ # Match any number of name characters
75
+ pat += valid_char + '*'
76
+ elif char == '?':
77
+ # Match a name character
78
+ pat += valid_char
79
+ elif char == '[':
80
+ # Character class
81
+ inner_i = i + 1
82
+ # Skip initial !/] chars
83
+ if inner_i < chunk_len and chunk[inner_i] == '!':
84
+ inner_i = inner_i + 1
85
+ if inner_i < chunk_len and chunk[inner_i] == ']':
86
+ inner_i = inner_i + 1
87
+
88
+ # Loop till the closing ] is found
89
+ while inner_i < chunk_len and chunk[inner_i] != ']':
90
+ inner_i = inner_i + 1
91
+
92
+ if inner_i >= chunk_len:
93
+ # Got to the end of the string without finding a closing ]
94
+ # Do not treat this as a matching group, but as a literal [
95
+ pat += re.escape(char)
96
+ else:
97
+ # Grab the insides of the [brackets]
98
+ inner = chunk[i + 1 : inner_i]
99
+ char_class = ''
100
+
101
+ # Class negation
102
+ if inner[0] == '!':
103
+ char_class = '^'
104
+ inner = inner[1:]
105
+
106
+ char_class += re.escape(inner)
107
+ pat += f'[{char_class}]'
108
+
109
+ # Skip to the end ]
110
+ i = inner_i
111
+ else:
112
+ pat += re.escape(char)
113
+ i += 1
114
+
115
+ # Join each chunk with the dir separator
116
+ if not last_chunk:
117
+ pat += sep
118
+
119
+ pat += r'\Z'
120
+ return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
121
+
122
+
123
+ class InfoCommon:
124
+ tag_build = None
125
+ tag_date = None
126
+
127
+ @property
128
+ def name(self):
129
+ return _normalization.safe_name(self.distribution.get_name())
130
+
131
+ def tagged_version(self):
132
+ tagged = self._maybe_tag(self.distribution.get_version())
133
+ return _normalization.safe_version(tagged)
134
+
135
+ def _maybe_tag(self, version):
136
+ """
137
+ egg_info may be called more than once for a distribution,
138
+ in which case the version string already contains all tags.
139
+ """
140
+ return (
141
+ version
142
+ if self.vtags and self._already_tagged(version)
143
+ else version + self.vtags
144
+ )
145
+
146
+ def _already_tagged(self, version: str) -> bool:
147
+ # Depending on their format, tags may change with version normalization.
148
+ # So in addition the regular tags, we have to search for the normalized ones.
149
+ return version.endswith((self.vtags, self._safe_tags()))
150
+
151
+ def _safe_tags(self) -> str:
152
+ # To implement this we can rely on `safe_version` pretending to be version 0
153
+ # followed by tags. Then we simply discard the starting 0 (fake version number)
154
+ try:
155
+ return _normalization.safe_version(f"0{self.vtags}")[1:]
156
+ except packaging.version.InvalidVersion:
157
+ return _normalization.safe_name(self.vtags.replace(' ', '.'))
158
+
159
+ def tags(self) -> str:
160
+ version = ''
161
+ if self.tag_build:
162
+ version += self.tag_build
163
+ if self.tag_date:
164
+ version += time.strftime("%Y%m%d")
165
+ return version
166
+
167
+ vtags = property(tags)
168
+
169
+
170
+ class egg_info(InfoCommon, Command):
171
+ description = "create a distribution's .egg-info directory"
172
+
173
+ user_options = [
174
+ (
175
+ 'egg-base=',
176
+ 'e',
177
+ "directory containing .egg-info directories"
178
+ " [default: top of the source tree]",
179
+ ),
180
+ ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
181
+ ('tag-build=', 'b', "Specify explicit tag to add to version number"),
182
+ ('no-date', 'D', "Don't include date stamp [default]"),
183
+ ]
184
+
185
+ boolean_options = ['tag-date']
186
+ negative_opt = {
187
+ 'no-date': 'tag-date',
188
+ }
189
+
190
+ def initialize_options(self):
191
+ self.egg_base = None
192
+ self.egg_name = None
193
+ self.egg_info = None
194
+ self.egg_version = None
195
+ self.ignore_egg_info_in_manifest = False
196
+
197
+ ####################################
198
+ # allow the 'tag_svn_revision' to be detected and
199
+ # set, supporting sdists built on older Setuptools.
200
+ @property
201
+ def tag_svn_revision(self) -> int | None:
202
+ pass
203
+
204
+ @tag_svn_revision.setter
205
+ def tag_svn_revision(self, value) -> None:
206
+ pass
207
+
208
+ ####################################
209
+
210
+ def save_version_info(self, filename) -> None:
211
+ """
212
+ Materialize the value of date into the
213
+ build tag. Install build keys in a deterministic order
214
+ to avoid arbitrary reordering on subsequent builds.
215
+ """
216
+ # follow the order these keys would have been added
217
+ # when PYTHONHASHSEED=0
218
+ egg_info = dict(tag_build=self.tags(), tag_date=0)
219
+ edit_config(filename, dict(egg_info=egg_info))
220
+
221
+ def finalize_options(self) -> None:
222
+ # Note: we need to capture the current value returned
223
+ # by `self.tagged_version()`, so we can later update
224
+ # `self.distribution.metadata.version` without
225
+ # repercussions.
226
+ self.egg_name = self.name
227
+ self.egg_version = self.tagged_version()
228
+ parsed_version = packaging.version.Version(self.egg_version)
229
+
230
+ try:
231
+ is_version = isinstance(parsed_version, packaging.version.Version)
232
+ spec = "%s==%s" if is_version else "%s===%s"
233
+ packaging.requirements.Requirement(spec % (self.egg_name, self.egg_version))
234
+ except ValueError as e:
235
+ raise distutils.errors.DistutilsOptionError(
236
+ f"Invalid distribution name or version syntax: {self.egg_name}-{self.egg_version}"
237
+ ) from e
238
+
239
+ if self.egg_base is None:
240
+ dirs = self.distribution.package_dir
241
+ self.egg_base = (dirs or {}).get('', os.curdir)
242
+
243
+ self.ensure_dirname('egg_base')
244
+ self.egg_info = _normalization.filename_component(self.egg_name) + '.egg-info'
245
+ if self.egg_base != os.curdir:
246
+ self.egg_info = os.path.join(self.egg_base, self.egg_info)
247
+
248
+ # Set package version for the benefit of dumber commands
249
+ # (e.g. sdist, bdist_wininst, etc.)
250
+ #
251
+ self.distribution.metadata.version = self.egg_version
252
+
253
+ def _get_egg_basename(self, py_version=PY_MAJOR, platform=None):
254
+ """Compute filename of the output egg. Private API."""
255
+ return _egg_basename(self.egg_name, self.egg_version, py_version, platform)
256
+
257
+ def write_or_delete_file(self, what, filename, data, force: bool = False) -> None:
258
+ """Write `data` to `filename` or delete if empty
259
+
260
+ If `data` is non-empty, this routine is the same as ``write_file()``.
261
+ If `data` is empty but not ``None``, this is the same as calling
262
+ ``delete_file(filename)`. If `data` is ``None``, then this is a no-op
263
+ unless `filename` exists, in which case a warning is issued about the
264
+ orphaned file (if `force` is false), or deleted (if `force` is true).
265
+ """
266
+ if data:
267
+ self.write_file(what, filename, data)
268
+ elif os.path.exists(filename):
269
+ if data is None and not force:
270
+ log.warn("%s not set in setup(), but %s exists", what, filename)
271
+ return
272
+ else:
273
+ self.delete_file(filename)
274
+
275
+ def write_file(self, what, filename, data) -> None:
276
+ """Write `data` to `filename` (if not a dry run) after announcing it
277
+
278
+ `what` is used in a log message to identify what is being written
279
+ to the file.
280
+ """
281
+ log.info("writing %s to %s", what, filename)
282
+ data = data.encode("utf-8")
283
+ f = open(filename, 'wb')
284
+ f.write(data)
285
+ f.close()
286
+
287
+ def delete_file(self, filename) -> None:
288
+ """Delete `filename` (if not a dry run) after announcing it"""
289
+ log.info("deleting %s", filename)
290
+ os.unlink(filename)
291
+
292
+ def run(self) -> None:
293
+ # Pre-load to avoid iterating over entry-points while an empty .egg-info
294
+ # exists in sys.path. See pypa/pyproject-hooks#206
295
+ writers = list(metadata.entry_points(group='egg_info.writers'))
296
+
297
+ self.mkpath(self.egg_info)
298
+ try:
299
+ os.utime(self.egg_info, None)
300
+ except OSError as e:
301
+ msg = f"Cannot update time stamp of directory '{self.egg_info}'"
302
+ raise distutils.errors.DistutilsFileError(msg) from e
303
+ for ep in writers:
304
+ writer = ep.load()
305
+ writer(self, ep.name, os.path.join(self.egg_info, ep.name))
306
+
307
+ # Get rid of native_libs.txt if it was put there by older bdist_egg
308
+ nl = os.path.join(self.egg_info, "native_libs.txt")
309
+ if os.path.exists(nl):
310
+ self.delete_file(nl)
311
+
312
+ self.find_sources()
313
+
314
+ def find_sources(self) -> None:
315
+ """Generate SOURCES.txt manifest file"""
316
+ manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
317
+ mm = manifest_maker(self.distribution)
318
+ mm.ignore_egg_info_dir = self.ignore_egg_info_in_manifest
319
+ mm.manifest = manifest_filename
320
+ mm.run()
321
+ self.filelist = mm.filelist
322
+
323
+
324
+ class FileList(_FileList):
325
+ # Implementations of the various MANIFEST.in commands
326
+
327
+ def __init__(
328
+ self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False
329
+ ) -> None:
330
+ super().__init__(warn, debug_print)
331
+ self.ignore_egg_info_dir = ignore_egg_info_dir
332
+
333
+ def process_template_line(self, line) -> None:
334
+ # Parse the line: split it up, make sure the right number of words
335
+ # is there, and return the relevant words. 'action' is always
336
+ # defined: it's the first word of the line. Which of the other
337
+ # three are defined depends on the action; it'll be either
338
+ # patterns, (dir and patterns), or (dir_pattern).
339
+ (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
340
+
341
+ action_map: dict[str, Callable] = {
342
+ 'include': self.include,
343
+ 'exclude': self.exclude,
344
+ 'global-include': self.global_include,
345
+ 'global-exclude': self.global_exclude,
346
+ 'recursive-include': functools.partial(
347
+ self.recursive_include,
348
+ dir,
349
+ ),
350
+ 'recursive-exclude': functools.partial(
351
+ self.recursive_exclude,
352
+ dir,
353
+ ),
354
+ 'graft': self.graft,
355
+ 'prune': self.prune,
356
+ }
357
+ log_map = {
358
+ 'include': "warning: no files found matching '%s'",
359
+ 'exclude': ("warning: no previously-included files found matching '%s'"),
360
+ 'global-include': (
361
+ "warning: no files found matching '%s' anywhere in distribution"
362
+ ),
363
+ 'global-exclude': (
364
+ "warning: no previously-included files matching "
365
+ "'%s' found anywhere in distribution"
366
+ ),
367
+ 'recursive-include': (
368
+ "warning: no files found matching '%s' under directory '%s'"
369
+ ),
370
+ 'recursive-exclude': (
371
+ "warning: no previously-included files matching "
372
+ "'%s' found under directory '%s'"
373
+ ),
374
+ 'graft': "warning: no directories found matching '%s'",
375
+ 'prune': "no previously-included directories found matching '%s'",
376
+ }
377
+
378
+ try:
379
+ process_action = action_map[action]
380
+ except KeyError:
381
+ msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
382
+ raise DistutilsInternalError(msg) from None
383
+
384
+ # OK, now we know that the action is valid and we have the
385
+ # right number of words on the line for that action -- so we
386
+ # can proceed with minimal error-checking.
387
+
388
+ action_is_recursive = action.startswith('recursive-')
389
+ if action in {'graft', 'prune'}:
390
+ patterns = [dir_pattern]
391
+ extra_log_args = (dir,) if action_is_recursive else ()
392
+ log_tmpl = log_map[action]
393
+
394
+ self.debug_print(
395
+ ' '.join(
396
+ [action] + ([dir] if action_is_recursive else []) + patterns,
397
+ )
398
+ )
399
+ for pattern in patterns:
400
+ if not process_action(pattern):
401
+ log.warn(log_tmpl, pattern, *extra_log_args)
402
+
403
+ def _remove_files(self, predicate):
404
+ """
405
+ Remove all files from the file list that match the predicate.
406
+ Return True if any matching files were removed
407
+ """
408
+ found = False
409
+ for i in range(len(self.files) - 1, -1, -1):
410
+ if predicate(self.files[i]):
411
+ self.debug_print(" removing " + self.files[i])
412
+ del self.files[i]
413
+ found = True
414
+ return found
415
+
416
+ def include(self, pattern):
417
+ """Include files that match 'pattern'."""
418
+ found = [f for f in glob(pattern) if not os.path.isdir(f)]
419
+ self.extend(found)
420
+ return bool(found)
421
+
422
+ def exclude(self, pattern):
423
+ """Exclude files that match 'pattern'."""
424
+ match = translate_pattern(pattern)
425
+ return self._remove_files(match.match)
426
+
427
+ def recursive_include(self, dir, pattern):
428
+ """
429
+ Include all files anywhere in 'dir/' that match the pattern.
430
+ """
431
+ full_pattern = os.path.join(dir, '**', pattern)
432
+ found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)]
433
+ self.extend(found)
434
+ return bool(found)
435
+
436
+ def recursive_exclude(self, dir, pattern):
437
+ """
438
+ Exclude any file anywhere in 'dir/' that match the pattern.
439
+ """
440
+ match = translate_pattern(os.path.join(dir, '**', pattern))
441
+ return self._remove_files(match.match)
442
+
443
+ def graft(self, dir):
444
+ """Include all files from 'dir/'."""
445
+ found = [
446
+ item
447
+ for match_dir in glob(dir)
448
+ for item in distutils.filelist.findall(match_dir)
449
+ ]
450
+ self.extend(found)
451
+ return bool(found)
452
+
453
+ def prune(self, dir):
454
+ """Filter out files from 'dir/'."""
455
+ match = translate_pattern(os.path.join(dir, '**'))
456
+ return self._remove_files(match.match)
457
+
458
+ def global_include(self, pattern):
459
+ """
460
+ Include all files anywhere in the current directory that match the
461
+ pattern. This is very inefficient on large file trees.
462
+ """
463
+ if self.allfiles is None:
464
+ self.findall()
465
+ match = translate_pattern(os.path.join('**', pattern))
466
+ found = [f for f in self.allfiles if match.match(f)]
467
+ self.extend(found)
468
+ return bool(found)
469
+
470
+ def global_exclude(self, pattern):
471
+ """
472
+ Exclude all files anywhere that match the pattern.
473
+ """
474
+ match = translate_pattern(os.path.join('**', pattern))
475
+ return self._remove_files(match.match)
476
+
477
+ def append(self, item) -> None:
478
+ item = item.removesuffix('\r') # Fix older sdists built on Windows
479
+ path = convert_path(item)
480
+
481
+ if self._safe_path(path):
482
+ self.files.append(path)
483
+
484
+ def extend(self, paths) -> None:
485
+ self.files.extend(filter(self._safe_path, paths))
486
+
487
+ def _repair(self):
488
+ """
489
+ Replace self.files with only safe paths
490
+
491
+ Because some owners of FileList manipulate the underlying
492
+ ``files`` attribute directly, this method must be called to
493
+ repair those paths.
494
+ """
495
+ self.files = list(filter(self._safe_path, self.files))
496
+
497
+ def _safe_path(self, path):
498
+ enc_warn = "'%s' not %s encodable -- skipping"
499
+
500
+ # To avoid accidental trans-codings errors, first to unicode
501
+ u_path = unicode_utils.filesys_decode(path)
502
+ if u_path is None:
503
+ log.warn(f"'{path}' in unexpected encoding -- skipping")
504
+ return False
505
+
506
+ # Must ensure utf-8 encodability
507
+ utf8_path = unicode_utils.try_encode(u_path, "utf-8")
508
+ if utf8_path is None:
509
+ log.warn(enc_warn, path, 'utf-8')
510
+ return False
511
+
512
+ try:
513
+ # ignore egg-info paths
514
+ is_egg_info = ".egg-info" in u_path or b".egg-info" in utf8_path
515
+ if self.ignore_egg_info_dir and is_egg_info:
516
+ return False
517
+ # accept is either way checks out
518
+ if os.path.exists(u_path) or os.path.exists(utf8_path):
519
+ return True
520
+ # this will catch any encode errors decoding u_path
521
+ except UnicodeEncodeError:
522
+ log.warn(enc_warn, path, sys.getfilesystemencoding())
523
+
524
+
525
+ class manifest_maker(sdist):
526
+ template = "MANIFEST.in"
527
+
528
+ def initialize_options(self) -> None:
529
+ self.use_defaults = True
530
+ self.prune = True
531
+ self.manifest_only = True
532
+ self.force_manifest = True
533
+ self.ignore_egg_info_dir = False
534
+
535
+ def finalize_options(self) -> None:
536
+ pass
537
+
538
+ def run(self) -> None:
539
+ self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)
540
+ if not os.path.exists(self.manifest):
541
+ self.write_manifest() # it must exist so it'll get in the list
542
+ self.add_defaults()
543
+ if os.path.exists(self.template):
544
+ self.read_template()
545
+ self.add_license_files()
546
+ self._add_referenced_files()
547
+ self.prune_file_list()
548
+ self.filelist.sort()
549
+ self.filelist.remove_duplicates()
550
+ self.write_manifest()
551
+
552
+ def _manifest_normalize(self, path):
553
+ path = unicode_utils.filesys_decode(path)
554
+ return path.replace(os.sep, '/')
555
+
556
+ def write_manifest(self) -> None:
557
+ """
558
+ Write the file list in 'self.filelist' to the manifest file
559
+ named by 'self.manifest'.
560
+ """
561
+ self.filelist._repair()
562
+
563
+ # Now _repairs should encodability, but not unicode
564
+ files = [self._manifest_normalize(f) for f in self.filelist.files]
565
+ msg = f"writing manifest file '{self.manifest}'"
566
+ self.execute(write_file, (self.manifest, files), msg)
567
+
568
+ def warn(self, msg) -> None:
569
+ if not self._should_suppress_warning(msg):
570
+ sdist.warn(self, msg)
571
+
572
+ @staticmethod
573
+ def _should_suppress_warning(msg):
574
+ """
575
+ suppress missing-file warnings from sdist
576
+ """
577
+ return re.match(r"standard file .*not found", msg)
578
+
579
+ def add_defaults(self) -> None:
580
+ sdist.add_defaults(self)
581
+ self.filelist.append(self.template)
582
+ self.filelist.append(self.manifest)
583
+ rcfiles = list(walk_revctrl())
584
+ if rcfiles:
585
+ self.filelist.extend(rcfiles)
586
+ elif os.path.exists(self.manifest):
587
+ self.read_manifest()
588
+
589
+ if os.path.exists("setup.py"):
590
+ # setup.py should be included by default, even if it's not
591
+ # the script called to create the sdist
592
+ self.filelist.append("setup.py")
593
+
594
+ ei_cmd = self.get_finalized_command('egg_info')
595
+ self.filelist.graft(ei_cmd.egg_info)
596
+
597
+ def add_license_files(self) -> None:
598
+ license_files = self.distribution.metadata.license_files or []
599
+ for lf in license_files:
600
+ log.info("adding license file '%s'", lf)
601
+ self.filelist.extend(license_files)
602
+
603
+ def _add_referenced_files(self):
604
+ """Add files referenced by the config (e.g. `file:` directive) to filelist"""
605
+ referenced = getattr(self.distribution, '_referenced_files', [])
606
+ # ^-- fallback if dist comes from distutils or is a custom class
607
+ for rf in referenced:
608
+ log.debug("adding file referenced by config '%s'", rf)
609
+ self.filelist.extend(referenced)
610
+
611
+ def _safe_data_files(self, build_py):
612
+ """
613
+ The parent class implementation of this method
614
+ (``sdist``) will try to include data files, which
615
+ might cause recursion problems when
616
+ ``include_package_data=True``.
617
+
618
+ Therefore, avoid triggering any attempt of
619
+ analyzing/building the manifest again.
620
+ """
621
+ if hasattr(build_py, 'get_data_files_without_manifest'):
622
+ return build_py.get_data_files_without_manifest()
623
+
624
+ SetuptoolsDeprecationWarning.emit(
625
+ "`build_py` command does not inherit from setuptools' `build_py`.",
626
+ """
627
+ Custom 'build_py' does not implement 'get_data_files_without_manifest'.
628
+ Please extend command classes from setuptools instead of distutils.
629
+ """,
630
+ see_url="https://peps.python.org/pep-0632/",
631
+ # due_date not defined yet, old projects might still do it?
632
+ )
633
+ return build_py.get_data_files()
634
+
635
+
636
+ def write_file(filename, contents) -> None:
637
+ """Create a file with the specified name and write 'contents' (a
638
+ sequence of strings without line terminators) to it.
639
+ """
640
+ contents = "\n".join(contents)
641
+
642
+ # assuming the contents has been vetted for utf-8 encoding
643
+ contents = contents.encode("utf-8")
644
+
645
+ with open(filename, "wb") as f: # always write POSIX-style manifest
646
+ f.write(contents)
647
+
648
+
649
+ def write_pkg_info(cmd, basename, filename) -> None:
650
+ log.info("writing %s", filename)
651
+ metadata = cmd.distribution.metadata
652
+ metadata.version, oldver = cmd.egg_version, metadata.version
653
+ metadata.name, oldname = cmd.egg_name, metadata.name
654
+
655
+ try:
656
+ metadata.write_pkg_info(cmd.egg_info)
657
+ finally:
658
+ metadata.name, metadata.version = oldname, oldver
659
+
660
+ safe = getattr(cmd.distribution, 'zip_safe', None)
661
+
662
+ bdist_egg.write_safety_flag(cmd.egg_info, safe)
663
+
664
+
665
+ def warn_depends_obsolete(cmd, basename, filename) -> None:
666
+ """
667
+ Unused: left to avoid errors when updating (from source) from <= 67.8.
668
+ Old installations have a .dist-info directory with the entry-point
669
+ ``depends.txt = setuptools.command.egg_info:warn_depends_obsolete``.
670
+ This may trigger errors when running the first egg_info in build_meta.
671
+ TODO: Remove this function in a version sufficiently > 68.
672
+ """
673
+
674
+
675
+ # Export API used in entry_points
676
+ write_requirements = _requirestxt.write_requirements
677
+ write_setup_requirements = _requirestxt.write_setup_requirements
678
+
679
+
680
+ def write_toplevel_names(cmd, basename, filename) -> None:
681
+ pkgs = dict.fromkeys([
682
+ k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names()
683
+ ])
684
+ cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
685
+
686
+
687
+ def overwrite_arg(cmd, basename, filename) -> None:
688
+ write_arg(cmd, basename, filename, True)
689
+
690
+
691
+ def write_arg(cmd, basename, filename, force: bool = False) -> None:
692
+ argname = os.path.splitext(basename)[0]
693
+ value = getattr(cmd.distribution, argname, None)
694
+ if value is not None:
695
+ value = '\n'.join(value) + '\n'
696
+ cmd.write_or_delete_file(argname, filename, value, force)
697
+
698
+
699
+ def write_entries(cmd, basename, filename) -> None:
700
+ eps = _entry_points.load(cmd.distribution.entry_points)
701
+ defn = _entry_points.render(eps)
702
+ cmd.write_or_delete_file('entry points', filename, defn, True)
703
+
704
+
705
+ def _egg_basename(egg_name, egg_version, py_version=None, platform=None):
706
+ """Compute filename of the output egg. Private API."""
707
+ name = _normalization.filename_component(egg_name)
708
+ version = _normalization.filename_component(egg_version)
709
+ egg = f"{name}-{version}-py{py_version or PY_MAJOR}"
710
+ if platform:
711
+ egg += f"-{platform}"
712
+ return egg
713
+
714
+
715
+ class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
716
+ """Deprecated behavior warning for EggInfo, bypassing suppression."""
python/Lib/site-packages/setuptools/command/install.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import platform
5
+ from collections.abc import Callable
6
+ from typing import TYPE_CHECKING, Any, ClassVar
7
+
8
+ from ..dist import Distribution
9
+ from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
10
+
11
+ import distutils.command.install as orig
12
+ from distutils.errors import DistutilsArgError
13
+
14
+ if TYPE_CHECKING:
15
+ # This is only used for a type-cast, don't import at runtime or it'll cause deprecation warnings
16
+ from .easy_install import easy_install as easy_install_cls
17
+ else:
18
+ easy_install_cls = None
19
+
20
+
21
+ def __getattr__(name: str): # pragma: no cover
22
+ if name == "_install":
23
+ SetuptoolsDeprecationWarning.emit(
24
+ "`setuptools.command._install` was an internal implementation detail "
25
+ "that was left in for numpy<1.9 support.",
26
+ due_date=(2025, 5, 2), # Originally added on 2024-11-01
27
+ )
28
+ return orig.install
29
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
30
+
31
+
32
+ class install(orig.install):
33
+ """Use easy_install to install the package, w/dependencies"""
34
+
35
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
36
+
37
+ user_options = orig.install.user_options + [
38
+ ('old-and-unmanageable', None, "Try not to use this!"),
39
+ (
40
+ 'single-version-externally-managed',
41
+ None,
42
+ "used by system package builders to create 'flat' eggs",
43
+ ),
44
+ ]
45
+ boolean_options = orig.install.boolean_options + [
46
+ 'old-and-unmanageable',
47
+ 'single-version-externally-managed',
48
+ ]
49
+ # Type the same as distutils.command.install.install.sub_commands
50
+ # Must keep the second tuple item potentially None due to invariance
51
+ new_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] = [
52
+ ('install_egg_info', lambda self: True),
53
+ ('install_scripts', lambda self: True),
54
+ ]
55
+ _nc = dict(new_commands)
56
+
57
+ def initialize_options(self):
58
+ SetuptoolsDeprecationWarning.emit(
59
+ "setup.py install is deprecated.",
60
+ """
61
+ Please avoid running ``setup.py`` directly.
62
+ Instead, use pypa/build, pypa/installer or other
63
+ standards-based tools.
64
+ """,
65
+ see_url="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html",
66
+ due_date=(2025, 10, 31),
67
+ )
68
+
69
+ super().initialize_options()
70
+ self.old_and_unmanageable = None
71
+ self.single_version_externally_managed = None
72
+
73
+ def finalize_options(self) -> None:
74
+ super().finalize_options()
75
+ if self.root:
76
+ self.single_version_externally_managed = True
77
+ elif self.single_version_externally_managed:
78
+ if not self.root and not self.record:
79
+ raise DistutilsArgError(
80
+ "You must specify --record or --root when building system packages"
81
+ )
82
+
83
+ def handle_extra_path(self):
84
+ if self.root or self.single_version_externally_managed:
85
+ # explicit backward-compatibility mode, allow extra_path to work
86
+ return orig.install.handle_extra_path(self)
87
+
88
+ # Ignore extra_path when installing an egg (or being run by another
89
+ # command without --root or --single-version-externally-managed
90
+ self.path_file = None
91
+ self.extra_dirs = ''
92
+ return None
93
+
94
+ @staticmethod
95
+ def _called_from_setup(run_frame):
96
+ """
97
+ Attempt to detect whether run() was called from setup() or by another
98
+ command. If called by setup(), the parent caller will be the
99
+ 'run_command' method in 'distutils.dist', and *its* caller will be
100
+ the 'run_commands' method. If called any other way, the
101
+ immediate caller *might* be 'run_command', but it won't have been
102
+ called by 'run_commands'. Return True in that case or if a call stack
103
+ is unavailable. Return False otherwise.
104
+ """
105
+ if run_frame is None:
106
+ msg = "Call stack not available. bdist_* commands may fail."
107
+ SetuptoolsWarning.emit(msg)
108
+ if platform.python_implementation() == 'IronPython':
109
+ msg = "For best results, pass -X:Frames to enable call stack."
110
+ SetuptoolsWarning.emit(msg)
111
+ return True
112
+
113
+ frames = inspect.getouterframes(run_frame)
114
+ for frame in frames[2:4]:
115
+ (caller,) = frame[:1]
116
+ info = inspect.getframeinfo(caller)
117
+ caller_module = caller.f_globals.get('__name__', '')
118
+
119
+ if caller_module == "setuptools.dist" and info.function == "run_command":
120
+ # Starting from v61.0.0 setuptools overwrites dist.run_command
121
+ continue
122
+
123
+ return caller_module == 'distutils.dist' and info.function == 'run_commands'
124
+
125
+ return False
126
+
127
+
128
+ # XXX Python 3.1 doesn't see _nc if this is inside the class
129
+ install.sub_commands = [
130
+ cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc
131
+ ] + install.new_commands
python/Lib/site-packages/setuptools/command/install_egg_info.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from setuptools import Command, namespaces
4
+ from setuptools.archive_util import unpack_archive
5
+
6
+ from .._path import ensure_directory
7
+
8
+ from distutils import dir_util, log
9
+
10
+
11
+ class install_egg_info(namespaces.Installer, Command):
12
+ """Install an .egg-info directory for the package"""
13
+
14
+ description = "Install an .egg-info directory for the package"
15
+
16
+ user_options = [
17
+ ('install-dir=', 'd', "directory to install to"),
18
+ ]
19
+
20
+ def initialize_options(self):
21
+ self.install_dir = None
22
+
23
+ def finalize_options(self) -> None:
24
+ self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
25
+ ei_cmd = self.get_finalized_command("egg_info")
26
+ basename = f"{ei_cmd._get_egg_basename()}.egg-info"
27
+ self.source = ei_cmd.egg_info
28
+ self.target = os.path.join(self.install_dir, basename)
29
+ self.outputs: list[str] = []
30
+
31
+ def run(self) -> None:
32
+ self.run_command('egg_info')
33
+ if os.path.isdir(self.target) and not os.path.islink(self.target):
34
+ dir_util.remove_tree(self.target)
35
+ elif os.path.exists(self.target):
36
+ self.execute(os.unlink, (self.target,), "Removing " + self.target)
37
+ ensure_directory(self.target)
38
+ self.execute(self.copytree, (), f"Copying {self.source} to {self.target}")
39
+ self.install_namespaces()
40
+
41
+ def get_outputs(self):
42
+ return self.outputs
43
+
44
+ def copytree(self) -> None:
45
+ # Copy the .egg-info tree to site-packages
46
+ def skimmer(src, dst):
47
+ # filter out source-control directories; note that 'src' is always
48
+ # a '/'-separated path, regardless of platform. 'dst' is a
49
+ # platform-specific path.
50
+ for skip in '.svn/', 'CVS/':
51
+ if src.startswith(skip) or '/' + skip in src:
52
+ return None
53
+ self.outputs.append(dst)
54
+ log.debug("Copying %s to %s", src, dst)
55
+ return dst
56
+
57
+ unpack_archive(self.source, self.target, skimmer)
python/Lib/site-packages/setuptools/command/install_lib.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from itertools import product, starmap
6
+
7
+ from .._path import StrPath
8
+ from ..dist import Distribution
9
+
10
+ import distutils.command.install_lib as orig
11
+
12
+
13
+ class install_lib(orig.install_lib):
14
+ """Don't add compiled flags to filenames of non-Python files"""
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def run(self) -> None:
19
+ self.build()
20
+ outfiles = self.install()
21
+ if outfiles is not None:
22
+ # always compile, in case we have any extension stubs to deal with
23
+ self.byte_compile(outfiles)
24
+
25
+ def get_exclusions(self):
26
+ """
27
+ Return a collections.Sized collections.Container of paths to be
28
+ excluded for single_version_externally_managed installations.
29
+ """
30
+ all_packages = (
31
+ pkg
32
+ for ns_pkg in self._get_SVEM_NSPs()
33
+ for pkg in self._all_packages(ns_pkg)
34
+ )
35
+
36
+ excl_specs = product(all_packages, self._gen_exclusion_paths())
37
+ return set(starmap(self._exclude_pkg_path, excl_specs))
38
+
39
+ def _exclude_pkg_path(self, pkg, exclusion_path):
40
+ """
41
+ Given a package name and exclusion path within that package,
42
+ compute the full exclusion path.
43
+ """
44
+ parts = pkg.split('.') + [exclusion_path]
45
+ return os.path.join(self.install_dir, *parts)
46
+
47
+ @staticmethod
48
+ def _all_packages(pkg_name):
49
+ """
50
+ >>> list(install_lib._all_packages('foo.bar.baz'))
51
+ ['foo.bar.baz', 'foo.bar', 'foo']
52
+ """
53
+ while pkg_name:
54
+ yield pkg_name
55
+ pkg_name, _sep, _child = pkg_name.rpartition('.')
56
+
57
+ def _get_SVEM_NSPs(self):
58
+ """
59
+ Get namespace packages (list) but only for
60
+ single_version_externally_managed installations and empty otherwise.
61
+ """
62
+ # TODO: is it necessary to short-circuit here? i.e. what's the cost
63
+ # if get_finalized_command is called even when namespace_packages is
64
+ # False?
65
+ if not self.distribution.namespace_packages:
66
+ return []
67
+
68
+ install_cmd = self.get_finalized_command('install')
69
+ svem = install_cmd.single_version_externally_managed
70
+
71
+ return self.distribution.namespace_packages if svem else []
72
+
73
+ @staticmethod
74
+ def _gen_exclusion_paths():
75
+ """
76
+ Generate file paths to be excluded for namespace packages (bytecode
77
+ cache files).
78
+ """
79
+ # always exclude the package module itself
80
+ yield '__init__.py'
81
+
82
+ yield '__init__.pyc'
83
+ yield '__init__.pyo'
84
+
85
+ if not hasattr(sys, 'implementation'):
86
+ return
87
+
88
+ base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag)
89
+ yield base + '.pyc'
90
+ yield base + '.pyo'
91
+ yield base + '.opt-1.pyc'
92
+ yield base + '.opt-2.pyc'
93
+
94
+ def copy_tree(
95
+ self,
96
+ infile: StrPath,
97
+ outfile: str,
98
+ # override: Using actual booleans
99
+ preserve_mode: bool = True, # type: ignore[override]
100
+ preserve_times: bool = True, # type: ignore[override]
101
+ preserve_symlinks: bool = False, # type: ignore[override]
102
+ level: object = 1,
103
+ ) -> list[str]:
104
+ assert preserve_mode
105
+ assert preserve_times
106
+ assert not preserve_symlinks
107
+ exclude = self.get_exclusions()
108
+
109
+ if not exclude:
110
+ return orig.install_lib.copy_tree(self, infile, outfile)
111
+
112
+ # Exclude namespace package __init__.py* files from the output
113
+
114
+ from setuptools.archive_util import unpack_directory
115
+
116
+ from distutils import log
117
+
118
+ outfiles: list[str] = []
119
+
120
+ def pf(src: str, dst: str):
121
+ if dst in exclude:
122
+ log.warn("Skipping installation of %s (namespace package)", dst)
123
+ return False
124
+
125
+ log.info("copying %s -> %s", src, os.path.dirname(dst))
126
+ outfiles.append(dst)
127
+ return dst
128
+
129
+ unpack_directory(infile, outfile, pf)
130
+ return outfiles
131
+
132
+ def get_outputs(self):
133
+ outputs = orig.install_lib.get_outputs(self)
134
+ exclude = self.get_exclusions()
135
+ if exclude:
136
+ return [f for f in outputs if f not in exclude]
137
+ return outputs
python/Lib/site-packages/setuptools/command/install_scripts.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+
6
+ from .._path import ensure_directory
7
+ from ..dist import Distribution
8
+
9
+ import distutils.command.install_scripts as orig
10
+ from distutils import log
11
+
12
+
13
+ class install_scripts(orig.install_scripts):
14
+ """Do normal script install, plus any egg_info wrapper scripts"""
15
+
16
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
17
+
18
+ def initialize_options(self) -> None:
19
+ orig.install_scripts.initialize_options(self)
20
+ self.no_ep = False
21
+
22
+ def run(self) -> None:
23
+ self.run_command("egg_info")
24
+ if self.distribution.scripts:
25
+ orig.install_scripts.run(self) # run first to set up self.outfiles
26
+ else:
27
+ self.outfiles: list[str] = []
28
+ if self.no_ep:
29
+ # don't install entry point scripts into .egg file!
30
+ return
31
+ self._install_ep_scripts()
32
+
33
+ def _install_ep_scripts(self):
34
+ # Delay import side-effects
35
+ from .. import _scripts
36
+ from .._importlib import metadata
37
+
38
+ ei_cmd = self.get_finalized_command("egg_info")
39
+ dist = metadata.Distribution.at(path=ei_cmd.egg_info)
40
+ bs_cmd = self.get_finalized_command('build_scripts')
41
+ exec_param = getattr(bs_cmd, 'executable', None)
42
+ writer = _scripts.ScriptWriter
43
+ if exec_param == sys.executable:
44
+ # In case the path to the Python executable contains a space, wrap
45
+ # it so it's not split up.
46
+ exec_param = [exec_param]
47
+ # resolve the writer to the environment
48
+ writer = writer.best()
49
+ cmd = writer.command_spec_class.best().from_param(exec_param)
50
+ for args in writer.get_args(dist, cmd.as_header()):
51
+ self.write_script(*args)
52
+
53
+ def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None:
54
+ """Write an executable file to the scripts directory"""
55
+ from .._shutil import attempt_chmod_verbose as chmod, current_umask
56
+
57
+ log.info("Installing %s script to %s", script_name, self.install_dir)
58
+ target = os.path.join(self.install_dir, script_name)
59
+ self.outfiles.append(target)
60
+
61
+ encoding = None if "b" in mode else "utf-8"
62
+ mask = current_umask()
63
+ ensure_directory(target)
64
+ with open(target, "w" + mode, encoding=encoding) as f:
65
+ f.write(contents)
66
+ chmod(target, 0o777 - mask)
python/Lib/site-packages/setuptools/command/rotate.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import ClassVar
5
+
6
+ from .. import Command, _shutil
7
+
8
+ from distutils import log
9
+ from distutils.errors import DistutilsOptionError
10
+ from distutils.util import convert_path
11
+
12
+
13
+ class rotate(Command):
14
+ """Delete older distributions"""
15
+
16
+ description = "delete older distributions, keeping N newest files"
17
+ user_options = [
18
+ ('match=', 'm', "patterns to match (required)"),
19
+ ('dist-dir=', 'd', "directory where the distributions are"),
20
+ ('keep=', 'k', "number of matching distributions to keep"),
21
+ ]
22
+
23
+ boolean_options: ClassVar[list[str]] = []
24
+
25
+ def initialize_options(self):
26
+ self.match = None
27
+ self.dist_dir = None
28
+ self.keep = None
29
+
30
+ def finalize_options(self) -> None:
31
+ if self.match is None:
32
+ raise DistutilsOptionError(
33
+ "Must specify one or more (comma-separated) match patterns "
34
+ "(e.g. '.zip' or '.egg')"
35
+ )
36
+ if self.keep is None:
37
+ raise DistutilsOptionError("Must specify number of files to keep")
38
+ try:
39
+ self.keep = int(self.keep)
40
+ except ValueError as e:
41
+ raise DistutilsOptionError("--keep must be an integer") from e
42
+ if isinstance(self.match, str):
43
+ self.match = [convert_path(p.strip()) for p in self.match.split(',')]
44
+ self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
45
+
46
+ def run(self) -> None:
47
+ self.run_command("egg_info")
48
+ from glob import glob
49
+
50
+ for pattern in self.match:
51
+ pattern = self.distribution.get_name() + '*' + pattern
52
+ files = glob(os.path.join(self.dist_dir, pattern))
53
+ files = [(os.path.getmtime(f), f) for f in files]
54
+ files.sort()
55
+ files.reverse()
56
+
57
+ log.info("%d file(s) matching %s", len(files), pattern)
58
+ files = files[self.keep :]
59
+ for t, f in files:
60
+ log.info("Deleting %s", f)
61
+ if os.path.isdir(f):
62
+ _shutil.rmtree(f)
63
+ else:
64
+ os.unlink(f)
python/Lib/site-packages/setuptools/command/saveopts.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools.command.setopt import edit_config, option_base
2
+
3
+
4
+ class saveopts(option_base):
5
+ """Save command-line options to a file"""
6
+
7
+ description = "save supplied options to setup.cfg or other config file"
8
+
9
+ def run(self) -> None:
10
+ dist = self.distribution
11
+ settings: dict[str, dict[str, str]] = {}
12
+
13
+ for cmd in dist.command_options:
14
+ if cmd == 'saveopts':
15
+ continue # don't save our own options!
16
+
17
+ for opt, (src, val) in dist.get_option_dict(cmd).items():
18
+ if src == "command line":
19
+ settings.setdefault(cmd, {})[opt] = val
20
+
21
+ edit_config(self.filename, settings)
python/Lib/site-packages/setuptools/command/sdist.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import os
5
+ import re
6
+ from collections.abc import Iterator
7
+ from itertools import chain
8
+ from typing import ClassVar
9
+
10
+ from .._importlib import metadata
11
+ from ..dist import Distribution
12
+ from .build import _ORIGINAL_SUBCOMMANDS
13
+
14
+ import distutils.command.sdist as orig
15
+ from distutils import log
16
+
17
+ _default_revctrl = list
18
+
19
+
20
+ def walk_revctrl(dirname='') -> Iterator:
21
+ """Find all files under revision control"""
22
+ for ep in metadata.entry_points(group='setuptools.file_finders'):
23
+ yield from ep.load()(dirname)
24
+
25
+
26
+ class sdist(orig.sdist):
27
+ """Smart sdist that finds anything supported by revision control"""
28
+
29
+ user_options = [
30
+ ('formats=', None, "formats for source distribution (comma-separated list)"),
31
+ (
32
+ 'keep-temp',
33
+ 'k',
34
+ "keep the distribution tree around after creating archive file(s)",
35
+ ),
36
+ (
37
+ 'dist-dir=',
38
+ 'd',
39
+ "directory to put the source distribution archive(s) in [default: dist]",
40
+ ),
41
+ (
42
+ 'owner=',
43
+ 'u',
44
+ "Owner name used when creating a tar file [default: current user]",
45
+ ),
46
+ (
47
+ 'group=',
48
+ 'g',
49
+ "Group name used when creating a tar file [default: current group]",
50
+ ),
51
+ ]
52
+
53
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
54
+ negative_opt: ClassVar[dict[str, str]] = {}
55
+
56
+ README_EXTENSIONS = ['', '.rst', '.txt', '.md']
57
+ READMES = tuple(f'README{ext}' for ext in README_EXTENSIONS)
58
+
59
+ def run(self) -> None:
60
+ self.run_command('egg_info')
61
+ ei_cmd = self.get_finalized_command('egg_info')
62
+ self.filelist = ei_cmd.filelist
63
+ self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
64
+ self.check_readme()
65
+
66
+ # Run sub commands
67
+ for cmd_name in self.get_sub_commands():
68
+ self.run_command(cmd_name)
69
+
70
+ self.make_distribution()
71
+
72
+ dist_files = getattr(self.distribution, 'dist_files', [])
73
+ for file in self.archive_files:
74
+ data = ('sdist', '', file)
75
+ if data not in dist_files:
76
+ dist_files.append(data)
77
+
78
+ def initialize_options(self) -> None:
79
+ orig.sdist.initialize_options(self)
80
+
81
+ def make_distribution(self) -> None:
82
+ """
83
+ Workaround for #516
84
+ """
85
+ with self._remove_os_link():
86
+ orig.sdist.make_distribution(self)
87
+
88
+ @staticmethod
89
+ @contextlib.contextmanager
90
+ def _remove_os_link():
91
+ """
92
+ In a context, remove and restore os.link if it exists
93
+ """
94
+
95
+ class NoValue:
96
+ pass
97
+
98
+ orig_val = getattr(os, 'link', NoValue)
99
+ try:
100
+ del os.link
101
+ except Exception:
102
+ pass
103
+ try:
104
+ yield
105
+ finally:
106
+ if orig_val is not NoValue:
107
+ os.link = orig_val
108
+
109
+ def add_defaults(self) -> None:
110
+ super().add_defaults()
111
+ self._add_defaults_build_sub_commands()
112
+
113
+ def _add_defaults_optional(self):
114
+ super()._add_defaults_optional()
115
+ if os.path.isfile('pyproject.toml'):
116
+ self.filelist.append('pyproject.toml')
117
+
118
+ def _add_defaults_python(self):
119
+ """getting python files"""
120
+ if self.distribution.has_pure_modules():
121
+ build_py = self.get_finalized_command('build_py')
122
+ self.filelist.extend(build_py.get_source_files())
123
+ self._add_data_files(self._safe_data_files(build_py))
124
+
125
+ def _add_defaults_build_sub_commands(self):
126
+ build = self.get_finalized_command("build")
127
+ missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS
128
+ # ^-- the original built-in sub-commands are already handled by default.
129
+ cmds = (self.get_finalized_command(c) for c in missing_cmds)
130
+ files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files"))
131
+ self.filelist.extend(chain.from_iterable(files))
132
+
133
+ def _safe_data_files(self, build_py):
134
+ """
135
+ Since the ``sdist`` class is also used to compute the MANIFEST
136
+ (via :obj:`setuptools.command.egg_info.manifest_maker`),
137
+ there might be recursion problems when trying to obtain the list of
138
+ data_files and ``include_package_data=True`` (which in turn depends on
139
+ the files included in the MANIFEST).
140
+
141
+ To avoid that, ``manifest_maker`` should be able to overwrite this
142
+ method and avoid recursive attempts to build/analyze the MANIFEST.
143
+ """
144
+ return build_py.data_files
145
+
146
+ def _add_data_files(self, data_files):
147
+ """
148
+ Add data files as found in build_py.data_files.
149
+ """
150
+ self.filelist.extend(
151
+ os.path.join(src_dir, name)
152
+ for _, src_dir, _, filenames in data_files
153
+ for name in filenames
154
+ )
155
+
156
+ def _add_defaults_data_files(self):
157
+ try:
158
+ super()._add_defaults_data_files()
159
+ except TypeError:
160
+ log.warn("data_files contains unexpected objects")
161
+
162
+ def prune_file_list(self) -> None:
163
+ super().prune_file_list()
164
+ # Prevent accidental inclusion of test-related cache dirs at the project root
165
+ sep = re.escape(os.sep)
166
+ self.filelist.exclude_pattern(r"^(\.tox|\.nox|\.venv)" + sep, is_regex=True)
167
+
168
+ def check_readme(self) -> None:
169
+ for f in self.READMES:
170
+ if os.path.exists(f):
171
+ return
172
+ else:
173
+ self.warn(
174
+ "standard file not found: should have one of " + ', '.join(self.READMES)
175
+ )
176
+
177
+ def make_release_tree(self, base_dir, files) -> None:
178
+ orig.sdist.make_release_tree(self, base_dir, files)
179
+
180
+ # Save any egg_info command line options used to create this sdist
181
+ dest = os.path.join(base_dir, 'setup.cfg')
182
+ if hasattr(os, 'link') and os.path.exists(dest):
183
+ # unlink and re-copy, since it might be hard-linked, and
184
+ # we don't want to change the source version
185
+ os.unlink(dest)
186
+ self.copy_file('setup.cfg', dest)
187
+
188
+ self.get_finalized_command('egg_info').save_version_info(dest)
189
+
190
+ def _manifest_is_not_generated(self):
191
+ # check for special comment used in 2.7.1 and higher
192
+ if not os.path.isfile(self.manifest):
193
+ return False
194
+
195
+ with open(self.manifest, 'rb') as fp:
196
+ first_line = fp.readline()
197
+ return first_line != b'# file GENERATED by distutils, do NOT edit\n'
198
+
199
+ def read_manifest(self) -> None:
200
+ """Read the manifest file (named by 'self.manifest') and use it to
201
+ fill in 'self.filelist', the list of files to include in the source
202
+ distribution.
203
+ """
204
+ log.info("reading manifest file '%s'", self.manifest)
205
+ manifest = open(self.manifest, 'rb')
206
+ for bytes_line in manifest:
207
+ # The manifest must contain UTF-8. See #303.
208
+ try:
209
+ line = bytes_line.decode('UTF-8')
210
+ except UnicodeDecodeError:
211
+ log.warn(f"{line!r} not UTF-8 decodable -- skipping")
212
+ continue
213
+ # ignore comments and blank lines
214
+ line = line.strip()
215
+ if line.startswith('#') or not line:
216
+ continue
217
+ self.filelist.append(line)
218
+ manifest.close()
python/Lib/site-packages/setuptools/command/setopt.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import configparser
2
+ import os
3
+
4
+ from .. import Command
5
+ from ..unicode_utils import _cfg_read_utf8_with_fallback
6
+
7
+ import distutils
8
+ from distutils import log
9
+ from distutils.errors import DistutilsOptionError
10
+ from distutils.util import convert_path
11
+
12
+ __all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
13
+
14
+
15
+ def config_file(kind="local"):
16
+ """Get the filename of the distutils, local, global, or per-user config
17
+
18
+ `kind` must be one of "local", "global", or "user"
19
+ """
20
+ if kind == 'local':
21
+ return 'setup.cfg'
22
+ if kind == 'global':
23
+ return os.path.join(os.path.dirname(distutils.__file__), 'distutils.cfg')
24
+ if kind == 'user':
25
+ dot = os.name == 'posix' and '.' or ''
26
+ return os.path.expanduser(convert_path(f"~/{dot}pydistutils.cfg"))
27
+ raise ValueError("config_file() type must be 'local', 'global', or 'user'", kind)
28
+
29
+
30
+ def edit_config(filename, settings) -> None:
31
+ """Edit a configuration file to include `settings`
32
+
33
+ `settings` is a dictionary of dictionaries or ``None`` values, keyed by
34
+ command/section name. A ``None`` value means to delete the entire section,
35
+ while a dictionary lists settings to be changed or deleted in that section.
36
+ A setting of ``None`` means to delete that setting.
37
+ """
38
+ log.debug("Reading configuration from %s", filename)
39
+ opts = configparser.RawConfigParser()
40
+ opts.optionxform = lambda optionstr: optionstr # type: ignore[method-assign] # overriding method
41
+ _cfg_read_utf8_with_fallback(opts, filename)
42
+
43
+ for section, options in settings.items():
44
+ if options is None:
45
+ log.info("Deleting section [%s] from %s", section, filename)
46
+ opts.remove_section(section)
47
+ else:
48
+ if not opts.has_section(section):
49
+ log.debug("Adding new section [%s] to %s", section, filename)
50
+ opts.add_section(section)
51
+ for option, value in options.items():
52
+ if value is None:
53
+ log.debug("Deleting %s.%s from %s", section, option, filename)
54
+ opts.remove_option(section, option)
55
+ if not opts.options(section):
56
+ log.info(
57
+ "Deleting empty [%s] section from %s", section, filename
58
+ )
59
+ opts.remove_section(section)
60
+ else:
61
+ log.debug(
62
+ "Setting %s.%s to %r in %s", section, option, value, filename
63
+ )
64
+ opts.set(section, option, value)
65
+
66
+ log.info("Writing %s", filename)
67
+ with open(filename, 'w', encoding="utf-8") as f:
68
+ opts.write(f)
69
+
70
+
71
+ class option_base(Command):
72
+ """Abstract base class for commands that mess with config files"""
73
+
74
+ user_options = [
75
+ ('global-config', 'g', "save options to the site-wide distutils.cfg file"),
76
+ ('user-config', 'u', "save options to the current user's pydistutils.cfg file"),
77
+ ('filename=', 'f', "configuration file to use (default=setup.cfg)"),
78
+ ]
79
+
80
+ boolean_options = [
81
+ 'global-config',
82
+ 'user-config',
83
+ ]
84
+
85
+ def initialize_options(self):
86
+ self.global_config = None
87
+ self.user_config = None
88
+ self.filename = None
89
+
90
+ def finalize_options(self) -> None:
91
+ filenames = []
92
+ if self.global_config:
93
+ filenames.append(config_file('global'))
94
+ if self.user_config:
95
+ filenames.append(config_file('user'))
96
+ if self.filename is not None:
97
+ filenames.append(self.filename)
98
+ if not filenames:
99
+ filenames.append(config_file('local'))
100
+ if len(filenames) > 1:
101
+ raise DistutilsOptionError(
102
+ "Must specify only one configuration file option", filenames
103
+ )
104
+ (self.filename,) = filenames
105
+
106
+
107
+ class setopt(option_base):
108
+ """Save command-line options to a file"""
109
+
110
+ description = "set an option in setup.cfg or another config file"
111
+
112
+ user_options = [
113
+ ('command=', 'c', 'command to set an option for'),
114
+ ('option=', 'o', 'option to set'),
115
+ ('set-value=', 's', 'value of the option'),
116
+ ('remove', 'r', 'remove (unset) the value'),
117
+ ] + option_base.user_options
118
+
119
+ boolean_options = option_base.boolean_options + ['remove']
120
+
121
+ def initialize_options(self):
122
+ option_base.initialize_options(self)
123
+ self.command = None
124
+ self.option = None
125
+ self.set_value = None
126
+ self.remove = None
127
+
128
+ def finalize_options(self) -> None:
129
+ option_base.finalize_options(self)
130
+ if self.command is None or self.option is None:
131
+ raise DistutilsOptionError("Must specify --command *and* --option")
132
+ if self.set_value is None and not self.remove:
133
+ raise DistutilsOptionError("Must specify --set-value or --remove")
134
+
135
+ def run(self) -> None:
136
+ edit_config(
137
+ self.filename,
138
+ {self.command: {self.option.replace('-', '_'): self.set_value}},
139
+ )
python/Lib/site-packages/setuptools/command/test.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import NoReturn
4
+
5
+ from setuptools import Command
6
+ from setuptools.warnings import SetuptoolsDeprecationWarning
7
+
8
+
9
+ # Would restrict to Literal["test"], but mypy doesn't support it: https://github.com/python/mypy/issues/8203
10
+ def __getattr__(name: str) -> type[_test]:
11
+ if name == 'test':
12
+ SetuptoolsDeprecationWarning.emit(
13
+ "The test command is disabled and references to it are deprecated.",
14
+ "Please remove any references to `setuptools.command.test` in all "
15
+ "supported versions of the affected package.",
16
+ due_date=(2024, 11, 15),
17
+ stacklevel=2,
18
+ )
19
+ return _test
20
+ raise AttributeError(name)
21
+
22
+
23
+ class _test(Command):
24
+ """
25
+ Stub to warn when test command is referenced or used.
26
+ """
27
+
28
+ description = "stub for old test command (do not use)"
29
+
30
+ user_options = [
31
+ ('test-module=', 'm', "Run 'test_suite' in specified module"),
32
+ (
33
+ 'test-suite=',
34
+ 's',
35
+ "Run single test, case or suite (e.g. 'module.test_suite')",
36
+ ),
37
+ ('test-runner=', 'r', "Test runner to use"),
38
+ ]
39
+
40
+ def initialize_options(self) -> None:
41
+ pass
42
+
43
+ def finalize_options(self) -> None:
44
+ pass
45
+
46
+ def run(self) -> NoReturn:
47
+ raise RuntimeError("Support for the test command was removed in Setuptools 72")
python/Lib/site-packages/setuptools/compat/__init__.py ADDED
File without changes
python/Lib/site-packages/setuptools/compat/py310.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ __all__ = ['tomllib']
4
+
5
+
6
+ if sys.version_info >= (3, 11):
7
+ import tomllib
8
+ else: # pragma: no cover
9
+ import tomli as tomllib
10
+
11
+
12
+ if sys.version_info >= (3, 11):
13
+
14
+ def add_note(ex, note):
15
+ ex.add_note(note)
16
+
17
+ else: # pragma: no cover
18
+
19
+ def add_note(ex, note):
20
+ vars(ex).setdefault('__notes__', []).append(note)
python/Lib/site-packages/setuptools/compat/py311.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import sys
5
+ from typing import TYPE_CHECKING, Any, Callable
6
+
7
+ if TYPE_CHECKING:
8
+ from _typeshed import ExcInfo, StrOrBytesPath
9
+ from typing_extensions import TypeAlias
10
+
11
+ # Same as shutil._OnExcCallback from typeshed
12
+ _OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]
13
+
14
+
15
+ def shutil_rmtree(
16
+ path: StrOrBytesPath,
17
+ ignore_errors: bool = False,
18
+ onexc: _OnExcCallback | None = None,
19
+ ) -> None:
20
+ if sys.version_info >= (3, 12):
21
+ return shutil.rmtree(path, ignore_errors, onexc=onexc)
22
+
23
+ def _handler(fn: Callable[..., Any], path: str, excinfo: ExcInfo) -> None:
24
+ if onexc:
25
+ onexc(fn, path, excinfo[1])
26
+
27
+ return shutil.rmtree(path, ignore_errors, onerror=_handler)
python/Lib/site-packages/setuptools/compat/py312.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ if sys.version_info >= (3, 12, 4):
6
+ # Python 3.13 should support `.pth` files encoded in UTF-8
7
+ # See discussion in https://github.com/python/cpython/issues/77102
8
+ PTH_ENCODING: str | None = "utf-8"
9
+ else:
10
+ from .py39 import LOCALE_ENCODING
11
+
12
+ # PTH_ENCODING = "locale"
13
+ PTH_ENCODING = LOCALE_ENCODING
python/Lib/site-packages/setuptools/compat/py39.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ # Explicitly use the ``"locale"`` encoding in versions that support it,
4
+ # otherwise just rely on the implicit handling of ``encoding=None``.
5
+ # Since all platforms that support ``EncodingWarning`` also support
6
+ # ``encoding="locale"``, this can be used to suppress the warning.
7
+ # However, please try to use UTF-8 when possible
8
+ # (.pth files are the notorious exception: python/cpython#77102, pypa/setuptools#3937).
9
+ LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
python/Lib/site-packages/setuptools/config/NOTICE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ The following files include code from opensource projects
2
+ (either as direct copies or modified versions):
3
+
4
+ - `setuptools.schema.json`, `distutils.schema.json`:
5
+ - project: `validate-pyproject` - licensed under MPL-2.0
6
+ (https://github.com/abravalheri/validate-pyproject):
7
+
8
+ This Source Code Form is subject to the terms of the Mozilla Public
9
+ License, v. 2.0. If a copy of the MPL was not distributed with this file,
10
+ You can obtain one at https://mozilla.org/MPL/2.0/.
python/Lib/site-packages/setuptools/config/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """For backward compatibility, expose main functions from
2
+ ``setuptools.config.setupcfg``
3
+ """
4
+
5
+ from functools import wraps
6
+ from typing import Callable, TypeVar, cast
7
+
8
+ from ..warnings import SetuptoolsDeprecationWarning
9
+ from . import setupcfg
10
+
11
+ Fn = TypeVar("Fn", bound=Callable)
12
+
13
+ __all__ = ('parse_configuration', 'read_configuration')
14
+
15
+
16
+ def _deprecation_notice(fn: Fn) -> Fn:
17
+ @wraps(fn)
18
+ def _wrapper(*args, **kwargs):
19
+ SetuptoolsDeprecationWarning.emit(
20
+ "Deprecated API usage.",
21
+ f"""
22
+ As setuptools moves its configuration towards `pyproject.toml`,
23
+ `{__name__}.{fn.__name__}` became deprecated.
24
+
25
+ For the time being, you can use the `{setupcfg.__name__}` module
26
+ to access a backward compatible API, but this module is provisional
27
+ and might be removed in the future.
28
+
29
+ To read project metadata, consider using
30
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
31
+ For simple scenarios, you can also try parsing the file directly
32
+ with the help of ``configparser``.
33
+ """,
34
+ # due_date not defined yet, because the community still heavily relies on it
35
+ # Warning introduced in 24 Mar 2022
36
+ )
37
+ return fn(*args, **kwargs)
38
+
39
+ return cast(Fn, _wrapper)
40
+
41
+
42
+ read_configuration = _deprecation_notice(setupcfg.read_configuration)
43
+ parse_configuration = _deprecation_notice(setupcfg.parse_configuration)
python/Lib/site-packages/setuptools/config/_apply_pyprojecttoml.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Translation layer between pyproject config and setuptools distribution and
2
+ metadata objects.
3
+
4
+ The distribution and metadata objects are modeled after (an old version of)
5
+ core metadata, therefore configs in the format specified for ``pyproject.toml``
6
+ need to be processed before being applied.
7
+
8
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ from collections.abc import Mapping
16
+ from email.headerregistry import Address
17
+ from functools import partial, reduce
18
+ from inspect import cleandoc
19
+ from itertools import chain
20
+ from types import MappingProxyType
21
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
22
+
23
+ from .. import _static
24
+ from .._path import StrPath
25
+ from ..errors import InvalidConfigError, RemovedConfigError
26
+ from ..extension import Extension
27
+ from ..warnings import SetuptoolsDeprecationWarning, SetuptoolsWarning
28
+
29
+ if TYPE_CHECKING:
30
+ from typing_extensions import TypeAlias
31
+
32
+ from setuptools._importlib import metadata
33
+ from setuptools.dist import Distribution
34
+
35
+ from distutils.dist import _OptionsList # Comes from typeshed
36
+
37
+
38
+ EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
39
+ _ProjectReadmeValue: TypeAlias = Union[str, dict[str, str]]
40
+ _Correspondence: TypeAlias = Callable[["Distribution", Any, Union[StrPath, None]], None]
41
+ _T = TypeVar("_T")
42
+
43
+ _logger = logging.getLogger(__name__)
44
+
45
+
46
+ def apply(dist: Distribution, config: dict, filename: StrPath) -> Distribution:
47
+ """Apply configuration dict read with :func:`read_configuration`"""
48
+
49
+ if not config:
50
+ return dist # short-circuit unrelated pyproject.toml file
51
+
52
+ root_dir = os.path.dirname(filename) or "."
53
+
54
+ _apply_project_table(dist, config, root_dir)
55
+ _apply_tool_table(dist, config, filename)
56
+
57
+ current_directory = os.getcwd()
58
+ os.chdir(root_dir)
59
+ try:
60
+ dist._finalize_requires()
61
+ dist._finalize_license_expression()
62
+ dist._finalize_license_files()
63
+ finally:
64
+ os.chdir(current_directory)
65
+
66
+ return dist
67
+
68
+
69
+ def _apply_project_table(dist: Distribution, config: dict, root_dir: StrPath):
70
+ orig_config = config.get("project", {})
71
+ if not orig_config:
72
+ return # short-circuit
73
+
74
+ project_table = {k: _static.attempt_conversion(v) for k, v in orig_config.items()}
75
+ _handle_missing_dynamic(dist, project_table)
76
+ _unify_entry_points(project_table)
77
+
78
+ for field, value in project_table.items():
79
+ norm_key = json_compatible_key(field)
80
+ corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)
81
+ if callable(corresp):
82
+ corresp(dist, value, root_dir)
83
+ else:
84
+ _set_config(dist, corresp, value)
85
+
86
+
87
+ def _apply_tool_table(dist: Distribution, config: dict, filename: StrPath):
88
+ tool_table = config.get("tool", {}).get("setuptools", {})
89
+ if not tool_table:
90
+ return # short-circuit
91
+
92
+ if "license-files" in tool_table:
93
+ if "license-files" in config.get("project", {}):
94
+ # https://github.com/pypa/setuptools/pull/4837#discussion_r2004983349
95
+ raise InvalidConfigError(
96
+ "'project.license-files' is defined already. "
97
+ "Remove 'tool.setuptools.license-files'."
98
+ )
99
+
100
+ pypa_guides = "guides/writing-pyproject-toml/#license-files"
101
+ SetuptoolsDeprecationWarning.emit(
102
+ "'tool.setuptools.license-files' is deprecated in favor of "
103
+ "'project.license-files' (available on setuptools>=77.0.0).",
104
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
105
+ due_date=(2027, 2, 18), # Warning introduced on 2025-02-18
106
+ )
107
+
108
+ for field, value in tool_table.items():
109
+ norm_key = json_compatible_key(field)
110
+
111
+ if norm_key in TOOL_TABLE_REMOVALS:
112
+ suggestion = cleandoc(TOOL_TABLE_REMOVALS[norm_key])
113
+ msg = f"""
114
+ The parameter `tool.setuptools.{field}` was long deprecated
115
+ and has been removed from `pyproject.toml`.
116
+ """
117
+ raise RemovedConfigError("\n".join([cleandoc(msg), suggestion]))
118
+
119
+ norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)
120
+ corresp = TOOL_TABLE_CORRESPONDENCE.get(norm_key, norm_key)
121
+ if callable(corresp):
122
+ corresp(dist, value)
123
+ else:
124
+ _set_config(dist, corresp, value)
125
+
126
+ _copy_command_options(config, dist, filename)
127
+
128
+
129
+ def _handle_missing_dynamic(dist: Distribution, project_table: dict):
130
+ """Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``"""
131
+ dynamic = set(project_table.get("dynamic", []))
132
+ for field, getter in _PREVIOUSLY_DEFINED.items():
133
+ if not (field in project_table or field in dynamic):
134
+ value = getter(dist)
135
+ if value:
136
+ _MissingDynamic.emit(field=field, value=value)
137
+ project_table[field] = _RESET_PREVIOUSLY_DEFINED.get(field)
138
+
139
+
140
+ def json_compatible_key(key: str) -> str:
141
+ """As defined in :pep:`566#json-compatible-metadata`"""
142
+ return key.lower().replace("-", "_")
143
+
144
+
145
+ def _set_config(dist: Distribution, field: str, value: Any):
146
+ val = _PREPROCESS.get(field, _noop)(dist, value)
147
+ setter = getattr(dist.metadata, f"set_{field}", None)
148
+ if setter:
149
+ setter(val)
150
+ elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:
151
+ setattr(dist.metadata, field, val)
152
+ else:
153
+ setattr(dist, field, val)
154
+
155
+
156
+ _CONTENT_TYPES = {
157
+ ".md": "text/markdown",
158
+ ".rst": "text/x-rst",
159
+ ".txt": "text/plain",
160
+ }
161
+
162
+
163
+ def _guess_content_type(file: str) -> str | None:
164
+ _, ext = os.path.splitext(file.lower())
165
+ if not ext:
166
+ return None
167
+
168
+ if ext in _CONTENT_TYPES:
169
+ return _static.Str(_CONTENT_TYPES[ext])
170
+
171
+ valid = ", ".join(f"{k} ({v})" for k, v in _CONTENT_TYPES.items())
172
+ msg = f"only the following file extensions are recognized: {valid}."
173
+ raise ValueError(f"Undefined content type for {file}, {msg}")
174
+
175
+
176
+ def _long_description(
177
+ dist: Distribution, val: _ProjectReadmeValue, root_dir: StrPath | None
178
+ ):
179
+ from setuptools.config import expand
180
+
181
+ file: str | tuple[()]
182
+ if isinstance(val, str):
183
+ file = val
184
+ text = expand.read_files(file, root_dir)
185
+ ctype = _guess_content_type(file)
186
+ else:
187
+ file = val.get("file") or ()
188
+ text = val.get("text") or expand.read_files(file, root_dir)
189
+ ctype = val["content-type"]
190
+
191
+ # XXX: Is it completely safe to assume static?
192
+ _set_config(dist, "long_description", _static.Str(text))
193
+
194
+ if ctype:
195
+ _set_config(dist, "long_description_content_type", _static.Str(ctype))
196
+
197
+ if file:
198
+ dist._referenced_files.add(file)
199
+
200
+
201
+ def _license(dist: Distribution, val: str | dict, root_dir: StrPath | None):
202
+ from setuptools.config import expand
203
+
204
+ if isinstance(val, str):
205
+ if getattr(dist.metadata, "license", None):
206
+ SetuptoolsWarning.emit("`license` overwritten by `pyproject.toml`")
207
+ dist.metadata.license = None
208
+ _set_config(dist, "license_expression", _static.Str(val))
209
+ else:
210
+ pypa_guides = "guides/writing-pyproject-toml/#license"
211
+ SetuptoolsDeprecationWarning.emit(
212
+ "`project.license` as a TOML table is deprecated",
213
+ "Please use a simple string containing a SPDX expression for "
214
+ "`project.license`. You can also use `project.license-files`. "
215
+ "(Both options available on setuptools>=77.0.0).",
216
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
217
+ due_date=(2027, 2, 18), # Introduced on 2025-02-18
218
+ )
219
+ if "file" in val:
220
+ # XXX: Is it completely safe to assume static?
221
+ value = expand.read_files([val["file"]], root_dir)
222
+ _set_config(dist, "license", _static.Str(value))
223
+ dist._referenced_files.add(val["file"])
224
+ else:
225
+ _set_config(dist, "license", _static.Str(val["text"]))
226
+
227
+
228
+ def _people(dist: Distribution, val: list[dict], _root_dir: StrPath | None, kind: str):
229
+ field = []
230
+ email_field = []
231
+ for person in val:
232
+ if "name" not in person:
233
+ email_field.append(person["email"])
234
+ elif "email" not in person:
235
+ field.append(person["name"])
236
+ else:
237
+ addr = Address(display_name=person["name"], addr_spec=person["email"])
238
+ email_field.append(str(addr))
239
+
240
+ if field:
241
+ _set_config(dist, kind, _static.Str(", ".join(field)))
242
+ if email_field:
243
+ _set_config(dist, f"{kind}_email", _static.Str(", ".join(email_field)))
244
+
245
+
246
+ def _project_urls(dist: Distribution, val: dict, _root_dir: StrPath | None):
247
+ _set_config(dist, "project_urls", val)
248
+
249
+
250
+ def _python_requires(dist: Distribution, val: str, _root_dir: StrPath | None):
251
+ _set_config(dist, "python_requires", _static.SpecifierSet(val))
252
+
253
+
254
+ def _dependencies(dist: Distribution, val: list, _root_dir: StrPath | None):
255
+ if getattr(dist, "install_requires", []):
256
+ msg = "`install_requires` overwritten in `pyproject.toml` (dependencies)"
257
+ SetuptoolsWarning.emit(msg)
258
+ dist.install_requires = val
259
+
260
+
261
+ def _optional_dependencies(dist: Distribution, val: dict, _root_dir: StrPath | None):
262
+ if getattr(dist, "extras_require", None):
263
+ msg = "`extras_require` overwritten in `pyproject.toml` (optional-dependencies)"
264
+ SetuptoolsWarning.emit(msg)
265
+ dist.extras_require = val
266
+
267
+
268
+ def _ext_modules(dist: Distribution, val: list[dict]) -> list[Extension]:
269
+ existing = dist.ext_modules or []
270
+ args = ({k.replace("-", "_"): v for k, v in x.items()} for x in val)
271
+ new = (Extension(**_adjust_ext_attrs(kw)) for kw in args)
272
+ return [*existing, *new]
273
+
274
+
275
+ def _adjust_ext_attrs(attrs: dict) -> dict:
276
+ # https://github.com/pypa/setuptools/issues/4810
277
+ # In TOML there is no differentiation between tuples and lists,
278
+ # and distutils requires tuples...
279
+ attrs["define_macros"] = list(map(tuple, attrs.get("define_macros") or []))
280
+ return attrs
281
+
282
+
283
+ def _noop(_dist: Distribution, val: _T) -> _T:
284
+ return val
285
+
286
+
287
+ def _identity(val: _T) -> _T:
288
+ return val
289
+
290
+
291
+ def _unify_entry_points(project_table: dict):
292
+ project = project_table
293
+ given = project.pop("entry-points", project.pop("entry_points", {}))
294
+ entry_points = dict(given) # Avoid problems with static
295
+ renaming = {"scripts": "console_scripts", "gui_scripts": "gui_scripts"}
296
+ for key, value in list(project.items()): # eager to allow modifications
297
+ norm_key = json_compatible_key(key)
298
+ if norm_key in renaming:
299
+ # Don't skip even if value is empty (reason: reset missing `dynamic`)
300
+ entry_points[renaming[norm_key]] = project.pop(key)
301
+
302
+ if entry_points:
303
+ project["entry-points"] = {
304
+ name: [f"{k} = {v}" for k, v in group.items()]
305
+ for name, group in entry_points.items()
306
+ if group # now we can skip empty groups
307
+ }
308
+ # Sometimes this will set `project["entry-points"] = {}`, and that is
309
+ # intentional (for resetting configurations that are missing `dynamic`).
310
+
311
+
312
+ def _copy_command_options(pyproject: dict, dist: Distribution, filename: StrPath):
313
+ tool_table = pyproject.get("tool", {})
314
+ cmdclass = tool_table.get("setuptools", {}).get("cmdclass", {})
315
+ valid_options = _valid_command_options(cmdclass)
316
+
317
+ cmd_opts = dist.command_options
318
+ for cmd, config in pyproject.get("tool", {}).get("distutils", {}).items():
319
+ cmd = json_compatible_key(cmd)
320
+ valid = valid_options.get(cmd, set())
321
+ cmd_opts.setdefault(cmd, {})
322
+ for key, value in config.items():
323
+ key = json_compatible_key(key)
324
+ cmd_opts[cmd][key] = (str(filename), value)
325
+ if key not in valid:
326
+ # To avoid removing options that are specified dynamically we
327
+ # just log a warn...
328
+ _logger.warning(f"Command option {cmd}.{key} is not defined")
329
+
330
+
331
+ def _valid_command_options(cmdclass: Mapping = EMPTY) -> dict[str, set[str]]:
332
+ from setuptools.dist import Distribution
333
+
334
+ from .._importlib import metadata
335
+
336
+ valid_options = {"global": _normalise_cmd_options(Distribution.global_options)}
337
+
338
+ unloaded_entry_points = metadata.entry_points(group='distutils.commands')
339
+ loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)
340
+ entry_points = (ep for ep in loaded_entry_points if ep)
341
+ for cmd, cmd_class in chain(entry_points, cmdclass.items()):
342
+ opts = valid_options.get(cmd, set())
343
+ opts = opts | _normalise_cmd_options(getattr(cmd_class, "user_options", []))
344
+ valid_options[cmd] = opts
345
+
346
+ return valid_options
347
+
348
+
349
+ def _load_ep(ep: metadata.EntryPoint) -> tuple[str, type] | None:
350
+ if ep.value.startswith("wheel.bdist_wheel"):
351
+ # Ignore deprecated entrypoint from wheel and avoid warning pypa/wheel#631
352
+ # TODO: remove check when `bdist_wheel` has been fully removed from pypa/wheel
353
+ return None
354
+
355
+ # Ignore all the errors
356
+ try:
357
+ return (ep.name, ep.load())
358
+ except Exception as ex:
359
+ msg = f"{ex.__class__.__name__} while trying to load entry-point {ep.name}"
360
+ _logger.warning(f"{msg}: {ex}")
361
+ return None
362
+
363
+
364
+ def _normalise_cmd_option_key(name: str) -> str:
365
+ return json_compatible_key(name).strip("_=")
366
+
367
+
368
+ def _normalise_cmd_options(desc: _OptionsList) -> set[str]:
369
+ return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}
370
+
371
+
372
+ def _get_previous_entrypoints(dist: Distribution) -> dict[str, list]:
373
+ ignore = ("console_scripts", "gui_scripts")
374
+ value = getattr(dist, "entry_points", None) or {}
375
+ return {k: v for k, v in value.items() if k not in ignore}
376
+
377
+
378
+ def _get_previous_scripts(dist: Distribution) -> list | None:
379
+ value = getattr(dist, "entry_points", None) or {}
380
+ return value.get("console_scripts")
381
+
382
+
383
+ def _get_previous_gui_scripts(dist: Distribution) -> list | None:
384
+ value = getattr(dist, "entry_points", None) or {}
385
+ return value.get("gui_scripts")
386
+
387
+
388
+ def _set_static_list_metadata(attr: str, dist: Distribution, val: list) -> None:
389
+ """Apply distutils metadata validation but preserve "static" behaviour"""
390
+ meta = dist.metadata
391
+ setter, getter = getattr(meta, f"set_{attr}"), getattr(meta, f"get_{attr}")
392
+ setter(val)
393
+ setattr(meta, attr, _static.List(getter()))
394
+
395
+
396
+ def _attrgetter(attr):
397
+ """
398
+ Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found
399
+ >>> from types import SimpleNamespace
400
+ >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
401
+ >>> _attrgetter("a")(obj)
402
+ 42
403
+ >>> _attrgetter("b.c")(obj)
404
+ 13
405
+ >>> _attrgetter("d")(obj) is None
406
+ True
407
+ """
408
+ return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split("."))
409
+
410
+
411
+ def _some_attrgetter(*items):
412
+ """
413
+ Return the first "truth-y" attribute or None
414
+ >>> from types import SimpleNamespace
415
+ >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))
416
+ >>> _some_attrgetter("d", "a", "b.c")(obj)
417
+ 42
418
+ >>> _some_attrgetter("d", "e", "b.c", "a")(obj)
419
+ 13
420
+ >>> _some_attrgetter("d", "e", "f")(obj) is None
421
+ True
422
+ """
423
+
424
+ def _acessor(obj):
425
+ values = (_attrgetter(i)(obj) for i in items)
426
+ return next((i for i in values if i is not None), None)
427
+
428
+ return _acessor
429
+
430
+
431
+ PYPROJECT_CORRESPONDENCE: dict[str, _Correspondence] = {
432
+ "readme": _long_description,
433
+ "license": _license,
434
+ "authors": partial(_people, kind="author"),
435
+ "maintainers": partial(_people, kind="maintainer"),
436
+ "urls": _project_urls,
437
+ "dependencies": _dependencies,
438
+ "optional_dependencies": _optional_dependencies,
439
+ "requires_python": _python_requires,
440
+ }
441
+
442
+ TOOL_TABLE_RENAMES = {"script_files": "scripts"}
443
+ TOOL_TABLE_REMOVALS = {
444
+ "namespace_packages": """
445
+ Please migrate to implicit native namespaces instead.
446
+ See https://packaging.python.org/en/latest/guides/packaging-namespace-packages/.
447
+ """,
448
+ }
449
+ TOOL_TABLE_CORRESPONDENCE = {
450
+ # Fields with corresponding core metadata need to be marked as static:
451
+ "obsoletes": partial(_set_static_list_metadata, "obsoletes"),
452
+ "provides": partial(_set_static_list_metadata, "provides"),
453
+ "platforms": partial(_set_static_list_metadata, "platforms"),
454
+ }
455
+
456
+ SETUPTOOLS_PATCHES = {
457
+ "long_description_content_type",
458
+ "project_urls",
459
+ "provides_extras",
460
+ "license_file",
461
+ "license_files",
462
+ "license_expression",
463
+ }
464
+
465
+ _PREPROCESS = {
466
+ "ext_modules": _ext_modules,
467
+ }
468
+
469
+ _PREVIOUSLY_DEFINED = {
470
+ "name": _attrgetter("metadata.name"),
471
+ "version": _attrgetter("metadata.version"),
472
+ "description": _attrgetter("metadata.description"),
473
+ "readme": _attrgetter("metadata.long_description"),
474
+ "requires-python": _some_attrgetter("python_requires", "metadata.python_requires"),
475
+ "license": _some_attrgetter("metadata.license_expression", "metadata.license"),
476
+ # XXX: `license-file` is currently not considered in the context of `dynamic`.
477
+ # See TestPresetField.test_license_files_exempt_from_dynamic
478
+ "authors": _some_attrgetter("metadata.author", "metadata.author_email"),
479
+ "maintainers": _some_attrgetter("metadata.maintainer", "metadata.maintainer_email"),
480
+ "keywords": _attrgetter("metadata.keywords"),
481
+ "classifiers": _attrgetter("metadata.classifiers"),
482
+ "urls": _attrgetter("metadata.project_urls"),
483
+ "entry-points": _get_previous_entrypoints,
484
+ "scripts": _get_previous_scripts,
485
+ "gui-scripts": _get_previous_gui_scripts,
486
+ "dependencies": _attrgetter("install_requires"),
487
+ "optional-dependencies": _attrgetter("extras_require"),
488
+ }
489
+
490
+
491
+ _RESET_PREVIOUSLY_DEFINED: dict = {
492
+ # Fix improper setting: given in `setup.py`, but not listed in `dynamic`
493
+ # Use "immutable" data structures to avoid in-place modification.
494
+ # dict: pyproject name => value to which reset
495
+ "license": "",
496
+ # XXX: `license-file` is currently not considered in the context of `dynamic`.
497
+ # See TestPresetField.test_license_files_exempt_from_dynamic
498
+ "authors": _static.EMPTY_LIST,
499
+ "maintainers": _static.EMPTY_LIST,
500
+ "keywords": _static.EMPTY_LIST,
501
+ "classifiers": _static.EMPTY_LIST,
502
+ "urls": _static.EMPTY_DICT,
503
+ "entry-points": _static.EMPTY_DICT,
504
+ "scripts": _static.EMPTY_DICT,
505
+ "gui-scripts": _static.EMPTY_DICT,
506
+ "dependencies": _static.EMPTY_LIST,
507
+ "optional-dependencies": _static.EMPTY_DICT,
508
+ }
509
+
510
+
511
+ class _MissingDynamic(SetuptoolsWarning):
512
+ _SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
513
+
514
+ _DETAILS = """
515
+ The following seems to be defined outside of `pyproject.toml`:
516
+
517
+ `{field} = {value!r}`
518
+
519
+ According to the spec (see the link below), however, setuptools CANNOT
520
+ consider this value unless `{field}` is listed as `dynamic`.
521
+
522
+ https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
523
+
524
+ To prevent this problem, you can list `{field}` under `dynamic` or alternatively
525
+ remove the `[project]` table from your file and rely entirely on other means of
526
+ configuration.
527
+ """
528
+ # TODO: Consider removing this check in the future?
529
+ # There is a trade-off here between improving "debug-ability" and the cost
530
+ # of running/testing/maintaining these unnecessary checks...
531
+
532
+ @classmethod
533
+ def details(cls, field: str, value: Any) -> str:
534
+ return cls._DETAILS.format(field=field, value=value)
python/Lib/site-packages/setuptools/config/distutils.schema.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+
4
+ "$id": "https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html",
5
+ "title": "``tool.distutils`` table",
6
+ "$$description": [
7
+ "**EXPERIMENTAL** (NOT OFFICIALLY SUPPORTED): Use ``tool.distutils``",
8
+ "subtables to configure arguments for ``distutils`` commands.",
9
+ "Originally, ``distutils`` allowed developers to configure arguments for",
10
+ "``setup.py`` commands via `distutils configuration files",
11
+ "<https://setuptools.pypa.io/en/latest/deprecated/distutils/configfile.html>`_.",
12
+ "See also `the old Python docs <https://docs.python.org/3.11/install/>_`."
13
+ ],
14
+
15
+ "type": "object",
16
+ "properties": {
17
+ "global": {
18
+ "type": "object",
19
+ "description": "Global options applied to all ``distutils`` commands"
20
+ }
21
+ },
22
+ "patternProperties": {
23
+ ".+": {"type": "object"}
24
+ },
25
+ "$comment": "TODO: Is there a practical way of making this schema more specific?"
26
+ }
python/Lib/site-packages/setuptools/config/expand.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions to expand configuration directives or special values
2
+ (such glob patterns).
3
+
4
+ We can split the process of interpreting configuration files into 2 steps:
5
+
6
+ 1. The parsing the file contents from strings to value objects
7
+ that can be understand by Python (for example a string with a comma
8
+ separated list of keywords into an actual Python list of strings).
9
+
10
+ 2. The expansion (or post-processing) of these values according to the
11
+ semantics ``setuptools`` assign to them (for example a configuration field
12
+ with the ``file:`` directive should be expanded from a list of file paths to
13
+ a single string with the contents of those files concatenated)
14
+
15
+ This module focus on the second step, and therefore allow sharing the expansion
16
+ functions among several configuration file formats.
17
+
18
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import ast
24
+ import importlib
25
+ import os
26
+ import pathlib
27
+ import sys
28
+ from collections.abc import Iterable, Iterator, Mapping
29
+ from configparser import ConfigParser
30
+ from glob import iglob
31
+ from importlib.machinery import ModuleSpec, all_suffixes
32
+ from itertools import chain
33
+ from pathlib import Path
34
+ from types import ModuleType, TracebackType
35
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar
36
+
37
+ from .. import _static
38
+ from .._path import StrPath, same_path as _same_path
39
+ from ..discovery import find_package_path
40
+ from ..warnings import SetuptoolsWarning
41
+
42
+ from distutils.errors import DistutilsOptionError
43
+
44
+ if TYPE_CHECKING:
45
+ from typing_extensions import Self
46
+
47
+ from setuptools.dist import Distribution
48
+
49
+ _K = TypeVar("_K")
50
+ _V_co = TypeVar("_V_co", covariant=True)
51
+
52
+
53
+ class StaticModule:
54
+ """Proxy to a module object that avoids executing arbitrary code."""
55
+
56
+ def __init__(self, name: str, spec: ModuleSpec) -> None:
57
+ module = ast.parse(pathlib.Path(spec.origin).read_bytes()) # type: ignore[arg-type] # Let it raise an error on None
58
+ vars(self).update(locals())
59
+ del self.self
60
+
61
+ def _find_assignments(self) -> Iterator[tuple[ast.AST, ast.AST]]:
62
+ for statement in self.module.body:
63
+ if isinstance(statement, ast.Assign):
64
+ yield from ((target, statement.value) for target in statement.targets)
65
+ elif isinstance(statement, ast.AnnAssign) and statement.value:
66
+ yield (statement.target, statement.value)
67
+
68
+ def __getattr__(self, attr: str) -> Any:
69
+ """Attempt to load an attribute "statically", via :func:`ast.literal_eval`."""
70
+ try:
71
+ return next(
72
+ ast.literal_eval(value)
73
+ for target, value in self._find_assignments()
74
+ if isinstance(target, ast.Name) and target.id == attr
75
+ )
76
+ except Exception as e:
77
+ raise AttributeError(f"{self.name} has no attribute {attr}") from e
78
+
79
+
80
+ def glob_relative(
81
+ patterns: Iterable[str], root_dir: StrPath | None = None
82
+ ) -> list[str]:
83
+ """Expand the list of glob patterns, but preserving relative paths.
84
+
85
+ :param list[str] patterns: List of glob patterns
86
+ :param str root_dir: Path to which globs should be relative
87
+ (current directory by default)
88
+ :rtype: list
89
+ """
90
+ glob_characters = {'*', '?', '[', ']', '{', '}'}
91
+ expanded_values = []
92
+ root_dir = root_dir or os.getcwd()
93
+ for value in patterns:
94
+ # Has globby characters?
95
+ if any(char in value for char in glob_characters):
96
+ # then expand the glob pattern while keeping paths *relative*:
97
+ glob_path = os.path.abspath(os.path.join(root_dir, value))
98
+ expanded_values.extend(
99
+ sorted(
100
+ os.path.relpath(path, root_dir).replace(os.sep, "/")
101
+ for path in iglob(glob_path, recursive=True)
102
+ )
103
+ )
104
+
105
+ else:
106
+ # take the value as-is
107
+ path = os.path.relpath(value, root_dir).replace(os.sep, "/")
108
+ expanded_values.append(path)
109
+
110
+ return expanded_values
111
+
112
+
113
+ def read_files(
114
+ filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None
115
+ ) -> str:
116
+ """Return the content of the files concatenated using ``\n`` as str
117
+
118
+ This function is sandboxed and won't reach anything outside ``root_dir``
119
+
120
+ (By default ``root_dir`` is the current directory).
121
+ """
122
+ from more_itertools import always_iterable
123
+
124
+ root_dir = os.path.abspath(root_dir or os.getcwd())
125
+ _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))
126
+ return '\n'.join(
127
+ _read_file(path)
128
+ for path in _filter_existing_files(_filepaths)
129
+ if _assert_local(path, root_dir)
130
+ )
131
+
132
+
133
+ def _filter_existing_files(filepaths: Iterable[StrPath]) -> Iterator[StrPath]:
134
+ for path in filepaths:
135
+ if os.path.isfile(path):
136
+ yield path
137
+ else:
138
+ SetuptoolsWarning.emit(f"File {path!r} cannot be found")
139
+
140
+
141
+ def _read_file(filepath: bytes | StrPath) -> str:
142
+ with open(filepath, encoding='utf-8') as f:
143
+ return f.read()
144
+
145
+
146
+ def _assert_local(filepath: StrPath, root_dir: str):
147
+ if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:
148
+ msg = f"Cannot access {filepath!r} (or anything outside {root_dir!r})"
149
+ raise DistutilsOptionError(msg)
150
+
151
+ return True
152
+
153
+
154
+ def read_attr(
155
+ attr_desc: str,
156
+ package_dir: Mapping[str, str] | None = None,
157
+ root_dir: StrPath | None = None,
158
+ ) -> Any:
159
+ """Reads the value of an attribute from a module.
160
+
161
+ This function will try to read the attributed statically first
162
+ (via :func:`ast.literal_eval`), and only evaluate the module if it fails.
163
+
164
+ Examples:
165
+ read_attr("package.attr")
166
+ read_attr("package.module.attr")
167
+
168
+ :param str attr_desc: Dot-separated string describing how to reach the
169
+ attribute (see examples above)
170
+ :param dict[str, str] package_dir: Mapping of package names to their
171
+ location in disk (represented by paths relative to ``root_dir``).
172
+ :param str root_dir: Path to directory containing all the packages in
173
+ ``package_dir`` (current directory by default).
174
+ :rtype: str
175
+ """
176
+ root_dir = root_dir or os.getcwd()
177
+ attrs_path = attr_desc.strip().split('.')
178
+ attr_name = attrs_path.pop()
179
+ module_name = '.'.join(attrs_path)
180
+ module_name = module_name or '__init__'
181
+ path = _find_module(module_name, package_dir, root_dir)
182
+ spec = _find_spec(module_name, path)
183
+
184
+ try:
185
+ value = getattr(StaticModule(module_name, spec), attr_name)
186
+ # XXX: Is marking as static contents coming from modules too optimistic?
187
+ return _static.attempt_conversion(value)
188
+ except Exception:
189
+ # fallback to evaluate module
190
+ module = _load_spec(spec, module_name)
191
+ return getattr(module, attr_name)
192
+
193
+
194
+ def _find_spec(module_name: str, module_path: StrPath | None) -> ModuleSpec:
195
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
196
+ spec = spec or importlib.util.find_spec(module_name)
197
+
198
+ if spec is None:
199
+ raise ModuleNotFoundError(module_name)
200
+
201
+ return spec
202
+
203
+
204
+ def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:
205
+ name = getattr(spec, "__name__", module_name)
206
+ if name in sys.modules:
207
+ return sys.modules[name]
208
+ module = importlib.util.module_from_spec(spec)
209
+ sys.modules[name] = module # cache (it also ensures `==` works on loaded items)
210
+ assert spec.loader is not None
211
+ spec.loader.exec_module(module)
212
+ return module
213
+
214
+
215
+ def _find_module(
216
+ module_name: str, package_dir: Mapping[str, str] | None, root_dir: StrPath
217
+ ) -> str | None:
218
+ """Find the path to the module named ``module_name``,
219
+ considering the ``package_dir`` in the build configuration and ``root_dir``.
220
+
221
+ >>> tmp = getfixture('tmpdir')
222
+ >>> _ = tmp.ensure("a/b/c.py")
223
+ >>> _ = tmp.ensure("a/b/d/__init__.py")
224
+ >>> r = lambda x: x.replace(str(tmp), "tmp").replace(os.sep, "/")
225
+ >>> r(_find_module("a.b.c", None, tmp))
226
+ 'tmp/a/b/c.py'
227
+ >>> r(_find_module("f.g.h", {"": "1", "f": "2", "f.g": "3", "f.g.h": "a/b/d"}, tmp))
228
+ 'tmp/a/b/d/__init__.py'
229
+ """
230
+ path_start = find_package_path(module_name, package_dir or {}, root_dir)
231
+ candidates = chain.from_iterable(
232
+ (f"{path_start}{ext}", os.path.join(path_start, f"__init__{ext}"))
233
+ for ext in all_suffixes()
234
+ )
235
+ return next((x for x in candidates if os.path.isfile(x)), None)
236
+
237
+
238
+ def resolve_class(
239
+ qualified_class_name: str,
240
+ package_dir: Mapping[str, str] | None = None,
241
+ root_dir: StrPath | None = None,
242
+ ) -> Callable:
243
+ """Given a qualified class name, return the associated class object"""
244
+ root_dir = root_dir or os.getcwd()
245
+ idx = qualified_class_name.rfind('.')
246
+ class_name = qualified_class_name[idx + 1 :]
247
+ pkg_name = qualified_class_name[:idx]
248
+
249
+ path = _find_module(pkg_name, package_dir, root_dir)
250
+ module = _load_spec(_find_spec(pkg_name, path), pkg_name)
251
+ return getattr(module, class_name)
252
+
253
+
254
+ def cmdclass(
255
+ values: dict[str, str],
256
+ package_dir: Mapping[str, str] | None = None,
257
+ root_dir: StrPath | None = None,
258
+ ) -> dict[str, Callable]:
259
+ """Given a dictionary mapping command names to strings for qualified class
260
+ names, apply :func:`resolve_class` to the dict values.
261
+ """
262
+ return {k: resolve_class(v, package_dir, root_dir) for k, v in values.items()}
263
+
264
+
265
+ def find_packages(
266
+ *,
267
+ namespaces=True,
268
+ fill_package_dir: dict[str, str] | None = None,
269
+ root_dir: StrPath | None = None,
270
+ **kwargs,
271
+ ) -> list[str]:
272
+ """Works similarly to :func:`setuptools.find_packages`, but with all
273
+ arguments given as keyword arguments. Moreover, ``where`` can be given
274
+ as a list (the results will be simply concatenated).
275
+
276
+ When the additional keyword argument ``namespaces`` is ``True``, it will
277
+ behave like :func:`setuptools.find_namespace_packages`` (i.e. include
278
+ implicit namespaces as per :pep:`420`).
279
+
280
+ The ``where`` argument will be considered relative to ``root_dir`` (or the current
281
+ working directory when ``root_dir`` is not given).
282
+
283
+ If the ``fill_package_dir`` argument is passed, this function will consider it as a
284
+ similar data structure to the ``package_dir`` configuration parameter add fill-in
285
+ any missing package location.
286
+
287
+ :rtype: list
288
+ """
289
+ from more_itertools import always_iterable, unique_everseen
290
+
291
+ from setuptools.discovery import construct_package_dir
292
+
293
+ # check "not namespaces" first due to python/mypy#6232
294
+ if not namespaces:
295
+ from setuptools.discovery import PackageFinder
296
+ else:
297
+ from setuptools.discovery import PEP420PackageFinder as PackageFinder
298
+
299
+ root_dir = root_dir or os.curdir
300
+ where = kwargs.pop('where', ['.'])
301
+ packages: list[str] = []
302
+ fill_package_dir = {} if fill_package_dir is None else fill_package_dir
303
+ search = list(unique_everseen(always_iterable(where)))
304
+
305
+ if len(search) == 1 and all(not _same_path(search[0], x) for x in (".", root_dir)):
306
+ fill_package_dir.setdefault("", search[0])
307
+
308
+ for path in search:
309
+ package_path = _nest_path(root_dir, path)
310
+ pkgs = PackageFinder.find(package_path, **kwargs)
311
+ packages.extend(pkgs)
312
+ if pkgs and not (
313
+ fill_package_dir.get("") == path or os.path.samefile(package_path, root_dir)
314
+ ):
315
+ fill_package_dir.update(construct_package_dir(pkgs, path))
316
+
317
+ return packages
318
+
319
+
320
+ def _nest_path(parent: StrPath, path: StrPath) -> str:
321
+ path = parent if path in {".", ""} else os.path.join(parent, path)
322
+ return os.path.normpath(path)
323
+
324
+
325
+ def version(value: Callable | Iterable[str | int] | str) -> str:
326
+ """When getting the version directly from an attribute,
327
+ it should be normalised to string.
328
+ """
329
+ _value = value() if callable(value) else value
330
+
331
+ if isinstance(_value, str):
332
+ return _value
333
+ if hasattr(_value, '__iter__'):
334
+ return '.'.join(map(str, _value))
335
+ return f'{_value}'
336
+
337
+
338
+ def canonic_package_data(package_data: dict) -> dict:
339
+ if "*" in package_data:
340
+ package_data[""] = package_data.pop("*")
341
+ return package_data
342
+
343
+
344
+ def canonic_data_files(
345
+ data_files: list | dict, root_dir: StrPath | None = None
346
+ ) -> list[tuple[str, list[str]]]:
347
+ """For compatibility with ``setup.py``, ``data_files`` should be a list
348
+ of pairs instead of a dict.
349
+
350
+ This function also expands glob patterns.
351
+ """
352
+ if isinstance(data_files, list):
353
+ return data_files
354
+
355
+ return [
356
+ (dest, glob_relative(patterns, root_dir))
357
+ for dest, patterns in data_files.items()
358
+ ]
359
+
360
+
361
+ def entry_points(
362
+ text: str, text_source: str = "entry-points"
363
+ ) -> dict[str, dict[str, str]]:
364
+ """Given the contents of entry-points file,
365
+ process it into a 2-level dictionary (``dict[str, dict[str, str]]``).
366
+ The first level keys are entry-point groups, the second level keys are
367
+ entry-point names, and the second level values are references to objects
368
+ (that correspond to the entry-point value).
369
+ """
370
+ # Using undocumented behaviour, see python/typeshed#12700
371
+ parser = ConfigParser(default_section=None, delimiters=("=",)) # type: ignore[call-overload]
372
+ parser.optionxform = str # case sensitive
373
+ parser.read_string(text, text_source)
374
+ groups = {k: dict(v.items()) for k, v in parser.items()}
375
+ groups.pop(parser.default_section, None)
376
+ return groups
377
+
378
+
379
+ class EnsurePackagesDiscovered:
380
+ """Some expand functions require all the packages to already be discovered before
381
+ they run, e.g. :func:`read_attr`, :func:`resolve_class`, :func:`cmdclass`.
382
+
383
+ Therefore in some cases we will need to run autodiscovery during the evaluation of
384
+ the configuration. However, it is better to postpone calling package discovery as
385
+ much as possible, because some parameters can influence it (e.g. ``package_dir``),
386
+ and those might not have been processed yet.
387
+ """
388
+
389
+ def __init__(self, distribution: Distribution) -> None:
390
+ self._dist = distribution
391
+ self._called = False
392
+
393
+ def __call__(self) -> None:
394
+ """Trigger the automatic package discovery, if it is still necessary."""
395
+ if not self._called:
396
+ self._called = True
397
+ self._dist.set_defaults(name=False) # Skip name, we can still be parsing
398
+
399
+ def __enter__(self) -> Self:
400
+ return self
401
+
402
+ def __exit__(
403
+ self,
404
+ exc_type: type[BaseException] | None,
405
+ exc_value: BaseException | None,
406
+ traceback: TracebackType | None,
407
+ ) -> None:
408
+ if self._called:
409
+ self._dist.set_defaults.analyse_name() # Now we can set a default name
410
+
411
+ def _get_package_dir(self) -> Mapping[str, str]:
412
+ self()
413
+ pkg_dir = self._dist.package_dir
414
+ return {} if pkg_dir is None else pkg_dir
415
+
416
+ @property
417
+ def package_dir(self) -> Mapping[str, str]:
418
+ """Proxy to ``package_dir`` that may trigger auto-discovery when used."""
419
+ return LazyMappingProxy(self._get_package_dir)
420
+
421
+
422
+ class LazyMappingProxy(Mapping[_K, _V_co]):
423
+ """Mapping proxy that delays resolving the target object, until really needed.
424
+
425
+ >>> def obtain_mapping():
426
+ ... print("Running expensive function!")
427
+ ... return {"key": "value", "other key": "other value"}
428
+ >>> mapping = LazyMappingProxy(obtain_mapping)
429
+ >>> mapping["key"]
430
+ Running expensive function!
431
+ 'value'
432
+ >>> mapping["other key"]
433
+ 'other value'
434
+ """
435
+
436
+ def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None:
437
+ self._obtain = obtain_mapping_value
438
+ self._value: Mapping[_K, _V_co] | None = None
439
+
440
+ def _target(self) -> Mapping[_K, _V_co]:
441
+ if self._value is None:
442
+ self._value = self._obtain()
443
+ return self._value
444
+
445
+ def __getitem__(self, key: _K) -> _V_co:
446
+ return self._target()[key]
447
+
448
+ def __len__(self) -> int:
449
+ return len(self._target())
450
+
451
+ def __iter__(self) -> Iterator[_K]:
452
+ return iter(self._target())
python/Lib/site-packages/setuptools/config/pyprojecttoml.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load setuptools configuration from ``pyproject.toml`` files.
3
+
4
+ **PRIVATE MODULE**: API reserved for setuptools internal usage only.
5
+
6
+ To read project metadata, consider using
7
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
8
+ For simple scenarios, you can also try parsing the file directly
9
+ with the help of ``tomllib`` or ``tomli``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ from collections.abc import Mapping
17
+ from contextlib import contextmanager
18
+ from functools import partial
19
+ from types import TracebackType
20
+ from typing import TYPE_CHECKING, Any, Callable
21
+
22
+ from .._path import StrPath
23
+ from ..errors import FileError, InvalidConfigError
24
+ from ..warnings import SetuptoolsWarning
25
+ from . import expand as _expand
26
+ from ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _MissingDynamic, apply as _apply
27
+
28
+ if TYPE_CHECKING:
29
+ from typing_extensions import Self
30
+
31
+ from setuptools.dist import Distribution
32
+
33
+ _logger = logging.getLogger(__name__)
34
+
35
+
36
+ def load_file(filepath: StrPath) -> dict:
37
+ from ..compat.py310 import tomllib
38
+
39
+ with open(filepath, "rb") as file:
40
+ return tomllib.load(file)
41
+
42
+
43
+ def validate(config: dict, filepath: StrPath) -> bool:
44
+ from . import _validate_pyproject as validator
45
+
46
+ trove_classifier = validator.FORMAT_FUNCTIONS.get("trove-classifier")
47
+ if hasattr(trove_classifier, "_disable_download"):
48
+ # Improve reproducibility by default. See abravalheri/validate-pyproject#31
49
+ trove_classifier._disable_download() # type: ignore[union-attr]
50
+
51
+ try:
52
+ return validator.validate(config)
53
+ except validator.ValidationError as ex:
54
+ summary = f"configuration error: {ex.summary}"
55
+ if ex.name.strip("`") != "project":
56
+ # Probably it is just a field missing/misnamed, not worthy the verbosity...
57
+ _logger.debug(summary)
58
+ _logger.debug(ex.details)
59
+
60
+ error = f"invalid pyproject.toml config: {ex.name}."
61
+ raise ValueError(f"{error}\n{summary}") from None
62
+
63
+
64
+ def apply_configuration(
65
+ dist: Distribution,
66
+ filepath: StrPath,
67
+ ignore_option_errors: bool = False,
68
+ ) -> Distribution:
69
+ """Apply the configuration from a ``pyproject.toml`` file into an existing
70
+ distribution object.
71
+ """
72
+ config = read_configuration(filepath, True, ignore_option_errors, dist)
73
+ return _apply(dist, config, filepath)
74
+
75
+
76
+ def read_configuration(
77
+ filepath: StrPath,
78
+ expand: bool = True,
79
+ ignore_option_errors: bool = False,
80
+ dist: Distribution | None = None,
81
+ ) -> dict[str, Any]:
82
+ """Read given configuration file and returns options from it as a dict.
83
+
84
+ :param str|unicode filepath: Path to configuration file in the ``pyproject.toml``
85
+ format.
86
+
87
+ :param bool expand: Whether to expand directives and other computed values
88
+ (i.e. post-process the given configuration)
89
+
90
+ :param bool ignore_option_errors: Whether to silently ignore
91
+ options, values of which could not be resolved (e.g. due to exceptions
92
+ in directives such as file:, attr:, etc.).
93
+ If False exceptions are propagated as expected.
94
+
95
+ :param Distribution|None: Distribution object to which the configuration refers.
96
+ If not given a dummy object will be created and discarded after the
97
+ configuration is read. This is used for auto-discovery of packages and in the
98
+ case a dynamic configuration (e.g. ``attr`` or ``cmdclass``) is expanded.
99
+ When ``expand=False`` this object is simply ignored.
100
+
101
+ :rtype: dict
102
+ """
103
+ filepath = os.path.abspath(filepath)
104
+
105
+ if not os.path.isfile(filepath):
106
+ raise FileError(f"Configuration file {filepath!r} does not exist.")
107
+
108
+ asdict = load_file(filepath) or {}
109
+ project_table = asdict.get("project", {})
110
+ tool_table = asdict.get("tool", {})
111
+ setuptools_table = tool_table.get("setuptools", {})
112
+ if not asdict or not (project_table or setuptools_table):
113
+ return {} # User is not using pyproject to configure setuptools
114
+
115
+ if "setuptools" in asdict.get("tools", {}):
116
+ # let the user know they probably have a typo in their metadata
117
+ _ToolsTypoInMetadata.emit()
118
+
119
+ if "distutils" in tool_table:
120
+ _ExperimentalConfiguration.emit(subject="[tool.distutils]")
121
+
122
+ # There is an overall sense in the community that making include_package_data=True
123
+ # the default would be an improvement.
124
+ # `ini2toml` backfills include_package_data=False when nothing is explicitly given,
125
+ # therefore setting a default here is backwards compatible.
126
+ if dist and dist.include_package_data is not None:
127
+ setuptools_table.setdefault("include-package-data", dist.include_package_data)
128
+ else:
129
+ setuptools_table.setdefault("include-package-data", True)
130
+ # Persist changes:
131
+ asdict["tool"] = tool_table
132
+ tool_table["setuptools"] = setuptools_table
133
+
134
+ if "ext-modules" in setuptools_table:
135
+ _ExperimentalConfiguration.emit(subject="[tool.setuptools.ext-modules]")
136
+
137
+ fields = ("import-names", "import-namespaces")
138
+ places = (project_table, project_table.get("dynamic", []))
139
+ if any(field in place for field in fields for place in places):
140
+ raise NotImplementedError(
141
+ "Setuptools does not support `import-names` and `import-namespaces`"
142
+ " in `pyproject.toml` yet. If your are interested in this feature, "
143
+ " please consider submitting a contribution via pull requests."
144
+ )
145
+
146
+ with _ignore_errors(ignore_option_errors):
147
+ # Don't complain about unrelated errors (e.g. tools not using the "tool" table)
148
+ subset = {"project": project_table, "tool": {"setuptools": setuptools_table}}
149
+ validate(subset, filepath)
150
+
151
+ if expand:
152
+ root_dir = os.path.dirname(filepath)
153
+ return expand_configuration(asdict, root_dir, ignore_option_errors, dist)
154
+
155
+ return asdict
156
+
157
+
158
+ def expand_configuration(
159
+ config: dict,
160
+ root_dir: StrPath | None = None,
161
+ ignore_option_errors: bool = False,
162
+ dist: Distribution | None = None,
163
+ ) -> dict:
164
+ """Given a configuration with unresolved fields (e.g. dynamic, cmdclass, ...)
165
+ find their final values.
166
+
167
+ :param dict config: Dict containing the configuration for the distribution
168
+ :param str root_dir: Top-level directory for the distribution/project
169
+ (the same directory where ``pyproject.toml`` is place)
170
+ :param bool ignore_option_errors: see :func:`read_configuration`
171
+ :param Distribution|None: Distribution object to which the configuration refers.
172
+ If not given a dummy object will be created and discarded after the
173
+ configuration is read. Used in the case a dynamic configuration
174
+ (e.g. ``attr`` or ``cmdclass``).
175
+
176
+ :rtype: dict
177
+ """
178
+ return _ConfigExpander(config, root_dir, ignore_option_errors, dist).expand()
179
+
180
+
181
+ class _ConfigExpander:
182
+ def __init__(
183
+ self,
184
+ config: dict,
185
+ root_dir: StrPath | None = None,
186
+ ignore_option_errors: bool = False,
187
+ dist: Distribution | None = None,
188
+ ) -> None:
189
+ self.config = config
190
+ self.root_dir = root_dir or os.getcwd()
191
+ self.project_cfg = config.get("project", {})
192
+ self.dynamic = self.project_cfg.get("dynamic", [])
193
+ self.setuptools_cfg = config.get("tool", {}).get("setuptools", {})
194
+ self.dynamic_cfg = self.setuptools_cfg.get("dynamic", {})
195
+ self.ignore_option_errors = ignore_option_errors
196
+ self._dist = dist
197
+ self._referenced_files = set[str]()
198
+
199
+ def _ensure_dist(self) -> Distribution:
200
+ from setuptools.dist import Distribution
201
+
202
+ attrs = {"src_root": self.root_dir, "name": self.project_cfg.get("name", None)}
203
+ return self._dist or Distribution(attrs)
204
+
205
+ def _process_field(self, container: dict, field: str, fn: Callable):
206
+ if field in container:
207
+ with _ignore_errors(self.ignore_option_errors):
208
+ container[field] = fn(container[field])
209
+
210
+ def _canonic_package_data(self, field="package-data"):
211
+ package_data = self.setuptools_cfg.get(field, {})
212
+ return _expand.canonic_package_data(package_data)
213
+
214
+ def expand(self):
215
+ self._expand_packages()
216
+ self._canonic_package_data()
217
+ self._canonic_package_data("exclude-package-data")
218
+
219
+ # A distribution object is required for discovering the correct package_dir
220
+ dist = self._ensure_dist()
221
+ ctx = _EnsurePackagesDiscovered(dist, self.project_cfg, self.setuptools_cfg)
222
+ with ctx as ensure_discovered:
223
+ package_dir = ensure_discovered.package_dir
224
+ self._expand_data_files()
225
+ self._expand_cmdclass(package_dir)
226
+ self._expand_all_dynamic(dist, package_dir)
227
+
228
+ dist._referenced_files.update(self._referenced_files)
229
+ return self.config
230
+
231
+ def _expand_packages(self):
232
+ packages = self.setuptools_cfg.get("packages")
233
+ if packages is None or isinstance(packages, (list, tuple)):
234
+ return
235
+
236
+ find = packages.get("find")
237
+ if isinstance(find, dict):
238
+ find["root_dir"] = self.root_dir
239
+ find["fill_package_dir"] = self.setuptools_cfg.setdefault("package-dir", {})
240
+ with _ignore_errors(self.ignore_option_errors):
241
+ self.setuptools_cfg["packages"] = _expand.find_packages(**find)
242
+
243
+ def _expand_data_files(self):
244
+ data_files = partial(_expand.canonic_data_files, root_dir=self.root_dir)
245
+ self._process_field(self.setuptools_cfg, "data-files", data_files)
246
+
247
+ def _expand_cmdclass(self, package_dir: Mapping[str, str]):
248
+ root_dir = self.root_dir
249
+ cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir)
250
+ self._process_field(self.setuptools_cfg, "cmdclass", cmdclass)
251
+
252
+ def _expand_all_dynamic(self, dist: Distribution, package_dir: Mapping[str, str]):
253
+ special = ( # need special handling
254
+ "version",
255
+ "readme",
256
+ "entry-points",
257
+ "scripts",
258
+ "gui-scripts",
259
+ "classifiers",
260
+ "dependencies",
261
+ "optional-dependencies",
262
+ )
263
+ # `_obtain` functions are assumed to raise appropriate exceptions/warnings.
264
+ obtained_dynamic = {
265
+ field: self._obtain(dist, field, package_dir)
266
+ for field in self.dynamic
267
+ if field not in special
268
+ }
269
+ obtained_dynamic.update(
270
+ self._obtain_entry_points(dist, package_dir) or {},
271
+ version=self._obtain_version(dist, package_dir),
272
+ readme=self._obtain_readme(dist),
273
+ classifiers=self._obtain_classifiers(dist),
274
+ dependencies=self._obtain_dependencies(dist),
275
+ optional_dependencies=self._obtain_optional_dependencies(dist),
276
+ )
277
+ # `None` indicates there is nothing in `tool.setuptools.dynamic` but the value
278
+ # might have already been set by setup.py/extensions, so avoid overwriting.
279
+ updates = {k: v for k, v in obtained_dynamic.items() if v is not None}
280
+ self.project_cfg.update(updates)
281
+
282
+ def _ensure_previously_set(self, dist: Distribution, field: str):
283
+ previous = _PREVIOUSLY_DEFINED[field](dist)
284
+ if previous is None and not self.ignore_option_errors:
285
+ msg = (
286
+ f"No configuration found for dynamic {field!r}.\n"
287
+ "Some dynamic fields need to be specified via `tool.setuptools.dynamic`"
288
+ "\nothers must be specified via the equivalent attribute in `setup.py`."
289
+ )
290
+ raise InvalidConfigError(msg)
291
+
292
+ def _expand_directive(
293
+ self, specifier: str, directive, package_dir: Mapping[str, str]
294
+ ):
295
+ from more_itertools import always_iterable
296
+
297
+ with _ignore_errors(self.ignore_option_errors):
298
+ root_dir = self.root_dir
299
+ if "file" in directive:
300
+ self._referenced_files.update(always_iterable(directive["file"]))
301
+ return _expand.read_files(directive["file"], root_dir)
302
+ if "attr" in directive:
303
+ return _expand.read_attr(directive["attr"], package_dir, root_dir)
304
+ raise ValueError(f"invalid `{specifier}`: {directive!r}")
305
+ return None
306
+
307
+ def _obtain(self, dist: Distribution, field: str, package_dir: Mapping[str, str]):
308
+ if field in self.dynamic_cfg:
309
+ return self._expand_directive(
310
+ f"tool.setuptools.dynamic.{field}",
311
+ self.dynamic_cfg[field],
312
+ package_dir,
313
+ )
314
+ self._ensure_previously_set(dist, field)
315
+ return None
316
+
317
+ def _obtain_version(self, dist: Distribution, package_dir: Mapping[str, str]):
318
+ # Since plugins can set version, let's silently skip if it cannot be obtained
319
+ if "version" in self.dynamic and "version" in self.dynamic_cfg:
320
+ return _expand.version(
321
+ # We already do an early check for the presence of "version"
322
+ self._obtain(dist, "version", package_dir) # pyright: ignore[reportArgumentType]
323
+ )
324
+ return None
325
+
326
+ def _obtain_readme(self, dist: Distribution) -> dict[str, str] | None:
327
+ if "readme" not in self.dynamic:
328
+ return None
329
+
330
+ dynamic_cfg = self.dynamic_cfg
331
+ if "readme" in dynamic_cfg:
332
+ return {
333
+ # We already do an early check for the presence of "readme"
334
+ "text": self._obtain(dist, "readme", {}),
335
+ "content-type": dynamic_cfg["readme"].get("content-type", "text/x-rst"),
336
+ } # pyright: ignore[reportReturnType]
337
+
338
+ self._ensure_previously_set(dist, "readme")
339
+ return None
340
+
341
+ def _obtain_entry_points(
342
+ self, dist: Distribution, package_dir: Mapping[str, str]
343
+ ) -> dict[str, dict[str, Any]] | None:
344
+ fields = ("entry-points", "scripts", "gui-scripts")
345
+ if not any(field in self.dynamic for field in fields):
346
+ return None
347
+
348
+ text = self._obtain(dist, "entry-points", package_dir)
349
+ if text is None:
350
+ return None
351
+
352
+ groups = _expand.entry_points(text)
353
+ # Any is str | dict[str, str], but causes variance issues
354
+ expanded: dict[str, dict[str, Any]] = {"entry-points": groups}
355
+
356
+ def _set_scripts(field: str, group: str):
357
+ if group in groups:
358
+ value = groups.pop(group)
359
+ if field not in self.dynamic:
360
+ raise InvalidConfigError(_MissingDynamic.details(field, value))
361
+ expanded[field] = value
362
+
363
+ _set_scripts("scripts", "console_scripts")
364
+ _set_scripts("gui-scripts", "gui_scripts")
365
+
366
+ return expanded
367
+
368
+ def _obtain_classifiers(self, dist: Distribution):
369
+ if "classifiers" in self.dynamic:
370
+ value = self._obtain(dist, "classifiers", {})
371
+ if value:
372
+ return value.splitlines()
373
+ return None
374
+
375
+ def _obtain_dependencies(self, dist: Distribution):
376
+ if "dependencies" in self.dynamic:
377
+ value = self._obtain(dist, "dependencies", {})
378
+ if value:
379
+ return _parse_requirements_list(value)
380
+ return None
381
+
382
+ def _obtain_optional_dependencies(self, dist: Distribution):
383
+ if "optional-dependencies" not in self.dynamic:
384
+ return None
385
+ if "optional-dependencies" in self.dynamic_cfg:
386
+ optional_dependencies_map = self.dynamic_cfg["optional-dependencies"]
387
+ assert isinstance(optional_dependencies_map, dict)
388
+ return {
389
+ group: _parse_requirements_list(
390
+ self._expand_directive(
391
+ f"tool.setuptools.dynamic.optional-dependencies.{group}",
392
+ directive,
393
+ {},
394
+ )
395
+ )
396
+ for group, directive in optional_dependencies_map.items()
397
+ }
398
+ self._ensure_previously_set(dist, "optional-dependencies")
399
+ return None
400
+
401
+
402
+ def _parse_requirements_list(value):
403
+ return [
404
+ line
405
+ for line in value.splitlines()
406
+ if line.strip() and not line.strip().startswith("#")
407
+ ]
408
+
409
+
410
+ @contextmanager
411
+ def _ignore_errors(ignore_option_errors: bool):
412
+ if not ignore_option_errors:
413
+ yield
414
+ return
415
+
416
+ try:
417
+ yield
418
+ except Exception as ex:
419
+ _logger.debug(f"ignored error: {ex.__class__.__name__} - {ex}")
420
+
421
+
422
+ class _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered):
423
+ def __init__(
424
+ self, distribution: Distribution, project_cfg: dict, setuptools_cfg: dict
425
+ ) -> None:
426
+ super().__init__(distribution)
427
+ self._project_cfg = project_cfg
428
+ self._setuptools_cfg = setuptools_cfg
429
+
430
+ def __enter__(self) -> Self:
431
+ """When entering the context, the values of ``packages``, ``py_modules`` and
432
+ ``package_dir`` that are missing in ``dist`` are copied from ``setuptools_cfg``.
433
+ """
434
+ dist, cfg = self._dist, self._setuptools_cfg
435
+ package_dir: dict[str, str] = cfg.setdefault("package-dir", {})
436
+ package_dir.update(dist.package_dir or {})
437
+ dist.package_dir = package_dir # needs to be the same object
438
+
439
+ dist.set_defaults._ignore_ext_modules() # pyproject.toml-specific behaviour
440
+
441
+ # Set `name`, `py_modules` and `packages` in dist to short-circuit
442
+ # auto-discovery, but avoid overwriting empty lists purposefully set by users.
443
+ if dist.metadata.name is None:
444
+ dist.metadata.name = self._project_cfg.get("name")
445
+ if dist.py_modules is None:
446
+ dist.py_modules = cfg.get("py-modules")
447
+ if dist.packages is None:
448
+ dist.packages = cfg.get("packages")
449
+
450
+ return super().__enter__()
451
+
452
+ def __exit__(
453
+ self,
454
+ exc_type: type[BaseException] | None,
455
+ exc_value: BaseException | None,
456
+ traceback: TracebackType | None,
457
+ ) -> None:
458
+ """When exiting the context, if values of ``packages``, ``py_modules`` and
459
+ ``package_dir`` are missing in ``setuptools_cfg``, copy from ``dist``.
460
+ """
461
+ # If anything was discovered set them back, so they count in the final config.
462
+ self._setuptools_cfg.setdefault("packages", self._dist.packages)
463
+ self._setuptools_cfg.setdefault("py-modules", self._dist.py_modules)
464
+ return super().__exit__(exc_type, exc_value, traceback)
465
+
466
+
467
+ class _ExperimentalConfiguration(SetuptoolsWarning):
468
+ _SUMMARY = (
469
+ "`{subject}` in `pyproject.toml` is still *experimental* "
470
+ "and likely to change in future releases."
471
+ )
472
+
473
+
474
+ class _ToolsTypoInMetadata(SetuptoolsWarning):
475
+ _SUMMARY = (
476
+ "Ignoring [tools.setuptools] in pyproject.toml, did you mean [tool.setuptools]?"
477
+ )
python/Lib/site-packages/setuptools/config/setupcfg.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load setuptools configuration from ``setup.cfg`` files.
3
+
4
+ **API will be made private in the future**
5
+
6
+ To read project metadata, consider using
7
+ ``build.util.project_wheel_metadata`` (https://pypi.org/project/build/).
8
+ For simple scenarios, you can also try parsing the file directly
9
+ with the help of ``configparser``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import functools
16
+ import os
17
+ from abc import abstractmethod
18
+ from collections import defaultdict
19
+ from collections.abc import Iterable, Iterator
20
+ from functools import partial, wraps
21
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, TypeVar, cast
22
+
23
+ from packaging.markers import default_environment as marker_env
24
+ from packaging.requirements import InvalidRequirement, Requirement
25
+ from packaging.version import InvalidVersion, Version
26
+
27
+ from .. import _static
28
+ from .._path import StrPath
29
+ from ..errors import FileError, OptionError
30
+ from ..warnings import SetuptoolsDeprecationWarning
31
+ from . import expand
32
+
33
+ if TYPE_CHECKING:
34
+ from typing_extensions import TypeAlias
35
+
36
+ from setuptools.dist import Distribution
37
+
38
+ from distutils.dist import DistributionMetadata
39
+
40
+ SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]]
41
+ """Dict that associate the name of the options of a particular command to a
42
+ tuple. The first element of the tuple indicates the origin of the option value
43
+ (e.g. the name of the configuration file where it was read from),
44
+ while the second element of the tuple is the option value itself
45
+ """
46
+ AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions]
47
+ """cmd name => its options"""
48
+ Target = TypeVar("Target", "Distribution", "DistributionMetadata")
49
+
50
+
51
+ def read_configuration(
52
+ filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False
53
+ ) -> dict:
54
+ """Read given configuration file and returns options from it as a dict.
55
+
56
+ :param str|unicode filepath: Path to configuration file
57
+ to get options from.
58
+
59
+ :param bool find_others: Whether to search for other configuration files
60
+ which could be on in various places.
61
+
62
+ :param bool ignore_option_errors: Whether to silently ignore
63
+ options, values of which could not be resolved (e.g. due to exceptions
64
+ in directives such as file:, attr:, etc.).
65
+ If False exceptions are propagated as expected.
66
+
67
+ :rtype: dict
68
+ """
69
+ from setuptools.dist import Distribution
70
+
71
+ dist = Distribution()
72
+ filenames = dist.find_config_files() if find_others else []
73
+ handlers = _apply(dist, filepath, filenames, ignore_option_errors)
74
+ return configuration_to_dict(handlers)
75
+
76
+
77
+ def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution:
78
+ """Apply the configuration from a ``setup.cfg`` file into an existing
79
+ distribution object.
80
+ """
81
+ _apply(dist, filepath)
82
+ dist._finalize_requires()
83
+ return dist
84
+
85
+
86
+ def _apply(
87
+ dist: Distribution,
88
+ filepath: StrPath,
89
+ other_files: Iterable[StrPath] = (),
90
+ ignore_option_errors: bool = False,
91
+ ) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
92
+ """Read configuration from ``filepath`` and applies to the ``dist`` object."""
93
+ from setuptools.dist import _Distribution
94
+
95
+ filepath = os.path.abspath(filepath)
96
+
97
+ if not os.path.isfile(filepath):
98
+ raise FileError(f'Configuration file {filepath} does not exist.')
99
+
100
+ current_directory = os.getcwd()
101
+ os.chdir(os.path.dirname(filepath))
102
+ filenames = [*other_files, filepath]
103
+
104
+ try:
105
+ # TODO: Temporary cast until mypy 1.12 is released with upstream fixes from typeshed
106
+ _Distribution.parse_config_files(dist, filenames=cast(list[str], filenames))
107
+ handlers = parse_configuration(
108
+ dist, dist.command_options, ignore_option_errors=ignore_option_errors
109
+ )
110
+ dist._finalize_license_files()
111
+ finally:
112
+ os.chdir(current_directory)
113
+
114
+ return handlers
115
+
116
+
117
+ def _get_option(target_obj: Distribution | DistributionMetadata, key: str):
118
+ """
119
+ Given a target object and option key, get that option from
120
+ the target object, either through a get_{key} method or
121
+ from an attribute directly.
122
+ """
123
+ getter_name = f'get_{key}'
124
+ by_attribute = functools.partial(getattr, target_obj, key)
125
+ getter = getattr(target_obj, getter_name, by_attribute)
126
+ return getter()
127
+
128
+
129
+ def configuration_to_dict(
130
+ handlers: Iterable[
131
+ ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]
132
+ ],
133
+ ) -> dict:
134
+ """Returns configuration data gathered by given handlers as a dict.
135
+
136
+ :param Iterable[ConfigHandler] handlers: Handlers list,
137
+ usually from parse_configuration()
138
+
139
+ :rtype: dict
140
+ """
141
+ config_dict: dict = defaultdict(dict)
142
+
143
+ for handler in handlers:
144
+ for option in handler.set_options:
145
+ value = _get_option(handler.target_obj, option)
146
+ config_dict[handler.section_prefix][option] = value
147
+
148
+ return config_dict
149
+
150
+
151
+ def parse_configuration(
152
+ distribution: Distribution,
153
+ command_options: AllCommandOptions,
154
+ ignore_option_errors: bool = False,
155
+ ) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]:
156
+ """Performs additional parsing of configuration options
157
+ for a distribution.
158
+
159
+ Returns a list of used option handlers.
160
+
161
+ :param Distribution distribution:
162
+ :param dict command_options:
163
+ :param bool ignore_option_errors: Whether to silently ignore
164
+ options, values of which could not be resolved (e.g. due to exceptions
165
+ in directives such as file:, attr:, etc.).
166
+ If False exceptions are propagated as expected.
167
+ :rtype: list
168
+ """
169
+ with expand.EnsurePackagesDiscovered(distribution) as ensure_discovered:
170
+ options = ConfigOptionsHandler(
171
+ distribution,
172
+ command_options,
173
+ ignore_option_errors,
174
+ ensure_discovered,
175
+ )
176
+
177
+ options.parse()
178
+ if not distribution.package_dir:
179
+ distribution.package_dir = options.package_dir # Filled by `find_packages`
180
+
181
+ meta = ConfigMetadataHandler(
182
+ distribution.metadata,
183
+ command_options,
184
+ ignore_option_errors,
185
+ ensure_discovered,
186
+ distribution.package_dir,
187
+ distribution.src_root,
188
+ )
189
+ meta.parse()
190
+ distribution._referenced_files.update(
191
+ options._referenced_files, meta._referenced_files
192
+ )
193
+
194
+ return meta, options
195
+
196
+
197
+ def _warn_accidental_env_marker_misconfig(label: str, orig_value: str, parsed: list):
198
+ """Because users sometimes misinterpret this configuration:
199
+
200
+ [options.extras_require]
201
+ foo = bar;python_version<"4"
202
+
203
+ It looks like one requirement with an environment marker
204
+ but because there is no newline, it's parsed as two requirements
205
+ with a semicolon as separator.
206
+
207
+ Therefore, if:
208
+ * input string does not contain a newline AND
209
+ * parsed result contains two requirements AND
210
+ * parsing of the two parts from the result ("<first>;<second>")
211
+ leads in a valid Requirement with a valid marker
212
+ a UserWarning is shown to inform the user about the possible problem.
213
+ """
214
+ if "\n" in orig_value or len(parsed) != 2:
215
+ return
216
+
217
+ markers = marker_env().keys()
218
+
219
+ try:
220
+ req = Requirement(parsed[1])
221
+ if req.name in markers:
222
+ _AmbiguousMarker.emit(field=label, req=parsed[1])
223
+ except InvalidRequirement as ex:
224
+ if any(parsed[1].startswith(marker) for marker in markers):
225
+ msg = _AmbiguousMarker.message(field=label, req=parsed[1])
226
+ raise InvalidRequirement(msg) from ex
227
+
228
+
229
+ class ConfigHandler(Generic[Target]):
230
+ """Handles metadata supplied in configuration files."""
231
+
232
+ section_prefix: str
233
+ """Prefix for config sections handled by this handler.
234
+ Must be provided by class heirs.
235
+
236
+ """
237
+
238
+ aliases: ClassVar[dict[str, str]] = {}
239
+ """Options aliases.
240
+ For compatibility with various packages. E.g.: d2to1 and pbr.
241
+ Note: `-` in keys is replaced with `_` by config parser.
242
+
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ target_obj: Target,
248
+ options: AllCommandOptions,
249
+ ignore_option_errors,
250
+ ensure_discovered: expand.EnsurePackagesDiscovered,
251
+ ) -> None:
252
+ self.ignore_option_errors = ignore_option_errors
253
+ self.target_obj: Target = target_obj
254
+ self.sections = dict(self._section_options(options))
255
+ self.set_options: list[str] = []
256
+ self.ensure_discovered = ensure_discovered
257
+ self._referenced_files = set[str]()
258
+ """After parsing configurations, this property will enumerate
259
+ all files referenced by the "file:" directive. Private API for setuptools only.
260
+ """
261
+
262
+ @classmethod
263
+ def _section_options(
264
+ cls, options: AllCommandOptions
265
+ ) -> Iterator[tuple[str, SingleCommandOptions]]:
266
+ for full_name, value in options.items():
267
+ pre, _sep, name = full_name.partition(cls.section_prefix)
268
+ if pre:
269
+ continue
270
+ yield name.lstrip('.'), value
271
+
272
+ @property
273
+ @abstractmethod
274
+ def parsers(self) -> dict[str, Callable]:
275
+ """Metadata item name to parser function mapping."""
276
+ raise NotImplementedError(
277
+ f'{self.__class__.__name__} must provide .parsers property'
278
+ )
279
+
280
+ def __setitem__(self, option_name, value) -> None:
281
+ target_obj = self.target_obj
282
+
283
+ # Translate alias into real name.
284
+ option_name = self.aliases.get(option_name, option_name)
285
+
286
+ try:
287
+ current_value = getattr(target_obj, option_name)
288
+ except AttributeError as e:
289
+ raise KeyError(option_name) from e
290
+
291
+ if current_value:
292
+ # Already inhabited. Skipping.
293
+ return
294
+
295
+ try:
296
+ parsed = self.parsers.get(option_name, lambda x: x)(value)
297
+ except (Exception,) * self.ignore_option_errors:
298
+ return
299
+
300
+ simple_setter = functools.partial(target_obj.__setattr__, option_name)
301
+ setter = getattr(target_obj, f"set_{option_name}", simple_setter)
302
+ setter(parsed)
303
+
304
+ self.set_options.append(option_name)
305
+
306
+ @classmethod
307
+ def _parse_list(cls, value, separator=','):
308
+ """Represents value as a list.
309
+
310
+ Value is split either by separator (defaults to comma) or by lines.
311
+
312
+ :param value:
313
+ :param separator: List items separator character.
314
+ :rtype: list
315
+ """
316
+ if isinstance(value, list): # _get_parser_compound case
317
+ return value
318
+
319
+ if '\n' in value:
320
+ value = value.splitlines()
321
+ else:
322
+ value = value.split(separator)
323
+
324
+ return [chunk.strip() for chunk in value if chunk.strip()]
325
+
326
+ @classmethod
327
+ def _parse_dict(cls, value):
328
+ """Represents value as a dict.
329
+
330
+ :param value:
331
+ :rtype: dict
332
+ """
333
+ separator = '='
334
+ result = {}
335
+ for line in cls._parse_list(value):
336
+ key, sep, val = line.partition(separator)
337
+ if sep != separator:
338
+ raise OptionError(f"Unable to parse option value to dict: {value}")
339
+ result[key.strip()] = val.strip()
340
+
341
+ return result
342
+
343
+ @classmethod
344
+ def _parse_bool(cls, value):
345
+ """Represents value as boolean.
346
+
347
+ :param value:
348
+ :rtype: bool
349
+ """
350
+ value = value.lower()
351
+ return value in ('1', 'true', 'yes')
352
+
353
+ @classmethod
354
+ def _exclude_files_parser(cls, key):
355
+ """Returns a parser function to make sure field inputs
356
+ are not files.
357
+
358
+ Parses a value after getting the key so error messages are
359
+ more informative.
360
+
361
+ :param key:
362
+ :rtype: callable
363
+ """
364
+
365
+ def parser(value):
366
+ exclude_directive = 'file:'
367
+ if value.startswith(exclude_directive):
368
+ raise ValueError(
369
+ f'Only strings are accepted for the {key} field, '
370
+ 'files are not accepted'
371
+ )
372
+ return _static.Str(value)
373
+
374
+ return parser
375
+
376
+ def _parse_file(self, value, root_dir: StrPath | None):
377
+ """Represents value as a string, allowing including text
378
+ from nearest files using `file:` directive.
379
+
380
+ Directive is sandboxed and won't reach anything outside
381
+ directory with setup.py.
382
+
383
+ Examples:
384
+ file: README.rst, CHANGELOG.md, src/file.txt
385
+
386
+ :param str value:
387
+ :rtype: str
388
+ """
389
+ include_directive = 'file:'
390
+
391
+ if not isinstance(value, str):
392
+ return value
393
+
394
+ if not value.startswith(include_directive):
395
+ return _static.Str(value)
396
+
397
+ spec = value[len(include_directive) :]
398
+ filepaths = [path.strip() for path in spec.split(',')]
399
+ self._referenced_files.update(filepaths)
400
+ # XXX: Is marking as static contents coming from files too optimistic?
401
+ return _static.Str(expand.read_files(filepaths, root_dir))
402
+
403
+ def _parse_attr(self, value, package_dir, root_dir: StrPath):
404
+ """Represents value as a module attribute.
405
+
406
+ Examples:
407
+ attr: package.attr
408
+ attr: package.module.attr
409
+
410
+ :param str value:
411
+ :rtype: str
412
+ """
413
+ attr_directive = 'attr:'
414
+ if not value.startswith(attr_directive):
415
+ return _static.Str(value)
416
+
417
+ attr_desc = value.replace(attr_directive, '')
418
+
419
+ # Make sure package_dir is populated correctly, so `attr:` directives can work
420
+ package_dir.update(self.ensure_discovered.package_dir)
421
+ return expand.read_attr(attr_desc, package_dir, root_dir)
422
+
423
+ @classmethod
424
+ def _get_parser_compound(cls, *parse_methods):
425
+ """Returns parser function to represents value as a list.
426
+
427
+ Parses a value applying given methods one after another.
428
+
429
+ :param parse_methods:
430
+ :rtype: callable
431
+ """
432
+
433
+ def parse(value):
434
+ parsed = value
435
+
436
+ for method in parse_methods:
437
+ parsed = method(parsed)
438
+
439
+ return parsed
440
+
441
+ return parse
442
+
443
+ @classmethod
444
+ def _parse_section_to_dict_with_key(cls, section_options, values_parser):
445
+ """Parses section options into a dictionary.
446
+
447
+ Applies a given parser to each option in a section.
448
+
449
+ :param dict section_options:
450
+ :param callable values_parser: function with 2 args corresponding to key, value
451
+ :rtype: dict
452
+ """
453
+ value = {}
454
+ for key, (_, val) in section_options.items():
455
+ value[key] = values_parser(key, val)
456
+ return value
457
+
458
+ @classmethod
459
+ def _parse_section_to_dict(cls, section_options, values_parser=None):
460
+ """Parses section options into a dictionary.
461
+
462
+ Optionally applies a given parser to each value.
463
+
464
+ :param dict section_options:
465
+ :param callable values_parser: function with 1 arg corresponding to option value
466
+ :rtype: dict
467
+ """
468
+ parser = (lambda _, v: values_parser(v)) if values_parser else (lambda _, v: v)
469
+ return cls._parse_section_to_dict_with_key(section_options, parser)
470
+
471
+ def parse_section(self, section_options) -> None:
472
+ """Parses configuration file section.
473
+
474
+ :param dict section_options:
475
+ """
476
+ for name, (_, value) in section_options.items():
477
+ with contextlib.suppress(KeyError):
478
+ # Keep silent for a new option may appear anytime.
479
+ self[name] = value
480
+
481
+ def parse(self) -> None:
482
+ """Parses configuration file items from one
483
+ or more related sections.
484
+
485
+ """
486
+ for section_name, section_options in self.sections.items():
487
+ method_postfix = ''
488
+ if section_name: # [section.option] variant
489
+ method_postfix = f"_{section_name}"
490
+
491
+ section_parser_method: Callable | None = getattr(
492
+ self,
493
+ # Dots in section names are translated into dunderscores.
494
+ f'parse_section{method_postfix}'.replace('.', '__'),
495
+ None,
496
+ )
497
+
498
+ if section_parser_method is None:
499
+ raise OptionError(
500
+ "Unsupported distribution option section: "
501
+ f"[{self.section_prefix}.{section_name}]"
502
+ )
503
+
504
+ section_parser_method(section_options)
505
+
506
+ def _deprecated_config_handler(self, func, msg, **kw):
507
+ """this function will wrap around parameters that are deprecated
508
+
509
+ :param msg: deprecation message
510
+ :param func: function to be wrapped around
511
+ """
512
+
513
+ @wraps(func)
514
+ def config_handler(*args, **kwargs):
515
+ kw.setdefault("stacklevel", 2)
516
+ _DeprecatedConfig.emit("Deprecated config in `setup.cfg`", msg, **kw)
517
+ return func(*args, **kwargs)
518
+
519
+ return config_handler
520
+
521
+
522
+ class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
523
+ section_prefix = 'metadata'
524
+
525
+ aliases = {
526
+ 'home_page': 'url',
527
+ 'summary': 'description',
528
+ 'classifier': 'classifiers',
529
+ 'platform': 'platforms',
530
+ }
531
+
532
+ strict_mode = False
533
+ """We need to keep it loose, to be partially compatible with
534
+ `pbr` and `d2to1` packages which also uses `metadata` section.
535
+
536
+ """
537
+
538
+ def __init__(
539
+ self,
540
+ target_obj: DistributionMetadata,
541
+ options: AllCommandOptions,
542
+ ignore_option_errors: bool,
543
+ ensure_discovered: expand.EnsurePackagesDiscovered,
544
+ package_dir: dict | None = None,
545
+ root_dir: StrPath | None = os.curdir,
546
+ ) -> None:
547
+ super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
548
+ self.package_dir = package_dir
549
+ self.root_dir = root_dir
550
+
551
+ @property
552
+ def parsers(self) -> dict[str, Callable]:
553
+ """Metadata item name to parser function mapping."""
554
+ parse_list_static = self._get_parser_compound(self._parse_list, _static.List)
555
+ parse_dict_static = self._get_parser_compound(self._parse_dict, _static.Dict)
556
+ parse_file = partial(self._parse_file, root_dir=self.root_dir)
557
+ exclude_files_parser = self._exclude_files_parser
558
+
559
+ return {
560
+ 'author': _static.Str,
561
+ 'author_email': _static.Str,
562
+ 'maintainer': _static.Str,
563
+ 'maintainer_email': _static.Str,
564
+ 'platforms': parse_list_static,
565
+ 'keywords': parse_list_static,
566
+ 'provides': parse_list_static,
567
+ 'obsoletes': parse_list_static,
568
+ 'classifiers': self._get_parser_compound(parse_file, parse_list_static),
569
+ 'license': exclude_files_parser('license'),
570
+ 'license_files': parse_list_static,
571
+ 'description': parse_file,
572
+ 'long_description': parse_file,
573
+ 'long_description_content_type': _static.Str,
574
+ 'version': self._parse_version, # Cannot be marked as dynamic
575
+ 'url': _static.Str,
576
+ 'project_urls': parse_dict_static,
577
+ }
578
+
579
+ def _parse_version(self, value):
580
+ """Parses `version` option value.
581
+
582
+ :param value:
583
+ :rtype: str
584
+
585
+ """
586
+ version = self._parse_file(value, self.root_dir)
587
+
588
+ if version != value:
589
+ version = version.strip()
590
+ # Be strict about versions loaded from file because it's easy to
591
+ # accidentally include newlines and other unintended content
592
+ try:
593
+ Version(version)
594
+ except InvalidVersion as e:
595
+ raise OptionError(
596
+ f'Version loaded from {value} does not '
597
+ f'comply with PEP 440: {version}'
598
+ ) from e
599
+
600
+ return version
601
+
602
+ return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))
603
+
604
+
605
+ class ConfigOptionsHandler(ConfigHandler["Distribution"]):
606
+ section_prefix = 'options'
607
+
608
+ def __init__(
609
+ self,
610
+ target_obj: Distribution,
611
+ options: AllCommandOptions,
612
+ ignore_option_errors: bool,
613
+ ensure_discovered: expand.EnsurePackagesDiscovered,
614
+ ) -> None:
615
+ super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
616
+ self.root_dir = target_obj.src_root
617
+ self.package_dir: dict[str, str] = {} # To be filled by `find_packages`
618
+
619
+ @classmethod
620
+ def _parse_list_semicolon(cls, value):
621
+ return cls._parse_list(value, separator=';')
622
+
623
+ def _parse_file_in_root(self, value):
624
+ return self._parse_file(value, root_dir=self.root_dir)
625
+
626
+ def _parse_requirements_list(self, label: str, value: str):
627
+ # Parse a requirements list, either by reading in a `file:`, or a list.
628
+ parsed = self._parse_list_semicolon(self._parse_file_in_root(value))
629
+ _warn_accidental_env_marker_misconfig(label, value, parsed)
630
+ # Filter it to only include lines that are not comments. `parse_list`
631
+ # will have stripped each line and filtered out empties.
632
+ return _static.List(line for line in parsed if not line.startswith("#"))
633
+ # ^-- Use `_static.List` to mark a non-`Dynamic` Core Metadata
634
+
635
+ @property
636
+ def parsers(self) -> dict[str, Callable]:
637
+ """Metadata item name to parser function mapping."""
638
+ parse_list = self._parse_list
639
+ parse_bool = self._parse_bool
640
+ parse_cmdclass = self._parse_cmdclass
641
+
642
+ return {
643
+ 'zip_safe': parse_bool,
644
+ 'include_package_data': parse_bool,
645
+ 'package_dir': self._parse_dict,
646
+ 'scripts': parse_list,
647
+ 'eager_resources': parse_list,
648
+ 'dependency_links': parse_list,
649
+ 'namespace_packages': self._deprecated_config_handler(
650
+ parse_list,
651
+ "The namespace_packages parameter is deprecated, "
652
+ "consider using implicit namespaces instead (PEP 420).",
653
+ # TODO: define due date, see setuptools.dist:check_nsp.
654
+ ),
655
+ 'install_requires': partial( # Core Metadata
656
+ self._parse_requirements_list, "install_requires"
657
+ ),
658
+ 'setup_requires': self._parse_list_semicolon,
659
+ 'packages': self._parse_packages,
660
+ 'entry_points': self._parse_file_in_root,
661
+ 'py_modules': parse_list,
662
+ 'python_requires': _static.SpecifierSet, # Core Metadata
663
+ 'cmdclass': parse_cmdclass,
664
+ }
665
+
666
+ def _parse_cmdclass(self, value):
667
+ package_dir = self.ensure_discovered.package_dir
668
+ return expand.cmdclass(self._parse_dict(value), package_dir, self.root_dir)
669
+
670
+ def _parse_packages(self, value):
671
+ """Parses `packages` option value.
672
+
673
+ :param value:
674
+ :rtype: list
675
+ """
676
+ find_directives = ['find:', 'find_namespace:']
677
+ trimmed_value = value.strip()
678
+
679
+ if trimmed_value not in find_directives:
680
+ return self._parse_list(value)
681
+
682
+ # Read function arguments from a dedicated section.
683
+ find_kwargs = self.parse_section_packages__find(
684
+ self.sections.get('packages.find', {})
685
+ )
686
+
687
+ find_kwargs.update(
688
+ namespaces=(trimmed_value == find_directives[1]),
689
+ root_dir=self.root_dir,
690
+ fill_package_dir=self.package_dir,
691
+ )
692
+
693
+ return expand.find_packages(**find_kwargs)
694
+
695
+ def parse_section_packages__find(self, section_options):
696
+ """Parses `packages.find` configuration file section.
697
+
698
+ To be used in conjunction with _parse_packages().
699
+
700
+ :param dict section_options:
701
+ """
702
+ section_data = self._parse_section_to_dict(section_options, self._parse_list)
703
+
704
+ valid_keys = ['where', 'include', 'exclude']
705
+ find_kwargs = {k: v for k, v in section_data.items() if k in valid_keys and v}
706
+
707
+ where = find_kwargs.get('where')
708
+ if where is not None:
709
+ find_kwargs['where'] = where[0] # cast list to single val
710
+
711
+ return find_kwargs
712
+
713
+ def parse_section_entry_points(self, section_options) -> None:
714
+ """Parses `entry_points` configuration file section.
715
+
716
+ :param dict section_options:
717
+ """
718
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
719
+ self['entry_points'] = parsed
720
+
721
+ def _parse_package_data(self, section_options):
722
+ package_data = self._parse_section_to_dict(section_options, self._parse_list)
723
+ return expand.canonic_package_data(package_data)
724
+
725
+ def parse_section_package_data(self, section_options) -> None:
726
+ """Parses `package_data` configuration file section.
727
+
728
+ :param dict section_options:
729
+ """
730
+ self['package_data'] = self._parse_package_data(section_options)
731
+
732
+ def parse_section_exclude_package_data(self, section_options) -> None:
733
+ """Parses `exclude_package_data` configuration file section.
734
+
735
+ :param dict section_options:
736
+ """
737
+ self['exclude_package_data'] = self._parse_package_data(section_options)
738
+
739
+ def parse_section_extras_require(self, section_options) -> None: # Core Metadata
740
+ """Parses `extras_require` configuration file section.
741
+
742
+ :param dict section_options:
743
+ """
744
+ parsed = self._parse_section_to_dict_with_key(
745
+ section_options,
746
+ lambda k, v: self._parse_requirements_list(f"extras_require[{k}]", v),
747
+ )
748
+
749
+ self['extras_require'] = _static.Dict(parsed)
750
+ # ^-- Use `_static.Dict` to mark a non-`Dynamic` Core Metadata
751
+
752
+ def parse_section_data_files(self, section_options) -> None:
753
+ """Parses `data_files` configuration file section.
754
+
755
+ :param dict section_options:
756
+ """
757
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
758
+ self['data_files'] = expand.canonic_data_files(parsed, self.root_dir)
759
+
760
+
761
+ class _AmbiguousMarker(SetuptoolsDeprecationWarning):
762
+ _SUMMARY = "Ambiguous requirement marker."
763
+ _DETAILS = """
764
+ One of the parsed requirements in `{field}` looks like a valid environment marker:
765
+
766
+ {req!r}
767
+
768
+ Please make sure that the configuration file is correct.
769
+ You can use dangling lines to avoid this problem.
770
+ """
771
+ _SEE_DOCS = "userguide/declarative_config.html#opt-2"
772
+ # TODO: should we include due_date here? Initially introduced in 6 Aug 2022.
773
+ # Does this make sense with latest version of packaging?
774
+
775
+ @classmethod
776
+ def message(cls, **kw):
777
+ docs = f"https://setuptools.pypa.io/en/latest/{cls._SEE_DOCS}"
778
+ return cls._format(cls._SUMMARY, cls._DETAILS, see_url=docs, format_args=kw)
779
+
780
+
781
+ class _DeprecatedConfig(SetuptoolsDeprecationWarning):
782
+ _SEE_DOCS = "userguide/declarative_config.html"
python/Lib/site-packages/setuptools/config/setuptools.schema.json ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+
4
+ "$id": "https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html",
5
+ "title": "``tool.setuptools`` table",
6
+ "$$description": [
7
+ "``setuptools``-specific configurations that can be set by users that require",
8
+ "customization.",
9
+ "These configurations are completely optional and probably can be skipped when",
10
+ "creating simple packages. They are equivalent to some of the `Keywords",
11
+ "<https://setuptools.pypa.io/en/latest/references/keywords.html>`_",
12
+ "used by the ``setup.py`` file, and can be set via the ``tool.setuptools`` table.",
13
+ "It considers only ``setuptools`` `parameters",
14
+ "<https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#setuptools-specific-configuration>`_",
15
+ "that are not covered by :pep:`621`; and intentionally excludes ``dependency_links``",
16
+ "and ``setup_requires`` (incompatible with modern workflows/standards)."
17
+ ],
18
+
19
+ "type": "object",
20
+ "additionalProperties": false,
21
+ "properties": {
22
+ "platforms": {
23
+ "type": "array",
24
+ "items": {"type": "string"}
25
+ },
26
+ "provides": {
27
+ "$$description": [
28
+ "Package and virtual package names contained within this package",
29
+ "**(not supported by pip)**"
30
+ ],
31
+ "type": "array",
32
+ "items": {"type": "string", "format": "pep508-identifier"}
33
+ },
34
+ "obsoletes": {
35
+ "$$description": [
36
+ "Packages which this package renders obsolete",
37
+ "**(not supported by pip)**"
38
+ ],
39
+ "type": "array",
40
+ "items": {"type": "string", "format": "pep508-identifier"}
41
+ },
42
+ "zip-safe": {
43
+ "$$description": [
44
+ "Whether the project can be safely installed and run from a zip file.",
45
+ "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
46
+ "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
47
+ ],
48
+ "type": "boolean"
49
+ },
50
+ "script-files": {
51
+ "$$description": [
52
+ "Legacy way of defining scripts (entry-points are preferred).",
53
+ "Equivalent to the ``script`` keyword in ``setup.py``",
54
+ "(it was renamed to avoid confusion with entry-point based ``project.scripts``",
55
+ "defined in :pep:`621`).",
56
+ "**DISCOURAGED**: generic script wrappers are tricky and may not work properly.",
57
+ "Whenever possible, please use ``project.scripts`` instead."
58
+ ],
59
+ "type": "array",
60
+ "items": {"type": "string"},
61
+ "$comment": "TODO: is this field deprecated/should be removed?"
62
+ },
63
+ "eager-resources": {
64
+ "$$description": [
65
+ "Resources that should be extracted together, if any of them is needed,",
66
+ "or if any C extensions included in the project are imported.",
67
+ "**OBSOLETE**: only relevant for ``pkg_resources``, ``easy_install`` and",
68
+ "``setup.py install`` in the context of ``eggs`` (**DEPRECATED**)."
69
+ ],
70
+ "type": "array",
71
+ "items": {"type": "string"}
72
+ },
73
+ "packages": {
74
+ "$$description": [
75
+ "Packages that should be included in the distribution.",
76
+ "It can be given either as a list of package identifiers",
77
+ "or as a ``dict``-like structure with a single key ``find``",
78
+ "which corresponds to a dynamic call to",
79
+ "``setuptools.config.expand.find_packages`` function.",
80
+ "The ``find`` key is associated with a nested ``dict``-like structure that can",
81
+ "contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,",
82
+ "mimicking the keyword arguments of the associated function."
83
+ ],
84
+ "oneOf": [
85
+ {
86
+ "title": "Array of Python package identifiers",
87
+ "type": "array",
88
+ "items": {"$ref": "#/definitions/package-name"}
89
+ },
90
+ {"$ref": "#/definitions/find-directive"}
91
+ ]
92
+ },
93
+ "package-dir": {
94
+ "$$description": [
95
+ ":class:`dict`-like structure mapping from package names to directories where their",
96
+ "code can be found.",
97
+ "The empty string (as key) means that all packages are contained inside",
98
+ "the given directory will be included in the distribution."
99
+ ],
100
+ "type": "object",
101
+ "additionalProperties": false,
102
+ "propertyNames": {
103
+ "anyOf": [{"const": ""}, {"$ref": "#/definitions/package-name"}]
104
+ },
105
+ "patternProperties": {
106
+ "^.*$": {"type": "string" }
107
+ }
108
+ },
109
+ "package-data": {
110
+ "$$description": [
111
+ "Mapping from package names to lists of glob patterns.",
112
+ "Usually this option is not needed when using ``include-package-data = true``",
113
+ "For more information on how to include data files, check ``setuptools`` `docs",
114
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
115
+ ],
116
+ "type": "object",
117
+ "additionalProperties": false,
118
+ "propertyNames": {
119
+ "anyOf": [{"$ref": "#/definitions/package-name"}, {"const": "*"}]
120
+ },
121
+ "patternProperties": {
122
+ "^.*$": {"type": "array", "items": {"type": "string"}}
123
+ }
124
+ },
125
+ "include-package-data": {
126
+ "$$description": [
127
+ "Automatically include any data files inside the package directories",
128
+ "that are specified by ``MANIFEST.in``",
129
+ "For more information on how to include data files, check ``setuptools`` `docs",
130
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
131
+ ],
132
+ "type": "boolean"
133
+ },
134
+ "exclude-package-data": {
135
+ "$$description": [
136
+ "Mapping from package names to lists of glob patterns that should be excluded",
137
+ "For more information on how to include data files, check ``setuptools`` `docs",
138
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
139
+ ],
140
+ "type": "object",
141
+ "additionalProperties": false,
142
+ "propertyNames": {
143
+ "anyOf": [{"$ref": "#/definitions/package-name"}, {"const": "*"}]
144
+ },
145
+ "patternProperties": {
146
+ "^.*$": {"type": "array", "items": {"type": "string"}}
147
+ }
148
+ },
149
+ "namespace-packages": {
150
+ "type": "array",
151
+ "items": {"type": "string", "format": "python-module-name-relaxed"},
152
+ "$comment": "https://setuptools.pypa.io/en/latest/userguide/package_discovery.html",
153
+ "description": "**DEPRECATED**: use implicit namespaces instead (:pep:`420`)."
154
+ },
155
+ "py-modules": {
156
+ "description": "Modules that setuptools will manipulate",
157
+ "type": "array",
158
+ "items": {"type": "string", "format": "python-module-name-relaxed"},
159
+ "$comment": "TODO: clarify the relationship with ``packages``"
160
+ },
161
+ "ext-modules": {
162
+ "description": "Extension modules to be compiled by setuptools",
163
+ "type": "array",
164
+ "items": {"$ref": "#/definitions/ext-module"}
165
+ },
166
+ "data-files": {
167
+ "$$description": [
168
+ "``dict``-like structure where each key represents a directory and",
169
+ "the value is a list of glob patterns that should be installed in them.",
170
+ "**DISCOURAGED**: please notice this might not work as expected with wheels.",
171
+ "Whenever possible, consider using data files inside the package directories",
172
+ "(or create a new namespace package that only contains data files).",
173
+ "See `data files support",
174
+ "<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_."
175
+ ],
176
+ "type": "object",
177
+ "patternProperties": {
178
+ "^.*$": {"type": "array", "items": {"type": "string"}}
179
+ }
180
+ },
181
+ "cmdclass": {
182
+ "$$description": [
183
+ "Mapping of distutils-style command names to ``setuptools.Command`` subclasses",
184
+ "which in turn should be represented by strings with a qualified class name",
185
+ "(i.e., \"dotted\" form with module), e.g.::\n\n",
186
+ " cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\n\n",
187
+ "The command class should be a directly defined at the top-level of the",
188
+ "containing module (no class nesting)."
189
+ ],
190
+ "type": "object",
191
+ "patternProperties": {
192
+ "^.*$": {"type": "string", "format": "python-qualified-identifier"}
193
+ }
194
+ },
195
+ "license-files": {
196
+ "type": "array",
197
+ "items": {"type": "string"},
198
+ "$$description": [
199
+ "**PROVISIONAL**: list of glob patterns for all license files being distributed.",
200
+ "(likely to become standard with :pep:`639`).",
201
+ "By default: ``['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']``"
202
+ ],
203
+ "$comment": "TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?"
204
+ },
205
+ "dynamic": {
206
+ "type": "object",
207
+ "description": "Instructions for loading :pep:`621`-related metadata dynamically",
208
+ "additionalProperties": false,
209
+ "properties": {
210
+ "version": {
211
+ "$$description": [
212
+ "A version dynamically loaded via either the ``attr:`` or ``file:``",
213
+ "directives. Please make sure the given file or attribute respects :pep:`440`.",
214
+ "Also ensure to set ``project.dynamic`` accordingly."
215
+ ],
216
+ "oneOf": [
217
+ {"$ref": "#/definitions/attr-directive"},
218
+ {"$ref": "#/definitions/file-directive"}
219
+ ]
220
+ },
221
+ "classifiers": {"$ref": "#/definitions/file-directive"},
222
+ "description": {"$ref": "#/definitions/file-directive"},
223
+ "entry-points": {"$ref": "#/definitions/file-directive"},
224
+ "dependencies": {"$ref": "#/definitions/file-directive-for-dependencies"},
225
+ "optional-dependencies": {
226
+ "type": "object",
227
+ "propertyNames": {"type": "string", "format": "pep508-identifier"},
228
+ "additionalProperties": false,
229
+ "patternProperties": {
230
+ ".+": {"$ref": "#/definitions/file-directive-for-dependencies"}
231
+ }
232
+ },
233
+ "readme": {
234
+ "type": "object",
235
+ "anyOf": [
236
+ {"$ref": "#/definitions/file-directive"},
237
+ {
238
+ "type": "object",
239
+ "properties": {
240
+ "content-type": {"type": "string"},
241
+ "file": { "$ref": "#/definitions/file-directive/properties/file" }
242
+ },
243
+ "additionalProperties": false}
244
+ ],
245
+ "required": ["file"]
246
+ }
247
+ }
248
+ }
249
+ },
250
+
251
+ "definitions": {
252
+ "package-name": {
253
+ "$id": "#/definitions/package-name",
254
+ "title": "Valid package name",
255
+ "description": "Valid package name (importable or :pep:`561`).",
256
+ "type": "string",
257
+ "anyOf": [
258
+ {"type": "string", "format": "python-module-name-relaxed"},
259
+ {"type": "string", "format": "pep561-stub-name"}
260
+ ]
261
+ },
262
+ "ext-module": {
263
+ "$id": "#/definitions/ext-module",
264
+ "title": "Extension module",
265
+ "description": "Parameters to construct a :class:`setuptools.Extension` object",
266
+ "type": "object",
267
+ "required": ["name", "sources"],
268
+ "additionalProperties": false,
269
+ "properties": {
270
+ "name": {
271
+ "type": "string",
272
+ "format": "python-module-name-relaxed"
273
+ },
274
+ "sources": {
275
+ "type": "array",
276
+ "items": {"type": "string"}
277
+ },
278
+ "include-dirs":{
279
+ "type": "array",
280
+ "items": {"type": "string"}
281
+ },
282
+ "define-macros": {
283
+ "type": "array",
284
+ "items": {
285
+ "type": "array",
286
+ "items": [
287
+ {"description": "macro name", "type": "string"},
288
+ {"description": "macro value", "oneOf": [{"type": "string"}, {"type": "null"}]}
289
+ ],
290
+ "additionalItems": false
291
+ }
292
+ },
293
+ "undef-macros": {
294
+ "type": "array",
295
+ "items": {"type": "string"}
296
+ },
297
+ "library-dirs": {
298
+ "type": "array",
299
+ "items": {"type": "string"}
300
+ },
301
+ "libraries": {
302
+ "type": "array",
303
+ "items": {"type": "string"}
304
+ },
305
+ "runtime-library-dirs": {
306
+ "type": "array",
307
+ "items": {"type": "string"}
308
+ },
309
+ "extra-objects": {
310
+ "type": "array",
311
+ "items": {"type": "string"}
312
+ },
313
+ "extra-compile-args": {
314
+ "type": "array",
315
+ "items": {"type": "string"}
316
+ },
317
+ "extra-link-args": {
318
+ "type": "array",
319
+ "items": {"type": "string"}
320
+ },
321
+ "export-symbols": {
322
+ "type": "array",
323
+ "items": {"type": "string"}
324
+ },
325
+ "swig-opts": {
326
+ "type": "array",
327
+ "items": {"type": "string"}
328
+ },
329
+ "depends": {
330
+ "type": "array",
331
+ "items": {"type": "string"}
332
+ },
333
+ "language": {"type": "string"},
334
+ "optional": {"type": "boolean"},
335
+ "py-limited-api": {"type": "boolean"}
336
+ }
337
+ },
338
+ "file-directive": {
339
+ "$id": "#/definitions/file-directive",
340
+ "title": "'file:' directive",
341
+ "description":
342
+ "Value is read from a file (or list of files and then concatenated)",
343
+ "type": "object",
344
+ "additionalProperties": false,
345
+ "properties": {
346
+ "file": {
347
+ "oneOf": [
348
+ {"type": "string"},
349
+ {"type": "array", "items": {"type": "string"}}
350
+ ]
351
+ }
352
+ },
353
+ "required": ["file"]
354
+ },
355
+ "file-directive-for-dependencies": {
356
+ "title": "'file:' directive for dependencies",
357
+ "allOf": [
358
+ {
359
+ "$$description": [
360
+ "**BETA**: subset of the ``requirements.txt`` format",
361
+ "without ``pip`` flags and options",
362
+ "(one :pep:`508`-compliant string per line,",
363
+ "lines that are blank or start with ``#`` are excluded).",
364
+ "See `dynamic metadata",
365
+ "<https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#dynamic-metadata>`_."
366
+ ]
367
+ },
368
+ {"$ref": "#/definitions/file-directive"}
369
+ ]
370
+ },
371
+ "attr-directive": {
372
+ "title": "'attr:' directive",
373
+ "$id": "#/definitions/attr-directive",
374
+ "$$description": [
375
+ "Value is read from a module attribute. Supports callables and iterables;",
376
+ "unsupported types are cast via ``str()``"
377
+ ],
378
+ "type": "object",
379
+ "additionalProperties": false,
380
+ "properties": {
381
+ "attr": {"type": "string", "format": "python-qualified-identifier"}
382
+ },
383
+ "required": ["attr"]
384
+ },
385
+ "find-directive": {
386
+ "$id": "#/definitions/find-directive",
387
+ "title": "'find:' directive",
388
+ "type": "object",
389
+ "additionalProperties": false,
390
+ "properties": {
391
+ "find": {
392
+ "type": "object",
393
+ "$$description": [
394
+ "Dynamic `package discovery",
395
+ "<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_."
396
+ ],
397
+ "additionalProperties": false,
398
+ "properties": {
399
+ "where": {
400
+ "description":
401
+ "Directories to be searched for packages (Unix-style relative path)",
402
+ "type": "array",
403
+ "items": {"type": "string"}
404
+ },
405
+ "exclude": {
406
+ "type": "array",
407
+ "$$description": [
408
+ "Exclude packages that match the values listed in this field.",
409
+ "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
410
+ ],
411
+ "items": {"type": "string"}
412
+ },
413
+ "include": {
414
+ "type": "array",
415
+ "$$description": [
416
+ "Restrict the found packages to just the ones listed in this field.",
417
+ "Can container shell-style wildcards (e.g. ``'pkg.*'``)"
418
+ ],
419
+ "items": {"type": "string"}
420
+ },
421
+ "namespaces": {
422
+ "type": "boolean",
423
+ "$$description": [
424
+ "When ``True``, directories without a ``__init__.py`` file will also",
425
+ "be scanned for :pep:`420`-style implicit namespaces"
426
+ ]
427
+ }
428
+ }
429
+ }
430
+ }
431
+ }
432
+ }
433
+ }
python/Lib/site-packages/setuptools/tests/contexts.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import io
3
+ import os
4
+ import shutil
5
+ import site
6
+ import sys
7
+ import tempfile
8
+
9
+ from filelock import FileLock
10
+
11
+
12
+ @contextlib.contextmanager
13
+ def tempdir(cd=lambda dir: None, **kwargs):
14
+ temp_dir = tempfile.mkdtemp(**kwargs)
15
+ orig_dir = os.getcwd()
16
+ try:
17
+ cd(temp_dir)
18
+ yield temp_dir
19
+ finally:
20
+ cd(orig_dir)
21
+ shutil.rmtree(temp_dir)
22
+
23
+
24
+ @contextlib.contextmanager
25
+ def environment(**replacements):
26
+ """
27
+ In a context, patch the environment with replacements. Pass None values
28
+ to clear the values.
29
+ """
30
+ saved = dict((key, os.environ[key]) for key in replacements if key in os.environ)
31
+
32
+ # remove values that are null
33
+ remove = (key for (key, value) in replacements.items() if value is None)
34
+ for key in list(remove):
35
+ os.environ.pop(key, None)
36
+ replacements.pop(key)
37
+
38
+ os.environ.update(replacements)
39
+
40
+ try:
41
+ yield saved
42
+ finally:
43
+ for key in replacements:
44
+ os.environ.pop(key, None)
45
+ os.environ.update(saved)
46
+
47
+
48
+ @contextlib.contextmanager
49
+ def quiet():
50
+ """
51
+ Redirect stdout/stderr to StringIO objects to prevent console output from
52
+ distutils commands.
53
+ """
54
+
55
+ old_stdout = sys.stdout
56
+ old_stderr = sys.stderr
57
+ new_stdout = sys.stdout = io.StringIO()
58
+ new_stderr = sys.stderr = io.StringIO()
59
+ try:
60
+ yield new_stdout, new_stderr
61
+ finally:
62
+ new_stdout.seek(0)
63
+ new_stderr.seek(0)
64
+ sys.stdout = old_stdout
65
+ sys.stderr = old_stderr
66
+
67
+
68
+ @contextlib.contextmanager
69
+ def save_user_site_setting():
70
+ saved = site.ENABLE_USER_SITE
71
+ try:
72
+ yield saved
73
+ finally:
74
+ site.ENABLE_USER_SITE = saved
75
+
76
+
77
+ @contextlib.contextmanager
78
+ def suppress_exceptions(*excs):
79
+ try:
80
+ yield
81
+ except excs:
82
+ pass
83
+
84
+
85
+ def multiproc(request):
86
+ """
87
+ Return True if running under xdist and multiple
88
+ workers are used.
89
+ """
90
+ try:
91
+ worker_id = request.getfixturevalue('worker_id')
92
+ except Exception:
93
+ return False
94
+ return worker_id != 'master'
95
+
96
+
97
+ @contextlib.contextmanager
98
+ def session_locked_tmp_dir(request, tmp_path_factory, name):
99
+ """Uses a file lock to guarantee only one worker can access a temp dir"""
100
+ # get the temp directory shared by all workers
101
+ base = tmp_path_factory.getbasetemp()
102
+ shared_dir = base.parent if multiproc(request) else base
103
+
104
+ locked_dir = shared_dir / name
105
+ with FileLock(locked_dir.with_suffix(".lock")):
106
+ # ^-- prevent multiple workers to access the directory at once
107
+ locked_dir.mkdir(exist_ok=True, parents=True)
108
+ yield locked_dir
109
+
110
+
111
+ @contextlib.contextmanager
112
+ def save_paths():
113
+ """Make sure ``sys.path``, ``sys.meta_path`` and ``sys.path_hooks`` are preserved"""
114
+ prev = sys.path[:], sys.meta_path[:], sys.path_hooks[:]
115
+
116
+ try:
117
+ yield
118
+ finally:
119
+ sys.path, sys.meta_path, sys.path_hooks = prev
120
+
121
+
122
+ @contextlib.contextmanager
123
+ def save_sys_modules():
124
+ """Make sure initial ``sys.modules`` is preserved"""
125
+ prev_modules = sys.modules
126
+
127
+ try:
128
+ sys.modules = sys.modules.copy()
129
+ yield
130
+ finally:
131
+ sys.modules = prev_modules
python/Lib/site-packages/setuptools/tests/environment.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ import unicodedata
5
+ from subprocess import PIPE as _PIPE, Popen as _Popen
6
+
7
+ import jaraco.envs
8
+
9
+
10
+ class VirtualEnv(jaraco.envs.VirtualEnv):
11
+ name = '.env'
12
+ # Some version of PyPy will import distutils on startup, implicitly
13
+ # importing setuptools, and thus leading to BackendInvalid errors
14
+ # when upgrading Setuptools. Bypass this behavior by avoiding the
15
+ # early availability and need to upgrade.
16
+ create_opts = ['--no-setuptools']
17
+
18
+ def run(self, cmd, *args, **kwargs):
19
+ cmd = [self.exe(cmd[0])] + cmd[1:]
20
+ kwargs = {"cwd": self.root, "encoding": "utf-8", **kwargs} # Allow overriding
21
+ # In some environments (eg. downstream distro packaging), where:
22
+ # - tox isn't used to run tests and
23
+ # - PYTHONPATH is set to point to a specific setuptools codebase and
24
+ # - no custom env is explicitly set by a test
25
+ # PYTHONPATH will leak into the spawned processes.
26
+ # In that case tests look for module in the wrong place (on PYTHONPATH).
27
+ # Unless the test sets its own special env, pass a copy of the existing
28
+ # environment with removed PYTHONPATH to the subprocesses.
29
+ if "env" not in kwargs:
30
+ env = dict(os.environ)
31
+ if "PYTHONPATH" in env:
32
+ del env["PYTHONPATH"]
33
+ kwargs["env"] = env
34
+ return subprocess.check_output(cmd, *args, **kwargs)
35
+
36
+
37
+ def _which_dirs(cmd):
38
+ result = set()
39
+ for path in os.environ.get('PATH', '').split(os.pathsep):
40
+ filename = os.path.join(path, cmd)
41
+ if os.access(filename, os.X_OK):
42
+ result.add(path)
43
+ return result
44
+
45
+
46
+ def run_setup_py(cmd, pypath=None, path=None, data_stream=0, env=None):
47
+ """
48
+ Execution command for tests, separate from those used by the
49
+ code directly to prevent accidental behavior issues
50
+ """
51
+ if env is None:
52
+ env = dict()
53
+ for envname in os.environ:
54
+ env[envname] = os.environ[envname]
55
+
56
+ # override the python path if needed
57
+ if pypath is not None:
58
+ env["PYTHONPATH"] = pypath
59
+
60
+ # override the execution path if needed
61
+ if path is not None:
62
+ env["PATH"] = path
63
+ if not env.get("PATH", ""):
64
+ env["PATH"] = _which_dirs("tar").union(_which_dirs("gzip"))
65
+ env["PATH"] = os.pathsep.join(env["PATH"])
66
+
67
+ cmd = [sys.executable, "setup.py"] + list(cmd)
68
+
69
+ # https://bugs.python.org/issue8557
70
+ shell = sys.platform == 'win32'
71
+
72
+ try:
73
+ proc = _Popen(
74
+ cmd,
75
+ stdout=_PIPE,
76
+ stderr=_PIPE,
77
+ shell=shell,
78
+ env=env,
79
+ encoding="utf-8",
80
+ )
81
+
82
+ if isinstance(data_stream, tuple):
83
+ data_stream = slice(*data_stream)
84
+ data = proc.communicate()[data_stream]
85
+ except OSError:
86
+ return 1, ''
87
+
88
+ # decode the console string if needed
89
+ if hasattr(data, "decode"):
90
+ # use the default encoding
91
+ data = data.decode()
92
+ data = unicodedata.normalize('NFC', data)
93
+
94
+ # communicate calls wait()
95
+ return proc.returncode, data
python/Lib/site-packages/setuptools/tests/fixtures.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import io
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ import tarfile
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import jaraco.path
11
+ import path
12
+ import pytest
13
+
14
+ from setuptools._normalization import safer_name
15
+
16
+ from . import contexts, environment
17
+ from .textwrap import DALS
18
+
19
+
20
+ @pytest.fixture
21
+ def user_override(monkeypatch):
22
+ """
23
+ Override site.USER_BASE and site.USER_SITE with temporary directories in
24
+ a context.
25
+ """
26
+ with contexts.tempdir() as user_base:
27
+ monkeypatch.setattr('site.USER_BASE', user_base)
28
+ with contexts.tempdir() as user_site:
29
+ monkeypatch.setattr('site.USER_SITE', user_site)
30
+ with contexts.save_user_site_setting():
31
+ yield
32
+
33
+
34
+ @pytest.fixture
35
+ def tmpdir_cwd(tmpdir):
36
+ with tmpdir.as_cwd() as orig:
37
+ yield orig
38
+
39
+
40
+ @pytest.fixture(autouse=True, scope="session")
41
+ def workaround_xdist_376(request):
42
+ """
43
+ Workaround pytest-dev/pytest-xdist#376
44
+
45
+ ``pytest-xdist`` tends to inject '' into ``sys.path``,
46
+ which may break certain isolation expectations.
47
+ Remove the entry so the import
48
+ machinery behaves the same irrespective of xdist.
49
+ """
50
+ if not request.config.pluginmanager.has_plugin('xdist'):
51
+ return
52
+
53
+ with contextlib.suppress(ValueError):
54
+ sys.path.remove('')
55
+
56
+
57
+ @pytest.fixture
58
+ def sample_project(tmp_path):
59
+ """
60
+ Clone the 'sampleproject' and return a path to it.
61
+ """
62
+ cmd = ['git', 'clone', 'https://github.com/pypa/sampleproject']
63
+ try:
64
+ subprocess.check_call(cmd, cwd=str(tmp_path))
65
+ except Exception:
66
+ pytest.skip("Unable to clone sampleproject")
67
+ return tmp_path / 'sampleproject'
68
+
69
+
70
+ @pytest.fixture
71
+ def sample_project_cwd(sample_project):
72
+ with path.Path(sample_project):
73
+ yield
74
+
75
+
76
+ # sdist and wheel artifacts should be stable across a round of tests
77
+ # so we can build them once per session and use the files as "readonly"
78
+
79
+ # In the case of setuptools, building the wheel without sdist may cause
80
+ # it to contain the `build` directory, and therefore create situations with
81
+ # `setuptools/build/lib/build/lib/...`. To avoid that, build both artifacts at once.
82
+
83
+
84
+ def _build_distributions(tmp_path_factory, request):
85
+ with contexts.session_locked_tmp_dir(
86
+ request, tmp_path_factory, "dist_build"
87
+ ) as tmp: # pragma: no cover
88
+ sdist = next(tmp.glob("*.tar.gz"), None)
89
+ wheel = next(tmp.glob("*.whl"), None)
90
+ if sdist and wheel:
91
+ return (sdist, wheel)
92
+
93
+ # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
94
+ assert not Path(request.config.rootdir, "build/lib/build").exists()
95
+
96
+ subprocess.check_output([
97
+ sys.executable,
98
+ "-m",
99
+ "build",
100
+ "--outdir",
101
+ str(tmp),
102
+ str(request.config.rootdir),
103
+ ])
104
+
105
+ # Sanity check: should not create recursive setuptools/build/lib/build/lib/...
106
+ assert not Path(request.config.rootdir, "build/lib/build").exists()
107
+
108
+ return next(tmp.glob("*.tar.gz")), next(tmp.glob("*.whl"))
109
+
110
+
111
+ @pytest.fixture(scope="session")
112
+ def setuptools_sdist(tmp_path_factory, request):
113
+ prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_SDIST")
114
+ if prebuilt and os.path.exists(prebuilt): # pragma: no cover
115
+ return Path(prebuilt).resolve()
116
+
117
+ sdist, _ = _build_distributions(tmp_path_factory, request)
118
+ return sdist
119
+
120
+
121
+ @pytest.fixture(scope="session")
122
+ def setuptools_wheel(tmp_path_factory, request):
123
+ prebuilt = os.getenv("PRE_BUILT_SETUPTOOLS_WHEEL")
124
+ if prebuilt and os.path.exists(prebuilt): # pragma: no cover
125
+ return Path(prebuilt).resolve()
126
+
127
+ _, wheel = _build_distributions(tmp_path_factory, request)
128
+ return wheel
129
+
130
+
131
+ @pytest.fixture
132
+ def venv(tmp_path, setuptools_wheel):
133
+ """Virtual env with the version of setuptools under test installed"""
134
+ env = environment.VirtualEnv()
135
+ env.root = path.Path(tmp_path / 'venv')
136
+ env.create_opts = ['--no-setuptools', '--wheel=bundle']
137
+ # TODO: Use `--no-wheel` when setuptools implements its own bdist_wheel
138
+ env.req = str(setuptools_wheel)
139
+ # In some environments (eg. downstream distro packaging),
140
+ # where tox isn't used to run tests and PYTHONPATH is set to point to
141
+ # a specific setuptools codebase, PYTHONPATH will leak into the spawned
142
+ # processes.
143
+ # env.create() should install the just created setuptools
144
+ # wheel, but it doesn't if it finds another existing matching setuptools
145
+ # installation present on PYTHONPATH:
146
+ # `setuptools is already installed with the same version as the provided
147
+ # wheel. Use --force-reinstall to force an installation of the wheel.`
148
+ # This prevents leaking PYTHONPATH to the created environment.
149
+ with contexts.environment(PYTHONPATH=None):
150
+ return env.create()
151
+
152
+
153
+ @pytest.fixture
154
+ def venv_without_setuptools(tmp_path):
155
+ """Virtual env without any version of setuptools installed"""
156
+ env = environment.VirtualEnv()
157
+ env.root = path.Path(tmp_path / 'venv_without_setuptools')
158
+ env.create_opts = ['--no-setuptools', '--no-wheel']
159
+ env.ensure_env()
160
+ return env
161
+
162
+
163
+ @pytest.fixture
164
+ def bare_venv(tmp_path):
165
+ """Virtual env without any common packages installed"""
166
+ env = environment.VirtualEnv()
167
+ env.root = path.Path(tmp_path / 'bare_venv')
168
+ env.create_opts = ['--no-setuptools', '--no-pip', '--no-wheel', '--no-seed']
169
+ env.ensure_env()
170
+ return env
171
+
172
+
173
+ def make_sdist(dist_path, files):
174
+ """
175
+ Create a simple sdist tarball at dist_path, containing the files
176
+ listed in ``files`` as ``(filename, content)`` tuples.
177
+ """
178
+
179
+ # Distributions with only one file don't play well with pip.
180
+ assert len(files) > 1
181
+ with tarfile.open(dist_path, 'w:gz') as dist:
182
+ for filename, content in files:
183
+ file_bytes = io.BytesIO(content.encode('utf-8'))
184
+ file_info = tarfile.TarInfo(name=filename)
185
+ file_info.size = len(file_bytes.getvalue())
186
+ file_info.mtime = int(time.time())
187
+ dist.addfile(file_info, fileobj=file_bytes)
188
+
189
+
190
+ def make_trivial_sdist(dist_path, distname, version, setuptools_wheel=None):
191
+ """
192
+ Create a simple sdist tarball at dist_path, containing just a simple
193
+ setup.py.
194
+
195
+ If ``setuptools_wheel`` is passed, a ``pyproject.toml`` file will also
196
+ be generated and the passed value will be used as location for
197
+ setuptools (as build dependency).
198
+ """
199
+ files = [
200
+ (
201
+ 'setup.py',
202
+ DALS(
203
+ f"""\
204
+ import setuptools
205
+ setuptools.setup(
206
+ name={distname!r},
207
+ version={version!r}
208
+ )
209
+ """
210
+ ),
211
+ ),
212
+ ('setup.cfg', ''),
213
+ ]
214
+
215
+ if setuptools_wheel:
216
+ files.append((
217
+ "pyproject.toml",
218
+ DALS(
219
+ f"""\
220
+ [build-system]
221
+ requires = ["setuptools @ {setuptools_wheel.as_uri()}"]
222
+ build-backend = "setuptools.build_meta"
223
+ """
224
+ ),
225
+ ))
226
+
227
+ make_sdist(dist_path, files)
228
+
229
+
230
+ def make_nspkg_sdist(dist_path, distname, version):
231
+ """
232
+ Make an sdist tarball with distname and version which also contains one
233
+ package with the same name as distname. The top-level package is
234
+ designated a namespace package).
235
+ """
236
+ # Assert that the distname contains at least one period
237
+ assert '.' in distname
238
+
239
+ parts = distname.split('.')
240
+ nspackage = parts[0]
241
+
242
+ packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)]
243
+
244
+ setup_py = DALS(
245
+ f"""\
246
+ import setuptools
247
+ setuptools.setup(
248
+ name={distname!r},
249
+ version={version!r},
250
+ packages={packages!r},
251
+ namespace_packages=[{nspackage!r}]
252
+ )
253
+ """
254
+ )
255
+
256
+ init = "__import__('pkg_resources').declare_namespace(__name__)"
257
+
258
+ files = [('setup.py', setup_py), (os.path.join(nspackage, '__init__.py'), init)]
259
+ for package in packages[1:]:
260
+ filename = os.path.join(*(package.split('.') + ['__init__.py']))
261
+ files.append((filename, ''))
262
+
263
+ make_sdist(dist_path, files)
264
+
265
+
266
+ def make_python_requires_sdist(dist_path, distname, version, python_requires):
267
+ make_sdist(
268
+ dist_path,
269
+ [
270
+ (
271
+ 'setup.py',
272
+ DALS(
273
+ """\
274
+ import setuptools
275
+ setuptools.setup(
276
+ name={name!r},
277
+ version={version!r},
278
+ python_requires={python_requires!r},
279
+ )
280
+ """
281
+ ).format(
282
+ name=distname, version=version, python_requires=python_requires
283
+ ),
284
+ ),
285
+ ('setup.cfg', ''),
286
+ ],
287
+ )
288
+
289
+
290
+ def create_setup_requires_package(
291
+ path,
292
+ distname='foobar',
293
+ version='0.1',
294
+ make_package=make_trivial_sdist,
295
+ setup_py_template=None,
296
+ setup_attrs=None,
297
+ use_setup_cfg=(),
298
+ ):
299
+ """Creates a source tree under path for a trivial test package that has a
300
+ single requirement in setup_requires--a tarball for that requirement is
301
+ also created and added to the dependency_links argument.
302
+
303
+ ``distname`` and ``version`` refer to the name/version of the package that
304
+ the test package requires via ``setup_requires``. The name of the test
305
+ package itself is just 'test_pkg'.
306
+ """
307
+
308
+ normalized_distname = safer_name(distname)
309
+ test_setup_attrs = {
310
+ 'name': 'test_pkg',
311
+ 'version': '0.0',
312
+ 'setup_requires': [f'{normalized_distname}=={version}'],
313
+ 'dependency_links': [os.path.abspath(path)],
314
+ }
315
+ if setup_attrs:
316
+ test_setup_attrs.update(setup_attrs)
317
+
318
+ test_pkg = os.path.join(path, 'test_pkg')
319
+ os.mkdir(test_pkg)
320
+
321
+ # setup.cfg
322
+ if use_setup_cfg:
323
+ options = []
324
+ metadata = []
325
+ for name in use_setup_cfg:
326
+ value = test_setup_attrs.pop(name)
327
+ if name in 'name version'.split():
328
+ section = metadata
329
+ else:
330
+ section = options
331
+ if isinstance(value, (tuple, list)):
332
+ value = ';'.join(value)
333
+ section.append(f'{name}: {value}')
334
+ test_setup_cfg_contents = DALS(
335
+ """
336
+ [metadata]
337
+ {metadata}
338
+ [options]
339
+ {options}
340
+ """
341
+ ).format(
342
+ options='\n'.join(options),
343
+ metadata='\n'.join(metadata),
344
+ )
345
+ else:
346
+ test_setup_cfg_contents = ''
347
+ with open(os.path.join(test_pkg, 'setup.cfg'), 'w', encoding="utf-8") as f:
348
+ f.write(test_setup_cfg_contents)
349
+
350
+ # setup.py
351
+ if setup_py_template is None:
352
+ setup_py_template = DALS(
353
+ """\
354
+ import setuptools
355
+ setuptools.setup(**%r)
356
+ """
357
+ )
358
+ with open(os.path.join(test_pkg, 'setup.py'), 'w', encoding="utf-8") as f:
359
+ f.write(setup_py_template % test_setup_attrs)
360
+
361
+ foobar_path = os.path.join(path, f'{normalized_distname}-{version}.tar.gz')
362
+ make_package(foobar_path, distname, version)
363
+
364
+ return test_pkg
365
+
366
+
367
+ @pytest.fixture
368
+ def pbr_package(tmp_path, monkeypatch, venv):
369
+ files = {
370
+ "pyproject.toml": DALS(
371
+ """
372
+ [build-system]
373
+ requires = ["setuptools"]
374
+ build-backend = "setuptools.build_meta"
375
+ """
376
+ ),
377
+ "setup.py": DALS(
378
+ """
379
+ __import__('setuptools').setup(
380
+ pbr=True,
381
+ setup_requires=["pbr"],
382
+ )
383
+ """
384
+ ),
385
+ "setup.cfg": DALS(
386
+ """
387
+ [metadata]
388
+ name = mypkg
389
+
390
+ [files]
391
+ packages =
392
+ mypkg
393
+ """
394
+ ),
395
+ "mypkg": {
396
+ "__init__.py": "",
397
+ "hello.py": "print('Hello world!')",
398
+ },
399
+ "other": {"test.txt": "Another file in here."},
400
+ }
401
+ venv.run(["python", "-m", "pip", "install", "pbr"])
402
+ prefix = tmp_path / 'mypkg'
403
+ prefix.mkdir()
404
+ jaraco.path.build(files, prefix=prefix)
405
+ monkeypatch.setenv('PBR_VERSION', "0.42")
406
+ return prefix
python/Lib/site-packages/setuptools/tests/mod_with_constant.py ADDED
@@ -0,0 +1 @@
 
 
1
+ value = 'three, sir!'
python/Lib/site-packages/setuptools/tests/namespaces.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ import textwrap
4
+ from pathlib import Path
5
+
6
+
7
+ def iter_namespace_pkgs(namespace):
8
+ parts = namespace.split(".")
9
+ for i in range(len(parts)):
10
+ yield ".".join(parts[: i + 1])
11
+
12
+
13
+ def build_namespace_package(tmpdir, name, version="1.0", impl="pkg_resources"):
14
+ src_dir = tmpdir / name
15
+ src_dir.mkdir()
16
+ setup_py = src_dir / 'setup.py'
17
+ namespace, _, rest = name.rpartition('.')
18
+ namespaces = list(iter_namespace_pkgs(namespace))
19
+ setup_args = {
20
+ "name": name,
21
+ "version": version,
22
+ "packages": namespaces,
23
+ }
24
+
25
+ if impl == "pkg_resources":
26
+ tmpl = '__import__("pkg_resources").declare_namespace(__name__)'
27
+ setup_args["namespace_packages"] = namespaces
28
+ elif impl == "pkgutil":
29
+ tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)'
30
+ else:
31
+ raise ValueError(f"Cannot recognise {impl=} when creating namespaces")
32
+
33
+ args = json.dumps(setup_args, indent=4)
34
+ assert ast.literal_eval(args) # ensure it is valid Python
35
+
36
+ script = textwrap.dedent(
37
+ """\
38
+ import setuptools
39
+ args = {args}
40
+ setuptools.setup(**args)
41
+ """
42
+ ).format(args=args)
43
+ setup_py.write_text(script, encoding='utf-8')
44
+
45
+ ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
46
+ ns_pkg_dir.mkdir(parents=True)
47
+
48
+ for ns in namespaces:
49
+ pkg_init = src_dir / ns.replace(".", "/") / '__init__.py'
50
+ pkg_init.write_text(tmpl, encoding='utf-8')
51
+
52
+ pkg_mod = ns_pkg_dir / (rest + '.py')
53
+ some_functionality = 'name = {rest!r}'.format(**locals())
54
+ pkg_mod.write_text(some_functionality, encoding='utf-8')
55
+ return src_dir
56
+
57
+
58
+ def build_pep420_namespace_package(tmpdir, name):
59
+ src_dir = tmpdir / name
60
+ src_dir.mkdir()
61
+ pyproject = src_dir / "pyproject.toml"
62
+ namespace, _, rest = name.rpartition(".")
63
+ script = f"""\
64
+ [build-system]
65
+ requires = ["setuptools"]
66
+ build-backend = "setuptools.build_meta"
67
+
68
+ [project]
69
+ name = "{name}"
70
+ version = "3.14159"
71
+ """
72
+ pyproject.write_text(textwrap.dedent(script), encoding='utf-8')
73
+ ns_pkg_dir = Path(src_dir, namespace.replace(".", "/"))
74
+ ns_pkg_dir.mkdir(parents=True)
75
+ pkg_mod = ns_pkg_dir / (rest + ".py")
76
+ some_functionality = f"name = {rest!r}"
77
+ pkg_mod.write_text(some_functionality, encoding='utf-8')
78
+ return src_dir
79
+
80
+
81
+ def make_site_dir(target):
82
+ """
83
+ Add a sitecustomize.py module in target to cause
84
+ target to be added to site dirs such that .pth files
85
+ are processed there.
86
+ """
87
+ sc = target / 'sitecustomize.py'
88
+ target_str = str(target)
89
+ tmpl = '__import__("site").addsitedir({target_str!r})'
90
+ sc.write_text(tmpl.format(**locals()), encoding='utf-8')
python/Lib/site-packages/setuptools/tests/script-with-bom.py ADDED
@@ -0,0 +1 @@
 
 
1
+ result = 'passed'
python/Lib/site-packages/setuptools/tests/test_archive_util.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import tarfile
3
+
4
+ import pytest
5
+
6
+ from setuptools import archive_util
7
+
8
+
9
+ @pytest.fixture
10
+ def tarfile_with_unicode(tmpdir):
11
+ """
12
+ Create a tarfile containing only a file whose name is
13
+ a zero byte file called testimäge.png.
14
+ """
15
+ tarobj = io.BytesIO()
16
+
17
+ with tarfile.open(fileobj=tarobj, mode="w:gz") as tgz:
18
+ data = b""
19
+
20
+ filename = "testimäge.png"
21
+
22
+ t = tarfile.TarInfo(filename)
23
+ t.size = len(data)
24
+
25
+ tgz.addfile(t, io.BytesIO(data))
26
+
27
+ target = tmpdir / 'unicode-pkg-1.0.tar.gz'
28
+ with open(str(target), mode='wb') as tf:
29
+ tf.write(tarobj.getvalue())
30
+ return str(target)
31
+
32
+
33
+ @pytest.mark.xfail(reason="#710 and #712")
34
+ def test_unicode_files(tarfile_with_unicode, tmpdir):
35
+ target = tmpdir / 'out'
36
+ archive_util.unpack_archive(tarfile_with_unicode, str(target))
python/Lib/site-packages/setuptools/tests/test_bdist_deprecations.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """develop tests"""
2
+
3
+ import sys
4
+ from unittest import mock
5
+
6
+ import pytest
7
+
8
+ from setuptools import SetuptoolsDeprecationWarning
9
+ from setuptools.dist import Distribution
10
+
11
+
12
+ @pytest.mark.skipif(sys.platform == 'win32', reason='non-Windows only')
13
+ @pytest.mark.xfail(reason="bdist_rpm is long deprecated, should we remove it? #1988")
14
+ @mock.patch('distutils.command.bdist_rpm.bdist_rpm')
15
+ def test_bdist_rpm_warning(distutils_cmd, tmpdir_cwd):
16
+ dist = Distribution(
17
+ dict(
18
+ script_name='setup.py',
19
+ script_args=['bdist_rpm'],
20
+ name='foo',
21
+ py_modules=['hi'],
22
+ )
23
+ )
24
+ dist.parse_command_line()
25
+ with pytest.warns(SetuptoolsDeprecationWarning):
26
+ dist.run_commands()
27
+
28
+ distutils_cmd.run.assert_called_once()
python/Lib/site-packages/setuptools/tests/test_bdist_egg.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """develop tests"""
2
+
3
+ import os
4
+ import re
5
+ import zipfile
6
+
7
+ import pytest
8
+
9
+ from setuptools.dist import Distribution
10
+
11
+ from . import contexts
12
+
13
+ SETUP_PY = """\
14
+ from setuptools import setup
15
+
16
+ setup(py_modules=['hi'])
17
+ """
18
+
19
+
20
+ @pytest.fixture
21
+ def setup_context(tmpdir):
22
+ with (tmpdir / 'setup.py').open('w') as f:
23
+ f.write(SETUP_PY)
24
+ with (tmpdir / 'hi.py').open('w') as f:
25
+ f.write('1\n')
26
+ with tmpdir.as_cwd():
27
+ yield tmpdir
28
+
29
+
30
+ class Test:
31
+ @pytest.mark.usefixtures("user_override")
32
+ @pytest.mark.usefixtures("setup_context")
33
+ def test_bdist_egg(self):
34
+ dist = Distribution(
35
+ dict(
36
+ script_name='setup.py',
37
+ script_args=['bdist_egg'],
38
+ name='foo',
39
+ py_modules=['hi'],
40
+ )
41
+ )
42
+ os.makedirs(os.path.join('build', 'src'))
43
+ with contexts.quiet():
44
+ dist.parse_command_line()
45
+ dist.run_commands()
46
+
47
+ # let's see if we got our egg link at the right place
48
+ [content] = os.listdir('dist')
49
+ assert re.match(r'foo-0.0.0-py[23].\d+.egg$', content)
50
+
51
+ @pytest.mark.xfail(
52
+ os.environ.get('PYTHONDONTWRITEBYTECODE', False),
53
+ reason="Byte code disabled",
54
+ )
55
+ @pytest.mark.usefixtures("user_override")
56
+ @pytest.mark.usefixtures("setup_context")
57
+ def test_exclude_source_files(self):
58
+ dist = Distribution(
59
+ dict(
60
+ script_name='setup.py',
61
+ script_args=['bdist_egg', '--exclude-source-files'],
62
+ py_modules=['hi'],
63
+ )
64
+ )
65
+ with contexts.quiet():
66
+ dist.parse_command_line()
67
+ dist.run_commands()
68
+ [dist_name] = os.listdir('dist')
69
+ dist_filename = os.path.join('dist', dist_name)
70
+ zip = zipfile.ZipFile(dist_filename)
71
+ names = list(zi.filename for zi in zip.filelist)
72
+ assert 'hi.pyc' in names
73
+ assert 'hi.py' not in names
python/Lib/site-packages/setuptools/tests/test_bdist_wheel.py ADDED
@@ -0,0 +1,708 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import builtins
4
+ import importlib
5
+ import os.path
6
+ import platform
7
+ import shutil
8
+ import stat
9
+ import struct
10
+ import sys
11
+ import sysconfig
12
+ from contextlib import suppress
13
+ from inspect import cleandoc
14
+ from zipfile import ZipFile
15
+
16
+ import jaraco.path
17
+ import pytest
18
+ from packaging import tags
19
+
20
+ import setuptools
21
+ from setuptools.command.bdist_wheel import bdist_wheel, get_abi_tag
22
+ from setuptools.dist import Distribution
23
+ from setuptools.warnings import SetuptoolsDeprecationWarning
24
+
25
+ from distutils.core import run_setup
26
+
27
+ DEFAULT_FILES = {
28
+ "dummy_dist-1.0.dist-info/top_level.txt",
29
+ "dummy_dist-1.0.dist-info/METADATA",
30
+ "dummy_dist-1.0.dist-info/WHEEL",
31
+ "dummy_dist-1.0.dist-info/RECORD",
32
+ }
33
+ DEFAULT_LICENSE_FILES = {
34
+ "LICENSE",
35
+ "LICENSE.txt",
36
+ "LICENCE",
37
+ "LICENCE.txt",
38
+ "COPYING",
39
+ "COPYING.md",
40
+ "NOTICE",
41
+ "NOTICE.rst",
42
+ "AUTHORS",
43
+ "AUTHORS.txt",
44
+ }
45
+ OTHER_IGNORED_FILES = {
46
+ "LICENSE~",
47
+ "AUTHORS~",
48
+ }
49
+ SETUPPY_EXAMPLE = """\
50
+ from setuptools import setup
51
+
52
+ setup(
53
+ name='dummy_dist',
54
+ version='1.0',
55
+ )
56
+ """
57
+
58
+
59
+ EXAMPLES = {
60
+ "dummy-dist": {
61
+ "setup.py": SETUPPY_EXAMPLE,
62
+ "licenses_dir": {"DUMMYFILE": ""},
63
+ **dict.fromkeys(DEFAULT_LICENSE_FILES | OTHER_IGNORED_FILES, ""),
64
+ },
65
+ "simple-dist": {
66
+ "setup.py": cleandoc(
67
+ """
68
+ from setuptools import setup
69
+
70
+ setup(
71
+ name="simple.dist",
72
+ version="0.1",
73
+ description="A testing distribution \N{SNOWMAN}",
74
+ extras_require={"voting": ["beaglevote"]},
75
+ )
76
+ """
77
+ ),
78
+ "simpledist": "",
79
+ },
80
+ "complex-dist": {
81
+ "setup.py": cleandoc(
82
+ """
83
+ from setuptools import setup
84
+
85
+ setup(
86
+ name="complex-dist",
87
+ version="0.1",
88
+ description="Another testing distribution \N{SNOWMAN}",
89
+ long_description="Another testing distribution \N{SNOWMAN}",
90
+ author="Illustrious Author",
91
+ author_email="illustrious@example.org",
92
+ url="http://example.org/exemplary",
93
+ packages=["complexdist"],
94
+ setup_requires=["setuptools"],
95
+ install_requires=["quux", "splort"],
96
+ extras_require={"simple": ["simple.dist"]},
97
+ entry_points={
98
+ "console_scripts": [
99
+ "complex-dist=complexdist:main",
100
+ "complex-dist2=complexdist:main",
101
+ ],
102
+ },
103
+ )
104
+ """
105
+ ),
106
+ "complexdist": {"__init__.py": "def main(): return"},
107
+ },
108
+ "headers-dist": {
109
+ "setup.py": cleandoc(
110
+ """
111
+ from setuptools import setup
112
+
113
+ setup(
114
+ name="headers.dist",
115
+ version="0.1",
116
+ description="A distribution with headers",
117
+ headers=["header.h"],
118
+ )
119
+ """
120
+ ),
121
+ "headersdist.py": "",
122
+ "header.h": "",
123
+ },
124
+ "commasinfilenames-dist": {
125
+ "setup.py": cleandoc(
126
+ """
127
+ from setuptools import setup
128
+
129
+ setup(
130
+ name="testrepo",
131
+ version="0.1",
132
+ packages=["mypackage"],
133
+ description="A test package with commas in file names",
134
+ include_package_data=True,
135
+ package_data={"mypackage.data": ["*"]},
136
+ )
137
+ """
138
+ ),
139
+ "mypackage": {
140
+ "__init__.py": "",
141
+ "data": {"__init__.py": "", "1,2,3.txt": ""},
142
+ },
143
+ "testrepo-0.1.0": {
144
+ "mypackage": {"__init__.py": ""},
145
+ },
146
+ },
147
+ "unicode-dist": {
148
+ "setup.py": cleandoc(
149
+ """
150
+ from setuptools import setup
151
+
152
+ setup(
153
+ name="unicode.dist",
154
+ version="0.1",
155
+ description="A testing distribution \N{SNOWMAN}",
156
+ packages=["unicodedist"],
157
+ zip_safe=True,
158
+ )
159
+ """
160
+ ),
161
+ "unicodedist": {"__init__.py": "", "åäö_日本語.py": ""},
162
+ },
163
+ "utf8-metadata-dist": {
164
+ "setup.cfg": cleandoc(
165
+ """
166
+ [metadata]
167
+ name = utf8-metadata-dist
168
+ version = 42
169
+ author_email = "John X. Ãørçeč" <john@utf8.org>, Γαμα קּ 東 <gama@utf8.org>
170
+ long_description = file: README.rst
171
+ """
172
+ ),
173
+ "README.rst": "UTF-8 描述 説明",
174
+ },
175
+ "licenses-dist": {
176
+ "setup.cfg": cleandoc(
177
+ """
178
+ [metadata]
179
+ name = licenses-dist
180
+ version = 1.0
181
+ license_files = **/LICENSE
182
+ """
183
+ ),
184
+ "LICENSE": "",
185
+ "src": {
186
+ "vendor": {"LICENSE": ""},
187
+ },
188
+ },
189
+ }
190
+
191
+
192
+ if sys.platform != "win32":
193
+ # ABI3 extensions don't really work on Windows
194
+ EXAMPLES["abi3extension-dist"] = {
195
+ "setup.py": cleandoc(
196
+ """
197
+ from setuptools import Extension, setup
198
+
199
+ setup(
200
+ name="extension.dist",
201
+ version="0.1",
202
+ description="A testing distribution \N{SNOWMAN}",
203
+ ext_modules=[
204
+ Extension(
205
+ name="extension", sources=["extension.c"], py_limited_api=True
206
+ )
207
+ ],
208
+ )
209
+ """
210
+ ),
211
+ "setup.cfg": "[bdist_wheel]\npy_limited_api=cp32",
212
+ "extension.c": "#define Py_LIMITED_API 0x03020000\n#include <Python.h>",
213
+ }
214
+
215
+
216
+ def bdist_wheel_cmd(**kwargs):
217
+ """Run command in the same process so that it is easier to collect coverage"""
218
+ dist_obj = (
219
+ run_setup("setup.py", stop_after="init")
220
+ if os.path.exists("setup.py")
221
+ else Distribution({"script_name": "%%build_meta%%"})
222
+ )
223
+ dist_obj.parse_config_files()
224
+ cmd = bdist_wheel(dist_obj)
225
+ for attr, value in kwargs.items():
226
+ setattr(cmd, attr, value)
227
+ cmd.finalize_options()
228
+ return cmd
229
+
230
+
231
+ def mkexample(tmp_path_factory, name):
232
+ basedir = tmp_path_factory.mktemp(name)
233
+ jaraco.path.build(EXAMPLES[name], prefix=str(basedir))
234
+ return basedir
235
+
236
+
237
+ @pytest.fixture(scope="session")
238
+ def wheel_paths(tmp_path_factory):
239
+ build_base = tmp_path_factory.mktemp("build")
240
+ dist_dir = tmp_path_factory.mktemp("dist")
241
+ for name in EXAMPLES:
242
+ example_dir = mkexample(tmp_path_factory, name)
243
+ build_dir = build_base / name
244
+ with jaraco.path.DirectoryStack().context(example_dir):
245
+ bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
246
+
247
+ return sorted(str(fname) for fname in dist_dir.glob("*.whl"))
248
+
249
+
250
+ @pytest.fixture
251
+ def dummy_dist(tmp_path_factory):
252
+ return mkexample(tmp_path_factory, "dummy-dist")
253
+
254
+
255
+ @pytest.fixture
256
+ def licenses_dist(tmp_path_factory):
257
+ return mkexample(tmp_path_factory, "licenses-dist")
258
+
259
+
260
+ def test_no_scripts(wheel_paths):
261
+ """Make sure entry point scripts are not generated."""
262
+ path = next(path for path in wheel_paths if "complex_dist" in path)
263
+ for entry in ZipFile(path).infolist():
264
+ assert ".data/scripts/" not in entry.filename
265
+
266
+
267
+ def test_unicode_record(wheel_paths):
268
+ path = next(path for path in wheel_paths if "unicode_dist" in path)
269
+ with ZipFile(path) as zf:
270
+ record = zf.read("unicode_dist-0.1.dist-info/RECORD")
271
+
272
+ assert "åäö_日本語.py".encode() in record
273
+
274
+
275
+ UTF8_PKG_INFO = """\
276
+ Metadata-Version: 2.1
277
+ Name: helloworld
278
+ Version: 42
279
+ Author-email: "John X. Ãørçeč" <john@utf8.org>, Γαμα קּ 東 <gama@utf8.org>
280
+
281
+
282
+ UTF-8 描述 説明
283
+ """
284
+
285
+
286
+ def test_preserve_unicode_metadata(monkeypatch, tmp_path):
287
+ monkeypatch.chdir(tmp_path)
288
+ egginfo = tmp_path / "dummy_dist.egg-info"
289
+ distinfo = tmp_path / "dummy_dist.dist-info"
290
+
291
+ egginfo.mkdir()
292
+ (egginfo / "PKG-INFO").write_text(UTF8_PKG_INFO, encoding="utf-8")
293
+ (egginfo / "dependency_links.txt").touch()
294
+
295
+ class simpler_bdist_wheel(bdist_wheel):
296
+ """Avoid messing with setuptools/distutils internals"""
297
+
298
+ def __init__(self) -> None:
299
+ pass
300
+
301
+ @property
302
+ def license_paths(self):
303
+ return []
304
+
305
+ cmd_obj = simpler_bdist_wheel()
306
+ cmd_obj.egg2dist(egginfo, distinfo)
307
+
308
+ metadata = (distinfo / "METADATA").read_text(encoding="utf-8")
309
+ assert 'Author-email: "John X. Ãørçeč"' in metadata
310
+ assert "Γαμα קּ 東 " in metadata
311
+ assert "UTF-8 描述 説明" in metadata
312
+
313
+
314
+ def test_licenses_default(dummy_dist, monkeypatch, tmp_path):
315
+ monkeypatch.chdir(dummy_dist)
316
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
317
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
318
+ license_files = {
319
+ "dummy_dist-1.0.dist-info/licenses/" + fname
320
+ for fname in DEFAULT_LICENSE_FILES
321
+ }
322
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
323
+
324
+
325
+ def test_licenses_deprecated(dummy_dist, monkeypatch, tmp_path):
326
+ dummy_dist.joinpath("setup.cfg").write_text(
327
+ "[metadata]\nlicense_file=licenses_dir/DUMMYFILE", encoding="utf-8"
328
+ )
329
+ monkeypatch.chdir(dummy_dist)
330
+
331
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
332
+
333
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
334
+ license_files = {"dummy_dist-1.0.dist-info/licenses/licenses_dir/DUMMYFILE"}
335
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
336
+
337
+
338
+ @pytest.mark.parametrize(
339
+ ("config_file", "config"),
340
+ [
341
+ ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*\n LICENSE"),
342
+ ("setup.cfg", "[metadata]\nlicense_files=licenses_dir/*, LICENSE"),
343
+ (
344
+ "setup.py",
345
+ SETUPPY_EXAMPLE.replace(
346
+ ")", " license_files=['licenses_dir/DUMMYFILE', 'LICENSE'])"
347
+ ),
348
+ ),
349
+ ],
350
+ )
351
+ def test_licenses_override(dummy_dist, monkeypatch, tmp_path, config_file, config):
352
+ dummy_dist.joinpath(config_file).write_text(config, encoding="utf-8")
353
+ monkeypatch.chdir(dummy_dist)
354
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
355
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
356
+ license_files = {
357
+ "dummy_dist-1.0.dist-info/licenses/" + fname
358
+ for fname in {"licenses_dir/DUMMYFILE", "LICENSE"}
359
+ }
360
+ assert set(wf.namelist()) == DEFAULT_FILES | license_files
361
+ metadata = wf.read("dummy_dist-1.0.dist-info/METADATA").decode("utf8")
362
+ assert "License-File: licenses_dir/DUMMYFILE" in metadata
363
+ assert "License-File: LICENSE" in metadata
364
+
365
+
366
+ def test_licenses_preserve_folder_structure(licenses_dist, monkeypatch, tmp_path):
367
+ monkeypatch.chdir(licenses_dist)
368
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
369
+ print(os.listdir("dist"))
370
+ with ZipFile("dist/licenses_dist-1.0-py3-none-any.whl") as wf:
371
+ default_files = {name.replace("dummy_", "licenses_") for name in DEFAULT_FILES}
372
+ license_files = {
373
+ "licenses_dist-1.0.dist-info/licenses/LICENSE",
374
+ "licenses_dist-1.0.dist-info/licenses/src/vendor/LICENSE",
375
+ }
376
+ assert set(wf.namelist()) == default_files | license_files
377
+ metadata = wf.read("licenses_dist-1.0.dist-info/METADATA").decode("utf8")
378
+ assert "License-File: src/vendor/LICENSE" in metadata
379
+ assert "License-File: LICENSE" in metadata
380
+
381
+
382
+ def test_licenses_disabled(dummy_dist, monkeypatch, tmp_path):
383
+ dummy_dist.joinpath("setup.cfg").write_text(
384
+ "[metadata]\nlicense_files=\n", encoding="utf-8"
385
+ )
386
+ monkeypatch.chdir(dummy_dist)
387
+ bdist_wheel_cmd(bdist_dir=str(tmp_path)).run()
388
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
389
+ assert set(wf.namelist()) == DEFAULT_FILES
390
+
391
+
392
+ def test_build_number(dummy_dist, monkeypatch, tmp_path):
393
+ monkeypatch.chdir(dummy_dist)
394
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2").run()
395
+ with ZipFile("dist/dummy_dist-1.0-2-py3-none-any.whl") as wf:
396
+ filenames = set(wf.namelist())
397
+ assert "dummy_dist-1.0.dist-info/RECORD" in filenames
398
+ assert "dummy_dist-1.0.dist-info/METADATA" in filenames
399
+
400
+
401
+ def test_universal_deprecated(dummy_dist, monkeypatch, tmp_path):
402
+ monkeypatch.chdir(dummy_dist)
403
+ with pytest.warns(SetuptoolsDeprecationWarning, match=".*universal is deprecated"):
404
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), universal=True).run()
405
+
406
+ # For now we still respect the option
407
+ assert os.path.exists("dist/dummy_dist-1.0-py2.py3-none-any.whl")
408
+
409
+
410
+ EXTENSION_EXAMPLE = """\
411
+ #include <Python.h>
412
+
413
+ static PyMethodDef methods[] = {
414
+ { NULL, NULL, 0, NULL }
415
+ };
416
+
417
+ static struct PyModuleDef module_def = {
418
+ PyModuleDef_HEAD_INIT,
419
+ "extension",
420
+ "Dummy extension module",
421
+ -1,
422
+ methods
423
+ };
424
+
425
+ PyMODINIT_FUNC PyInit_extension(void) {
426
+ return PyModule_Create(&module_def);
427
+ }
428
+ """
429
+ EXTENSION_SETUPPY = """\
430
+ from __future__ import annotations
431
+
432
+ from setuptools import Extension, setup
433
+
434
+ setup(
435
+ name="extension.dist",
436
+ version="0.1",
437
+ description="A testing distribution \N{SNOWMAN}",
438
+ ext_modules=[Extension(name="extension", sources=["extension.c"])],
439
+ )
440
+ """
441
+
442
+
443
+ @pytest.mark.filterwarnings(
444
+ "once:Config variable '.*' is unset.*, Python ABI tag may be incorrect"
445
+ )
446
+ def test_limited_abi(monkeypatch, tmp_path, tmp_path_factory):
447
+ """Test that building a binary wheel with the limited ABI works."""
448
+ source_dir = tmp_path_factory.mktemp("extension_dist")
449
+ (source_dir / "setup.py").write_text(EXTENSION_SETUPPY, encoding="utf-8")
450
+ (source_dir / "extension.c").write_text(EXTENSION_EXAMPLE, encoding="utf-8")
451
+ build_dir = tmp_path.joinpath("build")
452
+ dist_dir = tmp_path.joinpath("dist")
453
+ monkeypatch.chdir(source_dir)
454
+ bdist_wheel_cmd(bdist_dir=str(build_dir), dist_dir=str(dist_dir)).run()
455
+
456
+
457
+ def test_build_from_readonly_tree(dummy_dist, monkeypatch, tmp_path):
458
+ basedir = str(tmp_path.joinpath("dummy"))
459
+ shutil.copytree(str(dummy_dist), basedir)
460
+ monkeypatch.chdir(basedir)
461
+
462
+ # Make the tree read-only
463
+ for root, _dirs, files in os.walk(basedir):
464
+ for fname in files:
465
+ os.chmod(os.path.join(root, fname), stat.S_IREAD)
466
+
467
+ bdist_wheel_cmd().run()
468
+
469
+
470
+ @pytest.mark.parametrize(
471
+ ("option", "compress_type"),
472
+ list(bdist_wheel.supported_compressions.items()),
473
+ ids=list(bdist_wheel.supported_compressions),
474
+ )
475
+ def test_compression(dummy_dist, monkeypatch, tmp_path, option, compress_type):
476
+ monkeypatch.chdir(dummy_dist)
477
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), compression=option).run()
478
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
479
+ filenames = set(wf.namelist())
480
+ assert "dummy_dist-1.0.dist-info/RECORD" in filenames
481
+ assert "dummy_dist-1.0.dist-info/METADATA" in filenames
482
+ for zinfo in wf.filelist:
483
+ assert zinfo.compress_type == compress_type
484
+
485
+
486
+ def test_wheelfile_line_endings(wheel_paths):
487
+ for path in wheel_paths:
488
+ with ZipFile(path) as wf:
489
+ wheelfile = next(fn for fn in wf.filelist if fn.filename.endswith("WHEEL"))
490
+ wheelfile_contents = wf.read(wheelfile)
491
+ assert b"\r" not in wheelfile_contents
492
+
493
+
494
+ def test_unix_epoch_timestamps(dummy_dist, monkeypatch, tmp_path):
495
+ monkeypatch.setenv("SOURCE_DATE_EPOCH", "0")
496
+ monkeypatch.chdir(dummy_dist)
497
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), build_number="2a").run()
498
+ with ZipFile("dist/dummy_dist-1.0-2a-py3-none-any.whl") as wf:
499
+ for zinfo in wf.filelist:
500
+ assert zinfo.date_time >= (1980, 1, 1, 0, 0, 0) # min epoch is used
501
+
502
+
503
+ def test_get_abi_tag_windows(monkeypatch):
504
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
505
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313-win_amd64")
506
+ assert get_abi_tag() == "cp313"
507
+ monkeypatch.setattr(sys, "gettotalrefcount", lambda: 1, False)
508
+ assert get_abi_tag() == "cp313d"
509
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "cp313t-win_amd64")
510
+ assert get_abi_tag() == "cp313td"
511
+ monkeypatch.delattr(sys, "gettotalrefcount")
512
+ assert get_abi_tag() == "cp313t"
513
+
514
+
515
+ def test_get_abi_tag_pypy_old(monkeypatch):
516
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
517
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy36-pp73")
518
+ assert get_abi_tag() == "pypy36_pp73"
519
+
520
+
521
+ def test_get_abi_tag_pypy_new(monkeypatch):
522
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "pypy37-pp73-darwin")
523
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
524
+ assert get_abi_tag() == "pypy37_pp73"
525
+
526
+
527
+ def test_get_abi_tag_graalpy(monkeypatch):
528
+ monkeypatch.setattr(
529
+ sysconfig, "get_config_var", lambda x: "graalpy231-310-native-x86_64-linux"
530
+ )
531
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "graalpy")
532
+ assert get_abi_tag() == "graalpy231_310_native"
533
+
534
+
535
+ def test_get_abi_tag_fallback(monkeypatch):
536
+ monkeypatch.setattr(sysconfig, "get_config_var", lambda x: "unknown-python-310")
537
+ monkeypatch.setattr(tags, "interpreter_name", lambda: "unknown-python")
538
+ assert get_abi_tag() == "unknown_python_310"
539
+
540
+
541
+ def test_platform_with_space(dummy_dist, monkeypatch):
542
+ """Ensure building on platforms with a space in the name succeed."""
543
+ monkeypatch.chdir(dummy_dist)
544
+ bdist_wheel_cmd(plat_name="isilon onefs").run()
545
+
546
+
547
+ def test_data_dir_with_tag_build(monkeypatch, tmp_path):
548
+ """
549
+ Setuptools allow authors to set PEP 440's local version segments
550
+ using ``egg_info.tag_build``. This should be reflected not only in the
551
+ ``.whl`` file name, but also in the ``.dist-info`` and ``.data`` dirs.
552
+ See pypa/setuptools#3997.
553
+ """
554
+ monkeypatch.chdir(tmp_path)
555
+ files = {
556
+ "setup.py": """
557
+ from setuptools import setup
558
+ setup(headers=["hello.h"])
559
+ """,
560
+ "setup.cfg": """
561
+ [metadata]
562
+ name = test
563
+ version = 1.0
564
+
565
+ [options.data_files]
566
+ hello/world = file.txt
567
+
568
+ [egg_info]
569
+ tag_build = +what
570
+ tag_date = 0
571
+ """,
572
+ "file.txt": "",
573
+ "hello.h": "",
574
+ }
575
+ for file, content in files.items():
576
+ with open(file, "w", encoding="utf-8") as fh:
577
+ fh.write(cleandoc(content))
578
+
579
+ bdist_wheel_cmd().run()
580
+
581
+ # Ensure .whl, .dist-info and .data contain the local segment
582
+ wheel_path = "dist/test-1.0+what-py3-none-any.whl"
583
+ assert os.path.exists(wheel_path)
584
+ entries = set(ZipFile(wheel_path).namelist())
585
+ for expected in (
586
+ "test-1.0+what.data/headers/hello.h",
587
+ "test-1.0+what.data/data/hello/world/file.txt",
588
+ "test-1.0+what.dist-info/METADATA",
589
+ "test-1.0+what.dist-info/WHEEL",
590
+ ):
591
+ assert expected in entries
592
+
593
+ for not_expected in (
594
+ "test.data/headers/hello.h",
595
+ "test-1.0.data/data/hello/world/file.txt",
596
+ "test.dist-info/METADATA",
597
+ "test-1.0.dist-info/WHEEL",
598
+ ):
599
+ assert not_expected not in entries
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ ("reported", "expected"),
604
+ [("linux-x86_64", "linux_i686"), ("linux-aarch64", "linux_armv7l")],
605
+ )
606
+ @pytest.mark.skipif(
607
+ platform.system() != "Linux", reason="Only makes sense to test on Linux"
608
+ )
609
+ def test_platform_linux32(reported, expected, monkeypatch):
610
+ monkeypatch.setattr(struct, "calcsize", lambda x: 4)
611
+ dist = setuptools.Distribution()
612
+ cmd = bdist_wheel(dist)
613
+ cmd.plat_name = reported
614
+ cmd.root_is_pure = False
615
+ _, _, actual = cmd.get_tag()
616
+ assert actual == expected
617
+
618
+
619
+ def test_no_ctypes(monkeypatch) -> None:
620
+ def _fake_import(name: str, *args, **kwargs):
621
+ if name == "ctypes":
622
+ raise ModuleNotFoundError(f"No module named {name}")
623
+
624
+ return importlib.__import__(name, *args, **kwargs)
625
+
626
+ with suppress(KeyError):
627
+ monkeypatch.delitem(sys.modules, "wheel.macosx_libfile")
628
+
629
+ # Install an importer shim that refuses to load ctypes
630
+ monkeypatch.setattr(builtins, "__import__", _fake_import)
631
+ with pytest.raises(ModuleNotFoundError, match="No module named ctypes"):
632
+ import wheel.macosx_libfile # noqa: F401
633
+
634
+ # Unload and reimport the bdist_wheel command module to make sure it won't try to
635
+ # import ctypes
636
+ monkeypatch.delitem(sys.modules, "setuptools.command.bdist_wheel")
637
+
638
+ import setuptools.command.bdist_wheel # noqa: F401
639
+
640
+
641
+ def test_dist_info_provided(dummy_dist, monkeypatch, tmp_path):
642
+ monkeypatch.chdir(dummy_dist)
643
+ distinfo = tmp_path / "dummy_dist.dist-info"
644
+
645
+ distinfo.mkdir()
646
+ (distinfo / "METADATA").write_text("name: helloworld", encoding="utf-8")
647
+
648
+ # We don't control the metadata. According to PEP-517, "The hook MAY also
649
+ # create other files inside this directory, and a build frontend MUST
650
+ # preserve".
651
+ (distinfo / "FOO").write_text("bar", encoding="utf-8")
652
+
653
+ bdist_wheel_cmd(bdist_dir=str(tmp_path), dist_info_dir=str(distinfo)).run()
654
+ expected = {
655
+ "dummy_dist-1.0.dist-info/FOO",
656
+ "dummy_dist-1.0.dist-info/RECORD",
657
+ }
658
+ with ZipFile("dist/dummy_dist-1.0-py3-none-any.whl") as wf:
659
+ files_found = set(wf.namelist())
660
+ # Check that all expected files are there.
661
+ assert expected - files_found == set()
662
+ # Make sure there is no accidental egg-info bleeding into the wheel.
663
+ assert not [path for path in files_found if 'egg-info' in str(path)]
664
+
665
+
666
+ def test_allow_grace_period_parent_directory_license(monkeypatch, tmp_path):
667
+ # Motivation: https://github.com/pypa/setuptools/issues/4892
668
+ # TODO: Remove this test after deprecation period is over
669
+ files = {
670
+ "LICENSE.txt": "parent license", # <---- the license files are outside
671
+ "NOTICE.txt": "parent notice",
672
+ "python": {
673
+ "pyproject.toml": cleandoc(
674
+ """
675
+ [project]
676
+ name = "test-proj"
677
+ dynamic = ["version"] # <---- testing dynamic will not break
678
+ [tool.setuptools.dynamic]
679
+ version.file = "VERSION"
680
+ """
681
+ ),
682
+ "setup.cfg": cleandoc(
683
+ """
684
+ [metadata]
685
+ license_files =
686
+ ../LICENSE.txt
687
+ ../NOTICE.txt
688
+ """
689
+ ),
690
+ "VERSION": "42",
691
+ },
692
+ }
693
+ jaraco.path.build(files, prefix=str(tmp_path))
694
+ monkeypatch.chdir(tmp_path / "python")
695
+ msg = "Pattern '../.*.txt' cannot contain '..'"
696
+ with pytest.warns(SetuptoolsDeprecationWarning, match=msg):
697
+ bdist_wheel_cmd().run()
698
+ with ZipFile("dist/test_proj-42-py3-none-any.whl") as wf:
699
+ files_found = set(wf.namelist())
700
+ expected_files = {
701
+ "test_proj-42.dist-info/licenses/LICENSE.txt",
702
+ "test_proj-42.dist-info/licenses/NOTICE.txt",
703
+ }
704
+ assert expected_files <= files_found
705
+
706
+ metadata = wf.read("test_proj-42.dist-info/METADATA").decode("utf8")
707
+ assert "License-File: LICENSE.txt" in metadata
708
+ assert "License-File: NOTICE.txt" in metadata
python/Lib/site-packages/setuptools/tests/test_build.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import Command
2
+ from setuptools.command.build import build
3
+ from setuptools.dist import Distribution
4
+
5
+
6
+ def test_distribution_gives_setuptools_build_obj(tmpdir_cwd):
7
+ """
8
+ Check that the setuptools Distribution uses the
9
+ setuptools specific build object.
10
+ """
11
+
12
+ dist = Distribution(
13
+ dict(
14
+ script_name='setup.py',
15
+ script_args=['build'],
16
+ packages=[],
17
+ package_data={'': ['path/*']},
18
+ )
19
+ )
20
+ assert isinstance(dist.get_command_obj("build"), build)
21
+
22
+
23
+ class Subcommand(Command):
24
+ """Dummy command to be used in tests"""
25
+
26
+ def initialize_options(self):
27
+ pass
28
+
29
+ def finalize_options(self):
30
+ pass
31
+
32
+ def run(self):
33
+ raise NotImplementedError("just to check if the command runs")
python/Lib/site-packages/setuptools/tests/test_build_clib.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from unittest import mock
3
+
4
+ import pytest
5
+
6
+ from setuptools.command.build_clib import build_clib
7
+ from setuptools.dist import Distribution
8
+
9
+ from distutils.errors import DistutilsSetupError
10
+
11
+
12
+ class TestBuildCLib:
13
+ @mock.patch('setuptools.command.build_clib.newer_pairwise_group')
14
+ def test_build_libraries(self, mock_newer):
15
+ dist = Distribution()
16
+ cmd = build_clib(dist)
17
+
18
+ # this will be a long section, just making sure all
19
+ # exceptions are properly raised
20
+ libs = [('example', {'sources': 'broken.c'})]
21
+ with pytest.raises(DistutilsSetupError):
22
+ cmd.build_libraries(libs)
23
+
24
+ obj_deps = 'some_string'
25
+ libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})]
26
+ with pytest.raises(DistutilsSetupError):
27
+ cmd.build_libraries(libs)
28
+
29
+ obj_deps = {'': ''}
30
+ libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})]
31
+ with pytest.raises(DistutilsSetupError):
32
+ cmd.build_libraries(libs)
33
+
34
+ obj_deps = {'source.c': ''}
35
+ libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})]
36
+ with pytest.raises(DistutilsSetupError):
37
+ cmd.build_libraries(libs)
38
+
39
+ # with that out of the way, let's see if the crude dependency
40
+ # system works
41
+ cmd.compiler = mock.MagicMock(spec=cmd.compiler)
42
+ mock_newer.return_value = ([], [])
43
+
44
+ obj_deps = {'': ('global.h',), 'example.c': ('example.h',)}
45
+ libs = [('example', {'sources': ['example.c'], 'obj_deps': obj_deps})]
46
+
47
+ cmd.build_libraries(libs)
48
+ assert [['example.c', 'global.h', 'example.h']] in mock_newer.call_args[0]
49
+ assert not cmd.compiler.compile.called
50
+ assert cmd.compiler.create_static_lib.call_count == 1
51
+
52
+ # reset the call numbers so we can test again
53
+ cmd.compiler.reset_mock()
54
+
55
+ mock_newer.return_value = '' # anything as long as it's not ([],[])
56
+ cmd.build_libraries(libs)
57
+ assert cmd.compiler.compile.call_count == 1
58
+ assert cmd.compiler.create_static_lib.call_count == 1
59
+
60
+ @mock.patch('setuptools.command.build_clib.newer_pairwise_group')
61
+ def test_build_libraries_reproducible(self, mock_newer):
62
+ dist = Distribution()
63
+ cmd = build_clib(dist)
64
+
65
+ # with that out of the way, let's see if the crude dependency
66
+ # system works
67
+ cmd.compiler = mock.MagicMock(spec=cmd.compiler)
68
+ mock_newer.return_value = ([], [])
69
+
70
+ original_sources = ['a-example.c', 'example.c']
71
+ sources = original_sources
72
+
73
+ obj_deps = {'': ('global.h',), 'example.c': ('example.h',)}
74
+ libs = [('example', {'sources': sources, 'obj_deps': obj_deps})]
75
+
76
+ cmd.build_libraries(libs)
77
+ computed_call_args = mock_newer.call_args[0]
78
+
79
+ while sources == original_sources:
80
+ sources = random.sample(original_sources, len(original_sources))
81
+ libs = [('example', {'sources': sources, 'obj_deps': obj_deps})]
82
+
83
+ cmd.build_libraries(libs)
84
+ assert computed_call_args == mock_newer.call_args[0]
python/Lib/site-packages/setuptools/tests/test_build_ext.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from importlib.util import cache_from_source as _compiled_file_name
6
+
7
+ import pytest
8
+ from jaraco import path
9
+
10
+ from setuptools.command.build_ext import build_ext, get_abi3_suffix
11
+ from setuptools.dist import Distribution
12
+ from setuptools.errors import CompileError
13
+ from setuptools.extension import Extension
14
+
15
+ from . import environment
16
+ from .textwrap import DALS
17
+
18
+ import distutils.command.build_ext as orig
19
+ from distutils.sysconfig import get_config_var
20
+
21
+ IS_PYPY = '__pypy__' in sys.builtin_module_names
22
+
23
+
24
+ class TestBuildExt:
25
+ def test_get_ext_filename(self):
26
+ """
27
+ Setuptools needs to give back the same
28
+ result as distutils, even if the fullname
29
+ is not in ext_map.
30
+ """
31
+ dist = Distribution()
32
+ cmd = build_ext(dist)
33
+ cmd.ext_map['foo/bar'] = ''
34
+ res = cmd.get_ext_filename('foo')
35
+ wanted = orig.build_ext.get_ext_filename(cmd, 'foo')
36
+ assert res == wanted
37
+
38
+ def test_abi3_filename(self):
39
+ """
40
+ Filename needs to be loadable by several versions
41
+ of Python 3 if 'is_abi3' is truthy on Extension()
42
+ """
43
+ print(get_abi3_suffix())
44
+
45
+ extension = Extension('spam.eggs', ['eggs.c'], py_limited_api=True)
46
+ dist = Distribution(dict(ext_modules=[extension]))
47
+ cmd = build_ext(dist)
48
+ cmd.finalize_options()
49
+ assert 'spam.eggs' in cmd.ext_map
50
+ res = cmd.get_ext_filename('spam.eggs')
51
+
52
+ if not get_abi3_suffix():
53
+ assert res.endswith(get_config_var('EXT_SUFFIX'))
54
+ elif sys.platform == 'win32':
55
+ assert res.endswith('eggs.pyd')
56
+ else:
57
+ assert 'abi3' in res
58
+
59
+ def test_ext_suffix_override(self):
60
+ """
61
+ SETUPTOOLS_EXT_SUFFIX variable always overrides
62
+ default extension options.
63
+ """
64
+ dist = Distribution()
65
+ cmd = build_ext(dist)
66
+ cmd.ext_map['for_abi3'] = ext = Extension(
67
+ 'for_abi3',
68
+ ['s.c'],
69
+ # Override shouldn't affect abi3 modules
70
+ py_limited_api=True,
71
+ )
72
+ # Mock value needed to pass tests
73
+ ext._links_to_dynamic = False
74
+
75
+ if not IS_PYPY:
76
+ expect = cmd.get_ext_filename('for_abi3')
77
+ else:
78
+ # PyPy builds do not use ABI3 tag, so they will
79
+ # also get the overridden suffix.
80
+ expect = 'for_abi3.test-suffix'
81
+
82
+ try:
83
+ os.environ['SETUPTOOLS_EXT_SUFFIX'] = '.test-suffix'
84
+ res = cmd.get_ext_filename('normal')
85
+ assert 'normal.test-suffix' == res
86
+ res = cmd.get_ext_filename('for_abi3')
87
+ assert expect == res
88
+ finally:
89
+ del os.environ['SETUPTOOLS_EXT_SUFFIX']
90
+
91
+ def dist_with_example(self):
92
+ files = {
93
+ "src": {"mypkg": {"subpkg": {"ext2.c": ""}}},
94
+ "c-extensions": {"ext1": {"main.c": ""}},
95
+ }
96
+
97
+ ext1 = Extension("mypkg.ext1", ["c-extensions/ext1/main.c"])
98
+ ext2 = Extension("mypkg.subpkg.ext2", ["src/mypkg/subpkg/ext2.c"])
99
+ ext3 = Extension("ext3", ["c-extension/ext3.c"])
100
+
101
+ path.build(files)
102
+ return Distribution({
103
+ "script_name": "%test%",
104
+ "ext_modules": [ext1, ext2, ext3],
105
+ "package_dir": {"": "src"},
106
+ })
107
+
108
+ def test_get_outputs(self, tmpdir_cwd, monkeypatch):
109
+ monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent
110
+ monkeypatch.setattr('setuptools.command.build_ext.use_stubs', False)
111
+ dist = self.dist_with_example()
112
+
113
+ # Regular build: get_outputs not empty, but get_output_mappings is empty
114
+ build_ext = dist.get_command_obj("build_ext")
115
+ build_ext.editable_mode = False
116
+ build_ext.ensure_finalized()
117
+ build_lib = build_ext.build_lib.replace(os.sep, "/")
118
+ outputs = [x.replace(os.sep, "/") for x in build_ext.get_outputs()]
119
+ assert outputs == [
120
+ f"{build_lib}/ext3.mp3",
121
+ f"{build_lib}/mypkg/ext1.mp3",
122
+ f"{build_lib}/mypkg/subpkg/ext2.mp3",
123
+ ]
124
+ assert build_ext.get_output_mapping() == {}
125
+
126
+ # Editable build: get_output_mappings should contain everything in get_outputs
127
+ dist.reinitialize_command("build_ext")
128
+ build_ext.editable_mode = True
129
+ build_ext.ensure_finalized()
130
+ mapping = {
131
+ k.replace(os.sep, "/"): v.replace(os.sep, "/")
132
+ for k, v in build_ext.get_output_mapping().items()
133
+ }
134
+ assert mapping == {
135
+ f"{build_lib}/ext3.mp3": "src/ext3.mp3",
136
+ f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3",
137
+ f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3",
138
+ }
139
+
140
+ def test_get_output_mapping_with_stub(self, tmpdir_cwd, monkeypatch):
141
+ monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent
142
+ monkeypatch.setattr('setuptools.command.build_ext.use_stubs', True)
143
+ dist = self.dist_with_example()
144
+
145
+ # Editable build should create compiled stubs (.pyc files only, no .py)
146
+ build_ext = dist.get_command_obj("build_ext")
147
+ build_ext.editable_mode = True
148
+ build_ext.ensure_finalized()
149
+ for ext in build_ext.extensions:
150
+ monkeypatch.setattr(ext, "_needs_stub", True)
151
+
152
+ build_lib = build_ext.build_lib.replace(os.sep, "/")
153
+ mapping = {
154
+ k.replace(os.sep, "/"): v.replace(os.sep, "/")
155
+ for k, v in build_ext.get_output_mapping().items()
156
+ }
157
+
158
+ def C(file):
159
+ """Make it possible to do comparisons and tests in a OS-independent way"""
160
+ return _compiled_file_name(file).replace(os.sep, "/")
161
+
162
+ assert mapping == {
163
+ C(f"{build_lib}/ext3.py"): C("src/ext3.py"),
164
+ f"{build_lib}/ext3.mp3": "src/ext3.mp3",
165
+ C(f"{build_lib}/mypkg/ext1.py"): C("src/mypkg/ext1.py"),
166
+ f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3",
167
+ C(f"{build_lib}/mypkg/subpkg/ext2.py"): C("src/mypkg/subpkg/ext2.py"),
168
+ f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3",
169
+ }
170
+
171
+ # Ensure only the compiled stubs are present not the raw .py stub
172
+ assert f"{build_lib}/mypkg/ext1.py" not in mapping
173
+ assert f"{build_lib}/mypkg/subpkg/ext2.py" not in mapping
174
+
175
+ # Visualize what the cached stub files look like
176
+ example_stub = C(f"{build_lib}/mypkg/ext1.py")
177
+ assert example_stub in mapping
178
+ assert example_stub.startswith(f"{build_lib}/mypkg/__pycache__/ext1")
179
+ assert example_stub.endswith(".pyc")
180
+
181
+
182
+ class TestBuildExtInplace:
183
+ def get_build_ext_cmd(self, optional: bool, **opts) -> build_ext:
184
+ files: dict[str, str | dict[str, dict[str, str]]] = {
185
+ "eggs.c": "#include missingheader.h\n",
186
+ ".build": {"lib": {}, "tmp": {}},
187
+ }
188
+ path.build(files)
189
+ extension = Extension('spam.eggs', ['eggs.c'], optional=optional)
190
+ dist = Distribution(dict(ext_modules=[extension]))
191
+ dist.script_name = 'setup.py'
192
+ cmd = build_ext(dist)
193
+ vars(cmd).update(build_lib=".build/lib", build_temp=".build/tmp", **opts)
194
+ cmd.ensure_finalized()
195
+ return cmd
196
+
197
+ def get_log_messages(self, caplog, capsys):
198
+ """
199
+ Historically, distutils "logged" by printing to sys.std*.
200
+ Later versions adopted the logging framework. Grab
201
+ messages regardless of how they were captured.
202
+ """
203
+ std = capsys.readouterr()
204
+ return std.out.splitlines() + std.err.splitlines() + caplog.messages
205
+
206
+ def test_optional(self, tmpdir_cwd, caplog, capsys):
207
+ """
208
+ If optional extensions fail to build, setuptools should show the error
209
+ in the logs but not fail to build
210
+ """
211
+ cmd = self.get_build_ext_cmd(optional=True, inplace=True)
212
+ cmd.run()
213
+ assert any(
214
+ 'build_ext: building extension "spam.eggs" failed'
215
+ for msg in self.get_log_messages(caplog, capsys)
216
+ )
217
+ # No compile error exception should be raised
218
+
219
+ def test_non_optional(self, tmpdir_cwd):
220
+ # Non-optional extensions should raise an exception
221
+ cmd = self.get_build_ext_cmd(optional=False, inplace=True)
222
+ with pytest.raises(CompileError):
223
+ cmd.run()
224
+
225
+
226
+ def test_build_ext_config_handling(tmpdir_cwd):
227
+ files = {
228
+ 'setup.py': DALS(
229
+ """
230
+ from setuptools import Extension, setup
231
+ setup(
232
+ name='foo',
233
+ version='0.0.0',
234
+ ext_modules=[Extension('foo', ['foo.c'])],
235
+ )
236
+ """
237
+ ),
238
+ 'foo.c': DALS(
239
+ """
240
+ #include "Python.h"
241
+
242
+ #if PY_MAJOR_VERSION >= 3
243
+
244
+ static struct PyModuleDef moduledef = {
245
+ PyModuleDef_HEAD_INIT,
246
+ "foo",
247
+ NULL,
248
+ 0,
249
+ NULL,
250
+ NULL,
251
+ NULL,
252
+ NULL,
253
+ NULL
254
+ };
255
+
256
+ #define INITERROR return NULL
257
+
258
+ PyMODINIT_FUNC PyInit_foo(void)
259
+
260
+ #else
261
+
262
+ #define INITERROR return
263
+
264
+ void initfoo(void)
265
+
266
+ #endif
267
+ {
268
+ #if PY_MAJOR_VERSION >= 3
269
+ PyObject *module = PyModule_Create(&moduledef);
270
+ #else
271
+ PyObject *module = Py_InitModule("extension", NULL);
272
+ #endif
273
+ if (module == NULL)
274
+ INITERROR;
275
+ #if PY_MAJOR_VERSION >= 3
276
+ return module;
277
+ #endif
278
+ }
279
+ """
280
+ ),
281
+ 'setup.cfg': DALS(
282
+ """
283
+ [build]
284
+ build_base = foo_build
285
+ """
286
+ ),
287
+ }
288
+ path.build(files)
289
+ code, (stdout, stderr) = environment.run_setup_py(
290
+ cmd=['build'],
291
+ data_stream=(0, 2),
292
+ )
293
+ assert code == 0, f'\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}'
python/Lib/site-packages/setuptools/tests/test_build_meta.py ADDED
@@ -0,0 +1,959 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import importlib
3
+ import os
4
+ import re
5
+ import shutil
6
+ import signal
7
+ import sys
8
+ import tarfile
9
+ import warnings
10
+ from concurrent import futures
11
+ from pathlib import Path
12
+ from typing import Any, Callable
13
+ from zipfile import ZipFile
14
+
15
+ import pytest
16
+ from jaraco import path
17
+ from packaging.requirements import Requirement
18
+
19
+ from setuptools.warnings import SetuptoolsDeprecationWarning
20
+
21
+ from .textwrap import DALS
22
+
23
+ SETUP_SCRIPT_STUB = "__import__('setuptools').setup()"
24
+
25
+
26
+ TIMEOUT = int(os.getenv("TIMEOUT_BACKEND_TEST", "180")) # in seconds
27
+ IS_PYPY = '__pypy__' in sys.builtin_module_names
28
+
29
+
30
+ pytestmark = pytest.mark.skipif(
31
+ sys.platform == "win32" and IS_PYPY,
32
+ reason="The combination of PyPy + Windows + pytest-xdist + ProcessPoolExecutor "
33
+ "is flaky and problematic",
34
+ )
35
+
36
+
37
+ class BuildBackendBase:
38
+ def __init__(self, cwd='.', env=None, backend_name='setuptools.build_meta') -> None:
39
+ self.cwd = cwd
40
+ self.env = env or {}
41
+ self.backend_name = backend_name
42
+
43
+
44
+ class BuildBackend(BuildBackendBase):
45
+ """PEP 517 Build Backend"""
46
+
47
+ def __init__(self, *args, **kwargs) -> None:
48
+ super().__init__(*args, **kwargs)
49
+ self.pool = futures.ProcessPoolExecutor(max_workers=1)
50
+
51
+ def __getattr__(self, name: str) -> Callable[..., Any]:
52
+ """Handles arbitrary function invocations on the build backend."""
53
+
54
+ def method(*args, **kw):
55
+ root = os.path.abspath(self.cwd)
56
+ caller = BuildBackendCaller(root, self.env, self.backend_name)
57
+ pid = None
58
+ try:
59
+ pid = self.pool.submit(os.getpid).result(TIMEOUT)
60
+ return self.pool.submit(caller, name, *args, **kw).result(TIMEOUT)
61
+ except futures.TimeoutError:
62
+ self.pool.shutdown(wait=False) # doesn't stop already running processes
63
+ self._kill(pid)
64
+ pytest.xfail(f"Backend did not respond before timeout ({TIMEOUT} s)")
65
+ except (futures.process.BrokenProcessPool, MemoryError, OSError):
66
+ if IS_PYPY:
67
+ pytest.xfail("PyPy frequently fails tests with ProcessPoolExector")
68
+ raise
69
+
70
+ return method
71
+
72
+ def _kill(self, pid):
73
+ if pid is None:
74
+ return
75
+ with contextlib.suppress(ProcessLookupError, OSError):
76
+ os.kill(pid, signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
77
+
78
+
79
+ class BuildBackendCaller(BuildBackendBase):
80
+ def __init__(self, *args, **kwargs) -> None:
81
+ super().__init__(*args, **kwargs)
82
+
83
+ (self.backend_name, _, self.backend_obj) = self.backend_name.partition(':')
84
+
85
+ def __call__(self, name, *args, **kw) -> Any:
86
+ """Handles arbitrary function invocations on the build backend."""
87
+ os.chdir(self.cwd)
88
+ os.environ.update(self.env)
89
+ mod = importlib.import_module(self.backend_name)
90
+
91
+ if self.backend_obj:
92
+ backend = getattr(mod, self.backend_obj)
93
+ else:
94
+ backend = mod
95
+
96
+ return getattr(backend, name)(*args, **kw)
97
+
98
+
99
+ defns = [
100
+ { # simple setup.py script
101
+ 'setup.py': DALS(
102
+ """
103
+ __import__('setuptools').setup(
104
+ name='foo',
105
+ version='0.0.0',
106
+ py_modules=['hello'],
107
+ setup_requires=['six'],
108
+ )
109
+ """
110
+ ),
111
+ 'hello.py': DALS(
112
+ """
113
+ def run():
114
+ print('hello')
115
+ """
116
+ ),
117
+ },
118
+ { # setup.py that relies on __name__
119
+ 'setup.py': DALS(
120
+ """
121
+ assert __name__ == '__main__'
122
+ __import__('setuptools').setup(
123
+ name='foo',
124
+ version='0.0.0',
125
+ py_modules=['hello'],
126
+ setup_requires=['six'],
127
+ )
128
+ """
129
+ ),
130
+ 'hello.py': DALS(
131
+ """
132
+ def run():
133
+ print('hello')
134
+ """
135
+ ),
136
+ },
137
+ { # setup.py script that runs arbitrary code
138
+ 'setup.py': DALS(
139
+ """
140
+ variable = True
141
+ def function():
142
+ return variable
143
+ assert variable
144
+ __import__('setuptools').setup(
145
+ name='foo',
146
+ version='0.0.0',
147
+ py_modules=['hello'],
148
+ setup_requires=['six'],
149
+ )
150
+ """
151
+ ),
152
+ 'hello.py': DALS(
153
+ """
154
+ def run():
155
+ print('hello')
156
+ """
157
+ ),
158
+ },
159
+ { # setup.py script that constructs temp files to be included in the distribution
160
+ 'setup.py': DALS(
161
+ """
162
+ # Some packages construct files on the fly, include them in the package,
163
+ # and immediately remove them after `setup()` (e.g. pybind11==2.9.1).
164
+ # Therefore, we cannot use `distutils.core.run_setup(..., stop_after=...)`
165
+ # to obtain a distribution object first, and then run the distutils
166
+ # commands later, because these files will be removed in the meantime.
167
+
168
+ with open('world.py', 'w', encoding="utf-8") as f:
169
+ f.write('x = 42')
170
+
171
+ try:
172
+ __import__('setuptools').setup(
173
+ name='foo',
174
+ version='0.0.0',
175
+ py_modules=['world'],
176
+ setup_requires=['six'],
177
+ )
178
+ finally:
179
+ # Some packages will clean temporary files
180
+ __import__('os').unlink('world.py')
181
+ """
182
+ ),
183
+ },
184
+ { # setup.cfg only
185
+ 'setup.cfg': DALS(
186
+ """
187
+ [metadata]
188
+ name = foo
189
+ version = 0.0.0
190
+
191
+ [options]
192
+ py_modules=hello
193
+ setup_requires=six
194
+ """
195
+ ),
196
+ 'hello.py': DALS(
197
+ """
198
+ def run():
199
+ print('hello')
200
+ """
201
+ ),
202
+ },
203
+ { # setup.cfg and setup.py
204
+ 'setup.cfg': DALS(
205
+ """
206
+ [metadata]
207
+ name = foo
208
+ version = 0.0.0
209
+
210
+ [options]
211
+ py_modules=hello
212
+ setup_requires=six
213
+ """
214
+ ),
215
+ 'setup.py': "__import__('setuptools').setup()",
216
+ 'hello.py': DALS(
217
+ """
218
+ def run():
219
+ print('hello')
220
+ """
221
+ ),
222
+ },
223
+ ]
224
+
225
+
226
+ class TestBuildMetaBackend:
227
+ backend_name = 'setuptools.build_meta'
228
+
229
+ def get_build_backend(self):
230
+ return BuildBackend(backend_name=self.backend_name)
231
+
232
+ @pytest.fixture(params=defns)
233
+ def build_backend(self, tmpdir, request):
234
+ path.build(request.param, prefix=str(tmpdir))
235
+ with tmpdir.as_cwd():
236
+ yield self.get_build_backend()
237
+
238
+ def test_get_requires_for_build_wheel(self, build_backend):
239
+ actual = build_backend.get_requires_for_build_wheel()
240
+ expected = ['six']
241
+ assert sorted(actual) == sorted(expected)
242
+
243
+ def test_get_requires_for_build_sdist(self, build_backend):
244
+ actual = build_backend.get_requires_for_build_sdist()
245
+ expected = ['six']
246
+ assert sorted(actual) == sorted(expected)
247
+
248
+ def test_build_wheel(self, build_backend):
249
+ dist_dir = os.path.abspath('pip-wheel')
250
+ os.makedirs(dist_dir)
251
+ wheel_name = build_backend.build_wheel(dist_dir)
252
+
253
+ wheel_file = os.path.join(dist_dir, wheel_name)
254
+ assert os.path.isfile(wheel_file)
255
+
256
+ # Temporary files should be removed
257
+ assert not os.path.isfile('world.py')
258
+
259
+ with ZipFile(wheel_file) as zipfile:
260
+ wheel_contents = set(zipfile.namelist())
261
+
262
+ # Each one of the examples have a single module
263
+ # that should be included in the distribution
264
+ python_scripts = (f for f in wheel_contents if f.endswith('.py'))
265
+ modules = [f for f in python_scripts if not f.endswith('setup.py')]
266
+ assert len(modules) == 1
267
+
268
+ @pytest.mark.parametrize('build_type', ('wheel', 'sdist'))
269
+ def test_build_with_existing_file_present(self, build_type, tmpdir_cwd):
270
+ # Building a sdist/wheel should still succeed if there's
271
+ # already a sdist/wheel in the destination directory.
272
+ files = {
273
+ 'setup.py': "from setuptools import setup\nsetup()",
274
+ 'VERSION': "0.0.1",
275
+ 'setup.cfg': DALS(
276
+ """
277
+ [metadata]
278
+ name = foo
279
+ version = file: VERSION
280
+ """
281
+ ),
282
+ 'pyproject.toml': DALS(
283
+ """
284
+ [build-system]
285
+ requires = ["setuptools", "wheel"]
286
+ build-backend = "setuptools.build_meta"
287
+ """
288
+ ),
289
+ }
290
+
291
+ path.build(files)
292
+
293
+ dist_dir = os.path.abspath('preexisting-' + build_type)
294
+
295
+ build_backend = self.get_build_backend()
296
+ build_method = getattr(build_backend, 'build_' + build_type)
297
+
298
+ # Build a first sdist/wheel.
299
+ # Note: this also check the destination directory is
300
+ # successfully created if it does not exist already.
301
+ first_result = build_method(dist_dir)
302
+
303
+ # Change version.
304
+ with open("VERSION", "wt", encoding="utf-8") as version_file:
305
+ version_file.write("0.0.2")
306
+
307
+ # Build a *second* sdist/wheel.
308
+ second_result = build_method(dist_dir)
309
+
310
+ assert os.path.isfile(os.path.join(dist_dir, first_result))
311
+ assert first_result != second_result
312
+
313
+ # And if rebuilding the exact same sdist/wheel?
314
+ open(os.path.join(dist_dir, second_result), 'wb').close()
315
+ third_result = build_method(dist_dir)
316
+ assert third_result == second_result
317
+ assert os.path.getsize(os.path.join(dist_dir, third_result)) > 0
318
+
319
+ @pytest.mark.parametrize("setup_script", [None, SETUP_SCRIPT_STUB])
320
+ def test_build_with_pyproject_config(self, tmpdir, setup_script):
321
+ files = {
322
+ 'pyproject.toml': DALS(
323
+ """
324
+ [build-system]
325
+ requires = ["setuptools", "wheel"]
326
+ build-backend = "setuptools.build_meta"
327
+
328
+ [project]
329
+ name = "foo"
330
+ license = {text = "MIT"}
331
+ description = "This is a Python package"
332
+ dynamic = ["version", "readme"]
333
+ classifiers = [
334
+ "Development Status :: 5 - Production/Stable",
335
+ "Intended Audience :: Developers"
336
+ ]
337
+ urls = {Homepage = "http://github.com"}
338
+ dependencies = [
339
+ "appdirs",
340
+ ]
341
+
342
+ [project.optional-dependencies]
343
+ all = [
344
+ "tomli>=1",
345
+ "pyscaffold>=4,<5",
346
+ 'importlib; python_version == "2.6"',
347
+ ]
348
+
349
+ [project.scripts]
350
+ foo = "foo.cli:main"
351
+
352
+ [tool.setuptools]
353
+ zip-safe = false
354
+ package-dir = {"" = "src"}
355
+ packages = {find = {where = ["src"]}}
356
+ license-files = ["LICENSE*"]
357
+
358
+ [tool.setuptools.dynamic]
359
+ version = {attr = "foo.__version__"}
360
+ readme = {file = "README.rst"}
361
+
362
+ [tool.distutils.sdist]
363
+ formats = "gztar"
364
+ """
365
+ ),
366
+ "MANIFEST.in": DALS(
367
+ """
368
+ global-include *.py *.txt
369
+ global-exclude *.py[cod]
370
+ """
371
+ ),
372
+ "README.rst": "This is a ``README``",
373
+ "LICENSE.txt": "---- placeholder MIT license ----",
374
+ "src": {
375
+ "foo": {
376
+ "__init__.py": "__version__ = '0.1'",
377
+ "__init__.pyi": "__version__: str",
378
+ "cli.py": "def main(): print('hello world')",
379
+ "data.txt": "def main(): print('hello world')",
380
+ "py.typed": "",
381
+ }
382
+ },
383
+ }
384
+ if setup_script:
385
+ files["setup.py"] = setup_script
386
+
387
+ build_backend = self.get_build_backend()
388
+ with tmpdir.as_cwd():
389
+ path.build(files)
390
+ msgs = [
391
+ "'tool.setuptools.license-files' is deprecated in favor of 'project.license-files'",
392
+ "`project.license` as a TOML table is deprecated",
393
+ ]
394
+ with warnings.catch_warnings():
395
+ for msg in msgs:
396
+ warnings.filterwarnings("ignore", msg, SetuptoolsDeprecationWarning)
397
+ sdist_path = build_backend.build_sdist("temp")
398
+ wheel_file = build_backend.build_wheel("temp")
399
+
400
+ with tarfile.open(os.path.join(tmpdir, "temp", sdist_path)) as tar:
401
+ sdist_contents = set(tar.getnames())
402
+
403
+ with ZipFile(os.path.join(tmpdir, "temp", wheel_file)) as zipfile:
404
+ wheel_contents = set(zipfile.namelist())
405
+ metadata = str(zipfile.read("foo-0.1.dist-info/METADATA"), "utf-8")
406
+ license = str(
407
+ zipfile.read("foo-0.1.dist-info/licenses/LICENSE.txt"), "utf-8"
408
+ )
409
+ epoints = str(zipfile.read("foo-0.1.dist-info/entry_points.txt"), "utf-8")
410
+
411
+ assert sdist_contents - {"foo-0.1/setup.py"} == {
412
+ 'foo-0.1',
413
+ 'foo-0.1/LICENSE.txt',
414
+ 'foo-0.1/MANIFEST.in',
415
+ 'foo-0.1/PKG-INFO',
416
+ 'foo-0.1/README.rst',
417
+ 'foo-0.1/pyproject.toml',
418
+ 'foo-0.1/setup.cfg',
419
+ 'foo-0.1/src',
420
+ 'foo-0.1/src/foo',
421
+ 'foo-0.1/src/foo/__init__.py',
422
+ 'foo-0.1/src/foo/__init__.pyi',
423
+ 'foo-0.1/src/foo/cli.py',
424
+ 'foo-0.1/src/foo/data.txt',
425
+ 'foo-0.1/src/foo/py.typed',
426
+ 'foo-0.1/src/foo.egg-info',
427
+ 'foo-0.1/src/foo.egg-info/PKG-INFO',
428
+ 'foo-0.1/src/foo.egg-info/SOURCES.txt',
429
+ 'foo-0.1/src/foo.egg-info/dependency_links.txt',
430
+ 'foo-0.1/src/foo.egg-info/entry_points.txt',
431
+ 'foo-0.1/src/foo.egg-info/requires.txt',
432
+ 'foo-0.1/src/foo.egg-info/top_level.txt',
433
+ 'foo-0.1/src/foo.egg-info/not-zip-safe',
434
+ }
435
+ assert wheel_contents == {
436
+ "foo/__init__.py",
437
+ "foo/__init__.pyi", # include type information by default
438
+ "foo/cli.py",
439
+ "foo/data.txt", # include_package_data defaults to True
440
+ "foo/py.typed", # include type information by default
441
+ "foo-0.1.dist-info/licenses/LICENSE.txt",
442
+ "foo-0.1.dist-info/METADATA",
443
+ "foo-0.1.dist-info/WHEEL",
444
+ "foo-0.1.dist-info/entry_points.txt",
445
+ "foo-0.1.dist-info/top_level.txt",
446
+ "foo-0.1.dist-info/RECORD",
447
+ }
448
+ assert license == "---- placeholder MIT license ----"
449
+
450
+ for line in (
451
+ "Summary: This is a Python package",
452
+ "License: MIT",
453
+ "License-File: LICENSE.txt",
454
+ "Classifier: Intended Audience :: Developers",
455
+ "Requires-Dist: appdirs",
456
+ "Requires-Dist: " + str(Requirement('tomli>=1 ; extra == "all"')),
457
+ "Requires-Dist: "
458
+ + str(Requirement('importlib; python_version=="2.6" and extra =="all"')),
459
+ ):
460
+ assert line in metadata, (line, metadata)
461
+
462
+ assert metadata.strip().endswith("This is a ``README``")
463
+ assert epoints.strip() == "[console_scripts]\nfoo = foo.cli:main"
464
+
465
+ def test_static_metadata_in_pyproject_config(self, tmpdir):
466
+ # Make sure static metadata in pyproject.toml is not overwritten by setup.py
467
+ # as required by PEP 621
468
+ files = {
469
+ 'pyproject.toml': DALS(
470
+ """
471
+ [build-system]
472
+ requires = ["setuptools", "wheel"]
473
+ build-backend = "setuptools.build_meta"
474
+
475
+ [project]
476
+ name = "foo"
477
+ description = "This is a Python package"
478
+ version = "42"
479
+ dependencies = ["six"]
480
+ """
481
+ ),
482
+ 'hello.py': DALS(
483
+ """
484
+ def run():
485
+ print('hello')
486
+ """
487
+ ),
488
+ 'setup.py': DALS(
489
+ """
490
+ __import__('setuptools').setup(
491
+ name='bar',
492
+ version='13',
493
+ )
494
+ """
495
+ ),
496
+ }
497
+ build_backend = self.get_build_backend()
498
+ with tmpdir.as_cwd():
499
+ path.build(files)
500
+ sdist_path = build_backend.build_sdist("temp")
501
+ wheel_file = build_backend.build_wheel("temp")
502
+
503
+ assert (tmpdir / "temp/foo-42.tar.gz").exists()
504
+ assert (tmpdir / "temp/foo-42-py3-none-any.whl").exists()
505
+ assert not (tmpdir / "temp/bar-13.tar.gz").exists()
506
+ assert not (tmpdir / "temp/bar-42.tar.gz").exists()
507
+ assert not (tmpdir / "temp/foo-13.tar.gz").exists()
508
+ assert not (tmpdir / "temp/bar-13-py3-none-any.whl").exists()
509
+ assert not (tmpdir / "temp/bar-42-py3-none-any.whl").exists()
510
+ assert not (tmpdir / "temp/foo-13-py3-none-any.whl").exists()
511
+
512
+ with tarfile.open(os.path.join(tmpdir, "temp", sdist_path)) as tar:
513
+ pkg_info = str(tar.extractfile('foo-42/PKG-INFO').read(), "utf-8")
514
+ members = tar.getnames()
515
+ assert "bar-13/PKG-INFO" not in members
516
+
517
+ with ZipFile(os.path.join(tmpdir, "temp", wheel_file)) as zipfile:
518
+ metadata = str(zipfile.read("foo-42.dist-info/METADATA"), "utf-8")
519
+ members = zipfile.namelist()
520
+ assert "bar-13.dist-info/METADATA" not in members
521
+
522
+ for file in pkg_info, metadata:
523
+ for line in ("Name: foo", "Version: 42"):
524
+ assert line in file
525
+ for line in ("Name: bar", "Version: 13"):
526
+ assert line not in file
527
+
528
+ def test_build_sdist(self, build_backend):
529
+ dist_dir = os.path.abspath('pip-sdist')
530
+ os.makedirs(dist_dir)
531
+ sdist_name = build_backend.build_sdist(dist_dir)
532
+
533
+ assert os.path.isfile(os.path.join(dist_dir, sdist_name))
534
+
535
+ def test_prepare_metadata_for_build_wheel(self, build_backend):
536
+ dist_dir = os.path.abspath('pip-dist-info')
537
+ os.makedirs(dist_dir)
538
+
539
+ dist_info = build_backend.prepare_metadata_for_build_wheel(dist_dir)
540
+
541
+ assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA'))
542
+
543
+ def test_prepare_metadata_inplace(self, build_backend):
544
+ """
545
+ Some users might pass metadata_directory pre-populated with `.tox` or `.venv`.
546
+ See issue #3523.
547
+ """
548
+ for pre_existing in [
549
+ ".tox/python/lib/python3.10/site-packages/attrs-22.1.0.dist-info",
550
+ ".tox/python/lib/python3.10/site-packages/autocommand-2.2.1.dist-info",
551
+ ".nox/python/lib/python3.10/site-packages/build-0.8.0.dist-info",
552
+ ".venv/python3.10/site-packages/click-8.1.3.dist-info",
553
+ "venv/python3.10/site-packages/distlib-0.3.5.dist-info",
554
+ "env/python3.10/site-packages/docutils-0.19.dist-info",
555
+ ]:
556
+ os.makedirs(pre_existing, exist_ok=True)
557
+ dist_info = build_backend.prepare_metadata_for_build_wheel(".")
558
+ assert os.path.isfile(os.path.join(dist_info, 'METADATA'))
559
+
560
+ def test_build_sdist_explicit_dist(self, build_backend):
561
+ # explicitly specifying the dist folder should work
562
+ # the folder sdist_directory and the ``--dist-dir`` can be the same
563
+ dist_dir = os.path.abspath('dist')
564
+ sdist_name = build_backend.build_sdist(dist_dir)
565
+ assert os.path.isfile(os.path.join(dist_dir, sdist_name))
566
+
567
+ def test_build_sdist_version_change(self, build_backend):
568
+ sdist_into_directory = os.path.abspath("out_sdist")
569
+ os.makedirs(sdist_into_directory)
570
+
571
+ sdist_name = build_backend.build_sdist(sdist_into_directory)
572
+ assert os.path.isfile(os.path.join(sdist_into_directory, sdist_name))
573
+
574
+ # if the setup.py changes subsequent call of the build meta
575
+ # should still succeed, given the
576
+ # sdist_directory the frontend specifies is empty
577
+ setup_loc = os.path.abspath("setup.py")
578
+ if not os.path.exists(setup_loc):
579
+ setup_loc = os.path.abspath("setup.cfg")
580
+
581
+ with open(setup_loc, 'rt', encoding="utf-8") as file_handler:
582
+ content = file_handler.read()
583
+ with open(setup_loc, 'wt', encoding="utf-8") as file_handler:
584
+ file_handler.write(content.replace("version='0.0.0'", "version='0.0.1'"))
585
+
586
+ shutil.rmtree(sdist_into_directory)
587
+ os.makedirs(sdist_into_directory)
588
+
589
+ sdist_name = build_backend.build_sdist("out_sdist")
590
+ assert os.path.isfile(os.path.join(os.path.abspath("out_sdist"), sdist_name))
591
+
592
+ def test_build_sdist_pyproject_toml_exists(self, tmpdir_cwd):
593
+ files = {
594
+ 'setup.py': DALS(
595
+ """
596
+ __import__('setuptools').setup(
597
+ name='foo',
598
+ version='0.0.0',
599
+ py_modules=['hello']
600
+ )"""
601
+ ),
602
+ 'hello.py': '',
603
+ 'pyproject.toml': DALS(
604
+ """
605
+ [build-system]
606
+ requires = ["setuptools", "wheel"]
607
+ build-backend = "setuptools.build_meta"
608
+ """
609
+ ),
610
+ }
611
+ path.build(files)
612
+ build_backend = self.get_build_backend()
613
+ targz_path = build_backend.build_sdist("temp")
614
+ with tarfile.open(os.path.join("temp", targz_path)) as tar:
615
+ assert any('pyproject.toml' in name for name in tar.getnames())
616
+
617
+ def test_build_sdist_setup_py_exists(self, tmpdir_cwd):
618
+ # If build_sdist is called from a script other than setup.py,
619
+ # ensure setup.py is included
620
+ path.build(defns[0])
621
+
622
+ build_backend = self.get_build_backend()
623
+ targz_path = build_backend.build_sdist("temp")
624
+ with tarfile.open(os.path.join("temp", targz_path)) as tar:
625
+ assert any('setup.py' in name for name in tar.getnames())
626
+
627
+ def test_build_sdist_setup_py_manifest_excluded(self, tmpdir_cwd):
628
+ # Ensure that MANIFEST.in can exclude setup.py
629
+ files = {
630
+ 'setup.py': DALS(
631
+ """
632
+ __import__('setuptools').setup(
633
+ name='foo',
634
+ version='0.0.0',
635
+ py_modules=['hello']
636
+ )"""
637
+ ),
638
+ 'hello.py': '',
639
+ 'MANIFEST.in': DALS(
640
+ """
641
+ exclude setup.py
642
+ """
643
+ ),
644
+ }
645
+
646
+ path.build(files)
647
+
648
+ build_backend = self.get_build_backend()
649
+ targz_path = build_backend.build_sdist("temp")
650
+ with tarfile.open(os.path.join("temp", targz_path)) as tar:
651
+ assert not any('setup.py' in name for name in tar.getnames())
652
+
653
+ def test_build_sdist_builds_targz_even_if_zip_indicated(self, tmpdir_cwd):
654
+ files = {
655
+ 'setup.py': DALS(
656
+ """
657
+ __import__('setuptools').setup(
658
+ name='foo',
659
+ version='0.0.0',
660
+ py_modules=['hello']
661
+ )"""
662
+ ),
663
+ 'hello.py': '',
664
+ 'setup.cfg': DALS(
665
+ """
666
+ [sdist]
667
+ formats=zip
668
+ """
669
+ ),
670
+ }
671
+
672
+ path.build(files)
673
+
674
+ build_backend = self.get_build_backend()
675
+ build_backend.build_sdist("temp")
676
+
677
+ _relative_path_import_files = {
678
+ 'setup.py': DALS(
679
+ """
680
+ __import__('setuptools').setup(
681
+ name='foo',
682
+ version=__import__('hello').__version__,
683
+ py_modules=['hello']
684
+ )"""
685
+ ),
686
+ 'hello.py': '__version__ = "0.0.0"',
687
+ 'setup.cfg': DALS(
688
+ """
689
+ [sdist]
690
+ formats=zip
691
+ """
692
+ ),
693
+ }
694
+
695
+ def test_build_sdist_relative_path_import(self, tmpdir_cwd):
696
+ path.build(self._relative_path_import_files)
697
+ build_backend = self.get_build_backend()
698
+ with pytest.raises(ImportError, match="^No module named 'hello'$"):
699
+ build_backend.build_sdist("temp")
700
+
701
+ _simple_pyproject_example = {
702
+ "pyproject.toml": DALS(
703
+ """
704
+ [project]
705
+ name = "proj"
706
+ version = "42"
707
+ """
708
+ ),
709
+ "src": {"proj": {"__init__.py": ""}},
710
+ }
711
+
712
+ def _assert_link_tree(self, parent_dir):
713
+ """All files in the directory should be either links or hard links"""
714
+ files = list(Path(parent_dir).glob("**/*"))
715
+ assert files # Should not be empty
716
+ for file in files:
717
+ assert file.is_symlink() or os.stat(file).st_nlink > 0
718
+
719
+ def test_editable_without_config_settings(self, tmpdir_cwd):
720
+ """
721
+ Sanity check to ensure tests with --mode=strict are different from the ones
722
+ without --mode.
723
+
724
+ --mode=strict should create a local directory with a package tree.
725
+ The directory should not get created otherwise.
726
+ """
727
+ path.build(self._simple_pyproject_example)
728
+ build_backend = self.get_build_backend()
729
+ assert not Path("build").exists()
730
+ build_backend.build_editable("temp")
731
+ assert not Path("build").exists()
732
+
733
+ def test_build_wheel_inplace(self, tmpdir_cwd):
734
+ config_settings = {"--build-option": ["build_ext", "--inplace"]}
735
+ path.build(self._simple_pyproject_example)
736
+ build_backend = self.get_build_backend()
737
+ assert not Path("build").exists()
738
+ Path("build").mkdir()
739
+ build_backend.prepare_metadata_for_build_wheel("build", config_settings)
740
+ build_backend.build_wheel("build", config_settings)
741
+ assert Path("build/proj-42-py3-none-any.whl").exists()
742
+
743
+ @pytest.mark.parametrize("config_settings", [{"editable-mode": "strict"}])
744
+ def test_editable_with_config_settings(self, tmpdir_cwd, config_settings):
745
+ path.build({**self._simple_pyproject_example, '_meta': {}})
746
+ assert not Path("build").exists()
747
+ build_backend = self.get_build_backend()
748
+ build_backend.prepare_metadata_for_build_editable("_meta", config_settings)
749
+ build_backend.build_editable("temp", config_settings, "_meta")
750
+ self._assert_link_tree(next(Path("build").glob("__editable__.*")))
751
+
752
+ @pytest.mark.parametrize(
753
+ ("setup_literal", "requirements"),
754
+ [
755
+ ("'foo'", ['foo']),
756
+ ("['foo']", ['foo']),
757
+ (r"'foo\n'", ['foo']),
758
+ (r"'foo\n\n'", ['foo']),
759
+ ("['foo', 'bar']", ['foo', 'bar']),
760
+ (r"'# Has a comment line\nfoo'", ['foo']),
761
+ (r"'foo # Has an inline comment'", ['foo']),
762
+ (r"'foo \\\n >=3.0'", ['foo>=3.0']),
763
+ (r"'foo\nbar'", ['foo', 'bar']),
764
+ (r"'foo\nbar\n'", ['foo', 'bar']),
765
+ (r"['foo\n', 'bar\n']", ['foo', 'bar']),
766
+ ],
767
+ )
768
+ @pytest.mark.parametrize('use_wheel', [True, False])
769
+ def test_setup_requires(self, setup_literal, requirements, use_wheel, tmpdir_cwd):
770
+ files = {
771
+ 'setup.py': DALS(
772
+ """
773
+ from setuptools import setup
774
+
775
+ setup(
776
+ name="qux",
777
+ version="0.0.0",
778
+ py_modules=["hello"],
779
+ setup_requires={setup_literal},
780
+ )
781
+ """
782
+ ).format(setup_literal=setup_literal),
783
+ 'hello.py': DALS(
784
+ """
785
+ def run():
786
+ print('hello')
787
+ """
788
+ ),
789
+ }
790
+
791
+ path.build(files)
792
+
793
+ build_backend = self.get_build_backend()
794
+
795
+ if use_wheel:
796
+ get_requires = build_backend.get_requires_for_build_wheel
797
+ else:
798
+ get_requires = build_backend.get_requires_for_build_sdist
799
+
800
+ # Ensure that the build requirements are properly parsed
801
+ expected = sorted(requirements)
802
+ actual = get_requires()
803
+
804
+ assert expected == sorted(actual)
805
+
806
+ def test_setup_requires_with_auto_discovery(self, tmpdir_cwd):
807
+ # Make sure patches introduced to retrieve setup_requires don't accidentally
808
+ # activate auto-discovery and cause problems due to the incomplete set of
809
+ # attributes passed to MinimalDistribution
810
+ files = {
811
+ 'pyproject.toml': DALS(
812
+ """
813
+ [project]
814
+ name = "proj"
815
+ version = "42"
816
+ """
817
+ ),
818
+ "setup.py": DALS(
819
+ """
820
+ __import__('setuptools').setup(
821
+ setup_requires=["foo"],
822
+ py_modules = ["hello", "world"]
823
+ )
824
+ """
825
+ ),
826
+ 'hello.py': "'hello'",
827
+ 'world.py': "'world'",
828
+ }
829
+ path.build(files)
830
+ build_backend = self.get_build_backend()
831
+ setup_requires = build_backend.get_requires_for_build_wheel()
832
+ assert setup_requires == ["foo"]
833
+
834
+ def test_dont_install_setup_requires(self, tmpdir_cwd):
835
+ files = {
836
+ 'setup.py': DALS(
837
+ """
838
+ from setuptools import setup
839
+
840
+ setup(
841
+ name="qux",
842
+ version="0.0.0",
843
+ py_modules=["hello"],
844
+ setup_requires=["does-not-exist >99"],
845
+ )
846
+ """
847
+ ),
848
+ 'hello.py': DALS(
849
+ """
850
+ def run():
851
+ print('hello')
852
+ """
853
+ ),
854
+ }
855
+
856
+ path.build(files)
857
+
858
+ build_backend = self.get_build_backend()
859
+
860
+ dist_dir = os.path.abspath('pip-dist-info')
861
+ os.makedirs(dist_dir)
862
+
863
+ # does-not-exist can't be satisfied, so if it attempts to install
864
+ # setup_requires, it will fail.
865
+ build_backend.prepare_metadata_for_build_wheel(dist_dir)
866
+
867
+ _sys_argv_0_passthrough = {
868
+ 'setup.py': DALS(
869
+ """
870
+ import os
871
+ import sys
872
+
873
+ __import__('setuptools').setup(
874
+ name='foo',
875
+ version='0.0.0',
876
+ )
877
+
878
+ sys_argv = os.path.abspath(sys.argv[0])
879
+ file_path = os.path.abspath('setup.py')
880
+ assert sys_argv == file_path
881
+ """
882
+ )
883
+ }
884
+
885
+ def test_sys_argv_passthrough(self, tmpdir_cwd):
886
+ path.build(self._sys_argv_0_passthrough)
887
+ build_backend = self.get_build_backend()
888
+ with pytest.raises(AssertionError):
889
+ build_backend.build_sdist("temp")
890
+
891
+ _setup_py_file_abspath = {
892
+ 'setup.py': DALS(
893
+ """
894
+ import os
895
+ assert os.path.isabs(__file__)
896
+ __import__('setuptools').setup(
897
+ name='foo',
898
+ version='0.0.0',
899
+ py_modules=['hello'],
900
+ setup_requires=['six'],
901
+ )
902
+ """
903
+ )
904
+ }
905
+
906
+ def test_setup_py_file_abspath(self, tmpdir_cwd):
907
+ path.build(self._setup_py_file_abspath)
908
+ build_backend = self.get_build_backend()
909
+ build_backend.build_sdist("temp")
910
+
911
+ @pytest.mark.parametrize('build_hook', ('build_sdist', 'build_wheel'))
912
+ def test_build_with_empty_setuppy(self, build_backend, build_hook):
913
+ files = {'setup.py': ''}
914
+ path.build(files)
915
+
916
+ msg = re.escape('No distribution was found.')
917
+ with pytest.raises(ValueError, match=msg):
918
+ getattr(build_backend, build_hook)("temp")
919
+
920
+
921
+ class TestBuildMetaLegacyBackend(TestBuildMetaBackend):
922
+ backend_name = 'setuptools.build_meta:__legacy__'
923
+
924
+ # build_meta_legacy-specific tests
925
+ def test_build_sdist_relative_path_import(self, tmpdir_cwd):
926
+ # This must fail in build_meta, but must pass in build_meta_legacy
927
+ path.build(self._relative_path_import_files)
928
+
929
+ build_backend = self.get_build_backend()
930
+ build_backend.build_sdist("temp")
931
+
932
+ def test_sys_argv_passthrough(self, tmpdir_cwd):
933
+ path.build(self._sys_argv_0_passthrough)
934
+
935
+ build_backend = self.get_build_backend()
936
+ build_backend.build_sdist("temp")
937
+
938
+
939
+ @pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning")
940
+ def test_sys_exit_0_in_setuppy(monkeypatch, tmp_path):
941
+ """Setuptools should be resilient to setup.py with ``sys.exit(0)`` (#3973)."""
942
+ monkeypatch.chdir(tmp_path)
943
+ setuppy = """
944
+ import sys, setuptools
945
+ setuptools.setup(name='foo', version='0.0.0')
946
+ sys.exit(0)
947
+ """
948
+ (tmp_path / "setup.py").write_text(DALS(setuppy), encoding="utf-8")
949
+ backend = BuildBackend(backend_name="setuptools.build_meta")
950
+ assert backend.get_requires_for_build_wheel() == []
951
+
952
+
953
+ def test_system_exit_in_setuppy(monkeypatch, tmp_path):
954
+ monkeypatch.chdir(tmp_path)
955
+ setuppy = "import sys; sys.exit('some error')"
956
+ (tmp_path / "setup.py").write_text(setuppy, encoding="utf-8")
957
+ with pytest.raises(SystemExit, match="some error"):
958
+ backend = BuildBackend(backend_name="setuptools.build_meta")
959
+ backend.get_requires_for_build_wheel()
python/Lib/site-packages/setuptools/tests/test_build_py.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import stat
4
+ import warnings
5
+ from pathlib import Path
6
+ from unittest.mock import Mock
7
+
8
+ import jaraco.path
9
+ import pytest
10
+
11
+ from setuptools import SetuptoolsDeprecationWarning
12
+ from setuptools.dist import Distribution
13
+
14
+ from .textwrap import DALS
15
+
16
+
17
+ def test_directories_in_package_data_glob(tmpdir_cwd):
18
+ """
19
+ Directories matching the glob in package_data should
20
+ not be included in the package data.
21
+
22
+ Regression test for #261.
23
+ """
24
+ dist = Distribution(
25
+ dict(
26
+ script_name='setup.py',
27
+ script_args=['build_py'],
28
+ packages=[''],
29
+ package_data={'': ['path/*']},
30
+ )
31
+ )
32
+ os.makedirs('path/subpath')
33
+ dist.parse_command_line()
34
+ dist.run_commands()
35
+
36
+
37
+ def test_recursive_in_package_data_glob(tmpdir_cwd):
38
+ """
39
+ Files matching recursive globs (**) in package_data should
40
+ be included in the package data.
41
+
42
+ #1806
43
+ """
44
+ dist = Distribution(
45
+ dict(
46
+ script_name='setup.py',
47
+ script_args=['build_py'],
48
+ packages=[''],
49
+ package_data={'': ['path/**/data']},
50
+ )
51
+ )
52
+ os.makedirs('path/subpath/subsubpath')
53
+ open('path/subpath/subsubpath/data', 'wb').close()
54
+
55
+ dist.parse_command_line()
56
+ dist.run_commands()
57
+
58
+ assert stat.S_ISREG(os.stat('build/lib/path/subpath/subsubpath/data').st_mode), (
59
+ "File is not included"
60
+ )
61
+
62
+
63
+ def test_read_only(tmpdir_cwd):
64
+ """
65
+ Ensure read-only flag is not preserved in copy
66
+ for package modules and package data, as that
67
+ causes problems with deleting read-only files on
68
+ Windows.
69
+
70
+ #1451
71
+ """
72
+ dist = Distribution(
73
+ dict(
74
+ script_name='setup.py',
75
+ script_args=['build_py'],
76
+ packages=['pkg'],
77
+ package_data={'pkg': ['data.dat']},
78
+ )
79
+ )
80
+ os.makedirs('pkg')
81
+ open('pkg/__init__.py', 'wb').close()
82
+ open('pkg/data.dat', 'wb').close()
83
+ os.chmod('pkg/__init__.py', stat.S_IREAD)
84
+ os.chmod('pkg/data.dat', stat.S_IREAD)
85
+ dist.parse_command_line()
86
+ dist.run_commands()
87
+ shutil.rmtree('build')
88
+
89
+
90
+ @pytest.mark.xfail(
91
+ 'platform.system() == "Windows"',
92
+ reason="On Windows, files do not have executable bits",
93
+ raises=AssertionError,
94
+ strict=True,
95
+ )
96
+ def test_executable_data(tmpdir_cwd):
97
+ """
98
+ Ensure executable bit is preserved in copy for
99
+ package data, as users rely on it for scripts.
100
+
101
+ #2041
102
+ """
103
+ dist = Distribution(
104
+ dict(
105
+ script_name='setup.py',
106
+ script_args=['build_py'],
107
+ packages=['pkg'],
108
+ package_data={'pkg': ['run-me']},
109
+ )
110
+ )
111
+ os.makedirs('pkg')
112
+ open('pkg/__init__.py', 'wb').close()
113
+ open('pkg/run-me', 'wb').close()
114
+ os.chmod('pkg/run-me', 0o700)
115
+
116
+ dist.parse_command_line()
117
+ dist.run_commands()
118
+
119
+ assert os.stat('build/lib/pkg/run-me').st_mode & stat.S_IEXEC, (
120
+ "Script is not executable"
121
+ )
122
+
123
+
124
+ EXAMPLE_WITH_MANIFEST = {
125
+ "setup.cfg": DALS(
126
+ """
127
+ [metadata]
128
+ name = mypkg
129
+ version = 42
130
+
131
+ [options]
132
+ include_package_data = True
133
+ packages = find:
134
+
135
+ [options.packages.find]
136
+ exclude = *.tests*
137
+ """
138
+ ),
139
+ "mypkg": {
140
+ "__init__.py": "",
141
+ "resource_file.txt": "",
142
+ "tests": {
143
+ "__init__.py": "",
144
+ "test_mypkg.py": "",
145
+ "test_file.txt": "",
146
+ },
147
+ },
148
+ "MANIFEST.in": DALS(
149
+ """
150
+ global-include *.py *.txt
151
+ global-exclude *.py[cod]
152
+ prune dist
153
+ prune build
154
+ prune *.egg-info
155
+ """
156
+ ),
157
+ }
158
+
159
+
160
+ def test_excluded_subpackages(tmpdir_cwd):
161
+ jaraco.path.build(EXAMPLE_WITH_MANIFEST)
162
+ dist = Distribution({"script_name": "%PEP 517%"})
163
+ dist.parse_config_files()
164
+
165
+ build_py = dist.get_command_obj("build_py")
166
+
167
+ msg = r"Python recognizes 'mypkg\.tests' as an importable package"
168
+ with pytest.warns(SetuptoolsDeprecationWarning, match=msg): # noqa: PT031
169
+ # TODO: To fix #3260 we need some transition period to deprecate the
170
+ # existing behavior of `include_package_data`. After the transition, we
171
+ # should remove the warning and fix the behavior.
172
+
173
+ if os.getenv("SETUPTOOLS_USE_DISTUTILS") == "stdlib":
174
+ # pytest.warns reset the warning filter temporarily
175
+ # https://github.com/pytest-dev/pytest/issues/4011#issuecomment-423494810
176
+ warnings.filterwarnings(
177
+ "ignore",
178
+ "'encoding' argument not specified",
179
+ module="distutils.text_file",
180
+ # This warning is already fixed in pypa/distutils but not in stdlib
181
+ )
182
+
183
+ build_py.finalize_options()
184
+ build_py.run()
185
+
186
+ build_dir = Path(dist.get_command_obj("build_py").build_lib)
187
+ assert (build_dir / "mypkg/__init__.py").exists()
188
+ assert (build_dir / "mypkg/resource_file.txt").exists()
189
+
190
+ # Setuptools is configured to ignore `mypkg.tests`, therefore the following
191
+ # files/dirs should not be included in the distribution.
192
+ for f in [
193
+ "mypkg/tests/__init__.py",
194
+ "mypkg/tests/test_mypkg.py",
195
+ "mypkg/tests/test_file.txt",
196
+ "mypkg/tests",
197
+ ]:
198
+ with pytest.raises(AssertionError):
199
+ # TODO: Enforce the following assertion once #3260 is fixed
200
+ # (remove context manager and the following xfail).
201
+ assert not (build_dir / f).exists()
202
+
203
+ pytest.xfail("#3260")
204
+
205
+
206
+ @pytest.mark.filterwarnings("ignore::setuptools.SetuptoolsDeprecationWarning")
207
+ def test_existing_egg_info(tmpdir_cwd, monkeypatch):
208
+ """When provided with the ``existing_egg_info_dir`` attribute, build_py should not
209
+ attempt to run egg_info again.
210
+ """
211
+ # == Pre-condition ==
212
+ # Generate an egg-info dir
213
+ jaraco.path.build(EXAMPLE_WITH_MANIFEST)
214
+ dist = Distribution({"script_name": "%PEP 517%"})
215
+ dist.parse_config_files()
216
+ assert dist.include_package_data
217
+
218
+ egg_info = dist.get_command_obj("egg_info")
219
+ dist.run_command("egg_info")
220
+ egg_info_dir = next(Path(egg_info.egg_base).glob("*.egg-info"))
221
+ assert egg_info_dir.is_dir()
222
+
223
+ # == Setup ==
224
+ build_py = dist.get_command_obj("build_py")
225
+ build_py.finalize_options()
226
+ egg_info = dist.get_command_obj("egg_info")
227
+ egg_info_run = Mock(side_effect=egg_info.run)
228
+ monkeypatch.setattr(egg_info, "run", egg_info_run)
229
+
230
+ # == Remove caches ==
231
+ # egg_info is called when build_py looks for data_files, which gets cached.
232
+ # We need to ensure it is not cached yet, otherwise it may impact on the tests
233
+ build_py.__dict__.pop('data_files', None)
234
+ dist.reinitialize_command(egg_info)
235
+
236
+ # == Sanity check ==
237
+ # Ensure that if existing_egg_info is not given, build_py attempts to run egg_info
238
+ build_py.existing_egg_info_dir = None
239
+ build_py.run()
240
+ egg_info_run.assert_called()
241
+
242
+ # == Remove caches ==
243
+ egg_info_run.reset_mock()
244
+ build_py.__dict__.pop('data_files', None)
245
+ dist.reinitialize_command(egg_info)
246
+
247
+ # == Actual test ==
248
+ # Ensure that if existing_egg_info_dir is given, egg_info doesn't run
249
+ build_py.existing_egg_info_dir = egg_info_dir
250
+ build_py.run()
251
+ egg_info_run.assert_not_called()
252
+ assert build_py.data_files
253
+
254
+ # Make sure the list of outputs is actually OK
255
+ outputs = map(lambda x: x.replace(os.sep, "/"), build_py.get_outputs())
256
+ assert outputs
257
+ example = str(Path(build_py.build_lib, "mypkg/__init__.py")).replace(os.sep, "/")
258
+ assert example in outputs
259
+
260
+
261
+ EXAMPLE_ARBITRARY_MAPPING = {
262
+ "pyproject.toml": DALS(
263
+ """
264
+ [project]
265
+ name = "mypkg"
266
+ version = "42"
267
+
268
+ [tool.setuptools]
269
+ packages = ["mypkg", "mypkg.sub1", "mypkg.sub2", "mypkg.sub2.nested"]
270
+
271
+ [tool.setuptools.package-dir]
272
+ "" = "src"
273
+ "mypkg.sub2" = "src/mypkg/_sub2"
274
+ "mypkg.sub2.nested" = "other"
275
+ """
276
+ ),
277
+ "src": {
278
+ "mypkg": {
279
+ "__init__.py": "",
280
+ "resource_file.txt": "",
281
+ "sub1": {
282
+ "__init__.py": "",
283
+ "mod1.py": "",
284
+ },
285
+ "_sub2": {
286
+ "mod2.py": "",
287
+ },
288
+ },
289
+ },
290
+ "other": {
291
+ "__init__.py": "",
292
+ "mod3.py": "",
293
+ },
294
+ "MANIFEST.in": DALS(
295
+ """
296
+ global-include *.py *.txt
297
+ global-exclude *.py[cod]
298
+ """
299
+ ),
300
+ }
301
+
302
+
303
+ def test_get_outputs(tmpdir_cwd):
304
+ jaraco.path.build(EXAMPLE_ARBITRARY_MAPPING)
305
+ dist = Distribution({"script_name": "%test%"})
306
+ dist.parse_config_files()
307
+
308
+ build_py = dist.get_command_obj("build_py")
309
+ build_py.editable_mode = True
310
+ build_py.ensure_finalized()
311
+ build_lib = build_py.build_lib.replace(os.sep, "/")
312
+ outputs = {x.replace(os.sep, "/") for x in build_py.get_outputs()}
313
+ assert outputs == {
314
+ f"{build_lib}/mypkg/__init__.py",
315
+ f"{build_lib}/mypkg/resource_file.txt",
316
+ f"{build_lib}/mypkg/sub1/__init__.py",
317
+ f"{build_lib}/mypkg/sub1/mod1.py",
318
+ f"{build_lib}/mypkg/sub2/mod2.py",
319
+ f"{build_lib}/mypkg/sub2/nested/__init__.py",
320
+ f"{build_lib}/mypkg/sub2/nested/mod3.py",
321
+ }
322
+ mapping = {
323
+ k.replace(os.sep, "/"): v.replace(os.sep, "/")
324
+ for k, v in build_py.get_output_mapping().items()
325
+ }
326
+ assert mapping == {
327
+ f"{build_lib}/mypkg/__init__.py": "src/mypkg/__init__.py",
328
+ f"{build_lib}/mypkg/resource_file.txt": "src/mypkg/resource_file.txt",
329
+ f"{build_lib}/mypkg/sub1/__init__.py": "src/mypkg/sub1/__init__.py",
330
+ f"{build_lib}/mypkg/sub1/mod1.py": "src/mypkg/sub1/mod1.py",
331
+ f"{build_lib}/mypkg/sub2/mod2.py": "src/mypkg/_sub2/mod2.py",
332
+ f"{build_lib}/mypkg/sub2/nested/__init__.py": "other/__init__.py",
333
+ f"{build_lib}/mypkg/sub2/nested/mod3.py": "other/mod3.py",
334
+ }
335
+
336
+
337
+ class TestTypeInfoFiles:
338
+ PYPROJECTS = {
339
+ "default_pyproject": DALS(
340
+ """
341
+ [project]
342
+ name = "foo"
343
+ version = "1"
344
+ """
345
+ ),
346
+ "dont_include_package_data": DALS(
347
+ """
348
+ [project]
349
+ name = "foo"
350
+ version = "1"
351
+
352
+ [tool.setuptools]
353
+ include-package-data = false
354
+ """
355
+ ),
356
+ "exclude_type_info": DALS(
357
+ """
358
+ [project]
359
+ name = "foo"
360
+ version = "1"
361
+
362
+ [tool.setuptools]
363
+ include-package-data = false
364
+
365
+ [tool.setuptools.exclude-package-data]
366
+ "*" = ["py.typed", "*.pyi"]
367
+ """
368
+ ),
369
+ }
370
+
371
+ EXAMPLES = {
372
+ "simple_namespace": {
373
+ "directory_structure": {
374
+ "foo": {
375
+ "bar.pyi": "",
376
+ "py.typed": "",
377
+ "__init__.py": "",
378
+ }
379
+ },
380
+ "expected_type_files": {"foo/bar.pyi", "foo/py.typed"},
381
+ },
382
+ "nested_inside_namespace": {
383
+ "directory_structure": {
384
+ "foo": {
385
+ "bar": {
386
+ "py.typed": "",
387
+ "mod.pyi": "",
388
+ }
389
+ }
390
+ },
391
+ "expected_type_files": {"foo/bar/mod.pyi", "foo/bar/py.typed"},
392
+ },
393
+ "namespace_nested_inside_regular": {
394
+ "directory_structure": {
395
+ "foo": {
396
+ "namespace": {
397
+ "foo.pyi": "",
398
+ },
399
+ "__init__.pyi": "",
400
+ "py.typed": "",
401
+ }
402
+ },
403
+ "expected_type_files": {
404
+ "foo/namespace/foo.pyi",
405
+ "foo/__init__.pyi",
406
+ "foo/py.typed",
407
+ },
408
+ },
409
+ }
410
+
411
+ @pytest.mark.parametrize(
412
+ "pyproject",
413
+ [
414
+ "default_pyproject",
415
+ pytest.param(
416
+ "dont_include_package_data",
417
+ marks=pytest.mark.xfail(reason="pypa/setuptools#4350"),
418
+ ),
419
+ ],
420
+ )
421
+ @pytest.mark.parametrize("example", EXAMPLES.keys())
422
+ def test_type_files_included_by_default(self, tmpdir_cwd, pyproject, example):
423
+ structure = {
424
+ **self.EXAMPLES[example]["directory_structure"],
425
+ "pyproject.toml": self.PYPROJECTS[pyproject],
426
+ }
427
+ expected_type_files = self.EXAMPLES[example]["expected_type_files"]
428
+ jaraco.path.build(structure)
429
+
430
+ build_py = get_finalized_build_py()
431
+ outputs = get_outputs(build_py)
432
+ assert expected_type_files <= outputs
433
+
434
+ @pytest.mark.parametrize("pyproject", ["exclude_type_info"])
435
+ @pytest.mark.parametrize("example", EXAMPLES.keys())
436
+ def test_type_files_can_be_excluded(self, tmpdir_cwd, pyproject, example):
437
+ structure = {
438
+ **self.EXAMPLES[example]["directory_structure"],
439
+ "pyproject.toml": self.PYPROJECTS[pyproject],
440
+ }
441
+ expected_type_files = self.EXAMPLES[example]["expected_type_files"]
442
+ jaraco.path.build(structure)
443
+
444
+ build_py = get_finalized_build_py()
445
+ outputs = get_outputs(build_py)
446
+ assert expected_type_files.isdisjoint(outputs)
447
+
448
+ def test_stub_only_package(self, tmpdir_cwd):
449
+ structure = {
450
+ "pyproject.toml": DALS(
451
+ """
452
+ [project]
453
+ name = "foo-stubs"
454
+ version = "1"
455
+ """
456
+ ),
457
+ "foo-stubs": {"__init__.pyi": "", "bar.pyi": ""},
458
+ }
459
+ expected_type_files = {"foo-stubs/__init__.pyi", "foo-stubs/bar.pyi"}
460
+ jaraco.path.build(structure)
461
+
462
+ build_py = get_finalized_build_py()
463
+ outputs = get_outputs(build_py)
464
+ assert expected_type_files <= outputs
465
+
466
+
467
+ def get_finalized_build_py(script_name="%build_py-test%"):
468
+ dist = Distribution({"script_name": script_name})
469
+ dist.parse_config_files()
470
+ build_py = dist.get_command_obj("build_py")
471
+ build_py.finalize_options()
472
+ return build_py
473
+
474
+
475
+ def get_outputs(build_py):
476
+ build_dir = Path(build_py.build_lib)
477
+ return {
478
+ os.path.relpath(x, build_dir).replace(os.sep, "/")
479
+ for x in build_py.get_outputs()
480
+ }