codekingpro commited on
Commit
189339c
·
verified ·
1 Parent(s): b343561

Add files using upload-large-folder tool

Browse files
Files changed (26) hide show
  1. python/Lib/site-packages/hf_transfer-0.1.9.dist-info/INSTALLER +1 -0
  2. python/Lib/site-packages/hf_transfer-0.1.9.dist-info/METADATA +64 -0
  3. python/Lib/site-packages/hf_transfer-0.1.9.dist-info/RECORD +9 -0
  4. python/Lib/site-packages/hf_transfer-0.1.9.dist-info/REQUESTED +0 -0
  5. python/Lib/site-packages/hf_transfer-0.1.9.dist-info/WHEEL +4 -0
  6. python/Lib/site-packages/hf_transfer/__init__.py +5 -0
  7. python/Lib/site-packages/setuptools/archive_util.py +219 -0
  8. python/Lib/site-packages/setuptools/build_meta.py +556 -0
  9. python/Lib/site-packages/setuptools/cli-32.exe +0 -0
  10. python/Lib/site-packages/setuptools/cli-64.exe +0 -0
  11. python/Lib/site-packages/setuptools/cli-arm64.exe +0 -0
  12. python/Lib/site-packages/setuptools/cli.exe +0 -0
  13. python/Lib/site-packages/setuptools/depends.py +185 -0
  14. python/Lib/site-packages/setuptools/discovery.py +614 -0
  15. python/Lib/site-packages/setuptools/dist.py +1124 -0
  16. python/Lib/site-packages/setuptools/errors.py +67 -0
  17. python/Lib/site-packages/setuptools/extension.py +179 -0
  18. python/Lib/site-packages/setuptools/glob.py +185 -0
  19. python/Lib/site-packages/setuptools/gui-32.exe +0 -0
  20. python/Lib/site-packages/setuptools/gui-64.exe +0 -0
  21. python/Lib/site-packages/setuptools/gui-arm64.exe +0 -0
  22. python/Lib/site-packages/setuptools/gui.exe +0 -0
  23. python/Lib/site-packages/setuptools/installer.py +155 -0
  24. python/Lib/site-packages/setuptools/launch.py +36 -0
  25. python/Lib/site-packages/setuptools/launcher manifest.xml +15 -0
  26. python/Lib/site-packages/setuptools/logging.py +40 -0
