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

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/Lib/site-packages/setuptools/_distutils/archive_util.py +284 -0
  2. python/Lib/site-packages/setuptools/_distutils/ccompiler.py +26 -0
  3. python/Lib/site-packages/setuptools/_distutils/cmd.py +535 -0
  4. python/Lib/site-packages/setuptools/_distutils/core.py +289 -0
  5. python/Lib/site-packages/setuptools/_distutils/cygwinccompiler.py +31 -0
  6. python/Lib/site-packages/setuptools/_distutils/debug.py +5 -0
  7. python/Lib/site-packages/setuptools/_distutils/dep_util.py +14 -0
  8. python/Lib/site-packages/setuptools/_distutils/dir_util.py +232 -0
  9. python/Lib/site-packages/setuptools/_distutils/dist.py +1384 -0
  10. python/Lib/site-packages/setuptools/_distutils/errors.py +108 -0
  11. python/Lib/site-packages/setuptools/_distutils/extension.py +258 -0
  12. python/Lib/site-packages/setuptools/_distutils/fancy_getopt.py +471 -0
  13. python/Lib/site-packages/setuptools/_distutils/file_util.py +228 -0
  14. python/Lib/site-packages/setuptools/_distutils/filelist.py +431 -0
  15. python/Lib/site-packages/setuptools/_distutils/log.py +56 -0
  16. python/Lib/site-packages/setuptools/_distutils/spawn.py +130 -0
  17. python/Lib/site-packages/setuptools/_distutils/sysconfig.py +598 -0
  18. python/Lib/site-packages/setuptools/_distutils/text_file.py +286 -0
  19. python/Lib/site-packages/setuptools/_distutils/unixccompiler.py +9 -0
  20. python/Lib/site-packages/setuptools/_distutils/util.py +506 -0
  21. python/Lib/site-packages/setuptools/_distutils/version.py +348 -0
  22. python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER +1 -0
  23. python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA +283 -0
  24. python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD +13 -0
  25. python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED +0 -0
  26. python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL +4 -0
  27. python/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py +6 -0
  28. python/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.pyi +2 -0
  29. python/Lib/site-packages/setuptools/_vendor/more_itertools/py.typed +0 -0
  30. python/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.py +1471 -0
  31. python/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.pyi +205 -0
  32. python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER +1 -0
  33. python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/METADATA +107 -0
  34. python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/RECORD +26 -0
  35. python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/REQUESTED +0 -0
  36. python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/WHEEL +4 -0
  37. python/Lib/site-packages/setuptools/_vendor/packaging/__init__.py +15 -0
  38. python/Lib/site-packages/setuptools/_vendor/packaging/_elffile.py +108 -0
  39. python/Lib/site-packages/setuptools/_vendor/packaging/_manylinux.py +262 -0
  40. python/Lib/site-packages/setuptools/_vendor/packaging/_musllinux.py +85 -0
  41. python/Lib/site-packages/setuptools/_vendor/packaging/_parser.py +365 -0
  42. python/Lib/site-packages/setuptools/_vendor/packaging/_structures.py +69 -0
  43. python/Lib/site-packages/setuptools/_vendor/packaging/_tokenizer.py +193 -0
  44. python/Lib/site-packages/setuptools/_vendor/packaging/markers.py +388 -0
  45. python/Lib/site-packages/setuptools/_vendor/packaging/metadata.py +978 -0
  46. python/Lib/site-packages/setuptools/_vendor/packaging/py.typed +0 -0
  47. python/Lib/site-packages/setuptools/_vendor/packaging/pylock.py +635 -0
  48. python/Lib/site-packages/setuptools/_vendor/packaging/requirements.py +86 -0
  49. python/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py +1068 -0
  50. python/Lib/site-packages/setuptools/_vendor/packaging/tags.py +651 -0
python/Lib/site-packages/setuptools/_distutils/archive_util.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.archive_util
2
+
3
+ Utility functions for creating archive files (tarballs, zip files,
4
+ that sort of thing)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from typing import Literal, overload
10
+
11
+ try:
12
+ import zipfile
13
+ except ImportError:
14
+ zipfile = None
15
+
16
+
17
+ from ._log import log
18
+ from .dir_util import mkpath
19
+ from .errors import DistutilsExecError
20
+ from .spawn import spawn
21
+
22
+ try:
23
+ from pwd import getpwnam
24
+ except ImportError:
25
+ getpwnam = None
26
+
27
+ try:
28
+ from grp import getgrnam
29
+ except ImportError:
30
+ getgrnam = None
31
+
32
+
33
+ def _get_gid(name):
34
+ """Returns a gid, given a group name."""
35
+ if getgrnam is None or name is None:
36
+ return None
37
+ try:
38
+ result = getgrnam(name)
39
+ except KeyError:
40
+ result = None
41
+ if result is not None:
42
+ return result[2]
43
+ return None
44
+
45
+
46
+ def _get_uid(name):
47
+ """Returns an uid, given a user name."""
48
+ if getpwnam is None or name is None:
49
+ return None
50
+ try:
51
+ result = getpwnam(name)
52
+ except KeyError:
53
+ result = None
54
+ if result is not None:
55
+ return result[2]
56
+ return None
57
+
58
+
59
+ def make_tarball(
60
+ base_name: str,
61
+ base_dir: str | os.PathLike[str],
62
+ compress: Literal["gzip", "bzip2", "xz"] | None = "gzip",
63
+ verbose: bool = False,
64
+ owner: str | None = None,
65
+ group: str | None = None,
66
+ ) -> str:
67
+ """Create a (possibly compressed) tar file from all the files under
68
+ 'base_dir'.
69
+
70
+ 'compress' must be "gzip" (the default), "bzip2", "xz", or None.
71
+
72
+ 'owner' and 'group' can be used to define an owner and a group for the
73
+ archive that is being built. If not provided, the current owner and group
74
+ will be used.
75
+
76
+ The output tar file will be named 'base_dir' + ".tar", possibly plus
77
+ the appropriate compression extension (".gz", ".bz2", ".xz" or ".Z").
78
+
79
+ Returns the output filename.
80
+ """
81
+ tar_compression = {
82
+ 'gzip': 'gz',
83
+ 'bzip2': 'bz2',
84
+ 'xz': 'xz',
85
+ None: '',
86
+ }
87
+ compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'}
88
+
89
+ # flags for compression program, each element of list will be an argument
90
+ if compress is not None and compress not in compress_ext.keys():
91
+ raise ValueError(
92
+ "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'"
93
+ )
94
+
95
+ archive_name = base_name + '.tar'
96
+ archive_name += compress_ext.get(compress, '')
97
+
98
+ mkpath(os.path.dirname(archive_name))
99
+
100
+ # creating the tarball
101
+ import tarfile # late import so Python build itself doesn't break
102
+
103
+ log.info('Creating tar archive')
104
+
105
+ uid = _get_uid(owner)
106
+ gid = _get_gid(group)
107
+
108
+ def _set_uid_gid(tarinfo):
109
+ if gid is not None:
110
+ tarinfo.gid = gid
111
+ tarinfo.gname = group
112
+ if uid is not None:
113
+ tarinfo.uid = uid
114
+ tarinfo.uname = owner
115
+ return tarinfo
116
+
117
+ tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}')
118
+ try:
119
+ tar.add(base_dir, filter=_set_uid_gid)
120
+ finally:
121
+ tar.close()
122
+
123
+ return archive_name
124
+
125
+
126
+ def make_zipfile(
127
+ base_name: str,
128
+ base_dir: str | os.PathLike[str],
129
+ verbose: bool = False,
130
+ ) -> str:
131
+ """Create a zip file from all the files under 'base_dir'.
132
+
133
+ The output zip file will be named 'base_name' + ".zip". Uses either the
134
+ "zipfile" Python module (if available) or the InfoZIP "zip" utility
135
+ (if installed and found on the default search path). If neither tool is
136
+ available, raises DistutilsExecError. Returns the name of the output zip
137
+ file.
138
+ """
139
+ zip_filename = base_name + ".zip"
140
+ mkpath(os.path.dirname(zip_filename))
141
+
142
+ # If zipfile module is not available, try spawning an external
143
+ # 'zip' command.
144
+ if zipfile is None:
145
+ if verbose:
146
+ zipoptions = "-r"
147
+ else:
148
+ zipoptions = "-rq"
149
+
150
+ try:
151
+ spawn(["zip", zipoptions, zip_filename, base_dir])
152
+ except DistutilsExecError:
153
+ # XXX really should distinguish between "couldn't find
154
+ # external 'zip' command" and "zip failed".
155
+ raise DistutilsExecError(
156
+ f"unable to create zip file '{zip_filename}': "
157
+ "could neither import the 'zipfile' module nor "
158
+ "find a standalone zip utility"
159
+ )
160
+
161
+ else:
162
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
163
+
164
+ try:
165
+ zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED)
166
+ except RuntimeError:
167
+ zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
168
+
169
+ with zip:
170
+ if base_dir != os.curdir:
171
+ path = os.path.normpath(os.path.join(base_dir, ''))
172
+ zip.write(path, path)
173
+ log.info("adding '%s'", path)
174
+ for dirpath, dirnames, filenames in os.walk(base_dir):
175
+ for name in dirnames:
176
+ path = os.path.normpath(os.path.join(dirpath, name, ''))
177
+ zip.write(path, path)
178
+ log.info("adding '%s'", path)
179
+ for name in filenames:
180
+ path = os.path.normpath(os.path.join(dirpath, name))
181
+ if os.path.isfile(path):
182
+ zip.write(path, path)
183
+ log.info("adding '%s'", path)
184
+
185
+ return zip_filename
186
+
187
+
188
+ ARCHIVE_FORMATS = {
189
+ 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
190
+ 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
191
+ 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"),
192
+ 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
193
+ 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
194
+ 'zip': (make_zipfile, [], "ZIP file"),
195
+ }
196
+
197
+
198
+ def check_archive_formats(formats):
199
+ """Returns the first format from the 'format' list that is unknown.
200
+
201
+ If all formats are known, returns None
202
+ """
203
+ for format in formats:
204
+ if format not in ARCHIVE_FORMATS:
205
+ return format
206
+ return None
207
+
208
+
209
+ @overload
210
+ def make_archive(
211
+ base_name: str,
212
+ format: str,
213
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
214
+ base_dir: str | None = None,
215
+ verbose: bool = False,
216
+ owner: str | None = None,
217
+ group: str | None = None,
218
+ ) -> str: ...
219
+ @overload
220
+ def make_archive(
221
+ base_name: str | os.PathLike[str],
222
+ format: str,
223
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
224
+ base_dir: str | None = None,
225
+ verbose: bool = False,
226
+ owner: str | None = None,
227
+ group: str | None = None,
228
+ ) -> str: ...
229
+ def make_archive(
230
+ base_name: str | os.PathLike[str],
231
+ format: str,
232
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
233
+ base_dir: str | None = None,
234
+ verbose: bool = False,
235
+ owner: str | None = None,
236
+ group: str | None = None,
237
+ ) -> str:
238
+ """Create an archive file (eg. zip or tar).
239
+
240
+ 'base_name' is the name of the file to create, minus any format-specific
241
+ extension; 'format' is the archive format: one of "zip", "tar", "gztar",
242
+ "bztar", "xztar", or "ztar".
243
+
244
+ 'root_dir' is a directory that will be the root directory of the
245
+ archive; ie. we typically chdir into 'root_dir' before creating the
246
+ archive. 'base_dir' is the directory where we start archiving from;
247
+ ie. 'base_dir' will be the common prefix of all files and
248
+ directories in the archive. 'root_dir' and 'base_dir' both default
249
+ to the current directory. Returns the name of the archive file.
250
+
251
+ 'owner' and 'group' are used when creating a tar archive. By default,
252
+ uses the current owner and group.
253
+ """
254
+ save_cwd = os.getcwd()
255
+ if root_dir is not None:
256
+ log.debug("changing into '%s'", root_dir)
257
+ base_name = os.path.abspath(base_name)
258
+ os.chdir(root_dir)
259
+
260
+ if base_dir is None:
261
+ base_dir = os.curdir
262
+
263
+ kwargs: dict[str, bool | None] = {}
264
+
265
+ try:
266
+ format_info = ARCHIVE_FORMATS[format]
267
+ except KeyError:
268
+ raise ValueError(f"unknown archive format '{format}'")
269
+
270
+ func = format_info[0]
271
+ kwargs.update(format_info[1])
272
+
273
+ if format != 'zip':
274
+ kwargs['owner'] = owner
275
+ kwargs['group'] = group
276
+
277
+ try:
278
+ filename = func(base_name, base_dir, **kwargs)
279
+ finally:
280
+ if root_dir is not None:
281
+ log.debug("changing back to '%s'", save_cwd)
282
+ os.chdir(save_cwd)
283
+
284
+ return filename
python/Lib/site-packages/setuptools/_distutils/ccompiler.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .compat.numpy import ( # noqa: F401
2
+ _default_compilers,
3
+ compiler_class,
4
+ )
5
+ from .compilers.C import base
6
+ from .compilers.C.base import (
7
+ gen_lib_options,
8
+ gen_preprocess_options,
9
+ get_default_compiler,
10
+ new_compiler,
11
+ show_compilers,
12
+ )
13
+ from .compilers.C.errors import CompileError, LinkError
14
+
15
+ __all__ = [
16
+ 'CompileError',
17
+ 'LinkError',
18
+ 'gen_lib_options',
19
+ 'gen_preprocess_options',
20
+ 'get_default_compiler',
21
+ 'new_compiler',
22
+ 'show_compilers',
23
+ ]
24
+
25
+
26
+ CCompiler = base.Compiler
python/Lib/site-packages/setuptools/_distutils/cmd.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.cmd
2
+
3
+ Provides the Command class, the base class for the command classes
4
+ in the distutils.command package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import os
11
+ import re
12
+ import sys
13
+ from abc import abstractmethod
14
+ from collections.abc import Callable, MutableSequence
15
+ from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload
16
+
17
+ from . import _modified, archive_util, dir_util, file_util, util
18
+ from ._log import log
19
+ from .errors import DistutilsOptionError
20
+
21
+ if TYPE_CHECKING:
22
+ # type-only import because of mutual dependence between these classes
23
+ from distutils.dist import Distribution
24
+
25
+ from typing_extensions import TypeVarTuple, Unpack
26
+
27
+ _Ts = TypeVarTuple("_Ts")
28
+
29
+ _StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
30
+ _BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
31
+ _CommandT = TypeVar("_CommandT", bound="Command")
32
+
33
+
34
+ class Command:
35
+ """Abstract base class for defining command classes, the "worker bees"
36
+ of the Distutils. A useful analogy for command classes is to think of
37
+ them as subroutines with local variables called "options". The options
38
+ are "declared" in 'initialize_options()' and "defined" (given their
39
+ final values, aka "finalized") in 'finalize_options()', both of which
40
+ must be defined by every command class. The distinction between the
41
+ two is necessary because option values might come from the outside
42
+ world (command line, config file, ...), and any options dependent on
43
+ other options must be computed *after* these outside influences have
44
+ been processed -- hence 'finalize_options()'. The "body" of the
45
+ subroutine, where it does all its work based on the values of its
46
+ options, is the 'run()' method, which must also be implemented by every
47
+ command class.
48
+ """
49
+
50
+ # 'sub_commands' formalizes the notion of a "family" of commands,
51
+ # eg. "install" as the parent with sub-commands "install_lib",
52
+ # "install_headers", etc. The parent of a family of commands
53
+ # defines 'sub_commands' as a class attribute; it's a list of
54
+ # (command_name : string, predicate : unbound_method | string | None)
55
+ # tuples, where 'predicate' is a method of the parent command that
56
+ # determines whether the corresponding command is applicable in the
57
+ # current situation. (Eg. we "install_headers" is only applicable if
58
+ # we have any C header files to install.) If 'predicate' is None,
59
+ # that command is always applicable.
60
+ #
61
+ # 'sub_commands' is usually defined at the *end* of a class, because
62
+ # predicates can be unbound methods, so they must already have been
63
+ # defined. The canonical example is the "install" command.
64
+ sub_commands: ClassVar[ # Any to work around variance issues
65
+ list[tuple[str, Callable[[Any], bool] | None]]
66
+ ] = []
67
+
68
+ user_options: ClassVar[
69
+ # Specifying both because list is invariant. Avoids mypy override assignment issues
70
+ list[tuple[str, str, str]] | list[tuple[str, str | None, str]]
71
+ ] = []
72
+
73
+ # -- Creation/initialization methods -------------------------------
74
+
75
+ def __init__(self, dist: Distribution) -> None:
76
+ """Create and initialize a new Command object. Most importantly,
77
+ invokes the 'initialize_options()' method, which is the real
78
+ initializer and depends on the actual command being
79
+ instantiated.
80
+ """
81
+ # late import because of mutual dependence between these classes
82
+ from distutils.dist import Distribution
83
+
84
+ if not isinstance(dist, Distribution):
85
+ raise TypeError("dist must be a Distribution instance")
86
+ if self.__class__ is Command:
87
+ raise RuntimeError("Command is an abstract class")
88
+
89
+ self.distribution = dist
90
+ self.initialize_options()
91
+
92
+ # Per-command versions of the global flags, so that the user can
93
+ # customize Distutils' behaviour command-by-command and let some
94
+ # commands fall back on the Distribution's behaviour. None means
95
+ # "not defined, check self.distribution's copy".
96
+
97
+ # verbose is largely ignored, but needs to be set for
98
+ # backwards compatibility (I think)?
99
+ self.verbose = dist.verbose
100
+
101
+ # Some commands define a 'self.force' option to ignore file
102
+ # timestamps, but methods defined *here* assume that
103
+ # 'self.force' exists for all commands. So define it here
104
+ # just to be safe.
105
+ self.force = None
106
+
107
+ # The 'help' flag is just used for command-line parsing, so
108
+ # none of that complicated bureaucracy is needed.
109
+ self.help = False
110
+
111
+ # 'finalized' records whether or not 'finalize_options()' has been
112
+ # called. 'finalize_options()' itself should not pay attention to
113
+ # this flag: it is the business of 'ensure_finalized()', which
114
+ # always calls 'finalize_options()', to respect/update it.
115
+ self.finalized = False
116
+
117
+ def ensure_finalized(self) -> None:
118
+ if not self.finalized:
119
+ self.finalize_options()
120
+ self.finalized = True
121
+
122
+ # Subclasses must define:
123
+ # initialize_options()
124
+ # provide default values for all options; may be customized by
125
+ # setup script, by options from config file(s), or by command-line
126
+ # options
127
+ # finalize_options()
128
+ # decide on the final values for all options; this is called
129
+ # after all possible intervention from the outside world
130
+ # (command-line, option file, etc.) has been processed
131
+ # run()
132
+ # run the command: do whatever it is we're here to do,
133
+ # controlled by the command's various option values
134
+
135
+ @abstractmethod
136
+ def initialize_options(self) -> None:
137
+ """Set default values for all the options that this command
138
+ supports. Note that these defaults may be overridden by other
139
+ commands, by the setup script, by config files, or by the
140
+ command-line. Thus, this is not the place to code dependencies
141
+ between options; generally, 'initialize_options()' implementations
142
+ are just a bunch of "self.foo = None" assignments.
143
+
144
+ This method must be implemented by all command classes.
145
+ """
146
+ raise RuntimeError(
147
+ f"abstract method -- subclass {self.__class__} must override"
148
+ )
149
+
150
+ @abstractmethod
151
+ def finalize_options(self) -> None:
152
+ """Set final values for all the options that this command supports.
153
+ This is always called as late as possible, ie. after any option
154
+ assignments from the command-line or from other commands have been
155
+ done. Thus, this is the place to code option dependencies: if
156
+ 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
157
+ long as 'foo' still has the same value it was assigned in
158
+ 'initialize_options()'.
159
+
160
+ This method must be implemented by all command classes.
161
+ """
162
+ raise RuntimeError(
163
+ f"abstract method -- subclass {self.__class__} must override"
164
+ )
165
+
166
+ def dump_options(self, header=None, indent=""):
167
+ from distutils.fancy_getopt import longopt_xlate
168
+
169
+ if header is None:
170
+ header = f"command options for '{self.get_command_name()}':"
171
+ self.announce(indent + header, level=logging.INFO)
172
+ indent = indent + " "
173
+ for option, _, _ in self.user_options:
174
+ option = option.translate(longopt_xlate)
175
+ if option[-1] == "=":
176
+ option = option[:-1]
177
+ value = getattr(self, option)
178
+ self.announce(indent + f"{option} = {value}", level=logging.INFO)
179
+
180
+ @abstractmethod
181
+ def run(self) -> None:
182
+ """A command's raison d'etre: carry out the action it exists to
183
+ perform, controlled by the options initialized in
184
+ 'initialize_options()', customized by other commands, the setup
185
+ script, the command-line, and config files, and finalized in
186
+ 'finalize_options()'. All terminal output and filesystem
187
+ interaction should be done by 'run()'.
188
+
189
+ This method must be implemented by all command classes.
190
+ """
191
+ raise RuntimeError(
192
+ f"abstract method -- subclass {self.__class__} must override"
193
+ )
194
+
195
+ def announce(self, msg: object, level: int = logging.DEBUG) -> None:
196
+ log.log(level, msg)
197
+
198
+ def debug_print(self, msg: object) -> None:
199
+ """Print 'msg' to stdout if the global DEBUG (taken from the
200
+ DISTUTILS_DEBUG environment variable) flag is true.
201
+ """
202
+ from distutils.debug import DEBUG
203
+
204
+ if DEBUG:
205
+ print(msg)
206
+ sys.stdout.flush()
207
+
208
+ # -- Option validation methods -------------------------------------
209
+ # (these are very handy in writing the 'finalize_options()' method)
210
+ #
211
+ # NB. the general philosophy here is to ensure that a particular option
212
+ # value meets certain type and value constraints. If not, we try to
213
+ # force it into conformance (eg. if we expect a list but have a string,
214
+ # split the string on comma and/or whitespace). If we can't force the
215
+ # option into conformance, raise DistutilsOptionError. Thus, command
216
+ # classes need do nothing more than (eg.)
217
+ # self.ensure_string_list('foo')
218
+ # and they can be guaranteed that thereafter, self.foo will be
219
+ # a list of strings.
220
+
221
+ def _ensure_stringlike(self, option, what, default=None):
222
+ val = getattr(self, option)
223
+ if val is None:
224
+ setattr(self, option, default)
225
+ return default
226
+ elif not isinstance(val, str):
227
+ raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
228
+ return val
229
+
230
+ def ensure_string(self, option: str, default: str | None = None) -> None:
231
+ """Ensure that 'option' is a string; if not defined, set it to
232
+ 'default'.
233
+ """
234
+ self._ensure_stringlike(option, "string", default)
235
+
236
+ def ensure_string_list(self, option: str) -> None:
237
+ r"""Ensure that 'option' is a list of strings. If 'option' is
238
+ currently a string, we split it either on /,\s*/ or /\s+/, so
239
+ "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
240
+ ["foo", "bar", "baz"].
241
+ """
242
+ val = getattr(self, option)
243
+ if val is None:
244
+ return
245
+ elif isinstance(val, str):
246
+ setattr(self, option, re.split(r',\s*|\s+', val))
247
+ else:
248
+ if isinstance(val, list):
249
+ ok = all(isinstance(v, str) for v in val)
250
+ else:
251
+ ok = False
252
+ if not ok:
253
+ raise DistutilsOptionError(
254
+ f"'{option}' must be a list of strings (got {val!r})"
255
+ )
256
+
257
+ def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
258
+ val = self._ensure_stringlike(option, what, default)
259
+ if val is not None and not tester(val):
260
+ raise DistutilsOptionError(
261
+ ("error in '%s' option: " + error_fmt) % (option, val)
262
+ )
263
+
264
+ def ensure_filename(self, option: str) -> None:
265
+ """Ensure that 'option' is the name of an existing file."""
266
+ self._ensure_tested_string(
267
+ option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
268
+ )
269
+
270
+ def ensure_dirname(self, option: str) -> None:
271
+ self._ensure_tested_string(
272
+ option,
273
+ os.path.isdir,
274
+ "directory name",
275
+ "'%s' does not exist or is not a directory",
276
+ )
277
+
278
+ # -- Convenience methods for commands ------------------------------
279
+
280
+ def get_command_name(self) -> str:
281
+ if hasattr(self, 'command_name'):
282
+ return self.command_name
283
+ else:
284
+ return self.__class__.__name__
285
+
286
+ def set_undefined_options(
287
+ self, src_cmd: str, *option_pairs: tuple[str, str]
288
+ ) -> None:
289
+ """Set the values of any "undefined" options from corresponding
290
+ option values in some other command object. "Undefined" here means
291
+ "is None", which is the convention used to indicate that an option
292
+ has not been changed between 'initialize_options()' and
293
+ 'finalize_options()'. Usually called from 'finalize_options()' for
294
+ options that depend on some other command rather than another
295
+ option of the same command. 'src_cmd' is the other command from
296
+ which option values will be taken (a command object will be created
297
+ for it if necessary); the remaining arguments are
298
+ '(src_option,dst_option)' tuples which mean "take the value of
299
+ 'src_option' in the 'src_cmd' command object, and copy it to
300
+ 'dst_option' in the current command object".
301
+ """
302
+ # Option_pairs: list of (src_option, dst_option) tuples
303
+ src_cmd_obj = self.distribution.get_command_obj(src_cmd)
304
+ src_cmd_obj.ensure_finalized()
305
+ for src_option, dst_option in option_pairs:
306
+ if getattr(self, dst_option) is None:
307
+ setattr(self, dst_option, getattr(src_cmd_obj, src_option))
308
+
309
+ # NOTE: Because distutils is private to Setuptools and not all commands are exposed here,
310
+ # not every possible command is enumerated in the signature.
311
+ def get_finalized_command(self, command: str, create: bool = True) -> Command:
312
+ """Wrapper around Distribution's 'get_command_obj()' method: find
313
+ (create if necessary and 'create' is true) the command object for
314
+ 'command', call its 'ensure_finalized()' method, and return the
315
+ finalized command object.
316
+ """
317
+ cmd_obj = self.distribution.get_command_obj(command, create)
318
+ cmd_obj.ensure_finalized()
319
+ return cmd_obj
320
+
321
+ # XXX rename to 'get_reinitialized_command()'? (should do the
322
+ # same in dist.py, if so)
323
+ @overload
324
+ def reinitialize_command(
325
+ self, command: str, reinit_subcommands: bool = False
326
+ ) -> Command: ...
327
+ @overload
328
+ def reinitialize_command(
329
+ self, command: _CommandT, reinit_subcommands: bool = False
330
+ ) -> _CommandT: ...
331
+ def reinitialize_command(
332
+ self, command: str | Command, reinit_subcommands=False
333
+ ) -> Command:
334
+ return self.distribution.reinitialize_command(command, reinit_subcommands)
335
+
336
+ def run_command(self, command: str) -> None:
337
+ """Run some other command: uses the 'run_command()' method of
338
+ Distribution, which creates and finalizes the command object if
339
+ necessary and then invokes its 'run()' method.
340
+ """
341
+ self.distribution.run_command(command)
342
+
343
+ def get_sub_commands(self) -> list[str]:
344
+ """Determine the sub-commands that are relevant in the current
345
+ distribution (ie., that need to be run). This is based on the
346
+ 'sub_commands' class attribute: each tuple in that list may include
347
+ a method that we call to determine if the subcommand needs to be
348
+ run for the current distribution. Return a list of command names.
349
+ """
350
+ commands = []
351
+ for cmd_name, method in self.sub_commands:
352
+ if method is None or method(self):
353
+ commands.append(cmd_name)
354
+ return commands
355
+
356
+ # -- External world manipulation -----------------------------------
357
+
358
+ def warn(self, msg: object) -> None:
359
+ log.warning("warning: %s: %s\n", self.get_command_name(), msg)
360
+
361
+ def execute(
362
+ self,
363
+ func: Callable[[Unpack[_Ts]], object],
364
+ args: tuple[Unpack[_Ts]],
365
+ msg: object = None,
366
+ level: int = 1,
367
+ ) -> None:
368
+ util.execute(func, args, msg)
369
+
370
+ def mkpath(self, name: str, mode: int = 0o777) -> None:
371
+ dir_util.mkpath(name, mode)
372
+
373
+ @overload
374
+ def copy_file(
375
+ self,
376
+ infile: str | os.PathLike[str],
377
+ outfile: _StrPathT,
378
+ preserve_mode: bool = True,
379
+ preserve_times: bool = True,
380
+ link: str | None = None,
381
+ level: int = 1,
382
+ ) -> tuple[_StrPathT | str, bool]: ...
383
+ @overload
384
+ def copy_file(
385
+ self,
386
+ infile: bytes | os.PathLike[bytes],
387
+ outfile: _BytesPathT,
388
+ preserve_mode: bool = True,
389
+ preserve_times: bool = True,
390
+ link: str | None = None,
391
+ level: int = 1,
392
+ ) -> tuple[_BytesPathT | bytes, bool]: ...
393
+ def copy_file(
394
+ self,
395
+ infile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
396
+ outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
397
+ preserve_mode: bool = True,
398
+ preserve_times: bool = True,
399
+ link: str | None = None,
400
+ level: int = 1,
401
+ ) -> tuple[str | os.PathLike[str] | bytes | os.PathLike[bytes], bool]:
402
+ """Copy a file respecting verbose, dry-run and force flags. (The
403
+ former two default to whatever is in the Distribution object, and
404
+ the latter defaults to false for commands that don't define it.)"""
405
+ return file_util.copy_file(
406
+ infile,
407
+ outfile,
408
+ preserve_mode,
409
+ preserve_times,
410
+ not self.force,
411
+ link,
412
+ )
413
+
414
+ def copy_tree(
415
+ self,
416
+ infile: str | os.PathLike[str],
417
+ outfile: str,
418
+ preserve_mode: bool = True,
419
+ preserve_times: bool = True,
420
+ preserve_symlinks: bool = False,
421
+ level: int = 1,
422
+ ) -> list[str]:
423
+ """Copy an entire directory tree respecting verbose, dry-run,
424
+ and force flags.
425
+ """
426
+ return dir_util.copy_tree(
427
+ infile,
428
+ outfile,
429
+ preserve_mode,
430
+ preserve_times,
431
+ preserve_symlinks,
432
+ not self.force,
433
+ )
434
+
435
+ @overload
436
+ def move_file(
437
+ self, src: str | os.PathLike[str], dst: _StrPathT, level: int = 1
438
+ ) -> _StrPathT | str: ...
439
+ @overload
440
+ def move_file(
441
+ self, src: bytes | os.PathLike[bytes], dst: _BytesPathT, level: int = 1
442
+ ) -> _BytesPathT | bytes: ...
443
+ def move_file(
444
+ self,
445
+ src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
446
+ dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
447
+ level: int = 1,
448
+ ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
449
+ """Move a file respecting dry-run flag."""
450
+ return file_util.move_file(src, dst)
451
+
452
+ def spawn(
453
+ self, cmd: MutableSequence[str], search_path: bool = True, level: int = 1
454
+ ) -> None:
455
+ """Spawn an external command respecting dry-run flag."""
456
+ from distutils.spawn import spawn
457
+
458
+ spawn(cmd, search_path)
459
+
460
+ @overload
461
+ def make_archive(
462
+ self,
463
+ base_name: str,
464
+ format: str,
465
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
466
+ base_dir: str | None = None,
467
+ owner: str | None = None,
468
+ group: str | None = None,
469
+ ) -> str: ...
470
+ @overload
471
+ def make_archive(
472
+ self,
473
+ base_name: str | os.PathLike[str],
474
+ format: str,
475
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
476
+ base_dir: str | None = None,
477
+ owner: str | None = None,
478
+ group: str | None = None,
479
+ ) -> str: ...
480
+ def make_archive(
481
+ self,
482
+ base_name: str | os.PathLike[str],
483
+ format: str,
484
+ root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
485
+ base_dir: str | None = None,
486
+ owner: str | None = None,
487
+ group: str | None = None,
488
+ ) -> str:
489
+ return archive_util.make_archive(
490
+ base_name,
491
+ format,
492
+ root_dir,
493
+ base_dir,
494
+ owner=owner,
495
+ group=group,
496
+ )
497
+
498
+ def make_file(
499
+ self,
500
+ infiles: str | list[str] | tuple[str, ...],
501
+ outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
502
+ func: Callable[[Unpack[_Ts]], object],
503
+ args: tuple[Unpack[_Ts]],
504
+ exec_msg: object = None,
505
+ skip_msg: object = None,
506
+ level: int = 1,
507
+ ) -> None:
508
+ """Special case of 'execute()' for operations that process one or
509
+ more input files and generate one output file. Works just like
510
+ 'execute()', except the operation is skipped and a different
511
+ message printed if 'outfile' already exists and is newer than all
512
+ files listed in 'infiles'. If the command defined 'self.force',
513
+ and it is true, then the command is unconditionally run -- does no
514
+ timestamp checks.
515
+ """
516
+ if skip_msg is None:
517
+ skip_msg = f"skipping {outfile} (inputs unchanged)"
518
+
519
+ # Allow 'infiles' to be a single string
520
+ if isinstance(infiles, str):
521
+ infiles = (infiles,)
522
+ elif not isinstance(infiles, (list, tuple)):
523
+ raise TypeError("'infiles' must be a string, or a list or tuple of strings")
524
+
525
+ if exec_msg is None:
526
+ exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles))
527
+
528
+ # If 'outfile' must be regenerated (either because it doesn't
529
+ # exist, is out-of-date, or the 'force' flag is true) then
530
+ # perform the action that presumably regenerates it
531
+ if self.force or _modified.newer_group(infiles, outfile):
532
+ self.execute(func, args, exec_msg, level)
533
+ # Otherwise, print the "skip" message
534
+ else:
535
+ log.debug(skip_msg)
python/Lib/site-packages/setuptools/_distutils/core.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.core
2
+
3
+ The only module that needs to be imported to use the Distutils; provides
4
+ the 'setup' function (which is to be called from the setup script). Also
5
+ indirectly provides the Distribution and Command classes, although they are
6
+ really defined in distutils.dist and distutils.cmd.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import sys
13
+ import tokenize
14
+ from collections.abc import Iterable
15
+
16
+ from .cmd import Command
17
+ from .debug import DEBUG
18
+
19
+ # Mainly import these so setup scripts can "from distutils.core import" them.
20
+ from .dist import Distribution
21
+ from .errors import (
22
+ CCompilerError,
23
+ DistutilsArgError,
24
+ DistutilsError,
25
+ DistutilsSetupError,
26
+ )
27
+ from .extension import Extension
28
+
29
+ __all__ = ['Distribution', 'Command', 'Extension', 'setup']
30
+
31
+ # This is a barebones help message generated displayed when the user
32
+ # runs the setup script with no arguments at all. More useful help
33
+ # is generated with various --help options: global help, list commands,
34
+ # and per-command help.
35
+ USAGE = """\
36
+ usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
37
+ or: %(script)s --help [cmd1 cmd2 ...]
38
+ or: %(script)s --help-commands
39
+ or: %(script)s cmd --help
40
+ """
41
+
42
+
43
+ def gen_usage(script_name):
44
+ script = os.path.basename(script_name)
45
+ return USAGE % locals()
46
+
47
+
48
+ # Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
49
+ _setup_stop_after = None
50
+ _setup_distribution = None
51
+
52
+ # Legal keyword arguments for the setup() function
53
+ setup_keywords = (
54
+ 'distclass',
55
+ 'script_name',
56
+ 'script_args',
57
+ 'options',
58
+ 'name',
59
+ 'version',
60
+ 'author',
61
+ 'author_email',
62
+ 'maintainer',
63
+ 'maintainer_email',
64
+ 'url',
65
+ 'license',
66
+ 'description',
67
+ 'long_description',
68
+ 'keywords',
69
+ 'platforms',
70
+ 'classifiers',
71
+ 'download_url',
72
+ 'requires',
73
+ 'provides',
74
+ 'obsoletes',
75
+ )
76
+
77
+ # Legal keyword arguments for the Extension constructor
78
+ extension_keywords = (
79
+ 'name',
80
+ 'sources',
81
+ 'include_dirs',
82
+ 'define_macros',
83
+ 'undef_macros',
84
+ 'library_dirs',
85
+ 'libraries',
86
+ 'runtime_library_dirs',
87
+ 'extra_objects',
88
+ 'extra_compile_args',
89
+ 'extra_link_args',
90
+ 'swig_opts',
91
+ 'export_symbols',
92
+ 'depends',
93
+ 'language',
94
+ )
95
+
96
+
97
+ def setup(**attrs): # noqa: C901
98
+ """The gateway to the Distutils: do everything your setup script needs
99
+ to do, in a highly flexible and user-driven way. Briefly: create a
100
+ Distribution instance; find and parse config files; parse the command
101
+ line; run each Distutils command found there, customized by the options
102
+ supplied to 'setup()' (as keyword arguments), in config files, and on
103
+ the command line.
104
+
105
+ The Distribution instance might be an instance of a class supplied via
106
+ the 'distclass' keyword argument to 'setup'; if no such class is
107
+ supplied, then the Distribution class (in dist.py) is instantiated.
108
+ All other arguments to 'setup' (except for 'cmdclass') are used to set
109
+ attributes of the Distribution instance.
110
+
111
+ The 'cmdclass' argument, if supplied, is a dictionary mapping command
112
+ names to command classes. Each command encountered on the command line
113
+ will be turned into a command class, which is in turn instantiated; any
114
+ class found in 'cmdclass' is used in place of the default, which is
115
+ (for command 'foo_bar') class 'foo_bar' in module
116
+ 'distutils.command.foo_bar'. The command class must provide a
117
+ 'user_options' attribute which is a list of option specifiers for
118
+ 'distutils.fancy_getopt'. Any command-line options between the current
119
+ and the next command are used to set attributes of the current command
120
+ object.
121
+
122
+ When the entire command-line has been successfully parsed, calls the
123
+ 'run()' method on each command object in turn. This method will be
124
+ driven entirely by the Distribution object (which each command object
125
+ has a reference to, thanks to its constructor), and the
126
+ command-specific options that became attributes of each command
127
+ object.
128
+ """
129
+
130
+ global _setup_stop_after, _setup_distribution
131
+
132
+ # Determine the distribution class -- either caller-supplied or
133
+ # our Distribution (see below).
134
+ klass = attrs.get('distclass')
135
+ if klass:
136
+ attrs.pop('distclass')
137
+ else:
138
+ klass = Distribution
139
+
140
+ if 'script_name' not in attrs:
141
+ attrs['script_name'] = os.path.basename(sys.argv[0])
142
+ if 'script_args' not in attrs:
143
+ attrs['script_args'] = sys.argv[1:]
144
+
145
+ # Create the Distribution instance, using the remaining arguments
146
+ # (ie. everything except distclass) to initialize it
147
+ try:
148
+ _setup_distribution = dist = klass(attrs)
149
+ except DistutilsSetupError as msg:
150
+ if 'name' not in attrs:
151
+ raise SystemExit(f"error in setup command: {msg}")
152
+ else:
153
+ raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg))
154
+
155
+ if _setup_stop_after == "init":
156
+ return dist
157
+
158
+ # Find and parse the config file(s): they will override options from
159
+ # the setup script, but be overridden by the command line.
160
+ dist.parse_config_files()
161
+
162
+ if DEBUG:
163
+ print("options (after parsing config files):")
164
+ dist.dump_option_dicts()
165
+
166
+ if _setup_stop_after == "config":
167
+ return dist
168
+
169
+ # Parse the command line and override config files; any
170
+ # command-line errors are the end user's fault, so turn them into
171
+ # SystemExit to suppress tracebacks.
172
+ try:
173
+ ok = dist.parse_command_line()
174
+ except DistutilsArgError as msg:
175
+ raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}")
176
+
177
+ if DEBUG:
178
+ print("options (after parsing command line):")
179
+ dist.dump_option_dicts()
180
+
181
+ if _setup_stop_after == "commandline":
182
+ return dist
183
+
184
+ # And finally, run all the commands found on the command line.
185
+ if ok:
186
+ return run_commands(dist)
187
+
188
+ return dist
189
+
190
+
191
+ # setup ()
192
+
193
+
194
+ def run_commands(dist):
195
+ """Given a Distribution object run all the commands,
196
+ raising ``SystemExit`` errors in the case of failure.
197
+
198
+ This function assumes that either ``sys.argv`` or ``dist.script_args``
199
+ is already set accordingly.
200
+ """
201
+ try:
202
+ dist.run_commands()
203
+ except KeyboardInterrupt:
204
+ raise SystemExit("interrupted")
205
+ except OSError as exc:
206
+ if DEBUG:
207
+ sys.stderr.write(f"error: {exc}\n")
208
+ raise
209
+ else:
210
+ raise SystemExit(f"error: {exc}")
211
+
212
+ except (DistutilsError, CCompilerError) as msg:
213
+ if DEBUG:
214
+ raise
215
+ else:
216
+ raise SystemExit("error: " + str(msg))
217
+
218
+ return dist
219
+
220
+
221
+ def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"):
222
+ """Run a setup script in a somewhat controlled environment, and
223
+ return the Distribution instance that drives things. This is useful
224
+ if you need to find out the distribution meta-data (passed as
225
+ keyword args from 'script' to 'setup()', or the contents of the
226
+ config files or command-line.
227
+
228
+ 'script_name' is a file that will be read and run with 'exec()';
229
+ 'sys.argv[0]' will be replaced with 'script' for the duration of the
230
+ call. 'script_args' is a list of strings; if supplied,
231
+ 'sys.argv[1:]' will be replaced by 'script_args' for the duration of
232
+ the call.
233
+
234
+ 'stop_after' tells 'setup()' when to stop processing; possible
235
+ values:
236
+ init
237
+ stop after the Distribution instance has been created and
238
+ populated with the keyword arguments to 'setup()'
239
+ config
240
+ stop after config files have been parsed (and their data
241
+ stored in the Distribution instance)
242
+ commandline
243
+ stop after the command-line ('sys.argv[1:]' or 'script_args')
244
+ have been parsed (and the data stored in the Distribution)
245
+ run [default]
246
+ stop after all commands have been run (the same as if 'setup()'
247
+ had been called in the usual way
248
+
249
+ Returns the Distribution instance, which provides all information
250
+ used to drive the Distutils.
251
+ """
252
+ if stop_after not in ('init', 'config', 'commandline', 'run'):
253
+ raise ValueError(f"invalid value for 'stop_after': {stop_after!r}")
254
+
255
+ global _setup_stop_after, _setup_distribution
256
+ _setup_stop_after = stop_after
257
+
258
+ save_argv = sys.argv.copy()
259
+ g = {'__file__': script_name, '__name__': '__main__'}
260
+ try:
261
+ try:
262
+ sys.argv[0] = script_name
263
+ if script_args is not None:
264
+ sys.argv[1:] = script_args
265
+ # tokenize.open supports automatic encoding detection
266
+ with tokenize.open(script_name) as f:
267
+ code = f.read().replace(r'\r\n', r'\n')
268
+ exec(code, g)
269
+ finally:
270
+ sys.argv = save_argv
271
+ _setup_stop_after = None
272
+ except SystemExit:
273
+ # Hmm, should we do something if exiting with a non-zero code
274
+ # (ie. error)?
275
+ pass
276
+
277
+ if _setup_distribution is None:
278
+ raise RuntimeError(
279
+ "'distutils.core.setup()' was never called -- "
280
+ f"perhaps '{script_name}' is not a Distutils setup script?"
281
+ )
282
+
283
+ # I wonder if the setup script's namespace -- g and l -- would be of
284
+ # any interest to callers?
285
+ # print "_setup_distribution:", _setup_distribution
286
+ return _setup_distribution
287
+
288
+
289
+ # run_setup ()
python/Lib/site-packages/setuptools/_distutils/cygwinccompiler.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .compilers.C import cygwin
2
+ from .compilers.C.cygwin import (
3
+ CONFIG_H_NOTOK,
4
+ CONFIG_H_OK,
5
+ CONFIG_H_UNCERTAIN,
6
+ check_config_h,
7
+ get_msvcr,
8
+ is_cygwincc,
9
+ )
10
+
11
+ __all__ = [
12
+ 'CONFIG_H_NOTOK',
13
+ 'CONFIG_H_OK',
14
+ 'CONFIG_H_UNCERTAIN',
15
+ 'CygwinCCompiler',
16
+ 'Mingw32CCompiler',
17
+ 'check_config_h',
18
+ 'get_msvcr',
19
+ 'is_cygwincc',
20
+ ]
21
+
22
+
23
+ CygwinCCompiler = cygwin.Compiler
24
+ Mingw32CCompiler = cygwin.MinGW32Compiler
25
+
26
+
27
+ get_versions = None
28
+ """
29
+ A stand-in for the previous get_versions() function to prevent failures
30
+ when monkeypatched. See pypa/setuptools#2969.
31
+ """
python/Lib/site-packages/setuptools/_distutils/debug.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import os
2
+
3
+ # If DISTUTILS_DEBUG is anything other than the empty string, we run in
4
+ # debug mode.
5
+ DEBUG = os.environ.get('DISTUTILS_DEBUG')
python/Lib/site-packages/setuptools/_distutils/dep_util.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ from . import _modified
4
+
5
+
6
+ def __getattr__(name):
7
+ if name not in ['newer', 'newer_group', 'newer_pairwise']:
8
+ raise AttributeError(name)
9
+ warnings.warn(
10
+ "dep_util is Deprecated. Use functions from setuptools instead.",
11
+ DeprecationWarning,
12
+ stacklevel=2,
13
+ )
14
+ return getattr(_modified, name)
python/Lib/site-packages/setuptools/_distutils/dir_util.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.dir_util
2
+
3
+ Utility functions for manipulating directories and directory trees."""
4
+
5
+ import functools
6
+ import itertools
7
+ import os
8
+ import pathlib
9
+
10
+ from . import file_util
11
+ from ._log import log
12
+ from .errors import DistutilsFileError, DistutilsInternalError
13
+
14
+
15
+ class SkipRepeatAbsolutePaths(set):
16
+ """
17
+ Cache for mkpath.
18
+
19
+ In addition to cheapening redundant calls, eliminates redundant
20
+ "creating /foo/bar/baz" messages in dry-run mode.
21
+ """
22
+
23
+ def __init__(self):
24
+ SkipRepeatAbsolutePaths.instance = self
25
+
26
+ @classmethod
27
+ def clear(cls):
28
+ super(cls, cls.instance).clear()
29
+
30
+ def wrap(self, func):
31
+ @functools.wraps(func)
32
+ def wrapper(path, *args, **kwargs):
33
+ if path.absolute() in self:
34
+ return
35
+ result = func(path, *args, **kwargs)
36
+ self.add(path.absolute())
37
+ return result
38
+
39
+ return wrapper
40
+
41
+
42
+ # Python 3.8 compatibility
43
+ wrapper = SkipRepeatAbsolutePaths().wrap
44
+
45
+
46
+ @functools.singledispatch
47
+ @wrapper
48
+ def mkpath(name: pathlib.Path, mode=0o777, verbose=True) -> None:
49
+ """Create a directory and any missing ancestor directories.
50
+
51
+ If the directory already exists (or if 'name' is the empty string, which
52
+ means the current directory, which of course exists), then do nothing.
53
+ Raise DistutilsFileError if unable to create some directory along the way
54
+ (eg. some sub-path exists, but is a file rather than a directory).
55
+ If 'verbose' is true, log the directory created.
56
+ """
57
+ if verbose and not name.is_dir():
58
+ log.info("creating %s", name)
59
+
60
+ try:
61
+ name.mkdir(mode=mode, parents=True, exist_ok=True)
62
+ except OSError as exc:
63
+ raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}")
64
+
65
+
66
+ @mkpath.register
67
+ def _(name: str, *args, **kwargs):
68
+ return mkpath(pathlib.Path(name), *args, **kwargs)
69
+
70
+
71
+ @mkpath.register
72
+ def _(name: None, *args, **kwargs):
73
+ """
74
+ Detect a common bug -- name is None.
75
+ """
76
+ raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")
77
+
78
+
79
+ def create_tree(base_dir, files, mode=0o777, verbose=True):
80
+ """Create all the empty directories under 'base_dir' needed to put 'files'
81
+ there.
82
+
83
+ 'base_dir' is just the name of a directory which doesn't necessarily
84
+ exist yet; 'files' is a list of filenames to be interpreted relative to
85
+ 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
86
+ will be created if it doesn't already exist. 'mode' and 'verbose'
87
+ flags are as for 'mkpath()'.
88
+ """
89
+ # First get the list of directories to create
90
+ need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files)
91
+
92
+ # Now create them
93
+ for dir in sorted(need_dir):
94
+ mkpath(dir, mode, verbose=verbose)
95
+
96
+
97
+ def copy_tree(
98
+ src,
99
+ dst,
100
+ preserve_mode=True,
101
+ preserve_times=True,
102
+ preserve_symlinks=False,
103
+ update=False,
104
+ verbose=True,
105
+ ):
106
+ """Copy an entire directory tree 'src' to a new location 'dst'.
107
+
108
+ Both 'src' and 'dst' must be directory names. If 'src' is not a
109
+ directory, raise DistutilsFileError. If 'dst' does not exist, it is
110
+ created with 'mkpath()'. The end result of the copy is that every
111
+ file in 'src' is copied to 'dst', and directories under 'src' are
112
+ recursively copied to 'dst'. Return the list of files that were
113
+ copied or might have been copied, using their output name. The
114
+ return value is unaffected by 'update': it is simply
115
+ the list of all files under 'src', with the names changed to be
116
+ under 'dst'.
117
+
118
+ 'preserve_mode' and 'preserve_times' are the same as for
119
+ 'copy_file'; note that they only apply to regular files, not to
120
+ directories. If 'preserve_symlinks' is true, symlinks will be
121
+ copied as symlinks (on platforms that support them!); otherwise
122
+ (the default), the destination of the symlink will be copied.
123
+ 'update' and 'verbose' are the same as for 'copy_file'.
124
+ """
125
+ if not os.path.isdir(src):
126
+ raise DistutilsFileError(f"cannot copy tree '{src}': not a directory")
127
+ try:
128
+ names = os.listdir(src)
129
+ except OSError as e:
130
+ raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
131
+
132
+ mkpath(dst, verbose=verbose)
133
+
134
+ copy_one = functools.partial(
135
+ _copy_one,
136
+ src=src,
137
+ dst=dst,
138
+ preserve_symlinks=preserve_symlinks,
139
+ verbose=verbose,
140
+ preserve_mode=preserve_mode,
141
+ preserve_times=preserve_times,
142
+ update=update,
143
+ )
144
+ return list(itertools.chain.from_iterable(map(copy_one, names)))
145
+
146
+
147
+ def _copy_one(
148
+ name,
149
+ *,
150
+ src,
151
+ dst,
152
+ preserve_symlinks,
153
+ verbose,
154
+ preserve_mode,
155
+ preserve_times,
156
+ update,
157
+ ):
158
+ src_name = os.path.join(src, name)
159
+ dst_name = os.path.join(dst, name)
160
+
161
+ if name.startswith('.nfs'):
162
+ # skip NFS rename files
163
+ return
164
+
165
+ if preserve_symlinks and os.path.islink(src_name):
166
+ link_dest = os.readlink(src_name)
167
+ if verbose >= 1:
168
+ log.info("linking %s -> %s", dst_name, link_dest)
169
+ os.symlink(link_dest, dst_name)
170
+ yield dst_name
171
+
172
+ elif os.path.isdir(src_name):
173
+ yield from copy_tree(
174
+ src_name,
175
+ dst_name,
176
+ preserve_mode,
177
+ preserve_times,
178
+ preserve_symlinks,
179
+ update,
180
+ verbose=verbose,
181
+ )
182
+ else:
183
+ file_util.copy_file(
184
+ src_name,
185
+ dst_name,
186
+ preserve_mode,
187
+ preserve_times,
188
+ update,
189
+ verbose=verbose,
190
+ )
191
+ yield dst_name
192
+
193
+
194
+ def _build_cmdtuple(path, cmdtuples):
195
+ """Helper for remove_tree()."""
196
+ for f in os.listdir(path):
197
+ real_f = os.path.join(path, f)
198
+ if os.path.isdir(real_f) and not os.path.islink(real_f):
199
+ _build_cmdtuple(real_f, cmdtuples)
200
+ else:
201
+ cmdtuples.append((os.remove, real_f))
202
+ cmdtuples.append((os.rmdir, path))
203
+
204
+
205
+ def remove_tree(directory, verbose=True):
206
+ """Recursively remove an entire directory tree.
207
+
208
+ Any errors are ignored (apart from being reported to stdout if 'verbose'
209
+ is true).
210
+ """
211
+ if verbose >= 1:
212
+ log.info("removing '%s' (and everything under it)", directory)
213
+ cmdtuples = []
214
+ _build_cmdtuple(directory, cmdtuples)
215
+ for cmd in cmdtuples:
216
+ try:
217
+ cmd[0](cmd[1])
218
+ # Clear the cache
219
+ SkipRepeatAbsolutePaths.clear()
220
+ except OSError as exc:
221
+ log.warning("error removing %s: %s", directory, exc)
222
+
223
+
224
+ def ensure_relative(path):
225
+ """Take the full path 'path', and make it a relative path.
226
+
227
+ This is useful to make 'path' the second argument to os.path.join().
228
+ """
229
+ drive, path = os.path.splitdrive(path)
230
+ if path[0:1] == os.sep:
231
+ path = drive + path[1:]
232
+ return path
python/Lib/site-packages/setuptools/_distutils/dist.py ADDED
@@ -0,0 +1,1384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.dist
2
+
3
+ Provides the Distribution class, which represents the module distribution
4
+ being built/installed/distributed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import logging
11
+ import os
12
+ import pathlib
13
+ import re
14
+ import sys
15
+ import warnings
16
+ from collections.abc import Iterable, MutableMapping
17
+ from email import message_from_file
18
+ from typing import (
19
+ IO,
20
+ TYPE_CHECKING,
21
+ Any,
22
+ ClassVar,
23
+ Literal,
24
+ TypeVar,
25
+ Union,
26
+ overload,
27
+ )
28
+
29
+ from packaging.utils import canonicalize_name, canonicalize_version
30
+
31
+ from ._log import log
32
+ from .debug import DEBUG
33
+ from .errors import (
34
+ DistutilsArgError,
35
+ DistutilsClassError,
36
+ DistutilsModuleError,
37
+ DistutilsOptionError,
38
+ )
39
+ from .fancy_getopt import FancyGetopt, translate_longopt
40
+ from .util import check_environ, rfc822_escape, strtobool
41
+
42
+ if TYPE_CHECKING:
43
+ from _typeshed import SupportsWrite
44
+ from typing_extensions import TypeAlias
45
+
46
+ # type-only import because of mutual dependence between these modules
47
+ from .cmd import Command
48
+
49
+ _CommandT = TypeVar("_CommandT", bound="Command")
50
+ _OptionsList: TypeAlias = list[
51
+ Union[tuple[str, Union[str, None], str, int], tuple[str, Union[str, None], str]]
52
+ ]
53
+
54
+
55
+ # Regex to define acceptable Distutils command names. This is not *quite*
56
+ # the same as a Python NAME -- I don't allow leading underscores. The fact
57
+ # that they're very similar is no coincidence; the default naming scheme is
58
+ # to look for a Python module named after the command.
59
+ command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
60
+
61
+
62
+ def _ensure_list(value: str | Iterable[str], fieldname) -> str | list[str]:
63
+ if isinstance(value, str):
64
+ # a string containing comma separated values is okay. It will
65
+ # be converted to a list by Distribution.finalize_options().
66
+ pass
67
+ elif not isinstance(value, list):
68
+ # passing a tuple or an iterator perhaps, warn and convert
69
+ typename = type(value).__name__
70
+ msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"
71
+ msg = msg.format(**locals())
72
+ log.warning(msg)
73
+ value = list(value)
74
+ return value
75
+
76
+
77
+ class Distribution:
78
+ """The core of the Distutils. Most of the work hiding behind 'setup'
79
+ is really done within a Distribution instance, which farms the work out
80
+ to the Distutils commands specified on the command line.
81
+
82
+ Setup scripts will almost never instantiate Distribution directly,
83
+ unless the 'setup()' function is totally inadequate to their needs.
84
+ However, it is conceivable that a setup script might wish to subclass
85
+ Distribution for some specialized purpose, and then pass the subclass
86
+ to 'setup()' as the 'distclass' keyword argument. If so, it is
87
+ necessary to respect the expectations that 'setup' has of Distribution.
88
+ See the code for 'setup()', in core.py, for details.
89
+ """
90
+
91
+ # 'global_options' describes the command-line options that may be
92
+ # supplied to the setup script prior to any actual commands.
93
+ # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
94
+ # these global options. This list should be kept to a bare minimum,
95
+ # since every global option is also valid as a command option -- and we
96
+ # don't want to pollute the commands with too many options that they
97
+ # have minimal control over.
98
+ # The fourth entry for verbose means that it can be repeated.
99
+ global_options: ClassVar[_OptionsList] = [
100
+ ('verbose', 'v', "run verbosely (default)", 1),
101
+ ('quiet', 'q', "run quietly (turns verbosity off)"),
102
+ ('help', 'h', "show detailed help message"),
103
+ ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
104
+ ]
105
+
106
+ # 'common_usage' is a short (2-3 line) string describing the common
107
+ # usage of the setup script.
108
+ common_usage: ClassVar[str] = """\
109
+ Common commands: (see '--help-commands' for more)
110
+
111
+ setup.py build will build the package underneath 'build/'
112
+ setup.py install will install the package
113
+ """
114
+
115
+ # options that are not propagated to the commands
116
+ display_options: ClassVar[_OptionsList] = [
117
+ ('help-commands', None, "list all available commands"),
118
+ ('name', None, "print package name"),
119
+ ('version', 'V', "print package version"),
120
+ ('fullname', None, "print <package name>-<version>"),
121
+ ('author', None, "print the author's name"),
122
+ ('author-email', None, "print the author's email address"),
123
+ ('maintainer', None, "print the maintainer's name"),
124
+ ('maintainer-email', None, "print the maintainer's email address"),
125
+ ('contact', None, "print the maintainer's name if known, else the author's"),
126
+ (
127
+ 'contact-email',
128
+ None,
129
+ "print the maintainer's email address if known, else the author's",
130
+ ),
131
+ ('url', None, "print the URL for this package"),
132
+ ('license', None, "print the license of the package"),
133
+ ('licence', None, "alias for --license"),
134
+ ('description', None, "print the package description"),
135
+ ('long-description', None, "print the long package description"),
136
+ ('platforms', None, "print the list of platforms"),
137
+ ('classifiers', None, "print the list of classifiers"),
138
+ ('keywords', None, "print the list of keywords"),
139
+ ('provides', None, "print the list of packages/modules provided"),
140
+ ('requires', None, "print the list of packages/modules required"),
141
+ ('obsoletes', None, "print the list of packages/modules made obsolete"),
142
+ ]
143
+ display_option_names: ClassVar[list[str]] = [
144
+ translate_longopt(x[0]) for x in display_options
145
+ ]
146
+
147
+ # negative options are options that exclude other options
148
+ negative_opt: ClassVar[dict[str, str]] = {'quiet': 'verbose'}
149
+
150
+ # -- Creation/initialization methods -------------------------------
151
+
152
+ # Can't Unpack a TypedDict with optional properties, so using Any instead
153
+ def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None: # noqa: C901
154
+ """Construct a new Distribution instance: initialize all the
155
+ attributes of a Distribution, and then use 'attrs' (a dictionary
156
+ mapping attribute names to values) to assign some of those
157
+ attributes their "real" values. (Any attributes not mentioned in
158
+ 'attrs' will be assigned to some null value: 0, None, an empty list
159
+ or dictionary, etc.) Most importantly, initialize the
160
+ 'command_obj' attribute to the empty dictionary; this will be
161
+ filled in with real command objects by 'parse_command_line()'.
162
+ """
163
+
164
+ # Default values for our command-line options
165
+ self.verbose = True
166
+ self.help = False
167
+ for attr in self.display_option_names:
168
+ setattr(self, attr, False)
169
+
170
+ # Store the distribution meta-data (name, version, author, and so
171
+ # forth) in a separate object -- we're getting to have enough
172
+ # information here (and enough command-line options) that it's
173
+ # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
174
+ # object in a sneaky and underhanded (but efficient!) way.
175
+ self.metadata = DistributionMetadata()
176
+ for basename in self.metadata._METHOD_BASENAMES:
177
+ method_name = "get_" + basename
178
+ setattr(self, method_name, getattr(self.metadata, method_name))
179
+
180
+ # 'cmdclass' maps command names to class objects, so we
181
+ # can 1) quickly figure out which class to instantiate when
182
+ # we need to create a new command object, and 2) have a way
183
+ # for the setup script to override command classes
184
+ self.cmdclass: dict[str, type[Command]] = {}
185
+
186
+ # 'command_packages' is a list of packages in which commands
187
+ # are searched for. The factory for command 'foo' is expected
188
+ # to be named 'foo' in the module 'foo' in one of the packages
189
+ # named here. This list is searched from the left; an error
190
+ # is raised if no named package provides the command being
191
+ # searched for. (Always access using get_command_packages().)
192
+ self.command_packages: str | list[str] | None = None
193
+
194
+ # 'script_name' and 'script_args' are usually set to sys.argv[0]
195
+ # and sys.argv[1:], but they can be overridden when the caller is
196
+ # not necessarily a setup script run from the command-line.
197
+ self.script_name: str | os.PathLike[str] | None = None
198
+ self.script_args: list[str] | None = None
199
+
200
+ # 'command_options' is where we store command options between
201
+ # parsing them (from config files, the command-line, etc.) and when
202
+ # they are actually needed -- ie. when the command in question is
203
+ # instantiated. It is a dictionary of dictionaries of 2-tuples:
204
+ # command_options = { command_name : { option : (source, value) } }
205
+ self.command_options: dict[str, dict[str, tuple[str, str]]] = {}
206
+
207
+ # 'dist_files' is the list of (command, pyversion, file) that
208
+ # have been created by any dist commands run so far. This is
209
+ # filled regardless of whether the run is dry or not. pyversion
210
+ # gives sysconfig.get_python_version() if the dist file is
211
+ # specific to a Python version, 'any' if it is good for all
212
+ # Python versions on the target platform, and '' for a source
213
+ # file. pyversion should not be used to specify minimum or
214
+ # maximum required Python versions; use the metainfo for that
215
+ # instead.
216
+ self.dist_files: list[tuple[str, str, str]] = []
217
+
218
+ # These options are really the business of various commands, rather
219
+ # than of the Distribution itself. We provide aliases for them in
220
+ # Distribution as a convenience to the developer.
221
+ self.packages = None
222
+ self.package_data: dict[str, list[str]] = {}
223
+ self.package_dir = None
224
+ self.py_modules = None
225
+ self.libraries = None
226
+ self.headers = None
227
+ self.ext_modules = None
228
+ self.ext_package = None
229
+ self.include_dirs = None
230
+ self.extra_path = None
231
+ self.scripts = None
232
+ self.data_files = None
233
+ self.password = ''
234
+
235
+ # And now initialize bookkeeping stuff that can't be supplied by
236
+ # the caller at all. 'command_obj' maps command names to
237
+ # Command instances -- that's how we enforce that every command
238
+ # class is a singleton.
239
+ self.command_obj: dict[str, Command] = {}
240
+
241
+ # 'have_run' maps command names to boolean values; it keeps track
242
+ # of whether we have actually run a particular command, to make it
243
+ # cheap to "run" a command whenever we think we might need to -- if
244
+ # it's already been done, no need for expensive filesystem
245
+ # operations, we just check the 'have_run' dictionary and carry on.
246
+ # It's only safe to query 'have_run' for a command class that has
247
+ # been instantiated -- a false value will be inserted when the
248
+ # command object is created, and replaced with a true value when
249
+ # the command is successfully run. Thus it's probably best to use
250
+ # '.get()' rather than a straight lookup.
251
+ self.have_run: dict[str, bool] = {}
252
+
253
+ # Now we'll use the attrs dictionary (ultimately, keyword args from
254
+ # the setup script) to possibly override any or all of these
255
+ # distribution options.
256
+
257
+ if attrs:
258
+ # Pull out the set of command options and work on them
259
+ # specifically. Note that this order guarantees that aliased
260
+ # command options will override any supplied redundantly
261
+ # through the general options dictionary.
262
+ options = attrs.get('options')
263
+ if options is not None:
264
+ del attrs['options']
265
+ for command, cmd_options in options.items():
266
+ opt_dict = self.get_option_dict(command)
267
+ for opt, val in cmd_options.items():
268
+ opt_dict[opt] = ("setup script", val)
269
+
270
+ if 'licence' in attrs:
271
+ attrs['license'] = attrs['licence']
272
+ del attrs['licence']
273
+ msg = "'licence' distribution option is deprecated; use 'license'"
274
+ warnings.warn(msg)
275
+
276
+ # Now work on the rest of the attributes. Any attribute that's
277
+ # not already defined is invalid!
278
+ for key, val in attrs.items():
279
+ if hasattr(self.metadata, "set_" + key):
280
+ getattr(self.metadata, "set_" + key)(val)
281
+ elif hasattr(self.metadata, key):
282
+ setattr(self.metadata, key, val)
283
+ elif hasattr(self, key):
284
+ setattr(self, key, val)
285
+ else:
286
+ msg = f"Unknown distribution option: {key!r}"
287
+ warnings.warn(msg)
288
+
289
+ # no-user-cfg is handled before other command line args
290
+ # because other args override the config files, and this
291
+ # one is needed before we can load the config files.
292
+ # If attrs['script_args'] wasn't passed, assume false.
293
+ #
294
+ # This also make sure we just look at the global options
295
+ self.want_user_cfg = True
296
+
297
+ if self.script_args is not None:
298
+ # Coerce any possible iterable from attrs into a list
299
+ self.script_args = list(self.script_args)
300
+ for arg in self.script_args:
301
+ if not arg.startswith('-'):
302
+ break
303
+ if arg == '--no-user-cfg':
304
+ self.want_user_cfg = False
305
+ break
306
+
307
+ self.finalize_options()
308
+
309
+ def get_option_dict(self, command):
310
+ """Get the option dictionary for a given command. If that
311
+ command's option dictionary hasn't been created yet, then create it
312
+ and return the new dictionary; otherwise, return the existing
313
+ option dictionary.
314
+ """
315
+ dict = self.command_options.get(command)
316
+ if dict is None:
317
+ dict = self.command_options[command] = {}
318
+ return dict
319
+
320
+ def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None:
321
+ from pprint import pformat
322
+
323
+ if commands is None: # dump all command option dicts
324
+ commands = sorted(self.command_options.keys())
325
+
326
+ if header is not None:
327
+ self.announce(indent + header)
328
+ indent = indent + " "
329
+
330
+ if not commands:
331
+ self.announce(indent + "no commands known yet")
332
+ return
333
+
334
+ for cmd_name in commands:
335
+ opt_dict = self.command_options.get(cmd_name)
336
+ if opt_dict is None:
337
+ self.announce(indent + f"no option dict for '{cmd_name}' command")
338
+ else:
339
+ self.announce(indent + f"option dict for '{cmd_name}' command:")
340
+ out = pformat(opt_dict)
341
+ for line in out.split('\n'):
342
+ self.announce(indent + " " + line)
343
+
344
+ # -- Config file finding/parsing methods ---------------------------
345
+
346
+ def find_config_files(self):
347
+ """Find as many configuration files as should be processed for this
348
+ platform, and return a list of filenames in the order in which they
349
+ should be parsed. The filenames returned are guaranteed to exist
350
+ (modulo nasty race conditions).
351
+
352
+ There are multiple possible config files:
353
+ - distutils.cfg in the Distutils installation directory (i.e.
354
+ where the top-level Distutils __inst__.py file lives)
355
+ - a file in the user's home directory named .pydistutils.cfg
356
+ on Unix and pydistutils.cfg on Windows/Mac; may be disabled
357
+ with the ``--no-user-cfg`` option
358
+ - setup.cfg in the current directory
359
+ - a file named by an environment variable
360
+ """
361
+ check_environ()
362
+ files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
363
+
364
+ if DEBUG:
365
+ self.announce("using config files: {}".format(', '.join(files)))
366
+
367
+ return files
368
+
369
+ def _gen_paths(self):
370
+ # The system-wide Distutils config file
371
+ sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent
372
+ yield sys_dir / "distutils.cfg"
373
+
374
+ # The per-user config file
375
+ prefix = '.' * (os.name == 'posix')
376
+ filename = prefix + 'pydistutils.cfg'
377
+ if self.want_user_cfg:
378
+ with contextlib.suppress(RuntimeError):
379
+ yield pathlib.Path('~').expanduser() / filename
380
+
381
+ # All platforms support local setup.cfg
382
+ yield pathlib.Path('setup.cfg')
383
+
384
+ # Additional config indicated in the environment
385
+ with contextlib.suppress(TypeError):
386
+ yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG"))
387
+
388
+ def parse_config_files(self, filenames=None): # noqa: C901
389
+ from configparser import ConfigParser
390
+
391
+ # Ignore install directory options if we have a venv
392
+ if sys.prefix != sys.base_prefix:
393
+ ignore_options = [
394
+ 'install-base',
395
+ 'install-platbase',
396
+ 'install-lib',
397
+ 'install-platlib',
398
+ 'install-purelib',
399
+ 'install-headers',
400
+ 'install-scripts',
401
+ 'install-data',
402
+ 'prefix',
403
+ 'exec-prefix',
404
+ 'home',
405
+ 'user',
406
+ 'root',
407
+ ]
408
+ else:
409
+ ignore_options = []
410
+
411
+ ignore_options = frozenset(ignore_options)
412
+
413
+ if filenames is None:
414
+ filenames = self.find_config_files()
415
+
416
+ if DEBUG:
417
+ self.announce("Distribution.parse_config_files():")
418
+
419
+ parser = ConfigParser()
420
+ for filename in filenames:
421
+ if DEBUG:
422
+ self.announce(f" reading {filename}")
423
+ parser.read(filename, encoding='utf-8')
424
+ for section in parser.sections():
425
+ options = parser.options(section)
426
+ opt_dict = self.get_option_dict(section)
427
+
428
+ for opt in options:
429
+ if opt != '__name__' and opt not in ignore_options:
430
+ val = parser.get(section, opt)
431
+ opt = opt.replace('-', '_')
432
+ opt_dict[opt] = (filename, val)
433
+
434
+ # Make the ConfigParser forget everything (so we retain
435
+ # the original filenames that options come from)
436
+ parser.__init__()
437
+
438
+ # If there was a "global" section in the config file, use it
439
+ # to set Distribution options.
440
+
441
+ if 'global' in self.command_options:
442
+ for opt, (_src, val) in self.command_options['global'].items():
443
+ alias = self.negative_opt.get(opt)
444
+ try:
445
+ if alias:
446
+ setattr(self, alias, not strtobool(val))
447
+ elif opt in ('verbose',): # ugh!
448
+ setattr(self, opt, strtobool(val))
449
+ else:
450
+ setattr(self, opt, val)
451
+ except ValueError as msg:
452
+ raise DistutilsOptionError(msg)
453
+
454
+ # -- Command-line parsing methods ----------------------------------
455
+
456
+ def parse_command_line(self):
457
+ """Parse the setup script's command line, taken from the
458
+ 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
459
+ -- see 'setup()' in core.py). This list is first processed for
460
+ "global options" -- options that set attributes of the Distribution
461
+ instance. Then, it is alternately scanned for Distutils commands
462
+ and options for that command. Each new command terminates the
463
+ options for the previous command. The allowed options for a
464
+ command are determined by the 'user_options' attribute of the
465
+ command class -- thus, we have to be able to load command classes
466
+ in order to parse the command line. Any error in that 'options'
467
+ attribute raises DistutilsGetoptError; any error on the
468
+ command-line raises DistutilsArgError. If no Distutils commands
469
+ were found on the command line, raises DistutilsArgError. Return
470
+ true if command-line was successfully parsed and we should carry
471
+ on with executing commands; false if no errors but we shouldn't
472
+ execute commands (currently, this only happens if user asks for
473
+ help).
474
+ """
475
+ #
476
+ # We now have enough information to show the Macintosh dialog
477
+ # that allows the user to interactively specify the "command line".
478
+ #
479
+ toplevel_options = self._get_toplevel_options()
480
+
481
+ # We have to parse the command line a bit at a time -- global
482
+ # options, then the first command, then its options, and so on --
483
+ # because each command will be handled by a different class, and
484
+ # the options that are valid for a particular class aren't known
485
+ # until we have loaded the command class, which doesn't happen
486
+ # until we know what the command is.
487
+
488
+ self.commands = []
489
+ parser = FancyGetopt(toplevel_options + self.display_options)
490
+ parser.set_negative_aliases(self.negative_opt)
491
+ parser.set_aliases({'licence': 'license'})
492
+ args = parser.getopt(args=self.script_args, object=self)
493
+ option_order = parser.get_option_order()
494
+ logging.getLogger().setLevel(logging.WARN - 10 * self.verbose)
495
+
496
+ # for display options we return immediately
497
+ if self.handle_display_options(option_order):
498
+ return
499
+ while args:
500
+ args = self._parse_command_opts(parser, args)
501
+ if args is None: # user asked for help (and got it)
502
+ return
503
+
504
+ # Handle the cases of --help as a "global" option, ie.
505
+ # "setup.py --help" and "setup.py --help command ...". For the
506
+ # former, we show global options (--verbose, --dry-run, etc.)
507
+ # and display-only options (--name, --version, etc.); for the
508
+ # latter, we omit the display-only options and show help for
509
+ # each command listed on the command line.
510
+ if self.help:
511
+ self._show_help(
512
+ parser, display_options=len(self.commands) == 0, commands=self.commands
513
+ )
514
+ return
515
+
516
+ # Oops, no commands found -- an end-user error
517
+ if not self.commands:
518
+ raise DistutilsArgError("no commands supplied")
519
+
520
+ # All is well: return true
521
+ return True
522
+
523
+ def _get_toplevel_options(self):
524
+ """Return the non-display options recognized at the top level.
525
+
526
+ This includes options that are recognized *only* at the top
527
+ level as well as options recognized for commands.
528
+ """
529
+ return self.global_options + [
530
+ (
531
+ "command-packages=",
532
+ None,
533
+ "list of packages that provide distutils commands",
534
+ ),
535
+ ]
536
+
537
+ def _parse_command_opts(self, parser, args): # noqa: C901
538
+ """Parse the command-line options for a single command.
539
+ 'parser' must be a FancyGetopt instance; 'args' must be the list
540
+ of arguments, starting with the current command (whose options
541
+ we are about to parse). Returns a new version of 'args' with
542
+ the next command at the front of the list; will be the empty
543
+ list if there are no more commands on the command line. Returns
544
+ None if the user asked for help on this command.
545
+ """
546
+ # late import because of mutual dependence between these modules
547
+ from distutils.cmd import Command
548
+
549
+ # Pull the current command from the head of the command line
550
+ command = args[0]
551
+ if not command_re.match(command):
552
+ raise SystemExit(f"invalid command name '{command}'")
553
+ self.commands.append(command)
554
+
555
+ # Dig up the command class that implements this command, so we
556
+ # 1) know that it's a valid command, and 2) know which options
557
+ # it takes.
558
+ try:
559
+ cmd_class = self.get_command_class(command)
560
+ except DistutilsModuleError as msg:
561
+ raise DistutilsArgError(msg)
562
+
563
+ # Require that the command class be derived from Command -- want
564
+ # to be sure that the basic "command" interface is implemented.
565
+ if not issubclass(cmd_class, Command):
566
+ raise DistutilsClassError(
567
+ f"command class {cmd_class} must subclass Command"
568
+ )
569
+
570
+ # Also make sure that the command object provides a list of its
571
+ # known options.
572
+ if not (
573
+ hasattr(cmd_class, 'user_options')
574
+ and isinstance(cmd_class.user_options, list)
575
+ ):
576
+ msg = (
577
+ "command class %s must provide "
578
+ "'user_options' attribute (a list of tuples)"
579
+ )
580
+ raise DistutilsClassError(msg % cmd_class)
581
+
582
+ # If the command class has a list of negative alias options,
583
+ # merge it in with the global negative aliases.
584
+ negative_opt = self.negative_opt
585
+ if hasattr(cmd_class, 'negative_opt'):
586
+ negative_opt = negative_opt.copy()
587
+ negative_opt.update(cmd_class.negative_opt)
588
+
589
+ # Check for help_options in command class. They have a different
590
+ # format (tuple of four) so we need to preprocess them here.
591
+ if hasattr(cmd_class, 'help_options') and isinstance(
592
+ cmd_class.help_options, list
593
+ ):
594
+ help_options = fix_help_options(cmd_class.help_options)
595
+ else:
596
+ help_options = []
597
+
598
+ # All commands support the global options too, just by adding
599
+ # in 'global_options'.
600
+ parser.set_option_table(
601
+ self.global_options + cmd_class.user_options + help_options
602
+ )
603
+ parser.set_negative_aliases(negative_opt)
604
+ (args, opts) = parser.getopt(args[1:])
605
+ if hasattr(opts, 'help') and opts.help:
606
+ self._show_help(parser, display_options=False, commands=[cmd_class])
607
+ return
608
+
609
+ if hasattr(cmd_class, 'help_options') and isinstance(
610
+ cmd_class.help_options, list
611
+ ):
612
+ help_option_found = 0
613
+ for help_option, _short, _desc, func in cmd_class.help_options:
614
+ if hasattr(opts, parser.get_attr_name(help_option)):
615
+ help_option_found = 1
616
+ if callable(func):
617
+ func()
618
+ else:
619
+ raise DistutilsClassError(
620
+ f"invalid help function {func!r} for help option '{help_option}': "
621
+ "must be a callable object (function, etc.)"
622
+ )
623
+
624
+ if help_option_found:
625
+ return
626
+
627
+ # Put the options from the command-line into their official
628
+ # holding pen, the 'command_options' dictionary.
629
+ opt_dict = self.get_option_dict(command)
630
+ for name, value in vars(opts).items():
631
+ opt_dict[name] = ("command line", value)
632
+
633
+ return args
634
+
635
+ def finalize_options(self) -> None:
636
+ """Set final values for all the options on the Distribution
637
+ instance, analogous to the .finalize_options() method of Command
638
+ objects.
639
+ """
640
+ for attr in ('keywords', 'platforms'):
641
+ value = getattr(self.metadata, attr)
642
+ if value is None:
643
+ continue
644
+ if isinstance(value, str):
645
+ value = [elm.strip() for elm in value.split(',')]
646
+ setattr(self.metadata, attr, value)
647
+
648
+ def _show_help(
649
+ self, parser, global_options=True, display_options=True, commands: Iterable = ()
650
+ ):
651
+ """Show help for the setup script command-line in the form of
652
+ several lists of command-line options. 'parser' should be a
653
+ FancyGetopt instance; do not expect it to be returned in the
654
+ same state, as its option table will be reset to make it
655
+ generate the correct help text.
656
+
657
+ If 'global_options' is true, lists the global options:
658
+ --verbose, --dry-run, etc. If 'display_options' is true, lists
659
+ the "display-only" options: --name, --version, etc. Finally,
660
+ lists per-command help for every command name or command class
661
+ in 'commands'.
662
+ """
663
+ # late import because of mutual dependence between these modules
664
+ from distutils.cmd import Command
665
+ from distutils.core import gen_usage
666
+
667
+ if global_options:
668
+ if display_options:
669
+ options = self._get_toplevel_options()
670
+ else:
671
+ options = self.global_options
672
+ parser.set_option_table(options)
673
+ parser.print_help(self.common_usage + "\nGlobal options:")
674
+ print()
675
+
676
+ if display_options:
677
+ parser.set_option_table(self.display_options)
678
+ parser.print_help(
679
+ "Information display options (just display information, ignore any commands)"
680
+ )
681
+ print()
682
+
683
+ for command in commands:
684
+ if isinstance(command, type) and issubclass(command, Command):
685
+ klass = command
686
+ else:
687
+ klass = self.get_command_class(command)
688
+ if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
689
+ parser.set_option_table(
690
+ klass.user_options + fix_help_options(klass.help_options)
691
+ )
692
+ else:
693
+ parser.set_option_table(klass.user_options)
694
+ parser.print_help(f"Options for '{klass.__name__}' command:")
695
+ print()
696
+
697
+ print(gen_usage(self.script_name))
698
+
699
+ def handle_display_options(self, option_order):
700
+ """If there were any non-global "display-only" options
701
+ (--help-commands or the metadata display options) on the command
702
+ line, display the requested info and return true; else return
703
+ false.
704
+ """
705
+ from distutils.core import gen_usage
706
+
707
+ # User just wants a list of commands -- we'll print it out and stop
708
+ # processing now (ie. if they ran "setup --help-commands foo bar",
709
+ # we ignore "foo bar").
710
+ if self.help_commands:
711
+ self.print_commands()
712
+ print()
713
+ print(gen_usage(self.script_name))
714
+ return 1
715
+
716
+ # If user supplied any of the "display metadata" options, then
717
+ # display that metadata in the order in which the user supplied the
718
+ # metadata options.
719
+ any_display_options = 0
720
+ is_display_option = set()
721
+ for option in self.display_options:
722
+ is_display_option.add(option[0])
723
+
724
+ for opt, val in option_order:
725
+ if val and opt in is_display_option:
726
+ opt = translate_longopt(opt)
727
+ value = getattr(self.metadata, "get_" + opt)()
728
+ if opt in ('keywords', 'platforms'):
729
+ print(','.join(value))
730
+ elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
731
+ print('\n'.join(value))
732
+ else:
733
+ print(value)
734
+ any_display_options = 1
735
+
736
+ return any_display_options
737
+
738
+ def print_command_list(self, commands, header, max_length) -> None:
739
+ """Print a subset of the list of all commands -- used by
740
+ 'print_commands()'.
741
+ """
742
+ print(header + ":")
743
+
744
+ for cmd in commands:
745
+ klass = self.cmdclass.get(cmd)
746
+ if not klass:
747
+ klass = self.get_command_class(cmd)
748
+ try:
749
+ description = klass.description
750
+ except AttributeError:
751
+ description = "(no description available)"
752
+
753
+ print(f" {cmd:<{max_length}} {description}")
754
+
755
+ def print_commands(self) -> None:
756
+ """Print out a help message listing all available commands with a
757
+ description of each. The list is divided into "standard commands"
758
+ (listed in distutils.command.__all__) and "extra commands"
759
+ (mentioned in self.cmdclass, but not a standard command). The
760
+ descriptions come from the command class attribute
761
+ 'description'.
762
+ """
763
+ import distutils.command
764
+
765
+ std_commands = distutils.command.__all__
766
+ is_std = set(std_commands)
767
+
768
+ extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
769
+
770
+ max_length = 0
771
+ for cmd in std_commands + extra_commands:
772
+ if len(cmd) > max_length:
773
+ max_length = len(cmd)
774
+
775
+ self.print_command_list(std_commands, "Standard commands", max_length)
776
+ if extra_commands:
777
+ print()
778
+ self.print_command_list(extra_commands, "Extra commands", max_length)
779
+
780
+ def get_command_list(self):
781
+ """Get a list of (command, description) tuples.
782
+ The list is divided into "standard commands" (listed in
783
+ distutils.command.__all__) and "extra commands" (mentioned in
784
+ self.cmdclass, but not a standard command). The descriptions come
785
+ from the command class attribute 'description'.
786
+ """
787
+ # Currently this is only used on Mac OS, for the Mac-only GUI
788
+ # Distutils interface (by Jack Jansen)
789
+ import distutils.command
790
+
791
+ std_commands = distutils.command.__all__
792
+ is_std = set(std_commands)
793
+
794
+ extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
795
+
796
+ rv = []
797
+ for cmd in std_commands + extra_commands:
798
+ klass = self.cmdclass.get(cmd)
799
+ if not klass:
800
+ klass = self.get_command_class(cmd)
801
+ try:
802
+ description = klass.description
803
+ except AttributeError:
804
+ description = "(no description available)"
805
+ rv.append((cmd, description))
806
+ return rv
807
+
808
+ # -- Command class/object methods ----------------------------------
809
+
810
+ def get_command_packages(self):
811
+ """Return a list of packages from which commands are loaded."""
812
+ pkgs = self.command_packages
813
+ if not isinstance(pkgs, list):
814
+ if pkgs is None:
815
+ pkgs = ''
816
+ pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
817
+ if "distutils.command" not in pkgs:
818
+ pkgs.insert(0, "distutils.command")
819
+ self.command_packages = pkgs
820
+ return pkgs
821
+
822
+ def get_command_class(self, command: str) -> type[Command]:
823
+ """Return the class that implements the Distutils command named by
824
+ 'command'. First we check the 'cmdclass' dictionary; if the
825
+ command is mentioned there, we fetch the class object from the
826
+ dictionary and return it. Otherwise we load the command module
827
+ ("distutils.command." + command) and fetch the command class from
828
+ the module. The loaded class is also stored in 'cmdclass'
829
+ to speed future calls to 'get_command_class()'.
830
+
831
+ Raises DistutilsModuleError if the expected module could not be
832
+ found, or if that module does not define the expected class.
833
+ """
834
+ klass = self.cmdclass.get(command)
835
+ if klass:
836
+ return klass
837
+
838
+ for pkgname in self.get_command_packages():
839
+ module_name = f"{pkgname}.{command}"
840
+ klass_name = command
841
+
842
+ try:
843
+ __import__(module_name)
844
+ module = sys.modules[module_name]
845
+ except ImportError:
846
+ continue
847
+
848
+ try:
849
+ klass = getattr(module, klass_name)
850
+ except AttributeError:
851
+ raise DistutilsModuleError(
852
+ f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')"
853
+ )
854
+
855
+ self.cmdclass[command] = klass
856
+ return klass
857
+
858
+ raise DistutilsModuleError(f"invalid command '{command}'")
859
+
860
+ @overload
861
+ def get_command_obj(
862
+ self, command: str, create: Literal[True] = True
863
+ ) -> Command: ...
864
+ @overload
865
+ def get_command_obj(
866
+ self, command: str, create: Literal[False]
867
+ ) -> Command | None: ...
868
+ def get_command_obj(self, command: str, create: bool = True) -> Command | None:
869
+ """Return the command object for 'command'. Normally this object
870
+ is cached on a previous call to 'get_command_obj()'; if no command
871
+ object for 'command' is in the cache, then we either create and
872
+ return it (if 'create' is true) or return None.
873
+ """
874
+ cmd_obj = self.command_obj.get(command)
875
+ if not cmd_obj and create:
876
+ if DEBUG:
877
+ self.announce(
878
+ "Distribution.get_command_obj(): "
879
+ f"creating '{command}' command object"
880
+ )
881
+
882
+ klass = self.get_command_class(command)
883
+ cmd_obj = self.command_obj[command] = klass(self)
884
+ self.have_run[command] = False
885
+
886
+ # Set any options that were supplied in config files
887
+ # or on the command line. (NB. support for error
888
+ # reporting is lame here: any errors aren't reported
889
+ # until 'finalize_options()' is called, which means
890
+ # we won't report the source of the error.)
891
+ options = self.command_options.get(command)
892
+ if options:
893
+ self._set_command_options(cmd_obj, options)
894
+
895
+ return cmd_obj
896
+
897
+ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
898
+ """Set the options for 'command_obj' from 'option_dict'. Basically
899
+ this means copying elements of a dictionary ('option_dict') to
900
+ attributes of an instance ('command').
901
+
902
+ 'command_obj' must be a Command instance. If 'option_dict' is not
903
+ supplied, uses the standard option dictionary for this command
904
+ (from 'self.command_options').
905
+ """
906
+ command_name = command_obj.get_command_name()
907
+ if option_dict is None:
908
+ option_dict = self.get_option_dict(command_name)
909
+
910
+ if DEBUG:
911
+ self.announce(f" setting options for '{command_name}' command:")
912
+ for option, (source, value) in option_dict.items():
913
+ if DEBUG:
914
+ self.announce(f" {option} = {value} (from {source})")
915
+ try:
916
+ bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
917
+ except AttributeError:
918
+ bool_opts = []
919
+ try:
920
+ neg_opt = command_obj.negative_opt
921
+ except AttributeError:
922
+ neg_opt = {}
923
+
924
+ try:
925
+ is_string = isinstance(value, str)
926
+ if option in neg_opt and is_string:
927
+ setattr(command_obj, neg_opt[option], not strtobool(value))
928
+ elif option in bool_opts and is_string:
929
+ setattr(command_obj, option, strtobool(value))
930
+ elif hasattr(command_obj, option):
931
+ setattr(command_obj, option, value)
932
+ else:
933
+ raise DistutilsOptionError(
934
+ f"error in {source}: command '{command_name}' has no such option '{option}'"
935
+ )
936
+ except ValueError as msg:
937
+ raise DistutilsOptionError(msg)
938
+
939
+ @overload
940
+ def reinitialize_command(
941
+ self, command: str, reinit_subcommands: bool = False
942
+ ) -> Command: ...
943
+ @overload
944
+ def reinitialize_command(
945
+ self, command: _CommandT, reinit_subcommands: bool = False
946
+ ) -> _CommandT: ...
947
+ def reinitialize_command(
948
+ self, command: str | Command, reinit_subcommands=False
949
+ ) -> Command:
950
+ """Reinitializes a command to the state it was in when first
951
+ returned by 'get_command_obj()': ie., initialized but not yet
952
+ finalized. This provides the opportunity to sneak option
953
+ values in programmatically, overriding or supplementing
954
+ user-supplied values from the config files and command line.
955
+ You'll have to re-finalize the command object (by calling
956
+ 'finalize_options()' or 'ensure_finalized()') before using it for
957
+ real.
958
+
959
+ 'command' should be a command name (string) or command object. If
960
+ 'reinit_subcommands' is true, also reinitializes the command's
961
+ sub-commands, as declared by the 'sub_commands' class attribute (if
962
+ it has one). See the "install" command for an example. Only
963
+ reinitializes the sub-commands that actually matter, ie. those
964
+ whose test predicates return true.
965
+
966
+ Returns the reinitialized command object.
967
+ """
968
+ from distutils.cmd import Command
969
+
970
+ if not isinstance(command, Command):
971
+ command_name = command
972
+ command = self.get_command_obj(command_name)
973
+ else:
974
+ command_name = command.get_command_name()
975
+
976
+ if not command.finalized:
977
+ return command
978
+ command.initialize_options()
979
+ command.finalized = False
980
+ self.have_run[command_name] = False
981
+ self._set_command_options(command)
982
+
983
+ if reinit_subcommands:
984
+ for sub in command.get_sub_commands():
985
+ self.reinitialize_command(sub, reinit_subcommands)
986
+
987
+ return command
988
+
989
+ # -- Methods that operate on the Distribution ----------------------
990
+
991
+ def announce(self, msg, level: int = logging.INFO) -> None:
992
+ log.log(level, msg)
993
+
994
+ def run_commands(self) -> None:
995
+ """Run each command that was seen on the setup script command line.
996
+ Uses the list of commands found and cache of command objects
997
+ created by 'get_command_obj()'.
998
+ """
999
+ for cmd in self.commands:
1000
+ self.run_command(cmd)
1001
+
1002
+ # -- Methods that operate on its Commands --------------------------
1003
+
1004
+ def run_command(self, command: str) -> None:
1005
+ """Do whatever it takes to run a command (including nothing at all,
1006
+ if the command has already been run). Specifically: if we have
1007
+ already created and run the command named by 'command', return
1008
+ silently without doing anything. If the command named by 'command'
1009
+ doesn't even have a command object yet, create one. Then invoke
1010
+ 'run()' on that command object (or an existing one).
1011
+ """
1012
+ # Already been here, done that? then return silently.
1013
+ if self.have_run.get(command):
1014
+ return
1015
+
1016
+ log.info("running %s", command)
1017
+ cmd_obj = self.get_command_obj(command)
1018
+ cmd_obj.ensure_finalized()
1019
+ cmd_obj.run()
1020
+ self.have_run[command] = True
1021
+
1022
+ # -- Distribution query methods ------------------------------------
1023
+
1024
+ def has_pure_modules(self) -> bool:
1025
+ return len(self.packages or self.py_modules or []) > 0
1026
+
1027
+ def has_ext_modules(self) -> bool:
1028
+ return self.ext_modules and len(self.ext_modules) > 0
1029
+
1030
+ def has_c_libraries(self) -> bool:
1031
+ return self.libraries and len(self.libraries) > 0
1032
+
1033
+ def has_modules(self) -> bool:
1034
+ return self.has_pure_modules() or self.has_ext_modules()
1035
+
1036
+ def has_headers(self) -> bool:
1037
+ return self.headers and len(self.headers) > 0
1038
+
1039
+ def has_scripts(self) -> bool:
1040
+ return self.scripts and len(self.scripts) > 0
1041
+
1042
+ def has_data_files(self) -> bool:
1043
+ return self.data_files and len(self.data_files) > 0
1044
+
1045
+ def is_pure(self) -> bool:
1046
+ return (
1047
+ self.has_pure_modules()
1048
+ and not self.has_ext_modules()
1049
+ and not self.has_c_libraries()
1050
+ )
1051
+
1052
+ # -- Metadata query methods ----------------------------------------
1053
+
1054
+ # If you're looking for 'get_name()', 'get_version()', and so forth,
1055
+ # they are defined in a sneaky way: the constructor binds self.get_XXX
1056
+ # to self.metadata.get_XXX. The actual code is in the
1057
+ # DistributionMetadata class, below.
1058
+ if TYPE_CHECKING:
1059
+ # Unfortunately this means we need to specify them manually or not expose statically
1060
+ def _(self) -> None:
1061
+ self.get_name = self.metadata.get_name
1062
+ self.get_version = self.metadata.get_version
1063
+ self.get_fullname = self.metadata.get_fullname
1064
+ self.get_author = self.metadata.get_author
1065
+ self.get_author_email = self.metadata.get_author_email
1066
+ self.get_maintainer = self.metadata.get_maintainer
1067
+ self.get_maintainer_email = self.metadata.get_maintainer_email
1068
+ self.get_contact = self.metadata.get_contact
1069
+ self.get_contact_email = self.metadata.get_contact_email
1070
+ self.get_url = self.metadata.get_url
1071
+ self.get_license = self.metadata.get_license
1072
+ self.get_licence = self.metadata.get_licence
1073
+ self.get_description = self.metadata.get_description
1074
+ self.get_long_description = self.metadata.get_long_description
1075
+ self.get_keywords = self.metadata.get_keywords
1076
+ self.get_platforms = self.metadata.get_platforms
1077
+ self.get_classifiers = self.metadata.get_classifiers
1078
+ self.get_download_url = self.metadata.get_download_url
1079
+ self.get_requires = self.metadata.get_requires
1080
+ self.get_provides = self.metadata.get_provides
1081
+ self.get_obsoletes = self.metadata.get_obsoletes
1082
+
1083
+ # Default attributes generated in __init__ from self.display_option_names
1084
+ help_commands: bool
1085
+ name: str | Literal[False]
1086
+ version: str | Literal[False]
1087
+ fullname: str | Literal[False]
1088
+ author: str | Literal[False]
1089
+ author_email: str | Literal[False]
1090
+ maintainer: str | Literal[False]
1091
+ maintainer_email: str | Literal[False]
1092
+ contact: str | Literal[False]
1093
+ contact_email: str | Literal[False]
1094
+ url: str | Literal[False]
1095
+ license: str | Literal[False]
1096
+ licence: str | Literal[False]
1097
+ description: str | Literal[False]
1098
+ long_description: str | Literal[False]
1099
+ platforms: str | list[str] | Literal[False]
1100
+ classifiers: str | list[str] | Literal[False]
1101
+ keywords: str | list[str] | Literal[False]
1102
+ provides: list[str] | Literal[False]
1103
+ requires: list[str] | Literal[False]
1104
+ obsoletes: list[str] | Literal[False]
1105
+
1106
+
1107
+ class DistributionMetadata:
1108
+ """Dummy class to hold the distribution meta-data: name, version,
1109
+ author, and so forth.
1110
+ """
1111
+
1112
+ _METHOD_BASENAMES = (
1113
+ "name",
1114
+ "version",
1115
+ "author",
1116
+ "author_email",
1117
+ "maintainer",
1118
+ "maintainer_email",
1119
+ "url",
1120
+ "license",
1121
+ "description",
1122
+ "long_description",
1123
+ "keywords",
1124
+ "platforms",
1125
+ "fullname",
1126
+ "contact",
1127
+ "contact_email",
1128
+ "classifiers",
1129
+ "download_url",
1130
+ # PEP 314
1131
+ "provides",
1132
+ "requires",
1133
+ "obsoletes",
1134
+ )
1135
+
1136
+ def __init__(
1137
+ self, path: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None
1138
+ ) -> None:
1139
+ if path is not None:
1140
+ self.read_pkg_file(open(path))
1141
+ else:
1142
+ self.name: str | None = None
1143
+ self.version: str | None = None
1144
+ self.author: str | None = None
1145
+ self.author_email: str | None = None
1146
+ self.maintainer: str | None = None
1147
+ self.maintainer_email: str | None = None
1148
+ self.url: str | None = None
1149
+ self.license: str | None = None
1150
+ self.description: str | None = None
1151
+ self.long_description: str | None = None
1152
+ self.keywords: str | list[str] | None = None
1153
+ self.platforms: str | list[str] | None = None
1154
+ self.classifiers: str | list[str] | None = None
1155
+ self.download_url: str | None = None
1156
+ # PEP 314
1157
+ self.provides: str | list[str] | None = None
1158
+ self.requires: str | list[str] | None = None
1159
+ self.obsoletes: str | list[str] | None = None
1160
+
1161
+ def read_pkg_file(self, file: IO[str]) -> None:
1162
+ """Reads the metadata values from a file object."""
1163
+ msg = message_from_file(file)
1164
+
1165
+ def _read_field(name: str) -> str | None:
1166
+ value = msg[name]
1167
+ if value and value != "UNKNOWN":
1168
+ return value
1169
+ return None
1170
+
1171
+ def _read_list(name):
1172
+ values = msg.get_all(name, None)
1173
+ if values == []:
1174
+ return None
1175
+ return values
1176
+
1177
+ metadata_version = msg['metadata-version']
1178
+ self.name = _read_field('name')
1179
+ self.version = _read_field('version')
1180
+ self.description = _read_field('summary')
1181
+ # we are filling author only.
1182
+ self.author = _read_field('author')
1183
+ self.maintainer = None
1184
+ self.author_email = _read_field('author-email')
1185
+ self.maintainer_email = None
1186
+ self.url = _read_field('home-page')
1187
+ self.license = _read_field('license')
1188
+
1189
+ if 'download-url' in msg:
1190
+ self.download_url = _read_field('download-url')
1191
+ else:
1192
+ self.download_url = None
1193
+
1194
+ self.long_description = _read_field('description')
1195
+ self.description = _read_field('summary')
1196
+
1197
+ if 'keywords' in msg:
1198
+ self.keywords = _read_field('keywords').split(',')
1199
+
1200
+ self.platforms = _read_list('platform')
1201
+ self.classifiers = _read_list('classifier')
1202
+
1203
+ # PEP 314 - these fields only exist in 1.1
1204
+ if metadata_version == '1.1':
1205
+ self.requires = _read_list('requires')
1206
+ self.provides = _read_list('provides')
1207
+ self.obsoletes = _read_list('obsoletes')
1208
+ else:
1209
+ self.requires = None
1210
+ self.provides = None
1211
+ self.obsoletes = None
1212
+
1213
+ def write_pkg_info(self, base_dir: str | os.PathLike[str]) -> None:
1214
+ """Write the PKG-INFO file into the release tree."""
1215
+ with open(
1216
+ os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
1217
+ ) as pkg_info:
1218
+ self.write_pkg_file(pkg_info)
1219
+
1220
+ def write_pkg_file(self, file: SupportsWrite[str]) -> None:
1221
+ """Write the PKG-INFO format data to a file object."""
1222
+ version = '1.0'
1223
+ if (
1224
+ self.provides
1225
+ or self.requires
1226
+ or self.obsoletes
1227
+ or self.classifiers
1228
+ or self.download_url
1229
+ ):
1230
+ version = '1.1'
1231
+
1232
+ # required fields
1233
+ file.write(f'Metadata-Version: {version}\n')
1234
+ file.write(f'Name: {self.get_name()}\n')
1235
+ file.write(f'Version: {self.get_version()}\n')
1236
+
1237
+ def maybe_write(header, val):
1238
+ if val:
1239
+ file.write(f"{header}: {val}\n")
1240
+
1241
+ # optional fields
1242
+ maybe_write("Summary", self.get_description())
1243
+ maybe_write("Home-page", self.get_url())
1244
+ maybe_write("Author", self.get_contact())
1245
+ maybe_write("Author-email", self.get_contact_email())
1246
+ maybe_write("License", self.get_license())
1247
+ maybe_write("Download-URL", self.download_url)
1248
+ maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
1249
+ maybe_write("Keywords", ",".join(self.get_keywords()))
1250
+
1251
+ self._write_list(file, 'Platform', self.get_platforms())
1252
+ self._write_list(file, 'Classifier', self.get_classifiers())
1253
+
1254
+ # PEP 314
1255
+ self._write_list(file, 'Requires', self.get_requires())
1256
+ self._write_list(file, 'Provides', self.get_provides())
1257
+ self._write_list(file, 'Obsoletes', self.get_obsoletes())
1258
+
1259
+ def _write_list(self, file, name, values):
1260
+ values = values or []
1261
+ for value in values:
1262
+ file.write(f'{name}: {value}\n')
1263
+
1264
+ # -- Metadata query methods ----------------------------------------
1265
+
1266
+ def get_name(self) -> str:
1267
+ return self.name or "UNKNOWN"
1268
+
1269
+ def get_version(self) -> str:
1270
+ return self.version or "0.0.0"
1271
+
1272
+ def get_fullname(self) -> str:
1273
+ return self._fullname(self.get_name(), self.get_version())
1274
+
1275
+ @staticmethod
1276
+ def _fullname(name: str, version: str) -> str:
1277
+ """
1278
+ >>> DistributionMetadata._fullname('setup.tools', '1.0-2')
1279
+ 'setup_tools-1.0.post2'
1280
+ >>> DistributionMetadata._fullname('setup-tools', '1.2post2')
1281
+ 'setup_tools-1.2.post2'
1282
+ >>> DistributionMetadata._fullname('setup-tools', '1.0-r2')
1283
+ 'setup_tools-1.0.post2'
1284
+ >>> DistributionMetadata._fullname('setup.tools', '1.0.post')
1285
+ 'setup_tools-1.0.post0'
1286
+ >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1')
1287
+ 'setup_tools-1.0+ubuntu.1'
1288
+ """
1289
+ return "{}-{}".format(
1290
+ canonicalize_name(name).replace('-', '_'),
1291
+ canonicalize_version(version, strip_trailing_zero=False),
1292
+ )
1293
+
1294
+ def get_author(self) -> str | None:
1295
+ return self.author
1296
+
1297
+ def get_author_email(self) -> str | None:
1298
+ return self.author_email
1299
+
1300
+ def get_maintainer(self) -> str | None:
1301
+ return self.maintainer
1302
+
1303
+ def get_maintainer_email(self) -> str | None:
1304
+ return self.maintainer_email
1305
+
1306
+ def get_contact(self) -> str | None:
1307
+ return self.maintainer or self.author
1308
+
1309
+ def get_contact_email(self) -> str | None:
1310
+ return self.maintainer_email or self.author_email
1311
+
1312
+ def get_url(self) -> str | None:
1313
+ return self.url
1314
+
1315
+ def get_license(self) -> str | None:
1316
+ return self.license
1317
+
1318
+ get_licence = get_license
1319
+
1320
+ def get_description(self) -> str | None:
1321
+ return self.description
1322
+
1323
+ def get_long_description(self) -> str | None:
1324
+ return self.long_description
1325
+
1326
+ def get_keywords(self) -> str | list[str]:
1327
+ return self.keywords or []
1328
+
1329
+ def set_keywords(self, value: str | Iterable[str]) -> None:
1330
+ self.keywords = _ensure_list(value, 'keywords')
1331
+
1332
+ def get_platforms(self) -> str | list[str] | None:
1333
+ return self.platforms
1334
+
1335
+ def set_platforms(self, value: str | Iterable[str]) -> None:
1336
+ self.platforms = _ensure_list(value, 'platforms')
1337
+
1338
+ def get_classifiers(self) -> str | list[str]:
1339
+ return self.classifiers or []
1340
+
1341
+ def set_classifiers(self, value: str | Iterable[str]) -> None:
1342
+ self.classifiers = _ensure_list(value, 'classifiers')
1343
+
1344
+ def get_download_url(self) -> str | None:
1345
+ return self.download_url
1346
+
1347
+ # PEP 314
1348
+ def get_requires(self) -> str | list[str]:
1349
+ return self.requires or []
1350
+
1351
+ def set_requires(self, value: Iterable[str]) -> None:
1352
+ import distutils.versionpredicate
1353
+
1354
+ for v in value:
1355
+ distutils.versionpredicate.VersionPredicate(v)
1356
+ self.requires = list(value)
1357
+
1358
+ def get_provides(self) -> str | list[str]:
1359
+ return self.provides or []
1360
+
1361
+ def set_provides(self, value: Iterable[str]) -> None:
1362
+ value = [v.strip() for v in value]
1363
+ for v in value:
1364
+ import distutils.versionpredicate
1365
+
1366
+ distutils.versionpredicate.split_provision(v)
1367
+ self.provides = value
1368
+
1369
+ def get_obsoletes(self) -> str | list[str]:
1370
+ return self.obsoletes or []
1371
+
1372
+ def set_obsoletes(self, value: Iterable[str]) -> None:
1373
+ import distutils.versionpredicate
1374
+
1375
+ for v in value:
1376
+ distutils.versionpredicate.VersionPredicate(v)
1377
+ self.obsoletes = list(value)
1378
+
1379
+
1380
+ def fix_help_options(options):
1381
+ """Convert a 4-tuple 'help_options' list as found in various command
1382
+ classes to the 3-tuple form required by FancyGetopt.
1383
+ """
1384
+ return [opt[0:3] for opt in options]
python/Lib/site-packages/setuptools/_distutils/errors.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Exceptions used by the Distutils modules.
3
+
4
+ Distutils modules may raise these or standard exceptions,
5
+ including :exc:`SystemExit`.
6
+ """
7
+
8
+ # compiler exceptions aliased for compatibility
9
+ from .compilers.C.errors import CompileError as CompileError
10
+ from .compilers.C.errors import Error as _Error
11
+ from .compilers.C.errors import LibError as LibError
12
+ from .compilers.C.errors import LinkError as LinkError
13
+ from .compilers.C.errors import PreprocessError as PreprocessError
14
+ from .compilers.C.errors import UnknownFileType as _UnknownFileType
15
+
16
+ CCompilerError = _Error
17
+ UnknownFileError = _UnknownFileType
18
+
19
+
20
+ class DistutilsError(Exception):
21
+ """The root of all Distutils evil."""
22
+
23
+ pass
24
+
25
+
26
+ class DistutilsModuleError(DistutilsError):
27
+ """Unable to load an expected module, or to find an expected class
28
+ within some module (in particular, command modules and classes)."""
29
+
30
+ pass
31
+
32
+
33
+ class DistutilsClassError(DistutilsError):
34
+ """Some command class (or possibly distribution class, if anyone
35
+ feels a need to subclass Distribution) is found not to be holding
36
+ up its end of the bargain, ie. implementing some part of the
37
+ "command "interface."""
38
+
39
+ pass
40
+
41
+
42
+ class DistutilsGetoptError(DistutilsError):
43
+ """The option table provided to 'fancy_getopt()' is bogus."""
44
+
45
+ pass
46
+
47
+
48
+ class DistutilsArgError(DistutilsError):
49
+ """Raised by fancy_getopt in response to getopt.error -- ie. an
50
+ error in the command line usage."""
51
+
52
+ pass
53
+
54
+
55
+ class DistutilsFileError(DistutilsError):
56
+ """Any problems in the filesystem: expected file not found, etc.
57
+ Typically this is for problems that we detect before OSError
58
+ could be raised."""
59
+
60
+ pass
61
+
62
+
63
+ class DistutilsOptionError(DistutilsError):
64
+ """Syntactic/semantic errors in command options, such as use of
65
+ mutually conflicting options, or inconsistent options,
66
+ badly-spelled values, etc. No distinction is made between option
67
+ values originating in the setup script, the command line, config
68
+ files, or what-have-you -- but if we *know* something originated in
69
+ the setup script, we'll raise DistutilsSetupError instead."""
70
+
71
+ pass
72
+
73
+
74
+ class DistutilsSetupError(DistutilsError):
75
+ """For errors that can be definitely blamed on the setup script,
76
+ such as invalid keyword arguments to 'setup()'."""
77
+
78
+ pass
79
+
80
+
81
+ class DistutilsPlatformError(DistutilsError):
82
+ """We don't know how to do something on the current platform (but
83
+ we do know how to do it on some platform) -- eg. trying to compile
84
+ C files on a platform not supported by a CCompiler subclass."""
85
+
86
+ pass
87
+
88
+
89
+ class DistutilsExecError(DistutilsError):
90
+ """Any problems executing an external program (such as the C
91
+ compiler, when compiling C files)."""
92
+
93
+ pass
94
+
95
+
96
+ class DistutilsInternalError(DistutilsError):
97
+ """Internal inconsistencies or impossibilities (obviously, this
98
+ should never be seen if the code is working!)."""
99
+
100
+ pass
101
+
102
+
103
+ class DistutilsTemplateError(DistutilsError):
104
+ """Syntax error in a file list template."""
105
+
106
+
107
+ class DistutilsByteCompileError(DistutilsError):
108
+ """Byte compile error."""
python/Lib/site-packages/setuptools/_distutils/extension.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.extension
2
+
3
+ Provides the Extension class, used to describe C/C++ extension
4
+ modules in setup scripts."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import warnings
10
+ from collections.abc import Iterable
11
+
12
+ # This class is really only used by the "build_ext" command, so it might
13
+ # make sense to put it in distutils.command.build_ext. However, that
14
+ # module is already big enough, and I want to make this class a bit more
15
+ # complex to simplify some common cases ("foo" module in "foo.c") and do
16
+ # better error-checking ("foo.c" actually exists).
17
+ #
18
+ # Also, putting this in build_ext.py means every setup script would have to
19
+ # import that large-ish module (indirectly, through distutils.core) in
20
+ # order to do anything.
21
+
22
+
23
+ class Extension:
24
+ """Just a collection of attributes that describes an extension
25
+ module and everything needed to build it (hopefully in a portable
26
+ way, but there are hooks that let you be as unportable as you need).
27
+
28
+ Instance attributes:
29
+ name : string
30
+ the full name of the extension, including any packages -- ie.
31
+ *not* a filename or pathname, but Python dotted name
32
+ sources : Iterable[string | os.PathLike]
33
+ iterable of source filenames (except strings, which could be misinterpreted
34
+ as a single filename), relative to the distribution root (where the setup
35
+ script lives), in Unix form (slash-separated) for portability. Can be any
36
+ non-string iterable (list, tuple, set, etc.) containing strings or
37
+ PathLike objects. Source files may be C, C++, SWIG (.i), platform-specific
38
+ resource files, or whatever else is recognized by the "build_ext" command
39
+ as source for a Python extension.
40
+ include_dirs : [string]
41
+ list of directories to search for C/C++ header files (in Unix
42
+ form for portability)
43
+ define_macros : [(name : string, value : string|None)]
44
+ list of macros to define; each macro is defined using a 2-tuple,
45
+ where 'value' is either the string to define it to or None to
46
+ define it without a particular value (equivalent of "#define
47
+ FOO" in source or -DFOO on Unix C compiler command line)
48
+ undef_macros : [string]
49
+ list of macros to undefine explicitly
50
+ library_dirs : [string]
51
+ list of directories to search for C/C++ libraries at link time
52
+ libraries : [string]
53
+ list of library names (not filenames or paths) to link against
54
+ runtime_library_dirs : [string]
55
+ list of directories to search for C/C++ libraries at run time
56
+ (for shared extensions, this is when the extension is loaded)
57
+ extra_objects : [string]
58
+ list of extra files to link with (eg. object files not implied
59
+ by 'sources', static library that must be explicitly specified,
60
+ binary resource files, etc.)
61
+ extra_compile_args : [string]
62
+ any extra platform- and compiler-specific information to use
63
+ when compiling the source files in 'sources'. For platforms and
64
+ compilers where "command line" makes sense, this is typically a
65
+ list of command-line arguments, but for other platforms it could
66
+ be anything.
67
+ extra_link_args : [string]
68
+ any extra platform- and compiler-specific information to use
69
+ when linking object files together to create the extension (or
70
+ to create a new static Python interpreter). Similar
71
+ interpretation as for 'extra_compile_args'.
72
+ export_symbols : [string]
73
+ list of symbols to be exported from a shared extension. Not
74
+ used on all platforms, and not generally necessary for Python
75
+ extensions, which typically export exactly one symbol: "init" +
76
+ extension_name.
77
+ swig_opts : [string]
78
+ any extra options to pass to SWIG if a source file has the .i
79
+ extension.
80
+ depends : [string]
81
+ list of files that the extension depends on
82
+ language : string
83
+ extension language (i.e. "c", "c++", "objc"). Will be detected
84
+ from the source extensions if not provided.
85
+ optional : boolean
86
+ specifies that a build failure in the extension should not abort the
87
+ build process, but simply not install the failing extension.
88
+ """
89
+
90
+ # When adding arguments to this constructor, be sure to update
91
+ # setup_keywords in core.py.
92
+ def __init__(
93
+ self,
94
+ name: str,
95
+ sources: Iterable[str | os.PathLike[str]],
96
+ include_dirs: list[str] | None = None,
97
+ define_macros: list[tuple[str, str | None]] | None = None,
98
+ undef_macros: list[str] | None = None,
99
+ library_dirs: list[str] | None = None,
100
+ libraries: list[str] | None = None,
101
+ runtime_library_dirs: list[str] | None = None,
102
+ extra_objects: list[str] | None = None,
103
+ extra_compile_args: list[str] | None = None,
104
+ extra_link_args: list[str] | None = None,
105
+ export_symbols: list[str] | None = None,
106
+ swig_opts: list[str] | None = None,
107
+ depends: list[str] | None = None,
108
+ language: str | None = None,
109
+ optional: bool | None = None,
110
+ **kw, # To catch unknown keywords
111
+ ):
112
+ if not isinstance(name, str):
113
+ raise TypeError("'name' must be a string")
114
+
115
+ # handle the string case first; since strings are iterable, disallow them
116
+ if isinstance(sources, str):
117
+ raise TypeError(
118
+ "'sources' must be an iterable of strings or PathLike objects, not a string"
119
+ )
120
+
121
+ # now we check if it's iterable and contains valid types
122
+ try:
123
+ self.sources = list(map(os.fspath, sources))
124
+ except TypeError:
125
+ raise TypeError(
126
+ "'sources' must be an iterable of strings or PathLike objects"
127
+ )
128
+
129
+ self.name = name
130
+ self.include_dirs = include_dirs or []
131
+ self.define_macros = define_macros or []
132
+ self.undef_macros = undef_macros or []
133
+ self.library_dirs = library_dirs or []
134
+ self.libraries = libraries or []
135
+ self.runtime_library_dirs = runtime_library_dirs or []
136
+ self.extra_objects = extra_objects or []
137
+ self.extra_compile_args = extra_compile_args or []
138
+ self.extra_link_args = extra_link_args or []
139
+ self.export_symbols = export_symbols or []
140
+ self.swig_opts = swig_opts or []
141
+ self.depends = depends or []
142
+ self.language = language
143
+ self.optional = optional
144
+
145
+ # If there are unknown keyword options, warn about them
146
+ if len(kw) > 0:
147
+ options = [repr(option) for option in kw]
148
+ options = ', '.join(sorted(options))
149
+ msg = f"Unknown Extension options: {options}"
150
+ warnings.warn(msg)
151
+
152
+ def __repr__(self):
153
+ return f'<{self.__class__.__module__}.{self.__class__.__qualname__}({self.name!r}) at {id(self):#x}>'
154
+
155
+
156
+ def read_setup_file(filename): # noqa: C901
157
+ """Reads a Setup file and returns Extension instances."""
158
+ from distutils.sysconfig import _variable_rx, expand_makefile_vars, parse_makefile
159
+ from distutils.text_file import TextFile
160
+ from distutils.util import split_quoted
161
+
162
+ # First pass over the file to gather "VAR = VALUE" assignments.
163
+ vars = parse_makefile(filename)
164
+
165
+ # Second pass to gobble up the real content: lines of the form
166
+ # <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
167
+ file = TextFile(
168
+ filename,
169
+ strip_comments=True,
170
+ skip_blanks=True,
171
+ join_lines=True,
172
+ lstrip_ws=True,
173
+ rstrip_ws=True,
174
+ )
175
+ try:
176
+ extensions = []
177
+
178
+ while True:
179
+ line = file.readline()
180
+ if line is None: # eof
181
+ break
182
+ if _variable_rx.match(line): # VAR=VALUE, handled in first pass
183
+ continue
184
+
185
+ if line[0] == line[-1] == "*":
186
+ file.warn(f"'{line}' lines not handled yet")
187
+ continue
188
+
189
+ line = expand_makefile_vars(line, vars)
190
+ words = split_quoted(line)
191
+
192
+ # NB. this parses a slightly different syntax than the old
193
+ # makesetup script: here, there must be exactly one extension per
194
+ # line, and it must be the first word of the line. I have no idea
195
+ # why the old syntax supported multiple extensions per line, as
196
+ # they all wind up being the same.
197
+
198
+ module = words[0]
199
+ ext = Extension(module, [])
200
+ append_next_word = None
201
+
202
+ for word in words[1:]:
203
+ if append_next_word is not None:
204
+ append_next_word.append(word)
205
+ append_next_word = None
206
+ continue
207
+
208
+ suffix = os.path.splitext(word)[1]
209
+ switch = word[0:2]
210
+ value = word[2:]
211
+
212
+ if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
213
+ # hmm, should we do something about C vs. C++ sources?
214
+ # or leave it up to the CCompiler implementation to
215
+ # worry about?
216
+ ext.sources.append(word)
217
+ elif switch == "-I":
218
+ ext.include_dirs.append(value)
219
+ elif switch == "-D":
220
+ equals = value.find("=")
221
+ if equals == -1: # bare "-DFOO" -- no value
222
+ ext.define_macros.append((value, None))
223
+ else: # "-DFOO=blah"
224
+ ext.define_macros.append((value[0:equals], value[equals + 2 :]))
225
+ elif switch == "-U":
226
+ ext.undef_macros.append(value)
227
+ elif switch == "-C": # only here 'cause makesetup has it!
228
+ ext.extra_compile_args.append(word)
229
+ elif switch == "-l":
230
+ ext.libraries.append(value)
231
+ elif switch == "-L":
232
+ ext.library_dirs.append(value)
233
+ elif switch == "-R":
234
+ ext.runtime_library_dirs.append(value)
235
+ elif word == "-rpath":
236
+ append_next_word = ext.runtime_library_dirs
237
+ elif word == "-Xlinker":
238
+ append_next_word = ext.extra_link_args
239
+ elif word == "-Xcompiler":
240
+ append_next_word = ext.extra_compile_args
241
+ elif switch == "-u":
242
+ ext.extra_link_args.append(word)
243
+ if not value:
244
+ append_next_word = ext.extra_link_args
245
+ elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
246
+ # NB. a really faithful emulation of makesetup would
247
+ # append a .o file to extra_objects only if it
248
+ # had a slash in it; otherwise, it would s/.o/.c/
249
+ # and append it to sources. Hmmmm.
250
+ ext.extra_objects.append(word)
251
+ else:
252
+ file.warn(f"unrecognized argument '{word}'")
253
+
254
+ extensions.append(ext)
255
+ finally:
256
+ file.close()
257
+
258
+ return extensions
python/Lib/site-packages/setuptools/_distutils/fancy_getopt.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.fancy_getopt
2
+
3
+ Wrapper around the standard getopt module that provides the following
4
+ additional features:
5
+ * short and long options are tied together
6
+ * options have help strings, so fancy_getopt could potentially
7
+ create a complete usage summary
8
+ * options set attributes of a passed-in object
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import getopt
14
+ import re
15
+ import string
16
+ import sys
17
+ from collections.abc import Sequence
18
+ from typing import Any
19
+
20
+ from .errors import DistutilsArgError, DistutilsGetoptError
21
+
22
+ # Much like command_re in distutils.core, this is close to but not quite
23
+ # the same as a Python NAME -- except, in the spirit of most GNU
24
+ # utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)
25
+ # The similarities to NAME are again not a coincidence...
26
+ longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
27
+ longopt_re = re.compile(rf'^{longopt_pat}$')
28
+
29
+ # For recognizing "negative alias" options, eg. "quiet=!verbose"
30
+ neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")
31
+
32
+ # This is used to translate long options to legitimate Python identifiers
33
+ # (for use as attributes of some object).
34
+ longopt_xlate = str.maketrans('-', '_')
35
+
36
+
37
+ class FancyGetopt:
38
+ """Wrapper around the standard 'getopt()' module that provides some
39
+ handy extra functionality:
40
+ * short and long options are tied together
41
+ * options have help strings, and help text can be assembled
42
+ from them
43
+ * options set attributes of a passed-in object
44
+ * boolean options can have "negative aliases" -- eg. if
45
+ --quiet is the "negative alias" of --verbose, then "--quiet"
46
+ on the command line sets 'verbose' to false
47
+ """
48
+
49
+ def __init__(self, option_table=None):
50
+ # The option table is (currently) a list of tuples. The
51
+ # tuples may have 3 or four values:
52
+ # (long_option, short_option, help_string [, repeatable])
53
+ # if an option takes an argument, its long_option should have '='
54
+ # appended; short_option should just be a single character, no ':'
55
+ # in any case. If a long_option doesn't have a corresponding
56
+ # short_option, short_option should be None. All option tuples
57
+ # must have long options.
58
+ self.option_table = option_table
59
+
60
+ # 'option_index' maps long option names to entries in the option
61
+ # table (ie. those 3-tuples).
62
+ self.option_index = {}
63
+ if self.option_table:
64
+ self._build_index()
65
+
66
+ # 'alias' records (duh) alias options; {'foo': 'bar'} means
67
+ # --foo is an alias for --bar
68
+ self.alias = {}
69
+
70
+ # 'negative_alias' keeps track of options that are the boolean
71
+ # opposite of some other option
72
+ self.negative_alias = {}
73
+
74
+ # These keep track of the information in the option table. We
75
+ # don't actually populate these structures until we're ready to
76
+ # parse the command-line, since the 'option_table' passed in here
77
+ # isn't necessarily the final word.
78
+ self.short_opts = []
79
+ self.long_opts = []
80
+ self.short2long = {}
81
+ self.attr_name = {}
82
+ self.takes_arg = {}
83
+
84
+ # And 'option_order' is filled up in 'getopt()'; it records the
85
+ # original order of options (and their values) on the command-line,
86
+ # but expands short options, converts aliases, etc.
87
+ self.option_order = []
88
+
89
+ def _build_index(self):
90
+ self.option_index.clear()
91
+ for option in self.option_table:
92
+ self.option_index[option[0]] = option
93
+
94
+ def set_option_table(self, option_table):
95
+ self.option_table = option_table
96
+ self._build_index()
97
+
98
+ def add_option(self, long_option, short_option=None, help_string=None):
99
+ if long_option in self.option_index:
100
+ raise DistutilsGetoptError(
101
+ f"option conflict: already an option '{long_option}'"
102
+ )
103
+ else:
104
+ option = (long_option, short_option, help_string)
105
+ self.option_table.append(option)
106
+ self.option_index[long_option] = option
107
+
108
+ def has_option(self, long_option):
109
+ """Return true if the option table for this parser has an
110
+ option with long name 'long_option'."""
111
+ return long_option in self.option_index
112
+
113
+ def get_attr_name(self, long_option):
114
+ """Translate long option name 'long_option' to the form it
115
+ has as an attribute of some object: ie., translate hyphens
116
+ to underscores."""
117
+ return long_option.translate(longopt_xlate)
118
+
119
+ def _check_alias_dict(self, aliases, what):
120
+ assert isinstance(aliases, dict)
121
+ for alias, opt in aliases.items():
122
+ if alias not in self.option_index:
123
+ raise DistutilsGetoptError(
124
+ f"invalid {what} '{alias}': option '{alias}' not defined"
125
+ )
126
+ if opt not in self.option_index:
127
+ raise DistutilsGetoptError(
128
+ f"invalid {what} '{alias}': aliased option '{opt}' not defined"
129
+ )
130
+
131
+ def set_aliases(self, alias):
132
+ """Set the aliases for this option parser."""
133
+ self._check_alias_dict(alias, "alias")
134
+ self.alias = alias
135
+
136
+ def set_negative_aliases(self, negative_alias):
137
+ """Set the negative aliases for this option parser.
138
+ 'negative_alias' should be a dictionary mapping option names to
139
+ option names, both the key and value must already be defined
140
+ in the option table."""
141
+ self._check_alias_dict(negative_alias, "negative alias")
142
+ self.negative_alias = negative_alias
143
+
144
+ def _grok_option_table(self): # noqa: C901
145
+ """Populate the various data structures that keep tabs on the
146
+ option table. Called by 'getopt()' before it can do anything
147
+ worthwhile.
148
+ """
149
+ self.long_opts = []
150
+ self.short_opts = []
151
+ self.short2long.clear()
152
+ self.repeat = {}
153
+
154
+ for option in self.option_table:
155
+ if len(option) == 3:
156
+ long, short, help = option
157
+ repeat = 0
158
+ elif len(option) == 4:
159
+ long, short, help, repeat = option
160
+ else:
161
+ # the option table is part of the code, so simply
162
+ # assert that it is correct
163
+ raise ValueError(f"invalid option tuple: {option!r}")
164
+
165
+ # Type- and value-check the option names
166
+ if not isinstance(long, str) or len(long) < 2:
167
+ raise DistutilsGetoptError(
168
+ f"invalid long option '{long}': must be a string of length >= 2"
169
+ )
170
+
171
+ if not ((short is None) or (isinstance(short, str) and len(short) == 1)):
172
+ raise DistutilsGetoptError(
173
+ f"invalid short option '{short}': must a single character or None"
174
+ )
175
+
176
+ self.repeat[long] = repeat
177
+ self.long_opts.append(long)
178
+
179
+ if long[-1] == '=': # option takes an argument?
180
+ if short:
181
+ short = short + ':'
182
+ long = long[0:-1]
183
+ self.takes_arg[long] = True
184
+ else:
185
+ # Is option is a "negative alias" for some other option (eg.
186
+ # "quiet" == "!verbose")?
187
+ alias_to = self.negative_alias.get(long)
188
+ if alias_to is not None:
189
+ if self.takes_arg[alias_to]:
190
+ raise DistutilsGetoptError(
191
+ f"invalid negative alias '{long}': "
192
+ f"aliased option '{alias_to}' takes a value"
193
+ )
194
+
195
+ self.long_opts[-1] = long # XXX redundant?!
196
+ self.takes_arg[long] = False
197
+
198
+ # If this is an alias option, make sure its "takes arg" flag is
199
+ # the same as the option it's aliased to.
200
+ alias_to = self.alias.get(long)
201
+ if alias_to is not None:
202
+ if self.takes_arg[long] != self.takes_arg[alias_to]:
203
+ raise DistutilsGetoptError(
204
+ f"invalid alias '{long}': inconsistent with "
205
+ f"aliased option '{alias_to}' (one of them takes a value, "
206
+ "the other doesn't"
207
+ )
208
+
209
+ # Now enforce some bondage on the long option name, so we can
210
+ # later translate it to an attribute name on some object. Have
211
+ # to do this a bit late to make sure we've removed any trailing
212
+ # '='.
213
+ if not longopt_re.match(long):
214
+ raise DistutilsGetoptError(
215
+ f"invalid long option name '{long}' "
216
+ "(must be letters, numbers, hyphens only"
217
+ )
218
+
219
+ self.attr_name[long] = self.get_attr_name(long)
220
+ if short:
221
+ self.short_opts.append(short)
222
+ self.short2long[short[0]] = long
223
+
224
+ def getopt(self, args: Sequence[str] | None = None, object=None): # noqa: C901
225
+ """Parse command-line options in args. Store as attributes on object.
226
+
227
+ If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
228
+ 'object' is None or not supplied, creates a new OptionDummy
229
+ object, stores option values there, and returns a tuple (args,
230
+ object). If 'object' is supplied, it is modified in place and
231
+ 'getopt()' just returns 'args'; in both cases, the returned
232
+ 'args' is a modified copy of the passed-in 'args' list, which
233
+ is left untouched.
234
+ """
235
+ if args is None:
236
+ args = sys.argv[1:]
237
+ if object is None:
238
+ object = OptionDummy()
239
+ created_object = True
240
+ else:
241
+ created_object = False
242
+
243
+ self._grok_option_table()
244
+
245
+ short_opts = ' '.join(self.short_opts)
246
+ try:
247
+ opts, args = getopt.getopt(args, short_opts, self.long_opts)
248
+ except getopt.error as msg:
249
+ raise DistutilsArgError(msg)
250
+
251
+ for opt, val in opts:
252
+ if len(opt) == 2 and opt[0] == '-': # it's a short option
253
+ opt = self.short2long[opt[1]]
254
+ else:
255
+ assert len(opt) > 2 and opt[:2] == '--'
256
+ opt = opt[2:]
257
+
258
+ alias = self.alias.get(opt)
259
+ if alias:
260
+ opt = alias
261
+
262
+ if not self.takes_arg[opt]: # boolean option?
263
+ assert val == '', "boolean option can't have value"
264
+ alias = self.negative_alias.get(opt)
265
+ if alias:
266
+ opt = alias
267
+ val = 0
268
+ else:
269
+ val = 1
270
+
271
+ attr = self.attr_name[opt]
272
+ # The only repeating option at the moment is 'verbose'.
273
+ # It has a negative option -q quiet, which should set verbose = False.
274
+ if val and self.repeat.get(attr) is not None:
275
+ val = getattr(object, attr, 0) + 1
276
+ setattr(object, attr, val)
277
+ self.option_order.append((opt, val))
278
+
279
+ # for opts
280
+ if created_object:
281
+ return args, object
282
+ else:
283
+ return args
284
+
285
+ def get_option_order(self):
286
+ """Returns the list of (option, value) tuples processed by the
287
+ previous run of 'getopt()'. Raises RuntimeError if
288
+ 'getopt()' hasn't been called yet.
289
+ """
290
+ if self.option_order is None:
291
+ raise RuntimeError("'getopt()' hasn't been called yet")
292
+ else:
293
+ return self.option_order
294
+
295
+ def generate_help(self, header=None): # noqa: C901
296
+ """Generate help text (a list of strings, one per suggested line of
297
+ output) from the option table for this FancyGetopt object.
298
+ """
299
+ # Blithely assume the option table is good: probably wouldn't call
300
+ # 'generate_help()' unless you've already called 'getopt()'.
301
+
302
+ # First pass: determine maximum length of long option names
303
+ max_opt = 0
304
+ for option in self.option_table:
305
+ long = option[0]
306
+ short = option[1]
307
+ ell = len(long)
308
+ if long[-1] == '=':
309
+ ell = ell - 1
310
+ if short is not None:
311
+ ell = ell + 5 # " (-x)" where short == 'x'
312
+ if ell > max_opt:
313
+ max_opt = ell
314
+
315
+ opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
316
+
317
+ # Typical help block looks like this:
318
+ # --foo controls foonabulation
319
+ # Help block for longest option looks like this:
320
+ # --flimflam set the flim-flam level
321
+ # and with wrapped text:
322
+ # --flimflam set the flim-flam level (must be between
323
+ # 0 and 100, except on Tuesdays)
324
+ # Options with short names will have the short name shown (but
325
+ # it doesn't contribute to max_opt):
326
+ # --foo (-f) controls foonabulation
327
+ # If adding the short option would make the left column too wide,
328
+ # we push the explanation off to the next line
329
+ # --flimflam (-l)
330
+ # set the flim-flam level
331
+ # Important parameters:
332
+ # - 2 spaces before option block start lines
333
+ # - 2 dashes for each long option name
334
+ # - min. 2 spaces between option and explanation (gutter)
335
+ # - 5 characters (incl. space) for short option name
336
+
337
+ # Now generate lines of help text. (If 80 columns were good enough
338
+ # for Jesus, then 78 columns are good enough for me!)
339
+ line_width = 78
340
+ text_width = line_width - opt_width
341
+ big_indent = ' ' * opt_width
342
+ if header:
343
+ lines = [header]
344
+ else:
345
+ lines = ['Option summary:']
346
+
347
+ for option in self.option_table:
348
+ long, short, help = option[:3]
349
+ text = wrap_text(help, text_width)
350
+ if long[-1] == '=':
351
+ long = long[0:-1]
352
+
353
+ # Case 1: no short option at all (makes life easy)
354
+ if short is None:
355
+ if text:
356
+ lines.append(f" --{long:<{max_opt}} {text[0]}")
357
+ else:
358
+ lines.append(f" --{long:<{max_opt}}")
359
+
360
+ # Case 2: we have a short option, so we have to include it
361
+ # just after the long option
362
+ else:
363
+ opt_names = f"{long} (-{short})"
364
+ if text:
365
+ lines.append(f" --{opt_names:<{max_opt}} {text[0]}")
366
+ else:
367
+ lines.append(f" --{opt_names:<{max_opt}}")
368
+
369
+ for ell in text[1:]:
370
+ lines.append(big_indent + ell)
371
+ return lines
372
+
373
+ def print_help(self, header=None, file=None):
374
+ if file is None:
375
+ file = sys.stdout
376
+ for line in self.generate_help(header):
377
+ file.write(line + "\n")
378
+
379
+
380
+ def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None):
381
+ parser = FancyGetopt(options)
382
+ parser.set_negative_aliases(negative_opt)
383
+ return parser.getopt(args, object)
384
+
385
+
386
+ WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}
387
+
388
+
389
+ def wrap_text(text, width):
390
+ """wrap_text(text : string, width : int) -> [string]
391
+
392
+ Split 'text' into multiple lines of no more than 'width' characters
393
+ each, and return the list of strings that results.
394
+ """
395
+ if text is None:
396
+ return []
397
+ if len(text) <= width:
398
+ return [text]
399
+
400
+ text = text.expandtabs()
401
+ text = text.translate(WS_TRANS)
402
+ chunks = re.split(r'( +|-+)', text)
403
+ chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
404
+ lines = []
405
+
406
+ while chunks:
407
+ cur_line = [] # list of chunks (to-be-joined)
408
+ cur_len = 0 # length of current line
409
+
410
+ while chunks:
411
+ ell = len(chunks[0])
412
+ if cur_len + ell <= width: # can squeeze (at least) this chunk in
413
+ cur_line.append(chunks[0])
414
+ del chunks[0]
415
+ cur_len = cur_len + ell
416
+ else: # this line is full
417
+ # drop last chunk if all space
418
+ if cur_line and cur_line[-1][0] == ' ':
419
+ del cur_line[-1]
420
+ break
421
+
422
+ if chunks: # any chunks left to process?
423
+ # if the current line is still empty, then we had a single
424
+ # chunk that's too big too fit on a line -- so we break
425
+ # down and break it up at the line width
426
+ if cur_len == 0:
427
+ cur_line.append(chunks[0][0:width])
428
+ chunks[0] = chunks[0][width:]
429
+
430
+ # all-whitespace chunks at the end of a line can be discarded
431
+ # (and we know from the re.split above that if a chunk has
432
+ # *any* whitespace, it is *all* whitespace)
433
+ if chunks[0][0] == ' ':
434
+ del chunks[0]
435
+
436
+ # and store this line in the list-of-all-lines -- as a single
437
+ # string, of course!
438
+ lines.append(''.join(cur_line))
439
+
440
+ return lines
441
+
442
+
443
+ def translate_longopt(opt):
444
+ """Convert a long option name to a valid Python identifier by
445
+ changing "-" to "_".
446
+ """
447
+ return opt.translate(longopt_xlate)
448
+
449
+
450
+ class OptionDummy:
451
+ """Dummy class just used as a place to hold command-line option
452
+ values as instance attributes."""
453
+
454
+ def __init__(self, options: Sequence[Any] = []):
455
+ """Create a new OptionDummy instance. The attributes listed in
456
+ 'options' will be initialized to None."""
457
+ for opt in options:
458
+ setattr(self, opt, None)
459
+
460
+
461
+ if __name__ == "__main__":
462
+ text = """\
463
+ Tra-la-la, supercalifragilisticexpialidocious.
464
+ How *do* you spell that odd word, anyways?
465
+ (Someone ask Mary -- she'll know [or she'll
466
+ say, "How should I know?"].)"""
467
+
468
+ for w in (10, 20, 30, 40):
469
+ print(f"width: {w}")
470
+ print("\n".join(wrap_text(text, w)))
471
+ print()
python/Lib/site-packages/setuptools/_distutils/file_util.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.file_util
2
+
3
+ Utility functions for operating on single files.
4
+ """
5
+
6
+ import os
7
+
8
+ from ._log import log
9
+ from .errors import DistutilsFileError
10
+
11
+ # for generating verbose output in 'copy_file()'
12
+ _copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
13
+
14
+
15
+ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901
16
+ """Copy the file 'src' to 'dst'; both must be filenames. Any error
17
+ opening either file, reading from 'src', or writing to 'dst', raises
18
+ DistutilsFileError. Data is read/written in chunks of 'buffer_size'
19
+ bytes (default 16k). No attempt is made to handle anything apart from
20
+ regular files.
21
+ """
22
+ # Stolen from shutil module in the standard library, but with
23
+ # custom error-handling added.
24
+ fsrc = None
25
+ fdst = None
26
+ try:
27
+ try:
28
+ fsrc = open(src, 'rb')
29
+ except OSError as e:
30
+ raise DistutilsFileError(f"could not open '{src}': {e.strerror}")
31
+
32
+ if os.path.exists(dst):
33
+ try:
34
+ os.unlink(dst)
35
+ except OSError as e:
36
+ raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}")
37
+
38
+ try:
39
+ fdst = open(dst, 'wb')
40
+ except OSError as e:
41
+ raise DistutilsFileError(f"could not create '{dst}': {e.strerror}")
42
+
43
+ while True:
44
+ try:
45
+ buf = fsrc.read(buffer_size)
46
+ except OSError as e:
47
+ raise DistutilsFileError(f"could not read from '{src}': {e.strerror}")
48
+
49
+ if not buf:
50
+ break
51
+
52
+ try:
53
+ fdst.write(buf)
54
+ except OSError as e:
55
+ raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}")
56
+ finally:
57
+ if fdst:
58
+ fdst.close()
59
+ if fsrc:
60
+ fsrc.close()
61
+
62
+
63
+ def copy_file( # noqa: C901
64
+ src,
65
+ dst,
66
+ preserve_mode=True,
67
+ preserve_times=True,
68
+ update=False,
69
+ link=None,
70
+ verbose=True,
71
+ ):
72
+ """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
73
+ copied there with the same name; otherwise, it must be a filename. (If
74
+ the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
75
+ is true (the default), the file's mode (type and permission bits, or
76
+ whatever is analogous on the current platform) is copied. If
77
+ 'preserve_times' is true (the default), the last-modified and
78
+ last-access times are copied as well. If 'update' is true, 'src' will
79
+ only be copied if 'dst' does not exist, or if 'dst' does exist but is
80
+ older than 'src'.
81
+
82
+ 'link' allows you to make hard links (os.link) or symbolic links
83
+ (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
84
+ None (the default), files are copied. Don't set 'link' on systems that
85
+ don't support it: 'copy_file()' doesn't check if hard or symbolic
86
+ linking is available. If hardlink fails, falls back to
87
+ _copy_file_contents().
88
+
89
+ Under Mac OS, uses the native file copy function in macostools; on
90
+ other systems, uses '_copy_file_contents()' to copy file contents.
91
+
92
+ Return a tuple (dest_name, copied): 'dest_name' is the actual name of
93
+ the output file, and 'copied' is true if the file was copied.
94
+ """
95
+ # XXX if the destination file already exists, we clobber it if
96
+ # copying, but blow up if linking. Hmmm. And I don't know what
97
+ # macostools.copyfile() does. Should definitely be consistent, and
98
+ # should probably blow up if destination exists and we would be
99
+ # changing it (ie. it's not already a hard/soft link to src OR
100
+ # (not update) and (src newer than dst).
101
+
102
+ from distutils._modified import newer
103
+ from stat import S_IMODE, ST_ATIME, ST_MODE, ST_MTIME
104
+
105
+ if not os.path.isfile(src):
106
+ raise DistutilsFileError(
107
+ f"can't copy '{src}': doesn't exist or not a regular file"
108
+ )
109
+
110
+ if os.path.isdir(dst):
111
+ dir = dst
112
+ dst = os.path.join(dst, os.path.basename(src))
113
+ else:
114
+ dir = os.path.dirname(dst)
115
+
116
+ if update and not newer(src, dst):
117
+ if verbose >= 1:
118
+ log.debug("not copying %s (output up-to-date)", src)
119
+ return (dst, False)
120
+
121
+ try:
122
+ action = _copy_action[link]
123
+ except KeyError:
124
+ raise ValueError(f"invalid value '{link}' for 'link' argument")
125
+
126
+ if verbose >= 1:
127
+ if os.path.basename(dst) == os.path.basename(src):
128
+ log.info("%s %s -> %s", action, src, dir)
129
+ else:
130
+ log.info("%s %s -> %s", action, src, dst)
131
+
132
+ # If linking (hard or symbolic), use the appropriate system call
133
+ # (Unix only, of course, but that's the caller's responsibility)
134
+ if link == 'hard':
135
+ if not (os.path.exists(dst) and os.path.samefile(src, dst)):
136
+ try:
137
+ os.link(src, dst)
138
+ except OSError:
139
+ # If hard linking fails, fall back on copying file
140
+ # (some special filesystems don't support hard linking
141
+ # even under Unix, see issue #8876).
142
+ pass
143
+ else:
144
+ return (dst, True)
145
+ elif link == 'sym':
146
+ if not (os.path.exists(dst) and os.path.samefile(src, dst)):
147
+ os.symlink(src, dst)
148
+ return (dst, True)
149
+
150
+ # Otherwise (non-Mac, not linking), copy the file contents and
151
+ # (optionally) copy the times and mode.
152
+ _copy_file_contents(src, dst)
153
+ if preserve_mode or preserve_times:
154
+ st = os.stat(src)
155
+
156
+ # According to David Ascher <da@ski.org>, utime() should be done
157
+ # before chmod() (at least under NT).
158
+ if preserve_times:
159
+ os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
160
+ if preserve_mode:
161
+ os.chmod(dst, S_IMODE(st[ST_MODE]))
162
+
163
+ return (dst, True)
164
+
165
+
166
+ # XXX I suspect this is Unix-specific -- need porting help!
167
+ def move_file(src, dst, verbose=True): # noqa: C901
168
+ """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
169
+ be moved into it with the same name; otherwise, 'src' is just renamed
170
+ to 'dst'. Return the new full name of the file.
171
+
172
+ Handles cross-device moves on Unix using 'copy_file()'. What about
173
+ other systems???
174
+ """
175
+ import errno
176
+ from os.path import basename, dirname, exists, isdir, isfile
177
+
178
+ if verbose >= 1:
179
+ log.info("moving %s -> %s", src, dst)
180
+
181
+ if not isfile(src):
182
+ raise DistutilsFileError(f"can't move '{src}': not a regular file")
183
+
184
+ if isdir(dst):
185
+ dst = os.path.join(dst, basename(src))
186
+ elif exists(dst):
187
+ raise DistutilsFileError(
188
+ f"can't move '{src}': destination '{dst}' already exists"
189
+ )
190
+
191
+ if not isdir(dirname(dst)):
192
+ raise DistutilsFileError(
193
+ f"can't move '{src}': destination '{dst}' not a valid path"
194
+ )
195
+
196
+ copy_it = False
197
+ try:
198
+ os.rename(src, dst)
199
+ except OSError as e:
200
+ (num, msg) = e.args
201
+ if num == errno.EXDEV:
202
+ copy_it = True
203
+ else:
204
+ raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}")
205
+
206
+ if copy_it:
207
+ copy_file(src, dst, verbose=verbose)
208
+ try:
209
+ os.unlink(src)
210
+ except OSError as e:
211
+ (num, msg) = e.args
212
+ try:
213
+ os.unlink(dst)
214
+ except OSError:
215
+ pass
216
+ raise DistutilsFileError(
217
+ f"couldn't move '{src}' to '{dst}' by copy/delete: "
218
+ f"delete '{src}' failed: {msg}"
219
+ )
220
+ return dst
221
+
222
+
223
+ def write_file(filename, contents):
224
+ """Create a file with the specified name and write 'contents' (a
225
+ sequence of strings without line terminators) to it.
226
+ """
227
+ with open(filename, 'w', encoding='utf-8') as f:
228
+ f.writelines(line + '\n' for line in contents)
python/Lib/site-packages/setuptools/_distutils/filelist.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.filelist
2
+
3
+ Provides the FileList class, used for poking about the filesystem
4
+ and building lists of files.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import fnmatch
10
+ import functools
11
+ import os
12
+ import re
13
+ from collections.abc import Iterable
14
+ from typing import Literal, overload
15
+
16
+ from ._log import log
17
+ from .errors import DistutilsInternalError, DistutilsTemplateError
18
+ from .util import convert_path
19
+
20
+
21
+ class FileList:
22
+ """A list of files built by on exploring the filesystem and filtered by
23
+ applying various patterns to what we find there.
24
+
25
+ Instance attributes:
26
+ dir
27
+ directory from which files will be taken -- only used if
28
+ 'allfiles' not supplied to constructor
29
+ files
30
+ list of filenames currently being built/filtered/manipulated
31
+ allfiles
32
+ complete list of files under consideration (ie. without any
33
+ filtering applied)
34
+ """
35
+
36
+ def __init__(self, warn: object = None, debug_print: object = None) -> None:
37
+ # ignore argument to FileList, but keep them for backwards
38
+ # compatibility
39
+ self.allfiles: Iterable[str] | None = None
40
+ self.files: list[str] = []
41
+
42
+ def set_allfiles(self, allfiles: Iterable[str]) -> None:
43
+ self.allfiles = allfiles
44
+
45
+ def findall(self, dir: str | os.PathLike[str] = os.curdir) -> None:
46
+ self.allfiles = findall(dir)
47
+
48
+ def debug_print(self, msg: object) -> None:
49
+ """Print 'msg' to stdout if the global DEBUG (taken from the
50
+ DISTUTILS_DEBUG environment variable) flag is true.
51
+ """
52
+ from distutils.debug import DEBUG
53
+
54
+ if DEBUG:
55
+ print(msg)
56
+
57
+ # Collection methods
58
+
59
+ def append(self, item: str) -> None:
60
+ self.files.append(item)
61
+
62
+ def extend(self, items: Iterable[str]) -> None:
63
+ self.files.extend(items)
64
+
65
+ def sort(self) -> None:
66
+ # Not a strict lexical sort!
67
+ sortable_files = sorted(map(os.path.split, self.files))
68
+ self.files = []
69
+ for sort_tuple in sortable_files:
70
+ self.files.append(os.path.join(*sort_tuple))
71
+
72
+ # Other miscellaneous utility methods
73
+
74
+ def remove_duplicates(self) -> None:
75
+ # Assumes list has been sorted!
76
+ for i in range(len(self.files) - 1, 0, -1):
77
+ if self.files[i] == self.files[i - 1]:
78
+ del self.files[i]
79
+
80
+ # "File template" methods
81
+
82
+ def _parse_template_line(self, line):
83
+ words = line.split()
84
+ action = words[0]
85
+
86
+ patterns = dir = dir_pattern = None
87
+
88
+ if action in ('include', 'exclude', 'global-include', 'global-exclude'):
89
+ if len(words) < 2:
90
+ raise DistutilsTemplateError(
91
+ f"'{action}' expects <pattern1> <pattern2> ..."
92
+ )
93
+ patterns = [convert_path(w) for w in words[1:]]
94
+ elif action in ('recursive-include', 'recursive-exclude'):
95
+ if len(words) < 3:
96
+ raise DistutilsTemplateError(
97
+ f"'{action}' expects <dir> <pattern1> <pattern2> ..."
98
+ )
99
+ dir = convert_path(words[1])
100
+ patterns = [convert_path(w) for w in words[2:]]
101
+ elif action in ('graft', 'prune'):
102
+ if len(words) != 2:
103
+ raise DistutilsTemplateError(
104
+ f"'{action}' expects a single <dir_pattern>"
105
+ )
106
+ dir_pattern = convert_path(words[1])
107
+ else:
108
+ raise DistutilsTemplateError(f"unknown action '{action}'")
109
+
110
+ return (action, patterns, dir, dir_pattern)
111
+
112
+ def process_template_line(self, line: str) -> None: # noqa: C901
113
+ # Parse the line: split it up, make sure the right number of words
114
+ # is there, and return the relevant words. 'action' is always
115
+ # defined: it's the first word of the line. Which of the other
116
+ # three are defined depends on the action; it'll be either
117
+ # patterns, (dir and patterns), or (dir_pattern).
118
+ (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
119
+
120
+ # OK, now we know that the action is valid and we have the
121
+ # right number of words on the line for that action -- so we
122
+ # can proceed with minimal error-checking.
123
+ if action == 'include':
124
+ self.debug_print("include " + ' '.join(patterns))
125
+ for pattern in patterns:
126
+ if not self.include_pattern(pattern, anchor=True):
127
+ log.warning("warning: no files found matching '%s'", pattern)
128
+
129
+ elif action == 'exclude':
130
+ self.debug_print("exclude " + ' '.join(patterns))
131
+ for pattern in patterns:
132
+ if not self.exclude_pattern(pattern, anchor=True):
133
+ log.warning(
134
+ "warning: no previously-included files found matching '%s'",
135
+ pattern,
136
+ )
137
+
138
+ elif action == 'global-include':
139
+ self.debug_print("global-include " + ' '.join(patterns))
140
+ for pattern in patterns:
141
+ if not self.include_pattern(pattern, anchor=False):
142
+ log.warning(
143
+ (
144
+ "warning: no files found matching '%s' "
145
+ "anywhere in distribution"
146
+ ),
147
+ pattern,
148
+ )
149
+
150
+ elif action == 'global-exclude':
151
+ self.debug_print("global-exclude " + ' '.join(patterns))
152
+ for pattern in patterns:
153
+ if not self.exclude_pattern(pattern, anchor=False):
154
+ log.warning(
155
+ (
156
+ "warning: no previously-included files matching "
157
+ "'%s' found anywhere in distribution"
158
+ ),
159
+ pattern,
160
+ )
161
+
162
+ elif action == 'recursive-include':
163
+ self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns)))
164
+ for pattern in patterns:
165
+ if not self.include_pattern(pattern, prefix=dir):
166
+ msg = "warning: no files found matching '%s' under directory '%s'"
167
+ log.warning(msg, pattern, dir)
168
+
169
+ elif action == 'recursive-exclude':
170
+ self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns)))
171
+ for pattern in patterns:
172
+ if not self.exclude_pattern(pattern, prefix=dir):
173
+ log.warning(
174
+ (
175
+ "warning: no previously-included files matching "
176
+ "'%s' found under directory '%s'"
177
+ ),
178
+ pattern,
179
+ dir,
180
+ )
181
+
182
+ elif action == 'graft':
183
+ self.debug_print("graft " + dir_pattern)
184
+ if not self.include_pattern(None, prefix=dir_pattern):
185
+ log.warning("warning: no directories found matching '%s'", dir_pattern)
186
+
187
+ elif action == 'prune':
188
+ self.debug_print("prune " + dir_pattern)
189
+ if not self.exclude_pattern(None, prefix=dir_pattern):
190
+ log.warning(
191
+ ("no previously-included directories found matching '%s'"),
192
+ dir_pattern,
193
+ )
194
+ else:
195
+ raise DistutilsInternalError(
196
+ f"this cannot happen: invalid action '{action}'"
197
+ )
198
+
199
+ # Filtering/selection methods
200
+ @overload
201
+ def include_pattern(
202
+ self,
203
+ pattern: str,
204
+ anchor: bool = True,
205
+ prefix: str | None = None,
206
+ is_regex: Literal[False] = False,
207
+ ) -> bool: ...
208
+ @overload
209
+ def include_pattern(
210
+ self,
211
+ pattern: str | re.Pattern[str],
212
+ anchor: bool = True,
213
+ prefix: str | None = None,
214
+ *,
215
+ is_regex: Literal[True],
216
+ ) -> bool: ...
217
+ @overload
218
+ def include_pattern(
219
+ self,
220
+ pattern: str | re.Pattern[str],
221
+ anchor: bool,
222
+ prefix: str | None,
223
+ is_regex: Literal[True],
224
+ ) -> bool: ...
225
+ def include_pattern(
226
+ self,
227
+ pattern: str | re.Pattern,
228
+ anchor: bool = True,
229
+ prefix: str | None = None,
230
+ is_regex: bool = False,
231
+ ) -> bool:
232
+ """Select strings (presumably filenames) from 'self.files' that
233
+ match 'pattern', a Unix-style wildcard (glob) pattern. Patterns
234
+ are not quite the same as implemented by the 'fnmatch' module: '*'
235
+ and '?' match non-special characters, where "special" is platform-
236
+ dependent: slash on Unix; colon, slash, and backslash on
237
+ DOS/Windows; and colon on Mac OS.
238
+
239
+ If 'anchor' is true (the default), then the pattern match is more
240
+ stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
241
+ 'anchor' is false, both of these will match.
242
+
243
+ If 'prefix' is supplied, then only filenames starting with 'prefix'
244
+ (itself a pattern) and ending with 'pattern', with anything in between
245
+ them, will match. 'anchor' is ignored in this case.
246
+
247
+ If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
248
+ 'pattern' is assumed to be either a string containing a regex or a
249
+ regex object -- no translation is done, the regex is just compiled
250
+ and used as-is.
251
+
252
+ Selected strings will be added to self.files.
253
+
254
+ Return True if files are found, False otherwise.
255
+ """
256
+ # XXX docstring lying about what the special chars are?
257
+ files_found = False
258
+ pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
259
+ self.debug_print(f"include_pattern: applying regex r'{pattern_re.pattern}'")
260
+
261
+ # delayed loading of allfiles list
262
+ if self.allfiles is None:
263
+ self.findall()
264
+
265
+ for name in self.allfiles:
266
+ if pattern_re.search(name):
267
+ self.debug_print(" adding " + name)
268
+ self.files.append(name)
269
+ files_found = True
270
+ return files_found
271
+
272
+ @overload
273
+ def exclude_pattern(
274
+ self,
275
+ pattern: str,
276
+ anchor: bool = True,
277
+ prefix: str | None = None,
278
+ is_regex: Literal[False] = False,
279
+ ) -> bool: ...
280
+ @overload
281
+ def exclude_pattern(
282
+ self,
283
+ pattern: str | re.Pattern[str],
284
+ anchor: bool = True,
285
+ prefix: str | None = None,
286
+ *,
287
+ is_regex: Literal[True],
288
+ ) -> bool: ...
289
+ @overload
290
+ def exclude_pattern(
291
+ self,
292
+ pattern: str | re.Pattern[str],
293
+ anchor: bool,
294
+ prefix: str | None,
295
+ is_regex: Literal[True],
296
+ ) -> bool: ...
297
+ def exclude_pattern(
298
+ self,
299
+ pattern: str | re.Pattern,
300
+ anchor: bool = True,
301
+ prefix: str | None = None,
302
+ is_regex: bool = False,
303
+ ) -> bool:
304
+ """Remove strings (presumably filenames) from 'files' that match
305
+ 'pattern'. Other parameters are the same as for
306
+ 'include_pattern()', above.
307
+ The list 'self.files' is modified in place.
308
+ Return True if files are found, False otherwise.
309
+ """
310
+ files_found = False
311
+ pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
312
+ self.debug_print(f"exclude_pattern: applying regex r'{pattern_re.pattern}'")
313
+ for i in range(len(self.files) - 1, -1, -1):
314
+ if pattern_re.search(self.files[i]):
315
+ self.debug_print(" removing " + self.files[i])
316
+ del self.files[i]
317
+ files_found = True
318
+ return files_found
319
+
320
+
321
+ # Utility functions
322
+
323
+
324
+ def _find_all_simple(path):
325
+ """
326
+ Find all files under 'path'
327
+ """
328
+ all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))
329
+ results = (
330
+ os.path.join(base, file) for base, dirs, files in all_unique for file in files
331
+ )
332
+ return filter(os.path.isfile, results)
333
+
334
+
335
+ class _UniqueDirs(set):
336
+ """
337
+ Exclude previously-seen dirs from walk results,
338
+ avoiding infinite recursion.
339
+ Ref https://bugs.python.org/issue44497.
340
+ """
341
+
342
+ def __call__(self, walk_item):
343
+ """
344
+ Given an item from an os.walk result, determine
345
+ if the item represents a unique dir for this instance
346
+ and if not, prevent further traversal.
347
+ """
348
+ base, dirs, files = walk_item
349
+ stat = os.stat(base)
350
+ candidate = stat.st_dev, stat.st_ino
351
+ found = candidate in self
352
+ if found:
353
+ del dirs[:]
354
+ self.add(candidate)
355
+ return not found
356
+
357
+ @classmethod
358
+ def filter(cls, items):
359
+ return filter(cls(), items)
360
+
361
+
362
+ def findall(dir: str | os.PathLike[str] = os.curdir):
363
+ """
364
+ Find all files under 'dir' and return the list of full filenames.
365
+ Unless dir is '.', return full filenames with dir prepended.
366
+ """
367
+ files = _find_all_simple(dir)
368
+ if dir == os.curdir:
369
+ make_rel = functools.partial(os.path.relpath, start=dir)
370
+ files = map(make_rel, files)
371
+ return list(files)
372
+
373
+
374
+ def glob_to_re(pattern):
375
+ """Translate a shell-like glob pattern to a regular expression; return
376
+ a string containing the regex. Differs from 'fnmatch.translate()' in
377
+ that '*' does not match "special characters" (which are
378
+ platform-specific).
379
+ """
380
+ pattern_re = fnmatch.translate(pattern)
381
+
382
+ # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
383
+ # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
384
+ # and by extension they shouldn't match such "special characters" under
385
+ # any OS. So change all non-escaped dots in the RE to match any
386
+ # character except the special characters (currently: just os.sep).
387
+ sep = os.sep
388
+ if os.sep == '\\':
389
+ # we're using a regex to manipulate a regex, so we need
390
+ # to escape the backslash twice
391
+ sep = r'\\\\'
392
+ escaped = rf'\1[^{sep}]'
393
+ pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
394
+ return pattern_re
395
+
396
+
397
+ def translate_pattern(pattern, anchor=True, prefix=None, is_regex=False):
398
+ """Translate a shell-like wildcard pattern to a compiled regular
399
+ expression. Return the compiled regex. If 'is_regex' true,
400
+ then 'pattern' is directly compiled to a regex (if it's a string)
401
+ or just returned as-is (assumes it's a regex object).
402
+ """
403
+ if is_regex:
404
+ if isinstance(pattern, str):
405
+ return re.compile(pattern)
406
+ else:
407
+ return pattern
408
+
409
+ # ditch start and end characters
410
+ start, _, end = glob_to_re('_').partition('_')
411
+
412
+ if pattern:
413
+ pattern_re = glob_to_re(pattern)
414
+ assert pattern_re.startswith(start) and pattern_re.endswith(end)
415
+ else:
416
+ pattern_re = ''
417
+
418
+ if prefix is not None:
419
+ prefix_re = glob_to_re(prefix)
420
+ assert prefix_re.startswith(start) and prefix_re.endswith(end)
421
+ prefix_re = prefix_re[len(start) : len(prefix_re) - len(end)]
422
+ sep = os.sep
423
+ if os.sep == '\\':
424
+ sep = r'\\'
425
+ pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]
426
+ pattern_re = rf'{start}\A{prefix_re}{sep}.*{pattern_re}{end}'
427
+ else: # no prefix -- respect anchor flag
428
+ if anchor:
429
+ pattern_re = rf'{start}\A{pattern_re[len(start) :]}'
430
+
431
+ return re.compile(pattern_re)
python/Lib/site-packages/setuptools/_distutils/log.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A simple log mechanism styled after PEP 282.
3
+
4
+ Retained for compatibility and should not be used.
5
+ """
6
+
7
+ import logging
8
+ import warnings
9
+
10
+ from ._log import log as _global_log
11
+
12
+ DEBUG = logging.DEBUG
13
+ INFO = logging.INFO
14
+ WARN = logging.WARN
15
+ ERROR = logging.ERROR
16
+ FATAL = logging.FATAL
17
+
18
+ log = _global_log.log
19
+ debug = _global_log.debug
20
+ info = _global_log.info
21
+ warn = _global_log.warning
22
+ error = _global_log.error
23
+ fatal = _global_log.fatal
24
+
25
+
26
+ def set_threshold(level):
27
+ orig = _global_log.level
28
+ _global_log.setLevel(level)
29
+ return orig
30
+
31
+
32
+ def set_verbosity(v):
33
+ if v <= 0:
34
+ set_threshold(logging.WARN)
35
+ elif v == 1:
36
+ set_threshold(logging.INFO)
37
+ elif v >= 2:
38
+ set_threshold(logging.DEBUG)
39
+
40
+
41
+ class Log(logging.Logger):
42
+ """distutils.log.Log is deprecated, please use an alternative from `logging`."""
43
+
44
+ def __init__(self, threshold=WARN):
45
+ warnings.warn(Log.__doc__) # avoid DeprecationWarning to ensure warn is shown
46
+ super().__init__(__name__, level=threshold)
47
+
48
+ @property
49
+ def threshold(self):
50
+ return self.level
51
+
52
+ @threshold.setter
53
+ def threshold(self, level):
54
+ self.setLevel(level)
55
+
56
+ warn = logging.Logger.warning
python/Lib/site-packages/setuptools/_distutils/spawn.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.spawn
2
+
3
+ Provides the 'spawn()' function, a front-end to various platform-
4
+ specific functions for launching another program in a sub-process.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import platform
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import warnings
15
+ from collections.abc import Mapping, MutableSequence
16
+ from typing import TYPE_CHECKING, TypeVar, overload
17
+
18
+ from ._log import log
19
+ from .debug import DEBUG
20
+ from .errors import DistutilsExecError
21
+
22
+ if TYPE_CHECKING:
23
+ from subprocess import _ENV
24
+
25
+
26
+ _MappingT = TypeVar("_MappingT", bound=Mapping)
27
+
28
+
29
+ def _debug(cmd):
30
+ """
31
+ Render a subprocess command differently depending on DEBUG.
32
+ """
33
+ return cmd if DEBUG else cmd[0]
34
+
35
+
36
+ def _inject_macos_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None:
37
+ if platform.system() != 'Darwin':
38
+ return env
39
+
40
+ from .util import MACOSX_VERSION_VAR, get_macosx_target_ver
41
+
42
+ target_ver = get_macosx_target_ver()
43
+ update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {}
44
+ return {**_resolve(env), **update}
45
+
46
+
47
+ @overload
48
+ def _resolve(env: None) -> os._Environ[str]: ...
49
+ @overload
50
+ def _resolve(env: _MappingT) -> _MappingT: ...
51
+ def _resolve(env: _MappingT | None) -> _MappingT | os._Environ[str]:
52
+ return os.environ if env is None else env
53
+
54
+
55
+ def spawn(
56
+ cmd: MutableSequence[bytes | str | os.PathLike[str]],
57
+ search_path: bool = True,
58
+ verbose: bool = False,
59
+ env: _ENV | None = None,
60
+ ) -> None:
61
+ """Run another program, specified as a command list 'cmd', in a new process.
62
+
63
+ 'cmd' is just the argument list for the new process, ie.
64
+ cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
65
+ There is no way to run a program with a name different from that of its
66
+ executable.
67
+
68
+ If 'search_path' is true (the default), the system's executable
69
+ search path will be used to find the program; otherwise, cmd[0]
70
+ must be the exact path to the executable.
71
+
72
+ Raise DistutilsExecError if running the program fails in any way; just
73
+ return on success.
74
+ """
75
+ log.info(subprocess.list2cmdline(cmd))
76
+
77
+ if search_path:
78
+ executable = shutil.which(cmd[0])
79
+ if executable is not None:
80
+ cmd[0] = executable
81
+
82
+ try:
83
+ subprocess.check_call(cmd, env=_inject_macos_ver(env))
84
+ except OSError as exc:
85
+ raise DistutilsExecError(
86
+ f"command {_debug(cmd)!r} failed: {exc.args[-1]}"
87
+ ) from exc
88
+ except subprocess.CalledProcessError as err:
89
+ raise DistutilsExecError(
90
+ f"command {_debug(cmd)!r} failed with exit code {err.returncode}"
91
+ ) from err
92
+
93
+
94
+ def find_executable(executable: str, path: str | None = None) -> str | None:
95
+ """Tries to find 'executable' in the directories listed in 'path'.
96
+
97
+ A string listing directories separated by 'os.pathsep'; defaults to
98
+ os.environ['PATH']. Returns the complete filename or None if not found.
99
+ """
100
+ warnings.warn(
101
+ 'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2
102
+ )
103
+ _, ext = os.path.splitext(executable)
104
+ if (sys.platform == 'win32') and (ext != '.exe'):
105
+ executable = executable + '.exe'
106
+
107
+ if os.path.isfile(executable):
108
+ return executable
109
+
110
+ if path is None:
111
+ path = os.environ.get('PATH', None)
112
+ # bpo-35755: Don't fall through if PATH is the empty string
113
+ if path is None:
114
+ try:
115
+ path = os.confstr("CS_PATH")
116
+ except (AttributeError, ValueError):
117
+ # os.confstr() or CS_PATH is not available
118
+ path = os.defpath
119
+
120
+ # PATH='' doesn't match, whereas PATH=':' looks in the current directory
121
+ if not path:
122
+ return None
123
+
124
+ paths = path.split(os.pathsep)
125
+ for p in paths:
126
+ f = os.path.join(p, executable)
127
+ if os.path.isfile(f):
128
+ # the file exists, we have a shot at spawn working
129
+ return f
130
+ return None
python/Lib/site-packages/setuptools/_distutils/sysconfig.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provide access to Python's configuration information. The specific
2
+ configuration variables available depend heavily on the platform and
3
+ configuration. The values may be retrieved using
4
+ get_config_var(name), and the list of variables is available via
5
+ get_config_vars().keys(). Additional convenience functions are also
6
+ available.
7
+
8
+ Written by: Fred L. Drake, Jr.
9
+ Email: <fdrake@acm.org>
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import os
16
+ import pathlib
17
+ import re
18
+ import sys
19
+ import sysconfig
20
+ from typing import TYPE_CHECKING, Literal, overload
21
+
22
+ from jaraco.functools import pass_none
23
+
24
+ from .ccompiler import CCompiler
25
+ from .compat import py39
26
+ from .errors import DistutilsPlatformError
27
+ from .util import is_mingw
28
+
29
+ if TYPE_CHECKING:
30
+ from typing_extensions import deprecated
31
+ else:
32
+
33
+ def deprecated(message):
34
+ return lambda fn: fn
35
+
36
+
37
+ IS_PYPY = '__pypy__' in sys.builtin_module_names
38
+
39
+ # These are needed in a couple of spots, so just compute them once.
40
+ PREFIX = os.path.normpath(sys.prefix)
41
+ EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
42
+ BASE_PREFIX = os.path.normpath(sys.base_prefix)
43
+ BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
44
+
45
+ # Path to the base directory of the project. On Windows the binary may
46
+ # live in project/PCbuild/win32 or project/PCbuild/amd64.
47
+ # set for cross builds
48
+ if "_PYTHON_PROJECT_BASE" in os.environ:
49
+ project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
50
+ else:
51
+ if sys.executable:
52
+ project_base = os.path.dirname(os.path.abspath(sys.executable))
53
+ else:
54
+ # sys.executable can be empty if argv[0] has been changed and Python is
55
+ # unable to retrieve the real program name
56
+ project_base = os.getcwd()
57
+
58
+
59
+ def _is_python_source_dir(d):
60
+ """
61
+ Return True if the target directory appears to point to an
62
+ un-installed Python.
63
+ """
64
+ modules = pathlib.Path(d).joinpath('Modules')
65
+ return any(modules.joinpath(fn).is_file() for fn in ('Setup', 'Setup.local'))
66
+
67
+
68
+ _sys_home = getattr(sys, '_home', None)
69
+
70
+
71
+ def _is_parent(dir_a, dir_b):
72
+ """
73
+ Return True if a is a parent of b.
74
+ """
75
+ return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b))
76
+
77
+
78
+ if os.name == 'nt':
79
+
80
+ @pass_none
81
+ def _fix_pcbuild(d):
82
+ # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX.
83
+ prefixes = PREFIX, BASE_PREFIX
84
+ matched = (
85
+ prefix
86
+ for prefix in prefixes
87
+ if _is_parent(d, os.path.join(prefix, "PCbuild"))
88
+ )
89
+ return next(matched, d)
90
+
91
+ project_base = _fix_pcbuild(project_base)
92
+ _sys_home = _fix_pcbuild(_sys_home)
93
+
94
+
95
+ def _python_build():
96
+ if _sys_home:
97
+ return _is_python_source_dir(_sys_home)
98
+ return _is_python_source_dir(project_base)
99
+
100
+
101
+ python_build = _python_build()
102
+
103
+
104
+ # Calculate the build qualifier flags if they are defined. Adding the flags
105
+ # to the include and lib directories only makes sense for an installation, not
106
+ # an in-source build.
107
+ build_flags = ''
108
+ try:
109
+ if not python_build:
110
+ build_flags = sys.abiflags
111
+ except AttributeError:
112
+ # It's not a configure-based build, so the sys module doesn't have
113
+ # this attribute, which is fine.
114
+ pass
115
+
116
+
117
+ def get_python_version():
118
+ """Return a string containing the major and minor Python version,
119
+ leaving off the patchlevel. Sample return values could be '1.5'
120
+ or '2.2'.
121
+ """
122
+ return f'{sys.version_info.major}.{sys.version_info.minor}'
123
+
124
+
125
+ def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str:
126
+ """Return the directory containing installed Python header files.
127
+
128
+ If 'plat_specific' is false (the default), this is the path to the
129
+ non-platform-specific header files, i.e. Python.h and so on;
130
+ otherwise, this is the path to platform-specific header files
131
+ (namely pyconfig.h).
132
+
133
+ If 'prefix' is supplied, use it instead of sys.base_prefix or
134
+ sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
135
+ """
136
+ default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX
137
+ resolved_prefix = prefix if prefix is not None else default_prefix
138
+ # MinGW imitates posix like layout, but os.name != posix
139
+ os_name = "posix" if is_mingw() else os.name
140
+ try:
141
+ getter = globals()[f'_get_python_inc_{os_name}']
142
+ except KeyError:
143
+ raise DistutilsPlatformError(
144
+ "I don't know where Python installs its C header files "
145
+ f"on platform '{os.name}'"
146
+ )
147
+ return getter(resolved_prefix, prefix, plat_specific)
148
+
149
+
150
+ @pass_none
151
+ def _extant(path):
152
+ """
153
+ Replace path with None if it doesn't exist.
154
+ """
155
+ return path if os.path.exists(path) else None
156
+
157
+
158
+ def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
159
+ return (
160
+ _get_python_inc_posix_python(plat_specific)
161
+ or _extant(_get_python_inc_from_config(plat_specific, spec_prefix))
162
+ or _get_python_inc_posix_prefix(prefix)
163
+ )
164
+
165
+
166
+ def _get_python_inc_posix_python(plat_specific):
167
+ """
168
+ Assume the executable is in the build directory. The
169
+ pyconfig.h file should be in the same directory. Since
170
+ the build directory may not be the source directory,
171
+ use "srcdir" from the makefile to find the "Include"
172
+ directory.
173
+ """
174
+ if not python_build:
175
+ return
176
+ if plat_specific:
177
+ return _sys_home or project_base
178
+ incdir = os.path.join(get_config_var('srcdir'), 'Include')
179
+ return os.path.normpath(incdir)
180
+
181
+
182
+ def _get_python_inc_from_config(plat_specific, spec_prefix):
183
+ """
184
+ If no prefix was explicitly specified, provide the include
185
+ directory from the config vars. Useful when
186
+ cross-compiling, since the config vars may come from
187
+ the host
188
+ platform Python installation, while the current Python
189
+ executable is from the build platform installation.
190
+
191
+ >>> monkeypatch = getfixture('monkeypatch')
192
+ >>> gpifc = _get_python_inc_from_config
193
+ >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower)
194
+ >>> gpifc(False, '/usr/bin/')
195
+ >>> gpifc(False, '')
196
+ >>> gpifc(False, None)
197
+ 'includepy'
198
+ >>> gpifc(True, None)
199
+ 'confincludepy'
200
+ """
201
+ if spec_prefix is None:
202
+ return get_config_var('CONF' * plat_specific + 'INCLUDEPY')
203
+
204
+
205
+ def _get_python_inc_posix_prefix(prefix):
206
+ implementation = 'pypy' if IS_PYPY else 'python'
207
+ python_dir = implementation + get_python_version() + build_flags
208
+ return os.path.join(prefix, "include", python_dir)
209
+
210
+
211
+ def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
212
+ if python_build:
213
+ # Include both include dirs to ensure we can find pyconfig.h
214
+ return (
215
+ os.path.join(prefix, "include")
216
+ + os.path.pathsep
217
+ + os.path.dirname(sysconfig.get_config_h_filename())
218
+ )
219
+ return os.path.join(prefix, "include")
220
+
221
+
222
+ # allow this behavior to be monkey-patched. Ref pypa/distutils#2.
223
+ def _posix_lib(standard_lib, libpython, early_prefix, prefix):
224
+ if standard_lib:
225
+ return libpython
226
+ else:
227
+ return os.path.join(libpython, "site-packages")
228
+
229
+
230
+ def get_python_lib(
231
+ plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None
232
+ ) -> str:
233
+ """Return the directory containing the Python library (standard or
234
+ site additions).
235
+
236
+ If 'plat_specific' is true, return the directory containing
237
+ platform-specific modules, i.e. any module from a non-pure-Python
238
+ module distribution; otherwise, return the platform-shared library
239
+ directory. If 'standard_lib' is true, return the directory
240
+ containing standard Python library modules; otherwise, return the
241
+ directory for site-specific modules.
242
+
243
+ If 'prefix' is supplied, use it instead of sys.base_prefix or
244
+ sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
245
+ """
246
+
247
+ early_prefix = prefix
248
+
249
+ if prefix is None:
250
+ if standard_lib:
251
+ prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
252
+ else:
253
+ prefix = plat_specific and EXEC_PREFIX or PREFIX
254
+
255
+ if os.name == "posix" or is_mingw():
256
+ if plat_specific or standard_lib:
257
+ # Platform-specific modules (any module from a non-pure-Python
258
+ # module distribution) or standard Python library modules.
259
+ libdir = getattr(sys, "platlibdir", "lib")
260
+ else:
261
+ # Pure Python
262
+ libdir = "lib"
263
+ implementation = 'pypy' if IS_PYPY else 'python'
264
+ libpython = os.path.join(prefix, libdir, implementation + get_python_version())
265
+ return _posix_lib(standard_lib, libpython, early_prefix, prefix)
266
+ elif os.name == "nt":
267
+ if standard_lib:
268
+ return os.path.join(prefix, "Lib")
269
+ else:
270
+ return os.path.join(prefix, "Lib", "site-packages")
271
+ else:
272
+ raise DistutilsPlatformError(
273
+ f"I don't know where Python installs its library on platform '{os.name}'"
274
+ )
275
+
276
+
277
+ @functools.lru_cache
278
+ def _customize_macos():
279
+ """
280
+ Perform first-time customization of compiler-related
281
+ config vars on macOS. Use after a compiler is known
282
+ to be needed. This customization exists primarily to support Pythons
283
+ from binary installers. The kind and paths to build tools on
284
+ the user system may vary significantly from the system
285
+ that Python itself was built on. Also the user OS
286
+ version and build tools may not support the same set
287
+ of CPU architectures for universal builds.
288
+ """
289
+
290
+ sys.platform == "darwin" and __import__('_osx_support').customize_compiler(
291
+ get_config_vars()
292
+ )
293
+
294
+
295
+ def customize_compiler(compiler: CCompiler) -> None:
296
+ """Do any platform-specific customization of a CCompiler instance.
297
+
298
+ Mainly needed on Unix, so we can plug in the information that
299
+ varies across Unices and is stored in Python's Makefile.
300
+ """
301
+ if compiler.compiler_type in ["unix", "cygwin"] or (
302
+ compiler.compiler_type == "mingw32" and is_mingw()
303
+ ):
304
+ _customize_macos()
305
+
306
+ (
307
+ cc,
308
+ cxx,
309
+ cflags,
310
+ ccshared,
311
+ ldshared,
312
+ ldcxxshared,
313
+ shlib_suffix,
314
+ ar,
315
+ ar_flags,
316
+ ) = get_config_vars(
317
+ 'CC',
318
+ 'CXX',
319
+ 'CFLAGS',
320
+ 'CCSHARED',
321
+ 'LDSHARED',
322
+ 'LDCXXSHARED',
323
+ 'SHLIB_SUFFIX',
324
+ 'AR',
325
+ 'ARFLAGS',
326
+ )
327
+
328
+ cxxflags = cflags
329
+
330
+ if 'CC' in os.environ:
331
+ newcc = os.environ['CC']
332
+ if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
333
+ # If CC is overridden, use that as the default
334
+ # command for LDSHARED as well
335
+ ldshared = newcc + ldshared[len(cc) :]
336
+ cc = newcc
337
+ cxx = os.environ.get('CXX', cxx)
338
+ ldshared = os.environ.get('LDSHARED', ldshared)
339
+ ldcxxshared = os.environ.get('LDCXXSHARED', ldcxxshared)
340
+ cpp = os.environ.get(
341
+ 'CPP',
342
+ cc + " -E", # not always
343
+ )
344
+
345
+ ldshared = _add_flags(ldshared, 'LD')
346
+ ldcxxshared = _add_flags(ldcxxshared, 'LD')
347
+ cflags = os.environ.get('CFLAGS', cflags)
348
+ ldshared = _add_flags(ldshared, 'C')
349
+ cxxflags = os.environ.get('CXXFLAGS', cxxflags)
350
+ ldcxxshared = _add_flags(ldcxxshared, 'CXX')
351
+ cpp = _add_flags(cpp, 'CPP')
352
+ cflags = _add_flags(cflags, 'CPP')
353
+ cxxflags = _add_flags(cxxflags, 'CPP')
354
+ ldshared = _add_flags(ldshared, 'CPP')
355
+ ldcxxshared = _add_flags(ldcxxshared, 'CPP')
356
+
357
+ ar = os.environ.get('AR', ar)
358
+
359
+ archiver = ar + ' ' + os.environ.get('ARFLAGS', ar_flags)
360
+ cc_cmd = cc + ' ' + cflags
361
+ cxx_cmd = cxx + ' ' + cxxflags
362
+
363
+ compiler.set_executables(
364
+ preprocessor=cpp,
365
+ compiler=cc_cmd,
366
+ compiler_so=cc_cmd + ' ' + ccshared,
367
+ compiler_cxx=cxx_cmd,
368
+ compiler_so_cxx=cxx_cmd + ' ' + ccshared,
369
+ linker_so=ldshared,
370
+ linker_so_cxx=ldcxxshared,
371
+ linker_exe=cc,
372
+ linker_exe_cxx=cxx,
373
+ archiver=archiver,
374
+ )
375
+
376
+ if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
377
+ compiler.set_executables(ranlib=os.environ['RANLIB'])
378
+
379
+ compiler.shared_lib_extension = shlib_suffix
380
+
381
+
382
+ def get_config_h_filename() -> str:
383
+ """Return full pathname of installed pyconfig.h file."""
384
+ return sysconfig.get_config_h_filename()
385
+
386
+
387
+ def get_makefile_filename() -> str:
388
+ """Return full pathname of installed Makefile from the Python build."""
389
+ return sysconfig.get_makefile_filename()
390
+
391
+
392
+ def parse_config_h(fp, g=None):
393
+ """Parse a config.h-style file.
394
+
395
+ A dictionary containing name/value pairs is returned. If an
396
+ optional dictionary is passed in as the second argument, it is
397
+ used instead of a new dictionary.
398
+ """
399
+ return sysconfig.parse_config_h(fp, vars=g)
400
+
401
+
402
+ # Regexes needed for parsing Makefile (and similar syntaxes,
403
+ # like old-style Setup files).
404
+ _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
405
+ _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
406
+ _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
407
+
408
+
409
+ def parse_makefile(fn, g=None): # noqa: C901
410
+ """Parse a Makefile-style file.
411
+
412
+ A dictionary containing name/value pairs is returned. If an
413
+ optional dictionary is passed in as the second argument, it is
414
+ used instead of a new dictionary.
415
+ """
416
+ from distutils.text_file import TextFile
417
+
418
+ fp = TextFile(
419
+ fn,
420
+ strip_comments=True,
421
+ skip_blanks=True,
422
+ join_lines=True,
423
+ errors="surrogateescape",
424
+ )
425
+
426
+ if g is None:
427
+ g = {}
428
+ done = {}
429
+ notdone = {}
430
+
431
+ while True:
432
+ line = fp.readline()
433
+ if line is None: # eof
434
+ break
435
+ m = _variable_rx.match(line)
436
+ if m:
437
+ n, v = m.group(1, 2)
438
+ v = v.strip()
439
+ # `$$' is a literal `$' in make
440
+ tmpv = v.replace('$$', '')
441
+
442
+ if "$" in tmpv:
443
+ notdone[n] = v
444
+ else:
445
+ try:
446
+ v = int(v)
447
+ except ValueError:
448
+ # insert literal `$'
449
+ done[n] = v.replace('$$', '$')
450
+ else:
451
+ done[n] = v
452
+
453
+ # Variables with a 'PY_' prefix in the makefile. These need to
454
+ # be made available without that prefix through sysconfig.
455
+ # Special care is needed to ensure that variable expansion works, even
456
+ # if the expansion uses the name without a prefix.
457
+ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
458
+
459
+ # do variable interpolation here
460
+ while notdone:
461
+ for name in list(notdone):
462
+ value = notdone[name]
463
+ m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
464
+ if m:
465
+ n = m.group(1)
466
+ found = True
467
+ if n in done:
468
+ item = str(done[n])
469
+ elif n in notdone:
470
+ # get it on a subsequent round
471
+ found = False
472
+ elif n in os.environ:
473
+ # do it like make: fall back to environment
474
+ item = os.environ[n]
475
+
476
+ elif n in renamed_variables:
477
+ if name.startswith('PY_') and name[3:] in renamed_variables:
478
+ item = ""
479
+
480
+ elif 'PY_' + n in notdone:
481
+ found = False
482
+
483
+ else:
484
+ item = str(done['PY_' + n])
485
+ else:
486
+ done[n] = item = ""
487
+ if found:
488
+ after = value[m.end() :]
489
+ value = value[: m.start()] + item + after
490
+ if "$" in after:
491
+ notdone[name] = value
492
+ else:
493
+ try:
494
+ value = int(value)
495
+ except ValueError:
496
+ done[name] = value.strip()
497
+ else:
498
+ done[name] = value
499
+ del notdone[name]
500
+
501
+ if name.startswith('PY_') and name[3:] in renamed_variables:
502
+ name = name[3:]
503
+ if name not in done:
504
+ done[name] = value
505
+ else:
506
+ # bogus variable reference; just drop it since we can't deal
507
+ del notdone[name]
508
+
509
+ fp.close()
510
+
511
+ # strip spurious spaces
512
+ for k, v in done.items():
513
+ if isinstance(v, str):
514
+ done[k] = v.strip()
515
+
516
+ # save the results in the global dictionary
517
+ g.update(done)
518
+ return g
519
+
520
+
521
+ def expand_makefile_vars(s, vars):
522
+ """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
523
+ 'string' according to 'vars' (a dictionary mapping variable names to
524
+ values). Variables not present in 'vars' are silently expanded to the
525
+ empty string. The variable values in 'vars' should not contain further
526
+ variable expansions; if 'vars' is the output of 'parse_makefile()',
527
+ you're fine. Returns a variable-expanded version of 's'.
528
+ """
529
+
530
+ # This algorithm does multiple expansion, so if vars['foo'] contains
531
+ # "${bar}", it will expand ${foo} to ${bar}, and then expand
532
+ # ${bar}... and so forth. This is fine as long as 'vars' comes from
533
+ # 'parse_makefile()', which takes care of such expansions eagerly,
534
+ # according to make's variable expansion semantics.
535
+
536
+ while True:
537
+ m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
538
+ if m:
539
+ (beg, end) = m.span()
540
+ s = s[0:beg] + vars.get(m.group(1)) + s[end:]
541
+ else:
542
+ break
543
+ return s
544
+
545
+
546
+ _config_vars = None
547
+
548
+
549
+ @overload
550
+ def get_config_vars() -> dict[str, str | int]: ...
551
+ @overload
552
+ def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ...
553
+ def get_config_vars(*args: str) -> list[str | int] | dict[str, str | int]:
554
+ """With no arguments, return a dictionary of all configuration
555
+ variables relevant for the current platform. Generally this includes
556
+ everything needed to build extensions and install both pure modules and
557
+ extensions. On Unix, this means every variable defined in Python's
558
+ installed Makefile; on Windows it's a much smaller set.
559
+
560
+ With arguments, return a list of values that result from looking up
561
+ each argument in the configuration variable dictionary.
562
+ """
563
+ global _config_vars
564
+ if _config_vars is None:
565
+ _config_vars = sysconfig.get_config_vars().copy()
566
+ py39.add_ext_suffix(_config_vars)
567
+
568
+ return [_config_vars.get(name) for name in args] if args else _config_vars
569
+
570
+
571
+ @overload
572
+ @deprecated(
573
+ "SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11"
574
+ )
575
+ def get_config_var(name: Literal["SO"]) -> int | str | None: ...
576
+ @overload
577
+ def get_config_var(name: str) -> int | str | None: ...
578
+ def get_config_var(name: str) -> int | str | None:
579
+ """Return the value of a single variable using the dictionary
580
+ returned by 'get_config_vars()'. Equivalent to
581
+ get_config_vars().get(name)
582
+ """
583
+ if name == 'SO':
584
+ import warnings
585
+
586
+ warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
587
+ return get_config_vars().get(name)
588
+
589
+
590
+ @pass_none
591
+ def _add_flags(value: str, type: str) -> str:
592
+ """
593
+ Add any flags from the environment for the given type.
594
+
595
+ type is the prefix to FLAGS in the environment key (e.g. "C" for "CFLAGS").
596
+ """
597
+ flags = os.environ.get(f'{type}FLAGS')
598
+ return f'{value} {flags}' if flags else value
python/Lib/site-packages/setuptools/_distutils/text_file.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """text_file
2
+
3
+ provides the TextFile class, which gives an interface to text files
4
+ that (optionally) takes care of stripping comments, ignoring blank
5
+ lines, and joining lines with backslashes."""
6
+
7
+ import sys
8
+
9
+
10
+ class TextFile:
11
+ """Provides a file-like object that takes care of all the things you
12
+ commonly want to do when processing a text file that has some
13
+ line-by-line syntax: strip comments (as long as "#" is your
14
+ comment character), skip blank lines, join adjacent lines by
15
+ escaping the newline (ie. backslash at end of line), strip
16
+ leading and/or trailing whitespace. All of these are optional
17
+ and independently controllable.
18
+
19
+ Provides a 'warn()' method so you can generate warning messages that
20
+ report physical line number, even if the logical line in question
21
+ spans multiple physical lines. Also provides 'unreadline()' for
22
+ implementing line-at-a-time lookahead.
23
+
24
+ Constructor is called as:
25
+
26
+ TextFile (filename=None, file=None, **options)
27
+
28
+ It bombs (RuntimeError) if both 'filename' and 'file' are None;
29
+ 'filename' should be a string, and 'file' a file object (or
30
+ something that provides 'readline()' and 'close()' methods). It is
31
+ recommended that you supply at least 'filename', so that TextFile
32
+ can include it in warning messages. If 'file' is not supplied,
33
+ TextFile creates its own using 'io.open()'.
34
+
35
+ The options are all boolean, and affect the value returned by
36
+ 'readline()':
37
+ strip_comments [default: true]
38
+ strip from "#" to end-of-line, as well as any whitespace
39
+ leading up to the "#" -- unless it is escaped by a backslash
40
+ lstrip_ws [default: false]
41
+ strip leading whitespace from each line before returning it
42
+ rstrip_ws [default: true]
43
+ strip trailing whitespace (including line terminator!) from
44
+ each line before returning it
45
+ skip_blanks [default: true}
46
+ skip lines that are empty *after* stripping comments and
47
+ whitespace. (If both lstrip_ws and rstrip_ws are false,
48
+ then some lines may consist of solely whitespace: these will
49
+ *not* be skipped, even if 'skip_blanks' is true.)
50
+ join_lines [default: false]
51
+ if a backslash is the last non-newline character on a line
52
+ after stripping comments and whitespace, join the following line
53
+ to it to form one "logical line"; if N consecutive lines end
54
+ with a backslash, then N+1 physical lines will be joined to
55
+ form one logical line.
56
+ collapse_join [default: false]
57
+ strip leading whitespace from lines that are joined to their
58
+ predecessor; only matters if (join_lines and not lstrip_ws)
59
+ errors [default: 'strict']
60
+ error handler used to decode the file content
61
+
62
+ Note that since 'rstrip_ws' can strip the trailing newline, the
63
+ semantics of 'readline()' must differ from those of the builtin file
64
+ object's 'readline()' method! In particular, 'readline()' returns
65
+ None for end-of-file: an empty string might just be a blank line (or
66
+ an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
67
+ not."""
68
+
69
+ default_options = {
70
+ 'strip_comments': 1,
71
+ 'skip_blanks': 1,
72
+ 'lstrip_ws': 0,
73
+ 'rstrip_ws': 1,
74
+ 'join_lines': 0,
75
+ 'collapse_join': 0,
76
+ 'errors': 'strict',
77
+ }
78
+
79
+ def __init__(self, filename=None, file=None, **options):
80
+ """Construct a new TextFile object. At least one of 'filename'
81
+ (a string) and 'file' (a file-like object) must be supplied.
82
+ They keyword argument options are described above and affect
83
+ the values returned by 'readline()'."""
84
+ if filename is None and file is None:
85
+ raise RuntimeError(
86
+ "you must supply either or both of 'filename' and 'file'"
87
+ )
88
+
89
+ # set values for all options -- either from client option hash
90
+ # or fallback to default_options
91
+ for opt in self.default_options.keys():
92
+ if opt in options:
93
+ setattr(self, opt, options[opt])
94
+ else:
95
+ setattr(self, opt, self.default_options[opt])
96
+
97
+ # sanity check client option hash
98
+ for opt in options.keys():
99
+ if opt not in self.default_options:
100
+ raise KeyError(f"invalid TextFile option '{opt}'")
101
+
102
+ if file is None:
103
+ self.open(filename)
104
+ else:
105
+ self.filename = filename
106
+ self.file = file
107
+ self.current_line = 0 # assuming that file is at BOF!
108
+
109
+ # 'linebuf' is a stack of lines that will be emptied before we
110
+ # actually read from the file; it's only populated by an
111
+ # 'unreadline()' operation
112
+ self.linebuf = []
113
+
114
+ def open(self, filename):
115
+ """Open a new file named 'filename'. This overrides both the
116
+ 'filename' and 'file' arguments to the constructor."""
117
+ self.filename = filename
118
+ self.file = open(self.filename, errors=self.errors, encoding='utf-8')
119
+ self.current_line = 0
120
+
121
+ def close(self):
122
+ """Close the current file and forget everything we know about it
123
+ (filename, current line number)."""
124
+ file = self.file
125
+ self.file = None
126
+ self.filename = None
127
+ self.current_line = None
128
+ file.close()
129
+
130
+ def gen_error(self, msg, line=None):
131
+ outmsg = []
132
+ if line is None:
133
+ line = self.current_line
134
+ outmsg.append(self.filename + ", ")
135
+ if isinstance(line, (list, tuple)):
136
+ outmsg.append("lines {}-{}: ".format(*line))
137
+ else:
138
+ outmsg.append(f"line {int(line)}: ")
139
+ outmsg.append(str(msg))
140
+ return "".join(outmsg)
141
+
142
+ def error(self, msg, line=None):
143
+ raise ValueError("error: " + self.gen_error(msg, line))
144
+
145
+ def warn(self, msg, line=None):
146
+ """Print (to stderr) a warning message tied to the current logical
147
+ line in the current file. If the current logical line in the
148
+ file spans multiple physical lines, the warning refers to the
149
+ whole range, eg. "lines 3-5". If 'line' supplied, it overrides
150
+ the current line number; it may be a list or tuple to indicate a
151
+ range of physical lines, or an integer for a single physical
152
+ line."""
153
+ sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
154
+
155
+ def readline(self): # noqa: C901
156
+ """Read and return a single logical line from the current file (or
157
+ from an internal buffer if lines have previously been "unread"
158
+ with 'unreadline()'). If the 'join_lines' option is true, this
159
+ may involve reading multiple physical lines concatenated into a
160
+ single string. Updates the current line number, so calling
161
+ 'warn()' after 'readline()' emits a warning about the physical
162
+ line(s) just read. Returns None on end-of-file, since the empty
163
+ string can occur if 'rstrip_ws' is true but 'strip_blanks' is
164
+ not."""
165
+ # If any "unread" lines waiting in 'linebuf', return the top
166
+ # one. (We don't actually buffer read-ahead data -- lines only
167
+ # get put in 'linebuf' if the client explicitly does an
168
+ # 'unreadline()'.
169
+ if self.linebuf:
170
+ line = self.linebuf[-1]
171
+ del self.linebuf[-1]
172
+ return line
173
+
174
+ buildup_line = ''
175
+
176
+ while True:
177
+ # read the line, make it None if EOF
178
+ line = self.file.readline()
179
+ if line == '':
180
+ line = None
181
+
182
+ if self.strip_comments and line:
183
+ # Look for the first "#" in the line. If none, never
184
+ # mind. If we find one and it's the first character, or
185
+ # is not preceded by "\", then it starts a comment --
186
+ # strip the comment, strip whitespace before it, and
187
+ # carry on. Otherwise, it's just an escaped "#", so
188
+ # unescape it (and any other escaped "#"'s that might be
189
+ # lurking in there) and otherwise leave the line alone.
190
+
191
+ pos = line.find("#")
192
+ if pos == -1: # no "#" -- no comments
193
+ pass
194
+
195
+ # It's definitely a comment -- either "#" is the first
196
+ # character, or it's elsewhere and unescaped.
197
+ elif pos == 0 or line[pos - 1] != "\\":
198
+ # Have to preserve the trailing newline, because it's
199
+ # the job of a later step (rstrip_ws) to remove it --
200
+ # and if rstrip_ws is false, we'd better preserve it!
201
+ # (NB. this means that if the final line is all comment
202
+ # and has no trailing newline, we will think that it's
203
+ # EOF; I think that's OK.)
204
+ eol = (line[-1] == '\n') and '\n' or ''
205
+ line = line[0:pos] + eol
206
+
207
+ # If all that's left is whitespace, then skip line
208
+ # *now*, before we try to join it to 'buildup_line' --
209
+ # that way constructs like
210
+ # hello \\
211
+ # # comment that should be ignored
212
+ # there
213
+ # result in "hello there".
214
+ if line.strip() == "":
215
+ continue
216
+ else: # it's an escaped "#"
217
+ line = line.replace("\\#", "#")
218
+
219
+ # did previous line end with a backslash? then accumulate
220
+ if self.join_lines and buildup_line:
221
+ # oops: end of file
222
+ if line is None:
223
+ self.warn("continuation line immediately precedes end-of-file")
224
+ return buildup_line
225
+
226
+ if self.collapse_join:
227
+ line = line.lstrip()
228
+ line = buildup_line + line
229
+
230
+ # careful: pay attention to line number when incrementing it
231
+ if isinstance(self.current_line, list):
232
+ self.current_line[1] = self.current_line[1] + 1
233
+ else:
234
+ self.current_line = [self.current_line, self.current_line + 1]
235
+ # just an ordinary line, read it as usual
236
+ else:
237
+ if line is None: # eof
238
+ return None
239
+
240
+ # still have to be careful about incrementing the line number!
241
+ if isinstance(self.current_line, list):
242
+ self.current_line = self.current_line[1] + 1
243
+ else:
244
+ self.current_line = self.current_line + 1
245
+
246
+ # strip whitespace however the client wants (leading and
247
+ # trailing, or one or the other, or neither)
248
+ if self.lstrip_ws and self.rstrip_ws:
249
+ line = line.strip()
250
+ elif self.lstrip_ws:
251
+ line = line.lstrip()
252
+ elif self.rstrip_ws:
253
+ line = line.rstrip()
254
+
255
+ # blank line (whether we rstrip'ed or not)? skip to next line
256
+ # if appropriate
257
+ if line in ('', '\n') and self.skip_blanks:
258
+ continue
259
+
260
+ if self.join_lines:
261
+ if line[-1] == '\\':
262
+ buildup_line = line[:-1]
263
+ continue
264
+
265
+ if line[-2:] == '\\\n':
266
+ buildup_line = line[0:-2] + '\n'
267
+ continue
268
+
269
+ # well, I guess there's some actual content there: return it
270
+ return line
271
+
272
+ def readlines(self):
273
+ """Read and return the list of all logical lines remaining in the
274
+ current file."""
275
+ lines = []
276
+ while True:
277
+ line = self.readline()
278
+ if line is None:
279
+ return lines
280
+ lines.append(line)
281
+
282
+ def unreadline(self, line):
283
+ """Push 'line' (a string) onto an internal buffer that will be
284
+ checked by future 'readline()' calls. Handy for implementing
285
+ a parser with line-at-a-time lookahead."""
286
+ self.linebuf.append(line)
python/Lib/site-packages/setuptools/_distutils/unixccompiler.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ from .compilers.C import unix
4
+
5
+ UnixCCompiler = unix.Compiler
6
+
7
+ # ensure import of unixccompiler implies ccompiler imported
8
+ # (pypa/setuptools#4871)
9
+ importlib.import_module('distutils.ccompiler')
python/Lib/site-packages/setuptools/_distutils/util.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.util
2
+
3
+ Miscellaneous utility functions -- anything that doesn't fit into
4
+ one of the other *util.py modules.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import importlib.util
11
+ import os
12
+ import pathlib
13
+ import re
14
+ import string
15
+ import subprocess
16
+ import sys
17
+ import sysconfig
18
+ import tempfile
19
+ from collections.abc import Callable, Iterable, Mapping
20
+ from typing import TYPE_CHECKING, AnyStr
21
+
22
+ from jaraco.functools import pass_none
23
+
24
+ from ._log import log
25
+ from ._modified import newer
26
+ from .errors import DistutilsByteCompileError, DistutilsPlatformError
27
+ from .spawn import spawn
28
+
29
+ if TYPE_CHECKING:
30
+ from typing_extensions import TypeVarTuple, Unpack
31
+
32
+ _Ts = TypeVarTuple("_Ts")
33
+
34
+
35
+ def get_host_platform() -> str:
36
+ """
37
+ Return a string that identifies the current platform. Use this
38
+ function to distinguish platform-specific build directories and
39
+ platform-specific built distributions.
40
+ """
41
+
42
+ # This function initially exposed platforms as defined in Python 3.9
43
+ # even with older Python versions when distutils was split out.
44
+ # Now it delegates to stdlib sysconfig.
45
+
46
+ return sysconfig.get_platform()
47
+
48
+
49
+ def get_platform() -> str:
50
+ if os.name == 'nt':
51
+ TARGET_TO_PLAT = {
52
+ 'x86': 'win32',
53
+ 'x64': 'win-amd64',
54
+ 'arm': 'win-arm32',
55
+ 'arm64': 'win-arm64',
56
+ }
57
+ target = os.environ.get('VSCMD_ARG_TGT_ARCH')
58
+ return TARGET_TO_PLAT.get(target) or get_host_platform()
59
+ return get_host_platform()
60
+
61
+
62
+ if sys.platform == 'darwin':
63
+ _syscfg_macosx_ver = None # cache the version pulled from sysconfig
64
+ MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'
65
+
66
+
67
+ def _clear_cached_macosx_ver():
68
+ """For testing only. Do not call."""
69
+ global _syscfg_macosx_ver
70
+ _syscfg_macosx_ver = None
71
+
72
+
73
+ def get_macosx_target_ver_from_syscfg():
74
+ """Get the version of macOS latched in the Python interpreter configuration.
75
+ Returns the version as a string or None if can't obtain one. Cached."""
76
+ global _syscfg_macosx_ver
77
+ if _syscfg_macosx_ver is None:
78
+ from distutils import sysconfig
79
+
80
+ ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''
81
+ if ver:
82
+ _syscfg_macosx_ver = ver
83
+ return _syscfg_macosx_ver
84
+
85
+
86
+ def get_macosx_target_ver():
87
+ """Return the version of macOS for which we are building.
88
+
89
+ The target version defaults to the version in sysconfig latched at time
90
+ the Python interpreter was built, unless overridden by an environment
91
+ variable. If neither source has a value, then None is returned"""
92
+
93
+ syscfg_ver = get_macosx_target_ver_from_syscfg()
94
+ env_ver = os.environ.get(MACOSX_VERSION_VAR)
95
+
96
+ if env_ver:
97
+ # Validate overridden version against sysconfig version, if have both.
98
+ # Ensure that the deployment target of the build process is not less
99
+ # than 10.3 if the interpreter was built for 10.3 or later. This
100
+ # ensures extension modules are built with correct compatibility
101
+ # values, specifically LDSHARED which can use
102
+ # '-undefined dynamic_lookup' which only works on >= 10.3.
103
+ if (
104
+ syscfg_ver
105
+ and split_version(syscfg_ver) >= [10, 3]
106
+ and split_version(env_ver) < [10, 3]
107
+ ):
108
+ my_msg = (
109
+ '$' + MACOSX_VERSION_VAR + ' mismatch: '
110
+ f'now "{env_ver}" but "{syscfg_ver}" during configure; '
111
+ 'must use 10.3 or later'
112
+ )
113
+ raise DistutilsPlatformError(my_msg)
114
+ return env_ver
115
+ return syscfg_ver
116
+
117
+
118
+ def split_version(s: str) -> list[int]:
119
+ """Convert a dot-separated string into a list of numbers for comparisons"""
120
+ return [int(n) for n in s.split('.')]
121
+
122
+
123
+ @pass_none
124
+ def convert_path(pathname: str | os.PathLike[str]) -> str:
125
+ r"""
126
+ Allow for pathlib.Path inputs, coax to a native path string.
127
+
128
+ If None is passed, will just pass it through as
129
+ Setuptools relies on this behavior.
130
+
131
+ >>> convert_path(None) is None
132
+ True
133
+
134
+ Removes empty paths.
135
+
136
+ >>> convert_path('foo/./bar').replace('\\', '/')
137
+ 'foo/bar'
138
+ """
139
+ return os.fspath(pathlib.PurePath(pathname))
140
+
141
+
142
+ def change_root(
143
+ new_root: AnyStr | os.PathLike[AnyStr], pathname: AnyStr | os.PathLike[AnyStr]
144
+ ) -> AnyStr:
145
+ """Return 'pathname' with 'new_root' prepended. If 'pathname' is
146
+ relative, this is equivalent to "os.path.join(new_root,pathname)".
147
+ Otherwise, it requires making 'pathname' relative and then joining the
148
+ two, which is tricky on DOS/Windows and Mac OS.
149
+ """
150
+ if os.name == 'posix':
151
+ if not os.path.isabs(pathname):
152
+ return os.path.join(new_root, pathname)
153
+ else:
154
+ return os.path.join(new_root, pathname[1:])
155
+
156
+ elif os.name == 'nt':
157
+ (drive, path) = os.path.splitdrive(pathname)
158
+ if path[0] == os.sep:
159
+ path = path[1:]
160
+ return os.path.join(new_root, path)
161
+
162
+ raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
163
+
164
+
165
+ @functools.lru_cache
166
+ def check_environ() -> None:
167
+ """Ensure that 'os.environ' has all the environment variables we
168
+ guarantee that users can use in config files, command-line options,
169
+ etc. Currently this includes:
170
+ HOME - user's home directory (Unix only)
171
+ PLAT - description of the current platform, including hardware
172
+ and OS (see 'get_platform()')
173
+ """
174
+ if os.name == 'posix' and 'HOME' not in os.environ:
175
+ try:
176
+ import pwd
177
+
178
+ os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
179
+ except (ImportError, KeyError):
180
+ # bpo-10496: if the current user identifier doesn't exist in the
181
+ # password database, do nothing
182
+ pass
183
+
184
+ if 'PLAT' not in os.environ:
185
+ os.environ['PLAT'] = get_platform()
186
+
187
+
188
+ def subst_vars(s, local_vars: Mapping[str, object]) -> str:
189
+ """
190
+ Perform variable substitution on 'string'.
191
+ Variables are indicated by format-style braces ("{var}").
192
+ Variable is substituted by the value found in the 'local_vars'
193
+ dictionary or in 'os.environ' if it's not in 'local_vars'.
194
+ 'os.environ' is first checked/augmented to guarantee that it contains
195
+ certain values: see 'check_environ()'. Raise ValueError for any
196
+ variables not found in either 'local_vars' or 'os.environ'.
197
+ """
198
+ check_environ()
199
+ lookup = dict(os.environ)
200
+ lookup.update((name, str(value)) for name, value in local_vars.items())
201
+ try:
202
+ return _subst_compat(s).format_map(lookup)
203
+ except KeyError as var:
204
+ raise ValueError(f"invalid variable {var}")
205
+
206
+
207
+ def _subst_compat(s):
208
+ """
209
+ Replace shell/Perl-style variable substitution with
210
+ format-style. For compatibility.
211
+ """
212
+
213
+ def _subst(match):
214
+ return f'{{{match.group(1)}}}'
215
+
216
+ repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
217
+ if repl != s:
218
+ import warnings
219
+
220
+ warnings.warn(
221
+ "shell/Perl-style substitutions are deprecated",
222
+ DeprecationWarning,
223
+ )
224
+ return repl
225
+
226
+
227
+ def grok_environment_error(exc: object, prefix: str = "error: ") -> str:
228
+ # Function kept for backward compatibility.
229
+ # Used to try clever things with EnvironmentErrors,
230
+ # but nowadays str(exception) produces good messages.
231
+ return prefix + str(exc)
232
+
233
+
234
+ # Needed by 'split_quoted()'
235
+ _wordchars_re = _squote_re = _dquote_re = None
236
+
237
+
238
+ def _init_regex():
239
+ global _wordchars_re, _squote_re, _dquote_re
240
+ _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*')
241
+ _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
242
+ _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
243
+
244
+
245
+ def split_quoted(s: str) -> list[str]:
246
+ """Split a string up according to Unix shell-like rules for quotes and
247
+ backslashes. In short: words are delimited by spaces, as long as those
248
+ spaces are not escaped by a backslash, or inside a quoted string.
249
+ Single and double quotes are equivalent, and the quote characters can
250
+ be backslash-escaped. The backslash is stripped from any two-character
251
+ escape sequence, leaving only the escaped character. The quote
252
+ characters are stripped from any quoted string. Returns a list of
253
+ words.
254
+ """
255
+
256
+ # This is a nice algorithm for splitting up a single string, since it
257
+ # doesn't require character-by-character examination. It was a little
258
+ # bit of a brain-bender to get it working right, though...
259
+ if _wordchars_re is None:
260
+ _init_regex()
261
+
262
+ s = s.strip()
263
+ words = []
264
+ pos = 0
265
+
266
+ while s:
267
+ m = _wordchars_re.match(s, pos)
268
+ end = m.end()
269
+ if end == len(s):
270
+ words.append(s[:end])
271
+ break
272
+
273
+ if s[end] in string.whitespace:
274
+ # unescaped, unquoted whitespace: now
275
+ # we definitely have a word delimiter
276
+ words.append(s[:end])
277
+ s = s[end:].lstrip()
278
+ pos = 0
279
+
280
+ elif s[end] == '\\':
281
+ # preserve whatever is being escaped;
282
+ # will become part of the current word
283
+ s = s[:end] + s[end + 1 :]
284
+ pos = end + 1
285
+
286
+ else:
287
+ if s[end] == "'": # slurp singly-quoted string
288
+ m = _squote_re.match(s, end)
289
+ elif s[end] == '"': # slurp doubly-quoted string
290
+ m = _dquote_re.match(s, end)
291
+ else:
292
+ raise RuntimeError(f"this can't happen (bad char '{s[end]}')")
293
+
294
+ if m is None:
295
+ raise ValueError(f"bad string (mismatched {s[end]} quotes?)")
296
+
297
+ (beg, end) = m.span()
298
+ s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
299
+ pos = m.end() - 2
300
+
301
+ if pos >= len(s):
302
+ words.append(s)
303
+ break
304
+
305
+ return words
306
+
307
+
308
+ # split_quoted ()
309
+
310
+
311
+ def execute(
312
+ func: Callable[[Unpack[_Ts]], object],
313
+ args: tuple[Unpack[_Ts]],
314
+ msg: object = None,
315
+ verbose: bool = False,
316
+ ) -> None:
317
+ """
318
+ Perform some action that affects the outside world (e.g. by
319
+ writing to the filesystem). Was previously used to deal with
320
+ "dry run" operations, but now runs unconditionally.
321
+ """
322
+ if msg is None:
323
+ msg = f"{func.__name__}{args!r}"
324
+ if msg[-2:] == ',)': # correct for singleton tuple
325
+ msg = msg[0:-2] + ')'
326
+
327
+ log.info(msg)
328
+ func(*args)
329
+
330
+
331
+ def strtobool(val: str) -> bool:
332
+ """Convert a string representation of truth to true (1) or false (0).
333
+
334
+ True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
335
+ are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
336
+ 'val' is anything else.
337
+ """
338
+ val = val.lower()
339
+ if val in ('y', 'yes', 't', 'true', 'on', '1'):
340
+ return True
341
+ elif val in ('n', 'no', 'f', 'false', 'off', '0'):
342
+ return False
343
+ else:
344
+ raise ValueError(f"invalid truth value {val!r}")
345
+
346
+
347
+ def byte_compile( # noqa: C901
348
+ py_files: Iterable[str],
349
+ optimize: int = 0,
350
+ force: bool = False,
351
+ prefix: str | None = None,
352
+ base_dir: str | None = None,
353
+ verbose: bool = True,
354
+ direct: bool | None = None,
355
+ ) -> None:
356
+ """Byte-compile a collection of Python source files to .pyc
357
+ files in a __pycache__ subdirectory. 'py_files' is a list
358
+ of files to compile; any files that don't end in ".py" are silently
359
+ skipped. 'optimize' must be one of the following:
360
+ 0 - don't optimize
361
+ 1 - normal optimization (like "python -O")
362
+ 2 - extra optimization (like "python -OO")
363
+ If 'force' is true, all files are recompiled regardless of
364
+ timestamps.
365
+
366
+ The source filename encoded in each bytecode file defaults to the
367
+ filenames listed in 'py_files'; you can modify these with 'prefix' and
368
+ 'basedir'. 'prefix' is a string that will be stripped off of each
369
+ source filename, and 'base_dir' is a directory name that will be
370
+ prepended (after 'prefix' is stripped). You can supply either or both
371
+ (or neither) of 'prefix' and 'base_dir', as you wish.
372
+
373
+ Byte-compilation is either done directly in this interpreter process
374
+ with the standard py_compile module, or indirectly by writing a
375
+ temporary script and executing it. Normally, you should let
376
+ 'byte_compile()' figure out to use direct compilation or not (see
377
+ the source for details). The 'direct' flag is used by the script
378
+ generated in indirect mode; unless you know what you're doing, leave
379
+ it set to None.
380
+ """
381
+
382
+ # nothing is done if sys.dont_write_bytecode is True
383
+ if sys.dont_write_bytecode:
384
+ raise DistutilsByteCompileError('byte-compiling is disabled.')
385
+
386
+ # First, if the caller didn't force us into direct or indirect mode,
387
+ # figure out which mode we should be in. We take a conservative
388
+ # approach: choose direct mode *only* if the current interpreter is
389
+ # in debug mode and optimize is 0. If we're not in debug mode (-O
390
+ # or -OO), we don't know which level of optimization this
391
+ # interpreter is running with, so we can't do direct
392
+ # byte-compilation and be certain that it's the right thing. Thus,
393
+ # always compile indirectly if the current interpreter is in either
394
+ # optimize mode, or if either optimization level was requested by
395
+ # the caller.
396
+ if direct is None:
397
+ direct = __debug__ and optimize == 0
398
+
399
+ # "Indirect" byte-compilation: write a temporary script and then
400
+ # run it with the appropriate flags.
401
+ if not direct:
402
+ (script_fd, script_name) = tempfile.mkstemp(".py")
403
+ log.info("writing byte-compilation script '%s'", script_name)
404
+ script = os.fdopen(script_fd, "w", encoding='utf-8')
405
+
406
+ with script:
407
+ script.write(
408
+ """\
409
+ from distutils.util import byte_compile
410
+ files = [
411
+ """
412
+ )
413
+
414
+ # XXX would be nice to write absolute filenames, just for
415
+ # safety's sake (script should be more robust in the face of
416
+ # chdir'ing before running it). But this requires abspath'ing
417
+ # 'prefix' as well, and that breaks the hack in build_lib's
418
+ # 'byte_compile()' method that carefully tacks on a trailing
419
+ # slash (os.sep really) to make sure the prefix here is "just
420
+ # right". This whole prefix business is rather delicate -- the
421
+ # problem is that it's really a directory, but I'm treating it
422
+ # as a dumb string, so trailing slashes and so forth matter.
423
+
424
+ script.write(",\n".join(map(repr, py_files)) + "]\n")
425
+ script.write(
426
+ f"""
427
+ byte_compile(files, optimize={optimize!r}, force={force!r},
428
+ prefix={prefix!r}, base_dir={base_dir!r},
429
+ verbose={verbose!r},
430
+ direct=True)
431
+ """
432
+ )
433
+
434
+ cmd = [sys.executable]
435
+ cmd.extend(subprocess._optim_args_from_interpreter_flags())
436
+ cmd.append(script_name)
437
+ spawn(cmd)
438
+ execute(os.remove, (script_name,), f"removing {script_name}")
439
+
440
+ # "Direct" byte-compilation: use the py_compile module to compile
441
+ # right here, right now. Note that the script generated in indirect
442
+ # mode simply calls 'byte_compile()' in direct mode, a weird sort of
443
+ # cross-process recursion. Hey, it works!
444
+ else:
445
+ from py_compile import compile
446
+
447
+ for file in py_files:
448
+ if file[-3:] != ".py":
449
+ # This lets us be lazy and not filter filenames in
450
+ # the "install_lib" command.
451
+ continue
452
+
453
+ # Terminology from the py_compile module:
454
+ # cfile - byte-compiled file
455
+ # dfile - purported source filename (same as 'file' by default)
456
+ if optimize >= 0:
457
+ opt = '' if optimize == 0 else optimize
458
+ cfile = importlib.util.cache_from_source(file, optimization=opt)
459
+ else:
460
+ cfile = importlib.util.cache_from_source(file)
461
+ dfile = file
462
+ if prefix:
463
+ if file[: len(prefix)] != prefix:
464
+ raise ValueError(
465
+ f"invalid prefix: filename {file!r} doesn't start with {prefix!r}"
466
+ )
467
+ dfile = dfile[len(prefix) :]
468
+ if base_dir:
469
+ dfile = os.path.join(base_dir, dfile)
470
+
471
+ cfile_base = os.path.basename(cfile)
472
+ if direct:
473
+ if force or newer(file, cfile):
474
+ log.info("byte-compiling %s to %s", file, cfile_base)
475
+ compile(file, cfile, dfile)
476
+ else:
477
+ log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
478
+
479
+
480
+ def rfc822_escape(header: str) -> str:
481
+ """Return a version of the string escaped for inclusion in an
482
+ RFC-822 header, by ensuring there are 8 spaces space after each newline.
483
+ """
484
+ indent = 8 * " "
485
+ lines = header.splitlines(keepends=True)
486
+
487
+ # Emulate the behaviour of `str.split`
488
+ # (the terminal line break in `splitlines` does not result in an extra line):
489
+ ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1]
490
+ suffix = indent if ends_in_newline else ""
491
+
492
+ return indent.join(lines) + suffix
493
+
494
+
495
+ def is_mingw() -> bool:
496
+ """Returns True if the current platform is mingw.
497
+
498
+ Python compiled with Mingw-w64 has sys.platform == 'win32' and
499
+ get_platform() starts with 'mingw'.
500
+ """
501
+ return sys.platform == 'win32' and get_platform().startswith('mingw')
502
+
503
+
504
+ def is_freethreaded():
505
+ """Return True if the Python interpreter is built with free threading support."""
506
+ return bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
python/Lib/site-packages/setuptools/_distutils/version.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # distutils/version.py
3
+ #
4
+ # Implements multiple version numbering conventions for the
5
+ # Python Module Distribution Utilities.
6
+ #
7
+ # $Id$
8
+ #
9
+
10
+ """Provides classes to represent module version numbers (one class for
11
+ each style of version numbering). There are currently two such classes
12
+ implemented: StrictVersion and LooseVersion.
13
+
14
+ Every version number class implements the following interface:
15
+ * the 'parse' method takes a string and parses it to some internal
16
+ representation; if the string is an invalid version number,
17
+ 'parse' raises a ValueError exception
18
+ * the class constructor takes an optional string argument which,
19
+ if supplied, is passed to 'parse'
20
+ * __str__ reconstructs the string that was passed to 'parse' (or
21
+ an equivalent string -- ie. one that will generate an equivalent
22
+ version number instance)
23
+ * __repr__ generates Python code to recreate the version number instance
24
+ * _cmp compares the current instance with either another instance
25
+ of the same class or a string (which will be parsed to an instance
26
+ of the same class, thus must follow the same rules)
27
+ """
28
+
29
+ import contextlib
30
+ import re
31
+ import warnings
32
+
33
+
34
+ @contextlib.contextmanager
35
+ def suppress_known_deprecation():
36
+ with warnings.catch_warnings(record=True) as ctx:
37
+ warnings.filterwarnings(
38
+ action='default',
39
+ category=DeprecationWarning,
40
+ message="distutils Version classes are deprecated.",
41
+ )
42
+ yield ctx
43
+
44
+
45
+ class Version:
46
+ """Abstract base class for version numbering classes. Just provides
47
+ constructor (__init__) and reproducer (__repr__), because those
48
+ seem to be the same for all version numbering classes; and route
49
+ rich comparisons to _cmp.
50
+ """
51
+
52
+ def __init__(self, vstring=None):
53
+ if vstring:
54
+ self.parse(vstring)
55
+ warnings.warn(
56
+ "distutils Version classes are deprecated. Use packaging.version instead.",
57
+ DeprecationWarning,
58
+ stacklevel=2,
59
+ )
60
+
61
+ def __repr__(self):
62
+ return f"{self.__class__.__name__} ('{self}')"
63
+
64
+ def __eq__(self, other):
65
+ c = self._cmp(other)
66
+ if c is NotImplemented:
67
+ return c
68
+ return c == 0
69
+
70
+ def __lt__(self, other):
71
+ c = self._cmp(other)
72
+ if c is NotImplemented:
73
+ return c
74
+ return c < 0
75
+
76
+ def __le__(self, other):
77
+ c = self._cmp(other)
78
+ if c is NotImplemented:
79
+ return c
80
+ return c <= 0
81
+
82
+ def __gt__(self, other):
83
+ c = self._cmp(other)
84
+ if c is NotImplemented:
85
+ return c
86
+ return c > 0
87
+
88
+ def __ge__(self, other):
89
+ c = self._cmp(other)
90
+ if c is NotImplemented:
91
+ return c
92
+ return c >= 0
93
+
94
+
95
+ # Interface for version-number classes -- must be implemented
96
+ # by the following classes (the concrete ones -- Version should
97
+ # be treated as an abstract class).
98
+ # __init__ (string) - create and take same action as 'parse'
99
+ # (string parameter is optional)
100
+ # parse (string) - convert a string representation to whatever
101
+ # internal representation is appropriate for
102
+ # this style of version numbering
103
+ # __str__ (self) - convert back to a string; should be very similar
104
+ # (if not identical to) the string supplied to parse
105
+ # __repr__ (self) - generate Python code to recreate
106
+ # the instance
107
+ # _cmp (self, other) - compare two version numbers ('other' may
108
+ # be an unparsed version string, or another
109
+ # instance of your version class)
110
+
111
+
112
+ class StrictVersion(Version):
113
+ """Version numbering for anal retentives and software idealists.
114
+ Implements the standard interface for version number classes as
115
+ described above. A version number consists of two or three
116
+ dot-separated numeric components, with an optional "pre-release" tag
117
+ on the end. The pre-release tag consists of the letter 'a' or 'b'
118
+ followed by a number. If the numeric components of two version
119
+ numbers are equal, then one with a pre-release tag will always
120
+ be deemed earlier (lesser) than one without.
121
+
122
+ The following are valid version numbers (shown in the order that
123
+ would be obtained by sorting according to the supplied cmp function):
124
+
125
+ 0.4 0.4.0 (these two are equivalent)
126
+ 0.4.1
127
+ 0.5a1
128
+ 0.5b3
129
+ 0.5
130
+ 0.9.6
131
+ 1.0
132
+ 1.0.4a3
133
+ 1.0.4b1
134
+ 1.0.4
135
+
136
+ The following are examples of invalid version numbers:
137
+
138
+ 1
139
+ 2.7.2.2
140
+ 1.3.a4
141
+ 1.3pl1
142
+ 1.3c4
143
+
144
+ The rationale for this version numbering system will be explained
145
+ in the distutils documentation.
146
+ """
147
+
148
+ version_re = re.compile(
149
+ r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII
150
+ )
151
+
152
+ def parse(self, vstring):
153
+ match = self.version_re.match(vstring)
154
+ if not match:
155
+ raise ValueError(f"invalid version number '{vstring}'")
156
+
157
+ (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
158
+
159
+ if patch:
160
+ self.version = tuple(map(int, [major, minor, patch]))
161
+ else:
162
+ self.version = tuple(map(int, [major, minor])) + (0,)
163
+
164
+ if prerelease:
165
+ self.prerelease = (prerelease[0], int(prerelease_num))
166
+ else:
167
+ self.prerelease = None
168
+
169
+ def __str__(self):
170
+ if self.version[2] == 0:
171
+ vstring = '.'.join(map(str, self.version[0:2]))
172
+ else:
173
+ vstring = '.'.join(map(str, self.version))
174
+
175
+ if self.prerelease:
176
+ vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
177
+
178
+ return vstring
179
+
180
+ def _cmp(self, other):
181
+ if isinstance(other, str):
182
+ with suppress_known_deprecation():
183
+ other = StrictVersion(other)
184
+ elif not isinstance(other, StrictVersion):
185
+ return NotImplemented
186
+
187
+ if self.version == other.version:
188
+ # versions match; pre-release drives the comparison
189
+ return self._cmp_prerelease(other)
190
+
191
+ return -1 if self.version < other.version else 1
192
+
193
+ def _cmp_prerelease(self, other):
194
+ """
195
+ case 1: self has prerelease, other doesn't; other is greater
196
+ case 2: self doesn't have prerelease, other does: self is greater
197
+ case 3: both or neither have prerelease: compare them!
198
+ """
199
+ if self.prerelease and not other.prerelease:
200
+ return -1
201
+ elif not self.prerelease and other.prerelease:
202
+ return 1
203
+
204
+ if self.prerelease == other.prerelease:
205
+ return 0
206
+ elif self.prerelease < other.prerelease:
207
+ return -1
208
+ else:
209
+ return 1
210
+
211
+
212
+ # end class StrictVersion
213
+
214
+
215
+ # The rules according to Greg Stein:
216
+ # 1) a version number has 1 or more numbers separated by a period or by
217
+ # sequences of letters. If only periods, then these are compared
218
+ # left-to-right to determine an ordering.
219
+ # 2) sequences of letters are part of the tuple for comparison and are
220
+ # compared lexicographically
221
+ # 3) recognize the numeric components may have leading zeroes
222
+ #
223
+ # The LooseVersion class below implements these rules: a version number
224
+ # string is split up into a tuple of integer and string components, and
225
+ # comparison is a simple tuple comparison. This means that version
226
+ # numbers behave in a predictable and obvious way, but a way that might
227
+ # not necessarily be how people *want* version numbers to behave. There
228
+ # wouldn't be a problem if people could stick to purely numeric version
229
+ # numbers: just split on period and compare the numbers as tuples.
230
+ # However, people insist on putting letters into their version numbers;
231
+ # the most common purpose seems to be:
232
+ # - indicating a "pre-release" version
233
+ # ('alpha', 'beta', 'a', 'b', 'pre', 'p')
234
+ # - indicating a post-release patch ('p', 'pl', 'patch')
235
+ # but of course this can't cover all version number schemes, and there's
236
+ # no way to know what a programmer means without asking him.
237
+ #
238
+ # The problem is what to do with letters (and other non-numeric
239
+ # characters) in a version number. The current implementation does the
240
+ # obvious and predictable thing: keep them as strings and compare
241
+ # lexically within a tuple comparison. This has the desired effect if
242
+ # an appended letter sequence implies something "post-release":
243
+ # eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
244
+ #
245
+ # However, if letters in a version number imply a pre-release version,
246
+ # the "obvious" thing isn't correct. Eg. you would expect that
247
+ # "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
248
+ # implemented here, this just isn't so.
249
+ #
250
+ # Two possible solutions come to mind. The first is to tie the
251
+ # comparison algorithm to a particular set of semantic rules, as has
252
+ # been done in the StrictVersion class above. This works great as long
253
+ # as everyone can go along with bondage and discipline. Hopefully a
254
+ # (large) subset of Python module programmers will agree that the
255
+ # particular flavour of bondage and discipline provided by StrictVersion
256
+ # provides enough benefit to be worth using, and will submit their
257
+ # version numbering scheme to its domination. The free-thinking
258
+ # anarchists in the lot will never give in, though, and something needs
259
+ # to be done to accommodate them.
260
+ #
261
+ # Perhaps a "moderately strict" version class could be implemented that
262
+ # lets almost anything slide (syntactically), and makes some heuristic
263
+ # assumptions about non-digits in version number strings. This could
264
+ # sink into special-case-hell, though; if I was as talented and
265
+ # idiosyncratic as Larry Wall, I'd go ahead and implement a class that
266
+ # somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
267
+ # just as happy dealing with things like "2g6" and "1.13++". I don't
268
+ # think I'm smart enough to do it right though.
269
+ #
270
+ # In any case, I've coded the test suite for this module (see
271
+ # ../test/test_version.py) specifically to fail on things like comparing
272
+ # "1.2a2" and "1.2". That's not because the *code* is doing anything
273
+ # wrong, it's because the simple, obvious design doesn't match my
274
+ # complicated, hairy expectations for real-world version numbers. It
275
+ # would be a snap to fix the test suite to say, "Yep, LooseVersion does
276
+ # the Right Thing" (ie. the code matches the conception). But I'd rather
277
+ # have a conception that matches common notions about version numbers.
278
+
279
+
280
+ class LooseVersion(Version):
281
+ """Version numbering for anarchists and software realists.
282
+ Implements the standard interface for version number classes as
283
+ described above. A version number consists of a series of numbers,
284
+ separated by either periods or strings of letters. When comparing
285
+ version numbers, the numeric components will be compared
286
+ numerically, and the alphabetic components lexically. The following
287
+ are all valid version numbers, in no particular order:
288
+
289
+ 1.5.1
290
+ 1.5.2b2
291
+ 161
292
+ 3.10a
293
+ 8.02
294
+ 3.4j
295
+ 1996.07.12
296
+ 3.2.pl0
297
+ 3.1.1.6
298
+ 2g6
299
+ 11g
300
+ 0.960923
301
+ 2.2beta29
302
+ 1.13++
303
+ 5.5.kw
304
+ 2.0b1pl0
305
+
306
+ In fact, there is no such thing as an invalid version number under
307
+ this scheme; the rules for comparison are simple and predictable,
308
+ but may not always give the results you want (for some definition
309
+ of "want").
310
+ """
311
+
312
+ component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
313
+
314
+ def parse(self, vstring):
315
+ # I've given up on thinking I can reconstruct the version string
316
+ # from the parsed tuple -- so I just store the string here for
317
+ # use by __str__
318
+ self.vstring = vstring
319
+ components = [x for x in self.component_re.split(vstring) if x and x != '.']
320
+ for i, obj in enumerate(components):
321
+ try:
322
+ components[i] = int(obj)
323
+ except ValueError:
324
+ pass
325
+
326
+ self.version = components
327
+
328
+ def __str__(self):
329
+ return self.vstring
330
+
331
+ def __repr__(self):
332
+ return f"LooseVersion ('{self}')"
333
+
334
+ def _cmp(self, other):
335
+ if isinstance(other, str):
336
+ other = LooseVersion(other)
337
+ elif not isinstance(other, LooseVersion):
338
+ return NotImplemented
339
+
340
+ if self.version == other.version:
341
+ return 0
342
+ if self.version < other.version:
343
+ return -1
344
+ if self.version > other.version:
345
+ return 1
346
+
347
+
348
+ # end class LooseVersion
python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: more-itertools
3
+ Version: 10.8.0
4
+ Summary: More routines for operating on iterables, beyond itertools
5
+ Keywords: itertools,iterator,iteration,filter,peek,peekable,chunk,chunked
6
+ Author-email: Erik Rose <erikrose@grinchcentral.com>
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/x-rst
9
+ License-Expression: MIT
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ License-File: LICENSE
24
+ Project-URL: Documentation, https://more-itertools.readthedocs.io/en/stable/
25
+ Project-URL: Homepage, https://github.com/more-itertools/more-itertools
26
+
27
+ ==============
28
+ More Itertools
29
+ ==============
30
+
31
+ .. image:: https://readthedocs.org/projects/more-itertools/badge/?version=latest
32
+ :target: https://more-itertools.readthedocs.io/en/stable/
33
+
34
+ Python's ``itertools`` library is a gem - you can compose elegant solutions
35
+ for a variety of problems with the functions it provides. In ``more-itertools``
36
+ we collect additional building blocks, recipes, and routines for working with
37
+ Python iterables.
38
+
39
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
40
+ | Grouping | `chunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked>`_, |
41
+ | | `ichunked <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ichunked>`_, |
42
+ | | `chunked_even <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.chunked_even>`_, |
43
+ | | `sliced <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliced>`_, |
44
+ | | `constrained_batches <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.constrained_batches>`_, |
45
+ | | `distribute <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distribute>`_, |
46
+ | | `divide <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.divide>`_, |
47
+ | | `split_at <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_at>`_, |
48
+ | | `split_before <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_before>`_, |
49
+ | | `split_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_after>`_, |
50
+ | | `split_into <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_into>`_, |
51
+ | | `split_when <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.split_when>`_, |
52
+ | | `bucket <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.bucket>`_, |
53
+ | | `unzip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unzip>`_, |
54
+ | | `batched <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.batched>`_, |
55
+ | | `grouper <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.grouper>`_, |
56
+ | | `partition <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partition>`_, |
57
+ | | `transpose <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.transpose>`_ |
58
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
59
+ | Lookahead and lookback | `spy <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.spy>`_, |
60
+ | | `peekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.peekable>`_, |
61
+ | | `seekable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.seekable>`_ |
62
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
63
+ | Windowing | `windowed <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed>`_, |
64
+ | | `substrings <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings>`_, |
65
+ | | `substrings_indexes <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.substrings_indexes>`_, |
66
+ | | `stagger <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.stagger>`_, |
67
+ | | `windowed_complete <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.windowed_complete>`_, |
68
+ | | `pairwise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pairwise>`_, |
69
+ | | `triplewise <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.triplewise>`_, |
70
+ | | `sliding_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sliding_window>`_, |
71
+ | | `subslices <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.subslices>`_ |
72
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
73
+ | Augmenting | `count_cycle <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.count_cycle>`_, |
74
+ | | `intersperse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.intersperse>`_, |
75
+ | | `padded <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.padded>`_, |
76
+ | | `repeat_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_each>`_, |
77
+ | | `mark_ends <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.mark_ends>`_, |
78
+ | | `repeat_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeat_last>`_, |
79
+ | | `adjacent <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.adjacent>`_, |
80
+ | | `groupby_transform <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.groupby_transform>`_, |
81
+ | | `pad_none <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.pad_none>`_, |
82
+ | | `ncycles <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ncycles>`_ |
83
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
84
+ | Combining | `collapse <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.collapse>`_, |
85
+ | | `sort_together <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sort_together>`_, |
86
+ | | `interleave <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave>`_, |
87
+ | | `interleave_longest <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_longest>`_, |
88
+ | | `interleave_evenly <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_evenly>`_, |
89
+ | | `interleave_randomly <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.interleave_randomly>`_, |
90
+ | | `zip_offset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_offset>`_, |
91
+ | | `zip_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_equal>`_, |
92
+ | | `zip_broadcast <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.zip_broadcast>`_, |
93
+ | | `flatten <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten>`_, |
94
+ | | `roundrobin <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.roundrobin>`_, |
95
+ | | `prepend <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.prepend>`_, |
96
+ | | `value_chain <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.value_chain>`_, |
97
+ | | `partial_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partial_product>`_ |
98
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
99
+ | Summarizing | `ilen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.ilen>`_, |
100
+ | | `unique_to_each <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_to_each>`_, |
101
+ | | `sample <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sample>`_, |
102
+ | | `consecutive_groups <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups>`_, |
103
+ | | `run_length <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.run_length>`_, |
104
+ | | `map_reduce <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_reduce>`_, |
105
+ | | `join_mappings <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.join_mappings>`_, |
106
+ | | `exactly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.exactly_n>`_, |
107
+ | | `is_sorted <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.is_sorted>`_, |
108
+ | | `all_equal <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_equal>`_, |
109
+ | | `all_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.all_unique>`_, |
110
+ | | `argmin <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.argmin>`_, |
111
+ | | `argmax <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.argmax>`_, |
112
+ | | `minmax <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.minmax>`_, |
113
+ | | `first_true <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first_true>`_, |
114
+ | | `quantify <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.quantify>`_, |
115
+ | | `iequals <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iequals>`_ |
116
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
117
+ | Selecting | `islice_extended <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.islice_extended>`_, |
118
+ | | `first <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first>`_, |
119
+ | | `last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.last>`_, |
120
+ | | `one <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one>`_, |
121
+ | | `only <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.only>`_, |
122
+ | | `strictly_n <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strictly_n>`_, |
123
+ | | `strip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.strip>`_, |
124
+ | | `lstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.lstrip>`_, |
125
+ | | `rstrip <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rstrip>`_, |
126
+ | | `filter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_except>`_, |
127
+ | | `map_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_except>`_, |
128
+ | | `filter_map <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.filter_map>`_, |
129
+ | | `iter_suppress <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_suppress>`_, |
130
+ | | `nth_or_last <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_or_last>`_, |
131
+ | | `extract <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.extract>`_, |
132
+ | | `unique_in_window <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_in_window>`_, |
133
+ | | `before_and_after <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.before_and_after>`_, |
134
+ | | `nth <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth>`_, |
135
+ | | `take <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.take>`_, |
136
+ | | `tail <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tail>`_, |
137
+ | | `unique_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_everseen>`_, |
138
+ | | `unique_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_justseen>`_, |
139
+ | | `unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique>`_, |
140
+ | | `duplicates_everseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_everseen>`_, |
141
+ | | `duplicates_justseen <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.duplicates_justseen>`_, |
142
+ | | `classify_unique <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.classify_unique>`_, |
143
+ | | `longest_common_prefix <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.longest_common_prefix>`_, |
144
+ | | `takewhile_inclusive <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.takewhile_inclusive>`_ |
145
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
146
+ | Math | `dft <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.dft>`_, |
147
+ | | `idft <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.idft>`_, |
148
+ | | `convolve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.convolve>`_, |
149
+ | | `dotproduct <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.dotproduct>`_, |
150
+ | | `matmul <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.matmul>`_, |
151
+ | | `polynomial_from_roots <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_from_roots>`_, |
152
+ | | `polynomial_derivative <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_derivative>`_, |
153
+ | | `polynomial_eval <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.polynomial_eval>`_, |
154
+ | | `sum_of_squares <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sum_of_squares>`_, |
155
+ | | `running_median <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.running_median>`_, |
156
+ | | `totient <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.totient>`_ |
157
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
158
+ | Integer math | `factor <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.factor>`_, |
159
+ | | `is_prime <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.is_prime>`_, |
160
+ | | `multinomial <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.multinomial>`_, |
161
+ | | `nth_prime <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_prime>`_, |
162
+ | | `sieve <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.sieve>`_ |
163
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
164
+ | Combinatorics | `circular_shifts <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.circular_shifts>`_, |
165
+ | | `derangements <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.derangements>`_, |
166
+ | | `gray_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.gray_product>`_, |
167
+ | | `outer_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.outer_product>`_, |
168
+ | | `partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.partitions>`_, |
169
+ | | `set_partitions <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.set_partitions>`_, |
170
+ | | `powerset <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.powerset>`_, |
171
+ | | `powerset_of_sets <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.powerset_of_sets>`_ |
172
+ | +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
173
+ | | `distinct_combinations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_combinations>`_, |
174
+ | | `distinct_permutations <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_permutations>`_ |
175
+ | +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
176
+ | | `combination_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_index>`_, |
177
+ | | `combination_with_replacement_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.combination_with_replacement_index>`_, |
178
+ | | `permutation_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.permutation_index>`_, |
179
+ | | `product_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.product_index>`_ |
180
+ | +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
181
+ | | `nth_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination>`_, |
182
+ | | `nth_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_combination_with_replacement>`_, |
183
+ | | `nth_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_permutation>`_, |
184
+ | | `nth_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.nth_product>`_ |
185
+ | +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
186
+ | | `random_combination <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination>`_, |
187
+ | | `random_combination_with_replacement <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_combination_with_replacement>`_, |
188
+ | | `random_permutation <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_permutation>`_, |
189
+ | | `random_product <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.random_product>`_ |
190
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
191
+ | Wrapping | `always_iterable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable>`_, |
192
+ | | `always_reversible <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_reversible>`_, |
193
+ | | `countable <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.countable>`_, |
194
+ | | `consumer <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consumer>`_, |
195
+ | | `with_iter <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.with_iter>`_, |
196
+ | | `iter_except <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_except>`_ |
197
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
198
+ | Others | `locate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.locate>`_, |
199
+ | | `rlocate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.rlocate>`_, |
200
+ | | `replace <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.replace>`_, |
201
+ | | `numeric_range <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.numeric_range>`_, |
202
+ | | `side_effect <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.side_effect>`_, |
203
+ | | `iterate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iterate>`_, |
204
+ | | `loops <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.loops>`_, |
205
+ | | `difference <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.difference>`_, |
206
+ | | `make_decorator <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.make_decorator>`_, |
207
+ | | `SequenceView <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.SequenceView>`_, |
208
+ | | `time_limited <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.time_limited>`_, |
209
+ | | `map_if <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.map_if>`_, |
210
+ | | `iter_index <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.iter_index>`_, |
211
+ | | `consume <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consume>`_, |
212
+ | | `tabulate <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.tabulate>`_, |
213
+ | | `repeatfunc <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.repeatfunc>`_, |
214
+ | | `reshape <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.reshape>`_, |
215
+ | | `doublestarmap <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.doublestarmap>`_ |
216
+ +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
217
+
218
+
219
+ Getting started
220
+ ===============
221
+
222
+ To get started, install the library with `pip <https://pip.pypa.io/en/stable/>`_:
223
+
224
+ .. code-block:: shell
225
+
226
+ pip install more-itertools
227
+
228
+ The recipes from the `itertools docs <https://docs.python.org/3/library/itertools.html#itertools-recipes>`_
229
+ are included in the top-level package:
230
+
231
+ .. code-block:: python
232
+
233
+ >>> from more_itertools import flatten
234
+ >>> iterable = [(0, 1), (2, 3)]
235
+ >>> list(flatten(iterable))
236
+ [0, 1, 2, 3]
237
+
238
+ Several new recipes are available as well:
239
+
240
+ .. code-block:: python
241
+
242
+ >>> from more_itertools import chunked
243
+ >>> iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8]
244
+ >>> list(chunked(iterable, 3))
245
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
246
+
247
+ >>> from more_itertools import spy
248
+ >>> iterable = (x * x for x in range(1, 6))
249
+ >>> head, iterable = spy(iterable, n=3)
250
+ >>> list(head)
251
+ [1, 4, 9]
252
+ >>> list(iterable)
253
+ [1, 4, 9, 16, 25]
254
+
255
+
256
+
257
+ For the full listing of functions, see the `API documentation <https://more-itertools.readthedocs.io/en/stable/api.html>`_.
258
+
259
+
260
+ Links elsewhere
261
+ ===============
262
+
263
+ Blog posts about ``more-itertools``:
264
+
265
+ * `Yo, I heard you like decorators <https://www.bbayles.com/index/decorator_factory>`__
266
+ * `Tour of Python Itertools <https://martinheinz.dev/blog/16>`__ (`Alternate <https://dev.to/martinheinz/tour-of-python-itertools-4122>`__)
267
+ * `Real-World Python More Itertools <https://python.plainenglish.io/real-world-more-itertools-gideons-blog-a3901c607550>`_
268
+
269
+
270
+ Development
271
+ ===========
272
+
273
+ ``more-itertools`` is maintained by `@erikrose <https://github.com/erikrose>`_
274
+ and `@bbayles <https://github.com/bbayles>`_, with help from `many others <https://github.com/more-itertools/more-itertools/graphs/contributors>`_.
275
+ If you have a problem or suggestion, please file a bug or pull request in this
276
+ repository. Thanks for contributing!
277
+
278
+
279
+ Version History
280
+ ===============
281
+
282
+ The version history can be found in `documentation <https://more-itertools.readthedocs.io/en/stable/versions.html>`_.
283
+
python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ more_itertools-10.8.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ more_itertools-10.8.0.dist-info/METADATA,sha256=arNRUUWr5YsGfwh8hnYxz0z11lP-2BuWQu4SCGw5BLg,39413
3
+ more_itertools-10.8.0.dist-info/RECORD,,
4
+ more_itertools-10.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ more_itertools-10.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
6
+ more_itertools-10.8.0.dist-info/licenses/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053
7
+ more_itertools/__init__.py,sha256=5F7E_zpoGcEBW_T_3WE0WYYt8j-gJodIuiBcOJxrOv8,149
8
+ more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43
9
+ more_itertools/more.py,sha256=mNPKKu5UI7lRL460vgm0QTCWFiGMVCMosSPxVSdibos,163690
10
+ more_itertools/more.pyi,sha256=fpEgNX3O66wY5cnT-s5VYDKNUpAcaCyU3iP84It3OOM,27119
11
+ more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ more_itertools/recipes.py,sha256=Ma-kuBNZDFhaQDbIJgRmnrG86WzaupbOyUV3v8je3xw,41811
13
+ more_itertools/recipes.pyi,sha256=LNRwN-OL3nkMfQAqx-PPc1fBaetUObb_Z6mdePyzh1c,6226
python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED ADDED
File without changes
python/Lib/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
python/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """More routines for operating on iterables, beyond itertools"""
2
+
3
+ from .more import * # noqa
4
+ from .recipes import * # noqa
5
+
6
+ __version__ = '10.8.0'
python/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.pyi ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .more import *
2
+ from .recipes import *
python/Lib/site-packages/setuptools/_vendor/more_itertools/py.typed ADDED
File without changes
python/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.py ADDED
@@ -0,0 +1,1471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Imported from the recipes section of the itertools documentation.
2
+
3
+ All functions taken from the recipes section of the itertools library docs
4
+ [1]_.
5
+ Some backward-compatible usability improvements have been made.
6
+
7
+ .. [1] http://docs.python.org/library/itertools.html#recipes
8
+
9
+ """
10
+
11
+ import random
12
+
13
+ from bisect import bisect_left, insort
14
+ from collections import deque
15
+ from contextlib import suppress
16
+ from functools import lru_cache, partial, reduce
17
+ from heapq import heappush, heappushpop
18
+ from itertools import (
19
+ accumulate,
20
+ chain,
21
+ combinations,
22
+ compress,
23
+ count,
24
+ cycle,
25
+ groupby,
26
+ islice,
27
+ product,
28
+ repeat,
29
+ starmap,
30
+ takewhile,
31
+ tee,
32
+ zip_longest,
33
+ )
34
+ from math import prod, comb, isqrt, gcd
35
+ from operator import mul, not_, itemgetter, getitem, index
36
+ from random import randrange, sample, choice
37
+ from sys import hexversion
38
+
39
+ __all__ = [
40
+ 'all_equal',
41
+ 'batched',
42
+ 'before_and_after',
43
+ 'consume',
44
+ 'convolve',
45
+ 'dotproduct',
46
+ 'first_true',
47
+ 'factor',
48
+ 'flatten',
49
+ 'grouper',
50
+ 'is_prime',
51
+ 'iter_except',
52
+ 'iter_index',
53
+ 'loops',
54
+ 'matmul',
55
+ 'multinomial',
56
+ 'ncycles',
57
+ 'nth',
58
+ 'nth_combination',
59
+ 'padnone',
60
+ 'pad_none',
61
+ 'pairwise',
62
+ 'partition',
63
+ 'polynomial_eval',
64
+ 'polynomial_from_roots',
65
+ 'polynomial_derivative',
66
+ 'powerset',
67
+ 'prepend',
68
+ 'quantify',
69
+ 'reshape',
70
+ 'random_combination_with_replacement',
71
+ 'random_combination',
72
+ 'random_permutation',
73
+ 'random_product',
74
+ 'repeatfunc',
75
+ 'roundrobin',
76
+ 'running_median',
77
+ 'sieve',
78
+ 'sliding_window',
79
+ 'subslices',
80
+ 'sum_of_squares',
81
+ 'tabulate',
82
+ 'tail',
83
+ 'take',
84
+ 'totient',
85
+ 'transpose',
86
+ 'triplewise',
87
+ 'unique',
88
+ 'unique_everseen',
89
+ 'unique_justseen',
90
+ ]
91
+
92
+ _marker = object()
93
+
94
+
95
+ # zip with strict is available for Python 3.10+
96
+ try:
97
+ zip(strict=True)
98
+ except TypeError: # pragma: no cover
99
+ _zip_strict = zip
100
+ else: # pragma: no cover
101
+ _zip_strict = partial(zip, strict=True)
102
+
103
+
104
+ # math.sumprod is available for Python 3.12+
105
+ try:
106
+ from math import sumprod as _sumprod
107
+ except ImportError: # pragma: no cover
108
+ _sumprod = lambda x, y: dotproduct(x, y)
109
+
110
+
111
+ # heapq max-heap functions are available for Python 3.14+
112
+ try:
113
+ from heapq import heappush_max, heappushpop_max
114
+ except ImportError: # pragma: no cover
115
+ _max_heap_available = False
116
+ else: # pragma: no cover
117
+ _max_heap_available = True
118
+
119
+
120
+ def take(n, iterable):
121
+ """Return first *n* items of the *iterable* as a list.
122
+
123
+ >>> take(3, range(10))
124
+ [0, 1, 2]
125
+
126
+ If there are fewer than *n* items in the iterable, all of them are
127
+ returned.
128
+
129
+ >>> take(10, range(3))
130
+ [0, 1, 2]
131
+
132
+ """
133
+ return list(islice(iterable, n))
134
+
135
+
136
+ def tabulate(function, start=0):
137
+ """Return an iterator over the results of ``func(start)``,
138
+ ``func(start + 1)``, ``func(start + 2)``...
139
+
140
+ *func* should be a function that accepts one integer argument.
141
+
142
+ If *start* is not specified it defaults to 0. It will be incremented each
143
+ time the iterator is advanced.
144
+
145
+ >>> square = lambda x: x ** 2
146
+ >>> iterator = tabulate(square, -3)
147
+ >>> take(4, iterator)
148
+ [9, 4, 1, 0]
149
+
150
+ """
151
+ return map(function, count(start))
152
+
153
+
154
+ def tail(n, iterable):
155
+ """Return an iterator over the last *n* items of *iterable*.
156
+
157
+ >>> t = tail(3, 'ABCDEFG')
158
+ >>> list(t)
159
+ ['E', 'F', 'G']
160
+
161
+ """
162
+ try:
163
+ size = len(iterable)
164
+ except TypeError:
165
+ return iter(deque(iterable, maxlen=n))
166
+ else:
167
+ return islice(iterable, max(0, size - n), None)
168
+
169
+
170
+ def consume(iterator, n=None):
171
+ """Advance *iterable* by *n* steps. If *n* is ``None``, consume it
172
+ entirely.
173
+
174
+ Efficiently exhausts an iterator without returning values. Defaults to
175
+ consuming the whole iterator, but an optional second argument may be
176
+ provided to limit consumption.
177
+
178
+ >>> i = (x for x in range(10))
179
+ >>> next(i)
180
+ 0
181
+ >>> consume(i, 3)
182
+ >>> next(i)
183
+ 4
184
+ >>> consume(i)
185
+ >>> next(i)
186
+ Traceback (most recent call last):
187
+ File "<stdin>", line 1, in <module>
188
+ StopIteration
189
+
190
+ If the iterator has fewer items remaining than the provided limit, the
191
+ whole iterator will be consumed.
192
+
193
+ >>> i = (x for x in range(3))
194
+ >>> consume(i, 5)
195
+ >>> next(i)
196
+ Traceback (most recent call last):
197
+ File "<stdin>", line 1, in <module>
198
+ StopIteration
199
+
200
+ """
201
+ # Use functions that consume iterators at C speed.
202
+ if n is None:
203
+ # feed the entire iterator into a zero-length deque
204
+ deque(iterator, maxlen=0)
205
+ else:
206
+ # advance to the empty slice starting at position n
207
+ next(islice(iterator, n, n), None)
208
+
209
+
210
+ def nth(iterable, n, default=None):
211
+ """Returns the nth item or a default value.
212
+
213
+ >>> l = range(10)
214
+ >>> nth(l, 3)
215
+ 3
216
+ >>> nth(l, 20, "zebra")
217
+ 'zebra'
218
+
219
+ """
220
+ return next(islice(iterable, n, None), default)
221
+
222
+
223
+ def all_equal(iterable, key=None):
224
+ """
225
+ Returns ``True`` if all the elements are equal to each other.
226
+
227
+ >>> all_equal('aaaa')
228
+ True
229
+ >>> all_equal('aaab')
230
+ False
231
+
232
+ A function that accepts a single argument and returns a transformed version
233
+ of each input item can be specified with *key*:
234
+
235
+ >>> all_equal('AaaA', key=str.casefold)
236
+ True
237
+ >>> all_equal([1, 2, 3], key=lambda x: x < 10)
238
+ True
239
+
240
+ """
241
+ iterator = groupby(iterable, key)
242
+ for first in iterator:
243
+ for second in iterator:
244
+ return False
245
+ return True
246
+ return True
247
+
248
+
249
+ def quantify(iterable, pred=bool):
250
+ """Return the how many times the predicate is true.
251
+
252
+ >>> quantify([True, False, True])
253
+ 2
254
+
255
+ """
256
+ return sum(map(pred, iterable))
257
+
258
+
259
+ def pad_none(iterable):
260
+ """Returns the sequence of elements and then returns ``None`` indefinitely.
261
+
262
+ >>> take(5, pad_none(range(3)))
263
+ [0, 1, 2, None, None]
264
+
265
+ Useful for emulating the behavior of the built-in :func:`map` function.
266
+
267
+ See also :func:`padded`.
268
+
269
+ """
270
+ return chain(iterable, repeat(None))
271
+
272
+
273
+ padnone = pad_none
274
+
275
+
276
+ def ncycles(iterable, n):
277
+ """Returns the sequence elements *n* times
278
+
279
+ >>> list(ncycles(["a", "b"], 3))
280
+ ['a', 'b', 'a', 'b', 'a', 'b']
281
+
282
+ """
283
+ return chain.from_iterable(repeat(tuple(iterable), n))
284
+
285
+
286
+ def dotproduct(vec1, vec2):
287
+ """Returns the dot product of the two iterables.
288
+
289
+ >>> dotproduct([10, 15, 12], [0.65, 0.80, 1.25])
290
+ 33.5
291
+ >>> 10 * 0.65 + 15 * 0.80 + 12 * 1.25
292
+ 33.5
293
+
294
+ In Python 3.12 and later, use ``math.sumprod()`` instead.
295
+ """
296
+ return sum(map(mul, vec1, vec2))
297
+
298
+
299
+ def flatten(listOfLists):
300
+ """Return an iterator flattening one level of nesting in a list of lists.
301
+
302
+ >>> list(flatten([[0, 1], [2, 3]]))
303
+ [0, 1, 2, 3]
304
+
305
+ See also :func:`collapse`, which can flatten multiple levels of nesting.
306
+
307
+ """
308
+ return chain.from_iterable(listOfLists)
309
+
310
+
311
+ def repeatfunc(func, times=None, *args):
312
+ """Call *func* with *args* repeatedly, returning an iterable over the
313
+ results.
314
+
315
+ If *times* is specified, the iterable will terminate after that many
316
+ repetitions:
317
+
318
+ >>> from operator import add
319
+ >>> times = 4
320
+ >>> args = 3, 5
321
+ >>> list(repeatfunc(add, times, *args))
322
+ [8, 8, 8, 8]
323
+
324
+ If *times* is ``None`` the iterable will not terminate:
325
+
326
+ >>> from random import randrange
327
+ >>> times = None
328
+ >>> args = 1, 11
329
+ >>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP
330
+ [2, 4, 8, 1, 8, 4]
331
+
332
+ """
333
+ if times is None:
334
+ return starmap(func, repeat(args))
335
+ return starmap(func, repeat(args, times))
336
+
337
+
338
+ def _pairwise(iterable):
339
+ """Returns an iterator of paired items, overlapping, from the original
340
+
341
+ >>> take(4, pairwise(count()))
342
+ [(0, 1), (1, 2), (2, 3), (3, 4)]
343
+
344
+ On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`.
345
+
346
+ """
347
+ a, b = tee(iterable)
348
+ next(b, None)
349
+ return zip(a, b)
350
+
351
+
352
+ try:
353
+ from itertools import pairwise as itertools_pairwise
354
+ except ImportError: # pragma: no cover
355
+ pairwise = _pairwise
356
+ else: # pragma: no cover
357
+
358
+ def pairwise(iterable):
359
+ return itertools_pairwise(iterable)
360
+
361
+ pairwise.__doc__ = _pairwise.__doc__
362
+
363
+
364
+ class UnequalIterablesError(ValueError):
365
+ def __init__(self, details=None):
366
+ msg = 'Iterables have different lengths'
367
+ if details is not None:
368
+ msg += (': index 0 has length {}; index {} has length {}').format(
369
+ *details
370
+ )
371
+
372
+ super().__init__(msg)
373
+
374
+
375
+ def _zip_equal_generator(iterables):
376
+ for combo in zip_longest(*iterables, fillvalue=_marker):
377
+ for val in combo:
378
+ if val is _marker:
379
+ raise UnequalIterablesError()
380
+ yield combo
381
+
382
+
383
+ def _zip_equal(*iterables):
384
+ # Check whether the iterables are all the same size.
385
+ try:
386
+ first_size = len(iterables[0])
387
+ for i, it in enumerate(iterables[1:], 1):
388
+ size = len(it)
389
+ if size != first_size:
390
+ raise UnequalIterablesError(details=(first_size, i, size))
391
+ # All sizes are equal, we can use the built-in zip.
392
+ return zip(*iterables)
393
+ # If any one of the iterables didn't have a length, start reading
394
+ # them until one runs out.
395
+ except TypeError:
396
+ return _zip_equal_generator(iterables)
397
+
398
+
399
+ def grouper(iterable, n, incomplete='fill', fillvalue=None):
400
+ """Group elements from *iterable* into fixed-length groups of length *n*.
401
+
402
+ >>> list(grouper('ABCDEF', 3))
403
+ [('A', 'B', 'C'), ('D', 'E', 'F')]
404
+
405
+ The keyword arguments *incomplete* and *fillvalue* control what happens for
406
+ iterables whose length is not a multiple of *n*.
407
+
408
+ When *incomplete* is `'fill'`, the last group will contain instances of
409
+ *fillvalue*.
410
+
411
+ >>> list(grouper('ABCDEFG', 3, incomplete='fill', fillvalue='x'))
412
+ [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
413
+
414
+ When *incomplete* is `'ignore'`, the last group will not be emitted.
415
+
416
+ >>> list(grouper('ABCDEFG', 3, incomplete='ignore', fillvalue='x'))
417
+ [('A', 'B', 'C'), ('D', 'E', 'F')]
418
+
419
+ When *incomplete* is `'strict'`, a subclass of `ValueError` will be raised.
420
+
421
+ >>> iterator = grouper('ABCDEFG', 3, incomplete='strict')
422
+ >>> list(iterator) # doctest: +IGNORE_EXCEPTION_DETAIL
423
+ Traceback (most recent call last):
424
+ ...
425
+ UnequalIterablesError
426
+
427
+ """
428
+ iterators = [iter(iterable)] * n
429
+ if incomplete == 'fill':
430
+ return zip_longest(*iterators, fillvalue=fillvalue)
431
+ if incomplete == 'strict':
432
+ return _zip_equal(*iterators)
433
+ if incomplete == 'ignore':
434
+ return zip(*iterators)
435
+ else:
436
+ raise ValueError('Expected fill, strict, or ignore')
437
+
438
+
439
+ def roundrobin(*iterables):
440
+ """Visit input iterables in a cycle until each is exhausted.
441
+
442
+ >>> list(roundrobin('ABC', 'D', 'EF'))
443
+ ['A', 'D', 'E', 'B', 'F', 'C']
444
+
445
+ This function produces the same output as :func:`interleave_longest`, but
446
+ may perform better for some inputs (in particular when the number of
447
+ iterables is small).
448
+
449
+ """
450
+ # Algorithm credited to George Sakkis
451
+ iterators = map(iter, iterables)
452
+ for num_active in range(len(iterables), 0, -1):
453
+ iterators = cycle(islice(iterators, num_active))
454
+ yield from map(next, iterators)
455
+
456
+
457
+ def partition(pred, iterable):
458
+ """
459
+ Returns a 2-tuple of iterables derived from the input iterable.
460
+ The first yields the items that have ``pred(item) == False``.
461
+ The second yields the items that have ``pred(item) == True``.
462
+
463
+ >>> is_odd = lambda x: x % 2 != 0
464
+ >>> iterable = range(10)
465
+ >>> even_items, odd_items = partition(is_odd, iterable)
466
+ >>> list(even_items), list(odd_items)
467
+ ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
468
+
469
+ If *pred* is None, :func:`bool` is used.
470
+
471
+ >>> iterable = [0, 1, False, True, '', ' ']
472
+ >>> false_items, true_items = partition(None, iterable)
473
+ >>> list(false_items), list(true_items)
474
+ ([0, False, ''], [1, True, ' '])
475
+
476
+ """
477
+ if pred is None:
478
+ pred = bool
479
+
480
+ t1, t2, p = tee(iterable, 3)
481
+ p1, p2 = tee(map(pred, p))
482
+ return (compress(t1, map(not_, p1)), compress(t2, p2))
483
+
484
+
485
+ def powerset(iterable):
486
+ """Yields all possible subsets of the iterable.
487
+
488
+ >>> list(powerset([1, 2, 3]))
489
+ [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
490
+
491
+ :func:`powerset` will operate on iterables that aren't :class:`set`
492
+ instances, so repeated elements in the input will produce repeated elements
493
+ in the output.
494
+
495
+ >>> seq = [1, 1, 0]
496
+ >>> list(powerset(seq))
497
+ [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]
498
+
499
+ For a variant that efficiently yields actual :class:`set` instances, see
500
+ :func:`powerset_of_sets`.
501
+ """
502
+ s = list(iterable)
503
+ return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
504
+
505
+
506
+ def unique_everseen(iterable, key=None):
507
+ """
508
+ Yield unique elements, preserving order.
509
+
510
+ >>> list(unique_everseen('AAAABBBCCDAABBB'))
511
+ ['A', 'B', 'C', 'D']
512
+ >>> list(unique_everseen('ABBCcAD', str.lower))
513
+ ['A', 'B', 'C', 'D']
514
+
515
+ Sequences with a mix of hashable and unhashable items can be used.
516
+ The function will be slower (i.e., `O(n^2)`) for unhashable items.
517
+
518
+ Remember that ``list`` objects are unhashable - you can use the *key*
519
+ parameter to transform the list to a tuple (which is hashable) to
520
+ avoid a slowdown.
521
+
522
+ >>> iterable = ([1, 2], [2, 3], [1, 2])
523
+ >>> list(unique_everseen(iterable)) # Slow
524
+ [[1, 2], [2, 3]]
525
+ >>> list(unique_everseen(iterable, key=tuple)) # Faster
526
+ [[1, 2], [2, 3]]
527
+
528
+ Similarly, you may want to convert unhashable ``set`` objects with
529
+ ``key=frozenset``. For ``dict`` objects,
530
+ ``key=lambda x: frozenset(x.items())`` can be used.
531
+
532
+ """
533
+ seenset = set()
534
+ seenset_add = seenset.add
535
+ seenlist = []
536
+ seenlist_add = seenlist.append
537
+ use_key = key is not None
538
+
539
+ for element in iterable:
540
+ k = key(element) if use_key else element
541
+ try:
542
+ if k not in seenset:
543
+ seenset_add(k)
544
+ yield element
545
+ except TypeError:
546
+ if k not in seenlist:
547
+ seenlist_add(k)
548
+ yield element
549
+
550
+
551
+ def unique_justseen(iterable, key=None):
552
+ """Yields elements in order, ignoring serial duplicates
553
+
554
+ >>> list(unique_justseen('AAAABBBCCDAABBB'))
555
+ ['A', 'B', 'C', 'D', 'A', 'B']
556
+ >>> list(unique_justseen('ABBCcAD', str.lower))
557
+ ['A', 'B', 'C', 'A', 'D']
558
+
559
+ """
560
+ if key is None:
561
+ return map(itemgetter(0), groupby(iterable))
562
+
563
+ return map(next, map(itemgetter(1), groupby(iterable, key)))
564
+
565
+
566
+ def unique(iterable, key=None, reverse=False):
567
+ """Yields unique elements in sorted order.
568
+
569
+ >>> list(unique([[1, 2], [3, 4], [1, 2]]))
570
+ [[1, 2], [3, 4]]
571
+
572
+ *key* and *reverse* are passed to :func:`sorted`.
573
+
574
+ >>> list(unique('ABBcCAD', str.casefold))
575
+ ['A', 'B', 'c', 'D']
576
+ >>> list(unique('ABBcCAD', str.casefold, reverse=True))
577
+ ['D', 'c', 'B', 'A']
578
+
579
+ The elements in *iterable* need not be hashable, but they must be
580
+ comparable for sorting to work.
581
+ """
582
+ sequenced = sorted(iterable, key=key, reverse=reverse)
583
+ return unique_justseen(sequenced, key=key)
584
+
585
+
586
+ def iter_except(func, exception, first=None):
587
+ """Yields results from a function repeatedly until an exception is raised.
588
+
589
+ Converts a call-until-exception interface to an iterator interface.
590
+ Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel
591
+ to end the loop.
592
+
593
+ >>> l = [0, 1, 2]
594
+ >>> list(iter_except(l.pop, IndexError))
595
+ [2, 1, 0]
596
+
597
+ Multiple exceptions can be specified as a stopping condition:
598
+
599
+ >>> l = [1, 2, 3, '...', 4, 5, 6]
600
+ >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
601
+ [7, 6, 5]
602
+ >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
603
+ [4, 3, 2]
604
+ >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))
605
+ []
606
+
607
+ """
608
+ with suppress(exception):
609
+ if first is not None:
610
+ yield first()
611
+ while True:
612
+ yield func()
613
+
614
+
615
+ def first_true(iterable, default=None, pred=None):
616
+ """
617
+ Returns the first true value in the iterable.
618
+
619
+ If no true value is found, returns *default*
620
+
621
+ If *pred* is not None, returns the first item for which
622
+ ``pred(item) == True`` .
623
+
624
+ >>> first_true(range(10))
625
+ 1
626
+ >>> first_true(range(10), pred=lambda x: x > 5)
627
+ 6
628
+ >>> first_true(range(10), default='missing', pred=lambda x: x > 9)
629
+ 'missing'
630
+
631
+ """
632
+ return next(filter(pred, iterable), default)
633
+
634
+
635
+ def random_product(*args, repeat=1):
636
+ """Draw an item at random from each of the input iterables.
637
+
638
+ >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP
639
+ ('c', 3, 'Z')
640
+
641
+ If *repeat* is provided as a keyword argument, that many items will be
642
+ drawn from each iterable.
643
+
644
+ >>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP
645
+ ('a', 2, 'd', 3)
646
+
647
+ This equivalent to taking a random selection from
648
+ ``itertools.product(*args, repeat=repeat)``.
649
+
650
+ """
651
+ pools = [tuple(pool) for pool in args] * repeat
652
+ return tuple(choice(pool) for pool in pools)
653
+
654
+
655
+ def random_permutation(iterable, r=None):
656
+ """Return a random *r* length permutation of the elements in *iterable*.
657
+
658
+ If *r* is not specified or is ``None``, then *r* defaults to the length of
659
+ *iterable*.
660
+
661
+ >>> random_permutation(range(5)) # doctest:+SKIP
662
+ (3, 4, 0, 1, 2)
663
+
664
+ This equivalent to taking a random selection from
665
+ ``itertools.permutations(iterable, r)``.
666
+
667
+ """
668
+ pool = tuple(iterable)
669
+ r = len(pool) if r is None else r
670
+ return tuple(sample(pool, r))
671
+
672
+
673
+ def random_combination(iterable, r):
674
+ """Return a random *r* length subsequence of the elements in *iterable*.
675
+
676
+ >>> random_combination(range(5), 3) # doctest:+SKIP
677
+ (2, 3, 4)
678
+
679
+ This equivalent to taking a random selection from
680
+ ``itertools.combinations(iterable, r)``.
681
+
682
+ """
683
+ pool = tuple(iterable)
684
+ n = len(pool)
685
+ indices = sorted(sample(range(n), r))
686
+ return tuple(pool[i] for i in indices)
687
+
688
+
689
+ def random_combination_with_replacement(iterable, r):
690
+ """Return a random *r* length subsequence of elements in *iterable*,
691
+ allowing individual elements to be repeated.
692
+
693
+ >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP
694
+ (0, 0, 1, 2, 2)
695
+
696
+ This equivalent to taking a random selection from
697
+ ``itertools.combinations_with_replacement(iterable, r)``.
698
+
699
+ """
700
+ pool = tuple(iterable)
701
+ n = len(pool)
702
+ indices = sorted(randrange(n) for i in range(r))
703
+ return tuple(pool[i] for i in indices)
704
+
705
+
706
+ def nth_combination(iterable, r, index):
707
+ """Equivalent to ``list(combinations(iterable, r))[index]``.
708
+
709
+ The subsequences of *iterable* that are of length *r* can be ordered
710
+ lexicographically. :func:`nth_combination` computes the subsequence at
711
+ sort position *index* directly, without computing the previous
712
+ subsequences.
713
+
714
+ >>> nth_combination(range(5), 3, 5)
715
+ (0, 3, 4)
716
+
717
+ ``ValueError`` will be raised If *r* is negative or greater than the length
718
+ of *iterable*.
719
+ ``IndexError`` will be raised if the given *index* is invalid.
720
+ """
721
+ pool = tuple(iterable)
722
+ n = len(pool)
723
+ if (r < 0) or (r > n):
724
+ raise ValueError
725
+
726
+ c = 1
727
+ k = min(r, n - r)
728
+ for i in range(1, k + 1):
729
+ c = c * (n - k + i) // i
730
+
731
+ if index < 0:
732
+ index += c
733
+
734
+ if (index < 0) or (index >= c):
735
+ raise IndexError
736
+
737
+ result = []
738
+ while r:
739
+ c, n, r = c * r // n, n - 1, r - 1
740
+ while index >= c:
741
+ index -= c
742
+ c, n = c * (n - r) // n, n - 1
743
+ result.append(pool[-1 - n])
744
+
745
+ return tuple(result)
746
+
747
+
748
+ def prepend(value, iterator):
749
+ """Yield *value*, followed by the elements in *iterator*.
750
+
751
+ >>> value = '0'
752
+ >>> iterator = ['1', '2', '3']
753
+ >>> list(prepend(value, iterator))
754
+ ['0', '1', '2', '3']
755
+
756
+ To prepend multiple values, see :func:`itertools.chain`
757
+ or :func:`value_chain`.
758
+
759
+ """
760
+ return chain([value], iterator)
761
+
762
+
763
+ def convolve(signal, kernel):
764
+ """Discrete linear convolution of two iterables.
765
+ Equivalent to polynomial multiplication.
766
+
767
+ For example, multiplying ``(x² -x - 20)`` by ``(x - 3)``
768
+ gives ``(x³ -4x² -17x + 60)``.
769
+
770
+ >>> list(convolve([1, -1, -20], [1, -3]))
771
+ [1, -4, -17, 60]
772
+
773
+ Examples of popular kinds of kernels:
774
+
775
+ * The kernel ``[0.25, 0.25, 0.25, 0.25]`` computes a moving average.
776
+ For image data, this blurs the image and reduces noise.
777
+ * The kernel ``[1/2, 0, -1/2]`` estimates the first derivative of
778
+ a function evaluated at evenly spaced inputs.
779
+ * The kernel ``[1, -2, 1]`` estimates the second derivative of a
780
+ function evaluated at evenly spaced inputs.
781
+
782
+ Convolutions are mathematically commutative; however, the inputs are
783
+ evaluated differently. The signal is consumed lazily and can be
784
+ infinite. The kernel is fully consumed before the calculations begin.
785
+
786
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
787
+
788
+ References:
789
+
790
+ * Article: https://betterexplained.com/articles/intuitive-convolution/
791
+ * Video by 3Blue1Brown: https://www.youtube.com/watch?v=KuXjwB4LzSA
792
+
793
+ """
794
+ # This implementation comes from an older version of the itertools
795
+ # documentation. While the newer implementation is a bit clearer,
796
+ # this one was kept because the inlined window logic is faster
797
+ # and it avoids an unnecessary deque-to-tuple conversion.
798
+ kernel = tuple(kernel)[::-1]
799
+ n = len(kernel)
800
+ window = deque([0], maxlen=n) * n
801
+ for x in chain(signal, repeat(0, n - 1)):
802
+ window.append(x)
803
+ yield _sumprod(kernel, window)
804
+
805
+
806
+ def before_and_after(predicate, it):
807
+ """A variant of :func:`takewhile` that allows complete access to the
808
+ remainder of the iterator.
809
+
810
+ >>> it = iter('ABCdEfGhI')
811
+ >>> all_upper, remainder = before_and_after(str.isupper, it)
812
+ >>> ''.join(all_upper)
813
+ 'ABC'
814
+ >>> ''.join(remainder) # takewhile() would lose the 'd'
815
+ 'dEfGhI'
816
+
817
+ Note that the first iterator must be fully consumed before the second
818
+ iterator can generate valid results.
819
+ """
820
+ trues, after = tee(it)
821
+ trues = compress(takewhile(predicate, trues), zip(after))
822
+ return trues, after
823
+
824
+
825
+ def triplewise(iterable):
826
+ """Return overlapping triplets from *iterable*.
827
+
828
+ >>> list(triplewise('ABCDE'))
829
+ [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')]
830
+
831
+ """
832
+ # This deviates from the itertools documentation recipe - see
833
+ # https://github.com/more-itertools/more-itertools/issues/889
834
+ t1, t2, t3 = tee(iterable, 3)
835
+ next(t3, None)
836
+ next(t3, None)
837
+ next(t2, None)
838
+ return zip(t1, t2, t3)
839
+
840
+
841
+ def _sliding_window_islice(iterable, n):
842
+ # Fast path for small, non-zero values of n.
843
+ iterators = tee(iterable, n)
844
+ for i, iterator in enumerate(iterators):
845
+ next(islice(iterator, i, i), None)
846
+ return zip(*iterators)
847
+
848
+
849
+ def _sliding_window_deque(iterable, n):
850
+ # Normal path for other values of n.
851
+ iterator = iter(iterable)
852
+ window = deque(islice(iterator, n - 1), maxlen=n)
853
+ for x in iterator:
854
+ window.append(x)
855
+ yield tuple(window)
856
+
857
+
858
+ def sliding_window(iterable, n):
859
+ """Return a sliding window of width *n* over *iterable*.
860
+
861
+ >>> list(sliding_window(range(6), 4))
862
+ [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)]
863
+
864
+ If *iterable* has fewer than *n* items, then nothing is yielded:
865
+
866
+ >>> list(sliding_window(range(3), 4))
867
+ []
868
+
869
+ For a variant with more features, see :func:`windowed`.
870
+ """
871
+ if n > 20:
872
+ return _sliding_window_deque(iterable, n)
873
+ elif n > 2:
874
+ return _sliding_window_islice(iterable, n)
875
+ elif n == 2:
876
+ return pairwise(iterable)
877
+ elif n == 1:
878
+ return zip(iterable)
879
+ else:
880
+ raise ValueError(f'n should be at least one, not {n}')
881
+
882
+
883
+ def subslices(iterable):
884
+ """Return all contiguous non-empty subslices of *iterable*.
885
+
886
+ >>> list(subslices('ABC'))
887
+ [['A'], ['A', 'B'], ['A', 'B', 'C'], ['B'], ['B', 'C'], ['C']]
888
+
889
+ This is similar to :func:`substrings`, but emits items in a different
890
+ order.
891
+ """
892
+ seq = list(iterable)
893
+ slices = starmap(slice, combinations(range(len(seq) + 1), 2))
894
+ return map(getitem, repeat(seq), slices)
895
+
896
+
897
+ def polynomial_from_roots(roots):
898
+ """Compute a polynomial's coefficients from its roots.
899
+
900
+ >>> roots = [5, -4, 3] # (x - 5) * (x + 4) * (x - 3)
901
+ >>> polynomial_from_roots(roots) # x³ - 4 x² - 17 x + 60
902
+ [1, -4, -17, 60]
903
+
904
+ Note that polynomial coefficients are specified in descending power order.
905
+
906
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
907
+ """
908
+
909
+ # This recipe differs from the one in itertools docs in that it
910
+ # applies list() after each call to convolve(). This avoids
911
+ # hitting stack limits with nested generators.
912
+
913
+ poly = [1]
914
+ for root in roots:
915
+ poly = list(convolve(poly, (1, -root)))
916
+ return poly
917
+
918
+
919
+ def iter_index(iterable, value, start=0, stop=None):
920
+ """Yield the index of each place in *iterable* that *value* occurs,
921
+ beginning with index *start* and ending before index *stop*.
922
+
923
+
924
+ >>> list(iter_index('AABCADEAF', 'A'))
925
+ [0, 1, 4, 7]
926
+ >>> list(iter_index('AABCADEAF', 'A', 1)) # start index is inclusive
927
+ [1, 4, 7]
928
+ >>> list(iter_index('AABCADEAF', 'A', 1, 7)) # stop index is not inclusive
929
+ [1, 4]
930
+
931
+ The behavior for non-scalar *values* matches the built-in Python types.
932
+
933
+ >>> list(iter_index('ABCDABCD', 'AB'))
934
+ [0, 4]
935
+ >>> list(iter_index([0, 1, 2, 3, 0, 1, 2, 3], [0, 1]))
936
+ []
937
+ >>> list(iter_index([[0, 1], [2, 3], [0, 1], [2, 3]], [0, 1]))
938
+ [0, 2]
939
+
940
+ See :func:`locate` for a more general means of finding the indexes
941
+ associated with particular values.
942
+
943
+ """
944
+ seq_index = getattr(iterable, 'index', None)
945
+ if seq_index is None:
946
+ # Slow path for general iterables
947
+ iterator = islice(iterable, start, stop)
948
+ for i, element in enumerate(iterator, start):
949
+ if element is value or element == value:
950
+ yield i
951
+ else:
952
+ # Fast path for sequences
953
+ stop = len(iterable) if stop is None else stop
954
+ i = start - 1
955
+ with suppress(ValueError):
956
+ while True:
957
+ yield (i := seq_index(value, i + 1, stop))
958
+
959
+
960
+ def sieve(n):
961
+ """Yield the primes less than n.
962
+
963
+ >>> list(sieve(30))
964
+ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
965
+
966
+ """
967
+ # This implementation comes from an older version of the itertools
968
+ # documentation. The newer implementation is easier to read but is
969
+ # less lazy.
970
+ if n > 2:
971
+ yield 2
972
+ start = 3
973
+ data = bytearray((0, 1)) * (n // 2)
974
+ for p in iter_index(data, 1, start, stop=isqrt(n) + 1):
975
+ yield from iter_index(data, 1, start, p * p)
976
+ data[p * p : n : p + p] = bytes(len(range(p * p, n, p + p)))
977
+ start = p * p
978
+ yield from iter_index(data, 1, start)
979
+
980
+
981
+ def _batched(iterable, n, *, strict=False): # pragma: no cover
982
+ """Batch data into tuples of length *n*. If the number of items in
983
+ *iterable* is not divisible by *n*:
984
+ * The last batch will be shorter if *strict* is ``False``.
985
+ * :exc:`ValueError` will be raised if *strict* is ``True``.
986
+
987
+ >>> list(batched('ABCDEFG', 3))
988
+ [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
989
+
990
+ On Python 3.13 and above, this is an alias for :func:`itertools.batched`.
991
+ """
992
+ if n < 1:
993
+ raise ValueError('n must be at least one')
994
+ iterator = iter(iterable)
995
+ while batch := tuple(islice(iterator, n)):
996
+ if strict and len(batch) != n:
997
+ raise ValueError('batched(): incomplete batch')
998
+ yield batch
999
+
1000
+
1001
+ if hexversion >= 0x30D00A2: # pragma: no cover
1002
+ from itertools import batched as itertools_batched
1003
+
1004
+ def batched(iterable, n, *, strict=False):
1005
+ return itertools_batched(iterable, n, strict=strict)
1006
+
1007
+ batched.__doc__ = _batched.__doc__
1008
+ else: # pragma: no cover
1009
+ batched = _batched
1010
+
1011
+
1012
+ def transpose(it):
1013
+ """Swap the rows and columns of the input matrix.
1014
+
1015
+ >>> list(transpose([(1, 2, 3), (11, 22, 33)]))
1016
+ [(1, 11), (2, 22), (3, 33)]
1017
+
1018
+ The caller should ensure that the dimensions of the input are compatible.
1019
+ If the input is empty, no output will be produced.
1020
+ """
1021
+ return _zip_strict(*it)
1022
+
1023
+
1024
+ def _is_scalar(value, stringlike=(str, bytes)):
1025
+ "Scalars are bytes, strings, and non-iterables."
1026
+ try:
1027
+ iter(value)
1028
+ except TypeError:
1029
+ return True
1030
+ return isinstance(value, stringlike)
1031
+
1032
+
1033
+ def _flatten_tensor(tensor):
1034
+ "Depth-first iterator over scalars in a tensor."
1035
+ iterator = iter(tensor)
1036
+ while True:
1037
+ try:
1038
+ value = next(iterator)
1039
+ except StopIteration:
1040
+ return iterator
1041
+ iterator = chain((value,), iterator)
1042
+ if _is_scalar(value):
1043
+ return iterator
1044
+ iterator = chain.from_iterable(iterator)
1045
+
1046
+
1047
+ def reshape(matrix, shape):
1048
+ """Change the shape of a *matrix*.
1049
+
1050
+ If *shape* is an integer, the matrix must be two dimensional
1051
+ and the shape is interpreted as the desired number of columns:
1052
+
1053
+ >>> matrix = [(0, 1), (2, 3), (4, 5)]
1054
+ >>> cols = 3
1055
+ >>> list(reshape(matrix, cols))
1056
+ [(0, 1, 2), (3, 4, 5)]
1057
+
1058
+ If *shape* is a tuple (or other iterable), the input matrix can have
1059
+ any number of dimensions. It will first be flattened and then rebuilt
1060
+ to the desired shape which can also be multidimensional:
1061
+
1062
+ >>> matrix = [(0, 1), (2, 3), (4, 5)] # Start with a 3 x 2 matrix
1063
+
1064
+ >>> list(reshape(matrix, (2, 3))) # Make a 2 x 3 matrix
1065
+ [(0, 1, 2), (3, 4, 5)]
1066
+
1067
+ >>> list(reshape(matrix, (6,))) # Make a vector of length six
1068
+ [0, 1, 2, 3, 4, 5]
1069
+
1070
+ >>> list(reshape(matrix, (2, 1, 3, 1))) # Make 2 x 1 x 3 x 1 tensor
1071
+ [(((0,), (1,), (2,)),), (((3,), (4,), (5,)),)]
1072
+
1073
+ Each dimension is assumed to be uniform, either all arrays or all scalars.
1074
+ Flattening stops when the first value in a dimension is a scalar.
1075
+ Scalars are bytes, strings, and non-iterables.
1076
+ The reshape iterator stops when the requested shape is complete
1077
+ or when the input is exhausted, whichever comes first.
1078
+
1079
+ """
1080
+ if isinstance(shape, int):
1081
+ return batched(chain.from_iterable(matrix), shape)
1082
+ first_dim, *dims = shape
1083
+ scalar_stream = _flatten_tensor(matrix)
1084
+ reshaped = reduce(batched, reversed(dims), scalar_stream)
1085
+ return islice(reshaped, first_dim)
1086
+
1087
+
1088
+ def matmul(m1, m2):
1089
+ """Multiply two matrices.
1090
+
1091
+ >>> list(matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]))
1092
+ [(49, 80), (41, 60)]
1093
+
1094
+ The caller should ensure that the dimensions of the input matrices are
1095
+ compatible with each other.
1096
+
1097
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
1098
+ """
1099
+ n = len(m2[0])
1100
+ return batched(starmap(_sumprod, product(m1, transpose(m2))), n)
1101
+
1102
+
1103
+ def _factor_pollard(n):
1104
+ # Return a factor of n using Pollard's rho algorithm.
1105
+ # Efficient when n is odd and composite.
1106
+ for b in range(1, n):
1107
+ x = y = 2
1108
+ d = 1
1109
+ while d == 1:
1110
+ x = (x * x + b) % n
1111
+ y = (y * y + b) % n
1112
+ y = (y * y + b) % n
1113
+ d = gcd(x - y, n)
1114
+ if d != n:
1115
+ return d
1116
+ raise ValueError('prime or under 5') # pragma: no cover
1117
+
1118
+
1119
+ _primes_below_211 = tuple(sieve(211))
1120
+
1121
+
1122
+ def factor(n):
1123
+ """Yield the prime factors of n.
1124
+
1125
+ >>> list(factor(360))
1126
+ [2, 2, 2, 3, 3, 5]
1127
+
1128
+ Finds small factors with trial division. Larger factors are
1129
+ either verified as prime with ``is_prime`` or split into
1130
+ smaller factors with Pollard's rho algorithm.
1131
+ """
1132
+
1133
+ # Corner case reduction
1134
+ if n < 2:
1135
+ return
1136
+
1137
+ # Trial division reduction
1138
+ for prime in _primes_below_211:
1139
+ while not n % prime:
1140
+ yield prime
1141
+ n //= prime
1142
+
1143
+ # Pollard's rho reduction
1144
+ primes = []
1145
+ todo = [n] if n > 1 else []
1146
+ for n in todo:
1147
+ if n < 211**2 or is_prime(n):
1148
+ primes.append(n)
1149
+ else:
1150
+ fact = _factor_pollard(n)
1151
+ todo += (fact, n // fact)
1152
+ yield from sorted(primes)
1153
+
1154
+
1155
+ def polynomial_eval(coefficients, x):
1156
+ """Evaluate a polynomial at a specific value.
1157
+
1158
+ Computes with better numeric stability than Horner's method.
1159
+
1160
+ Evaluate ``x^3 - 4 * x^2 - 17 * x + 60`` at ``x = 2.5``:
1161
+
1162
+ >>> coefficients = [1, -4, -17, 60]
1163
+ >>> x = 2.5
1164
+ >>> polynomial_eval(coefficients, x)
1165
+ 8.125
1166
+
1167
+ Note that polynomial coefficients are specified in descending power order.
1168
+
1169
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
1170
+ """
1171
+ n = len(coefficients)
1172
+ if n == 0:
1173
+ return type(x)(0)
1174
+ powers = map(pow, repeat(x), reversed(range(n)))
1175
+ return _sumprod(coefficients, powers)
1176
+
1177
+
1178
+ def sum_of_squares(it):
1179
+ """Return the sum of the squares of the input values.
1180
+
1181
+ >>> sum_of_squares([10, 20, 30])
1182
+ 1400
1183
+
1184
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
1185
+ """
1186
+ return _sumprod(*tee(it))
1187
+
1188
+
1189
+ def polynomial_derivative(coefficients):
1190
+ """Compute the first derivative of a polynomial.
1191
+
1192
+ Evaluate the derivative of ``x³ - 4 x² - 17 x + 60``:
1193
+
1194
+ >>> coefficients = [1, -4, -17, 60]
1195
+ >>> derivative_coefficients = polynomial_derivative(coefficients)
1196
+ >>> derivative_coefficients
1197
+ [3, -8, -17]
1198
+
1199
+ Note that polynomial coefficients are specified in descending power order.
1200
+
1201
+ Supports all numeric types: int, float, complex, Decimal, Fraction.
1202
+ """
1203
+ n = len(coefficients)
1204
+ powers = reversed(range(1, n))
1205
+ return list(map(mul, coefficients, powers))
1206
+
1207
+
1208
+ def totient(n):
1209
+ """Return the count of natural numbers up to *n* that are coprime with *n*.
1210
+
1211
+ Euler's totient function φ(n) gives the number of totatives.
1212
+ Totative are integers k in the range 1 ≤ k ≤ n such that gcd(n, k) = 1.
1213
+
1214
+ >>> n = 9
1215
+ >>> totient(n)
1216
+ 6
1217
+
1218
+ >>> totatives = [x for x in range(1, n) if gcd(n, x) == 1]
1219
+ >>> totatives
1220
+ [1, 2, 4, 5, 7, 8]
1221
+ >>> len(totatives)
1222
+ 6
1223
+
1224
+ Reference: https://en.wikipedia.org/wiki/Euler%27s_totient_function
1225
+
1226
+ """
1227
+ for prime in set(factor(n)):
1228
+ n -= n // prime
1229
+ return n
1230
+
1231
+
1232
+ # Miller–Rabin primality test: https://oeis.org/A014233
1233
+ _perfect_tests = [
1234
+ (2047, (2,)),
1235
+ (9080191, (31, 73)),
1236
+ (4759123141, (2, 7, 61)),
1237
+ (1122004669633, (2, 13, 23, 1662803)),
1238
+ (2152302898747, (2, 3, 5, 7, 11)),
1239
+ (3474749660383, (2, 3, 5, 7, 11, 13)),
1240
+ (18446744073709551616, (2, 325, 9375, 28178, 450775, 9780504, 1795265022)),
1241
+ (
1242
+ 3317044064679887385961981,
1243
+ (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41),
1244
+ ),
1245
+ ]
1246
+
1247
+
1248
+ @lru_cache
1249
+ def _shift_to_odd(n):
1250
+ 'Return s, d such that 2**s * d == n'
1251
+ s = ((n - 1) ^ n).bit_length() - 1
1252
+ d = n >> s
1253
+ assert (1 << s) * d == n and d & 1 and s >= 0
1254
+ return s, d
1255
+
1256
+
1257
+ def _strong_probable_prime(n, base):
1258
+ assert (n > 2) and (n & 1) and (2 <= base < n)
1259
+
1260
+ s, d = _shift_to_odd(n - 1)
1261
+
1262
+ x = pow(base, d, n)
1263
+ if x == 1 or x == n - 1:
1264
+ return True
1265
+
1266
+ for _ in range(s - 1):
1267
+ x = x * x % n
1268
+ if x == n - 1:
1269
+ return True
1270
+
1271
+ return False
1272
+
1273
+
1274
+ # Separate instance of Random() that doesn't share state
1275
+ # with the default user instance of Random().
1276
+ _private_randrange = random.Random().randrange
1277
+
1278
+
1279
+ def is_prime(n):
1280
+ """Return ``True`` if *n* is prime and ``False`` otherwise.
1281
+
1282
+ Basic examples:
1283
+
1284
+ >>> is_prime(37)
1285
+ True
1286
+ >>> is_prime(3 * 13)
1287
+ False
1288
+ >>> is_prime(18_446_744_073_709_551_557)
1289
+ True
1290
+
1291
+ Find the next prime over one billion:
1292
+
1293
+ >>> next(filter(is_prime, count(10**9)))
1294
+ 1000000007
1295
+
1296
+ Generate random primes up to 200 bits and up to 60 decimal digits:
1297
+
1298
+ >>> from random import seed, randrange, getrandbits
1299
+ >>> seed(18675309)
1300
+
1301
+ >>> next(filter(is_prime, map(getrandbits, repeat(200))))
1302
+ 893303929355758292373272075469392561129886005037663238028407
1303
+
1304
+ >>> next(filter(is_prime, map(randrange, repeat(10**60))))
1305
+ 269638077304026462407872868003560484232362454342414618963649
1306
+
1307
+ This function is exact for values of *n* below 10**24. For larger inputs,
1308
+ the probabilistic Miller-Rabin primality test has a less than 1 in 2**128
1309
+ chance of a false positive.
1310
+ """
1311
+
1312
+ if n < 17:
1313
+ return n in {2, 3, 5, 7, 11, 13}
1314
+
1315
+ if not (n & 1 and n % 3 and n % 5 and n % 7 and n % 11 and n % 13):
1316
+ return False
1317
+
1318
+ for limit, bases in _perfect_tests:
1319
+ if n < limit:
1320
+ break
1321
+ else:
1322
+ bases = (_private_randrange(2, n - 1) for i in range(64))
1323
+
1324
+ return all(_strong_probable_prime(n, base) for base in bases)
1325
+
1326
+
1327
+ def loops(n):
1328
+ """Returns an iterable with *n* elements for efficient looping.
1329
+ Like ``range(n)`` but doesn't create integers.
1330
+
1331
+ >>> i = 0
1332
+ >>> for _ in loops(5):
1333
+ ... i += 1
1334
+ >>> i
1335
+ 5
1336
+
1337
+ """
1338
+ return repeat(None, n)
1339
+
1340
+
1341
+ def multinomial(*counts):
1342
+ """Number of distinct arrangements of a multiset.
1343
+
1344
+ The expression ``multinomial(3, 4, 2)`` has several equivalent
1345
+ interpretations:
1346
+
1347
+ * In the expansion of ``(a + b + c)⁹``, the coefficient of the
1348
+ ``a³b⁴c²`` term is 1260.
1349
+
1350
+ * There are 1260 distinct ways to arrange 9 balls consisting of 3 reds, 4
1351
+ greens, and 2 blues.
1352
+
1353
+ * There are 1260 unique ways to place 9 distinct objects into three bins
1354
+ with sizes 3, 4, and 2.
1355
+
1356
+ The :func:`multinomial` function computes the length of
1357
+ :func:`distinct_permutations`. For example, there are 83,160 distinct
1358
+ anagrams of the word "abracadabra":
1359
+
1360
+ >>> from more_itertools import distinct_permutations, ilen
1361
+ >>> ilen(distinct_permutations('abracadabra'))
1362
+ 83160
1363
+
1364
+ This can be computed directly from the letter counts, 5a 2b 2r 1c 1d:
1365
+
1366
+ >>> from collections import Counter
1367
+ >>> list(Counter('abracadabra').values())
1368
+ [5, 2, 2, 1, 1]
1369
+ >>> multinomial(5, 2, 2, 1, 1)
1370
+ 83160
1371
+
1372
+ A binomial coefficient is a special case of multinomial where there are
1373
+ only two categories. For example, the number of ways to arrange 12 balls
1374
+ with 5 reds and 7 blues is ``multinomial(5, 7)`` or ``math.comb(12, 5)``.
1375
+
1376
+ Likewise, factorial is a special case of multinomial where
1377
+ the multiplicities are all just 1 so that
1378
+ ``multinomial(1, 1, 1, 1, 1, 1, 1) == math.factorial(7)``.
1379
+
1380
+ Reference: https://en.wikipedia.org/wiki/Multinomial_theorem
1381
+
1382
+ """
1383
+ return prod(map(comb, accumulate(counts), counts))
1384
+
1385
+
1386
+ def _running_median_minheap_and_maxheap(iterator): # pragma: no cover
1387
+ "Non-windowed running_median() for Python 3.14+"
1388
+
1389
+ read = iterator.__next__
1390
+ lo = [] # max-heap
1391
+ hi = [] # min-heap (same size as or one smaller than lo)
1392
+
1393
+ with suppress(StopIteration):
1394
+ while True:
1395
+ heappush_max(lo, heappushpop(hi, read()))
1396
+ yield lo[0]
1397
+
1398
+ heappush(hi, heappushpop_max(lo, read()))
1399
+ yield (lo[0] + hi[0]) / 2
1400
+
1401
+
1402
+ def _running_median_minheap_only(iterator): # pragma: no cover
1403
+ "Backport of non-windowed running_median() for Python 3.13 and prior."
1404
+
1405
+ read = iterator.__next__
1406
+ lo = [] # max-heap (actually a minheap with negated values)
1407
+ hi = [] # min-heap (same size as or one smaller than lo)
1408
+
1409
+ with suppress(StopIteration):
1410
+ while True:
1411
+ heappush(lo, -heappushpop(hi, read()))
1412
+ yield -lo[0]
1413
+
1414
+ heappush(hi, -heappushpop(lo, -read()))
1415
+ yield (hi[0] - lo[0]) / 2
1416
+
1417
+
1418
+ def _running_median_windowed(iterator, maxlen):
1419
+ "Yield median of values in a sliding window."
1420
+
1421
+ window = deque()
1422
+ ordered = []
1423
+
1424
+ for x in iterator:
1425
+ window.append(x)
1426
+ insort(ordered, x)
1427
+
1428
+ if len(ordered) > maxlen:
1429
+ i = bisect_left(ordered, window.popleft())
1430
+ del ordered[i]
1431
+
1432
+ n = len(ordered)
1433
+ m = n // 2
1434
+ yield ordered[m] if n & 1 else (ordered[m - 1] + ordered[m]) / 2
1435
+
1436
+
1437
+ def running_median(iterable, *, maxlen=None):
1438
+ """Cumulative median of values seen so far or values in a sliding window.
1439
+
1440
+ Set *maxlen* to a positive integer to specify the maximum size
1441
+ of the sliding window. The default of *None* is equivalent to
1442
+ an unbounded window.
1443
+
1444
+ For example:
1445
+
1446
+ >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0]))
1447
+ [5.0, 7.0, 5.0, 7.0, 8.0, 8.5]
1448
+ >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0], maxlen=3))
1449
+ [5.0, 7.0, 5.0, 9.0, 8.0, 9.0]
1450
+
1451
+ Supports numeric types such as int, float, Decimal, and Fraction,
1452
+ but not complex numbers which are unorderable.
1453
+
1454
+ On version Python 3.13 and prior, max-heaps are simulated with
1455
+ negative values. The negation causes Decimal inputs to apply context
1456
+ rounding, making the results slightly different than that obtained
1457
+ by statistics.median().
1458
+ """
1459
+
1460
+ iterator = iter(iterable)
1461
+
1462
+ if maxlen is not None:
1463
+ maxlen = index(maxlen)
1464
+ if maxlen <= 0:
1465
+ raise ValueError('Window size should be positive')
1466
+ return _running_median_windowed(iterator, maxlen)
1467
+
1468
+ if not _max_heap_available:
1469
+ return _running_median_minheap_only(iterator) # pragma: no cover
1470
+
1471
+ return _running_median_minheap_and_maxheap(iterator) # pragma: no cover
python/Lib/site-packages/setuptools/_vendor/more_itertools/recipes.pyi ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stubs for more_itertools.recipes"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Iterator, Sequence
6
+ from decimal import Decimal
7
+ from fractions import Fraction
8
+ from typing import (
9
+ Any,
10
+ Callable,
11
+ TypeVar,
12
+ overload,
13
+ )
14
+
15
+ __all__ = [
16
+ 'all_equal',
17
+ 'batched',
18
+ 'before_and_after',
19
+ 'consume',
20
+ 'convolve',
21
+ 'dotproduct',
22
+ 'first_true',
23
+ 'factor',
24
+ 'flatten',
25
+ 'grouper',
26
+ 'is_prime',
27
+ 'iter_except',
28
+ 'iter_index',
29
+ 'loops',
30
+ 'matmul',
31
+ 'multinomial',
32
+ 'ncycles',
33
+ 'nth',
34
+ 'nth_combination',
35
+ 'padnone',
36
+ 'pad_none',
37
+ 'pairwise',
38
+ 'partition',
39
+ 'polynomial_eval',
40
+ 'polynomial_from_roots',
41
+ 'polynomial_derivative',
42
+ 'powerset',
43
+ 'prepend',
44
+ 'quantify',
45
+ 'reshape',
46
+ 'random_combination_with_replacement',
47
+ 'random_combination',
48
+ 'random_permutation',
49
+ 'random_product',
50
+ 'repeatfunc',
51
+ 'roundrobin',
52
+ 'running_median',
53
+ 'sieve',
54
+ 'sliding_window',
55
+ 'subslices',
56
+ 'sum_of_squares',
57
+ 'tabulate',
58
+ 'tail',
59
+ 'take',
60
+ 'totient',
61
+ 'transpose',
62
+ 'triplewise',
63
+ 'unique',
64
+ 'unique_everseen',
65
+ 'unique_justseen',
66
+ ]
67
+
68
+ # Type and type variable definitions
69
+ _T = TypeVar('_T')
70
+ _T1 = TypeVar('_T1')
71
+ _T2 = TypeVar('_T2')
72
+ _U = TypeVar('_U')
73
+ _NumberT = TypeVar("_NumberT", float, Decimal, Fraction)
74
+
75
+ def take(n: int, iterable: Iterable[_T]) -> list[_T]: ...
76
+ def tabulate(
77
+ function: Callable[[int], _T], start: int = ...
78
+ ) -> Iterator[_T]: ...
79
+ def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: ...
80
+ def consume(iterator: Iterable[_T], n: int | None = ...) -> None: ...
81
+ @overload
82
+ def nth(iterable: Iterable[_T], n: int) -> _T | None: ...
83
+ @overload
84
+ def nth(iterable: Iterable[_T], n: int, default: _U) -> _T | _U: ...
85
+ def all_equal(
86
+ iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
87
+ ) -> bool: ...
88
+ def quantify(
89
+ iterable: Iterable[_T], pred: Callable[[_T], bool] = ...
90
+ ) -> int: ...
91
+ def pad_none(iterable: Iterable[_T]) -> Iterator[_T | None]: ...
92
+ def padnone(iterable: Iterable[_T]) -> Iterator[_T | None]: ...
93
+ def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: ...
94
+ def dotproduct(vec1: Iterable[_T1], vec2: Iterable[_T2]) -> Any: ...
95
+ def flatten(listOfLists: Iterable[Iterable[_T]]) -> Iterator[_T]: ...
96
+ def repeatfunc(
97
+ func: Callable[..., _U], times: int | None = ..., *args: Any
98
+ ) -> Iterator[_U]: ...
99
+ def pairwise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T]]: ...
100
+ def grouper(
101
+ iterable: Iterable[_T],
102
+ n: int,
103
+ incomplete: str = ...,
104
+ fillvalue: _U = ...,
105
+ ) -> Iterator[tuple[_T | _U, ...]]: ...
106
+ def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: ...
107
+ def partition(
108
+ pred: Callable[[_T], object] | None, iterable: Iterable[_T]
109
+ ) -> tuple[Iterator[_T], Iterator[_T]]: ...
110
+ def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: ...
111
+ def unique_everseen(
112
+ iterable: Iterable[_T], key: Callable[[_T], _U] | None = ...
113
+ ) -> Iterator[_T]: ...
114
+ def unique_justseen(
115
+ iterable: Iterable[_T], key: Callable[[_T], object] | None = ...
116
+ ) -> Iterator[_T]: ...
117
+ def unique(
118
+ iterable: Iterable[_T],
119
+ key: Callable[[_T], object] | None = ...,
120
+ reverse: bool = False,
121
+ ) -> Iterator[_T]: ...
122
+ @overload
123
+ def iter_except(
124
+ func: Callable[[], _T],
125
+ exception: type[BaseException] | tuple[type[BaseException], ...],
126
+ first: None = ...,
127
+ ) -> Iterator[_T]: ...
128
+ @overload
129
+ def iter_except(
130
+ func: Callable[[], _T],
131
+ exception: type[BaseException] | tuple[type[BaseException], ...],
132
+ first: Callable[[], _U],
133
+ ) -> Iterator[_T | _U]: ...
134
+ @overload
135
+ def first_true(
136
+ iterable: Iterable[_T], *, pred: Callable[[_T], object] | None = ...
137
+ ) -> _T | None: ...
138
+ @overload
139
+ def first_true(
140
+ iterable: Iterable[_T],
141
+ default: _U,
142
+ pred: Callable[[_T], object] | None = ...,
143
+ ) -> _T | _U: ...
144
+ def random_product(
145
+ *args: Iterable[_T], repeat: int = ...
146
+ ) -> tuple[_T, ...]: ...
147
+ def random_permutation(
148
+ iterable: Iterable[_T], r: int | None = ...
149
+ ) -> tuple[_T, ...]: ...
150
+ def random_combination(iterable: Iterable[_T], r: int) -> tuple[_T, ...]: ...
151
+ def random_combination_with_replacement(
152
+ iterable: Iterable[_T], r: int
153
+ ) -> tuple[_T, ...]: ...
154
+ def nth_combination(
155
+ iterable: Iterable[_T], r: int, index: int
156
+ ) -> tuple[_T, ...]: ...
157
+ def prepend(value: _T, iterator: Iterable[_U]) -> Iterator[_T | _U]: ...
158
+ def convolve(signal: Iterable[_T], kernel: Iterable[_T]) -> Iterator[_T]: ...
159
+ def before_and_after(
160
+ predicate: Callable[[_T], bool], it: Iterable[_T]
161
+ ) -> tuple[Iterator[_T], Iterator[_T]]: ...
162
+ def triplewise(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: ...
163
+ def sliding_window(
164
+ iterable: Iterable[_T], n: int
165
+ ) -> Iterator[tuple[_T, ...]]: ...
166
+ def subslices(iterable: Iterable[_T]) -> Iterator[list[_T]]: ...
167
+ def polynomial_from_roots(roots: Sequence[_T]) -> list[_T]: ...
168
+ def iter_index(
169
+ iterable: Iterable[_T],
170
+ value: Any,
171
+ start: int | None = ...,
172
+ stop: int | None = ...,
173
+ ) -> Iterator[int]: ...
174
+ def sieve(n: int) -> Iterator[int]: ...
175
+ def _batched(
176
+ iterable: Iterable[_T], n: int, *, strict: bool = False
177
+ ) -> Iterator[tuple[_T, ...]]: ...
178
+
179
+ batched = _batched
180
+
181
+ def transpose(
182
+ it: Iterable[Iterable[_T]],
183
+ ) -> Iterator[tuple[_T, ...]]: ...
184
+ @overload
185
+ def reshape(
186
+ matrix: Iterable[Iterable[_T]], shape: int
187
+ ) -> Iterator[tuple[_T, ...]]: ...
188
+ @overload
189
+ def reshape(matrix: Iterable[Any], shape: Iterable[int]) -> Iterator[Any]: ...
190
+ def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[tuple[_T]]: ...
191
+ def _factor_trial(n: int) -> Iterator[int]: ...
192
+ def _factor_pollard(n: int) -> int: ...
193
+ def factor(n: int) -> Iterator[int]: ...
194
+ def polynomial_eval(coefficients: Sequence[_T], x: _U) -> _U: ...
195
+ def sum_of_squares(it: Iterable[_T]) -> _T: ...
196
+ def polynomial_derivative(coefficients: Sequence[_T]) -> list[_T]: ...
197
+ def totient(n: int) -> int: ...
198
+ def _shift_to_odd(n: int) -> tuple[int, int]: ...
199
+ def _strong_probable_prime(n: int, base: int) -> bool: ...
200
+ def is_prime(n: int) -> bool: ...
201
+ def loops(n: int) -> Iterator[None]: ...
202
+ def multinomial(*counts: int) -> int: ...
203
+ def running_median(
204
+ iterable: Iterable[_NumberT], *, maxlen: int | None = ...
205
+ ) -> Iterator[_NumberT]: ...
python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/METADATA ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: packaging
3
+ Version: 26.0
4
+ Summary: Core utilities for Python packages
5
+ Author-email: Donald Stufft <donald@stufft.io>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/x-rst
8
+ License-Expression: Apache-2.0 OR BSD-2-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
23
+ Classifier: Typing :: Typed
24
+ License-File: LICENSE
25
+ License-File: LICENSE.APACHE
26
+ License-File: LICENSE.BSD
27
+ Project-URL: Documentation, https://packaging.pypa.io/
28
+ Project-URL: Source, https://github.com/pypa/packaging
29
+
30
+ packaging
31
+ =========
32
+
33
+ .. start-intro
34
+
35
+ Reusable core utilities for various Python Packaging
36
+ `interoperability specifications <https://packaging.python.org/specifications/>`_.
37
+
38
+ This library provides utilities that implement the interoperability
39
+ specifications which have clearly one correct behaviour (eg: :pep:`440`)
40
+ or benefit greatly from having a single shared implementation (eg: :pep:`425`).
41
+
42
+ .. end-intro
43
+
44
+ The ``packaging`` project includes the following: version handling, specifiers,
45
+ markers, requirements, tags, metadata, lockfiles, utilities.
46
+
47
+ Documentation
48
+ -------------
49
+
50
+ The `documentation`_ provides information and the API for the following:
51
+
52
+ - Version Handling
53
+ - Specifiers
54
+ - Markers
55
+ - Requirements
56
+ - Tags
57
+ - Metadata
58
+ - Lockfiles
59
+ - Utilities
60
+
61
+ Installation
62
+ ------------
63
+
64
+ Use ``pip`` to install these utilities::
65
+
66
+ pip install packaging
67
+
68
+ The ``packaging`` library uses calendar-based versioning (``YY.N``).
69
+
70
+ Discussion
71
+ ----------
72
+
73
+ If you run into bugs, you can file them in our `issue tracker`_.
74
+
75
+ You can also join ``#pypa`` on Freenode to ask questions or get involved.
76
+
77
+
78
+ .. _`documentation`: https://packaging.pypa.io/
79
+ .. _`issue tracker`: https://github.com/pypa/packaging/issues
80
+
81
+
82
+ Code of Conduct
83
+ ---------------
84
+
85
+ Everyone interacting in the packaging project's codebases, issue trackers, chat
86
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
87
+
88
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
89
+
90
+ Contributing
91
+ ------------
92
+
93
+ The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
94
+ well as how to report a potential security issue. The documentation for this
95
+ project also covers information about `project development`_ and `security`_.
96
+
97
+ .. _`project development`: https://packaging.pypa.io/en/latest/development/
98
+ .. _`security`: https://packaging.pypa.io/en/latest/security/
99
+
100
+ Project History
101
+ ---------------
102
+
103
+ Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
104
+ recent changes and project history.
105
+
106
+ .. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
107
+
python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/RECORD ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ packaging-26.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309
3
+ packaging-26.0.dist-info/RECORD,,
4
+ packaging-26.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
6
+ packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
7
+ packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
8
+ packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
9
+ packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494
10
+ packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
11
+ packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
12
+ packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
13
+ packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518
14
+ packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514
15
+ packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421
16
+ packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819
17
+ packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
18
+ packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771
19
+ packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360
20
+ packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537
22
+ packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870
23
+ packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797
24
+ packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856
25
+ packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040
26
+ packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272
python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/REQUESTED ADDED
File without changes
python/Lib/site-packages/setuptools/_vendor/packaging-26.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
python/Lib/site-packages/setuptools/_vendor/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "26.0"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
python/Lib/site-packages/setuptools/_vendor/packaging/_elffile.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELF file parser.
3
+
4
+ This provides a class ``ELFFile`` that parses an ELF executable in a similar
5
+ interface to ``ZipFile``. Only the read interface is implemented.
6
+
7
+ ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ import os
14
+ import struct
15
+ from typing import IO
16
+
17
+
18
+ class ELFInvalid(ValueError):
19
+ pass
20
+
21
+
22
+ class EIClass(enum.IntEnum):
23
+ C32 = 1
24
+ C64 = 2
25
+
26
+
27
+ class EIData(enum.IntEnum):
28
+ Lsb = 1
29
+ Msb = 2
30
+
31
+
32
+ class EMachine(enum.IntEnum):
33
+ I386 = 3
34
+ S390 = 22
35
+ Arm = 40
36
+ X8664 = 62
37
+ AArc64 = 183
38
+
39
+
40
+ class ELFFile:
41
+ """
42
+ Representation of an ELF executable.
43
+ """
44
+
45
+ def __init__(self, f: IO[bytes]) -> None:
46
+ self._f = f
47
+
48
+ try:
49
+ ident = self._read("16B")
50
+ except struct.error as e:
51
+ raise ELFInvalid("unable to parse identification") from e
52
+ magic = bytes(ident[:4])
53
+ if magic != b"\x7fELF":
54
+ raise ELFInvalid(f"invalid magic: {magic!r}")
55
+
56
+ self.capacity = ident[4] # Format for program header (bitness).
57
+ self.encoding = ident[5] # Data structure encoding (endianness).
58
+
59
+ try:
60
+ # e_fmt: Format for program header.
61
+ # p_fmt: Format for section header.
62
+ # p_idx: Indexes to find p_type, p_offset, and p_filesz.
63
+ e_fmt, self._p_fmt, self._p_idx = {
64
+ (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB.
65
+ (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB.
66
+ (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
67
+ (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
68
+ }[(self.capacity, self.encoding)]
69
+ except KeyError as e:
70
+ raise ELFInvalid(
71
+ f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
72
+ ) from e
73
+
74
+ try:
75
+ (
76
+ _,
77
+ self.machine, # Architecture type.
78
+ _,
79
+ _,
80
+ self._e_phoff, # Offset of program header.
81
+ _,
82
+ self.flags, # Processor-specific flags.
83
+ _,
84
+ self._e_phentsize, # Size of section.
85
+ self._e_phnum, # Number of sections.
86
+ ) = self._read(e_fmt)
87
+ except struct.error as e:
88
+ raise ELFInvalid("unable to parse machine and section information") from e
89
+
90
+ def _read(self, fmt: str) -> tuple[int, ...]:
91
+ return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
92
+
93
+ @property
94
+ def interpreter(self) -> str | None:
95
+ """
96
+ The path recorded in the ``PT_INTERP`` section header.
97
+ """
98
+ for index in range(self._e_phnum):
99
+ self._f.seek(self._e_phoff + self._e_phentsize * index)
100
+ try:
101
+ data = self._read(self._p_fmt)
102
+ except struct.error:
103
+ continue
104
+ if data[self._p_idx[0]] != 3: # Not PT_INTERP.
105
+ continue
106
+ self._f.seek(data[self._p_idx[1]])
107
+ return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
108
+ return None
python/Lib/site-packages/setuptools/_vendor/packaging/_manylinux.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import contextlib
5
+ import functools
6
+ import os
7
+ import re
8
+ import sys
9
+ import warnings
10
+ from typing import Generator, Iterator, NamedTuple, Sequence
11
+
12
+ from ._elffile import EIClass, EIData, ELFFile, EMachine
13
+
14
+ EF_ARM_ABIMASK = 0xFF000000
15
+ EF_ARM_ABI_VER5 = 0x05000000
16
+ EF_ARM_ABI_FLOAT_HARD = 0x00000400
17
+
18
+ _ALLOWED_ARCHS = {
19
+ "x86_64",
20
+ "aarch64",
21
+ "ppc64",
22
+ "ppc64le",
23
+ "s390x",
24
+ "loongarch64",
25
+ "riscv64",
26
+ }
27
+
28
+
29
+ # `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
30
+ # as the type for `path` until then.
31
+ @contextlib.contextmanager
32
+ def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
33
+ try:
34
+ with open(path, "rb") as f:
35
+ yield ELFFile(f)
36
+ except (OSError, TypeError, ValueError):
37
+ yield None
38
+
39
+
40
+ def _is_linux_armhf(executable: str) -> bool:
41
+ # hard-float ABI can be detected from the ELF header of the running
42
+ # process
43
+ # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
44
+ with _parse_elf(executable) as f:
45
+ return (
46
+ f is not None
47
+ and f.capacity == EIClass.C32
48
+ and f.encoding == EIData.Lsb
49
+ and f.machine == EMachine.Arm
50
+ and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
51
+ and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
52
+ )
53
+
54
+
55
+ def _is_linux_i686(executable: str) -> bool:
56
+ with _parse_elf(executable) as f:
57
+ return (
58
+ f is not None
59
+ and f.capacity == EIClass.C32
60
+ and f.encoding == EIData.Lsb
61
+ and f.machine == EMachine.I386
62
+ )
63
+
64
+
65
+ def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
66
+ if "armv7l" in archs:
67
+ return _is_linux_armhf(executable)
68
+ if "i686" in archs:
69
+ return _is_linux_i686(executable)
70
+ return any(arch in _ALLOWED_ARCHS for arch in archs)
71
+
72
+
73
+ # If glibc ever changes its major version, we need to know what the last
74
+ # minor version was, so we can build the complete list of all versions.
75
+ # For now, guess what the highest minor version might be, assume it will
76
+ # be 50 for testing. Once this actually happens, update the dictionary
77
+ # with the actual value.
78
+ _LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
79
+
80
+
81
+ class _GLibCVersion(NamedTuple):
82
+ major: int
83
+ minor: int
84
+
85
+
86
+ def _glibc_version_string_confstr() -> str | None:
87
+ """
88
+ Primary implementation of glibc_version_string using os.confstr.
89
+ """
90
+ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
91
+ # to be broken or missing. This strategy is used in the standard library
92
+ # platform module.
93
+ # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
94
+ try:
95
+ # Should be a string like "glibc 2.17".
96
+ version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
97
+ assert version_string is not None
98
+ _, version = version_string.rsplit()
99
+ except (AssertionError, AttributeError, OSError, ValueError):
100
+ # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
101
+ return None
102
+ return version
103
+
104
+
105
+ def _glibc_version_string_ctypes() -> str | None:
106
+ """
107
+ Fallback implementation of glibc_version_string using ctypes.
108
+ """
109
+ try:
110
+ import ctypes # noqa: PLC0415
111
+ except ImportError:
112
+ return None
113
+
114
+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
115
+ # manpage says, "If filename is NULL, then the returned handle is for the
116
+ # main program". This way we can let the linker do the work to figure out
117
+ # which libc our process is actually using.
118
+ #
119
+ # We must also handle the special case where the executable is not a
120
+ # dynamically linked executable. This can occur when using musl libc,
121
+ # for example. In this situation, dlopen() will error, leading to an
122
+ # OSError. Interestingly, at least in the case of musl, there is no
123
+ # errno set on the OSError. The single string argument used to construct
124
+ # OSError comes from libc itself and is therefore not portable to
125
+ # hard code here. In any case, failure to call dlopen() means we
126
+ # can proceed, so we bail on our attempt.
127
+ try:
128
+ process_namespace = ctypes.CDLL(None)
129
+ except OSError:
130
+ return None
131
+
132
+ try:
133
+ gnu_get_libc_version = process_namespace.gnu_get_libc_version
134
+ except AttributeError:
135
+ # Symbol doesn't exist -> therefore, we are not linked to
136
+ # glibc.
137
+ return None
138
+
139
+ # Call gnu_get_libc_version, which returns a string like "2.5"
140
+ gnu_get_libc_version.restype = ctypes.c_char_p
141
+ version_str: str = gnu_get_libc_version()
142
+ # py2 / py3 compatibility:
143
+ if not isinstance(version_str, str):
144
+ version_str = version_str.decode("ascii")
145
+
146
+ return version_str
147
+
148
+
149
+ def _glibc_version_string() -> str | None:
150
+ """Returns glibc version string, or None if not using glibc."""
151
+ return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
152
+
153
+
154
+ def _parse_glibc_version(version_str: str) -> _GLibCVersion:
155
+ """Parse glibc version.
156
+
157
+ We use a regexp instead of str.split because we want to discard any
158
+ random junk that might come after the minor version -- this might happen
159
+ in patched/forked versions of glibc (e.g. Linaro's version of glibc
160
+ uses version strings like "2.20-2014.11"). See gh-3588.
161
+ """
162
+ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
163
+ if not m:
164
+ warnings.warn(
165
+ f"Expected glibc version with 2 components major.minor, got: {version_str}",
166
+ RuntimeWarning,
167
+ stacklevel=2,
168
+ )
169
+ return _GLibCVersion(-1, -1)
170
+ return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
171
+
172
+
173
+ @functools.lru_cache
174
+ def _get_glibc_version() -> _GLibCVersion:
175
+ version_str = _glibc_version_string()
176
+ if version_str is None:
177
+ return _GLibCVersion(-1, -1)
178
+ return _parse_glibc_version(version_str)
179
+
180
+
181
+ # From PEP 513, PEP 600
182
+ def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
183
+ sys_glibc = _get_glibc_version()
184
+ if sys_glibc < version:
185
+ return False
186
+ # Check for presence of _manylinux module.
187
+ try:
188
+ import _manylinux # noqa: PLC0415
189
+ except ImportError:
190
+ return True
191
+ if hasattr(_manylinux, "manylinux_compatible"):
192
+ result = _manylinux.manylinux_compatible(version[0], version[1], arch)
193
+ if result is not None:
194
+ return bool(result)
195
+ return True
196
+ if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
197
+ return bool(_manylinux.manylinux1_compatible)
198
+ if version == _GLibCVersion(2, 12) and hasattr(
199
+ _manylinux, "manylinux2010_compatible"
200
+ ):
201
+ return bool(_manylinux.manylinux2010_compatible)
202
+ if version == _GLibCVersion(2, 17) and hasattr(
203
+ _manylinux, "manylinux2014_compatible"
204
+ ):
205
+ return bool(_manylinux.manylinux2014_compatible)
206
+ return True
207
+
208
+
209
+ _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
210
+ # CentOS 7 w/ glibc 2.17 (PEP 599)
211
+ _GLibCVersion(2, 17): "manylinux2014",
212
+ # CentOS 6 w/ glibc 2.12 (PEP 571)
213
+ _GLibCVersion(2, 12): "manylinux2010",
214
+ # CentOS 5 w/ glibc 2.5 (PEP 513)
215
+ _GLibCVersion(2, 5): "manylinux1",
216
+ }
217
+
218
+
219
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
220
+ """Generate manylinux tags compatible to the current platform.
221
+
222
+ :param archs: Sequence of compatible architectures.
223
+ The first one shall be the closest to the actual architecture and be the part of
224
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
225
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
226
+ be manylinux-compatible.
227
+
228
+ :returns: An iterator of compatible manylinux tags.
229
+ """
230
+ if not _have_compatible_abi(sys.executable, archs):
231
+ return
232
+ # Oldest glibc to be supported regardless of architecture is (2, 17).
233
+ too_old_glibc2 = _GLibCVersion(2, 16)
234
+ if set(archs) & {"x86_64", "i686"}:
235
+ # On x86/i686 also oldest glibc to be supported is (2, 5).
236
+ too_old_glibc2 = _GLibCVersion(2, 4)
237
+ current_glibc = _GLibCVersion(*_get_glibc_version())
238
+ glibc_max_list = [current_glibc]
239
+ # We can assume compatibility across glibc major versions.
240
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
241
+ #
242
+ # Build a list of maximum glibc versions so that we can
243
+ # output the canonical list of all glibc from current_glibc
244
+ # down to too_old_glibc2, including all intermediary versions.
245
+ for glibc_major in range(current_glibc.major - 1, 1, -1):
246
+ glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
247
+ glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
248
+ for arch in archs:
249
+ for glibc_max in glibc_max_list:
250
+ if glibc_max.major == too_old_glibc2.major:
251
+ min_minor = too_old_glibc2.minor
252
+ else:
253
+ # For other glibc major versions oldest supported is (x, 0).
254
+ min_minor = -1
255
+ for glibc_minor in range(glibc_max.minor, min_minor, -1):
256
+ glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
257
+ if _is_compatible(arch, glibc_version):
258
+ yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
259
+
260
+ # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
261
+ if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):
262
+ yield f"{legacy_tag}_{arch}"
python/Lib/site-packages/setuptools/_vendor/packaging/_musllinux.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PEP 656 support.
2
+
3
+ This module implements logic to detect if the currently running Python is
4
+ linked against musl, and what musl version is used.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ from typing import Iterator, NamedTuple, Sequence
14
+
15
+ from ._elffile import ELFFile
16
+
17
+
18
+ class _MuslVersion(NamedTuple):
19
+ major: int
20
+ minor: int
21
+
22
+
23
+ def _parse_musl_version(output: str) -> _MuslVersion | None:
24
+ lines = [n for n in (n.strip() for n in output.splitlines()) if n]
25
+ if len(lines) < 2 or lines[0][:4] != "musl":
26
+ return None
27
+ m = re.match(r"Version (\d+)\.(\d+)", lines[1])
28
+ if not m:
29
+ return None
30
+ return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
31
+
32
+
33
+ @functools.lru_cache
34
+ def _get_musl_version(executable: str) -> _MuslVersion | None:
35
+ """Detect currently-running musl runtime version.
36
+
37
+ This is done by checking the specified executable's dynamic linking
38
+ information, and invoking the loader to parse its output for a version
39
+ string. If the loader is musl, the output would be something like::
40
+
41
+ musl libc (x86_64)
42
+ Version 1.2.2
43
+ Dynamic Program Loader
44
+ """
45
+ try:
46
+ with open(executable, "rb") as f:
47
+ ld = ELFFile(f).interpreter
48
+ except (OSError, TypeError, ValueError):
49
+ return None
50
+ if ld is None or "musl" not in ld:
51
+ return None
52
+ proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)
53
+ return _parse_musl_version(proc.stderr)
54
+
55
+
56
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
57
+ """Generate musllinux tags compatible to the current platform.
58
+
59
+ :param archs: Sequence of compatible architectures.
60
+ The first one shall be the closest to the actual architecture and be the part of
61
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
62
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
63
+ be musllinux-compatible.
64
+
65
+ :returns: An iterator of compatible musllinux tags.
66
+ """
67
+ sys_musl = _get_musl_version(sys.executable)
68
+ if sys_musl is None: # Python not dynamically linked against musl.
69
+ return
70
+ for arch in archs:
71
+ for minor in range(sys_musl.minor, -1, -1):
72
+ yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
73
+
74
+
75
+ if __name__ == "__main__": # pragma: no cover
76
+ import sysconfig
77
+
78
+ plat = sysconfig.get_platform()
79
+ assert plat.startswith("linux-"), "not linux"
80
+
81
+ print("plat:", plat)
82
+ print("musl:", _get_musl_version(sys.executable))
83
+ print("tags:", end=" ")
84
+ for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
85
+ print(t, end="\n ")
python/Lib/site-packages/setuptools/_vendor/packaging/_parser.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handwritten parser of dependency specifiers.
2
+
3
+ The docstring for each __parse_* function contains EBNF-inspired grammar representing
4
+ the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
11
+
12
+ from ._tokenizer import DEFAULT_RULES, Tokenizer
13
+
14
+
15
+ class Node:
16
+ __slots__ = ("value",)
17
+
18
+ def __init__(self, value: str) -> None:
19
+ self.value = value
20
+
21
+ def __str__(self) -> str:
22
+ return self.value
23
+
24
+ def __repr__(self) -> str:
25
+ return f"<{self.__class__.__name__}({self.value!r})>"
26
+
27
+ def serialize(self) -> str:
28
+ raise NotImplementedError
29
+
30
+
31
+ class Variable(Node):
32
+ __slots__ = ()
33
+
34
+ def serialize(self) -> str:
35
+ return str(self)
36
+
37
+
38
+ class Value(Node):
39
+ __slots__ = ()
40
+
41
+ def serialize(self) -> str:
42
+ return f'"{self}"'
43
+
44
+
45
+ class Op(Node):
46
+ __slots__ = ()
47
+
48
+ def serialize(self) -> str:
49
+ return str(self)
50
+
51
+
52
+ MarkerLogical = Literal["and", "or"]
53
+ MarkerVar = Union[Variable, Value]
54
+ MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
55
+ MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
56
+ MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
57
+
58
+
59
+ class ParsedRequirement(NamedTuple):
60
+ name: str
61
+ url: str
62
+ extras: list[str]
63
+ specifier: str
64
+ marker: MarkerList | None
65
+
66
+
67
+ # --------------------------------------------------------------------------------------
68
+ # Recursive descent parser for dependency specifier
69
+ # --------------------------------------------------------------------------------------
70
+ def parse_requirement(source: str) -> ParsedRequirement:
71
+ return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
72
+
73
+
74
+ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
75
+ """
76
+ requirement = WS? IDENTIFIER WS? extras WS? requirement_details
77
+ """
78
+ tokenizer.consume("WS")
79
+
80
+ name_token = tokenizer.expect(
81
+ "IDENTIFIER", expected="package name at the start of dependency specifier"
82
+ )
83
+ name = name_token.text
84
+ tokenizer.consume("WS")
85
+
86
+ extras = _parse_extras(tokenizer)
87
+ tokenizer.consume("WS")
88
+
89
+ url, specifier, marker = _parse_requirement_details(tokenizer)
90
+ tokenizer.expect("END", expected="end of dependency specifier")
91
+
92
+ return ParsedRequirement(name, url, extras, specifier, marker)
93
+
94
+
95
+ def _parse_requirement_details(
96
+ tokenizer: Tokenizer,
97
+ ) -> tuple[str, str, MarkerList | None]:
98
+ """
99
+ requirement_details = AT URL (WS requirement_marker?)?
100
+ | specifier WS? (requirement_marker)?
101
+ """
102
+
103
+ specifier = ""
104
+ url = ""
105
+ marker = None
106
+
107
+ if tokenizer.check("AT"):
108
+ tokenizer.read()
109
+ tokenizer.consume("WS")
110
+
111
+ url_start = tokenizer.position
112
+ url = tokenizer.expect("URL", expected="URL after @").text
113
+ if tokenizer.check("END", peek=True):
114
+ return (url, specifier, marker)
115
+
116
+ tokenizer.expect("WS", expected="whitespace after URL")
117
+
118
+ # The input might end after whitespace.
119
+ if tokenizer.check("END", peek=True):
120
+ return (url, specifier, marker)
121
+
122
+ marker = _parse_requirement_marker(
123
+ tokenizer,
124
+ span_start=url_start,
125
+ expected="semicolon (after URL and whitespace)",
126
+ )
127
+ else:
128
+ specifier_start = tokenizer.position
129
+ specifier = _parse_specifier(tokenizer)
130
+ tokenizer.consume("WS")
131
+
132
+ if tokenizer.check("END", peek=True):
133
+ return (url, specifier, marker)
134
+
135
+ marker = _parse_requirement_marker(
136
+ tokenizer,
137
+ span_start=specifier_start,
138
+ expected=(
139
+ "comma (within version specifier), semicolon (after version specifier)"
140
+ if specifier
141
+ else "semicolon (after name with no version specifier)"
142
+ ),
143
+ )
144
+
145
+ return (url, specifier, marker)
146
+
147
+
148
+ def _parse_requirement_marker(
149
+ tokenizer: Tokenizer, *, span_start: int, expected: str
150
+ ) -> MarkerList:
151
+ """
152
+ requirement_marker = SEMICOLON marker WS?
153
+ """
154
+
155
+ if not tokenizer.check("SEMICOLON"):
156
+ tokenizer.raise_syntax_error(
157
+ f"Expected {expected} or end",
158
+ span_start=span_start,
159
+ span_end=None,
160
+ )
161
+ tokenizer.read()
162
+
163
+ marker = _parse_marker(tokenizer)
164
+ tokenizer.consume("WS")
165
+
166
+ return marker
167
+
168
+
169
+ def _parse_extras(tokenizer: Tokenizer) -> list[str]:
170
+ """
171
+ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
172
+ """
173
+ if not tokenizer.check("LEFT_BRACKET", peek=True):
174
+ return []
175
+
176
+ with tokenizer.enclosing_tokens(
177
+ "LEFT_BRACKET",
178
+ "RIGHT_BRACKET",
179
+ around="extras",
180
+ ):
181
+ tokenizer.consume("WS")
182
+ extras = _parse_extras_list(tokenizer)
183
+ tokenizer.consume("WS")
184
+
185
+ return extras
186
+
187
+
188
+ def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
189
+ """
190
+ extras_list = identifier (wsp* ',' wsp* identifier)*
191
+ """
192
+ extras: list[str] = []
193
+
194
+ if not tokenizer.check("IDENTIFIER"):
195
+ return extras
196
+
197
+ extras.append(tokenizer.read().text)
198
+
199
+ while True:
200
+ tokenizer.consume("WS")
201
+ if tokenizer.check("IDENTIFIER", peek=True):
202
+ tokenizer.raise_syntax_error("Expected comma between extra names")
203
+ elif not tokenizer.check("COMMA"):
204
+ break
205
+
206
+ tokenizer.read()
207
+ tokenizer.consume("WS")
208
+
209
+ extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
210
+ extras.append(extra_token.text)
211
+
212
+ return extras
213
+
214
+
215
+ def _parse_specifier(tokenizer: Tokenizer) -> str:
216
+ """
217
+ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
218
+ | WS? version_many WS?
219
+ """
220
+ with tokenizer.enclosing_tokens(
221
+ "LEFT_PARENTHESIS",
222
+ "RIGHT_PARENTHESIS",
223
+ around="version specifier",
224
+ ):
225
+ tokenizer.consume("WS")
226
+ parsed_specifiers = _parse_version_many(tokenizer)
227
+ tokenizer.consume("WS")
228
+
229
+ return parsed_specifiers
230
+
231
+
232
+ def _parse_version_many(tokenizer: Tokenizer) -> str:
233
+ """
234
+ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
235
+ """
236
+ parsed_specifiers = ""
237
+ while tokenizer.check("SPECIFIER"):
238
+ span_start = tokenizer.position
239
+ parsed_specifiers += tokenizer.read().text
240
+ if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
241
+ tokenizer.raise_syntax_error(
242
+ ".* suffix can only be used with `==` or `!=` operators",
243
+ span_start=span_start,
244
+ span_end=tokenizer.position + 1,
245
+ )
246
+ if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
247
+ tokenizer.raise_syntax_error(
248
+ "Local version label can only be used with `==` or `!=` operators",
249
+ span_start=span_start,
250
+ span_end=tokenizer.position,
251
+ )
252
+ tokenizer.consume("WS")
253
+ if not tokenizer.check("COMMA"):
254
+ break
255
+ parsed_specifiers += tokenizer.read().text
256
+ tokenizer.consume("WS")
257
+
258
+ return parsed_specifiers
259
+
260
+
261
+ # --------------------------------------------------------------------------------------
262
+ # Recursive descent parser for marker expression
263
+ # --------------------------------------------------------------------------------------
264
+ def parse_marker(source: str) -> MarkerList:
265
+ return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
266
+
267
+
268
+ def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
269
+ retval = _parse_marker(tokenizer)
270
+ tokenizer.expect("END", expected="end of marker expression")
271
+ return retval
272
+
273
+
274
+ def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
275
+ """
276
+ marker = marker_atom (BOOLOP marker_atom)+
277
+ """
278
+ expression = [_parse_marker_atom(tokenizer)]
279
+ while tokenizer.check("BOOLOP"):
280
+ token = tokenizer.read()
281
+ expr_right = _parse_marker_atom(tokenizer)
282
+ expression.extend((token.text, expr_right))
283
+ return expression
284
+
285
+
286
+ def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
287
+ """
288
+ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
289
+ | WS? marker_item WS?
290
+ """
291
+
292
+ tokenizer.consume("WS")
293
+ if tokenizer.check("LEFT_PARENTHESIS", peek=True):
294
+ with tokenizer.enclosing_tokens(
295
+ "LEFT_PARENTHESIS",
296
+ "RIGHT_PARENTHESIS",
297
+ around="marker expression",
298
+ ):
299
+ tokenizer.consume("WS")
300
+ marker: MarkerAtom = _parse_marker(tokenizer)
301
+ tokenizer.consume("WS")
302
+ else:
303
+ marker = _parse_marker_item(tokenizer)
304
+ tokenizer.consume("WS")
305
+ return marker
306
+
307
+
308
+ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
309
+ """
310
+ marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
311
+ """
312
+ tokenizer.consume("WS")
313
+ marker_var_left = _parse_marker_var(tokenizer)
314
+ tokenizer.consume("WS")
315
+ marker_op = _parse_marker_op(tokenizer)
316
+ tokenizer.consume("WS")
317
+ marker_var_right = _parse_marker_var(tokenizer)
318
+ tokenizer.consume("WS")
319
+ return (marker_var_left, marker_op, marker_var_right)
320
+
321
+
322
+ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503
323
+ """
324
+ marker_var = VARIABLE | QUOTED_STRING
325
+ """
326
+ if tokenizer.check("VARIABLE"):
327
+ return process_env_var(tokenizer.read().text.replace(".", "_"))
328
+ elif tokenizer.check("QUOTED_STRING"):
329
+ return process_python_str(tokenizer.read().text)
330
+ else:
331
+ tokenizer.raise_syntax_error(
332
+ message="Expected a marker variable or quoted string"
333
+ )
334
+
335
+
336
+ def process_env_var(env_var: str) -> Variable:
337
+ if env_var in ("platform_python_implementation", "python_implementation"):
338
+ return Variable("platform_python_implementation")
339
+ else:
340
+ return Variable(env_var)
341
+
342
+
343
+ def process_python_str(python_str: str) -> Value:
344
+ value = ast.literal_eval(python_str)
345
+ return Value(str(value))
346
+
347
+
348
+ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
349
+ """
350
+ marker_op = IN | NOT IN | OP
351
+ """
352
+ if tokenizer.check("IN"):
353
+ tokenizer.read()
354
+ return Op("in")
355
+ elif tokenizer.check("NOT"):
356
+ tokenizer.read()
357
+ tokenizer.expect("WS", expected="whitespace after 'not'")
358
+ tokenizer.expect("IN", expected="'in' after 'not'")
359
+ return Op("not in")
360
+ elif tokenizer.check("OP"):
361
+ return Op(tokenizer.read().text)
362
+ else:
363
+ return tokenizer.raise_syntax_error(
364
+ "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
365
+ )
python/Lib/site-packages/setuptools/_vendor/packaging/_structures.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+
8
+ @typing.final
9
+ class InfinityType:
10
+ __slots__ = ()
11
+
12
+ def __repr__(self) -> str:
13
+ return "Infinity"
14
+
15
+ def __hash__(self) -> int:
16
+ return hash(repr(self))
17
+
18
+ def __lt__(self, other: object) -> bool:
19
+ return False
20
+
21
+ def __le__(self, other: object) -> bool:
22
+ return False
23
+
24
+ def __eq__(self, other: object) -> bool:
25
+ return isinstance(other, self.__class__)
26
+
27
+ def __gt__(self, other: object) -> bool:
28
+ return True
29
+
30
+ def __ge__(self, other: object) -> bool:
31
+ return True
32
+
33
+ def __neg__(self: object) -> "NegativeInfinityType":
34
+ return NegativeInfinity
35
+
36
+
37
+ Infinity = InfinityType()
38
+
39
+
40
+ @typing.final
41
+ class NegativeInfinityType:
42
+ __slots__ = ()
43
+
44
+ def __repr__(self) -> str:
45
+ return "-Infinity"
46
+
47
+ def __hash__(self) -> int:
48
+ return hash(repr(self))
49
+
50
+ def __lt__(self, other: object) -> bool:
51
+ return True
52
+
53
+ def __le__(self, other: object) -> bool:
54
+ return True
55
+
56
+ def __eq__(self, other: object) -> bool:
57
+ return isinstance(other, self.__class__)
58
+
59
+ def __gt__(self, other: object) -> bool:
60
+ return False
61
+
62
+ def __ge__(self, other: object) -> bool:
63
+ return False
64
+
65
+ def __neg__(self: object) -> InfinityType:
66
+ return Infinity
67
+
68
+
69
+ NegativeInfinity = NegativeInfinityType()
python/Lib/site-packages/setuptools/_vendor/packaging/_tokenizer.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Generator, Mapping, NoReturn
7
+
8
+ from .specifiers import Specifier
9
+
10
+
11
+ @dataclass
12
+ class Token:
13
+ name: str
14
+ text: str
15
+ position: int
16
+
17
+
18
+ class ParserSyntaxError(Exception):
19
+ """The provided source text could not be parsed correctly."""
20
+
21
+ def __init__(
22
+ self,
23
+ message: str,
24
+ *,
25
+ source: str,
26
+ span: tuple[int, int],
27
+ ) -> None:
28
+ self.span = span
29
+ self.message = message
30
+ self.source = source
31
+
32
+ super().__init__()
33
+
34
+ def __str__(self) -> str:
35
+ marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
36
+ return f"{self.message}\n {self.source}\n {marker}"
37
+
38
+
39
+ DEFAULT_RULES: dict[str, re.Pattern[str]] = {
40
+ "LEFT_PARENTHESIS": re.compile(r"\("),
41
+ "RIGHT_PARENTHESIS": re.compile(r"\)"),
42
+ "LEFT_BRACKET": re.compile(r"\["),
43
+ "RIGHT_BRACKET": re.compile(r"\]"),
44
+ "SEMICOLON": re.compile(r";"),
45
+ "COMMA": re.compile(r","),
46
+ "QUOTED_STRING": re.compile(
47
+ r"""
48
+ (
49
+ ('[^']*')
50
+ |
51
+ ("[^"]*")
52
+ )
53
+ """,
54
+ re.VERBOSE,
55
+ ),
56
+ "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"),
57
+ "BOOLOP": re.compile(r"\b(or|and)\b"),
58
+ "IN": re.compile(r"\bin\b"),
59
+ "NOT": re.compile(r"\bnot\b"),
60
+ "VARIABLE": re.compile(
61
+ r"""
62
+ \b(
63
+ python_version
64
+ |python_full_version
65
+ |os[._]name
66
+ |sys[._]platform
67
+ |platform_(release|system)
68
+ |platform[._](version|machine|python_implementation)
69
+ |python_implementation
70
+ |implementation_(name|version)
71
+ |extras?
72
+ |dependency_groups
73
+ )\b
74
+ """,
75
+ re.VERBOSE,
76
+ ),
77
+ "SPECIFIER": re.compile(
78
+ Specifier._operator_regex_str + Specifier._version_regex_str,
79
+ re.VERBOSE | re.IGNORECASE,
80
+ ),
81
+ "AT": re.compile(r"\@"),
82
+ "URL": re.compile(r"[^ \t]+"),
83
+ "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"),
84
+ "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"),
85
+ "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"),
86
+ "WS": re.compile(r"[ \t]+"),
87
+ "END": re.compile(r"$"),
88
+ }
89
+
90
+
91
+ class Tokenizer:
92
+ """Context-sensitive token parsing.
93
+
94
+ Provides methods to examine the input stream to check whether the next token
95
+ matches.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ source: str,
101
+ *,
102
+ rules: Mapping[str, re.Pattern[str]],
103
+ ) -> None:
104
+ self.source = source
105
+ self.rules = rules
106
+ self.next_token: Token | None = None
107
+ self.position = 0
108
+
109
+ def consume(self, name: str) -> None:
110
+ """Move beyond provided token name, if at current position."""
111
+ if self.check(name):
112
+ self.read()
113
+
114
+ def check(self, name: str, *, peek: bool = False) -> bool:
115
+ """Check whether the next token has the provided name.
116
+
117
+ By default, if the check succeeds, the token *must* be read before
118
+ another check. If `peek` is set to `True`, the token is not loaded and
119
+ would need to be checked again.
120
+ """
121
+ assert self.next_token is None, (
122
+ f"Cannot check for {name!r}, already have {self.next_token!r}"
123
+ )
124
+ assert name in self.rules, f"Unknown token name: {name!r}"
125
+
126
+ expression = self.rules[name]
127
+
128
+ match = expression.match(self.source, self.position)
129
+ if match is None:
130
+ return False
131
+ if not peek:
132
+ self.next_token = Token(name, match[0], self.position)
133
+ return True
134
+
135
+ def expect(self, name: str, *, expected: str) -> Token:
136
+ """Expect a certain token name next, failing with a syntax error otherwise.
137
+
138
+ The token is *not* read.
139
+ """
140
+ if not self.check(name):
141
+ raise self.raise_syntax_error(f"Expected {expected}")
142
+ return self.read()
143
+
144
+ def read(self) -> Token:
145
+ """Consume the next token and return it."""
146
+ token = self.next_token
147
+ assert token is not None
148
+
149
+ self.position += len(token.text)
150
+ self.next_token = None
151
+
152
+ return token
153
+
154
+ def raise_syntax_error(
155
+ self,
156
+ message: str,
157
+ *,
158
+ span_start: int | None = None,
159
+ span_end: int | None = None,
160
+ ) -> NoReturn:
161
+ """Raise ParserSyntaxError at the given position."""
162
+ span = (
163
+ self.position if span_start is None else span_start,
164
+ self.position if span_end is None else span_end,
165
+ )
166
+ raise ParserSyntaxError(
167
+ message,
168
+ source=self.source,
169
+ span=span,
170
+ )
171
+
172
+ @contextlib.contextmanager
173
+ def enclosing_tokens(
174
+ self, open_token: str, close_token: str, *, around: str
175
+ ) -> Generator[None, None, None]:
176
+ if self.check(open_token):
177
+ open_position = self.position
178
+ self.read()
179
+ else:
180
+ open_position = None
181
+
182
+ yield
183
+
184
+ if open_position is None:
185
+ return
186
+
187
+ if not self.check(close_token):
188
+ self.raise_syntax_error(
189
+ f"Expected matching {close_token} for {open_token}, after {around}",
190
+ span_start=open_position,
191
+ )
192
+
193
+ self.read()
python/Lib/site-packages/setuptools/_vendor/packaging/markers.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import operator
8
+ import os
9
+ import platform
10
+ import sys
11
+ from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
12
+
13
+ from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
14
+ from ._parser import parse_marker as _parse_marker
15
+ from ._tokenizer import ParserSyntaxError
16
+ from .specifiers import InvalidSpecifier, Specifier
17
+ from .utils import canonicalize_name
18
+
19
+ __all__ = [
20
+ "Environment",
21
+ "EvaluateContext",
22
+ "InvalidMarker",
23
+ "Marker",
24
+ "UndefinedComparison",
25
+ "UndefinedEnvironmentName",
26
+ "default_environment",
27
+ ]
28
+
29
+ Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
30
+ EvaluateContext = Literal["metadata", "lock_file", "requirement"]
31
+ MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
32
+ MARKERS_REQUIRING_VERSION = {
33
+ "implementation_version",
34
+ "platform_release",
35
+ "python_full_version",
36
+ "python_version",
37
+ }
38
+
39
+
40
+ class InvalidMarker(ValueError):
41
+ """
42
+ An invalid marker was found, users should refer to PEP 508.
43
+ """
44
+
45
+
46
+ class UndefinedComparison(ValueError):
47
+ """
48
+ An invalid operation was attempted on a value that doesn't support it.
49
+ """
50
+
51
+
52
+ class UndefinedEnvironmentName(ValueError):
53
+ """
54
+ A name was attempted to be used that does not exist inside of the
55
+ environment.
56
+ """
57
+
58
+
59
+ class Environment(TypedDict):
60
+ implementation_name: str
61
+ """The implementation's identifier, e.g. ``'cpython'``."""
62
+
63
+ implementation_version: str
64
+ """
65
+ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
66
+ ``'7.3.13'`` for PyPy3.10 v7.3.13.
67
+ """
68
+
69
+ os_name: str
70
+ """
71
+ The value of :py:data:`os.name`. The name of the operating system dependent module
72
+ imported, e.g. ``'posix'``.
73
+ """
74
+
75
+ platform_machine: str
76
+ """
77
+ Returns the machine type, e.g. ``'i386'``.
78
+
79
+ An empty string if the value cannot be determined.
80
+ """
81
+
82
+ platform_release: str
83
+ """
84
+ The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
85
+
86
+ An empty string if the value cannot be determined.
87
+ """
88
+
89
+ platform_system: str
90
+ """
91
+ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
92
+
93
+ An empty string if the value cannot be determined.
94
+ """
95
+
96
+ platform_version: str
97
+ """
98
+ The system's release version, e.g. ``'#3 on degas'``.
99
+
100
+ An empty string if the value cannot be determined.
101
+ """
102
+
103
+ python_full_version: str
104
+ """
105
+ The Python version as string ``'major.minor.patchlevel'``.
106
+
107
+ Note that unlike the Python :py:data:`sys.version`, this value will always include
108
+ the patchlevel (it defaults to 0).
109
+ """
110
+
111
+ platform_python_implementation: str
112
+ """
113
+ A string identifying the Python implementation, e.g. ``'CPython'``.
114
+ """
115
+
116
+ python_version: str
117
+ """The Python version as string ``'major.minor'``."""
118
+
119
+ sys_platform: str
120
+ """
121
+ This string contains a platform identifier that can be used to append
122
+ platform-specific components to :py:data:`sys.path`, for instance.
123
+
124
+ For Unix systems, except on Linux and AIX, this is the lowercased OS name as
125
+ returned by ``uname -s`` with the first part of the version as returned by
126
+ ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
127
+ was built.
128
+ """
129
+
130
+
131
+ def _normalize_extras(
132
+ result: MarkerList | MarkerAtom | str,
133
+ ) -> MarkerList | MarkerAtom | str:
134
+ if not isinstance(result, tuple):
135
+ return result
136
+
137
+ lhs, op, rhs = result
138
+ if isinstance(lhs, Variable) and lhs.value == "extra":
139
+ normalized_extra = canonicalize_name(rhs.value)
140
+ rhs = Value(normalized_extra)
141
+ elif isinstance(rhs, Variable) and rhs.value == "extra":
142
+ normalized_extra = canonicalize_name(lhs.value)
143
+ lhs = Value(normalized_extra)
144
+ return lhs, op, rhs
145
+
146
+
147
+ def _normalize_extra_values(results: MarkerList) -> MarkerList:
148
+ """
149
+ Normalize extra values.
150
+ """
151
+
152
+ return [_normalize_extras(r) for r in results]
153
+
154
+
155
+ def _format_marker(
156
+ marker: list[str] | MarkerAtom | str, first: bool | None = True
157
+ ) -> str:
158
+ assert isinstance(marker, (list, tuple, str))
159
+
160
+ # Sometimes we have a structure like [[...]] which is a single item list
161
+ # where the single item is itself it's own list. In that case we want skip
162
+ # the rest of this function so that we don't get extraneous () on the
163
+ # outside.
164
+ if (
165
+ isinstance(marker, list)
166
+ and len(marker) == 1
167
+ and isinstance(marker[0], (list, tuple))
168
+ ):
169
+ return _format_marker(marker[0])
170
+
171
+ if isinstance(marker, list):
172
+ inner = (_format_marker(m, first=False) for m in marker)
173
+ if first:
174
+ return " ".join(inner)
175
+ else:
176
+ return "(" + " ".join(inner) + ")"
177
+ elif isinstance(marker, tuple):
178
+ return " ".join([m.serialize() for m in marker])
179
+ else:
180
+ return marker
181
+
182
+
183
+ _operators: dict[str, Operator] = {
184
+ "in": lambda lhs, rhs: lhs in rhs,
185
+ "not in": lambda lhs, rhs: lhs not in rhs,
186
+ "<": lambda _lhs, _rhs: False,
187
+ "<=": operator.eq,
188
+ "==": operator.eq,
189
+ "!=": operator.ne,
190
+ ">=": operator.eq,
191
+ ">": lambda _lhs, _rhs: False,
192
+ }
193
+
194
+
195
+ def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:
196
+ op_str = op.serialize()
197
+ if key in MARKERS_REQUIRING_VERSION:
198
+ try:
199
+ spec = Specifier(f"{op_str}{rhs}")
200
+ except InvalidSpecifier:
201
+ pass
202
+ else:
203
+ return spec.contains(lhs, prereleases=True)
204
+
205
+ oper: Operator | None = _operators.get(op_str)
206
+ if oper is None:
207
+ raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
208
+
209
+ return oper(lhs, rhs)
210
+
211
+
212
+ def _normalize(
213
+ lhs: str, rhs: str | AbstractSet[str], key: str
214
+ ) -> tuple[str, str | AbstractSet[str]]:
215
+ # PEP 685 - Comparison of extra names for optional distribution dependencies
216
+ # https://peps.python.org/pep-0685/
217
+ # > When comparing extra names, tools MUST normalize the names being
218
+ # > compared using the semantics outlined in PEP 503 for names
219
+ if key == "extra":
220
+ assert isinstance(rhs, str), "extra value must be a string"
221
+ # Both sides are normalized at this point already
222
+ return (lhs, rhs)
223
+ if key in MARKERS_ALLOWING_SET:
224
+ if isinstance(rhs, str): # pragma: no cover
225
+ return (canonicalize_name(lhs), canonicalize_name(rhs))
226
+ else:
227
+ return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
228
+
229
+ # other environment markers don't have such standards
230
+ return lhs, rhs
231
+
232
+
233
+ def _evaluate_markers(
234
+ markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
235
+ ) -> bool:
236
+ groups: list[list[bool]] = [[]]
237
+
238
+ for marker in markers:
239
+ if isinstance(marker, list):
240
+ groups[-1].append(_evaluate_markers(marker, environment))
241
+ elif isinstance(marker, tuple):
242
+ lhs, op, rhs = marker
243
+
244
+ if isinstance(lhs, Variable):
245
+ environment_key = lhs.value
246
+ lhs_value = environment[environment_key]
247
+ rhs_value = rhs.value
248
+ else:
249
+ lhs_value = lhs.value
250
+ environment_key = rhs.value
251
+ rhs_value = environment[environment_key]
252
+
253
+ assert isinstance(lhs_value, str), "lhs must be a string"
254
+ lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
255
+ groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))
256
+ elif marker == "or":
257
+ groups.append([])
258
+ elif marker == "and":
259
+ pass
260
+ else: # pragma: nocover
261
+ raise TypeError(f"Unexpected marker {marker!r}")
262
+
263
+ return any(all(item) for item in groups)
264
+
265
+
266
+ def format_full_version(info: sys._version_info) -> str:
267
+ version = f"{info.major}.{info.minor}.{info.micro}"
268
+ kind = info.releaselevel
269
+ if kind != "final":
270
+ version += kind[0] + str(info.serial)
271
+ return version
272
+
273
+
274
+ def default_environment() -> Environment:
275
+ iver = format_full_version(sys.implementation.version)
276
+ implementation_name = sys.implementation.name
277
+ return {
278
+ "implementation_name": implementation_name,
279
+ "implementation_version": iver,
280
+ "os_name": os.name,
281
+ "platform_machine": platform.machine(),
282
+ "platform_release": platform.release(),
283
+ "platform_system": platform.system(),
284
+ "platform_version": platform.version(),
285
+ "python_full_version": platform.python_version(),
286
+ "platform_python_implementation": platform.python_implementation(),
287
+ "python_version": ".".join(platform.python_version_tuple()[:2]),
288
+ "sys_platform": sys.platform,
289
+ }
290
+
291
+
292
+ class Marker:
293
+ def __init__(self, marker: str) -> None:
294
+ # Note: We create a Marker object without calling this constructor in
295
+ # packaging.requirements.Requirement. If any additional logic is
296
+ # added here, make sure to mirror/adapt Requirement.
297
+
298
+ # If this fails and throws an error, the repr still expects _markers to
299
+ # be defined.
300
+ self._markers: MarkerList = []
301
+
302
+ try:
303
+ self._markers = _normalize_extra_values(_parse_marker(marker))
304
+ # The attribute `_markers` can be described in terms of a recursive type:
305
+ # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
306
+ #
307
+ # For example, the following expression:
308
+ # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
309
+ #
310
+ # is parsed into:
311
+ # [
312
+ # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),
313
+ # 'and',
314
+ # [
315
+ # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),
316
+ # 'or',
317
+ # (<Variable('os_name')>, <Op('==')>, <Value('unix')>)
318
+ # ]
319
+ # ]
320
+ except ParserSyntaxError as e:
321
+ raise InvalidMarker(str(e)) from e
322
+
323
+ def __str__(self) -> str:
324
+ return _format_marker(self._markers)
325
+
326
+ def __repr__(self) -> str:
327
+ return f"<{self.__class__.__name__}('{self}')>"
328
+
329
+ def __hash__(self) -> int:
330
+ return hash(str(self))
331
+
332
+ def __eq__(self, other: object) -> bool:
333
+ if not isinstance(other, Marker):
334
+ return NotImplemented
335
+
336
+ return str(self) == str(other)
337
+
338
+ def evaluate(
339
+ self,
340
+ environment: Mapping[str, str | AbstractSet[str]] | None = None,
341
+ context: EvaluateContext = "metadata",
342
+ ) -> bool:
343
+ """Evaluate a marker.
344
+
345
+ Return the boolean from evaluating the given marker against the
346
+ environment. environment is an optional argument to override all or
347
+ part of the determined environment. The *context* parameter specifies what
348
+ context the markers are being evaluated for, which influences what markers
349
+ are considered valid. Acceptable values are "metadata" (for core metadata;
350
+ default), "lock_file", and "requirement" (i.e. all other situations).
351
+
352
+ The environment is determined from the current Python process.
353
+ """
354
+ current_environment = cast(
355
+ "dict[str, str | AbstractSet[str]]", default_environment()
356
+ )
357
+ if context == "lock_file":
358
+ current_environment.update(
359
+ extras=frozenset(), dependency_groups=frozenset()
360
+ )
361
+ elif context == "metadata":
362
+ current_environment["extra"] = ""
363
+
364
+ if environment is not None:
365
+ current_environment.update(environment)
366
+ if "extra" in current_environment:
367
+ # The API used to allow setting extra to None. We need to handle
368
+ # this case for backwards compatibility. Also skip running
369
+ # normalize name if extra is empty.
370
+ extra = cast("str | None", current_environment["extra"])
371
+ current_environment["extra"] = canonicalize_name(extra) if extra else ""
372
+
373
+ return _evaluate_markers(
374
+ self._markers, _repair_python_full_version(current_environment)
375
+ )
376
+
377
+
378
+ def _repair_python_full_version(
379
+ env: dict[str, str | AbstractSet[str]],
380
+ ) -> dict[str, str | AbstractSet[str]]:
381
+ """
382
+ Work around platform.python_version() returning something that is not PEP 440
383
+ compliant for non-tagged Python builds.
384
+ """
385
+ python_full_version = cast("str", env["python_full_version"])
386
+ if python_full_version.endswith("+"):
387
+ env["python_full_version"] = f"{python_full_version}local"
388
+ return env
python/Lib/site-packages/setuptools/_vendor/packaging/metadata.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import email.feedparser
4
+ import email.header
5
+ import email.message
6
+ import email.parser
7
+ import email.policy
8
+ import keyword
9
+ import pathlib
10
+ import sys
11
+ import typing
12
+ from typing import (
13
+ Any,
14
+ Callable,
15
+ Generic,
16
+ Literal,
17
+ TypedDict,
18
+ cast,
19
+ )
20
+
21
+ from . import licenses, requirements, specifiers, utils
22
+ from . import version as version_module
23
+
24
+ if typing.TYPE_CHECKING:
25
+ from .licenses import NormalizedLicenseExpression
26
+
27
+ T = typing.TypeVar("T")
28
+
29
+
30
+ if sys.version_info >= (3, 11): # pragma: no cover
31
+ ExceptionGroup = ExceptionGroup # noqa: F821
32
+ else: # pragma: no cover
33
+
34
+ class ExceptionGroup(Exception):
35
+ """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
36
+
37
+ If :external:exc:`ExceptionGroup` is already defined by Python itself,
38
+ that version is used instead.
39
+ """
40
+
41
+ message: str
42
+ exceptions: list[Exception]
43
+
44
+ def __init__(self, message: str, exceptions: list[Exception]) -> None:
45
+ self.message = message
46
+ self.exceptions = exceptions
47
+
48
+ def __repr__(self) -> str:
49
+ return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
50
+
51
+
52
+ class InvalidMetadata(ValueError):
53
+ """A metadata field contains invalid data."""
54
+
55
+ field: str
56
+ """The name of the field that contains invalid data."""
57
+
58
+ def __init__(self, field: str, message: str) -> None:
59
+ self.field = field
60
+ super().__init__(message)
61
+
62
+
63
+ # The RawMetadata class attempts to make as few assumptions about the underlying
64
+ # serialization formats as possible. The idea is that as long as a serialization
65
+ # formats offer some very basic primitives in *some* way then we can support
66
+ # serializing to and from that format.
67
+ class RawMetadata(TypedDict, total=False):
68
+ """A dictionary of raw core metadata.
69
+
70
+ Each field in core metadata maps to a key of this dictionary (when data is
71
+ provided). The key is lower-case and underscores are used instead of dashes
72
+ compared to the equivalent core metadata field. Any core metadata field that
73
+ can be specified multiple times or can hold multiple values in a single
74
+ field have a key with a plural name. See :class:`Metadata` whose attributes
75
+ match the keys of this dictionary.
76
+
77
+ Core metadata fields that can be specified multiple times are stored as a
78
+ list or dict depending on which is appropriate for the field. Any fields
79
+ which hold multiple values in a single field are stored as a list.
80
+
81
+ """
82
+
83
+ # Metadata 1.0 - PEP 241
84
+ metadata_version: str
85
+ name: str
86
+ version: str
87
+ platforms: list[str]
88
+ summary: str
89
+ description: str
90
+ keywords: list[str]
91
+ home_page: str
92
+ author: str
93
+ author_email: str
94
+ license: str
95
+
96
+ # Metadata 1.1 - PEP 314
97
+ supported_platforms: list[str]
98
+ download_url: str
99
+ classifiers: list[str]
100
+ requires: list[str]
101
+ provides: list[str]
102
+ obsoletes: list[str]
103
+
104
+ # Metadata 1.2 - PEP 345
105
+ maintainer: str
106
+ maintainer_email: str
107
+ requires_dist: list[str]
108
+ provides_dist: list[str]
109
+ obsoletes_dist: list[str]
110
+ requires_python: str
111
+ requires_external: list[str]
112
+ project_urls: dict[str, str]
113
+
114
+ # Metadata 2.0
115
+ # PEP 426 attempted to completely revamp the metadata format
116
+ # but got stuck without ever being able to build consensus on
117
+ # it and ultimately ended up withdrawn.
118
+ #
119
+ # However, a number of tools had started emitting METADATA with
120
+ # `2.0` Metadata-Version, so for historical reasons, this version
121
+ # was skipped.
122
+
123
+ # Metadata 2.1 - PEP 566
124
+ description_content_type: str
125
+ provides_extra: list[str]
126
+
127
+ # Metadata 2.2 - PEP 643
128
+ dynamic: list[str]
129
+
130
+ # Metadata 2.3 - PEP 685
131
+ # No new fields were added in PEP 685, just some edge case were
132
+ # tightened up to provide better interoperability.
133
+
134
+ # Metadata 2.4 - PEP 639
135
+ license_expression: str
136
+ license_files: list[str]
137
+
138
+ # Metadata 2.5 - PEP 794
139
+ import_names: list[str]
140
+ import_namespaces: list[str]
141
+
142
+
143
+ # 'keywords' is special as it's a string in the core metadata spec, but we
144
+ # represent it as a list.
145
+ _STRING_FIELDS = {
146
+ "author",
147
+ "author_email",
148
+ "description",
149
+ "description_content_type",
150
+ "download_url",
151
+ "home_page",
152
+ "license",
153
+ "license_expression",
154
+ "maintainer",
155
+ "maintainer_email",
156
+ "metadata_version",
157
+ "name",
158
+ "requires_python",
159
+ "summary",
160
+ "version",
161
+ }
162
+
163
+ _LIST_FIELDS = {
164
+ "classifiers",
165
+ "dynamic",
166
+ "license_files",
167
+ "obsoletes",
168
+ "obsoletes_dist",
169
+ "platforms",
170
+ "provides",
171
+ "provides_dist",
172
+ "provides_extra",
173
+ "requires",
174
+ "requires_dist",
175
+ "requires_external",
176
+ "supported_platforms",
177
+ "import_names",
178
+ "import_namespaces",
179
+ }
180
+
181
+ _DICT_FIELDS = {
182
+ "project_urls",
183
+ }
184
+
185
+
186
+ def _parse_keywords(data: str) -> list[str]:
187
+ """Split a string of comma-separated keywords into a list of keywords."""
188
+ return [k.strip() for k in data.split(",")]
189
+
190
+
191
+ def _parse_project_urls(data: list[str]) -> dict[str, str]:
192
+ """Parse a list of label/URL string pairings separated by a comma."""
193
+ urls = {}
194
+ for pair in data:
195
+ # Our logic is slightly tricky here as we want to try and do
196
+ # *something* reasonable with malformed data.
197
+ #
198
+ # The main thing that we have to worry about, is data that does
199
+ # not have a ',' at all to split the label from the Value. There
200
+ # isn't a singular right answer here, and we will fail validation
201
+ # later on (if the caller is validating) so it doesn't *really*
202
+ # matter, but since the missing value has to be an empty str
203
+ # and our return value is dict[str, str], if we let the key
204
+ # be the missing value, then they'd have multiple '' values that
205
+ # overwrite each other in a accumulating dict.
206
+ #
207
+ # The other potential issue is that it's possible to have the
208
+ # same label multiple times in the metadata, with no solid "right"
209
+ # answer with what to do in that case. As such, we'll do the only
210
+ # thing we can, which is treat the field as unparsable and add it
211
+ # to our list of unparsed fields.
212
+ #
213
+ # TODO: The spec doesn't say anything about if the keys should be
214
+ # considered case sensitive or not... logically they should
215
+ # be case-preserving and case-insensitive, but doing that
216
+ # would open up more cases where we might have duplicate
217
+ # entries.
218
+ label, _, url = (s.strip() for s in pair.partition(","))
219
+
220
+ if label in urls:
221
+ # The label already exists in our set of urls, so this field
222
+ # is unparsable, and we can just add the whole thing to our
223
+ # unparsable data and stop processing it.
224
+ raise KeyError("duplicate labels in project urls")
225
+ urls[label] = url
226
+
227
+ return urls
228
+
229
+
230
+ def _get_payload(msg: email.message.Message, source: bytes | str) -> str:
231
+ """Get the body of the message."""
232
+ # If our source is a str, then our caller has managed encodings for us,
233
+ # and we don't need to deal with it.
234
+ if isinstance(source, str):
235
+ payload = msg.get_payload()
236
+ assert isinstance(payload, str)
237
+ return payload
238
+ # If our source is a bytes, then we're managing the encoding and we need
239
+ # to deal with it.
240
+ else:
241
+ bpayload = msg.get_payload(decode=True)
242
+ assert isinstance(bpayload, bytes)
243
+ try:
244
+ return bpayload.decode("utf8", "strict")
245
+ except UnicodeDecodeError as exc:
246
+ raise ValueError("payload in an invalid encoding") from exc
247
+
248
+
249
+ # The various parse_FORMAT functions here are intended to be as lenient as
250
+ # possible in their parsing, while still returning a correctly typed
251
+ # RawMetadata.
252
+ #
253
+ # To aid in this, we also generally want to do as little touching of the
254
+ # data as possible, except where there are possibly some historic holdovers
255
+ # that make valid data awkward to work with.
256
+ #
257
+ # While this is a lower level, intermediate format than our ``Metadata``
258
+ # class, some light touch ups can make a massive difference in usability.
259
+
260
+ # Map METADATA fields to RawMetadata.
261
+ _EMAIL_TO_RAW_MAPPING = {
262
+ "author": "author",
263
+ "author-email": "author_email",
264
+ "classifier": "classifiers",
265
+ "description": "description",
266
+ "description-content-type": "description_content_type",
267
+ "download-url": "download_url",
268
+ "dynamic": "dynamic",
269
+ "home-page": "home_page",
270
+ "import-name": "import_names",
271
+ "import-namespace": "import_namespaces",
272
+ "keywords": "keywords",
273
+ "license": "license",
274
+ "license-expression": "license_expression",
275
+ "license-file": "license_files",
276
+ "maintainer": "maintainer",
277
+ "maintainer-email": "maintainer_email",
278
+ "metadata-version": "metadata_version",
279
+ "name": "name",
280
+ "obsoletes": "obsoletes",
281
+ "obsoletes-dist": "obsoletes_dist",
282
+ "platform": "platforms",
283
+ "project-url": "project_urls",
284
+ "provides": "provides",
285
+ "provides-dist": "provides_dist",
286
+ "provides-extra": "provides_extra",
287
+ "requires": "requires",
288
+ "requires-dist": "requires_dist",
289
+ "requires-external": "requires_external",
290
+ "requires-python": "requires_python",
291
+ "summary": "summary",
292
+ "supported-platform": "supported_platforms",
293
+ "version": "version",
294
+ }
295
+ _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
296
+
297
+
298
+ # This class is for writing RFC822 messages
299
+ class RFC822Policy(email.policy.EmailPolicy):
300
+ """
301
+ This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``
302
+ implementation that handles multi-line values, and some nice defaults.
303
+ """
304
+
305
+ utf8 = True
306
+ mangle_from_ = False
307
+ max_line_length = 0
308
+
309
+ def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
310
+ size = len(name) + 2
311
+ value = value.replace("\n", "\n" + " " * size)
312
+ return (name, value)
313
+
314
+
315
+ # This class is for writing RFC822 messages
316
+ class RFC822Message(email.message.EmailMessage):
317
+ """
318
+ This is :class:`email.message.EmailMessage` with two small changes: it defaults to
319
+ our `RFC822Policy`, and it correctly writes unicode when being called
320
+ with `bytes()`.
321
+ """
322
+
323
+ def __init__(self) -> None:
324
+ super().__init__(policy=RFC822Policy())
325
+
326
+ def as_bytes(
327
+ self, unixfrom: bool = False, policy: email.policy.Policy | None = None
328
+ ) -> bytes:
329
+ """
330
+ Return the bytes representation of the message.
331
+
332
+ This handles unicode encoding.
333
+ """
334
+ return self.as_string(unixfrom, policy=policy).encode("utf-8")
335
+
336
+
337
+ def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
338
+ """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
339
+
340
+ This function returns a two-item tuple of dicts. The first dict is of
341
+ recognized fields from the core metadata specification. Fields that can be
342
+ parsed and translated into Python's built-in types are converted
343
+ appropriately. All other fields are left as-is. Fields that are allowed to
344
+ appear multiple times are stored as lists.
345
+
346
+ The second dict contains all other fields from the metadata. This includes
347
+ any unrecognized fields. It also includes any fields which are expected to
348
+ be parsed into a built-in type but were not formatted appropriately. Finally,
349
+ any fields that are expected to appear only once but are repeated are
350
+ included in this dict.
351
+
352
+ """
353
+ raw: dict[str, str | list[str] | dict[str, str]] = {}
354
+ unparsed: dict[str, list[str]] = {}
355
+
356
+ if isinstance(data, str):
357
+ parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
358
+ else:
359
+ parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
360
+
361
+ # We have to wrap parsed.keys() in a set, because in the case of multiple
362
+ # values for a key (a list), the key will appear multiple times in the
363
+ # list of keys, but we're avoiding that by using get_all().
364
+ for name_with_case in frozenset(parsed.keys()):
365
+ # Header names in RFC are case insensitive, so we'll normalize to all
366
+ # lower case to make comparisons easier.
367
+ name = name_with_case.lower()
368
+
369
+ # We use get_all() here, even for fields that aren't multiple use,
370
+ # because otherwise someone could have e.g. two Name fields, and we
371
+ # would just silently ignore it rather than doing something about it.
372
+ headers = parsed.get_all(name) or []
373
+
374
+ # The way the email module works when parsing bytes is that it
375
+ # unconditionally decodes the bytes as ascii using the surrogateescape
376
+ # handler. When you pull that data back out (such as with get_all() ),
377
+ # it looks to see if the str has any surrogate escapes, and if it does
378
+ # it wraps it in a Header object instead of returning the string.
379
+ #
380
+ # As such, we'll look for those Header objects, and fix up the encoding.
381
+ value = []
382
+ # Flag if we have run into any issues processing the headers, thus
383
+ # signalling that the data belongs in 'unparsed'.
384
+ valid_encoding = True
385
+ for h in headers:
386
+ # It's unclear if this can return more types than just a Header or
387
+ # a str, so we'll just assert here to make sure.
388
+ assert isinstance(h, (email.header.Header, str))
389
+
390
+ # If it's a header object, we need to do our little dance to get
391
+ # the real data out of it. In cases where there is invalid data
392
+ # we're going to end up with mojibake, but there's no obvious, good
393
+ # way around that without reimplementing parts of the Header object
394
+ # ourselves.
395
+ #
396
+ # That should be fine since, if mojibacked happens, this key is
397
+ # going into the unparsed dict anyways.
398
+ if isinstance(h, email.header.Header):
399
+ # The Header object stores it's data as chunks, and each chunk
400
+ # can be independently encoded, so we'll need to check each
401
+ # of them.
402
+ chunks: list[tuple[bytes, str | None]] = []
403
+ for binary, _encoding in email.header.decode_header(h):
404
+ try:
405
+ binary.decode("utf8", "strict")
406
+ except UnicodeDecodeError:
407
+ # Enable mojibake.
408
+ encoding = "latin1"
409
+ valid_encoding = False
410
+ else:
411
+ encoding = "utf8"
412
+ chunks.append((binary, encoding))
413
+
414
+ # Turn our chunks back into a Header object, then let that
415
+ # Header object do the right thing to turn them into a
416
+ # string for us.
417
+ value.append(str(email.header.make_header(chunks)))
418
+ # This is already a string, so just add it.
419
+ else:
420
+ value.append(h)
421
+
422
+ # We've processed all of our values to get them into a list of str,
423
+ # but we may have mojibake data, in which case this is an unparsed
424
+ # field.
425
+ if not valid_encoding:
426
+ unparsed[name] = value
427
+ continue
428
+
429
+ raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
430
+ if raw_name is None:
431
+ # This is a bit of a weird situation, we've encountered a key that
432
+ # we don't know what it means, so we don't know whether it's meant
433
+ # to be a list or not.
434
+ #
435
+ # Since we can't really tell one way or another, we'll just leave it
436
+ # as a list, even though it may be a single item list, because that's
437
+ # what makes the most sense for email headers.
438
+ unparsed[name] = value
439
+ continue
440
+
441
+ # If this is one of our string fields, then we'll check to see if our
442
+ # value is a list of a single item. If it is then we'll assume that
443
+ # it was emitted as a single string, and unwrap the str from inside
444
+ # the list.
445
+ #
446
+ # If it's any other kind of data, then we haven't the faintest clue
447
+ # what we should parse it as, and we have to just add it to our list
448
+ # of unparsed stuff.
449
+ if raw_name in _STRING_FIELDS and len(value) == 1:
450
+ raw[raw_name] = value[0]
451
+ # If this is import_names, we need to special case the empty field
452
+ # case, which converts to an empty list instead of None. We can't let
453
+ # the empty case slip through, as it will fail validation.
454
+ elif raw_name == "import_names" and value == [""]:
455
+ raw[raw_name] = []
456
+ # If this is one of our list of string fields, then we can just assign
457
+ # the value, since email *only* has strings, and our get_all() call
458
+ # above ensures that this is a list.
459
+ elif raw_name in _LIST_FIELDS:
460
+ raw[raw_name] = value
461
+ # Special Case: Keywords
462
+ # The keywords field is implemented in the metadata spec as a str,
463
+ # but it conceptually is a list of strings, and is serialized using
464
+ # ", ".join(keywords), so we'll do some light data massaging to turn
465
+ # this into what it logically is.
466
+ elif raw_name == "keywords" and len(value) == 1:
467
+ raw[raw_name] = _parse_keywords(value[0])
468
+ # Special Case: Project-URL
469
+ # The project urls is implemented in the metadata spec as a list of
470
+ # specially-formatted strings that represent a key and a value, which
471
+ # is fundamentally a mapping, however the email format doesn't support
472
+ # mappings in a sane way, so it was crammed into a list of strings
473
+ # instead.
474
+ #
475
+ # We will do a little light data massaging to turn this into a map as
476
+ # it logically should be.
477
+ elif raw_name == "project_urls":
478
+ try:
479
+ raw[raw_name] = _parse_project_urls(value)
480
+ except KeyError:
481
+ unparsed[name] = value
482
+ # Nothing that we've done has managed to parse this, so it'll just
483
+ # throw it in our unparsable data and move on.
484
+ else:
485
+ unparsed[name] = value
486
+
487
+ # We need to support getting the Description from the message payload in
488
+ # addition to getting it from the the headers. This does mean, though, there
489
+ # is the possibility of it being set both ways, in which case we put both
490
+ # in 'unparsed' since we don't know which is right.
491
+ try:
492
+ payload = _get_payload(parsed, data)
493
+ except ValueError:
494
+ unparsed.setdefault("description", []).append(
495
+ parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload]
496
+ )
497
+ else:
498
+ if payload:
499
+ # Check to see if we've already got a description, if so then both
500
+ # it, and this body move to unparsable.
501
+ if "description" in raw:
502
+ description_header = cast("str", raw.pop("description"))
503
+ unparsed.setdefault("description", []).extend(
504
+ [description_header, payload]
505
+ )
506
+ elif "description" in unparsed:
507
+ unparsed["description"].append(payload)
508
+ else:
509
+ raw["description"] = payload
510
+
511
+ # We need to cast our `raw` to a metadata, because a TypedDict only support
512
+ # literal key names, but we're computing our key names on purpose, but the
513
+ # way this function is implemented, our `TypedDict` can only have valid key
514
+ # names.
515
+ return cast("RawMetadata", raw), unparsed
516
+
517
+
518
+ _NOT_FOUND = object()
519
+
520
+
521
+ # Keep the two values in sync.
522
+ _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
523
+ _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
524
+
525
+ _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
526
+
527
+
528
+ class _Validator(Generic[T]):
529
+ """Validate a metadata field.
530
+
531
+ All _process_*() methods correspond to a core metadata field. The method is
532
+ called with the field's raw value. If the raw value is valid it is returned
533
+ in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
534
+ If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
535
+ as appropriate).
536
+ """
537
+
538
+ name: str
539
+ raw_name: str
540
+ added: _MetadataVersion
541
+
542
+ def __init__(
543
+ self,
544
+ *,
545
+ added: _MetadataVersion = "1.0",
546
+ ) -> None:
547
+ self.added = added
548
+
549
+ def __set_name__(self, _owner: Metadata, name: str) -> None:
550
+ self.name = name
551
+ self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
552
+
553
+ def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:
554
+ # With Python 3.8, the caching can be replaced with functools.cached_property().
555
+ # No need to check the cache as attribute lookup will resolve into the
556
+ # instance's __dict__ before __get__ is called.
557
+ cache = instance.__dict__
558
+ value = instance._raw.get(self.name)
559
+
560
+ # To make the _process_* methods easier, we'll check if the value is None
561
+ # and if this field is NOT a required attribute, and if both of those
562
+ # things are true, we'll skip the the converter. This will mean that the
563
+ # converters never have to deal with the None union.
564
+ if self.name in _REQUIRED_ATTRS or value is not None:
565
+ try:
566
+ converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
567
+ except AttributeError:
568
+ pass
569
+ else:
570
+ value = converter(value)
571
+
572
+ cache[self.name] = value
573
+ try:
574
+ del instance._raw[self.name] # type: ignore[misc]
575
+ except KeyError:
576
+ pass
577
+
578
+ return cast("T", value)
579
+
580
+ def _invalid_metadata(
581
+ self, msg: str, cause: Exception | None = None
582
+ ) -> InvalidMetadata:
583
+ exc = InvalidMetadata(
584
+ self.raw_name, msg.format_map({"field": repr(self.raw_name)})
585
+ )
586
+ exc.__cause__ = cause
587
+ return exc
588
+
589
+ def _process_metadata_version(self, value: str) -> _MetadataVersion:
590
+ # Implicitly makes Metadata-Version required.
591
+ if value not in _VALID_METADATA_VERSIONS:
592
+ raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
593
+ return cast("_MetadataVersion", value)
594
+
595
+ def _process_name(self, value: str) -> str:
596
+ if not value:
597
+ raise self._invalid_metadata("{field} is a required field")
598
+ # Validate the name as a side-effect.
599
+ try:
600
+ utils.canonicalize_name(value, validate=True)
601
+ except utils.InvalidName as exc:
602
+ raise self._invalid_metadata(
603
+ f"{value!r} is invalid for {{field}}", cause=exc
604
+ ) from exc
605
+ else:
606
+ return value
607
+
608
+ def _process_version(self, value: str) -> version_module.Version:
609
+ if not value:
610
+ raise self._invalid_metadata("{field} is a required field")
611
+ try:
612
+ return version_module.parse(value)
613
+ except version_module.InvalidVersion as exc:
614
+ raise self._invalid_metadata(
615
+ f"{value!r} is invalid for {{field}}", cause=exc
616
+ ) from exc
617
+
618
+ def _process_summary(self, value: str) -> str:
619
+ """Check the field contains no newlines."""
620
+ if "\n" in value:
621
+ raise self._invalid_metadata("{field} must be a single line")
622
+ return value
623
+
624
+ def _process_description_content_type(self, value: str) -> str:
625
+ content_types = {"text/plain", "text/x-rst", "text/markdown"}
626
+ message = email.message.EmailMessage()
627
+ message["content-type"] = value
628
+
629
+ content_type, parameters = (
630
+ # Defaults to `text/plain` if parsing failed.
631
+ message.get_content_type().lower(),
632
+ message["content-type"].params,
633
+ )
634
+ # Check if content-type is valid or defaulted to `text/plain` and thus was
635
+ # not parseable.
636
+ if content_type not in content_types or content_type not in value.lower():
637
+ raise self._invalid_metadata(
638
+ f"{{field}} must be one of {list(content_types)}, not {value!r}"
639
+ )
640
+
641
+ charset = parameters.get("charset", "UTF-8")
642
+ if charset != "UTF-8":
643
+ raise self._invalid_metadata(
644
+ f"{{field}} can only specify the UTF-8 charset, not {list(charset)}"
645
+ )
646
+
647
+ markdown_variants = {"GFM", "CommonMark"}
648
+ variant = parameters.get("variant", "GFM") # Use an acceptable default.
649
+ if content_type == "text/markdown" and variant not in markdown_variants:
650
+ raise self._invalid_metadata(
651
+ f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
652
+ f"not {variant!r}",
653
+ )
654
+ return value
655
+
656
+ def _process_dynamic(self, value: list[str]) -> list[str]:
657
+ for dynamic_field in map(str.lower, value):
658
+ if dynamic_field in {"name", "version", "metadata-version"}:
659
+ raise self._invalid_metadata(
660
+ f"{dynamic_field!r} is not allowed as a dynamic field"
661
+ )
662
+ elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
663
+ raise self._invalid_metadata(
664
+ f"{dynamic_field!r} is not a valid dynamic field"
665
+ )
666
+ return list(map(str.lower, value))
667
+
668
+ def _process_provides_extra(
669
+ self,
670
+ value: list[str],
671
+ ) -> list[utils.NormalizedName]:
672
+ normalized_names = []
673
+ try:
674
+ for name in value:
675
+ normalized_names.append(utils.canonicalize_name(name, validate=True))
676
+ except utils.InvalidName as exc:
677
+ raise self._invalid_metadata(
678
+ f"{name!r} is invalid for {{field}}", cause=exc
679
+ ) from exc
680
+ else:
681
+ return normalized_names
682
+
683
+ def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
684
+ try:
685
+ return specifiers.SpecifierSet(value)
686
+ except specifiers.InvalidSpecifier as exc:
687
+ raise self._invalid_metadata(
688
+ f"{value!r} is invalid for {{field}}", cause=exc
689
+ ) from exc
690
+
691
+ def _process_requires_dist(
692
+ self,
693
+ value: list[str],
694
+ ) -> list[requirements.Requirement]:
695
+ reqs = []
696
+ try:
697
+ for req in value:
698
+ reqs.append(requirements.Requirement(req))
699
+ except requirements.InvalidRequirement as exc:
700
+ raise self._invalid_metadata(
701
+ f"{req!r} is invalid for {{field}}", cause=exc
702
+ ) from exc
703
+ else:
704
+ return reqs
705
+
706
+ def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:
707
+ try:
708
+ return licenses.canonicalize_license_expression(value)
709
+ except ValueError as exc:
710
+ raise self._invalid_metadata(
711
+ f"{value!r} is invalid for {{field}}", cause=exc
712
+ ) from exc
713
+
714
+ def _process_license_files(self, value: list[str]) -> list[str]:
715
+ paths = []
716
+ for path in value:
717
+ if ".." in path:
718
+ raise self._invalid_metadata(
719
+ f"{path!r} is invalid for {{field}}, "
720
+ "parent directory indicators are not allowed"
721
+ )
722
+ if "*" in path:
723
+ raise self._invalid_metadata(
724
+ f"{path!r} is invalid for {{field}}, paths must be resolved"
725
+ )
726
+ if (
727
+ pathlib.PurePosixPath(path).is_absolute()
728
+ or pathlib.PureWindowsPath(path).is_absolute()
729
+ ):
730
+ raise self._invalid_metadata(
731
+ f"{path!r} is invalid for {{field}}, paths must be relative"
732
+ )
733
+ if pathlib.PureWindowsPath(path).as_posix() != path:
734
+ raise self._invalid_metadata(
735
+ f"{path!r} is invalid for {{field}}, paths must use '/' delimiter"
736
+ )
737
+ paths.append(path)
738
+ return paths
739
+
740
+ def _process_import_names(self, value: list[str]) -> list[str]:
741
+ for import_name in value:
742
+ name, semicolon, private = import_name.partition(";")
743
+ name = name.rstrip()
744
+ for identifier in name.split("."):
745
+ if not identifier.isidentifier():
746
+ raise self._invalid_metadata(
747
+ f"{name!r} is invalid for {{field}}; "
748
+ f"{identifier!r} is not a valid identifier"
749
+ )
750
+ elif keyword.iskeyword(identifier):
751
+ raise self._invalid_metadata(
752
+ f"{name!r} is invalid for {{field}}; "
753
+ f"{identifier!r} is a keyword"
754
+ )
755
+ if semicolon and private.lstrip() != "private":
756
+ raise self._invalid_metadata(
757
+ f"{import_name!r} is invalid for {{field}}; "
758
+ "the only valid option is 'private'"
759
+ )
760
+ return value
761
+
762
+ _process_import_namespaces = _process_import_names
763
+
764
+
765
+ class Metadata:
766
+ """Representation of distribution metadata.
767
+
768
+ Compared to :class:`RawMetadata`, this class provides objects representing
769
+ metadata fields instead of only using built-in types. Any invalid metadata
770
+ will cause :exc:`InvalidMetadata` to be raised (with a
771
+ :py:attr:`~BaseException.__cause__` attribute as appropriate).
772
+ """
773
+
774
+ _raw: RawMetadata
775
+
776
+ @classmethod
777
+ def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:
778
+ """Create an instance from :class:`RawMetadata`.
779
+
780
+ If *validate* is true, all metadata will be validated. All exceptions
781
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
782
+ """
783
+ ins = cls()
784
+ ins._raw = data.copy() # Mutations occur due to caching enriched values.
785
+
786
+ if validate:
787
+ exceptions: list[Exception] = []
788
+ try:
789
+ metadata_version = ins.metadata_version
790
+ metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
791
+ except InvalidMetadata as metadata_version_exc:
792
+ exceptions.append(metadata_version_exc)
793
+ metadata_version = None
794
+
795
+ # Make sure to check for the fields that are present, the required
796
+ # fields (so their absence can be reported).
797
+ fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
798
+ # Remove fields that have already been checked.
799
+ fields_to_check -= {"metadata_version"}
800
+
801
+ for key in fields_to_check:
802
+ try:
803
+ if metadata_version:
804
+ # Can't use getattr() as that triggers descriptor protocol which
805
+ # will fail due to no value for the instance argument.
806
+ try:
807
+ field_metadata_version = cls.__dict__[key].added
808
+ except KeyError:
809
+ exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
810
+ exceptions.append(exc)
811
+ continue
812
+ field_age = _VALID_METADATA_VERSIONS.index(
813
+ field_metadata_version
814
+ )
815
+ if field_age > metadata_age:
816
+ field = _RAW_TO_EMAIL_MAPPING[key]
817
+ exc = InvalidMetadata(
818
+ field,
819
+ f"{field} introduced in metadata version "
820
+ f"{field_metadata_version}, not {metadata_version}",
821
+ )
822
+ exceptions.append(exc)
823
+ continue
824
+ getattr(ins, key)
825
+ except InvalidMetadata as exc:
826
+ exceptions.append(exc)
827
+
828
+ if exceptions:
829
+ raise ExceptionGroup("invalid metadata", exceptions)
830
+
831
+ return ins
832
+
833
+ @classmethod
834
+ def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:
835
+ """Parse metadata from email headers.
836
+
837
+ If *validate* is true, the metadata will be validated. All exceptions
838
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
839
+ """
840
+ raw, unparsed = parse_email(data)
841
+
842
+ if validate:
843
+ exceptions: list[Exception] = []
844
+ for unparsed_key in unparsed:
845
+ if unparsed_key in _EMAIL_TO_RAW_MAPPING:
846
+ message = f"{unparsed_key!r} has invalid data"
847
+ else:
848
+ message = f"unrecognized field: {unparsed_key!r}"
849
+ exceptions.append(InvalidMetadata(unparsed_key, message))
850
+
851
+ if exceptions:
852
+ raise ExceptionGroup("unparsed", exceptions)
853
+
854
+ try:
855
+ return cls.from_raw(raw, validate=validate)
856
+ except ExceptionGroup as exc_group:
857
+ raise ExceptionGroup(
858
+ "invalid or unparsed metadata", exc_group.exceptions
859
+ ) from None
860
+
861
+ metadata_version: _Validator[_MetadataVersion] = _Validator()
862
+ """:external:ref:`core-metadata-metadata-version`
863
+ (required; validated to be a valid metadata version)"""
864
+ # `name` is not normalized/typed to NormalizedName so as to provide access to
865
+ # the original/raw name.
866
+ name: _Validator[str] = _Validator()
867
+ """:external:ref:`core-metadata-name`
868
+ (required; validated using :func:`~packaging.utils.canonicalize_name` and its
869
+ *validate* parameter)"""
870
+ version: _Validator[version_module.Version] = _Validator()
871
+ """:external:ref:`core-metadata-version` (required)"""
872
+ dynamic: _Validator[list[str] | None] = _Validator(
873
+ added="2.2",
874
+ )
875
+ """:external:ref:`core-metadata-dynamic`
876
+ (validated against core metadata field names and lowercased)"""
877
+ platforms: _Validator[list[str] | None] = _Validator()
878
+ """:external:ref:`core-metadata-platform`"""
879
+ supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1")
880
+ """:external:ref:`core-metadata-supported-platform`"""
881
+ summary: _Validator[str | None] = _Validator()
882
+ """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
883
+ description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body
884
+ """:external:ref:`core-metadata-description`"""
885
+ description_content_type: _Validator[str | None] = _Validator(added="2.1")
886
+ """:external:ref:`core-metadata-description-content-type` (validated)"""
887
+ keywords: _Validator[list[str] | None] = _Validator()
888
+ """:external:ref:`core-metadata-keywords`"""
889
+ home_page: _Validator[str | None] = _Validator()
890
+ """:external:ref:`core-metadata-home-page`"""
891
+ download_url: _Validator[str | None] = _Validator(added="1.1")
892
+ """:external:ref:`core-metadata-download-url`"""
893
+ author: _Validator[str | None] = _Validator()
894
+ """:external:ref:`core-metadata-author`"""
895
+ author_email: _Validator[str | None] = _Validator()
896
+ """:external:ref:`core-metadata-author-email`"""
897
+ maintainer: _Validator[str | None] = _Validator(added="1.2")
898
+ """:external:ref:`core-metadata-maintainer`"""
899
+ maintainer_email: _Validator[str | None] = _Validator(added="1.2")
900
+ """:external:ref:`core-metadata-maintainer-email`"""
901
+ license: _Validator[str | None] = _Validator()
902
+ """:external:ref:`core-metadata-license`"""
903
+ license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(
904
+ added="2.4"
905
+ )
906
+ """:external:ref:`core-metadata-license-expression`"""
907
+ license_files: _Validator[list[str] | None] = _Validator(added="2.4")
908
+ """:external:ref:`core-metadata-license-file`"""
909
+ classifiers: _Validator[list[str] | None] = _Validator(added="1.1")
910
+ """:external:ref:`core-metadata-classifier`"""
911
+ requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(
912
+ added="1.2"
913
+ )
914
+ """:external:ref:`core-metadata-requires-dist`"""
915
+ requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(
916
+ added="1.2"
917
+ )
918
+ """:external:ref:`core-metadata-requires-python`"""
919
+ # Because `Requires-External` allows for non-PEP 440 version specifiers, we
920
+ # don't do any processing on the values.
921
+ requires_external: _Validator[list[str] | None] = _Validator(added="1.2")
922
+ """:external:ref:`core-metadata-requires-external`"""
923
+ project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2")
924
+ """:external:ref:`core-metadata-project-url`"""
925
+ # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
926
+ # regardless of metadata version.
927
+ provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(
928
+ added="2.1",
929
+ )
930
+ """:external:ref:`core-metadata-provides-extra`"""
931
+ provides_dist: _Validator[list[str] | None] = _Validator(added="1.2")
932
+ """:external:ref:`core-metadata-provides-dist`"""
933
+ obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2")
934
+ """:external:ref:`core-metadata-obsoletes-dist`"""
935
+ import_names: _Validator[list[str] | None] = _Validator(added="2.5")
936
+ """:external:ref:`core-metadata-import-name`"""
937
+ import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5")
938
+ """:external:ref:`core-metadata-import-namespace`"""
939
+ requires: _Validator[list[str] | None] = _Validator(added="1.1")
940
+ """``Requires`` (deprecated)"""
941
+ provides: _Validator[list[str] | None] = _Validator(added="1.1")
942
+ """``Provides`` (deprecated)"""
943
+ obsoletes: _Validator[list[str] | None] = _Validator(added="1.1")
944
+ """``Obsoletes`` (deprecated)"""
945
+
946
+ def as_rfc822(self) -> RFC822Message:
947
+ """
948
+ Return an RFC822 message with the metadata.
949
+ """
950
+ message = RFC822Message()
951
+ self._write_metadata(message)
952
+ return message
953
+
954
+ def _write_metadata(self, message: RFC822Message) -> None:
955
+ """
956
+ Return an RFC822 message with the metadata.
957
+ """
958
+ for name, validator in self.__class__.__dict__.items():
959
+ if isinstance(validator, _Validator) and name != "description":
960
+ value = getattr(self, name)
961
+ email_name = _RAW_TO_EMAIL_MAPPING[name]
962
+ if value is not None:
963
+ if email_name == "project-url":
964
+ for label, url in value.items():
965
+ message[email_name] = f"{label}, {url}"
966
+ elif email_name == "keywords":
967
+ message[email_name] = ",".join(value)
968
+ elif email_name == "import-name" and value == []:
969
+ message[email_name] = ""
970
+ elif isinstance(value, list):
971
+ for item in value:
972
+ message[email_name] = str(item)
973
+ else:
974
+ message[email_name] = str(value)
975
+
976
+ # The description is a special case because it is in the body of the message.
977
+ if self.description is not None:
978
+ message.set_payload(self.description)
python/Lib/site-packages/setuptools/_vendor/packaging/py.typed ADDED
File without changes
python/Lib/site-packages/setuptools/_vendor/packaging/pylock.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import logging
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Callable,
13
+ Protocol,
14
+ TypeVar,
15
+ )
16
+
17
+ from .markers import Marker
18
+ from .specifiers import SpecifierSet
19
+ from .utils import NormalizedName, is_normalized_name
20
+ from .version import Version
21
+
22
+ if TYPE_CHECKING: # pragma: no cover
23
+ from pathlib import Path
24
+
25
+ from typing_extensions import Self
26
+
27
+ _logger = logging.getLogger(__name__)
28
+
29
+ __all__ = [
30
+ "Package",
31
+ "PackageArchive",
32
+ "PackageDirectory",
33
+ "PackageSdist",
34
+ "PackageVcs",
35
+ "PackageWheel",
36
+ "Pylock",
37
+ "PylockUnsupportedVersionError",
38
+ "PylockValidationError",
39
+ "is_valid_pylock_path",
40
+ ]
41
+
42
+ _T = TypeVar("_T")
43
+ _T2 = TypeVar("_T2")
44
+
45
+
46
+ class _FromMappingProtocol(Protocol): # pragma: no cover
47
+ @classmethod
48
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
49
+
50
+
51
+ _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
52
+
53
+
54
+ _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
55
+
56
+
57
+ def is_valid_pylock_path(path: Path) -> bool:
58
+ """Check if the given path is a valid pylock file path."""
59
+ return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
60
+
61
+
62
+ def _toml_key(key: str) -> str:
63
+ return key.replace("_", "-")
64
+
65
+
66
+ def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401
67
+ if isinstance(value, (Version, Marker, SpecifierSet)):
68
+ return str(value)
69
+ if isinstance(value, Sequence) and key == "environments":
70
+ return [str(v) for v in value]
71
+ return value
72
+
73
+
74
+ def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
75
+ return {
76
+ _toml_key(key): _toml_value(key, value)
77
+ for key, value in data
78
+ if value is not None
79
+ }
80
+
81
+
82
+ def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
83
+ """Get a value from the dictionary and verify it's the expected type."""
84
+ if (value := d.get(key)) is None:
85
+ return None
86
+ if not isinstance(value, expected_type):
87
+ raise PylockValidationError(
88
+ f"Unexpected type {type(value).__name__} "
89
+ f"(expected {expected_type.__name__})",
90
+ context=key,
91
+ )
92
+ return value
93
+
94
+
95
+ def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
96
+ """Get a required value from the dictionary and verify it's the expected type."""
97
+ if (value := _get(d, expected_type, key)) is None:
98
+ raise _PylockRequiredKeyError(key)
99
+ return value
100
+
101
+
102
+ def _get_sequence(
103
+ d: Mapping[str, Any], expected_item_type: type[_T], key: str
104
+ ) -> Sequence[_T] | None:
105
+ """Get a list value from the dictionary and verify it's the expected items type."""
106
+ if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract]
107
+ return None
108
+ if isinstance(value, (str, bytes)):
109
+ # special case: str and bytes are Sequences, but we want to reject it
110
+ raise PylockValidationError(
111
+ f"Unexpected type {type(value).__name__} (expected Sequence)",
112
+ context=key,
113
+ )
114
+ for i, item in enumerate(value):
115
+ if not isinstance(item, expected_item_type):
116
+ raise PylockValidationError(
117
+ f"Unexpected type {type(item).__name__} "
118
+ f"(expected {expected_item_type.__name__})",
119
+ context=f"{key}[{i}]",
120
+ )
121
+ return value
122
+
123
+
124
+ def _get_as(
125
+ d: Mapping[str, Any],
126
+ expected_type: type[_T],
127
+ target_type: Callable[[_T], _T2],
128
+ key: str,
129
+ ) -> _T2 | None:
130
+ """Get a value from the dictionary, verify it's the expected type,
131
+ and convert to the target type.
132
+
133
+ This assumes the target_type constructor accepts the value.
134
+ """
135
+ if (value := _get(d, expected_type, key)) is None:
136
+ return None
137
+ try:
138
+ return target_type(value)
139
+ except Exception as e:
140
+ raise PylockValidationError(e, context=key) from e
141
+
142
+
143
+ def _get_required_as(
144
+ d: Mapping[str, Any],
145
+ expected_type: type[_T],
146
+ target_type: Callable[[_T], _T2],
147
+ key: str,
148
+ ) -> _T2:
149
+ """Get a required value from the dict, verify it's the expected type,
150
+ and convert to the target type."""
151
+ if (value := _get_as(d, expected_type, target_type, key)) is None:
152
+ raise _PylockRequiredKeyError(key)
153
+ return value
154
+
155
+
156
+ def _get_sequence_as(
157
+ d: Mapping[str, Any],
158
+ expected_item_type: type[_T],
159
+ target_item_type: Callable[[_T], _T2],
160
+ key: str,
161
+ ) -> list[_T2] | None:
162
+ """Get list value from dictionary and verify expected items type."""
163
+ if (value := _get_sequence(d, expected_item_type, key)) is None:
164
+ return None
165
+ result = []
166
+ try:
167
+ for item in value:
168
+ typed_item = target_item_type(item)
169
+ result.append(typed_item)
170
+ except Exception as e:
171
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
172
+ return result
173
+
174
+
175
+ def _get_object(
176
+ d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
177
+ ) -> _FromMappingProtocolT | None:
178
+ """Get a dictionary value from the dictionary and convert it to a dataclass."""
179
+ if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract]
180
+ return None
181
+ try:
182
+ return target_type._from_dict(value)
183
+ except Exception as e:
184
+ raise PylockValidationError(e, context=key) from e
185
+
186
+
187
+ def _get_sequence_of_objects(
188
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
189
+ ) -> list[_FromMappingProtocolT] | None:
190
+ """Get a list value from the dictionary and convert its items to a dataclass."""
191
+ if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract]
192
+ return None
193
+ result: list[_FromMappingProtocolT] = []
194
+ try:
195
+ for item in value:
196
+ typed_item = target_item_type._from_dict(item)
197
+ result.append(typed_item)
198
+ except Exception as e:
199
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
200
+ return result
201
+
202
+
203
+ def _get_required_sequence_of_objects(
204
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
205
+ ) -> Sequence[_FromMappingProtocolT]:
206
+ """Get a required list value from the dictionary and convert its items to a
207
+ dataclass."""
208
+ if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:
209
+ raise _PylockRequiredKeyError(key)
210
+ return result
211
+
212
+
213
+ def _validate_normalized_name(name: str) -> NormalizedName:
214
+ """Validate that a string is a NormalizedName."""
215
+ if not is_normalized_name(name):
216
+ raise PylockValidationError(f"Name {name!r} is not normalized")
217
+ return NormalizedName(name)
218
+
219
+
220
+ def _validate_path_url(path: str | None, url: str | None) -> None:
221
+ if not path and not url:
222
+ raise PylockValidationError("path or url must be provided")
223
+
224
+
225
+ def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
226
+ if not hashes:
227
+ raise PylockValidationError("At least one hash must be provided")
228
+ if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
229
+ raise PylockValidationError("Hash values must be strings")
230
+ return hashes
231
+
232
+
233
+ class PylockValidationError(Exception):
234
+ """Raised when when input data is not spec-compliant."""
235
+
236
+ context: str | None = None
237
+ message: str
238
+
239
+ def __init__(
240
+ self,
241
+ cause: str | Exception,
242
+ *,
243
+ context: str | None = None,
244
+ ) -> None:
245
+ if isinstance(cause, PylockValidationError):
246
+ if cause.context:
247
+ self.context = (
248
+ f"{context}.{cause.context}" if context else cause.context
249
+ )
250
+ else:
251
+ self.context = context
252
+ self.message = cause.message
253
+ else:
254
+ self.context = context
255
+ self.message = str(cause)
256
+
257
+ def __str__(self) -> str:
258
+ if self.context:
259
+ return f"{self.message} in {self.context!r}"
260
+ return self.message
261
+
262
+
263
+ class _PylockRequiredKeyError(PylockValidationError):
264
+ def __init__(self, key: str) -> None:
265
+ super().__init__("Missing required value", context=key)
266
+
267
+
268
+ class PylockUnsupportedVersionError(PylockValidationError):
269
+ """Raised when encountering an unsupported `lock_version`."""
270
+
271
+
272
+ @dataclass(frozen=True, init=False)
273
+ class PackageVcs:
274
+ type: str
275
+ url: str | None = None
276
+ path: str | None = None
277
+ requested_revision: str | None = None
278
+ commit_id: str # type: ignore[misc]
279
+ subdirectory: str | None = None
280
+
281
+ def __init__(
282
+ self,
283
+ *,
284
+ type: str,
285
+ url: str | None = None,
286
+ path: str | None = None,
287
+ requested_revision: str | None = None,
288
+ commit_id: str,
289
+ subdirectory: str | None = None,
290
+ ) -> None:
291
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
292
+ object.__setattr__(self, "type", type)
293
+ object.__setattr__(self, "url", url)
294
+ object.__setattr__(self, "path", path)
295
+ object.__setattr__(self, "requested_revision", requested_revision)
296
+ object.__setattr__(self, "commit_id", commit_id)
297
+ object.__setattr__(self, "subdirectory", subdirectory)
298
+
299
+ @classmethod
300
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
301
+ package_vcs = cls(
302
+ type=_get_required(d, str, "type"),
303
+ url=_get(d, str, "url"),
304
+ path=_get(d, str, "path"),
305
+ requested_revision=_get(d, str, "requested-revision"),
306
+ commit_id=_get_required(d, str, "commit-id"),
307
+ subdirectory=_get(d, str, "subdirectory"),
308
+ )
309
+ _validate_path_url(package_vcs.path, package_vcs.url)
310
+ return package_vcs
311
+
312
+
313
+ @dataclass(frozen=True, init=False)
314
+ class PackageDirectory:
315
+ path: str
316
+ editable: bool | None = None
317
+ subdirectory: str | None = None
318
+
319
+ def __init__(
320
+ self,
321
+ *,
322
+ path: str,
323
+ editable: bool | None = None,
324
+ subdirectory: str | None = None,
325
+ ) -> None:
326
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
327
+ object.__setattr__(self, "path", path)
328
+ object.__setattr__(self, "editable", editable)
329
+ object.__setattr__(self, "subdirectory", subdirectory)
330
+
331
+ @classmethod
332
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
333
+ return cls(
334
+ path=_get_required(d, str, "path"),
335
+ editable=_get(d, bool, "editable"),
336
+ subdirectory=_get(d, str, "subdirectory"),
337
+ )
338
+
339
+
340
+ @dataclass(frozen=True, init=False)
341
+ class PackageArchive:
342
+ url: str | None = None
343
+ path: str | None = None
344
+ size: int | None = None
345
+ upload_time: datetime | None = None
346
+ hashes: Mapping[str, str] # type: ignore[misc]
347
+ subdirectory: str | None = None
348
+
349
+ def __init__(
350
+ self,
351
+ *,
352
+ url: str | None = None,
353
+ path: str | None = None,
354
+ size: int | None = None,
355
+ upload_time: datetime | None = None,
356
+ hashes: Mapping[str, str],
357
+ subdirectory: str | None = None,
358
+ ) -> None:
359
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
360
+ object.__setattr__(self, "url", url)
361
+ object.__setattr__(self, "path", path)
362
+ object.__setattr__(self, "size", size)
363
+ object.__setattr__(self, "upload_time", upload_time)
364
+ object.__setattr__(self, "hashes", hashes)
365
+ object.__setattr__(self, "subdirectory", subdirectory)
366
+
367
+ @classmethod
368
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
369
+ package_archive = cls(
370
+ url=_get(d, str, "url"),
371
+ path=_get(d, str, "path"),
372
+ size=_get(d, int, "size"),
373
+ upload_time=_get(d, datetime, "upload-time"),
374
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
375
+ subdirectory=_get(d, str, "subdirectory"),
376
+ )
377
+ _validate_path_url(package_archive.path, package_archive.url)
378
+ return package_archive
379
+
380
+
381
+ @dataclass(frozen=True, init=False)
382
+ class PackageSdist:
383
+ name: str | None = None
384
+ upload_time: datetime | None = None
385
+ url: str | None = None
386
+ path: str | None = None
387
+ size: int | None = None
388
+ hashes: Mapping[str, str] # type: ignore[misc]
389
+
390
+ def __init__(
391
+ self,
392
+ *,
393
+ name: str | None = None,
394
+ upload_time: datetime | None = None,
395
+ url: str | None = None,
396
+ path: str | None = None,
397
+ size: int | None = None,
398
+ hashes: Mapping[str, str],
399
+ ) -> None:
400
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
401
+ object.__setattr__(self, "name", name)
402
+ object.__setattr__(self, "upload_time", upload_time)
403
+ object.__setattr__(self, "url", url)
404
+ object.__setattr__(self, "path", path)
405
+ object.__setattr__(self, "size", size)
406
+ object.__setattr__(self, "hashes", hashes)
407
+
408
+ @classmethod
409
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
410
+ package_sdist = cls(
411
+ name=_get(d, str, "name"),
412
+ upload_time=_get(d, datetime, "upload-time"),
413
+ url=_get(d, str, "url"),
414
+ path=_get(d, str, "path"),
415
+ size=_get(d, int, "size"),
416
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
417
+ )
418
+ _validate_path_url(package_sdist.path, package_sdist.url)
419
+ return package_sdist
420
+
421
+
422
+ @dataclass(frozen=True, init=False)
423
+ class PackageWheel:
424
+ name: str | None = None
425
+ upload_time: datetime | None = None
426
+ url: str | None = None
427
+ path: str | None = None
428
+ size: int | None = None
429
+ hashes: Mapping[str, str] # type: ignore[misc]
430
+
431
+ def __init__(
432
+ self,
433
+ *,
434
+ name: str | None = None,
435
+ upload_time: datetime | None = None,
436
+ url: str | None = None,
437
+ path: str | None = None,
438
+ size: int | None = None,
439
+ hashes: Mapping[str, str],
440
+ ) -> None:
441
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
442
+ object.__setattr__(self, "name", name)
443
+ object.__setattr__(self, "upload_time", upload_time)
444
+ object.__setattr__(self, "url", url)
445
+ object.__setattr__(self, "path", path)
446
+ object.__setattr__(self, "size", size)
447
+ object.__setattr__(self, "hashes", hashes)
448
+
449
+ @classmethod
450
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
451
+ package_wheel = cls(
452
+ name=_get(d, str, "name"),
453
+ upload_time=_get(d, datetime, "upload-time"),
454
+ url=_get(d, str, "url"),
455
+ path=_get(d, str, "path"),
456
+ size=_get(d, int, "size"),
457
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
458
+ )
459
+ _validate_path_url(package_wheel.path, package_wheel.url)
460
+ return package_wheel
461
+
462
+
463
+ @dataclass(frozen=True, init=False)
464
+ class Package:
465
+ name: NormalizedName
466
+ version: Version | None = None
467
+ marker: Marker | None = None
468
+ requires_python: SpecifierSet | None = None
469
+ dependencies: Sequence[Mapping[str, Any]] | None = None
470
+ vcs: PackageVcs | None = None
471
+ directory: PackageDirectory | None = None
472
+ archive: PackageArchive | None = None
473
+ index: str | None = None
474
+ sdist: PackageSdist | None = None
475
+ wheels: Sequence[PackageWheel] | None = None
476
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None
477
+ tool: Mapping[str, Any] | None = None
478
+
479
+ def __init__(
480
+ self,
481
+ *,
482
+ name: NormalizedName,
483
+ version: Version | None = None,
484
+ marker: Marker | None = None,
485
+ requires_python: SpecifierSet | None = None,
486
+ dependencies: Sequence[Mapping[str, Any]] | None = None,
487
+ vcs: PackageVcs | None = None,
488
+ directory: PackageDirectory | None = None,
489
+ archive: PackageArchive | None = None,
490
+ index: str | None = None,
491
+ sdist: PackageSdist | None = None,
492
+ wheels: Sequence[PackageWheel] | None = None,
493
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None,
494
+ tool: Mapping[str, Any] | None = None,
495
+ ) -> None:
496
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
497
+ object.__setattr__(self, "name", name)
498
+ object.__setattr__(self, "version", version)
499
+ object.__setattr__(self, "marker", marker)
500
+ object.__setattr__(self, "requires_python", requires_python)
501
+ object.__setattr__(self, "dependencies", dependencies)
502
+ object.__setattr__(self, "vcs", vcs)
503
+ object.__setattr__(self, "directory", directory)
504
+ object.__setattr__(self, "archive", archive)
505
+ object.__setattr__(self, "index", index)
506
+ object.__setattr__(self, "sdist", sdist)
507
+ object.__setattr__(self, "wheels", wheels)
508
+ object.__setattr__(self, "attestation_identities", attestation_identities)
509
+ object.__setattr__(self, "tool", tool)
510
+
511
+ @classmethod
512
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
513
+ package = cls(
514
+ name=_get_required_as(d, str, _validate_normalized_name, "name"),
515
+ version=_get_as(d, str, Version, "version"),
516
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
517
+ dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract]
518
+ marker=_get_as(d, str, Marker, "marker"),
519
+ vcs=_get_object(d, PackageVcs, "vcs"),
520
+ directory=_get_object(d, PackageDirectory, "directory"),
521
+ archive=_get_object(d, PackageArchive, "archive"),
522
+ index=_get(d, str, "index"),
523
+ sdist=_get_object(d, PackageSdist, "sdist"),
524
+ wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"),
525
+ attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract]
526
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
527
+ )
528
+ distributions = bool(package.sdist) + len(package.wheels or [])
529
+ direct_urls = (
530
+ bool(package.vcs) + bool(package.directory) + bool(package.archive)
531
+ )
532
+ if distributions > 0 and direct_urls > 0:
533
+ raise PylockValidationError(
534
+ "None of vcs, directory, archive must be set if sdist or wheels are set"
535
+ )
536
+ if distributions == 0 and direct_urls != 1:
537
+ raise PylockValidationError(
538
+ "Exactly one of vcs, directory, archive must be set "
539
+ "if sdist and wheels are not set"
540
+ )
541
+ try:
542
+ for i, attestation_identity in enumerate( # noqa: B007
543
+ package.attestation_identities or []
544
+ ):
545
+ _get_required(attestation_identity, str, "kind")
546
+ except Exception as e:
547
+ raise PylockValidationError(
548
+ e, context=f"attestation-identities[{i}]"
549
+ ) from e
550
+ return package
551
+
552
+ @property
553
+ def is_direct(self) -> bool:
554
+ return not (self.sdist or self.wheels)
555
+
556
+
557
+ @dataclass(frozen=True, init=False)
558
+ class Pylock:
559
+ """A class representing a pylock file."""
560
+
561
+ lock_version: Version
562
+ environments: Sequence[Marker] | None = None
563
+ requires_python: SpecifierSet | None = None
564
+ extras: Sequence[NormalizedName] | None = None
565
+ dependency_groups: Sequence[str] | None = None
566
+ default_groups: Sequence[str] | None = None
567
+ created_by: str # type: ignore[misc]
568
+ packages: Sequence[Package] # type: ignore[misc]
569
+ tool: Mapping[str, Any] | None = None
570
+
571
+ def __init__(
572
+ self,
573
+ *,
574
+ lock_version: Version,
575
+ environments: Sequence[Marker] | None = None,
576
+ requires_python: SpecifierSet | None = None,
577
+ extras: Sequence[NormalizedName] | None = None,
578
+ dependency_groups: Sequence[str] | None = None,
579
+ default_groups: Sequence[str] | None = None,
580
+ created_by: str,
581
+ packages: Sequence[Package],
582
+ tool: Mapping[str, Any] | None = None,
583
+ ) -> None:
584
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
585
+ object.__setattr__(self, "lock_version", lock_version)
586
+ object.__setattr__(self, "environments", environments)
587
+ object.__setattr__(self, "requires_python", requires_python)
588
+ object.__setattr__(self, "extras", extras)
589
+ object.__setattr__(self, "dependency_groups", dependency_groups)
590
+ object.__setattr__(self, "default_groups", default_groups)
591
+ object.__setattr__(self, "created_by", created_by)
592
+ object.__setattr__(self, "packages", packages)
593
+ object.__setattr__(self, "tool", tool)
594
+
595
+ @classmethod
596
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
597
+ pylock = cls(
598
+ lock_version=_get_required_as(d, str, Version, "lock-version"),
599
+ environments=_get_sequence_as(d, str, Marker, "environments"),
600
+ extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"),
601
+ dependency_groups=_get_sequence(d, str, "dependency-groups"),
602
+ default_groups=_get_sequence(d, str, "default-groups"),
603
+ created_by=_get_required(d, str, "created-by"),
604
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
605
+ packages=_get_required_sequence_of_objects(d, Package, "packages"),
606
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
607
+ )
608
+ if not Version("1") <= pylock.lock_version < Version("2"):
609
+ raise PylockUnsupportedVersionError(
610
+ f"pylock version {pylock.lock_version} is not supported"
611
+ )
612
+ if pylock.lock_version > Version("1.0"):
613
+ _logger.warning(
614
+ "pylock minor version %s is not supported", pylock.lock_version
615
+ )
616
+ return pylock
617
+
618
+ @classmethod
619
+ def from_dict(cls, d: Mapping[str, Any], /) -> Self:
620
+ """Create and validate a Pylock instance from a TOML dictionary.
621
+
622
+ Raises :class:`PylockValidationError` if the input data is not
623
+ spec-compliant.
624
+ """
625
+ return cls._from_dict(d)
626
+
627
+ def to_dict(self) -> Mapping[str, Any]:
628
+ """Convert the Pylock instance to a TOML dictionary."""
629
+ return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
630
+
631
+ def validate(self) -> None:
632
+ """Validate the Pylock instance against the specification.
633
+
634
+ Raises :class:`PylockValidationError` otherwise."""
635
+ self.from_dict(self.to_dict())
python/Lib/site-packages/setuptools/_vendor/packaging/requirements.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ from __future__ import annotations
5
+
6
+ from typing import Iterator
7
+
8
+ from ._parser import parse_requirement as _parse_requirement
9
+ from ._tokenizer import ParserSyntaxError
10
+ from .markers import Marker, _normalize_extra_values
11
+ from .specifiers import SpecifierSet
12
+ from .utils import canonicalize_name
13
+
14
+
15
+ class InvalidRequirement(ValueError):
16
+ """
17
+ An invalid requirement was found, users should refer to PEP 508.
18
+ """
19
+
20
+
21
+ class Requirement:
22
+ """Parse a requirement.
23
+
24
+ Parse a given requirement string into its parts, such as name, specifier,
25
+ URL, and extras. Raises InvalidRequirement on a badly-formed requirement
26
+ string.
27
+ """
28
+
29
+ # TODO: Can we test whether something is contained within a requirement?
30
+ # If so how do we do that? Do we need to test against the _name_ of
31
+ # the thing as well as the version? What about the markers?
32
+ # TODO: Can we normalize the name and extra name?
33
+
34
+ def __init__(self, requirement_string: str) -> None:
35
+ try:
36
+ parsed = _parse_requirement(requirement_string)
37
+ except ParserSyntaxError as e:
38
+ raise InvalidRequirement(str(e)) from e
39
+
40
+ self.name: str = parsed.name
41
+ self.url: str | None = parsed.url or None
42
+ self.extras: set[str] = set(parsed.extras or [])
43
+ self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
44
+ self.marker: Marker | None = None
45
+ if parsed.marker is not None:
46
+ self.marker = Marker.__new__(Marker)
47
+ self.marker._markers = _normalize_extra_values(parsed.marker)
48
+
49
+ def _iter_parts(self, name: str) -> Iterator[str]:
50
+ yield name
51
+
52
+ if self.extras:
53
+ formatted_extras = ",".join(sorted(self.extras))
54
+ yield f"[{formatted_extras}]"
55
+
56
+ if self.specifier:
57
+ yield str(self.specifier)
58
+
59
+ if self.url:
60
+ yield f" @ {self.url}"
61
+ if self.marker:
62
+ yield " "
63
+
64
+ if self.marker:
65
+ yield f"; {self.marker}"
66
+
67
+ def __str__(self) -> str:
68
+ return "".join(self._iter_parts(self.name))
69
+
70
+ def __repr__(self) -> str:
71
+ return f"<{self.__class__.__name__}('{self}')>"
72
+
73
+ def __hash__(self) -> int:
74
+ return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
75
+
76
+ def __eq__(self, other: object) -> bool:
77
+ if not isinstance(other, Requirement):
78
+ return NotImplemented
79
+
80
+ return (
81
+ canonicalize_name(self.name) == canonicalize_name(other.name)
82
+ and self.extras == other.extras
83
+ and self.specifier == other.specifier
84
+ and self.url == other.url
85
+ and self.marker == other.marker
86
+ )
python/Lib/site-packages/setuptools/_vendor/packaging/specifiers.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ """
5
+ .. testsetup::
6
+
7
+ from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
8
+ from packaging.version import Version
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import abc
14
+ import itertools
15
+ import re
16
+ from typing import Callable, Final, Iterable, Iterator, TypeVar, Union
17
+
18
+ from .utils import canonicalize_version
19
+ from .version import InvalidVersion, Version
20
+
21
+ UnparsedVersion = Union[Version, str]
22
+ UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
23
+ CallableOperator = Callable[[Version, str], bool]
24
+
25
+
26
+ def _coerce_version(version: UnparsedVersion) -> Version | None:
27
+ if not isinstance(version, Version):
28
+ try:
29
+ version = Version(version)
30
+ except InvalidVersion:
31
+ return None
32
+ return version
33
+
34
+
35
+ def _public_version(version: Version) -> Version:
36
+ return version.__replace__(local=None)
37
+
38
+
39
+ def _base_version(version: Version) -> Version:
40
+ return version.__replace__(pre=None, post=None, dev=None, local=None)
41
+
42
+
43
+ class InvalidSpecifier(ValueError):
44
+ """
45
+ Raised when attempting to create a :class:`Specifier` with a specifier
46
+ string that is invalid.
47
+
48
+ >>> Specifier("lolwat")
49
+ Traceback (most recent call last):
50
+ ...
51
+ packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
52
+ """
53
+
54
+
55
+ class BaseSpecifier(metaclass=abc.ABCMeta):
56
+ __slots__ = ()
57
+ __match_args__ = ("_str",)
58
+
59
+ @property
60
+ def _str(self) -> str:
61
+ """Internal property for match_args"""
62
+ return str(self)
63
+
64
+ @abc.abstractmethod
65
+ def __str__(self) -> str:
66
+ """
67
+ Returns the str representation of this Specifier-like object. This
68
+ should be representative of the Specifier itself.
69
+ """
70
+
71
+ @abc.abstractmethod
72
+ def __hash__(self) -> int:
73
+ """
74
+ Returns a hash value for this Specifier-like object.
75
+ """
76
+
77
+ @abc.abstractmethod
78
+ def __eq__(self, other: object) -> bool:
79
+ """
80
+ Returns a boolean representing whether or not the two Specifier-like
81
+ objects are equal.
82
+
83
+ :param other: The other object to check against.
84
+ """
85
+
86
+ @property
87
+ @abc.abstractmethod
88
+ def prereleases(self) -> bool | None:
89
+ """Whether or not pre-releases as a whole are allowed.
90
+
91
+ This can be set to either ``True`` or ``False`` to explicitly enable or disable
92
+ prereleases or it can be set to ``None`` (the default) to use default semantics.
93
+ """
94
+
95
+ @prereleases.setter # noqa: B027
96
+ def prereleases(self, value: bool) -> None:
97
+ """Setter for :attr:`prereleases`.
98
+
99
+ :param value: The value to set.
100
+ """
101
+
102
+ @abc.abstractmethod
103
+ def contains(self, item: str, prereleases: bool | None = None) -> bool:
104
+ """
105
+ Determines if the given item is contained within this specifier.
106
+ """
107
+
108
+ @abc.abstractmethod
109
+ def filter(
110
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
111
+ ) -> Iterator[UnparsedVersionVar]:
112
+ """
113
+ Takes an iterable of items and filters them so that only items which
114
+ are contained within this specifier are allowed in it.
115
+ """
116
+
117
+
118
+ class Specifier(BaseSpecifier):
119
+ """This class abstracts handling of version specifiers.
120
+
121
+ .. tip::
122
+
123
+ It is generally not required to instantiate this manually. You should instead
124
+ prefer to work with :class:`SpecifierSet` instead, which can parse
125
+ comma-separated version specifiers (which is what package metadata contains).
126
+ """
127
+
128
+ __slots__ = ("_prereleases", "_spec", "_spec_version")
129
+
130
+ _operator_regex_str = r"""
131
+ (?P<operator>(~=|==|!=|<=|>=|<|>|===))
132
+ """
133
+ _version_regex_str = r"""
134
+ (?P<version>
135
+ (?:
136
+ # The identity operators allow for an escape hatch that will
137
+ # do an exact string match of the version you wish to install.
138
+ # This will not be parsed by PEP 440 and we cannot determine
139
+ # any semantic meaning from it. This operator is discouraged
140
+ # but included entirely as an escape hatch.
141
+ (?<====) # Only match for the identity operator
142
+ \s*
143
+ [^\s;)]* # The arbitrary version can be just about anything,
144
+ # we match everything except for whitespace, a
145
+ # semi-colon for marker support, and a closing paren
146
+ # since versions can be enclosed in them.
147
+ )
148
+ |
149
+ (?:
150
+ # The (non)equality operators allow for wild card and local
151
+ # versions to be specified so we have to define these two
152
+ # operators separately to enable that.
153
+ (?<===|!=) # Only match for equals and not equals
154
+
155
+ \s*
156
+ v?
157
+ (?:[0-9]+!)? # epoch
158
+ [0-9]+(?:\.[0-9]+)* # release
159
+
160
+ # You cannot use a wild card and a pre-release, post-release, a dev or
161
+ # local version together so group them with a | and make them optional.
162
+ (?:
163
+ \.\* # Wild card syntax of .*
164
+ |
165
+ (?: # pre release
166
+ [-_\.]?
167
+ (alpha|beta|preview|pre|a|b|c|rc)
168
+ [-_\.]?
169
+ [0-9]*
170
+ )?
171
+ (?: # post release
172
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
173
+ )?
174
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
175
+ (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
176
+ )?
177
+ )
178
+ |
179
+ (?:
180
+ # The compatible operator requires at least two digits in the
181
+ # release segment.
182
+ (?<=~=) # Only match for the compatible operator
183
+
184
+ \s*
185
+ v?
186
+ (?:[0-9]+!)? # epoch
187
+ [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *)
188
+ (?: # pre release
189
+ [-_\.]?
190
+ (alpha|beta|preview|pre|a|b|c|rc)
191
+ [-_\.]?
192
+ [0-9]*
193
+ )?
194
+ (?: # post release
195
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
196
+ )?
197
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
198
+ )
199
+ |
200
+ (?:
201
+ # All other operators only allow a sub set of what the
202
+ # (non)equality operators do. Specifically they do not allow
203
+ # local versions to be specified nor do they allow the prefix
204
+ # matching wild cards.
205
+ (?<!==|!=|~=) # We have special cases for these
206
+ # operators so we want to make sure they
207
+ # don't match here.
208
+
209
+ \s*
210
+ v?
211
+ (?:[0-9]+!)? # epoch
212
+ [0-9]+(?:\.[0-9]+)* # release
213
+ (?: # pre release
214
+ [-_\.]?
215
+ (alpha|beta|preview|pre|a|b|c|rc)
216
+ [-_\.]?
217
+ [0-9]*
218
+ )?
219
+ (?: # post release
220
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
221
+ )?
222
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
223
+ )
224
+ )
225
+ """
226
+
227
+ _regex = re.compile(
228
+ r"\s*" + _operator_regex_str + _version_regex_str + r"\s*",
229
+ re.VERBOSE | re.IGNORECASE,
230
+ )
231
+
232
+ _operators: Final = {
233
+ "~=": "compatible",
234
+ "==": "equal",
235
+ "!=": "not_equal",
236
+ "<=": "less_than_equal",
237
+ ">=": "greater_than_equal",
238
+ "<": "less_than",
239
+ ">": "greater_than",
240
+ "===": "arbitrary",
241
+ }
242
+
243
+ def __init__(self, spec: str = "", prereleases: bool | None = None) -> None:
244
+ """Initialize a Specifier instance.
245
+
246
+ :param spec:
247
+ The string representation of a specifier which will be parsed and
248
+ normalized before use.
249
+ :param prereleases:
250
+ This tells the specifier if it should accept prerelease versions if
251
+ applicable or not. The default of ``None`` will autodetect it from the
252
+ given specifiers.
253
+ :raises InvalidSpecifier:
254
+ If the given specifier is invalid (i.e. bad syntax).
255
+ """
256
+ match = self._regex.fullmatch(spec)
257
+ if not match:
258
+ raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
259
+
260
+ self._spec: tuple[str, str] = (
261
+ match.group("operator").strip(),
262
+ match.group("version").strip(),
263
+ )
264
+
265
+ # Store whether or not this Specifier should accept prereleases
266
+ self._prereleases = prereleases
267
+
268
+ # Specifier version cache
269
+ self._spec_version: tuple[str, Version] | None = None
270
+
271
+ def _get_spec_version(self, version: str) -> Version | None:
272
+ """One element cache, as only one spec Version is needed per Specifier."""
273
+ if self._spec_version is not None and self._spec_version[0] == version:
274
+ return self._spec_version[1]
275
+
276
+ version_specifier = _coerce_version(version)
277
+ if version_specifier is None:
278
+ return None
279
+
280
+ self._spec_version = (version, version_specifier)
281
+ return version_specifier
282
+
283
+ def _require_spec_version(self, version: str) -> Version:
284
+ """Get spec version, asserting it's valid (not for === operator).
285
+
286
+ This method should only be called for operators where version
287
+ strings are guaranteed to be valid PEP 440 versions (not ===).
288
+ """
289
+ spec_version = self._get_spec_version(version)
290
+ assert spec_version is not None
291
+ return spec_version
292
+
293
+ @property
294
+ def prereleases(self) -> bool | None:
295
+ # If there is an explicit prereleases set for this, then we'll just
296
+ # blindly use that.
297
+ if self._prereleases is not None:
298
+ return self._prereleases
299
+
300
+ # Only the "!=" operator does not imply prereleases when
301
+ # the version in the specifier is a prerelease.
302
+ operator, version_str = self._spec
303
+ if operator != "!=":
304
+ # The == specifier with trailing .* cannot include prereleases
305
+ # e.g. "==1.0a1.*" is not valid.
306
+ if operator == "==" and version_str.endswith(".*"):
307
+ return False
308
+
309
+ # "===" can have arbitrary string versions, so we cannot parse
310
+ # those, we take prereleases as unknown (None) for those.
311
+ version = self._get_spec_version(version_str)
312
+ if version is None:
313
+ return None
314
+
315
+ # For all other operators, use the check if spec Version
316
+ # object implies pre-releases.
317
+ if version.is_prerelease:
318
+ return True
319
+
320
+ return False
321
+
322
+ @prereleases.setter
323
+ def prereleases(self, value: bool | None) -> None:
324
+ self._prereleases = value
325
+
326
+ @property
327
+ def operator(self) -> str:
328
+ """The operator of this specifier.
329
+
330
+ >>> Specifier("==1.2.3").operator
331
+ '=='
332
+ """
333
+ return self._spec[0]
334
+
335
+ @property
336
+ def version(self) -> str:
337
+ """The version of this specifier.
338
+
339
+ >>> Specifier("==1.2.3").version
340
+ '1.2.3'
341
+ """
342
+ return self._spec[1]
343
+
344
+ def __repr__(self) -> str:
345
+ """A representation of the Specifier that shows all internal state.
346
+
347
+ >>> Specifier('>=1.0.0')
348
+ <Specifier('>=1.0.0')>
349
+ >>> Specifier('>=1.0.0', prereleases=False)
350
+ <Specifier('>=1.0.0', prereleases=False)>
351
+ >>> Specifier('>=1.0.0', prereleases=True)
352
+ <Specifier('>=1.0.0', prereleases=True)>
353
+ """
354
+ pre = (
355
+ f", prereleases={self.prereleases!r}"
356
+ if self._prereleases is not None
357
+ else ""
358
+ )
359
+
360
+ return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
361
+
362
+ def __str__(self) -> str:
363
+ """A string representation of the Specifier that can be round-tripped.
364
+
365
+ >>> str(Specifier('>=1.0.0'))
366
+ '>=1.0.0'
367
+ >>> str(Specifier('>=1.0.0', prereleases=False))
368
+ '>=1.0.0'
369
+ """
370
+ return "{}{}".format(*self._spec)
371
+
372
+ @property
373
+ def _canonical_spec(self) -> tuple[str, str]:
374
+ operator, version = self._spec
375
+ if operator == "===" or version.endswith(".*"):
376
+ return operator, version
377
+
378
+ spec_version = self._require_spec_version(version)
379
+
380
+ canonical_version = canonicalize_version(
381
+ spec_version, strip_trailing_zero=(operator != "~=")
382
+ )
383
+
384
+ return operator, canonical_version
385
+
386
+ def __hash__(self) -> int:
387
+ return hash(self._canonical_spec)
388
+
389
+ def __eq__(self, other: object) -> bool:
390
+ """Whether or not the two Specifier-like objects are equal.
391
+
392
+ :param other: The other object to check against.
393
+
394
+ The value of :attr:`prereleases` is ignored.
395
+
396
+ >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
397
+ True
398
+ >>> (Specifier("==1.2.3", prereleases=False) ==
399
+ ... Specifier("==1.2.3", prereleases=True))
400
+ True
401
+ >>> Specifier("==1.2.3") == "==1.2.3"
402
+ True
403
+ >>> Specifier("==1.2.3") == Specifier("==1.2.4")
404
+ False
405
+ >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
406
+ False
407
+ """
408
+ if isinstance(other, str):
409
+ try:
410
+ other = self.__class__(str(other))
411
+ except InvalidSpecifier:
412
+ return NotImplemented
413
+ elif not isinstance(other, self.__class__):
414
+ return NotImplemented
415
+
416
+ return self._canonical_spec == other._canonical_spec
417
+
418
+ def _get_operator(self, op: str) -> CallableOperator:
419
+ operator_callable: CallableOperator = getattr(
420
+ self, f"_compare_{self._operators[op]}"
421
+ )
422
+ return operator_callable
423
+
424
+ def _compare_compatible(self, prospective: Version, spec: str) -> bool:
425
+ # Compatible releases have an equivalent combination of >= and ==. That
426
+ # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
427
+ # implement this in terms of the other specifiers instead of
428
+ # implementing it ourselves. The only thing we need to do is construct
429
+ # the other specifiers.
430
+
431
+ # We want everything but the last item in the version, but we want to
432
+ # ignore suffix segments.
433
+ prefix = _version_join(
434
+ list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
435
+ )
436
+
437
+ # Add the prefix notation to the end of our string
438
+ prefix += ".*"
439
+
440
+ return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
441
+ prospective, prefix
442
+ )
443
+
444
+ def _compare_equal(self, prospective: Version, spec: str) -> bool:
445
+ # We need special logic to handle prefix matching
446
+ if spec.endswith(".*"):
447
+ # In the case of prefix matching we want to ignore local segment.
448
+ normalized_prospective = canonicalize_version(
449
+ _public_version(prospective), strip_trailing_zero=False
450
+ )
451
+ # Get the normalized version string ignoring the trailing .*
452
+ normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
453
+ # Split the spec out by bangs and dots, and pretend that there is
454
+ # an implicit dot in between a release segment and a pre-release segment.
455
+ split_spec = _version_split(normalized_spec)
456
+
457
+ # Split the prospective version out by bangs and dots, and pretend
458
+ # that there is an implicit dot in between a release segment and
459
+ # a pre-release segment.
460
+ split_prospective = _version_split(normalized_prospective)
461
+
462
+ # 0-pad the prospective version before shortening it to get the correct
463
+ # shortened version.
464
+ padded_prospective, _ = _pad_version(split_prospective, split_spec)
465
+
466
+ # Shorten the prospective version to be the same length as the spec
467
+ # so that we can determine if the specifier is a prefix of the
468
+ # prospective version or not.
469
+ shortened_prospective = padded_prospective[: len(split_spec)]
470
+
471
+ return shortened_prospective == split_spec
472
+ else:
473
+ # Convert our spec string into a Version
474
+ spec_version = self._require_spec_version(spec)
475
+
476
+ # If the specifier does not have a local segment, then we want to
477
+ # act as if the prospective version also does not have a local
478
+ # segment.
479
+ if not spec_version.local:
480
+ prospective = _public_version(prospective)
481
+
482
+ return prospective == spec_version
483
+
484
+ def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
485
+ return not self._compare_equal(prospective, spec)
486
+
487
+ def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
488
+ # NB: Local version identifiers are NOT permitted in the version
489
+ # specifier, so local version labels can be universally removed from
490
+ # the prospective version.
491
+ return _public_version(prospective) <= self._require_spec_version(spec)
492
+
493
+ def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
494
+ # NB: Local version identifiers are NOT permitted in the version
495
+ # specifier, so local version labels can be universally removed from
496
+ # the prospective version.
497
+ return _public_version(prospective) >= self._require_spec_version(spec)
498
+
499
+ def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
500
+ # Convert our spec to a Version instance, since we'll want to work with
501
+ # it as a version.
502
+ spec = self._require_spec_version(spec_str)
503
+
504
+ # Check to see if the prospective version is less than the spec
505
+ # version. If it's not we can short circuit and just return False now
506
+ # instead of doing extra unneeded work.
507
+ if not prospective < spec:
508
+ return False
509
+
510
+ # This special case is here so that, unless the specifier itself
511
+ # includes is a pre-release version, that we do not accept pre-release
512
+ # versions for the version mentioned in the specifier (e.g. <3.1 should
513
+ # not match 3.1.dev0, but should match 3.0.dev0).
514
+ if (
515
+ not spec.is_prerelease
516
+ and prospective.is_prerelease
517
+ and _base_version(prospective) == _base_version(spec)
518
+ ):
519
+ return False
520
+
521
+ # If we've gotten to here, it means that prospective version is both
522
+ # less than the spec version *and* it's not a pre-release of the same
523
+ # version in the spec.
524
+ return True
525
+
526
+ def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
527
+ # Convert our spec to a Version instance, since we'll want to work with
528
+ # it as a version.
529
+ spec = self._require_spec_version(spec_str)
530
+
531
+ # Check to see if the prospective version is greater than the spec
532
+ # version. If it's not we can short circuit and just return False now
533
+ # instead of doing extra unneeded work.
534
+ if not prospective > spec:
535
+ return False
536
+
537
+ # This special case is here so that, unless the specifier itself
538
+ # includes is a post-release version, that we do not accept
539
+ # post-release versions for the version mentioned in the specifier
540
+ # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
541
+ if (
542
+ not spec.is_postrelease
543
+ and prospective.is_postrelease
544
+ and _base_version(prospective) == _base_version(spec)
545
+ ):
546
+ return False
547
+
548
+ # Ensure that we do not allow a local version of the version mentioned
549
+ # in the specifier, which is technically greater than, to match.
550
+ if prospective.local is not None and _base_version(
551
+ prospective
552
+ ) == _base_version(spec):
553
+ return False
554
+
555
+ # If we've gotten to here, it means that prospective version is both
556
+ # greater than the spec version *and* it's not a pre-release of the
557
+ # same version in the spec.
558
+ return True
559
+
560
+ def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool:
561
+ return str(prospective).lower() == str(spec).lower()
562
+
563
+ def __contains__(self, item: str | Version) -> bool:
564
+ """Return whether or not the item is contained in this specifier.
565
+
566
+ :param item: The item to check for.
567
+
568
+ This is used for the ``in`` operator and behaves the same as
569
+ :meth:`contains` with no ``prereleases`` argument passed.
570
+
571
+ >>> "1.2.3" in Specifier(">=1.2.3")
572
+ True
573
+ >>> Version("1.2.3") in Specifier(">=1.2.3")
574
+ True
575
+ >>> "1.0.0" in Specifier(">=1.2.3")
576
+ False
577
+ >>> "1.3.0a1" in Specifier(">=1.2.3")
578
+ True
579
+ >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
580
+ True
581
+ """
582
+ return self.contains(item)
583
+
584
+ def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:
585
+ """Return whether or not the item is contained in this specifier.
586
+
587
+ :param item:
588
+ The item to check for, which can be a version string or a
589
+ :class:`Version` instance.
590
+ :param prereleases:
591
+ Whether or not to match prereleases with this Specifier. If set to
592
+ ``None`` (the default), it will follow the recommendation from
593
+ :pep:`440` and match prereleases, as there are no other versions.
594
+
595
+ >>> Specifier(">=1.2.3").contains("1.2.3")
596
+ True
597
+ >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
598
+ True
599
+ >>> Specifier(">=1.2.3").contains("1.0.0")
600
+ False
601
+ >>> Specifier(">=1.2.3").contains("1.3.0a1")
602
+ True
603
+ >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1")
604
+ False
605
+ >>> Specifier(">=1.2.3").contains("1.3.0a1")
606
+ True
607
+ """
608
+
609
+ return bool(list(self.filter([item], prereleases=prereleases)))
610
+
611
+ def filter(
612
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
613
+ ) -> Iterator[UnparsedVersionVar]:
614
+ """Filter items in the given iterable, that match the specifier.
615
+
616
+ :param iterable:
617
+ An iterable that can contain version strings and :class:`Version` instances.
618
+ The items in the iterable will be filtered according to the specifier.
619
+ :param prereleases:
620
+ Whether or not to allow prereleases in the returned iterator. If set to
621
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
622
+ and match prereleases if there are no other versions.
623
+
624
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
625
+ ['1.3']
626
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
627
+ ['1.2.3', '1.3', <Version('1.4')>]
628
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
629
+ ['1.5a1']
630
+ >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
631
+ ['1.3', '1.5a1']
632
+ >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
633
+ ['1.3', '1.5a1']
634
+ """
635
+ prereleases_versions = []
636
+ found_non_prereleases = False
637
+
638
+ # Determine if to include prereleases by default
639
+ include_prereleases = (
640
+ prereleases if prereleases is not None else self.prereleases
641
+ )
642
+
643
+ # Get the matching operator
644
+ operator_callable = self._get_operator(self.operator)
645
+
646
+ # Filter versions
647
+ for version in iterable:
648
+ parsed_version = _coerce_version(version)
649
+ if parsed_version is None:
650
+ # === operator can match arbitrary (non-version) strings
651
+ if self.operator == "===" and self._compare_arbitrary(
652
+ version, self.version
653
+ ):
654
+ yield version
655
+ elif operator_callable(parsed_version, self.version):
656
+ # If it's not a prerelease or prereleases are allowed, yield it directly
657
+ if not parsed_version.is_prerelease or include_prereleases:
658
+ found_non_prereleases = True
659
+ yield version
660
+ # Otherwise collect prereleases for potential later use
661
+ elif prereleases is None and self._prereleases is not False:
662
+ prereleases_versions.append(version)
663
+
664
+ # If no non-prereleases were found and prereleases weren't
665
+ # explicitly forbidden, yield the collected prereleases
666
+ if (
667
+ not found_non_prereleases
668
+ and prereleases is None
669
+ and self._prereleases is not False
670
+ ):
671
+ yield from prereleases_versions
672
+
673
+
674
+ _prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)")
675
+
676
+
677
+ def _version_split(version: str) -> list[str]:
678
+ """Split version into components.
679
+
680
+ The split components are intended for version comparison. The logic does
681
+ not attempt to retain the original version string, so joining the
682
+ components back with :func:`_version_join` may not produce the original
683
+ version string.
684
+ """
685
+ result: list[str] = []
686
+
687
+ epoch, _, rest = version.rpartition("!")
688
+ result.append(epoch or "0")
689
+
690
+ for item in rest.split("."):
691
+ match = _prefix_regex.fullmatch(item)
692
+ if match:
693
+ result.extend(match.groups())
694
+ else:
695
+ result.append(item)
696
+ return result
697
+
698
+
699
+ def _version_join(components: list[str]) -> str:
700
+ """Join split version components into a version string.
701
+
702
+ This function assumes the input came from :func:`_version_split`, where the
703
+ first component must be the epoch (either empty or numeric), and all other
704
+ components numeric.
705
+ """
706
+ epoch, *rest = components
707
+ return f"{epoch}!{'.'.join(rest)}"
708
+
709
+
710
+ def _is_not_suffix(segment: str) -> bool:
711
+ return not any(
712
+ segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
713
+ )
714
+
715
+
716
+ def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]:
717
+ left_split, right_split = [], []
718
+
719
+ # Get the release segment of our versions
720
+ left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
721
+ right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
722
+
723
+ # Get the rest of our versions
724
+ left_split.append(left[len(left_split[0]) :])
725
+ right_split.append(right[len(right_split[0]) :])
726
+
727
+ # Insert our padding
728
+ left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
729
+ right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
730
+
731
+ return (
732
+ list(itertools.chain.from_iterable(left_split)),
733
+ list(itertools.chain.from_iterable(right_split)),
734
+ )
735
+
736
+
737
+ class SpecifierSet(BaseSpecifier):
738
+ """This class abstracts handling of a set of version specifiers.
739
+
740
+ It can be passed a single specifier (``>=3.0``), a comma-separated list of
741
+ specifiers (``>=3.0,!=3.1``), or no specifier at all.
742
+ """
743
+
744
+ __slots__ = ("_prereleases", "_specs")
745
+
746
+ def __init__(
747
+ self,
748
+ specifiers: str | Iterable[Specifier] = "",
749
+ prereleases: bool | None = None,
750
+ ) -> None:
751
+ """Initialize a SpecifierSet instance.
752
+
753
+ :param specifiers:
754
+ The string representation of a specifier or a comma-separated list of
755
+ specifiers which will be parsed and normalized before use.
756
+ May also be an iterable of ``Specifier`` instances, which will be used
757
+ as is.
758
+ :param prereleases:
759
+ This tells the SpecifierSet if it should accept prerelease versions if
760
+ applicable or not. The default of ``None`` will autodetect it from the
761
+ given specifiers.
762
+
763
+ :raises InvalidSpecifier:
764
+ If the given ``specifiers`` are not parseable than this exception will be
765
+ raised.
766
+ """
767
+
768
+ if isinstance(specifiers, str):
769
+ # Split on `,` to break each individual specifier into its own item, and
770
+ # strip each item to remove leading/trailing whitespace.
771
+ split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
772
+
773
+ # Make each individual specifier a Specifier and save in a frozen set
774
+ # for later.
775
+ self._specs = frozenset(map(Specifier, split_specifiers))
776
+ else:
777
+ # Save the supplied specifiers in a frozen set.
778
+ self._specs = frozenset(specifiers)
779
+
780
+ # Store our prereleases value so we can use it later to determine if
781
+ # we accept prereleases or not.
782
+ self._prereleases = prereleases
783
+
784
+ @property
785
+ def prereleases(self) -> bool | None:
786
+ # If we have been given an explicit prerelease modifier, then we'll
787
+ # pass that through here.
788
+ if self._prereleases is not None:
789
+ return self._prereleases
790
+
791
+ # If we don't have any specifiers, and we don't have a forced value,
792
+ # then we'll just return None since we don't know if this should have
793
+ # pre-releases or not.
794
+ if not self._specs:
795
+ return None
796
+
797
+ # Otherwise we'll see if any of the given specifiers accept
798
+ # prereleases, if any of them do we'll return True, otherwise False.
799
+ if any(s.prereleases for s in self._specs):
800
+ return True
801
+
802
+ return None
803
+
804
+ @prereleases.setter
805
+ def prereleases(self, value: bool | None) -> None:
806
+ self._prereleases = value
807
+
808
+ def __repr__(self) -> str:
809
+ """A representation of the specifier set that shows all internal state.
810
+
811
+ Note that the ordering of the individual specifiers within the set may not
812
+ match the input string.
813
+
814
+ >>> SpecifierSet('>=1.0.0,!=2.0.0')
815
+ <SpecifierSet('!=2.0.0,>=1.0.0')>
816
+ >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
817
+ <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)>
818
+ >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
819
+ <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)>
820
+ """
821
+ pre = (
822
+ f", prereleases={self.prereleases!r}"
823
+ if self._prereleases is not None
824
+ else ""
825
+ )
826
+
827
+ return f"<SpecifierSet({str(self)!r}{pre})>"
828
+
829
+ def __str__(self) -> str:
830
+ """A string representation of the specifier set that can be round-tripped.
831
+
832
+ Note that the ordering of the individual specifiers within the set may not
833
+ match the input string.
834
+
835
+ >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
836
+ '!=1.0.1,>=1.0.0'
837
+ >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
838
+ '!=1.0.1,>=1.0.0'
839
+ """
840
+ return ",".join(sorted(str(s) for s in self._specs))
841
+
842
+ def __hash__(self) -> int:
843
+ return hash(self._specs)
844
+
845
+ def __and__(self, other: SpecifierSet | str) -> SpecifierSet:
846
+ """Return a SpecifierSet which is a combination of the two sets.
847
+
848
+ :param other: The other object to combine with.
849
+
850
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
851
+ <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
852
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
853
+ <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
854
+ """
855
+ if isinstance(other, str):
856
+ other = SpecifierSet(other)
857
+ elif not isinstance(other, SpecifierSet):
858
+ return NotImplemented
859
+
860
+ specifier = SpecifierSet()
861
+ specifier._specs = frozenset(self._specs | other._specs)
862
+
863
+ if self._prereleases is None and other._prereleases is not None:
864
+ specifier._prereleases = other._prereleases
865
+ elif (
866
+ self._prereleases is not None and other._prereleases is None
867
+ ) or self._prereleases == other._prereleases:
868
+ specifier._prereleases = self._prereleases
869
+ else:
870
+ raise ValueError(
871
+ "Cannot combine SpecifierSets with True and False prerelease overrides."
872
+ )
873
+
874
+ return specifier
875
+
876
+ def __eq__(self, other: object) -> bool:
877
+ """Whether or not the two SpecifierSet-like objects are equal.
878
+
879
+ :param other: The other object to check against.
880
+
881
+ The value of :attr:`prereleases` is ignored.
882
+
883
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
884
+ True
885
+ >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
886
+ ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
887
+ True
888
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
889
+ True
890
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
891
+ False
892
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
893
+ False
894
+ """
895
+ if isinstance(other, (str, Specifier)):
896
+ other = SpecifierSet(str(other))
897
+ elif not isinstance(other, SpecifierSet):
898
+ return NotImplemented
899
+
900
+ return self._specs == other._specs
901
+
902
+ def __len__(self) -> int:
903
+ """Returns the number of specifiers in this specifier set."""
904
+ return len(self._specs)
905
+
906
+ def __iter__(self) -> Iterator[Specifier]:
907
+ """
908
+ Returns an iterator over all the underlying :class:`Specifier` instances
909
+ in this specifier set.
910
+
911
+ >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
912
+ [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>]
913
+ """
914
+ return iter(self._specs)
915
+
916
+ def __contains__(self, item: UnparsedVersion) -> bool:
917
+ """Return whether or not the item is contained in this specifier.
918
+
919
+ :param item: The item to check for.
920
+
921
+ This is used for the ``in`` operator and behaves the same as
922
+ :meth:`contains` with no ``prereleases`` argument passed.
923
+
924
+ >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
925
+ True
926
+ >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
927
+ True
928
+ >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
929
+ False
930
+ >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
931
+ True
932
+ >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
933
+ True
934
+ """
935
+ return self.contains(item)
936
+
937
+ def contains(
938
+ self,
939
+ item: UnparsedVersion,
940
+ prereleases: bool | None = None,
941
+ installed: bool | None = None,
942
+ ) -> bool:
943
+ """Return whether or not the item is contained in this SpecifierSet.
944
+
945
+ :param item:
946
+ The item to check for, which can be a version string or a
947
+ :class:`Version` instance.
948
+ :param prereleases:
949
+ Whether or not to match prereleases with this SpecifierSet. If set to
950
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
951
+ and match prereleases, as there are no other versions.
952
+ :param installed:
953
+ Whether or not the item is installed. If set to ``True``, it will
954
+ accept prerelease versions even if the specifier does not allow them.
955
+
956
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
957
+ True
958
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
959
+ True
960
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
961
+ False
962
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
963
+ True
964
+ >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1")
965
+ False
966
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
967
+ True
968
+ """
969
+ version = _coerce_version(item)
970
+
971
+ if version is not None and installed and version.is_prerelease:
972
+ prereleases = True
973
+
974
+ check_item = item if version is None else version
975
+ return bool(list(self.filter([check_item], prereleases=prereleases)))
976
+
977
+ def filter(
978
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
979
+ ) -> Iterator[UnparsedVersionVar]:
980
+ """Filter items in the given iterable, that match the specifiers in this set.
981
+
982
+ :param iterable:
983
+ An iterable that can contain version strings and :class:`Version` instances.
984
+ The items in the iterable will be filtered according to the specifier.
985
+ :param prereleases:
986
+ Whether or not to allow prereleases in the returned iterator. If set to
987
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
988
+ and match prereleases if there are no other versions.
989
+
990
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
991
+ ['1.3']
992
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
993
+ ['1.3', <Version('1.4')>]
994
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
995
+ ['1.5a1']
996
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
997
+ ['1.3', '1.5a1']
998
+ >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
999
+ ['1.3', '1.5a1']
1000
+
1001
+ An "empty" SpecifierSet will filter items based on the presence of prerelease
1002
+ versions in the set.
1003
+
1004
+ >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
1005
+ ['1.3']
1006
+ >>> list(SpecifierSet("").filter(["1.5a1"]))
1007
+ ['1.5a1']
1008
+ >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
1009
+ ['1.3', '1.5a1']
1010
+ >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
1011
+ ['1.3', '1.5a1']
1012
+ """
1013
+ # Determine if we're forcing a prerelease or not, if we're not forcing
1014
+ # one for this particular filter call, then we'll use whatever the
1015
+ # SpecifierSet thinks for whether or not we should support prereleases.
1016
+ if prereleases is None and self.prereleases is not None:
1017
+ prereleases = self.prereleases
1018
+
1019
+ # If we have any specifiers, then we want to wrap our iterable in the
1020
+ # filter method for each one, this will act as a logical AND amongst
1021
+ # each specifier.
1022
+ if self._specs:
1023
+ # When prereleases is None, we need to let all versions through
1024
+ # the individual filters, then decide about prereleases at the end
1025
+ # based on whether any non-prereleases matched ALL specs.
1026
+ for spec in self._specs:
1027
+ iterable = spec.filter(
1028
+ iterable, prereleases=True if prereleases is None else prereleases
1029
+ )
1030
+
1031
+ if prereleases is not None:
1032
+ # If we have a forced prereleases value,
1033
+ # we can immediately return the iterator.
1034
+ return iter(iterable)
1035
+ else:
1036
+ # Handle empty SpecifierSet cases where prereleases is not None.
1037
+ if prereleases is True:
1038
+ return iter(iterable)
1039
+
1040
+ if prereleases is False:
1041
+ return (
1042
+ item
1043
+ for item in iterable
1044
+ if (version := _coerce_version(item)) is None
1045
+ or not version.is_prerelease
1046
+ )
1047
+
1048
+ # Finally if prereleases is None, apply PEP 440 logic:
1049
+ # exclude prereleases unless there are no final releases that matched.
1050
+ filtered_items: list[UnparsedVersionVar] = []
1051
+ found_prereleases: list[UnparsedVersionVar] = []
1052
+ found_final_release = False
1053
+
1054
+ for item in iterable:
1055
+ parsed_version = _coerce_version(item)
1056
+ # Arbitrary strings are always included as it is not
1057
+ # possible to determine if they are prereleases,
1058
+ # and they have already passed all specifiers.
1059
+ if parsed_version is None:
1060
+ filtered_items.append(item)
1061
+ found_prereleases.append(item)
1062
+ elif parsed_version.is_prerelease:
1063
+ found_prereleases.append(item)
1064
+ else:
1065
+ filtered_items.append(item)
1066
+ found_final_release = True
1067
+
1068
+ return iter(filtered_items if found_final_release else found_prereleases)
python/Lib/site-packages/setuptools/_vendor/packaging/tags.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import platform
9
+ import re
10
+ import struct
11
+ import subprocess
12
+ import sys
13
+ import sysconfig
14
+ from importlib.machinery import EXTENSION_SUFFIXES
15
+ from typing import (
16
+ Any,
17
+ Iterable,
18
+ Iterator,
19
+ Sequence,
20
+ Tuple,
21
+ cast,
22
+ )
23
+
24
+ from . import _manylinux, _musllinux
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ PythonVersion = Sequence[int]
29
+ AppleVersion = Tuple[int, int]
30
+
31
+ INTERPRETER_SHORT_NAMES: dict[str, str] = {
32
+ "python": "py", # Generic.
33
+ "cpython": "cp",
34
+ "pypy": "pp",
35
+ "ironpython": "ip",
36
+ "jython": "jy",
37
+ }
38
+
39
+
40
+ _32_BIT_INTERPRETER = struct.calcsize("P") == 4
41
+
42
+
43
+ class Tag:
44
+ """
45
+ A representation of the tag triple for a wheel.
46
+
47
+ Instances are considered immutable and thus are hashable. Equality checking
48
+ is also supported.
49
+ """
50
+
51
+ __slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
52
+
53
+ def __init__(self, interpreter: str, abi: str, platform: str) -> None:
54
+ self._interpreter = interpreter.lower()
55
+ self._abi = abi.lower()
56
+ self._platform = platform.lower()
57
+ # The __hash__ of every single element in a Set[Tag] will be evaluated each time
58
+ # that a set calls its `.disjoint()` method, which may be called hundreds of
59
+ # times when scanning a page of links for packages with tags matching that
60
+ # Set[Tag]. Pre-computing the value here produces significant speedups for
61
+ # downstream consumers.
62
+ self._hash = hash((self._interpreter, self._abi, self._platform))
63
+
64
+ @property
65
+ def interpreter(self) -> str:
66
+ return self._interpreter
67
+
68
+ @property
69
+ def abi(self) -> str:
70
+ return self._abi
71
+
72
+ @property
73
+ def platform(self) -> str:
74
+ return self._platform
75
+
76
+ def __eq__(self, other: object) -> bool:
77
+ if not isinstance(other, Tag):
78
+ return NotImplemented
79
+
80
+ return (
81
+ (self._hash == other._hash) # Short-circuit ASAP for perf reasons.
82
+ and (self._platform == other._platform)
83
+ and (self._abi == other._abi)
84
+ and (self._interpreter == other._interpreter)
85
+ )
86
+
87
+ def __hash__(self) -> int:
88
+ return self._hash
89
+
90
+ def __str__(self) -> str:
91
+ return f"{self._interpreter}-{self._abi}-{self._platform}"
92
+
93
+ def __repr__(self) -> str:
94
+ return f"<{self} @ {id(self)}>"
95
+
96
+ def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None:
97
+ # The cached _hash is wrong when unpickling.
98
+ _, slots = state
99
+ for k, v in slots.items():
100
+ setattr(self, k, v)
101
+ self._hash = hash((self._interpreter, self._abi, self._platform))
102
+
103
+
104
+ def parse_tag(tag: str) -> frozenset[Tag]:
105
+ """
106
+ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
107
+
108
+ Returning a set is required due to the possibility that the tag is a
109
+ compressed tag set.
110
+ """
111
+ tags = set()
112
+ interpreters, abis, platforms = tag.split("-")
113
+ for interpreter in interpreters.split("."):
114
+ for abi in abis.split("."):
115
+ for platform_ in platforms.split("."):
116
+ tags.add(Tag(interpreter, abi, platform_))
117
+ return frozenset(tags)
118
+
119
+
120
+ def _get_config_var(name: str, warn: bool = False) -> int | str | None:
121
+ value: int | str | None = sysconfig.get_config_var(name)
122
+ if value is None and warn:
123
+ logger.debug(
124
+ "Config variable '%s' is unset, Python ABI tag may be incorrect", name
125
+ )
126
+ return value
127
+
128
+
129
+ def _normalize_string(string: str) -> str:
130
+ return string.replace(".", "_").replace("-", "_").replace(" ", "_")
131
+
132
+
133
+ def _is_threaded_cpython(abis: list[str]) -> bool:
134
+ """
135
+ Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
136
+
137
+ The threaded builds are indicated by a "t" in the abiflags.
138
+ """
139
+ if len(abis) == 0:
140
+ return False
141
+ # expect e.g., cp313
142
+ m = re.match(r"cp\d+(.*)", abis[0])
143
+ if not m:
144
+ return False
145
+ abiflags = m.group(1)
146
+ return "t" in abiflags
147
+
148
+
149
+ def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:
150
+ """
151
+ Determine if the Python version supports abi3.
152
+
153
+ PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)
154
+ builds do not support abi3.
155
+ """
156
+ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
157
+
158
+
159
+ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]:
160
+ py_version = tuple(py_version) # To allow for version comparison.
161
+ abis = []
162
+ version = _version_nodot(py_version[:2])
163
+ threading = debug = pymalloc = ucs4 = ""
164
+ with_debug = _get_config_var("Py_DEBUG", warn)
165
+ has_refcount = hasattr(sys, "gettotalrefcount")
166
+ # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
167
+ # extension modules is the best option.
168
+ # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
169
+ has_ext = "_d.pyd" in EXTENSION_SUFFIXES
170
+ if with_debug or (with_debug is None and (has_refcount or has_ext)):
171
+ debug = "d"
172
+ if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn):
173
+ threading = "t"
174
+ if py_version < (3, 8):
175
+ with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
176
+ if with_pymalloc or with_pymalloc is None:
177
+ pymalloc = "m"
178
+ if py_version < (3, 3):
179
+ unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
180
+ if unicode_size == 4 or (
181
+ unicode_size is None and sys.maxunicode == 0x10FFFF
182
+ ):
183
+ ucs4 = "u"
184
+ elif debug:
185
+ # Debug builds can also load "normal" extension modules.
186
+ # We can also assume no UCS-4 or pymalloc requirement.
187
+ abis.append(f"cp{version}{threading}")
188
+ abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
189
+ return abis
190
+
191
+
192
+ def cpython_tags(
193
+ python_version: PythonVersion | None = None,
194
+ abis: Iterable[str] | None = None,
195
+ platforms: Iterable[str] | None = None,
196
+ *,
197
+ warn: bool = False,
198
+ ) -> Iterator[Tag]:
199
+ """
200
+ Yields the tags for a CPython interpreter.
201
+
202
+ The tags consist of:
203
+ - cp<python_version>-<abi>-<platform>
204
+ - cp<python_version>-abi3-<platform>
205
+ - cp<python_version>-none-<platform>
206
+ - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
207
+
208
+ If python_version only specifies a major version then user-provided ABIs and
209
+ the 'none' ABItag will be used.
210
+
211
+ If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
212
+ their normal position and not at the beginning.
213
+ """
214
+ if not python_version:
215
+ python_version = sys.version_info[:2]
216
+
217
+ interpreter = f"cp{_version_nodot(python_version[:2])}"
218
+
219
+ if abis is None:
220
+ abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else []
221
+ abis = list(abis)
222
+ # 'abi3' and 'none' are explicitly handled later.
223
+ for explicit_abi in ("abi3", "none"):
224
+ try:
225
+ abis.remove(explicit_abi)
226
+ except ValueError: # noqa: PERF203
227
+ pass
228
+
229
+ platforms = list(platforms or platform_tags())
230
+ for abi in abis:
231
+ for platform_ in platforms:
232
+ yield Tag(interpreter, abi, platform_)
233
+
234
+ threading = _is_threaded_cpython(abis)
235
+ use_abi3 = _abi3_applies(python_version, threading)
236
+ if use_abi3:
237
+ yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
238
+ yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
239
+
240
+ if use_abi3:
241
+ for minor_version in range(python_version[1] - 1, 1, -1):
242
+ for platform_ in platforms:
243
+ version = _version_nodot((python_version[0], minor_version))
244
+ interpreter = f"cp{version}"
245
+ yield Tag(interpreter, "abi3", platform_)
246
+
247
+
248
+ def _generic_abi() -> list[str]:
249
+ """
250
+ Return the ABI tag based on EXT_SUFFIX.
251
+ """
252
+ # The following are examples of `EXT_SUFFIX`.
253
+ # We want to keep the parts which are related to the ABI and remove the
254
+ # parts which are related to the platform:
255
+ # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310
256
+ # - mac: '.cpython-310-darwin.so' => cp310
257
+ # - win: '.cp310-win_amd64.pyd' => cp310
258
+ # - win: '.pyd' => cp37 (uses _cpython_abis())
259
+ # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
260
+ # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
261
+ # => graalpy_38_native
262
+
263
+ ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
264
+ if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
265
+ raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
266
+ parts = ext_suffix.split(".")
267
+ if len(parts) < 3:
268
+ # CPython3.7 and earlier uses ".pyd" on Windows.
269
+ return _cpython_abis(sys.version_info[:2])
270
+ soabi = parts[1]
271
+ if soabi.startswith("cpython"):
272
+ # non-windows
273
+ abi = "cp" + soabi.split("-")[1]
274
+ elif soabi.startswith("cp"):
275
+ # windows
276
+ abi = soabi.split("-")[0]
277
+ elif soabi.startswith("pypy"):
278
+ abi = "-".join(soabi.split("-")[:2])
279
+ elif soabi.startswith("graalpy"):
280
+ abi = "-".join(soabi.split("-")[:3])
281
+ elif soabi:
282
+ # pyston, ironpython, others?
283
+ abi = soabi
284
+ else:
285
+ return []
286
+ return [_normalize_string(abi)]
287
+
288
+
289
+ def generic_tags(
290
+ interpreter: str | None = None,
291
+ abis: Iterable[str] | None = None,
292
+ platforms: Iterable[str] | None = None,
293
+ *,
294
+ warn: bool = False,
295
+ ) -> Iterator[Tag]:
296
+ """
297
+ Yields the tags for a generic interpreter.
298
+
299
+ The tags consist of:
300
+ - <interpreter>-<abi>-<platform>
301
+
302
+ The "none" ABI will be added if it was not explicitly provided.
303
+ """
304
+ if not interpreter:
305
+ interp_name = interpreter_name()
306
+ interp_version = interpreter_version(warn=warn)
307
+ interpreter = f"{interp_name}{interp_version}"
308
+ abis = _generic_abi() if abis is None else list(abis)
309
+ platforms = list(platforms or platform_tags())
310
+ if "none" not in abis:
311
+ abis.append("none")
312
+ for abi in abis:
313
+ for platform_ in platforms:
314
+ yield Tag(interpreter, abi, platform_)
315
+
316
+
317
+ def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
318
+ """
319
+ Yields Python versions in descending order.
320
+
321
+ After the latest version, the major-only version will be yielded, and then
322
+ all previous versions of that major version.
323
+ """
324
+ if len(py_version) > 1:
325
+ yield f"py{_version_nodot(py_version[:2])}"
326
+ yield f"py{py_version[0]}"
327
+ if len(py_version) > 1:
328
+ for minor in range(py_version[1] - 1, -1, -1):
329
+ yield f"py{_version_nodot((py_version[0], minor))}"
330
+
331
+
332
+ def compatible_tags(
333
+ python_version: PythonVersion | None = None,
334
+ interpreter: str | None = None,
335
+ platforms: Iterable[str] | None = None,
336
+ ) -> Iterator[Tag]:
337
+ """
338
+ Yields the sequence of tags that are compatible with a specific version of Python.
339
+
340
+ The tags consist of:
341
+ - py*-none-<platform>
342
+ - <interpreter>-none-any # ... if `interpreter` is provided.
343
+ - py*-none-any
344
+ """
345
+ if not python_version:
346
+ python_version = sys.version_info[:2]
347
+ platforms = list(platforms or platform_tags())
348
+ for version in _py_interpreter_range(python_version):
349
+ for platform_ in platforms:
350
+ yield Tag(version, "none", platform_)
351
+ if interpreter:
352
+ yield Tag(interpreter, "none", "any")
353
+ for version in _py_interpreter_range(python_version):
354
+ yield Tag(version, "none", "any")
355
+
356
+
357
+ def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
358
+ if not is_32bit:
359
+ return arch
360
+
361
+ if arch.startswith("ppc"):
362
+ return "ppc"
363
+
364
+ return "i386"
365
+
366
+
367
+ def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]:
368
+ formats = [cpu_arch]
369
+ if cpu_arch == "x86_64":
370
+ if version < (10, 4):
371
+ return []
372
+ formats.extend(["intel", "fat64", "fat32"])
373
+
374
+ elif cpu_arch == "i386":
375
+ if version < (10, 4):
376
+ return []
377
+ formats.extend(["intel", "fat32", "fat"])
378
+
379
+ elif cpu_arch == "ppc64":
380
+ # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
381
+ if version > (10, 5) or version < (10, 4):
382
+ return []
383
+ formats.append("fat64")
384
+
385
+ elif cpu_arch == "ppc":
386
+ if version > (10, 6):
387
+ return []
388
+ formats.extend(["fat32", "fat"])
389
+
390
+ if cpu_arch in {"arm64", "x86_64"}:
391
+ formats.append("universal2")
392
+
393
+ if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
394
+ formats.append("universal")
395
+
396
+ return formats
397
+
398
+
399
+ def mac_platforms(
400
+ version: AppleVersion | None = None, arch: str | None = None
401
+ ) -> Iterator[str]:
402
+ """
403
+ Yields the platform tags for a macOS system.
404
+
405
+ The `version` parameter is a two-item tuple specifying the macOS version to
406
+ generate platform tags for. The `arch` parameter is the CPU architecture to
407
+ generate platform tags for. Both parameters default to the appropriate value
408
+ for the current system.
409
+ """
410
+ version_str, _, cpu_arch = platform.mac_ver()
411
+ if version is None:
412
+ version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
413
+ if version == (10, 16):
414
+ # When built against an older macOS SDK, Python will report macOS 10.16
415
+ # instead of the real version.
416
+ version_str = subprocess.run(
417
+ [
418
+ sys.executable,
419
+ "-sS",
420
+ "-c",
421
+ "import platform; print(platform.mac_ver()[0])",
422
+ ],
423
+ check=True,
424
+ env={"SYSTEM_VERSION_COMPAT": "0"},
425
+ stdout=subprocess.PIPE,
426
+ text=True,
427
+ ).stdout
428
+ version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
429
+
430
+ if arch is None:
431
+ arch = _mac_arch(cpu_arch)
432
+
433
+ if (10, 0) <= version < (11, 0):
434
+ # Prior to Mac OS 11, each yearly release of Mac OS bumped the
435
+ # "minor" version number. The major version was always 10.
436
+ major_version = 10
437
+ for minor_version in range(version[1], -1, -1):
438
+ compat_version = major_version, minor_version
439
+ binary_formats = _mac_binary_formats(compat_version, arch)
440
+ for binary_format in binary_formats:
441
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
442
+
443
+ if version >= (11, 0):
444
+ # Starting with Mac OS 11, each yearly release bumps the major version
445
+ # number. The minor versions are now the midyear updates.
446
+ minor_version = 0
447
+ for major_version in range(version[0], 10, -1):
448
+ compat_version = major_version, minor_version
449
+ binary_formats = _mac_binary_formats(compat_version, arch)
450
+ for binary_format in binary_formats:
451
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
452
+
453
+ if version >= (11, 0):
454
+ # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
455
+ # Arm64 support was introduced in 11.0, so no Arm binaries from previous
456
+ # releases exist.
457
+ #
458
+ # However, the "universal2" binary format can have a
459
+ # macOS version earlier than 11.0 when the x86_64 part of the binary supports
460
+ # that version of macOS.
461
+ major_version = 10
462
+ if arch == "x86_64":
463
+ for minor_version in range(16, 3, -1):
464
+ compat_version = major_version, minor_version
465
+ binary_formats = _mac_binary_formats(compat_version, arch)
466
+ for binary_format in binary_formats:
467
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
468
+ else:
469
+ for minor_version in range(16, 3, -1):
470
+ compat_version = major_version, minor_version
471
+ binary_format = "universal2"
472
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
473
+
474
+
475
+ def ios_platforms(
476
+ version: AppleVersion | None = None, multiarch: str | None = None
477
+ ) -> Iterator[str]:
478
+ """
479
+ Yields the platform tags for an iOS system.
480
+
481
+ :param version: A two-item tuple specifying the iOS version to generate
482
+ platform tags for. Defaults to the current iOS version.
483
+ :param multiarch: The CPU architecture+ABI to generate platform tags for -
484
+ (the value used by `sys.implementation._multiarch` e.g.,
485
+ `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current
486
+ multiarch value.
487
+ """
488
+ if version is None:
489
+ # if iOS is the current platform, ios_ver *must* be defined. However,
490
+ # it won't exist for CPython versions before 3.13, which causes a mypy
491
+ # error.
492
+ _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore]
493
+ version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
494
+
495
+ if multiarch is None:
496
+ multiarch = sys.implementation._multiarch
497
+ multiarch = multiarch.replace("-", "_")
498
+
499
+ ios_platform_template = "ios_{major}_{minor}_{multiarch}"
500
+
501
+ # Consider any iOS major.minor version from the version requested, down to
502
+ # 12.0. 12.0 is the first iOS version that is known to have enough features
503
+ # to support CPython. Consider every possible minor release up to X.9. There
504
+ # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra
505
+ # candidates that won't ever match doesn't really hurt, and it saves us from
506
+ # having to keep an explicit list of known iOS versions in the code. Return
507
+ # the results descending order of version number.
508
+
509
+ # If the requested major version is less than 12, there won't be any matches.
510
+ if version[0] < 12:
511
+ return
512
+
513
+ # Consider the actual X.Y version that was requested.
514
+ yield ios_platform_template.format(
515
+ major=version[0], minor=version[1], multiarch=multiarch
516
+ )
517
+
518
+ # Consider every minor version from X.0 to the minor version prior to the
519
+ # version requested by the platform.
520
+ for minor in range(version[1] - 1, -1, -1):
521
+ yield ios_platform_template.format(
522
+ major=version[0], minor=minor, multiarch=multiarch
523
+ )
524
+
525
+ for major in range(version[0] - 1, 11, -1):
526
+ for minor in range(9, -1, -1):
527
+ yield ios_platform_template.format(
528
+ major=major, minor=minor, multiarch=multiarch
529
+ )
530
+
531
+
532
+ def android_platforms(
533
+ api_level: int | None = None, abi: str | None = None
534
+ ) -> Iterator[str]:
535
+ """
536
+ Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on
537
+ non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
538
+
539
+ :param int api_level: The maximum `API level
540
+ <https://developer.android.com/tools/releases/platforms>`__ to return. Defaults
541
+ to the current system's version, as returned by ``platform.android_ver``.
542
+ :param str abi: The `Android ABI <https://developer.android.com/ndk/guides/abis>`__,
543
+ e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by
544
+ ``sysconfig.get_platform``. Hyphens and periods will be replaced with
545
+ underscores.
546
+ """
547
+ if platform.system() != "Android" and (api_level is None or abi is None):
548
+ raise TypeError(
549
+ "on non-Android platforms, the api_level and abi arguments are required"
550
+ )
551
+
552
+ if api_level is None:
553
+ # Python 3.13 was the first version to return platform.system() == "Android",
554
+ # and also the first version to define platform.android_ver().
555
+ api_level = platform.android_ver().api_level # type: ignore[attr-defined]
556
+
557
+ if abi is None:
558
+ abi = sysconfig.get_platform().split("-")[-1]
559
+ abi = _normalize_string(abi)
560
+
561
+ # 16 is the minimum API level known to have enough features to support CPython
562
+ # without major patching. Yield every API level from the maximum down to the
563
+ # minimum, inclusive.
564
+ min_api_level = 16
565
+ for ver in range(api_level, min_api_level - 1, -1):
566
+ yield f"android_{ver}_{abi}"
567
+
568
+
569
+ def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
570
+ linux = _normalize_string(sysconfig.get_platform())
571
+ if not linux.startswith("linux_"):
572
+ # we should never be here, just yield the sysconfig one and return
573
+ yield linux
574
+ return
575
+ if is_32bit:
576
+ if linux == "linux_x86_64":
577
+ linux = "linux_i686"
578
+ elif linux == "linux_aarch64":
579
+ linux = "linux_armv8l"
580
+ _, arch = linux.split("_", 1)
581
+ archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
582
+ yield from _manylinux.platform_tags(archs)
583
+ yield from _musllinux.platform_tags(archs)
584
+ for arch in archs:
585
+ yield f"linux_{arch}"
586
+
587
+
588
+ def _generic_platforms() -> Iterator[str]:
589
+ yield _normalize_string(sysconfig.get_platform())
590
+
591
+
592
+ def platform_tags() -> Iterator[str]:
593
+ """
594
+ Provides the platform tags for this installation.
595
+ """
596
+ if platform.system() == "Darwin":
597
+ return mac_platforms()
598
+ elif platform.system() == "iOS":
599
+ return ios_platforms()
600
+ elif platform.system() == "Android":
601
+ return android_platforms()
602
+ elif platform.system() == "Linux":
603
+ return _linux_platforms()
604
+ else:
605
+ return _generic_platforms()
606
+
607
+
608
+ def interpreter_name() -> str:
609
+ """
610
+ Returns the name of the running interpreter.
611
+
612
+ Some implementations have a reserved, two-letter abbreviation which will
613
+ be returned when appropriate.
614
+ """
615
+ name = sys.implementation.name
616
+ return INTERPRETER_SHORT_NAMES.get(name) or name
617
+
618
+
619
+ def interpreter_version(*, warn: bool = False) -> str:
620
+ """
621
+ Returns the version of the running interpreter.
622
+ """
623
+ version = _get_config_var("py_version_nodot", warn=warn)
624
+ return str(version) if version else _version_nodot(sys.version_info[:2])
625
+
626
+
627
+ def _version_nodot(version: PythonVersion) -> str:
628
+ return "".join(map(str, version))
629
+
630
+
631
+ def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
632
+ """
633
+ Returns the sequence of tag triples for the running interpreter.
634
+
635
+ The order of the sequence corresponds to priority order for the
636
+ interpreter, from most to least important.
637
+ """
638
+
639
+ interp_name = interpreter_name()
640
+ if interp_name == "cp":
641
+ yield from cpython_tags(warn=warn)
642
+ else:
643
+ yield from generic_tags()
644
+
645
+ if interp_name == "pp":
646
+ interp = "pp3"
647
+ elif interp_name == "cp":
648
+ interp = "cp" + interpreter_version(warn=warn)
649
+ else:
650
+ interp = None
651
+ yield from compatible_tags(interpreter=interp)