python/Lib/site-packages/hf_transfer-0.1.9.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python/Lib/site-packages/hf_transfer-0.1.9.dist-info/METADATA ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: hf_transfer
3
+ Version: 0.1.9
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
7
+ License-File: LICENSE
8
+ Summary: Speed up file transfers with the Hugging Face Hub.
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
11
+ Project-URL: Issues, https://github.com/huggingface/hf_transfer/issues
12
+ Project-URL: Repository, https://github.com/huggingface/hf_transfer.git
13
+
14
+ # HF Transfer
15
+
16
+ Speed up file transfers with the Hub.
17
+
18
+ # DISCLAIMER
19
+
20
+ This library is a power user tool, to go beyond `~500MB/s` on very high bandwidth
21
+ network, where Python cannot cap out the available bandwidth.
22
+
23
+ This is *not* meant to be a general usability tool.
24
+ It purposefully lacks progressbars and comes generally as-is.
25
+
26
+ Please file issues *only* if there's an issue on the underlying downloaded file.
27
+
28
+ ## Contributing
29
+
30
+ ```sh
31
+ python3 -m venv ~/.venv/hf_transfer
32
+ source ~/.venv/hf_transfer/bin/activate
33
+ pip install maturin
34
+ maturin develop
35
+ ```
36
+
37
+ ### `huggingface_hub`
38
+
39
+ If you are working on changes with `huggingface_hub`
40
+
41
+ ```sh
42
+ git clone git@github.com:huggingface/huggingface_hub.git
43
+ # git clone https://github.com/huggingface/huggingface_hub.git
44
+
45
+ cd huggingface_hub
46
+ python3 -m pip install -e ".[quality]"
47
+ ```
48
+
49
+ You can use the following test script:
50
+
51
+ ```py
52
+ import os
53
+
54
+ # os.environ["HF_ENDPOINT"] = "http://localhost:5564"
55
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
56
+
57
+ from huggingface_hub import HfApi, logging
58
+
59
+ logging.set_verbosity_debug()
60
+ hf = HfApi()
61
+ hf.upload_file(path_or_fileobj="/path/to/my/repo/some_file", path_in_repo="some_file", repo_id="my/repo", repo_type="model")
62
+ ```
63
+
64
+
python/Lib/site-packages/hf_transfer-0.1.9.dist-info/RECORD ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ hf_transfer-0.1.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ hf_transfer-0.1.9.dist-info/METADATA,sha256=VWLZxM49xoghKmRUqX_s7uQ9O0aM7EZ8EWbpc0OPeqo,1797
3
+ hf_transfer-0.1.9.dist-info/RECORD,,
4
+ hf_transfer-0.1.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ hf_transfer-0.1.9.dist-info/WHEEL,sha256=mYDPFrpmO1_UhonyEoMo2i0zHOwqc92hj_Q3CYuEBdM,94
6
+ hf_transfer-0.1.9.dist-info/licenses/LICENSE,sha256=yGuFwk6lP4-PKnjwjg7B1dmLvfNh2Xxj6ecUTvrrUPQ,11547
7
+ hf_transfer/__init__.py,sha256=0OjYn5WBWp_eK3hJKyYtyMWxAStjTCTRjSh_eXoOldE,127
8
+ hf_transfer/__pycache__/__init__.cpython-313.pyc,,
9
+ hf_transfer/hf_transfer.pyd,sha256=AZ0SvMR1ikAD0FyuEKlKq0KxIa1-7g34FMCxqnzLagA,3111424
python/Lib/site-packages/hf_transfer-0.1.9.dist-info/REQUESTED ADDED
File without changes
python/Lib/site-packages/hf_transfer-0.1.9.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.8.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp38-abi3-win_amd64
python/Lib/site-packages/hf_transfer/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .hf_transfer import *
2
+
3
+ __doc__ = hf_transfer.__doc__
4
+ if hasattr(hf_transfer, "__all__"):
5
+ __all__ = hf_transfer.__all__
python/Lib/site-packages/setuptools/archive_util.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for extracting common archive formats"""
2
+
3
+ import contextlib
4
+ import os
5
+ import posixpath
6
+ import shutil
7
+ import tarfile
8
+ import zipfile
9
+
10
+ from ._path import ensure_directory
11
+
12
+ from distutils.errors import DistutilsError
13
+
14
+ __all__ = [
15
+ "unpack_archive",
16
+ "unpack_zipfile",
17
+ "unpack_tarfile",
18
+ "default_filter",
19
+ "UnrecognizedFormat",
20
+ "extraction_drivers",
21
+ "unpack_directory",
22
+ ]
23
+
24
+
25
+ class UnrecognizedFormat(DistutilsError):
26
+ """Couldn't recognize the archive type"""
27
+
28
+
29
+ def default_filter(src, dst):
30
+ """The default progress/filter callback; returns True for all files"""
31
+ return dst
32
+
33
+
34
+ def unpack_archive(
35
+ filename, extract_dir, progress_filter=default_filter, drivers=None
36
+ ) -> None:
37
+ """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
38
+
39
+ `progress_filter` is a function taking two arguments: a source path
40
+ internal to the archive ('/'-separated), and a filesystem path where it
41
+ will be extracted. The callback must return the desired extract path
42
+ (which may be the same as the one passed in), or else ``None`` to skip
43
+ that file or directory. The callback can thus be used to report on the
44
+ progress of the extraction, as well as to filter the items extracted or
45
+ alter their extraction paths.
46
+
47
+ `drivers`, if supplied, must be a non-empty sequence of functions with the
48
+ same signature as this function (minus the `drivers` argument), that raise
49
+ ``UnrecognizedFormat`` if they do not support extracting the designated
50
+ archive type. The `drivers` are tried in sequence until one is found that
51
+ does not raise an error, or until all are exhausted (in which case
52
+ ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
53
+ drivers, the module's ``extraction_drivers`` constant will be used, which
54
+ means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
55
+ order.
56
+ """
57
+ for driver in drivers or extraction_drivers:
58
+ try:
59
+ driver(filename, extract_dir, progress_filter)
60
+ except UnrecognizedFormat:
61
+ continue
62
+ else:
63
+ return
64
+ else:
65
+ raise UnrecognizedFormat(f"Not a recognized archive type: {filename}")
66
+
67
+
68
+ def unpack_directory(filename, extract_dir, progress_filter=default_filter) -> None:
69
+ """ "Unpack" a directory, using the same interface as for archives
70
+
71
+ Raises ``UnrecognizedFormat`` if `filename` is not a directory
72
+ """
73
+ if not os.path.isdir(filename):
74
+ raise UnrecognizedFormat(f"{filename} is not a directory")
75
+
76
+ paths = {
77
+ filename: ('', extract_dir),
78
+ }
79
+ for base, dirs, files in os.walk(filename):
80
+ src, dst = paths[base]
81
+ for d in dirs:
82
+ paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
83
+ for f in files:
84
+ target = os.path.join(dst, f)
85
+ target = progress_filter(src + f, target)
86
+ if not target:
87
+ # skip non-files
88
+ continue
89
+ ensure_directory(target)
90
+ f = os.path.join(base, f)
91
+ shutil.copyfile(f, target)
92
+ shutil.copystat(f, target)
93
+
94
+
95
+ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter) -> None:
96
+ """Unpack zip `filename` to `extract_dir`
97
+
98
+ Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
99
+ by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
100
+ of the `progress_filter` argument.
101
+ """
102
+
103
+ if not zipfile.is_zipfile(filename):
104
+ raise UnrecognizedFormat(f"{filename} is not a zip file")
105
+
106
+ with zipfile.ZipFile(filename) as z:
107
+ _unpack_zipfile_obj(z, extract_dir, progress_filter)
108
+
109
+
110
+ def _unpack_zipfile_obj(zipfile_obj, extract_dir, progress_filter=default_filter):
111
+ """Internal/private API used by other parts of setuptools.
112
+ Similar to ``unpack_zipfile``, but receives an already opened :obj:`zipfile.ZipFile`
113
+ object instead of a filename.
114
+ """
115
+ for info in zipfile_obj.infolist():
116
+ name = info.filename
117
+
118
+ # don't extract absolute paths or ones with .. in them
119
+ if name.startswith('/') or '..' in name.split('/'):
120
+ continue
121
+
122
+ target = os.path.join(extract_dir, *name.split('/'))
123
+ target = progress_filter(name, target)
124
+ if not target:
125
+ continue
126
+ if name.endswith('/'):
127
+ # directory
128
+ ensure_directory(target)
129
+ else:
130
+ # file
131
+ ensure_directory(target)
132
+ data = zipfile_obj.read(info.filename)
133
+ with open(target, 'wb') as f:
134
+ f.write(data)
135
+ unix_attributes = info.external_attr >> 16
136
+ if unix_attributes:
137
+ os.chmod(target, unix_attributes)
138
+
139
+
140
+ def _resolve_tar_file_or_dir(tar_obj, tar_member_obj):
141
+ """Resolve any links and extract link targets as normal files."""
142
+ while tar_member_obj is not None and (
143
+ tar_member_obj.islnk() or tar_member_obj.issym()
144
+ ):
145
+ linkpath = tar_member_obj.linkname
146
+ if tar_member_obj.issym():
147
+ base = posixpath.dirname(tar_member_obj.name)
148
+ linkpath = posixpath.join(base, linkpath)
149
+ linkpath = posixpath.normpath(linkpath)
150
+ tar_member_obj = tar_obj._getmember(linkpath)
151
+
152
+ is_file_or_dir = tar_member_obj is not None and (
153
+ tar_member_obj.isfile() or tar_member_obj.isdir()
154
+ )
155
+ if is_file_or_dir:
156
+ return tar_member_obj
157
+
158
+ raise LookupError('Got unknown file type')
159
+
160
+
161
+ def _iter_open_tar(tar_obj, extract_dir, progress_filter):
162
+ """Emit member-destination pairs from a tar archive."""
163
+ # don't do any chowning!
164
+ tar_obj.chown = lambda *args: None
165
+
166
+ with contextlib.closing(tar_obj):
167
+ for member in tar_obj:
168
+ name = member.name
169
+ # don't extract absolute paths or ones with .. in them
170
+ if name.startswith('/') or '..' in name.split('/'):
171
+ continue
172
+
173
+ prelim_dst = os.path.join(extract_dir, *name.split('/'))
174
+
175
+ try:
176
+ member = _resolve_tar_file_or_dir(tar_obj, member)
177
+ except LookupError:
178
+ continue
179
+
180
+ final_dst = progress_filter(name, prelim_dst)
181
+ if not final_dst:
182
+ continue
183
+
184
+ if final_dst.endswith(os.sep):
185
+ final_dst = final_dst[:-1]
186
+
187
+ yield member, final_dst
188
+
189
+
190
+ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter) -> bool:
191
+ """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
192
+
193
+ Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
194
+ by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
195
+ of the `progress_filter` argument.
196
+ """
197
+ try:
198
+ tarobj = tarfile.open(filename)
199
+ except tarfile.TarError as e:
200
+ raise UnrecognizedFormat(
201
+ f"{filename} is not a compressed or uncompressed tar file"
202
+ ) from e
203
+
204
+ for member, final_dst in _iter_open_tar(
205
+ tarobj,
206
+ extract_dir,
207
+ progress_filter,
208
+ ):
209
+ try:
210
+ # XXX Ugh
211
+ tarobj._extract_member(member, final_dst)
212
+ except tarfile.ExtractError:
213
+ # chown/chmod/mkfifo/mknode/makedev failed
214
+ pass
215
+
216
+ return True
217
+
218
+
219
+ extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
python/Lib/site-packages/setuptools/build_meta.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A PEP 517 interface to setuptools
2
+
3
+ Previously, when a user or a command line tool (let's call it a "frontend")
4
+ needed to make a request of setuptools to take a certain action, for
5
+ example, generating a list of installation requirements, the frontend
6
+ would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
7
+
8
+ PEP 517 defines a different method of interfacing with setuptools. Rather
9
+ than calling "setup.py" directly, the frontend should:
10
+
11
+ 1. Set the current directory to the directory with a setup.py file
12
+ 2. Import this module into a safe python interpreter (one in which
13
+ setuptools can potentially set global variables or crash hard).
14
+ 3. Call one of the functions defined in PEP 517.
15
+
16
+ What each function does is defined in PEP 517. However, here is a "casual"
17
+ definition of the functions (this definition should not be relied on for
18
+ bug reports or API stability):
19
+
20
+ - `build_wheel`: build a wheel in the folder and return the basename
21
+ - `get_requires_for_build_wheel`: get the `setup_requires` to build
22
+ - `prepare_metadata_for_build_wheel`: get the `install_requires`
23
+ - `build_sdist`: build an sdist in the folder and return the basename
24
+ - `get_requires_for_build_sdist`: get the `setup_requires` to build
25
+
26
+ Again, this is not a formal definition! Just a "taste" of the module.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import contextlib
32
+ import io
33
+ import os
34
+ import shlex
35
+ import shutil
36
+ import sys
37
+ import tempfile
38
+ import tokenize
39
+ import warnings
40
+ from collections.abc import Iterable, Iterator, Mapping
41
+ from pathlib import Path
42
+ from typing import TYPE_CHECKING, NoReturn, Union
43
+
44
+ import setuptools
45
+
46
+ from . import errors
47
+ from ._path import StrPath, same_path
48
+ from ._reqs import parse_strings
49
+ from .warnings import SetuptoolsDeprecationWarning
50
+
51
+ import distutils
52
+ from distutils.util import strtobool
53
+
54
+ if TYPE_CHECKING:
55
+ from typing_extensions import TypeAlias
56
+
57
+ __all__ = [
58
+ 'get_requires_for_build_sdist',
59
+ 'get_requires_for_build_wheel',
60
+ 'prepare_metadata_for_build_wheel',
61
+ 'build_wheel',
62
+ 'build_sdist',
63
+ 'get_requires_for_build_editable',
64
+ 'prepare_metadata_for_build_editable',
65
+ 'build_editable',
66
+ '__legacy__',
67
+ 'SetupRequirementsError',
68
+ ]
69
+
70
+
71
+ class SetupRequirementsError(BaseException):
72
+ def __init__(self, specifiers) -> None:
73
+ self.specifiers = specifiers
74
+
75
+
76
+ class Distribution(setuptools.dist.Distribution):
77
+ def fetch_build_eggs(self, specifiers) -> NoReturn:
78
+ specifier_list = list(parse_strings(specifiers))
79
+
80
+ raise SetupRequirementsError(specifier_list)
81
+
82
+ @classmethod
83
+ @contextlib.contextmanager
84
+ def patch(cls) -> Iterator[None]:
85
+ """
86
+ Replace
87
+ distutils.dist.Distribution with this class
88
+ for the duration of this context.
89
+ """
90
+ orig = distutils.core.Distribution
91
+ distutils.core.Distribution = cls # type: ignore[misc] # monkeypatching
92
+ try:
93
+ yield
94
+ finally:
95
+ distutils.core.Distribution = orig # type: ignore[misc] # monkeypatching
96
+
97
+
98
+ @contextlib.contextmanager
99
+ def no_install_setup_requires():
100
+ """Temporarily disable installing setup_requires
101
+
102
+ Under PEP 517, the backend reports build dependencies to the frontend,
103
+ and the frontend is responsible for ensuring they're installed.
104
+ So setuptools (acting as a backend) should not try to install them.
105
+ """
106
+ orig = setuptools._install_setup_requires
107
+ setuptools._install_setup_requires = lambda attrs: None
108
+ try:
109
+ yield
110
+ finally:
111
+ setuptools._install_setup_requires = orig
112
+
113
+
114
+ def _get_immediate_subdirectories(a_dir):
115
+ return [
116
+ name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))
117
+ ]
118
+
119
+
120
+ def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
121
+ matching = (f for f in os.listdir(directory) if f.endswith(extension))
122
+ try:
123
+ (file,) = matching
124
+ except ValueError:
125
+ raise ValueError(
126
+ 'No distribution was found. Ensure that `setup.py` '
127
+ 'is not empty and that it calls `setup()`.'
128
+ ) from None
129
+ return file
130
+
131
+
132
+ def _open_setup_script(setup_script):
133
+ if not os.path.exists(setup_script):
134
+ # Supply a default setup.py
135
+ return io.StringIO("from setuptools import setup; setup()")
136
+
137
+ return tokenize.open(setup_script)
138
+
139
+
140
+ @contextlib.contextmanager
141
+ def suppress_known_deprecation():
142
+ with warnings.catch_warnings():
143
+ warnings.filterwarnings('ignore', 'setup.py install is deprecated')
144
+ yield
145
+
146
+
147
+ _ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, list[str], None]], None]
148
+ """
149
+ Currently the user can run::
150
+
151
+ pip install -e . --config-settings key=value
152
+ python -m build -C--key=value -C key=value
153
+
154
+ - pip will pass both key and value as strings and overwriting repeated keys
155
+ (pypa/pip#11059).
156
+ - build will accumulate values associated with repeated keys in a list.
157
+ It will also accept keys with no associated value.
158
+ This means that an option passed by build can be ``str | list[str] | None``.
159
+ - PEP 517 specifies that ``config_settings`` is an optional dict.
160
+ """
161
+
162
+
163
+ class _ConfigSettingsTranslator:
164
+ """Translate ``config_settings`` into distutils-style command arguments.
165
+ Only a limited number of options is currently supported.
166
+ """
167
+
168
+ # See pypa/setuptools#1928 pypa/setuptools#2491
169
+
170
+ def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
171
+ """
172
+ Get the value of a specific key in ``config_settings`` as a list of strings.
173
+
174
+ >>> fn = _ConfigSettingsTranslator()._get_config
175
+ >>> fn("--global-option", None)
176
+ []
177
+ >>> fn("--global-option", {})
178
+ []
179
+ >>> fn("--global-option", {'--global-option': 'foo'})
180
+ ['foo']
181
+ >>> fn("--global-option", {'--global-option': ['foo']})
182
+ ['foo']
183
+ >>> fn("--global-option", {'--global-option': 'foo'})
184
+ ['foo']
185
+ >>> fn("--global-option", {'--global-option': 'foo bar'})
186
+ ['foo', 'bar']
187
+ """
188
+ cfg = config_settings or {}
189
+ opts = cfg.get(key) or []
190
+ return shlex.split(opts) if isinstance(opts, str) else opts
191
+
192
+ def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
193
+ """
194
+ Let the user specify ``verbose`` or ``quiet`` + escape hatch via
195
+ ``--global-option``.
196
+ Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
197
+ so we just have to cover the basic scenario ``-v``.
198
+
199
+ >>> fn = _ConfigSettingsTranslator()._global_args
200
+ >>> list(fn(None))
201
+ []
202
+ >>> list(fn({"verbose": "False"}))
203
+ ['-q']
204
+ >>> list(fn({"verbose": "1"}))
205
+ ['-v']
206
+ >>> list(fn({"--verbose": None}))
207
+ ['-v']
208
+ >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
209
+ ['-v', '-q', '--no-user-cfg']
210
+ >>> list(fn({"--quiet": None}))
211
+ ['-q']
212
+ """
213
+ cfg = config_settings or {}
214
+ falsey = {"false", "no", "0", "off"}
215
+ if "verbose" in cfg or "--verbose" in cfg:
216
+ level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
217
+ yield ("-q" if level.lower() in falsey else "-v")
218
+ if "quiet" in cfg or "--quiet" in cfg:
219
+ level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
220
+ yield ("-v" if level.lower() in falsey else "-q")
221
+
222
+ yield from self._get_config("--global-option", config_settings)
223
+
224
+ def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
225
+ """
226
+ The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
227
+
228
+ .. warning::
229
+ We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
230
+ commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
231
+ directory created in ``prepare_metadata_for_build_wheel``.
232
+
233
+ >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
234
+ >>> list(fn(None))
235
+ []
236
+ >>> list(fn({"tag-date": "False"}))
237
+ ['--no-date']
238
+ >>> list(fn({"tag-date": None}))
239
+ ['--no-date']
240
+ >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
241
+ ['--tag-date', '--tag-build', '.a']
242
+ """
243
+ cfg = config_settings or {}
244
+ if "tag-date" in cfg:
245
+ val = strtobool(str(cfg["tag-date"] or "false"))
246
+ yield ("--tag-date" if val else "--no-date")
247
+ if "tag-build" in cfg:
248
+ yield from ["--tag-build", str(cfg["tag-build"])]
249
+
250
+ def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
251
+ """
252
+ The ``editable_wheel`` command accepts ``editable-mode=strict``.
253
+
254
+ >>> fn = _ConfigSettingsTranslator()._editable_args
255
+ >>> list(fn(None))
256
+ []
257
+ >>> list(fn({"editable-mode": "strict"}))
258
+ ['--mode', 'strict']
259
+ """
260
+ cfg = config_settings or {}
261
+ mode = cfg.get("editable-mode") or cfg.get("editable_mode")
262
+ if not mode:
263
+ return
264
+ yield from ["--mode", str(mode)]
265
+
266
+ def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
267
+ """
268
+ Users may expect to pass arbitrary lists of arguments to a command
269
+ via "--global-option" (example provided in PEP 517 of a "escape hatch").
270
+
271
+ >>> fn = _ConfigSettingsTranslator()._arbitrary_args
272
+ >>> list(fn(None))
273
+ []
274
+ >>> list(fn({}))
275
+ []
276
+ >>> list(fn({'--build-option': 'foo'}))
277
+ ['foo']
278
+ >>> list(fn({'--build-option': ['foo']}))
279
+ ['foo']
280
+ >>> list(fn({'--build-option': 'foo'}))
281
+ ['foo']
282
+ >>> list(fn({'--build-option': 'foo bar'}))
283
+ ['foo', 'bar']
284
+ >>> list(fn({'--global-option': 'foo'}))
285
+ []
286
+ """
287
+ yield from self._get_config("--build-option", config_settings)
288
+
289
+
290
+ class _BuildMetaBackend(_ConfigSettingsTranslator):
291
+ def _get_build_requires(
292
+ self, config_settings: _ConfigSettings, requirements: list[str]
293
+ ):
294
+ sys.argv = [
295
+ *sys.argv[:1],
296
+ *self._global_args(config_settings),
297
+ "egg_info",
298
+ ]
299
+ try:
300
+ with Distribution.patch():
301
+ self.run_setup()
302
+ except SetupRequirementsError as e:
303
+ requirements += e.specifiers
304
+
305
+ return requirements
306
+
307
+ def run_setup(self, setup_script: str = 'setup.py') -> None:
308
+ # Note that we can reuse our build directory between calls
309
+ # Correctness comes first, then optimization later
310
+ __file__ = os.path.abspath(setup_script)
311
+ __name__ = '__main__'
312
+
313
+ with _open_setup_script(__file__) as f:
314
+ code = f.read().replace(r'\r\n', r'\n')
315
+
316
+ try:
317
+ exec(code, locals())
318
+ except SystemExit as e:
319
+ if e.code:
320
+ raise
321
+ # We ignore exit code indicating success
322
+ SetuptoolsDeprecationWarning.emit(
323
+ "Running `setup.py` directly as CLI tool is deprecated.",
324
+ "Please avoid using `sys.exit(0)` or similar statements "
325
+ "that don't fit in the paradigm of a configuration file.",
326
+ see_url="https://blog.ganssle.io/articles/2021/10/"
327
+ "setup-py-deprecated.html",
328
+ )
329
+
330
+ def get_requires_for_build_wheel(
331
+ self, config_settings: _ConfigSettings = None
332
+ ) -> list[str]:
333
+ return self._get_build_requires(config_settings, requirements=[])
334
+
335
+ def get_requires_for_build_sdist(
336
+ self, config_settings: _ConfigSettings = None
337
+ ) -> list[str]:
338
+ return self._get_build_requires(config_settings, requirements=[])
339
+
340
+ def _bubble_up_info_directory(
341
+ self, metadata_directory: StrPath, suffix: str
342
+ ) -> str:
343
+ """
344
+ PEP 517 requires that the .dist-info directory be placed in the
345
+ metadata_directory. To comply, we MUST copy the directory to the root.
346
+
347
+ Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
348
+ """
349
+ info_dir = self._find_info_directory(metadata_directory, suffix)
350
+ if not same_path(info_dir.parent, metadata_directory):
351
+ shutil.move(str(info_dir), metadata_directory)
352
+ # PEP 517 allow other files and dirs to exist in metadata_directory
353
+ return info_dir.name
354
+
355
+ def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path:
356
+ for parent, dirs, _ in os.walk(metadata_directory):
357
+ candidates = [f for f in dirs if f.endswith(suffix)]
358
+
359
+ if len(candidates) != 0 or len(dirs) != 1:
360
+ assert len(candidates) == 1, (
361
+ f"Exactly one {suffix} should have been produced, but found {len(candidates)}: {candidates}"
362
+ )
363
+ return Path(parent, candidates[0])
364
+
365
+ msg = f"No {suffix} directory found in {metadata_directory}"
366
+ raise errors.InternalError(msg)
367
+
368
+ def prepare_metadata_for_build_wheel(
369
+ self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
370
+ ) -> str:
371
+ sys.argv = [
372
+ *sys.argv[:1],
373
+ *self._global_args(config_settings),
374
+ "dist_info",
375
+ "--output-dir",
376
+ str(metadata_directory),
377
+ "--keep-egg-info",
378
+ ]
379
+ with no_install_setup_requires():
380
+ self.run_setup()
381
+
382
+ self._bubble_up_info_directory(metadata_directory, ".egg-info")
383
+ return self._bubble_up_info_directory(metadata_directory, ".dist-info")
384
+
385
+ def _build_with_temp_dir(
386
+ self,
387
+ setup_command: Iterable[str],
388
+ result_extension: str | tuple[str, ...],
389
+ result_directory: StrPath,
390
+ config_settings: _ConfigSettings,
391
+ arbitrary_args: Iterable[str] = (),
392
+ ):
393
+ result_directory = os.path.abspath(result_directory)
394
+
395
+ # Build in a temporary directory, then copy to the target.
396
+ os.makedirs(result_directory, exist_ok=True)
397
+
398
+ with tempfile.TemporaryDirectory(
399
+ prefix=".tmp-", dir=result_directory
400
+ ) as tmp_dist_dir:
401
+ sys.argv = [
402
+ *sys.argv[:1],
403
+ *self._global_args(config_settings),
404
+ *setup_command,
405
+ "--dist-dir",
406
+ tmp_dist_dir,
407
+ *arbitrary_args,
408
+ ]
409
+ with no_install_setup_requires():
410
+ self.run_setup()
411
+
412
+ result_basename = _file_with_extension(tmp_dist_dir, result_extension)
413
+ result_path = os.path.join(result_directory, result_basename)
414
+ if os.path.exists(result_path):
415
+ # os.rename will fail overwriting on non-Unix.
416
+ os.remove(result_path)
417
+ os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
418
+
419
+ return result_basename
420
+
421
+ def build_wheel(
422
+ self,
423
+ wheel_directory: StrPath,
424
+ config_settings: _ConfigSettings = None,
425
+ metadata_directory: StrPath | None = None,
426
+ ) -> str:
427
+ def _build(cmd: list[str]):
428
+ with suppress_known_deprecation():
429
+ return self._build_with_temp_dir(
430
+ cmd,
431
+ '.whl',
432
+ wheel_directory,
433
+ config_settings,
434
+ self._arbitrary_args(config_settings),
435
+ )
436
+
437
+ if metadata_directory is None:
438
+ return _build(['bdist_wheel'])
439
+
440
+ try:
441
+ return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
442
+ except SystemExit as ex: # pragma: nocover
443
+ # pypa/setuptools#4683
444
+ if "--dist-info-dir not recognized" not in str(ex):
445
+ raise
446
+ _IncompatibleBdistWheel.emit()
447
+ return _build(['bdist_wheel'])
448
+
449
+ def build_sdist(
450
+ self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
451
+ ) -> str:
452
+ return self._build_with_temp_dir(
453
+ ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
454
+ )
455
+
456
+ def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
457
+ if not metadata_directory:
458
+ return None
459
+ dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
460
+ assert len(dist_info_candidates) <= 1
461
+ return str(dist_info_candidates[0]) if dist_info_candidates else None
462
+
463
+ def build_editable(
464
+ self,
465
+ wheel_directory: StrPath,
466
+ config_settings: _ConfigSettings = None,
467
+ metadata_directory: StrPath | None = None,
468
+ ) -> str:
469
+ # XXX can or should we hide our editable_wheel command normally?
470
+ info_dir = self._get_dist_info_dir(metadata_directory)
471
+ opts = ["--dist-info-dir", info_dir] if info_dir else []
472
+ cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
473
+ with suppress_known_deprecation():
474
+ return self._build_with_temp_dir(
475
+ cmd, ".whl", wheel_directory, config_settings
476
+ )
477
+
478
+ def get_requires_for_build_editable(
479
+ self, config_settings: _ConfigSettings = None
480
+ ) -> list[str]:
481
+ return self.get_requires_for_build_wheel(config_settings)
482
+
483
+ def prepare_metadata_for_build_editable(
484
+ self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
485
+ ) -> str:
486
+ return self.prepare_metadata_for_build_wheel(
487
+ metadata_directory, config_settings
488
+ )
489
+
490
+
491
+ class _BuildMetaLegacyBackend(_BuildMetaBackend):
492
+ """Compatibility backend for setuptools
493
+
494
+ This is a version of setuptools.build_meta that endeavors
495
+ to maintain backwards
496
+ compatibility with pre-PEP 517 modes of invocation. It
497
+ exists as a temporary
498
+ bridge between the old packaging mechanism and the new
499
+ packaging mechanism,
500
+ and will eventually be removed.
501
+ """
502
+
503
+ def run_setup(self, setup_script: str = 'setup.py') -> None:
504
+ # In order to maintain compatibility with scripts assuming that
505
+ # the setup.py script is in a directory on the PYTHONPATH, inject
506
+ # '' into sys.path. (pypa/setuptools#1642)
507
+ sys_path = list(sys.path) # Save the original path
508
+
509
+ script_dir = os.path.dirname(os.path.abspath(setup_script))
510
+ if script_dir not in sys.path:
511
+ sys.path.insert(0, script_dir)
512
+
513
+ # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
514
+ # get the directory of the source code. They expect it to refer to the
515
+ # setup.py script.
516
+ sys_argv_0 = sys.argv[0]
517
+ sys.argv[0] = setup_script
518
+
519
+ try:
520
+ super().run_setup(setup_script=setup_script)
521
+ finally:
522
+ # While PEP 517 frontends should be calling each hook in a fresh
523
+ # subprocess according to the standard (and thus it should not be
524
+ # strictly necessary to restore the old sys.path), we'll restore
525
+ # the original path so that the path manipulation does not persist
526
+ # within the hook after run_setup is called.
527
+ sys.path[:] = sys_path
528
+ sys.argv[0] = sys_argv_0
529
+
530
+
531
+ class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
532
+ _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
533
+ _DETAILS = """
534
+ Ensure that any custom bdist_wheel implementation is a subclass of
535
+ setuptools.command.bdist_wheel.bdist_wheel.
536
+ """
537
+ _DUE_DATE = (2025, 10, 15)
538
+ # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
539
+ _SEE_URL = "https://github.com/pypa/wheel/pull/631"
540
+
541
+
542
+ # The primary backend
543
+ _BACKEND = _BuildMetaBackend()
544
+
545
+ get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
546
+ get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
547
+ prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
548
+ build_wheel = _BACKEND.build_wheel
549
+ build_sdist = _BACKEND.build_sdist
550
+ get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
551
+ prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
552
+ build_editable = _BACKEND.build_editable
553
+
554
+
555
+ # The legacy backend
556
+ __legacy__ = _BuildMetaLegacyBackend()
python/Lib/site-packages/setuptools/cli-32.exe ADDED
Binary file (11.8 kB). View file
 
python/Lib/site-packages/setuptools/cli-64.exe ADDED
Binary file (14.3 kB). View file
 
python/Lib/site-packages/setuptools/cli-arm64.exe ADDED
Binary file (13.8 kB). View file
 
python/Lib/site-packages/setuptools/cli.exe ADDED
Binary file (11.8 kB). View file
 
python/Lib/site-packages/setuptools/depends.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dis
5
+ import marshal
6
+ import sys
7
+ from types import CodeType
8
+ from typing import Any, Literal, TypeVar
9
+
10
+ from packaging.version import Version
11
+
12
+ from . import _imp
13
+ from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module
14
+
15
+ _T = TypeVar("_T")
16
+
17
+ __all__ = ['Require', 'find_module']
18
+
19
+
20
+ class Require:
21
+ """A prerequisite to building or installing a distribution"""
22
+
23
+ def __init__(
24
+ self,
25
+ name,
26
+ requested_version,
27
+ module,
28
+ homepage: str = '',
29
+ attribute=None,
30
+ format=None,
31
+ ) -> None:
32
+ if format is None and requested_version is not None:
33
+ format = Version
34
+
35
+ if format is not None:
36
+ requested_version = format(requested_version)
37
+ if attribute is None:
38
+ attribute = '__version__'
39
+
40
+ self.__dict__.update(locals())
41
+ del self.self
42
+
43
+ def full_name(self):
44
+ """Return full package/distribution name, w/version"""
45
+ if self.requested_version is not None:
46
+ return f'{self.name}-{self.requested_version}'
47
+ return self.name
48
+
49
+ def version_ok(self, version):
50
+ """Is 'version' sufficiently up-to-date?"""
51
+ return (
52
+ self.attribute is None
53
+ or self.format is None
54
+ or str(version) != "unknown"
55
+ and self.format(version) >= self.requested_version
56
+ )
57
+
58
+ def get_version(
59
+ self, paths=None, default: _T | Literal["unknown"] = "unknown"
60
+ ) -> _T | Literal["unknown"] | None | Any:
61
+ """Get version number of installed module, 'None', or 'default'
62
+
63
+ Search 'paths' for module. If not found, return 'None'. If found,
64
+ return the extracted version attribute, or 'default' if no version
65
+ attribute was specified, or the value cannot be determined without
66
+ importing the module. The version is formatted according to the
67
+ requirement's version format (if any), unless it is 'None' or the
68
+ supplied 'default'.
69
+ """
70
+
71
+ if self.attribute is None:
72
+ try:
73
+ f, _p, _i = find_module(self.module, paths)
74
+ except ImportError:
75
+ return None
76
+ if f:
77
+ f.close()
78
+ return default
79
+
80
+ v = get_module_constant(self.module, self.attribute, default, paths)
81
+
82
+ if v is not None and v is not default and self.format is not None:
83
+ return self.format(v)
84
+
85
+ return v
86
+
87
+ def is_present(self, paths=None):
88
+ """Return true if dependency is present on 'paths'"""
89
+ return self.get_version(paths) is not None
90
+
91
+ def is_current(self, paths=None):
92
+ """Return true if dependency is present and up-to-date on 'paths'"""
93
+ version = self.get_version(paths)
94
+ if version is None:
95
+ return False
96
+ return self.version_ok(str(version))
97
+
98
+
99
+ def maybe_close(f):
100
+ @contextlib.contextmanager
101
+ def empty():
102
+ yield
103
+ return
104
+
105
+ if not f:
106
+ return empty()
107
+
108
+ return contextlib.closing(f)
109
+
110
+
111
+ # Some objects are not available on some platforms.
112
+ # XXX it'd be better to test assertions about bytecode instead.
113
+ if not sys.platform.startswith('java') and sys.platform != 'cli':
114
+
115
+ def get_module_constant(
116
+ module, symbol, default: _T | int = -1, paths=None
117
+ ) -> _T | int | None | Any:
118
+ """Find 'module' by searching 'paths', and extract 'symbol'
119
+
120
+ Return 'None' if 'module' does not exist on 'paths', or it does not define
121
+ 'symbol'. If the module defines 'symbol' as a constant, return the
122
+ constant. Otherwise, return 'default'."""
123
+
124
+ try:
125
+ f, path, (_suffix, _mode, kind) = info = find_module(module, paths)
126
+ except ImportError:
127
+ # Module doesn't exist
128
+ return None
129
+
130
+ with maybe_close(f):
131
+ if kind == PY_COMPILED:
132
+ f.read(8) # skip magic & date
133
+ code = marshal.load(f)
134
+ elif kind == PY_FROZEN:
135
+ code = _imp.get_frozen_object(module, paths)
136
+ elif kind == PY_SOURCE:
137
+ code = compile(f.read(), path, 'exec')
138
+ else:
139
+ # Not something we can parse; we'll have to import it. :(
140
+ imported = _imp.get_module(module, paths, info)
141
+ return getattr(imported, symbol, None)
142
+
143
+ return extract_constant(code, symbol, default)
144
+
145
+ def extract_constant(
146
+ code: CodeType, symbol: str, default: _T | int = -1
147
+ ) -> _T | int | None | Any:
148
+ """Extract the constant value of 'symbol' from 'code'
149
+
150
+ If the name 'symbol' is bound to a constant value by the Python code
151
+ object 'code', return that value. If 'symbol' is bound to an expression,
152
+ return 'default'. Otherwise, return 'None'.
153
+
154
+ Return value is based on the first assignment to 'symbol'. 'symbol' must
155
+ be a global, or at least a non-"fast" local in the code block. That is,
156
+ only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
157
+ must be present in 'code.co_names'.
158
+ """
159
+ if symbol not in code.co_names:
160
+ # name's not there, can't possibly be an assignment
161
+ return None
162
+
163
+ name_idx = list(code.co_names).index(symbol)
164
+
165
+ STORE_NAME = dis.opmap['STORE_NAME']
166
+ STORE_GLOBAL = dis.opmap['STORE_GLOBAL']
167
+ LOAD_CONST = dis.opmap['LOAD_CONST']
168
+
169
+ const = default
170
+
171
+ for byte_code in dis.Bytecode(code):
172
+ op = byte_code.opcode
173
+ arg = byte_code.arg
174
+
175
+ if op == LOAD_CONST:
176
+ assert arg is not None
177
+ const = code.co_consts[arg]
178
+ elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
179
+ return const
180
+ else:
181
+ const = default
182
+
183
+ return None
184
+
185
+ __all__ += ['get_module_constant', 'extract_constant']
python/Lib/site-packages/setuptools/discovery.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Automatic discovery of Python modules and packages (for inclusion in the
2
+ distribution) and other config values.
3
+
4
+ For the purposes of this module, the following nomenclature is used:
5
+
6
+ - "src-layout": a directory representing a Python project that contains a "src"
7
+ folder. Everything under the "src" folder is meant to be included in the
8
+ distribution when packaging the project. Example::
9
+
10
+ .
11
+ ├── tox.ini
12
+ ├── pyproject.toml
13
+ └── src/
14
+ └── mypkg/
15
+ ├── __init__.py
16
+ ├── mymodule.py
17
+ └── my_data_file.txt
18
+
19
+ - "flat-layout": a Python project that does not use "src-layout" but instead
20
+ have a directory under the project root for each package::
21
+
22
+ .
23
+ ├── tox.ini
24
+ ├── pyproject.toml
25
+ └── mypkg/
26
+ ├── __init__.py
27
+ ├── mymodule.py
28
+ └── my_data_file.txt
29
+
30
+ - "single-module": a project that contains a single Python script direct under
31
+ the project root (no directory used)::
32
+
33
+ .
34
+ ├── tox.ini
35
+ ├── pyproject.toml
36
+ └── mymodule.py
37
+
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import itertools
43
+ import os
44
+ from collections.abc import Iterable, Iterator, Mapping
45
+ from fnmatch import fnmatchcase
46
+ from glob import glob
47
+ from pathlib import Path
48
+ from typing import TYPE_CHECKING, ClassVar
49
+
50
+ import _distutils_hack.override # noqa: F401
51
+
52
+ from ._path import StrPath
53
+
54
+ from distutils import log
55
+ from distutils.util import convert_path
56
+
57
+ if TYPE_CHECKING:
58
+ from setuptools import Distribution
59
+
60
+ chain_iter = itertools.chain.from_iterable
61
+
62
+
63
+ def _valid_name(path: StrPath) -> bool:
64
+ # Ignore invalid names that cannot be imported directly
65
+ return os.path.basename(path).isidentifier()
66
+
67
+
68
+ class _Filter:
69
+ """
70
+ Given a list of patterns, create a callable that will be true only if
71
+ the input matches at least one of the patterns.
72
+ """
73
+
74
+ def __init__(self, *patterns: str) -> None:
75
+ self._patterns = dict.fromkeys(patterns)
76
+
77
+ def __call__(self, item: str) -> bool:
78
+ return any(fnmatchcase(item, pat) for pat in self._patterns)
79
+
80
+ def __contains__(self, item: str) -> bool:
81
+ return item in self._patterns
82
+
83
+
84
+ class _Finder:
85
+ """Base class that exposes functionality for module/package finders"""
86
+
87
+ ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] = ()
88
+ DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] = ()
89
+
90
+ @classmethod
91
+ def find(
92
+ cls,
93
+ where: StrPath = '.',
94
+ exclude: Iterable[str] = (),
95
+ include: Iterable[str] = ('*',),
96
+ ) -> list[str]:
97
+ """Return a list of all Python items (packages or modules, depending on
98
+ the finder implementation) found within directory ``where``.
99
+
100
+ ``where`` is the root directory which will be searched.
101
+ It should be supplied as a "cross-platform" (i.e. URL-style) path;
102
+ it will be converted to the appropriate local path syntax.
103
+
104
+ ``exclude`` is a sequence of names to exclude; ``*`` can be used
105
+ as a wildcard in the names.
106
+ When finding packages, ``foo.*`` will exclude all subpackages of ``foo``
107
+ (but not ``foo`` itself).
108
+
109
+ ``include`` is a sequence of names to include.
110
+ If it's specified, only the named items will be included.
111
+ If it's not specified, all found items will be included.
112
+ ``include`` can contain shell style wildcard patterns just like
113
+ ``exclude``.
114
+ """
115
+
116
+ exclude = exclude or cls.DEFAULT_EXCLUDE
117
+ return list(
118
+ cls._find_iter(
119
+ convert_path(str(where)),
120
+ _Filter(*cls.ALWAYS_EXCLUDE, *exclude),
121
+ _Filter(*include),
122
+ )
123
+ )
124
+
125
+ @classmethod
126
+ def _find_iter(
127
+ cls, where: StrPath, exclude: _Filter, include: _Filter
128
+ ) -> Iterator[str]:
129
+ raise NotImplementedError
130
+
131
+
132
+ class PackageFinder(_Finder):
133
+ """
134
+ Generate a list of all Python packages found within a directory
135
+ """
136
+
137
+ ALWAYS_EXCLUDE = ("ez_setup", "*__pycache__")
138
+
139
+ @classmethod
140
+ def _find_iter(
141
+ cls, where: StrPath, exclude: _Filter, include: _Filter
142
+ ) -> Iterator[str]:
143
+ """
144
+ All the packages found in 'where' that pass the 'include' filter, but
145
+ not the 'exclude' filter.
146
+ """
147
+ for root, dirs, files in os.walk(str(where), followlinks=True):
148
+ # Copy dirs to iterate over it, then empty dirs.
149
+ all_dirs = dirs[:]
150
+ dirs[:] = []
151
+
152
+ for dir in all_dirs:
153
+ full_path = os.path.join(root, dir)
154
+ rel_path = os.path.relpath(full_path, where)
155
+ package = rel_path.replace(os.path.sep, '.')
156
+
157
+ # Skip directory trees that are not valid packages
158
+ if '.' in dir or not cls._looks_like_package(full_path, package):
159
+ continue
160
+
161
+ # Should this package be included?
162
+ if include(package) and not exclude(package):
163
+ yield package
164
+
165
+ # Early pruning if there is nothing else to be scanned
166
+ if f"{package}*" in exclude or f"{package}.*" in exclude:
167
+ continue
168
+
169
+ # Keep searching subdirectories, as there may be more packages
170
+ # down there, even if the parent was excluded.
171
+ dirs.append(dir)
172
+
173
+ @staticmethod
174
+ def _looks_like_package(path: StrPath, _package_name: str) -> bool:
175
+ """Does a directory look like a package?"""
176
+ return os.path.isfile(os.path.join(path, '__init__.py'))
177
+
178
+
179
+ class PEP420PackageFinder(PackageFinder):
180
+ @staticmethod
181
+ def _looks_like_package(_path: StrPath, _package_name: str) -> bool:
182
+ return True
183
+
184
+
185
+ class ModuleFinder(_Finder):
186
+ """Find isolated Python modules.
187
+ This function will **not** recurse subdirectories.
188
+ """
189
+
190
+ @classmethod
191
+ def _find_iter(
192
+ cls, where: StrPath, exclude: _Filter, include: _Filter
193
+ ) -> Iterator[str]:
194
+ for file in glob(os.path.join(where, "*.py")):
195
+ module, _ext = os.path.splitext(os.path.basename(file))
196
+
197
+ if not cls._looks_like_module(module):
198
+ continue
199
+
200
+ if include(module) and not exclude(module):
201
+ yield module
202
+
203
+ _looks_like_module = staticmethod(_valid_name)
204
+
205
+
206
+ # We have to be extra careful in the case of flat layout to not include files
207
+ # and directories not meant for distribution (e.g. tool-related)
208
+
209
+
210
+ class FlatLayoutPackageFinder(PEP420PackageFinder):
211
+ _EXCLUDE = (
212
+ "ci",
213
+ "bin",
214
+ "debian",
215
+ "doc",
216
+ "docs",
217
+ "documentation",
218
+ "manpages",
219
+ "news",
220
+ "newsfragments",
221
+ "changelog",
222
+ "test",
223
+ "tests",
224
+ "unit_test",
225
+ "unit_tests",
226
+ "example",
227
+ "examples",
228
+ "scripts",
229
+ "tools",
230
+ "util",
231
+ "utils",
232
+ "python",
233
+ "build",
234
+ "dist",
235
+ "venv",
236
+ "env",
237
+ "requirements",
238
+ # ---- Task runners / Build tools ----
239
+ "tasks", # invoke
240
+ "fabfile", # fabric
241
+ "site_scons", # SCons
242
+ # ---- Other tools ----
243
+ "benchmark",
244
+ "benchmarks",
245
+ "exercise",
246
+ "exercises",
247
+ "htmlcov", # Coverage.py
248
+ # ---- Hidden directories/Private packages ----
249
+ "[._]*",
250
+ )
251
+
252
+ DEFAULT_EXCLUDE = tuple(chain_iter((p, f"{p}.*") for p in _EXCLUDE))
253
+ """Reserved package names"""
254
+
255
+ @staticmethod
256
+ def _looks_like_package(_path: StrPath, package_name: str) -> bool:
257
+ names = package_name.split('.')
258
+ # Consider PEP 561
259
+ root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs")
260
+ return root_pkg_is_valid and all(name.isidentifier() for name in names[1:])
261
+
262
+
263
+ class FlatLayoutModuleFinder(ModuleFinder):
264
+ DEFAULT_EXCLUDE = (
265
+ "setup",
266
+ "conftest",
267
+ "test",
268
+ "tests",
269
+ "example",
270
+ "examples",
271
+ "build",
272
+ # ---- Task runners ----
273
+ "toxfile",
274
+ "noxfile",
275
+ "pavement",
276
+ "dodo",
277
+ "tasks",
278
+ "fabfile",
279
+ # ---- Other tools ----
280
+ "[Ss][Cc]onstruct", # SCons
281
+ "conanfile", # Connan: C/C++ build tool
282
+ "manage", # Django
283
+ "benchmark",
284
+ "benchmarks",
285
+ "exercise",
286
+ "exercises",
287
+ # ---- Hidden files/Private modules ----
288
+ "[._]*",
289
+ )
290
+ """Reserved top-level module names"""
291
+
292
+
293
+ def _find_packages_within(root_pkg: str, pkg_dir: StrPath) -> list[str]:
294
+ nested = PEP420PackageFinder.find(pkg_dir)
295
+ return [root_pkg] + [".".join((root_pkg, n)) for n in nested]
296
+
297
+
298
+ class ConfigDiscovery:
299
+ """Fill-in metadata and options that can be automatically derived
300
+ (from other metadata/options, the file system or conventions)
301
+ """
302
+
303
+ def __init__(self, distribution: Distribution) -> None:
304
+ self.dist = distribution
305
+ self._called = False
306
+ self._disabled = False
307
+ self._skip_ext_modules = False
308
+
309
+ def _disable(self):
310
+ """Internal API to disable automatic discovery"""
311
+ self._disabled = True
312
+
313
+ def _ignore_ext_modules(self):
314
+ """Internal API to disregard ext_modules.
315
+
316
+ Normally auto-discovery would not be triggered if ``ext_modules`` are set
317
+ (this is done for backward compatibility with existing packages relying on
318
+ ``setup.py`` or ``setup.cfg``). However, ``setuptools`` can call this function
319
+ to ignore given ``ext_modules`` and proceed with the auto-discovery if
320
+ ``packages`` and ``py_modules`` are not given (e.g. when using pyproject.toml
321
+ metadata).
322
+ """
323
+ self._skip_ext_modules = True
324
+
325
+ @property
326
+ def _root_dir(self) -> StrPath:
327
+ # The best is to wait until `src_root` is set in dist, before using _root_dir.
328
+ return self.dist.src_root or os.curdir
329
+
330
+ @property
331
+ def _package_dir(self) -> dict[str, str]:
332
+ if self.dist.package_dir is None:
333
+ return {}
334
+ return self.dist.package_dir
335
+
336
+ def __call__(
337
+ self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False
338
+ ) -> None:
339
+ """Automatically discover missing configuration fields
340
+ and modifies the given ``distribution`` object in-place.
341
+
342
+ Note that by default this will only have an effect the first time the
343
+ ``ConfigDiscovery`` object is called.
344
+
345
+ To repeatedly invoke automatic discovery (e.g. when the project
346
+ directory changes), please use ``force=True`` (or create a new
347
+ ``ConfigDiscovery`` instance).
348
+ """
349
+ if force is False and (self._called or self._disabled):
350
+ # Avoid overhead of multiple calls
351
+ return
352
+
353
+ self._analyse_package_layout(ignore_ext_modules)
354
+ if name:
355
+ self.analyse_name() # depends on ``packages`` and ``py_modules``
356
+
357
+ self._called = True
358
+
359
+ def _explicitly_specified(self, ignore_ext_modules: bool) -> bool:
360
+ """``True`` if the user has specified some form of package/module listing"""
361
+ ignore_ext_modules = ignore_ext_modules or self._skip_ext_modules
362
+ ext_modules = not (self.dist.ext_modules is None or ignore_ext_modules)
363
+ return (
364
+ self.dist.packages is not None
365
+ or self.dist.py_modules is not None
366
+ or ext_modules
367
+ or hasattr(self.dist, "configuration")
368
+ and self.dist.configuration
369
+ # ^ Some projects use numpy.distutils.misc_util.Configuration
370
+ )
371
+
372
+ def _analyse_package_layout(self, ignore_ext_modules: bool) -> bool:
373
+ if self._explicitly_specified(ignore_ext_modules):
374
+ # For backward compatibility, just try to find modules/packages
375
+ # when nothing is given
376
+ return True
377
+
378
+ log.debug(
379
+ "No `packages` or `py_modules` configuration, performing "
380
+ "automatic discovery."
381
+ )
382
+
383
+ return (
384
+ self._analyse_explicit_layout()
385
+ or self._analyse_src_layout()
386
+ # flat-layout is the trickiest for discovery so it should be last
387
+ or self._analyse_flat_layout()
388
+ )
389
+
390
+ def _analyse_explicit_layout(self) -> bool:
391
+ """The user can explicitly give a package layout via ``package_dir``"""
392
+ package_dir = self._package_dir.copy() # don't modify directly
393
+ package_dir.pop("", None) # This falls under the "src-layout" umbrella
394
+ root_dir = self._root_dir
395
+
396
+ if not package_dir:
397
+ return False
398
+
399
+ log.debug(f"`explicit-layout` detected -- analysing {package_dir}")
400
+ pkgs = chain_iter(
401
+ _find_packages_within(pkg, os.path.join(root_dir, parent_dir))
402
+ for pkg, parent_dir in package_dir.items()
403
+ )
404
+ self.dist.packages = list(pkgs)
405
+ log.debug(f"discovered packages -- {self.dist.packages}")
406
+ return True
407
+
408
+ def _analyse_src_layout(self) -> bool:
409
+ """Try to find all packages or modules under the ``src`` directory
410
+ (or anything pointed by ``package_dir[""]``).
411
+
412
+ The "src-layout" is relatively safe for automatic discovery.
413
+ We assume that everything within is meant to be included in the
414
+ distribution.
415
+
416
+ If ``package_dir[""]`` is not given, but the ``src`` directory exists,
417
+ this function will set ``package_dir[""] = "src"``.
418
+ """
419
+ package_dir = self._package_dir
420
+ src_dir = os.path.join(self._root_dir, package_dir.get("", "src"))
421
+ if not os.path.isdir(src_dir):
422
+ return False
423
+
424
+ log.debug(f"`src-layout` detected -- analysing {src_dir}")
425
+ package_dir.setdefault("", os.path.basename(src_dir))
426
+ self.dist.package_dir = package_dir # persist eventual modifications
427
+ self.dist.packages = PEP420PackageFinder.find(src_dir)
428
+ self.dist.py_modules = ModuleFinder.find(src_dir)
429
+ log.debug(f"discovered packages -- {self.dist.packages}")
430
+ log.debug(f"discovered py_modules -- {self.dist.py_modules}")
431
+ return True
432
+
433
+ def _analyse_flat_layout(self) -> bool:
434
+ """Try to find all packages and modules under the project root.
435
+
436
+ Since the ``flat-layout`` is more dangerous in terms of accidentally including
437
+ extra files/directories, this function is more conservative and will raise an
438
+ error if multiple packages or modules are found.
439
+
440
+ This assumes that multi-package dists are uncommon and refuse to support that
441
+ use case in order to be able to prevent unintended errors.
442
+ """
443
+ log.debug(f"`flat-layout` detected -- analysing {self._root_dir}")
444
+ return self._analyse_flat_packages() or self._analyse_flat_modules()
445
+
446
+ def _analyse_flat_packages(self) -> bool:
447
+ self.dist.packages = FlatLayoutPackageFinder.find(self._root_dir)
448
+ top_level = remove_nested_packages(remove_stubs(self.dist.packages))
449
+ log.debug(f"discovered packages -- {self.dist.packages}")
450
+ self._ensure_no_accidental_inclusion(top_level, "packages")
451
+ return bool(top_level)
452
+
453
+ def _analyse_flat_modules(self) -> bool:
454
+ self.dist.py_modules = FlatLayoutModuleFinder.find(self._root_dir)
455
+ log.debug(f"discovered py_modules -- {self.dist.py_modules}")
456
+ self._ensure_no_accidental_inclusion(self.dist.py_modules, "modules")
457
+ return bool(self.dist.py_modules)
458
+
459
+ def _ensure_no_accidental_inclusion(self, detected: list[str], kind: str):
460
+ if len(detected) > 1:
461
+ from inspect import cleandoc
462
+
463
+ from setuptools.errors import PackageDiscoveryError
464
+
465
+ msg = f"""Multiple top-level {kind} discovered in a flat-layout: {detected}.
466
+
467
+ To avoid accidental inclusion of unwanted files or directories,
468
+ setuptools will not proceed with this build.
469
+
470
+ If you are trying to create a single distribution with multiple {kind}
471
+ on purpose, you should not rely on automatic discovery.
472
+ Instead, consider the following options:
473
+
474
+ 1. set up custom discovery (`find` directive with `include` or `exclude`)
475
+ 2. use a `src-layout`
476
+ 3. explicitly set `py_modules` or `packages` with a list of names
477
+
478
+ To find more information, look for "package discovery" on setuptools docs.
479
+ """
480
+ raise PackageDiscoveryError(cleandoc(msg))
481
+
482
+ def analyse_name(self) -> None:
483
+ """The packages/modules are the essential contribution of the author.
484
+ Therefore the name of the distribution can be derived from them.
485
+ """
486
+ if self.dist.metadata.name or self.dist.name:
487
+ # get_name() is not reliable (can return "UNKNOWN")
488
+ return
489
+
490
+ log.debug("No `name` configuration, performing automatic discovery")
491
+
492
+ name = (
493
+ self._find_name_single_package_or_module()
494
+ or self._find_name_from_packages()
495
+ )
496
+ if name:
497
+ self.dist.metadata.name = name
498
+
499
+ def _find_name_single_package_or_module(self) -> str | None:
500
+ """Exactly one module or package"""
501
+ for field in ('packages', 'py_modules'):
502
+ items = getattr(self.dist, field, None) or []
503
+ if items and len(items) == 1:
504
+ log.debug(f"Single module/package detected, name: {items[0]}")
505
+ return items[0]
506
+
507
+ return None
508
+
509
+ def _find_name_from_packages(self) -> str | None:
510
+ """Try to find the root package that is not a PEP 420 namespace"""
511
+ if not self.dist.packages:
512
+ return None
513
+
514
+ packages = remove_stubs(sorted(self.dist.packages, key=len))
515
+ package_dir = self.dist.package_dir or {}
516
+
517
+ parent_pkg = find_parent_package(packages, package_dir, self._root_dir)
518
+ if parent_pkg:
519
+ log.debug(f"Common parent package detected, name: {parent_pkg}")
520
+ return parent_pkg
521
+
522
+ log.warn("No parent package detected, impossible to derive `name`")
523
+ return None
524
+
525
+
526
+ def remove_nested_packages(packages: list[str]) -> list[str]:
527
+ """Remove nested packages from a list of packages.
528
+
529
+ >>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
530
+ ['a']
531
+ >>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"])
532
+ ['a', 'b', 'c.d', 'g.h']
533
+ """
534
+ pkgs = sorted(packages, key=len)
535
+ top_level = pkgs[:]
536
+ size = len(pkgs)
537
+ for i, name in enumerate(reversed(pkgs)):
538
+ if any(name.startswith(f"{other}.") for other in top_level):
539
+ top_level.pop(size - i - 1)
540
+
541
+ return top_level
542
+
543
+
544
+ def remove_stubs(packages: list[str]) -> list[str]:
545
+ """Remove type stubs (:pep:`561`) from a list of packages.
546
+
547
+ >>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"])
548
+ ['a', 'a.b', 'b']
549
+ """
550
+ return [pkg for pkg in packages if not pkg.split(".")[0].endswith("-stubs")]
551
+
552
+
553
+ def find_parent_package(
554
+ packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath
555
+ ) -> str | None:
556
+ """Find the parent package that is not a namespace."""
557
+ packages = sorted(packages, key=len)
558
+ common_ancestors = []
559
+ for i, name in enumerate(packages):
560
+ if not all(n.startswith(f"{name}.") for n in packages[i + 1 :]):
561
+ # Since packages are sorted by length, this condition is able
562
+ # to find a list of all common ancestors.
563
+ # When there is divergence (e.g. multiple root packages)
564
+ # the list will be empty
565
+ break
566
+ common_ancestors.append(name)
567
+
568
+ for name in common_ancestors:
569
+ pkg_path = find_package_path(name, package_dir, root_dir)
570
+ init = os.path.join(pkg_path, "__init__.py")
571
+ if os.path.isfile(init):
572
+ return name
573
+
574
+ return None
575
+
576
+
577
+ def find_package_path(
578
+ name: str, package_dir: Mapping[str, str], root_dir: StrPath
579
+ ) -> str:
580
+ """Given a package name, return the path where it should be found on
581
+ disk, considering the ``package_dir`` option.
582
+
583
+ >>> path = find_package_path("my.pkg", {"": "root/is/nested"}, ".")
584
+ >>> path.replace(os.sep, "/")
585
+ './root/is/nested/my/pkg'
586
+
587
+ >>> path = find_package_path("my.pkg", {"my": "root/is/nested"}, ".")
588
+ >>> path.replace(os.sep, "/")
589
+ './root/is/nested/pkg'
590
+
591
+ >>> path = find_package_path("my.pkg", {"my.pkg": "root/is/nested"}, ".")
592
+ >>> path.replace(os.sep, "/")
593
+ './root/is/nested'
594
+
595
+ >>> path = find_package_path("other.pkg", {"my.pkg": "root/is/nested"}, ".")
596
+ >>> path.replace(os.sep, "/")
597
+ './other/pkg'
598
+ """
599
+ parts = name.split(".")
600
+ for i in range(len(parts), 0, -1):
601
+ # Look backwards, the most specific package_dir first
602
+ partial_name = ".".join(parts[:i])
603
+ if partial_name in package_dir:
604
+ parent = package_dir[partial_name]
605
+ return os.path.join(root_dir, parent, *parts[i:])
606
+
607
+ parent = package_dir.get("") or ""
608
+ return os.path.join(root_dir, *parent.split("/"), *parts)
609
+
610
+
611
+ def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]:
612
+ parent_pkgs = remove_nested_packages(packages)
613
+ prefix = Path(package_path).parts
614
+ return {pkg: "/".join([*prefix, *pkg.split(".")]) for pkg in parent_pkgs}
python/Lib/site-packages/setuptools/dist.py ADDED
@@ -0,0 +1,1124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import io
5
+ import itertools
6
+ import numbers
7
+ import os
8
+ import re
9
+ import sys
10
+ from collections.abc import Iterable, Iterator, MutableMapping, Sequence
11
+ from glob import glob
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any, Union
14
+
15
+ from more_itertools import partition, unique_everseen
16
+ from packaging.markers import InvalidMarker, Marker
17
+ from packaging.specifiers import InvalidSpecifier, SpecifierSet
18
+ from packaging.version import Version
19
+
20
+ from . import (
21
+ _entry_points,
22
+ _reqs,
23
+ _static,
24
+ command as _, # noqa: F401 # imported for side-effects
25
+ )
26
+ from ._importlib import metadata
27
+ from ._normalization import _canonicalize_license_expression
28
+ from ._path import StrPath
29
+ from ._reqs import _StrOrIter
30
+ from .config import pyprojecttoml, setupcfg
31
+ from .discovery import ConfigDiscovery
32
+ from .errors import InvalidConfigError
33
+ from .monkey import get_unpatched
34
+ from .warnings import InformationOnly, SetuptoolsDeprecationWarning
35
+
36
+ import distutils.cmd
37
+ import distutils.command
38
+ import distutils.core
39
+ import distutils.dist
40
+ import distutils.log
41
+ from distutils.debug import DEBUG
42
+ from distutils.errors import DistutilsOptionError, DistutilsSetupError
43
+ from distutils.fancy_getopt import translate_longopt
44
+ from distutils.util import strtobool
45
+
46
+ if TYPE_CHECKING:
47
+ from typing_extensions import TypeAlias
48
+
49
+
50
+ __all__ = ['Distribution']
51
+
52
+ _sequence = tuple, list
53
+ """
54
+ :meta private:
55
+
56
+ Supported iterable types that are known to be:
57
+ - ordered (which `set` isn't)
58
+ - not match a str (which `Sequence[str]` does)
59
+ - not imply a nested type (like `dict`)
60
+ for use with `isinstance`.
61
+ """
62
+ _Sequence: TypeAlias = Union[tuple[str, ...], list[str]]
63
+ # This is how stringifying _Sequence would look in Python 3.10
64
+ _sequence_type_repr = "tuple[str, ...] | list[str]"
65
+ _OrderedStrSequence: TypeAlias = Union[str, dict[str, Any], Sequence[str]]
66
+ """
67
+ :meta private:
68
+ Avoid single-use iterable. Disallow sets.
69
+ A poor approximation of an OrderedSequence (dict doesn't match a Sequence).
70
+ """
71
+
72
+
73
+ def __getattr__(name: str) -> Any: # pragma: no cover
74
+ if name == "sequence":
75
+ SetuptoolsDeprecationWarning.emit(
76
+ "`setuptools.dist.sequence` is an internal implementation detail.",
77
+ "Please define your own `sequence = tuple, list` instead.",
78
+ due_date=(2025, 8, 28), # Originally added on 2024-08-27
79
+ )
80
+ return _sequence
81
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
82
+
83
+
84
+ def check_importable(dist, attr, value):
85
+ try:
86
+ ep = metadata.EntryPoint(value=value, name=None, group=None)
87
+ assert not ep.extras
88
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
89
+ raise DistutilsSetupError(
90
+ f"{attr!r} must be importable 'module:attrs' string (got {value!r})"
91
+ ) from e
92
+
93
+
94
+ def assert_string_list(dist, attr: str, value: _Sequence) -> None:
95
+ """Verify that value is a string list"""
96
+ try:
97
+ # verify that value is a list or tuple to exclude unordered
98
+ # or single-use iterables
99
+ assert isinstance(value, _sequence)
100
+ # verify that elements of value are strings
101
+ assert ''.join(value) != value
102
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
103
+ raise DistutilsSetupError(
104
+ f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})"
105
+ ) from e
106
+
107
+
108
+ def check_nsp(dist, attr, value):
109
+ """Verify that namespace packages are valid"""
110
+ ns_packages = value
111
+ assert_string_list(dist, attr, ns_packages)
112
+ for nsp in ns_packages:
113
+ if not dist.has_contents_for(nsp):
114
+ raise DistutilsSetupError(
115
+ f"Distribution contains no modules or packages for namespace package {nsp!r}"
116
+ )
117
+ parent, _sep, _child = nsp.rpartition('.')
118
+ if parent and parent not in ns_packages:
119
+ distutils.log.warn(
120
+ "WARNING: %r is declared as a package namespace, but %r"
121
+ " is not: please correct this in setup.py",
122
+ nsp,
123
+ parent,
124
+ )
125
+ SetuptoolsDeprecationWarning.emit(
126
+ "The namespace_packages parameter is deprecated.",
127
+ "Please replace its usage with implicit namespaces (PEP 420).",
128
+ see_docs="references/keywords.html#keyword-namespace-packages",
129
+ # TODO: define due_date, it may break old packages that are no longer
130
+ # maintained (e.g. sphinxcontrib extensions) when installed from source.
131
+ # Warning officially introduced in May 2022, however the deprecation
132
+ # was mentioned much earlier in the docs (May 2020, see #2149).
133
+ )
134
+
135
+
136
+ def check_extras(dist, attr, value):
137
+ """Verify that extras_require mapping is valid"""
138
+ try:
139
+ list(itertools.starmap(_check_extra, value.items()))
140
+ except (TypeError, ValueError, AttributeError) as e:
141
+ raise DistutilsSetupError(
142
+ "'extras_require' must be a dictionary whose values are "
143
+ "strings or lists of strings containing valid project/version "
144
+ "requirement specifiers."
145
+ ) from e
146
+
147
+
148
+ def _check_extra(extra, reqs):
149
+ _name, _sep, marker = extra.partition(':')
150
+ try:
151
+ _check_marker(marker)
152
+ except InvalidMarker:
153
+ msg = f"Invalid environment marker: {marker} ({extra!r})"
154
+ raise DistutilsSetupError(msg) from None
155
+ list(_reqs.parse(reqs))
156
+
157
+
158
+ def _check_marker(marker):
159
+ if not marker:
160
+ return
161
+ m = Marker(marker)
162
+ m.evaluate()
163
+
164
+
165
+ def assert_bool(dist, attr, value):
166
+ """Verify that value is True, False, 0, or 1"""
167
+ if bool(value) != value:
168
+ raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})")
169
+
170
+
171
+ def invalid_unless_false(dist, attr, value):
172
+ if not value:
173
+ DistDeprecationWarning.emit(f"{attr} is ignored.")
174
+ # TODO: should there be a `due_date` here?
175
+ return
176
+ raise DistutilsSetupError(f"{attr} is invalid.")
177
+
178
+
179
+ def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None:
180
+ """Verify that install_requires is a valid requirements list"""
181
+ try:
182
+ list(_reqs.parse(value))
183
+ if isinstance(value, set):
184
+ raise TypeError("Unordered types are not allowed")
185
+ except (TypeError, ValueError) as error:
186
+ msg = (
187
+ f"{attr!r} must be a string or iterable of strings "
188
+ f"containing valid project/version requirement specifiers; {error}"
189
+ )
190
+ raise DistutilsSetupError(msg) from error
191
+
192
+
193
+ def check_specifier(dist, attr, value):
194
+ """Verify that value is a valid version specifier"""
195
+ try:
196
+ SpecifierSet(value)
197
+ except (InvalidSpecifier, AttributeError) as error:
198
+ msg = f"{attr!r} must be a string containing valid version specifiers; {error}"
199
+ raise DistutilsSetupError(msg) from error
200
+
201
+
202
+ def check_entry_points(dist, attr, value):
203
+ """Verify that entry_points map is parseable"""
204
+ try:
205
+ _entry_points.load(value)
206
+ except Exception as e:
207
+ raise DistutilsSetupError(e) from e
208
+
209
+
210
+ def check_package_data(dist, attr, value):
211
+ """Verify that value is a dictionary of package names to glob lists"""
212
+ if not isinstance(value, dict):
213
+ raise DistutilsSetupError(
214
+ f"{attr!r} must be a dictionary mapping package names to lists of "
215
+ "string wildcard patterns"
216
+ )
217
+ for k, v in value.items():
218
+ if not isinstance(k, str):
219
+ raise DistutilsSetupError(
220
+ f"keys of {attr!r} dict must be strings (got {k!r})"
221
+ )
222
+ assert_string_list(dist, f'values of {attr!r} dict', v)
223
+
224
+
225
+ def check_packages(dist, attr, value):
226
+ for pkgname in value:
227
+ if not re.match(r'\w+(\.\w+)*', pkgname):
228
+ distutils.log.warn(
229
+ "WARNING: %r not a valid package name; please use only "
230
+ ".-separated package names in setup.py",
231
+ pkgname,
232
+ )
233
+
234
+
235
+ if TYPE_CHECKING:
236
+ # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
237
+ from distutils.core import Distribution as _Distribution
238
+ else:
239
+ _Distribution = get_unpatched(distutils.core.Distribution)
240
+
241
+
242
+ class Distribution(_Distribution):
243
+ """Distribution with support for tests and package data
244
+
245
+ This is an enhanced version of 'distutils.dist.Distribution' that
246
+ effectively adds the following new optional keyword arguments to 'setup()':
247
+
248
+ 'install_requires' -- a string or sequence of strings specifying project
249
+ versions that the distribution requires when installed, in the format
250
+ used by 'pkg_resources.require()'. They will be installed
251
+ automatically when the package is installed. If you wish to use
252
+ packages that are not available in PyPI, or want to give your users an
253
+ alternate download location, you can add a 'find_links' option to the
254
+ '[easy_install]' section of your project's 'setup.cfg' file, and then
255
+ setuptools will scan the listed web pages for links that satisfy the
256
+ requirements.
257
+
258
+ 'extras_require' -- a dictionary mapping names of optional "extras" to the
259
+ additional requirement(s) that using those extras incurs. For example,
260
+ this::
261
+
262
+ extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
263
+
264
+ indicates that the distribution can optionally provide an extra
265
+ capability called "reST", but it can only be used if docutils and
266
+ reSTedit are installed. If the user installs your package using
267
+ EasyInstall and requests one of your extras, the corresponding
268
+ additional requirements will be installed if needed.
269
+
270
+ 'package_data' -- a dictionary mapping package names to lists of filenames
271
+ or globs to use to find data files contained in the named packages.
272
+ If the dictionary has filenames or globs listed under '""' (the empty
273
+ string), those names will be searched for in every package, in addition
274
+ to any names for the specific package. Data files found using these
275
+ names/globs will be installed along with the package, in the same
276
+ location as the package. Note that globs are allowed to reference
277
+ the contents of non-package subdirectories, as long as you use '/' as
278
+ a path separator. (Globs are automatically converted to
279
+ platform-specific paths at runtime.)
280
+
281
+ In addition to these new keywords, this class also has several new methods
282
+ for manipulating the distribution's contents. For example, the 'include()'
283
+ and 'exclude()' methods can be thought of as in-place add and subtract
284
+ commands that add or remove packages, modules, extensions, and so on from
285
+ the distribution.
286
+ """
287
+
288
+ _DISTUTILS_UNSUPPORTED_METADATA = {
289
+ 'long_description_content_type': lambda: None,
290
+ 'project_urls': dict,
291
+ 'provides_extras': dict, # behaves like an ordered set
292
+ 'license_expression': lambda: None,
293
+ 'license_file': lambda: None,
294
+ 'license_files': lambda: None,
295
+ 'install_requires': list,
296
+ 'extras_require': dict,
297
+ }
298
+
299
+ # Used by build_py, editable_wheel and install_lib commands for legacy namespaces
300
+ namespace_packages: list[str] #: :meta private: DEPRECATED
301
+
302
+ # Any: Dynamic assignment results in Incompatible types in assignment
303
+ def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:
304
+ have_package_data = hasattr(self, "package_data")
305
+ if not have_package_data:
306
+ self.package_data: dict[str, list[str]] = {}
307
+ attrs = attrs or {}
308
+ self.dist_files: list[tuple[str, str, str]] = []
309
+ self.include_package_data: bool | None = None
310
+ self.exclude_package_data: dict[str, list[str]] | None = None
311
+ # Filter-out setuptools' specific options.
312
+ self.src_root: str | None = attrs.pop("src_root", None)
313
+ self.dependency_links: list[str] = attrs.pop('dependency_links', [])
314
+ self.setup_requires: list[str] = attrs.pop('setup_requires', [])
315
+ for ep in metadata.entry_points(group='distutils.setup_keywords'):
316
+ vars(self).setdefault(ep.name, None)
317
+
318
+ metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA)
319
+ metadata_only -= {"install_requires", "extras_require"}
320
+ dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only}
321
+ _Distribution.__init__(self, dist_attrs)
322
+
323
+ # Private API (setuptools-use only, not restricted to Distribution)
324
+ # Stores files that are referenced by the configuration and need to be in the
325
+ # sdist (e.g. `version = file: VERSION.txt`)
326
+ self._referenced_files = set[str]()
327
+
328
+ self.set_defaults = ConfigDiscovery(self)
329
+
330
+ self._set_metadata_defaults(attrs)
331
+
332
+ self.metadata.version = self._normalize_version(self.metadata.version)
333
+ self._finalize_requires()
334
+
335
+ def _validate_metadata(self):
336
+ required = {"name"}
337
+ provided = {
338
+ key
339
+ for key in vars(self.metadata)
340
+ if getattr(self.metadata, key, None) is not None
341
+ }
342
+ missing = required - provided
343
+
344
+ if missing:
345
+ msg = f"Required package metadata is missing: {missing}"
346
+ raise DistutilsSetupError(msg)
347
+
348
+ def _set_metadata_defaults(self, attrs):
349
+ """
350
+ Fill-in missing metadata fields not supported by distutils.
351
+ Some fields may have been set by other tools (e.g. pbr).
352
+ Those fields (vars(self.metadata)) take precedence to
353
+ supplied attrs.
354
+ """
355
+ for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
356
+ vars(self.metadata).setdefault(option, attrs.get(option, default()))
357
+
358
+ @staticmethod
359
+ def _normalize_version(version):
360
+ from . import sic
361
+
362
+ if isinstance(version, numbers.Number):
363
+ # Some people apparently take "version number" too literally :)
364
+ version = str(version)
365
+ elif isinstance(version, sic) or version is None:
366
+ return version
367
+
368
+ normalized = str(Version(version))
369
+ if version != normalized:
370
+ InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'")
371
+ return normalized
372
+ return version
373
+
374
+ def _finalize_requires(self):
375
+ """
376
+ Set `metadata.python_requires` and fix environment markers
377
+ in `install_requires` and `extras_require`.
378
+ """
379
+ if getattr(self, 'python_requires', None):
380
+ self.metadata.python_requires = self.python_requires
381
+
382
+ self._normalize_requires()
383
+ self.metadata.install_requires = self.install_requires
384
+ self.metadata.extras_require = self.extras_require
385
+
386
+ if self.extras_require:
387
+ for extra in self.extras_require.keys():
388
+ # Setuptools allows a weird "<name>:<env markers> syntax for extras
389
+ extra = extra.split(':')[0]
390
+ if extra:
391
+ self.metadata.provides_extras.setdefault(extra)
392
+
393
+ def _normalize_requires(self):
394
+ """Make sure requirement-related attributes exist and are normalized"""
395
+ install_requires = getattr(self, "install_requires", None) or []
396
+ extras_require = getattr(self, "extras_require", None) or {}
397
+
398
+ # Preserve the "static"-ness of values parsed from config files
399
+ list_ = _static.List if _static.is_static(install_requires) else list
400
+ self.install_requires = list_(map(str, _reqs.parse(install_requires)))
401
+
402
+ dict_ = _static.Dict if _static.is_static(extras_require) else dict
403
+ self.extras_require = dict_(
404
+ (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items()
405
+ )
406
+
407
+ def _finalize_license_expression(self) -> None:
408
+ """
409
+ Normalize license and license_expression.
410
+ >>> dist = Distribution({"license_expression": _static.Str("mit aNd gpl-3.0-OR-later")})
411
+ >>> _static.is_static(dist.metadata.license_expression)
412
+ True
413
+ >>> dist._finalize_license_expression()
414
+ >>> _static.is_static(dist.metadata.license_expression) # preserve "static-ness"
415
+ True
416
+ >>> print(dist.metadata.license_expression)
417
+ MIT AND GPL-3.0-or-later
418
+ """
419
+ classifiers = self.metadata.get_classifiers()
420
+ license_classifiers = [cl for cl in classifiers if cl.startswith("License :: ")]
421
+
422
+ license_expr = self.metadata.license_expression
423
+ if license_expr:
424
+ str_ = _static.Str if _static.is_static(license_expr) else str
425
+ normalized = str_(_canonicalize_license_expression(license_expr))
426
+ if license_expr != normalized:
427
+ InformationOnly.emit(f"Normalizing '{license_expr}' to '{normalized}'")
428
+ self.metadata.license_expression = normalized
429
+ if license_classifiers:
430
+ raise InvalidConfigError(
431
+ "License classifiers have been superseded by license expressions "
432
+ "(see https://peps.python.org/pep-0639/). Please remove:\n\n"
433
+ + "\n".join(license_classifiers),
434
+ )
435
+ elif license_classifiers:
436
+ pypa_guides = "guides/writing-pyproject-toml/#license"
437
+ SetuptoolsDeprecationWarning.emit(
438
+ "License classifiers are deprecated.",
439
+ "Please consider removing the following classifiers in favor of a "
440
+ "SPDX license expression:\n\n" + "\n".join(license_classifiers),
441
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
442
+ # Warning introduced on 2025-02-17
443
+ # TODO: Should we add a due date? It may affect old/unmaintained
444
+ # packages in the ecosystem and cause problems...
445
+ )
446
+
447
+ def _finalize_license_files(self) -> None:
448
+ """Compute names of all license files which should be included."""
449
+ license_files: list[str] | None = self.metadata.license_files
450
+ patterns = license_files or []
451
+
452
+ license_file: str | None = self.metadata.license_file
453
+ if license_file and license_file not in patterns:
454
+ patterns.append(license_file)
455
+
456
+ if license_files is None and license_file is None:
457
+ # Default patterns match the ones wheel uses
458
+ # See https://wheel.readthedocs.io/en/stable/user_guide.html
459
+ # -> 'Including license files in the generated wheel file'
460
+ patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']
461
+ files = self._expand_patterns(patterns, enforce_match=False)
462
+ else: # Patterns explicitly given by the user
463
+ files = self._expand_patterns(patterns, enforce_match=True)
464
+
465
+ self.metadata.license_files = list(unique_everseen(files))
466
+
467
+ @classmethod
468
+ def _expand_patterns(
469
+ cls, patterns: list[str], enforce_match: bool = True
470
+ ) -> Iterator[str]:
471
+ """
472
+ >>> getfixture('sample_project_cwd')
473
+ >>> list(Distribution._expand_patterns(['LICENSE.txt']))
474
+ ['LICENSE.txt']
475
+ >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*']))
476
+ ['pyproject.toml', 'LICENSE.txt']
477
+ >>> list(Distribution._expand_patterns(['src/**/*.dat']))
478
+ ['src/sample/package_data.dat']
479
+ """
480
+ return (
481
+ path.replace(os.sep, "/")
482
+ for pattern in patterns
483
+ for path in sorted(cls._find_pattern(pattern, enforce_match))
484
+ if not path.endswith('~') and os.path.isfile(path)
485
+ )
486
+
487
+ @staticmethod
488
+ def _find_pattern(pattern: str, enforce_match: bool = True) -> list[str]:
489
+ r"""
490
+ >>> getfixture('sample_project_cwd')
491
+ >>> Distribution._find_pattern("LICENSE.txt")
492
+ ['LICENSE.txt']
493
+ >>> Distribution._find_pattern("/LICENSE.MIT")
494
+ Traceback (most recent call last):
495
+ ...
496
+ setuptools.errors.InvalidConfigError: Pattern '/LICENSE.MIT' should be relative...
497
+ >>> Distribution._find_pattern("../LICENSE.MIT")
498
+ Traceback (most recent call last):
499
+ ...
500
+ setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern '../LICENSE.MIT' cannot contain '..'...
501
+ >>> Distribution._find_pattern("LICEN{CSE*")
502
+ Traceback (most recent call last):
503
+ ...
504
+ setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern 'LICEN{CSE*' contains invalid characters...
505
+ """
506
+ pypa_guides = "specifications/glob-patterns/"
507
+ if ".." in pattern:
508
+ SetuptoolsDeprecationWarning.emit(
509
+ f"Pattern {pattern!r} cannot contain '..'",
510
+ """
511
+ Please ensure the files specified are contained by the root
512
+ of the Python package (normally marked by `pyproject.toml`).
513
+ """,
514
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
515
+ due_date=(2027, 2, 18), # Introduced in 2025-03-20
516
+ # Replace with InvalidConfigError after deprecation
517
+ )
518
+ if pattern.startswith((os.sep, "/")) or ":\\" in pattern:
519
+ raise InvalidConfigError(
520
+ f"Pattern {pattern!r} should be relative and must not start with '/'"
521
+ )
522
+ if re.match(r'^[\w\-\.\/\*\?\[\]]+$', pattern) is None:
523
+ SetuptoolsDeprecationWarning.emit(
524
+ "Please provide a valid glob pattern.",
525
+ "Pattern {pattern!r} contains invalid characters.",
526
+ pattern=pattern,
527
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
528
+ due_date=(2027, 2, 18), # Introduced in 2025-02-20
529
+ )
530
+
531
+ found = glob(pattern, recursive=True)
532
+
533
+ if enforce_match and not found:
534
+ SetuptoolsDeprecationWarning.emit(
535
+ "Cannot find any files for the given pattern.",
536
+ "Pattern {pattern!r} did not match any files.",
537
+ pattern=pattern,
538
+ due_date=(2027, 2, 18), # Introduced in 2025-02-20
539
+ # PEP 639 requires us to error, but as a transition period
540
+ # we will only issue a warning to give people time to prepare.
541
+ # After the transition, this should raise an InvalidConfigError.
542
+ )
543
+ return found
544
+
545
+ # FIXME: 'Distribution._parse_config_files' is too complex (14)
546
+ def _parse_config_files(self, filenames=None): # noqa: C901
547
+ """
548
+ Adapted from distutils.dist.Distribution.parse_config_files,
549
+ this method provides the same functionality in subtly-improved
550
+ ways.
551
+ """
552
+ from configparser import ConfigParser
553
+
554
+ # Ignore install directory options if we have a venv
555
+ ignore_options = (
556
+ []
557
+ if sys.prefix == sys.base_prefix
558
+ else [
559
+ 'install-base',
560
+ 'install-platbase',
561
+ 'install-lib',
562
+ 'install-platlib',
563
+ 'install-purelib',
564
+ 'install-headers',
565
+ 'install-scripts',
566
+ 'install-data',
567
+ 'prefix',
568
+ 'exec-prefix',
569
+ 'home',
570
+ 'user',
571
+ 'root',
572
+ ]
573
+ )
574
+
575
+ ignore_options = frozenset(ignore_options)
576
+
577
+ if filenames is None:
578
+ filenames = self.find_config_files()
579
+
580
+ if DEBUG:
581
+ self.announce("Distribution.parse_config_files():")
582
+
583
+ parser = ConfigParser()
584
+ parser.optionxform = str
585
+ for filename in filenames:
586
+ with open(filename, encoding='utf-8') as reader:
587
+ if DEBUG:
588
+ self.announce(" reading {filename}".format(**locals()))
589
+ parser.read_file(reader)
590
+ for section in parser.sections():
591
+ options = parser.options(section)
592
+ opt_dict = self.get_option_dict(section)
593
+
594
+ for opt in options:
595
+ if opt == '__name__' or opt in ignore_options:
596
+ continue
597
+
598
+ val = parser.get(section, opt)
599
+ opt = self._enforce_underscore(opt, section)
600
+ opt = self._enforce_option_lowercase(opt, section)
601
+ opt_dict[opt] = (filename, val)
602
+
603
+ # Make the ConfigParser forget everything (so we retain
604
+ # the original filenames that options come from)
605
+ parser.__init__()
606
+
607
+ if 'global' not in self.command_options:
608
+ return
609
+
610
+ # If there was a "global" section in the config file, use it
611
+ # to set Distribution options.
612
+
613
+ for opt, (src, val) in self.command_options['global'].items():
614
+ alias = self.negative_opt.get(opt)
615
+ if alias:
616
+ val = not strtobool(val)
617
+ elif opt == 'verbose':
618
+ val = strtobool(val)
619
+
620
+ try:
621
+ setattr(self, alias or opt, val)
622
+ except ValueError as e:
623
+ raise DistutilsOptionError(e) from e
624
+
625
+ def _enforce_underscore(self, opt: str, section: str) -> str:
626
+ if "-" not in opt or self._skip_setupcfg_normalization(section):
627
+ return opt
628
+
629
+ underscore_opt = opt.replace('-', '_')
630
+ affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
631
+ SetuptoolsDeprecationWarning.emit(
632
+ f"Invalid dash-separated key {opt!r} in {section!r} (setup.cfg), "
633
+ f"please use the underscore name {underscore_opt!r} instead.",
634
+ f"""
635
+ Usage of dash-separated {opt!r} will not be supported in future
636
+ versions. Please use the underscore name {underscore_opt!r} instead.
637
+ {affected}
638
+
639
+ Available configuration options are listed in:
640
+ https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
641
+ """,
642
+ see_url="https://github.com/pypa/setuptools/discussions/5011",
643
+ due_date=(2026, 3, 3),
644
+ # Warning initially introduced in 3 Mar 2021
645
+ )
646
+ return underscore_opt
647
+
648
+ def _enforce_option_lowercase(self, opt: str, section: str) -> str:
649
+ if opt.islower() or self._skip_setupcfg_normalization(section):
650
+ return opt
651
+
652
+ lowercase_opt = opt.lower()
653
+ affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
654
+ SetuptoolsDeprecationWarning.emit(
655
+ f"Invalid uppercase key {opt!r} in {section!r} (setup.cfg), "
656
+ f"please use lowercase {lowercase_opt!r} instead.",
657
+ f"""
658
+ Usage of uppercase key {opt!r} in {section!r} will not be supported in
659
+ future versions. Please use lowercase {lowercase_opt!r} instead.
660
+ {affected}
661
+
662
+ Available configuration options are listed in:
663
+ https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
664
+ """,
665
+ see_url="https://github.com/pypa/setuptools/discussions/5011",
666
+ due_date=(2026, 3, 3),
667
+ # Warning initially introduced in 6 Mar 2021
668
+ )
669
+ return lowercase_opt
670
+
671
+ def _skip_setupcfg_normalization(self, section: str) -> bool:
672
+ skip = (
673
+ 'options.extras_require',
674
+ 'options.data_files',
675
+ 'options.entry_points',
676
+ 'options.package_data',
677
+ 'options.exclude_package_data',
678
+ )
679
+ return section in skip or not self._is_setuptools_section(section)
680
+
681
+ def _is_setuptools_section(self, section: str) -> bool:
682
+ return (
683
+ section == "metadata"
684
+ or section.startswith("options")
685
+ or section in _setuptools_commands()
686
+ )
687
+
688
+ # FIXME: 'Distribution._set_command_options' is too complex (14)
689
+ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
690
+ """
691
+ Set the options for 'command_obj' from 'option_dict'. Basically
692
+ this means copying elements of a dictionary ('option_dict') to
693
+ attributes of an instance ('command').
694
+
695
+ 'command_obj' must be a Command instance. If 'option_dict' is not
696
+ supplied, uses the standard option dictionary for this command
697
+ (from 'self.command_options').
698
+
699
+ (Adopted from distutils.dist.Distribution._set_command_options)
700
+ """
701
+ command_name = command_obj.get_command_name()
702
+ if option_dict is None:
703
+ option_dict = self.get_option_dict(command_name)
704
+
705
+ if DEBUG:
706
+ self.announce(f" setting options for '{command_name}' command:")
707
+ for option, (source, value) in option_dict.items():
708
+ if DEBUG:
709
+ self.announce(f" {option} = {value} (from {source})")
710
+ try:
711
+ bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
712
+ except AttributeError:
713
+ bool_opts = []
714
+ try:
715
+ neg_opt = command_obj.negative_opt
716
+ except AttributeError:
717
+ neg_opt = {}
718
+
719
+ try:
720
+ is_string = isinstance(value, str)
721
+ if option in neg_opt and is_string:
722
+ setattr(command_obj, neg_opt[option], not strtobool(value))
723
+ elif option in bool_opts and is_string:
724
+ setattr(command_obj, option, strtobool(value))
725
+ elif hasattr(command_obj, option):
726
+ setattr(command_obj, option, value)
727
+ else:
728
+ raise DistutilsOptionError(
729
+ f"error in {source}: command '{command_name}' has no such option '{option}'"
730
+ )
731
+ except ValueError as e:
732
+ raise DistutilsOptionError(e) from e
733
+
734
+ def _get_project_config_files(self, filenames: Iterable[StrPath] | None):
735
+ """Add default file and split between INI and TOML"""
736
+ tomlfiles = []
737
+ standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
738
+ if filenames is not None:
739
+ parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
740
+ filenames = list(parts[0]) # 1st element => predicate is False
741
+ tomlfiles = list(parts[1]) # 2nd element => predicate is True
742
+ elif standard_project_metadata.exists():
743
+ tomlfiles = [standard_project_metadata]
744
+ return filenames, tomlfiles
745
+
746
+ def parse_config_files(
747
+ self,
748
+ filenames: Iterable[StrPath] | None = None,
749
+ ignore_option_errors: bool = False,
750
+ ) -> None:
751
+ """Parses configuration files from various levels
752
+ and loads configuration.
753
+ """
754
+ inifiles, tomlfiles = self._get_project_config_files(filenames)
755
+
756
+ self._parse_config_files(filenames=inifiles)
757
+
758
+ setupcfg.parse_configuration(
759
+ self, self.command_options, ignore_option_errors=ignore_option_errors
760
+ )
761
+ for filename in tomlfiles:
762
+ pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
763
+
764
+ self._finalize_requires()
765
+ self._finalize_license_expression()
766
+ self._finalize_license_files()
767
+
768
+ def fetch_build_eggs(self, requires: _StrOrIter) -> list[metadata.Distribution]:
769
+ """Resolve pre-setup requirements"""
770
+ from .installer import _fetch_build_eggs
771
+
772
+ return _fetch_build_eggs(self, requires)
773
+
774
+ def finalize_options(self) -> None:
775
+ """
776
+ Allow plugins to apply arbitrary operations to the
777
+ distribution. Each hook may optionally define a 'order'
778
+ to influence the order of execution. Smaller numbers
779
+ go first and the default is 0.
780
+ """
781
+ group = 'setuptools.finalize_distribution_options'
782
+
783
+ def by_order(hook):
784
+ return getattr(hook, 'order', 0)
785
+
786
+ defined = metadata.entry_points(group=group)
787
+ filtered = itertools.filterfalse(self._removed, defined)
788
+ loaded = map(lambda e: e.load(), filtered)
789
+ for ep in sorted(loaded, key=by_order):
790
+ ep(self)
791
+
792
+ @staticmethod
793
+ def _removed(ep):
794
+ """
795
+ When removing an entry point, if metadata is loaded
796
+ from an older version of Setuptools, that removed
797
+ entry point will attempt to be loaded and will fail.
798
+ See #2765 for more details.
799
+ """
800
+ removed = {
801
+ # removed 2021-09-05
802
+ '2to3_doctests',
803
+ }
804
+ return ep.name in removed
805
+
806
+ def _finalize_setup_keywords(self):
807
+ for ep in metadata.entry_points(group='distutils.setup_keywords'):
808
+ value = getattr(self, ep.name, None)
809
+ if value is not None:
810
+ ep.load()(self, ep.name, value)
811
+
812
+ def get_egg_cache_dir(self) -> str:
813
+ from . import windows_support
814
+
815
+ egg_cache_dir = os.path.join(os.curdir, '.eggs')
816
+ if not os.path.exists(egg_cache_dir):
817
+ os.mkdir(egg_cache_dir)
818
+ windows_support.hide_file(egg_cache_dir)
819
+ readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
820
+ with open(readme_txt_filename, 'w', encoding="utf-8") as f:
821
+ f.write(
822
+ 'This directory contains eggs that were downloaded '
823
+ 'by setuptools to build, test, and run plug-ins.\n\n'
824
+ )
825
+ f.write(
826
+ 'This directory caches those eggs to prevent '
827
+ 'repeated downloads.\n\n'
828
+ )
829
+ f.write('However, it is safe to delete this directory.\n\n')
830
+
831
+ return egg_cache_dir
832
+
833
+ def fetch_build_egg(self, req):
834
+ """Fetch an egg needed for building"""
835
+ from .installer import fetch_build_egg
836
+
837
+ return fetch_build_egg(self, req)
838
+
839
+ def get_command_class(self, command: str) -> type[distutils.cmd.Command]: # type: ignore[override] # Not doing complex overrides yet
840
+ """Pluggable version of get_command_class()"""
841
+ if command in self.cmdclass:
842
+ return self.cmdclass[command]
843
+
844
+ # Special case bdist_wheel so it's never loaded from "wheel"
845
+ if command == 'bdist_wheel':
846
+ from .command.bdist_wheel import bdist_wheel
847
+
848
+ return bdist_wheel
849
+
850
+ eps = metadata.entry_points(group='distutils.commands', name=command)
851
+ for ep in eps:
852
+ self.cmdclass[command] = cmdclass = ep.load()
853
+ return cmdclass
854
+ else:
855
+ return _Distribution.get_command_class(self, command)
856
+
857
+ def print_commands(self):
858
+ for ep in metadata.entry_points(group='distutils.commands'):
859
+ if ep.name not in self.cmdclass:
860
+ cmdclass = ep.load()
861
+ self.cmdclass[ep.name] = cmdclass
862
+ return _Distribution.print_commands(self)
863
+
864
+ def get_command_list(self):
865
+ for ep in metadata.entry_points(group='distutils.commands'):
866
+ if ep.name not in self.cmdclass:
867
+ cmdclass = ep.load()
868
+ self.cmdclass[ep.name] = cmdclass
869
+ return _Distribution.get_command_list(self)
870
+
871
+ def include(self, **attrs) -> None:
872
+ """Add items to distribution that are named in keyword arguments
873
+
874
+ For example, 'dist.include(py_modules=["x"])' would add 'x' to
875
+ the distribution's 'py_modules' attribute, if it was not already
876
+ there.
877
+
878
+ Currently, this method only supports inclusion for attributes that are
879
+ lists or tuples. If you need to add support for adding to other
880
+ attributes in this or a subclass, you can add an '_include_X' method,
881
+ where 'X' is the name of the attribute. The method will be called with
882
+ the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
883
+ will try to call 'dist._include_foo({"bar":"baz"})', which can then
884
+ handle whatever special inclusion logic is needed.
885
+ """
886
+ for k, v in attrs.items():
887
+ include = getattr(self, '_include_' + k, None)
888
+ if include:
889
+ include(v)
890
+ else:
891
+ self._include_misc(k, v)
892
+
893
+ def exclude_package(self, package: str) -> None:
894
+ """Remove packages, modules, and extensions in named package"""
895
+
896
+ pfx = package + '.'
897
+ if self.packages:
898
+ self.packages = [
899
+ p for p in self.packages if p != package and not p.startswith(pfx)
900
+ ]
901
+
902
+ if self.py_modules:
903
+ self.py_modules = [
904
+ p for p in self.py_modules if p != package and not p.startswith(pfx)
905
+ ]
906
+
907
+ if self.ext_modules:
908
+ self.ext_modules = [
909
+ p
910
+ for p in self.ext_modules
911
+ if p.name != package and not p.name.startswith(pfx)
912
+ ]
913
+
914
+ def has_contents_for(self, package: str) -> bool:
915
+ """Return true if 'exclude_package(package)' would do something"""
916
+
917
+ pfx = package + '.'
918
+
919
+ for p in self.iter_distribution_names():
920
+ if p == package or p.startswith(pfx):
921
+ return True
922
+
923
+ return False
924
+
925
+ def _exclude_misc(self, name: str, value: _Sequence) -> None:
926
+ """Handle 'exclude()' for list/tuple attrs without a special handler"""
927
+ if not isinstance(value, _sequence):
928
+ raise DistutilsSetupError(
929
+ f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
930
+ )
931
+ try:
932
+ old = getattr(self, name)
933
+ except AttributeError as e:
934
+ raise DistutilsSetupError(f"{name}: No such distribution setting") from e
935
+ if old is not None and not isinstance(old, _sequence):
936
+ raise DistutilsSetupError(
937
+ name + ": this setting cannot be changed via include/exclude"
938
+ )
939
+ elif old:
940
+ setattr(self, name, [item for item in old if item not in value])
941
+
942
+ def _include_misc(self, name: str, value: _Sequence) -> None:
943
+ """Handle 'include()' for list/tuple attrs without a special handler"""
944
+
945
+ if not isinstance(value, _sequence):
946
+ raise DistutilsSetupError(
947
+ f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
948
+ )
949
+ try:
950
+ old = getattr(self, name)
951
+ except AttributeError as e:
952
+ raise DistutilsSetupError(f"{name}: No such distribution setting") from e
953
+ if old is None:
954
+ setattr(self, name, value)
955
+ elif not isinstance(old, _sequence):
956
+ raise DistutilsSetupError(
957
+ name + ": this setting cannot be changed via include/exclude"
958
+ )
959
+ else:
960
+ new = [item for item in value if item not in old]
961
+ setattr(self, name, list(old) + new)
962
+
963
+ def exclude(self, **attrs) -> None:
964
+ """Remove items from distribution that are named in keyword arguments
965
+
966
+ For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
967
+ the distribution's 'py_modules' attribute. Excluding packages uses
968
+ the 'exclude_package()' method, so all of the package's contained
969
+ packages, modules, and extensions are also excluded.
970
+
971
+ Currently, this method only supports exclusion from attributes that are
972
+ lists or tuples. If you need to add support for excluding from other
973
+ attributes in this or a subclass, you can add an '_exclude_X' method,
974
+ where 'X' is the name of the attribute. The method will be called with
975
+ the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
976
+ will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
977
+ handle whatever special exclusion logic is needed.
978
+ """
979
+ for k, v in attrs.items():
980
+ exclude = getattr(self, '_exclude_' + k, None)
981
+ if exclude:
982
+ exclude(v)
983
+ else:
984
+ self._exclude_misc(k, v)
985
+
986
+ def _exclude_packages(self, packages: _Sequence) -> None:
987
+ if not isinstance(packages, _sequence):
988
+ raise DistutilsSetupError(
989
+ f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})"
990
+ )
991
+ list(map(self.exclude_package, packages))
992
+
993
+ def _parse_command_opts(self, parser, args):
994
+ # Remove --with-X/--without-X options when processing command args
995
+ self.global_options = self.__class__.global_options
996
+ self.negative_opt = self.__class__.negative_opt
997
+
998
+ # First, expand any aliases
999
+ command = args[0]
1000
+ aliases = self.get_option_dict('aliases')
1001
+ while command in aliases:
1002
+ _src, alias = aliases[command]
1003
+ del aliases[command] # ensure each alias can expand only once!
1004
+ import shlex
1005
+
1006
+ args[:1] = shlex.split(alias, True)
1007
+ command = args[0]
1008
+
1009
+ nargs = _Distribution._parse_command_opts(self, parser, args)
1010
+
1011
+ # Handle commands that want to consume all remaining arguments
1012
+ cmd_class = self.get_command_class(command)
1013
+ if getattr(cmd_class, 'command_consumes_arguments', None):
1014
+ self.get_option_dict(command)['args'] = ("command line", nargs)
1015
+ if nargs is not None:
1016
+ return []
1017
+
1018
+ return nargs
1019
+
1020
+ def get_cmdline_options(self) -> dict[str, dict[str, str | None]]:
1021
+ """Return a '{cmd: {opt:val}}' map of all command-line options
1022
+
1023
+ Option names are all long, but do not include the leading '--', and
1024
+ contain dashes rather than underscores. If the option doesn't take
1025
+ an argument (e.g. '--quiet'), the 'val' is 'None'.
1026
+
1027
+ Note that options provided by config files are intentionally excluded.
1028
+ """
1029
+
1030
+ d: dict[str, dict[str, str | None]] = {}
1031
+
1032
+ for cmd, opts in self.command_options.items():
1033
+ val: str | None
1034
+ for opt, (src, val) in opts.items():
1035
+ if src != "command line":
1036
+ continue
1037
+
1038
+ opt = opt.replace('_', '-')
1039
+
1040
+ if val == 0:
1041
+ cmdobj = self.get_command_obj(cmd)
1042
+ neg_opt = self.negative_opt.copy()
1043
+ neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
1044
+ for neg, pos in neg_opt.items():
1045
+ if pos == opt:
1046
+ opt = neg
1047
+ val = None
1048
+ break
1049
+ else:
1050
+ raise AssertionError("Shouldn't be able to get here")
1051
+
1052
+ elif val == 1:
1053
+ val = None
1054
+
1055
+ d.setdefault(cmd, {})[opt] = val
1056
+
1057
+ return d
1058
+
1059
+ def iter_distribution_names(self) -> Iterator[str]:
1060
+ """Yield all packages, modules, and extension names in distribution"""
1061
+
1062
+ yield from self.packages or ()
1063
+
1064
+ yield from self.py_modules or ()
1065
+
1066
+ for ext in self.ext_modules or ():
1067
+ if isinstance(ext, tuple):
1068
+ name, _buildinfo = ext
1069
+ else:
1070
+ name = ext.name
1071
+ name = name.removesuffix('module')
1072
+ yield name
1073
+
1074
+ def handle_display_options(self, option_order):
1075
+ """If there were any non-global "display-only" options
1076
+ (--help-commands or the metadata display options) on the command
1077
+ line, display the requested info and return true; else return
1078
+ false.
1079
+ """
1080
+ import sys
1081
+
1082
+ if self.help_commands:
1083
+ return _Distribution.handle_display_options(self, option_order)
1084
+
1085
+ # Stdout may be StringIO (e.g. in tests)
1086
+ if not isinstance(sys.stdout, io.TextIOWrapper):
1087
+ return _Distribution.handle_display_options(self, option_order)
1088
+
1089
+ # Don't wrap stdout if utf-8 is already the encoding. Provides
1090
+ # workaround for #334.
1091
+ if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
1092
+ return _Distribution.handle_display_options(self, option_order)
1093
+
1094
+ # Print metadata in UTF-8 no matter the platform
1095
+ encoding = sys.stdout.encoding
1096
+ sys.stdout.reconfigure(encoding='utf-8')
1097
+ try:
1098
+ return _Distribution.handle_display_options(self, option_order)
1099
+ finally:
1100
+ sys.stdout.reconfigure(encoding=encoding)
1101
+
1102
+ def run_command(self, command) -> None:
1103
+ self.set_defaults()
1104
+ # Postpone defaults until all explicit configuration is considered
1105
+ # (setup() args, config files, command line and plugins)
1106
+
1107
+ super().run_command(command)
1108
+
1109
+
1110
+ @functools.cache
1111
+ def _setuptools_commands() -> set[str]:
1112
+ try:
1113
+ # Use older API for importlib.metadata compatibility
1114
+ entry_points = metadata.distribution('setuptools').entry_points
1115
+ eps: Iterable[str] = (ep.name for ep in entry_points)
1116
+ except metadata.PackageNotFoundError:
1117
+ # during bootstrapping, distribution doesn't exist
1118
+ eps = []
1119
+ return {*distutils.command.__all__, *eps}
1120
+
1121
+
1122
+ class DistDeprecationWarning(SetuptoolsDeprecationWarning):
1123
+ """Class for warning about deprecations in dist in
1124
+ setuptools. Not ignored by default, unlike DeprecationWarning."""
python/Lib/site-packages/setuptools/errors.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """setuptools.errors
2
+
3
+ Provides exceptions used by setuptools modules.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from distutils import errors as _distutils_errors
9
+
10
+ # Re-export errors from distutils to facilitate the migration to PEP632
11
+
12
+ ByteCompileError = _distutils_errors.DistutilsByteCompileError
13
+ CCompilerError = _distutils_errors.CCompilerError
14
+ ClassError = _distutils_errors.DistutilsClassError
15
+ CompileError = _distutils_errors.CompileError
16
+ ExecError = _distutils_errors.DistutilsExecError
17
+ FileError = _distutils_errors.DistutilsFileError
18
+ InternalError = _distutils_errors.DistutilsInternalError
19
+ LibError = _distutils_errors.LibError
20
+ LinkError = _distutils_errors.LinkError
21
+ ModuleError = _distutils_errors.DistutilsModuleError
22
+ OptionError = _distutils_errors.DistutilsOptionError
23
+ PlatformError = _distutils_errors.DistutilsPlatformError
24
+ PreprocessError = _distutils_errors.PreprocessError
25
+ SetupError = _distutils_errors.DistutilsSetupError
26
+ TemplateError = _distutils_errors.DistutilsTemplateError
27
+ UnknownFileError = _distutils_errors.UnknownFileError
28
+
29
+ # The root error class in the hierarchy
30
+ BaseError = _distutils_errors.DistutilsError
31
+
32
+
33
+ class InvalidConfigError(OptionError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
34
+ """Error used for invalid configurations."""
35
+
36
+
37
+ class RemovedConfigError(OptionError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
38
+ """Error used for configurations that were deprecated and removed."""
39
+
40
+
41
+ class RemovedCommandError(BaseError, RuntimeError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
42
+ """Error used for commands that have been removed in setuptools.
43
+
44
+ Since ``setuptools`` is built on ``distutils``, simply removing a command
45
+ from ``setuptools`` will make the behavior fall back to ``distutils``; this
46
+ error is raised if a command exists in ``distutils`` but has been actively
47
+ removed in ``setuptools``.
48
+ """
49
+
50
+
51
+ class PackageDiscoveryError(BaseError, RuntimeError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+
52
+ """Impossible to perform automatic discovery of packages and/or modules.
53
+
54
+ The current project layout or given discovery options can lead to problems when
55
+ scanning the project directory.
56
+
57
+ Setuptools might also refuse to complete auto-discovery if an error prone condition
58
+ is detected (e.g. when a project is organised as a flat-layout but contains
59
+ multiple directories that can be taken as top-level packages inside a single
60
+ distribution [*]_). In these situations the users are encouraged to be explicit
61
+ about which packages to include or to make the discovery parameters more specific.
62
+
63
+ .. [*] Since multi-package distributions are uncommon it is very likely that the
64
+ developers did not intend for all the directories to be packaged, and are just
65
+ leaving auxiliary code in the repository top-level, such as maintenance-related
66
+ scripts.
67
+ """
python/Lib/site-packages/setuptools/extension.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import re
5
+ from collections.abc import Iterable
6
+ from typing import TYPE_CHECKING
7
+
8
+ from setuptools._path import StrPath
9
+
10
+ from .monkey import get_unpatched
11
+
12
+ import distutils.core
13
+ import distutils.errors
14
+ import distutils.extension
15
+
16
+
17
+ def _have_cython() -> bool:
18
+ """
19
+ Return True if Cython can be imported.
20
+ """
21
+ cython_impl = 'Cython.Distutils.build_ext'
22
+ try:
23
+ # from (cython_impl) import build_ext
24
+ __import__(cython_impl, fromlist=['build_ext']).build_ext
25
+ except Exception:
26
+ return False
27
+ return True
28
+
29
+
30
+ # for compatibility
31
+ have_pyrex = _have_cython
32
+ if TYPE_CHECKING:
33
+ # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
34
+ from distutils.core import Extension as _Extension
35
+ else:
36
+ _Extension = get_unpatched(distutils.core.Extension)
37
+
38
+
39
+ class Extension(_Extension):
40
+ """
41
+ Describes a single extension module.
42
+
43
+ This means that all source files will be compiled into a single binary file
44
+ ``<module path>.<suffix>`` (with ``<module path>`` derived from ``name`` and
45
+ ``<suffix>`` defined by one of the values in
46
+ ``importlib.machinery.EXTENSION_SUFFIXES``).
47
+
48
+ In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not**
49
+ installed in the build environment, ``setuptools`` may also try to look for the
50
+ equivalent ``.cpp`` or ``.c`` files.
51
+
52
+ :arg str name:
53
+ the full name of the extension, including any packages -- ie.
54
+ *not* a filename or pathname, but Python dotted name
55
+
56
+ :arg Iterable[str | os.PathLike[str]] sources:
57
+ iterable of source filenames, (except strings, which could be misinterpreted
58
+ as a single filename), relative to the distribution root
59
+ (where the setup script lives), in Unix form (slash-separated)
60
+ for portability. Source files may be C, C++, SWIG (.i),
61
+ platform-specific resource files, or whatever else is recognized
62
+ by the "build_ext" command as source for a Python extension.
63
+
64
+ :keyword list[str] include_dirs:
65
+ list of directories to search for C/C++ header files (in Unix
66
+ form for portability)
67
+
68
+ :keyword list[tuple[str, str|None]] define_macros:
69
+ list of macros to define; each macro is defined using a 2-tuple:
70
+ the first item corresponding to the name of the macro and the second
71
+ item either a string with its value or None to
72
+ define it without a particular value (equivalent of "#define
73
+ FOO" in source or -DFOO on Unix C compiler command line)
74
+
75
+ :keyword list[str] undef_macros:
76
+ list of macros to undefine explicitly
77
+
78
+ :keyword list[str] library_dirs:
79
+ list of directories to search for C/C++ libraries at link time
80
+
81
+ :keyword list[str] libraries:
82
+ list of library names (not filenames or paths) to link against
83
+
84
+ :keyword list[str] runtime_library_dirs:
85
+ list of directories to search for C/C++ libraries at run time
86
+ (for shared extensions, this is when the extension is loaded).
87
+ Setting this will cause an exception during build on Windows
88
+ platforms.
89
+
90
+ :keyword list[str] extra_objects:
91
+ list of extra files to link with (eg. object files not implied
92
+ by 'sources', static library that must be explicitly specified,
93
+ binary resource files, etc.)
94
+
95
+ :keyword list[str] extra_compile_args:
96
+ any extra platform- and compiler-specific information to use
97
+ when compiling the source files in 'sources'. For platforms and
98
+ compilers where "command line" makes sense, this is typically a
99
+ list of command-line arguments, but for other platforms it could
100
+ be anything.
101
+
102
+ :keyword list[str] extra_link_args:
103
+ any extra platform- and compiler-specific information to use
104
+ when linking object files together to create the extension (or
105
+ to create a new static Python interpreter). Similar
106
+ interpretation as for 'extra_compile_args'.
107
+
108
+ :keyword list[str] export_symbols:
109
+ list of symbols to be exported from a shared extension. Not
110
+ used on all platforms, and not generally necessary for Python
111
+ extensions, which typically export exactly one symbol: "init" +
112
+ extension_name.
113
+
114
+ :keyword list[str] swig_opts:
115
+ any extra options to pass to SWIG if a source file has the .i
116
+ extension.
117
+
118
+ :keyword list[str] depends:
119
+ list of files that the extension depends on
120
+
121
+ :keyword str language:
122
+ extension language (i.e. "c", "c++", "objc"). Will be detected
123
+ from the source extensions if not provided.
124
+
125
+ :keyword bool optional:
126
+ specifies that a build failure in the extension should not abort the
127
+ build process, but simply not install the failing extension.
128
+
129
+ :keyword bool py_limited_api:
130
+ opt-in flag for the usage of :doc:`Python's limited API <python:c-api/stable>`.
131
+
132
+ :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is
133
+ specified on Windows. (since v63)
134
+ """
135
+
136
+ # These 4 are set and used in setuptools/command/build_ext.py
137
+ # The lack of a default value and risk of `AttributeError` is purposeful
138
+ # to avoid people forgetting to call finalize_options if they modify the extension list.
139
+ # See example/rationale in https://github.com/pypa/setuptools/issues/4529.
140
+ _full_name: str #: Private API, internal use only.
141
+ _links_to_dynamic: bool #: Private API, internal use only.
142
+ _needs_stub: bool #: Private API, internal use only.
143
+ _file_name: str #: Private API, internal use only.
144
+
145
+ def __init__(
146
+ self,
147
+ name: str,
148
+ sources: Iterable[StrPath],
149
+ *args,
150
+ py_limited_api: bool = False,
151
+ **kw,
152
+ ) -> None:
153
+ # The *args is needed for compatibility as calls may use positional
154
+ # arguments. py_limited_api may be set only via keyword.
155
+ self.py_limited_api = py_limited_api
156
+ super().__init__(
157
+ name,
158
+ sources, # type: ignore[arg-type] # Vendored version of setuptools supports PathLike
159
+ *args,
160
+ **kw,
161
+ )
162
+
163
+ def _convert_pyx_sources_to_lang(self):
164
+ """
165
+ Replace sources with .pyx extensions to sources with the target
166
+ language extension. This mechanism allows language authors to supply
167
+ pre-converted sources but to prefer the .pyx sources.
168
+ """
169
+ if _have_cython():
170
+ # the build has Cython, so allow it to compile the .pyx files
171
+ return
172
+ lang = self.language or ''
173
+ target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
174
+ sub = functools.partial(re.sub, '.pyx$', target_ext)
175
+ self.sources = list(map(sub, self.sources))
176
+
177
+
178
+ class Library(Extension):
179
+ """Just like a regular Extension, but built as a library instead"""
python/Lib/site-packages/setuptools/glob.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Filename globbing utility. Mostly a copy of `glob` from Python 3.5.
3
+
4
+ Changes include:
5
+ * `yield from` and PEP3102 `*` removed.
6
+ * Hidden files are not ignored.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import os
13
+ import re
14
+ from collections.abc import Iterable, Iterator
15
+ from typing import TYPE_CHECKING, AnyStr, overload
16
+
17
+ if TYPE_CHECKING:
18
+ from _typeshed import BytesPath, StrOrBytesPath, StrPath
19
+
20
+ __all__ = ["glob", "iglob", "escape"]
21
+
22
+
23
+ def glob(pathname: AnyStr, recursive: bool = False) -> list[AnyStr]:
24
+ """Return a list of paths matching a pathname pattern.
25
+
26
+ The pattern may contain simple shell-style wildcards a la
27
+ fnmatch. However, unlike fnmatch, filenames starting with a
28
+ dot are special cases that are not matched by '*' and '?'
29
+ patterns.
30
+
31
+ If recursive is true, the pattern '**' will match any files and
32
+ zero or more directories and subdirectories.
33
+ """
34
+ return list(iglob(pathname, recursive=recursive))
35
+
36
+
37
+ def iglob(pathname: AnyStr, recursive: bool = False) -> Iterator[AnyStr]:
38
+ """Return an iterator which yields the paths matching a pathname pattern.
39
+
40
+ The pattern may contain simple shell-style wildcards a la
41
+ fnmatch. However, unlike fnmatch, filenames starting with a
42
+ dot are special cases that are not matched by '*' and '?'
43
+ patterns.
44
+
45
+ If recursive is true, the pattern '**' will match any files and
46
+ zero or more directories and subdirectories.
47
+ """
48
+ it = _iglob(pathname, recursive)
49
+ if recursive and _isrecursive(pathname):
50
+ s = next(it) # skip empty string
51
+ assert not s
52
+ return it
53
+
54
+
55
+ def _iglob(pathname: AnyStr, recursive: bool) -> Iterator[AnyStr]:
56
+ dirname, basename = os.path.split(pathname)
57
+ glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1
58
+
59
+ if not has_magic(pathname):
60
+ if basename:
61
+ if os.path.lexists(pathname):
62
+ yield pathname
63
+ else:
64
+ # Patterns ending with a slash should match only directories
65
+ if os.path.isdir(dirname):
66
+ yield pathname
67
+ return
68
+
69
+ if not dirname:
70
+ yield from glob_in_dir(dirname, basename)
71
+ return
72
+ # `os.path.split()` returns the argument itself as a dirname if it is a
73
+ # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
74
+ # contains magic characters (i.e. r'\\?\C:').
75
+ if dirname != pathname and has_magic(dirname):
76
+ dirs: Iterable[AnyStr] = _iglob(dirname, recursive)
77
+ else:
78
+ dirs = [dirname]
79
+ if not has_magic(basename):
80
+ glob_in_dir = glob0
81
+ for dirname in dirs:
82
+ for name in glob_in_dir(dirname, basename):
83
+ yield os.path.join(dirname, name)
84
+
85
+
86
+ # These 2 helper functions non-recursively glob inside a literal directory.
87
+ # They return a list of basenames. `glob1` accepts a pattern while `glob0`
88
+ # takes a literal basename (so it only has to check for its existence).
89
+
90
+
91
+ @overload
92
+ def glob1(dirname: StrPath, pattern: str) -> list[str]: ...
93
+ @overload
94
+ def glob1(dirname: BytesPath, pattern: bytes) -> list[bytes]: ...
95
+ def glob1(dirname: StrOrBytesPath, pattern: str | bytes) -> list[str] | list[bytes]:
96
+ if not dirname:
97
+ if isinstance(pattern, bytes):
98
+ dirname = os.curdir.encode('ASCII')
99
+ else:
100
+ dirname = os.curdir
101
+ try:
102
+ names = os.listdir(dirname)
103
+ except OSError:
104
+ return []
105
+ # mypy false-positives: str or bytes type possibility is always kept in sync
106
+ return fnmatch.filter(names, pattern) # type: ignore[type-var, return-value]
107
+
108
+
109
+ def glob0(dirname, basename):
110
+ if not basename:
111
+ # `os.path.split()` returns an empty basename for paths ending with a
112
+ # directory separator. 'q*x/' should match only directories.
113
+ if os.path.isdir(dirname):
114
+ return [basename]
115
+ else:
116
+ if os.path.lexists(os.path.join(dirname, basename)):
117
+ return [basename]
118
+ return []
119
+
120
+
121
+ # This helper function recursively yields relative pathnames inside a literal
122
+ # directory.
123
+
124
+
125
+ @overload
126
+ def glob2(dirname: StrPath, pattern: str) -> Iterator[str]: ...
127
+ @overload
128
+ def glob2(dirname: BytesPath, pattern: bytes) -> Iterator[bytes]: ...
129
+ def glob2(dirname: StrOrBytesPath, pattern: str | bytes) -> Iterator[str | bytes]:
130
+ assert _isrecursive(pattern)
131
+ yield pattern[:0]
132
+ yield from _rlistdir(dirname)
133
+
134
+
135
+ # Recursively yields relative pathnames inside a literal directory.
136
+ @overload
137
+ def _rlistdir(dirname: StrPath) -> Iterator[str]: ...
138
+ @overload
139
+ def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ...
140
+ def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]:
141
+ if not dirname:
142
+ if isinstance(dirname, bytes):
143
+ dirname = os.curdir.encode('ASCII')
144
+ else:
145
+ dirname = os.curdir
146
+ try:
147
+ names = os.listdir(dirname)
148
+ except OSError:
149
+ return
150
+ for x in names:
151
+ yield x
152
+ # mypy false-positives: str or bytes type possibility is always kept in sync
153
+ path = os.path.join(dirname, x) if dirname else x # type: ignore[arg-type]
154
+ for y in _rlistdir(path):
155
+ yield os.path.join(x, y) # type: ignore[arg-type]
156
+
157
+
158
+ magic_check = re.compile('([*?[])')
159
+ magic_check_bytes = re.compile(b'([*?[])')
160
+
161
+
162
+ def has_magic(s: str | bytes) -> bool:
163
+ if isinstance(s, bytes):
164
+ return magic_check_bytes.search(s) is not None
165
+ else:
166
+ return magic_check.search(s) is not None
167
+
168
+
169
+ def _isrecursive(pattern: str | bytes) -> bool:
170
+ if isinstance(pattern, bytes):
171
+ return pattern == b'**'
172
+ else:
173
+ return pattern == '**'
174
+
175
+
176
+ def escape(pathname):
177
+ """Escape all special characters."""
178
+ # Escaping is done by wrapping any of "*?[" between square brackets.
179
+ # Metacharacters do not work in the drive part and shouldn't be escaped.
180
+ drive, pathname = os.path.splitdrive(pathname)
181
+ if isinstance(pathname, bytes):
182
+ pathname = magic_check_bytes.sub(rb'[\1]', pathname)
183
+ else:
184
+ pathname = magic_check.sub(r'[\1]', pathname)
185
+ return drive + pathname
python/Lib/site-packages/setuptools/gui-32.exe ADDED
Binary file (11.8 kB). View file
 
python/Lib/site-packages/setuptools/gui-64.exe ADDED
Binary file (14.3 kB). View file
 
python/Lib/site-packages/setuptools/gui-arm64.exe ADDED
Binary file (13.8 kB). View file
 
python/Lib/site-packages/setuptools/gui.exe ADDED
Binary file (11.8 kB). View file
 
python/Lib/site-packages/setuptools/installer.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import glob
4
+ import itertools
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+
10
+ import packaging.requirements
11
+ import packaging.utils
12
+
13
+ from . import _reqs
14
+ from ._importlib import metadata
15
+ from .warnings import SetuptoolsDeprecationWarning
16
+ from .wheel import Wheel
17
+
18
+ from distutils import log
19
+ from distutils.errors import DistutilsError
20
+
21
+
22
+ def _fixup_find_links(find_links):
23
+ """Ensure find-links option end-up being a list of strings."""
24
+ if isinstance(find_links, str):
25
+ return find_links.split()
26
+ assert isinstance(find_links, (tuple, list))
27
+ return find_links
28
+
29
+
30
+ def fetch_build_egg(dist, req) -> metadata.Distribution | metadata.PathDistribution:
31
+ """Fetch an egg needed for building.
32
+
33
+ Use pip/wheel to fetch/build a wheel."""
34
+ _DeprecatedInstaller.emit()
35
+ _warn_wheel_not_available(dist)
36
+ return _fetch_build_egg_no_warn(dist, req)
37
+
38
+
39
+ def _present(req):
40
+ return any(_dist_matches_req(dist, req) for dist in metadata.distributions())
41
+
42
+
43
+ def _fetch_build_eggs(dist, requires: _reqs._StrOrIter) -> list[metadata.Distribution]:
44
+ _DeprecatedInstaller.emit(stacklevel=3)
45
+ _warn_wheel_not_available(dist)
46
+
47
+ parsed_reqs = _reqs.parse(requires)
48
+
49
+ missing_reqs = itertools.filterfalse(_present, parsed_reqs)
50
+
51
+ needed_reqs = (
52
+ req for req in missing_reqs if not req.marker or req.marker.evaluate()
53
+ )
54
+ resolved_dists = [_fetch_build_egg_no_warn(dist, req) for req in needed_reqs]
55
+ for dist in resolved_dists:
56
+ # dist.locate_file('') is the directory containing EGG-INFO, where the importabl
57
+ # contents can be found.
58
+ sys.path.insert(0, str(dist.locate_file('')))
59
+ return resolved_dists
60
+
61
+
62
+ def _dist_matches_req(egg_dist, req):
63
+ return (
64
+ packaging.utils.canonicalize_name(egg_dist.name)
65
+ == packaging.utils.canonicalize_name(req.name)
66
+ and egg_dist.version in req.specifier
67
+ )
68
+
69
+
70
+ def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # FIXME
71
+ # Ignore environment markers; if supplied, it is required.
72
+ req = strip_marker(req)
73
+ # Take easy_install options into account, but do not override relevant
74
+ # pip environment variables (like PIP_INDEX_URL or PIP_QUIET); they'll
75
+ # take precedence.
76
+ opts = dist.get_option_dict('easy_install')
77
+ if 'allow_hosts' in opts:
78
+ raise DistutilsError(
79
+ 'the `allow-hosts` option is not supported '
80
+ 'when using pip to install requirements.'
81
+ )
82
+ quiet = 'PIP_QUIET' not in os.environ and 'PIP_VERBOSE' not in os.environ
83
+ if 'PIP_INDEX_URL' in os.environ:
84
+ index_url = None
85
+ elif 'index_url' in opts:
86
+ index_url = opts['index_url'][1]
87
+ else:
88
+ index_url = None
89
+ find_links = (
90
+ _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts else []
91
+ )
92
+ if dist.dependency_links:
93
+ find_links.extend(dist.dependency_links)
94
+ eggs_dir = os.path.realpath(dist.get_egg_cache_dir())
95
+ cached_dists = metadata.Distribution.discover(path=glob.glob(f'{eggs_dir}/*.egg'))
96
+ for egg_dist in cached_dists:
97
+ if _dist_matches_req(egg_dist, req):
98
+ return egg_dist
99
+ with tempfile.TemporaryDirectory() as tmpdir:
100
+ cmd = [
101
+ sys.executable,
102
+ '-m',
103
+ 'pip',
104
+ '--disable-pip-version-check',
105
+ 'wheel',
106
+ '--no-deps',
107
+ '-w',
108
+ tmpdir,
109
+ ]
110
+ if quiet:
111
+ cmd.append('--quiet')
112
+ if index_url is not None:
113
+ cmd.extend(('--index-url', index_url))
114
+ for link in find_links or []:
115
+ cmd.extend(('--find-links', link))
116
+ # If requirement is a PEP 508 direct URL, directly pass
117
+ # the URL to pip, as `req @ url` does not work on the
118
+ # command line.
119
+ cmd.append(req.url or str(req))
120
+ try:
121
+ subprocess.check_call(cmd)
122
+ except subprocess.CalledProcessError as e:
123
+ raise DistutilsError(str(e)) from e
124
+ wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])
125
+ dist_location = os.path.join(eggs_dir, wheel.egg_name())
126
+ wheel.install_as_egg(dist_location)
127
+ return metadata.Distribution.at(dist_location + '/EGG-INFO')
128
+
129
+
130
+ def strip_marker(req) -> packaging.requirements.Requirement:
131
+ """
132
+ Return a new requirement without the environment marker to avoid
133
+ calling pip with something like `babel; extra == "i18n"`, which
134
+ would always be ignored.
135
+ """
136
+ # create a copy to avoid mutating the input
137
+ req = packaging.requirements.Requirement(str(req))
138
+ req.marker = None
139
+ return req
140
+
141
+
142
+ def _warn_wheel_not_available(dist):
143
+ try:
144
+ metadata.distribution('wheel')
145
+ except metadata.PackageNotFoundError:
146
+ dist.announce('WARNING: The wheel package is not available.', log.WARN)
147
+
148
+
149
+ class _DeprecatedInstaller(SetuptoolsDeprecationWarning):
150
+ _SUMMARY = "setuptools.installer and fetch_build_eggs are deprecated."
151
+ _DETAILS = """
152
+ Requirements should be satisfied by a PEP 517 installer.
153
+ If you are using pip, you can try `pip install --use-pep517`.
154
+ """
155
+ _DUE_DATE = 2025, 10, 31
python/Lib/site-packages/setuptools/launch.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Launch the Python script on the command line after
3
+ setuptools is bootstrapped via import.
4
+ """
5
+
6
+ # Note that setuptools gets imported implicitly by the
7
+ # invocation of this script using python -m setuptools.launch
8
+
9
+ import sys
10
+ import tokenize
11
+
12
+
13
+ def run() -> None:
14
+ """
15
+ Run the script in sys.argv[1] as if it had
16
+ been invoked naturally.
17
+ """
18
+ __builtins__
19
+ script_name = sys.argv[1]
20
+ namespace = dict(
21
+ __file__=script_name,
22
+ __name__='__main__',
23
+ __doc__=None,
24
+ )
25
+ sys.argv[:] = sys.argv[1:]
26
+
27
+ open_ = getattr(tokenize, 'open', open)
28
+ with open_(script_name) as fid:
29
+ script = fid.read()
30
+ norm_script = script.replace('\\r\\n', '\\n')
31
+ code = compile(norm_script, script_name, 'exec')
32
+ exec(code, namespace)
33
+
34
+
35
+ if __name__ == '__main__':
36
+ run()
python/Lib/site-packages/setuptools/launcher manifest.xml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
3
+ <assemblyIdentity version="1.0.0.0"
4
+ processorArchitecture="X86"
5
+ name="%(name)s"
6
+ type="win32"/>
7
+ <!-- Identify the application security requirements. -->
8
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
9
+ <security>
10
+ <requestedPrivileges>
11
+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/>
12
+ </requestedPrivileges>
13
+ </security>
14
+ </trustInfo>
15
+ </assembly>
python/Lib/site-packages/setuptools/logging.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import logging
3
+ import sys
4
+
5
+ from . import monkey
6
+
7
+ import distutils.log
8
+
9
+
10
+ def _not_warning(record):
11
+ return record.levelno < logging.WARNING
12
+
13
+
14
+ def configure() -> None:
15
+ """
16
+ Configure logging to emit warning and above to stderr
17
+ and everything else to stdout. This behavior is provided
18
+ for compatibility with distutils.log but may change in
19
+ the future.
20
+ """
21
+ err_handler = logging.StreamHandler()
22
+ err_handler.setLevel(logging.WARNING)
23
+ out_handler = logging.StreamHandler(sys.stdout)
24
+ out_handler.addFilter(_not_warning)
25
+ handlers = err_handler, out_handler
26
+ logging.basicConfig(
27
+ format="{message}", style='{', handlers=handlers, level=logging.DEBUG
28
+ )
29
+ if inspect.ismodule(distutils.dist.log):
30
+ monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
31
+ # For some reason `distutils.log` module is getting cached in `distutils.dist`
32
+ # and then loaded again when patched,
33
+ # implying: id(distutils.log) != id(distutils.dist.log).
34
+ # Make sure the same module object is used everywhere:
35
+ distutils.dist.log = distutils.log
36
+
37
+
38
+ def set_threshold(level: int) -> int:
39
+ logging.root.setLevel(level * 10)
40
+ return set_threshold.unpatched(level)