ZTWHHH commited on
Commit
92ef116
·
verified ·
1 Parent(s): 2a8efdb

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. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/__init__.py +14 -0
  2. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_log.py +3 -0
  3. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_macos_compat.py +12 -0
  4. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_modified.py +73 -0
  5. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_msvccompiler.py +611 -0
  6. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/archive_util.py +264 -0
  7. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/ccompiler.py +1263 -0
  8. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/cmd.py +462 -0
  9. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/core.py +289 -0
  10. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/cygwinccompiler.py +339 -0
  11. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/debug.py +5 -0
  12. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/dep_util.py +14 -0
  13. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/dir_util.py +244 -0
  14. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/dist.py +1317 -0
  15. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/errors.py +124 -0
  16. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/extension.py +255 -0
  17. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/fancy_getopt.py +471 -0
  18. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/file_util.py +236 -0
  19. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/filelist.py +366 -0
  20. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/log.py +56 -0
  21. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/spawn.py +117 -0
  22. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/sysconfig.py +583 -0
  23. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/__init__.py +42 -0
  24. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_cmd.py +107 -0
  25. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_data.py +74 -0
  26. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_sysconfig.py +319 -0
  27. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_util.py +243 -0
  28. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/text_file.py +286 -0
  29. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/unixccompiler.py +402 -0
  30. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/util.py +502 -0
  31. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/version.py +348 -0
  32. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/versionpredicate.py +175 -0
  33. evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/zosccompiler.py +229 -0
  34. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/contexts.cpython-310.pyc +0 -0
  36. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc +0 -0
  37. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/namespaces.cpython-310.pyc +0 -0
  38. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc +0 -0
  39. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc +0 -0
  40. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc +0 -0
  41. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc +0 -0
  42. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc +0 -0
  43. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc +0 -0
  44. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build.cpython-310.pyc +0 -0
  45. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc +0 -0
  46. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc +0 -0
  47. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc +0 -0
  48. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc +0 -0
  49. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_depends.cpython-310.pyc +0 -0
  50. evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_develop.cpython-310.pyc +0 -0
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import sys
3
+
4
+ __version__, _, _ = sys.version.partition(' ')
5
+
6
+
7
+ try:
8
+ # Allow Debian and pkgsrc (only) to customize system
9
+ # behavior. Ref pypa/distutils#2 and pypa/distutils#16.
10
+ # This hook is deprecated and no other environments
11
+ # should use it.
12
+ importlib.import_module('_distutils_system_mod')
13
+ except ImportError:
14
+ pass
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_log.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import logging
2
+
3
+ log = logging.getLogger()
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_macos_compat.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import sys
3
+
4
+
5
+ def bypass_compiler_fixup(cmd, args):
6
+ return cmd
7
+
8
+
9
+ if sys.platform == 'darwin':
10
+ compiler_fixup = importlib.import_module('_osx_support').compiler_fixup
11
+ else:
12
+ compiler_fixup = bypass_compiler_fixup
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_modified.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Timestamp comparison of files and groups of files."""
2
+
3
+ import functools
4
+ import os.path
5
+
6
+ from jaraco.functools import splat
7
+
8
+ from .compat.py39 import zip_strict
9
+ from .errors import DistutilsFileError
10
+
11
+
12
+ def _newer(source, target):
13
+ return not os.path.exists(target) or (
14
+ os.path.getmtime(source) > os.path.getmtime(target)
15
+ )
16
+
17
+
18
+ def newer(source, target):
19
+ """
20
+ Is source modified more recently than target.
21
+
22
+ Returns True if 'source' is modified more recently than
23
+ 'target' or if 'target' does not exist.
24
+
25
+ Raises DistutilsFileError if 'source' does not exist.
26
+ """
27
+ if not os.path.exists(source):
28
+ raise DistutilsFileError(f"file '{os.path.abspath(source)}' does not exist")
29
+
30
+ return _newer(source, target)
31
+
32
+
33
+ def newer_pairwise(sources, targets, newer=newer):
34
+ """
35
+ Filter filenames where sources are newer than targets.
36
+
37
+ Walk two filename iterables in parallel, testing if each source is newer
38
+ than its corresponding target. Returns a pair of lists (sources,
39
+ targets) where source is newer than target, according to the semantics
40
+ of 'newer()'.
41
+ """
42
+ newer_pairs = filter(splat(newer), zip_strict(sources, targets))
43
+ return tuple(map(list, zip(*newer_pairs))) or ([], [])
44
+
45
+
46
+ def newer_group(sources, target, missing='error'):
47
+ """
48
+ Is target out-of-date with respect to any file in sources.
49
+
50
+ Return True if 'target' is out-of-date with respect to any file
51
+ listed in 'sources'. In other words, if 'target' exists and is newer
52
+ than every file in 'sources', return False; otherwise return True.
53
+ ``missing`` controls how to handle a missing source file:
54
+
55
+ - error (default): allow the ``stat()`` call to fail.
56
+ - ignore: silently disregard any missing source files.
57
+ - newer: treat missing source files as "target out of date". This
58
+ mode is handy in "dry-run" mode: it will pretend to carry out
59
+ commands that wouldn't work because inputs are missing, but
60
+ that doesn't matter because dry-run won't run the commands.
61
+ """
62
+
63
+ def missing_as_newer(source):
64
+ return missing == 'newer' and not os.path.exists(source)
65
+
66
+ ignored = os.path.exists if missing == 'ignore' else None
67
+ return not os.path.exists(target) or any(
68
+ missing_as_newer(source) or _newer(source, target)
69
+ for source in filter(ignored, sources)
70
+ )
71
+
72
+
73
+ newer_pairwise_group = functools.partial(newer_pairwise, newer=newer_group)
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/_msvccompiler.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils._msvccompiler
2
+
3
+ Contains MSVCCompiler, an implementation of the abstract CCompiler class
4
+ for Microsoft Visual Studio 2015.
5
+
6
+ This module requires VS 2015 or later.
7
+ """
8
+
9
+ # Written by Perry Stoll
10
+ # hacked by Robin Becker and Thomas Heller to do a better job of
11
+ # finding DevStudio (through the registry)
12
+ # ported to VS 2005 and VS 2008 by Christian Heimes
13
+ # ported to VS 2015 by Steve Dower
14
+
15
+ import contextlib
16
+ import os
17
+ import subprocess
18
+ import unittest.mock as mock
19
+ import warnings
20
+
21
+ with contextlib.suppress(ImportError):
22
+ import winreg
23
+
24
+ from itertools import count
25
+
26
+ from ._log import log
27
+ from .ccompiler import CCompiler, gen_lib_options
28
+ from .errors import (
29
+ CompileError,
30
+ DistutilsExecError,
31
+ DistutilsPlatformError,
32
+ LibError,
33
+ LinkError,
34
+ )
35
+ from .util import get_host_platform, get_platform
36
+
37
+
38
+ def _find_vc2015():
39
+ try:
40
+ key = winreg.OpenKeyEx(
41
+ winreg.HKEY_LOCAL_MACHINE,
42
+ r"Software\Microsoft\VisualStudio\SxS\VC7",
43
+ access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
44
+ )
45
+ except OSError:
46
+ log.debug("Visual C++ is not registered")
47
+ return None, None
48
+
49
+ best_version = 0
50
+ best_dir = None
51
+ with key:
52
+ for i in count():
53
+ try:
54
+ v, vc_dir, vt = winreg.EnumValue(key, i)
55
+ except OSError:
56
+ break
57
+ if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
58
+ try:
59
+ version = int(float(v))
60
+ except (ValueError, TypeError):
61
+ continue
62
+ if version >= 14 and version > best_version:
63
+ best_version, best_dir = version, vc_dir
64
+ return best_version, best_dir
65
+
66
+
67
+ def _find_vc2017():
68
+ """Returns "15, path" based on the result of invoking vswhere.exe
69
+ If no install is found, returns "None, None"
70
+
71
+ The version is returned to avoid unnecessarily changing the function
72
+ result. It may be ignored when the path is not None.
73
+
74
+ If vswhere.exe is not available, by definition, VS 2017 is not
75
+ installed.
76
+ """
77
+ root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
78
+ if not root:
79
+ return None, None
80
+
81
+ variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64'
82
+ suitable_components = (
83
+ f"Microsoft.VisualStudio.Component.VC.Tools.{variant}",
84
+ "Microsoft.VisualStudio.Workload.WDExpress",
85
+ )
86
+
87
+ for component in suitable_components:
88
+ # Workaround for `-requiresAny` (only available on VS 2017 > 15.6)
89
+ with contextlib.suppress(
90
+ subprocess.CalledProcessError, OSError, UnicodeDecodeError
91
+ ):
92
+ path = (
93
+ subprocess.check_output([
94
+ os.path.join(
95
+ root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
96
+ ),
97
+ "-latest",
98
+ "-prerelease",
99
+ "-requires",
100
+ component,
101
+ "-property",
102
+ "installationPath",
103
+ "-products",
104
+ "*",
105
+ ])
106
+ .decode(encoding="mbcs", errors="strict")
107
+ .strip()
108
+ )
109
+
110
+ path = os.path.join(path, "VC", "Auxiliary", "Build")
111
+ if os.path.isdir(path):
112
+ return 15, path
113
+
114
+ return None, None # no suitable component found
115
+
116
+
117
+ PLAT_SPEC_TO_RUNTIME = {
118
+ 'x86': 'x86',
119
+ 'x86_amd64': 'x64',
120
+ 'x86_arm': 'arm',
121
+ 'x86_arm64': 'arm64',
122
+ }
123
+
124
+
125
+ def _find_vcvarsall(plat_spec):
126
+ # bpo-38597: Removed vcruntime return value
127
+ _, best_dir = _find_vc2017()
128
+
129
+ if not best_dir:
130
+ best_version, best_dir = _find_vc2015()
131
+
132
+ if not best_dir:
133
+ log.debug("No suitable Visual C++ version found")
134
+ return None, None
135
+
136
+ vcvarsall = os.path.join(best_dir, "vcvarsall.bat")
137
+ if not os.path.isfile(vcvarsall):
138
+ log.debug("%s cannot be found", vcvarsall)
139
+ return None, None
140
+
141
+ return vcvarsall, None
142
+
143
+
144
+ def _get_vc_env(plat_spec):
145
+ if os.getenv("DISTUTILS_USE_SDK"):
146
+ return {key.lower(): value for key, value in os.environ.items()}
147
+
148
+ vcvarsall, _ = _find_vcvarsall(plat_spec)
149
+ if not vcvarsall:
150
+ raise DistutilsPlatformError(
151
+ 'Microsoft Visual C++ 14.0 or greater is required. '
152
+ 'Get it with "Microsoft C++ Build Tools": '
153
+ 'https://visualstudio.microsoft.com/visual-cpp-build-tools/'
154
+ )
155
+
156
+ try:
157
+ out = subprocess.check_output(
158
+ f'cmd /u /c "{vcvarsall}" {plat_spec} && set',
159
+ stderr=subprocess.STDOUT,
160
+ ).decode('utf-16le', errors='replace')
161
+ except subprocess.CalledProcessError as exc:
162
+ log.error(exc.output)
163
+ raise DistutilsPlatformError(f"Error executing {exc.cmd}")
164
+
165
+ env = {
166
+ key.lower(): value
167
+ for key, _, value in (line.partition('=') for line in out.splitlines())
168
+ if key and value
169
+ }
170
+
171
+ return env
172
+
173
+
174
+ def _find_exe(exe, paths=None):
175
+ """Return path to an MSVC executable program.
176
+
177
+ Tries to find the program in several places: first, one of the
178
+ MSVC program search paths from the registry; next, the directories
179
+ in the PATH environment variable. If any of those work, return an
180
+ absolute path that is known to exist. If none of them work, just
181
+ return the original program name, 'exe'.
182
+ """
183
+ if not paths:
184
+ paths = os.getenv('path').split(os.pathsep)
185
+ for p in paths:
186
+ fn = os.path.join(os.path.abspath(p), exe)
187
+ if os.path.isfile(fn):
188
+ return fn
189
+ return exe
190
+
191
+
192
+ _vcvars_names = {
193
+ 'win32': 'x86',
194
+ 'win-amd64': 'amd64',
195
+ 'win-arm32': 'arm',
196
+ 'win-arm64': 'arm64',
197
+ }
198
+
199
+
200
+ def _get_vcvars_spec(host_platform, platform):
201
+ """
202
+ Given a host platform and platform, determine the spec for vcvarsall.
203
+
204
+ Uses the native MSVC host if the host platform would need expensive
205
+ emulation for x86.
206
+
207
+ >>> _get_vcvars_spec('win-arm64', 'win32')
208
+ 'arm64_x86'
209
+ >>> _get_vcvars_spec('win-arm64', 'win-amd64')
210
+ 'arm64_amd64'
211
+
212
+ Otherwise, always cross-compile from x86 to work with the
213
+ lighter-weight MSVC installs that do not include native 64-bit tools.
214
+
215
+ >>> _get_vcvars_spec('win32', 'win32')
216
+ 'x86'
217
+ >>> _get_vcvars_spec('win-arm32', 'win-arm32')
218
+ 'x86_arm'
219
+ >>> _get_vcvars_spec('win-amd64', 'win-arm64')
220
+ 'x86_arm64'
221
+ """
222
+ if host_platform != 'win-arm64':
223
+ host_platform = 'win32'
224
+ vc_hp = _vcvars_names[host_platform]
225
+ vc_plat = _vcvars_names[platform]
226
+ return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}'
227
+
228
+
229
+ class MSVCCompiler(CCompiler):
230
+ """Concrete class that implements an interface to Microsoft Visual C++,
231
+ as defined by the CCompiler abstract class."""
232
+
233
+ compiler_type = 'msvc'
234
+
235
+ # Just set this so CCompiler's constructor doesn't barf. We currently
236
+ # don't use the 'set_executables()' bureaucracy provided by CCompiler,
237
+ # as it really isn't necessary for this sort of single-compiler class.
238
+ # Would be nice to have a consistent interface with UnixCCompiler,
239
+ # though, so it's worth thinking about.
240
+ executables = {}
241
+
242
+ # Private class data (need to distinguish C from C++ source for compiler)
243
+ _c_extensions = ['.c']
244
+ _cpp_extensions = ['.cc', '.cpp', '.cxx']
245
+ _rc_extensions = ['.rc']
246
+ _mc_extensions = ['.mc']
247
+
248
+ # Needed for the filename generation methods provided by the
249
+ # base class, CCompiler.
250
+ src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
251
+ res_extension = '.res'
252
+ obj_extension = '.obj'
253
+ static_lib_extension = '.lib'
254
+ shared_lib_extension = '.dll'
255
+ static_lib_format = shared_lib_format = '%s%s'
256
+ exe_extension = '.exe'
257
+
258
+ def __init__(self, verbose=False, dry_run=False, force=False):
259
+ super().__init__(verbose, dry_run, force)
260
+ # target platform (.plat_name is consistent with 'bdist')
261
+ self.plat_name = None
262
+ self.initialized = False
263
+
264
+ @classmethod
265
+ def _configure(cls, vc_env):
266
+ """
267
+ Set class-level include/lib dirs.
268
+ """
269
+ cls.include_dirs = cls._parse_path(vc_env.get('include', ''))
270
+ cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))
271
+
272
+ @staticmethod
273
+ def _parse_path(val):
274
+ return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]
275
+
276
+ def initialize(self, plat_name=None):
277
+ # multi-init means we would need to check platform same each time...
278
+ assert not self.initialized, "don't init multiple times"
279
+ if plat_name is None:
280
+ plat_name = get_platform()
281
+ # sanity check for platforms to prevent obscure errors later.
282
+ if plat_name not in _vcvars_names:
283
+ raise DistutilsPlatformError(
284
+ f"--plat-name must be one of {tuple(_vcvars_names)}"
285
+ )
286
+
287
+ plat_spec = _get_vcvars_spec(get_host_platform(), plat_name)
288
+
289
+ vc_env = _get_vc_env(plat_spec)
290
+ if not vc_env:
291
+ raise DistutilsPlatformError(
292
+ "Unable to find a compatible Visual Studio installation."
293
+ )
294
+ self._configure(vc_env)
295
+
296
+ self._paths = vc_env.get('path', '')
297
+ paths = self._paths.split(os.pathsep)
298
+ self.cc = _find_exe("cl.exe", paths)
299
+ self.linker = _find_exe("link.exe", paths)
300
+ self.lib = _find_exe("lib.exe", paths)
301
+ self.rc = _find_exe("rc.exe", paths) # resource compiler
302
+ self.mc = _find_exe("mc.exe", paths) # message compiler
303
+ self.mt = _find_exe("mt.exe", paths) # message compiler
304
+
305
+ self.preprocess_options = None
306
+ # bpo-38597: Always compile with dynamic linking
307
+ # Future releases of Python 3.x will include all past
308
+ # versions of vcruntime*.dll for compatibility.
309
+ self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
310
+
311
+ self.compile_options_debug = [
312
+ '/nologo',
313
+ '/Od',
314
+ '/MDd',
315
+ '/Zi',
316
+ '/W3',
317
+ '/D_DEBUG',
318
+ ]
319
+
320
+ ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
321
+
322
+ ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
323
+
324
+ self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
325
+ self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
326
+ self.ldflags_shared = [
327
+ *ldflags,
328
+ '/DLL',
329
+ '/MANIFEST:EMBED,ID=2',
330
+ '/MANIFESTUAC:NO',
331
+ ]
332
+ self.ldflags_shared_debug = [
333
+ *ldflags_debug,
334
+ '/DLL',
335
+ '/MANIFEST:EMBED,ID=2',
336
+ '/MANIFESTUAC:NO',
337
+ ]
338
+ self.ldflags_static = [*ldflags]
339
+ self.ldflags_static_debug = [*ldflags_debug]
340
+
341
+ self._ldflags = {
342
+ (CCompiler.EXECUTABLE, None): self.ldflags_exe,
343
+ (CCompiler.EXECUTABLE, False): self.ldflags_exe,
344
+ (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug,
345
+ (CCompiler.SHARED_OBJECT, None): self.ldflags_shared,
346
+ (CCompiler.SHARED_OBJECT, False): self.ldflags_shared,
347
+ (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug,
348
+ (CCompiler.SHARED_LIBRARY, None): self.ldflags_static,
349
+ (CCompiler.SHARED_LIBRARY, False): self.ldflags_static,
350
+ (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug,
351
+ }
352
+
353
+ self.initialized = True
354
+
355
+ # -- Worker methods ------------------------------------------------
356
+
357
+ @property
358
+ def out_extensions(self):
359
+ return {
360
+ **super().out_extensions,
361
+ **{
362
+ ext: self.res_extension
363
+ for ext in self._rc_extensions + self._mc_extensions
364
+ },
365
+ }
366
+
367
+ def compile( # noqa: C901
368
+ self,
369
+ sources,
370
+ output_dir=None,
371
+ macros=None,
372
+ include_dirs=None,
373
+ debug=False,
374
+ extra_preargs=None,
375
+ extra_postargs=None,
376
+ depends=None,
377
+ ):
378
+ if not self.initialized:
379
+ self.initialize()
380
+ compile_info = self._setup_compile(
381
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
382
+ )
383
+ macros, objects, extra_postargs, pp_opts, build = compile_info
384
+
385
+ compile_opts = extra_preargs or []
386
+ compile_opts.append('/c')
387
+ if debug:
388
+ compile_opts.extend(self.compile_options_debug)
389
+ else:
390
+ compile_opts.extend(self.compile_options)
391
+
392
+ add_cpp_opts = False
393
+
394
+ for obj in objects:
395
+ try:
396
+ src, ext = build[obj]
397
+ except KeyError:
398
+ continue
399
+ if debug:
400
+ # pass the full pathname to MSVC in debug mode,
401
+ # this allows the debugger to find the source file
402
+ # without asking the user to browse for it
403
+ src = os.path.abspath(src)
404
+
405
+ # Anaconda/conda-forge customisation, we want our pdbs to be
406
+ # relocatable:
407
+ # https://developercommunity.visualstudio.com/comments/623156/view.html
408
+ d1trimfile_opts = []
409
+ if 'SRC_DIR' in os.environ and os.path.basename(self.cc) == "cl.exe":
410
+ d1trimfile_opts.append("/d1trimfile:" + os.environ['SRC_DIR'])
411
+
412
+ if ext in self._c_extensions:
413
+ input_opt = "/Tc" + src
414
+ elif ext in self._cpp_extensions:
415
+ input_opt = "/Tp" + src
416
+ add_cpp_opts = True
417
+ elif ext in self._rc_extensions:
418
+ # compile .RC to .RES file
419
+ input_opt = src
420
+ output_opt = "/fo" + obj
421
+ try:
422
+ self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
423
+ except DistutilsExecError as msg:
424
+ raise CompileError(msg)
425
+ continue
426
+ elif ext in self._mc_extensions:
427
+ # Compile .MC to .RC file to .RES file.
428
+ # * '-h dir' specifies the directory for the
429
+ # generated include file
430
+ # * '-r dir' specifies the target directory of the
431
+ # generated RC file and the binary message resource
432
+ # it includes
433
+ #
434
+ # For now (since there are no options to change this),
435
+ # we use the source-directory for the include file and
436
+ # the build directory for the RC file and message
437
+ # resources. This works at least for win32all.
438
+ h_dir = os.path.dirname(src)
439
+ rc_dir = os.path.dirname(obj)
440
+ try:
441
+ # first compile .MC to .RC and .H file
442
+ self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
443
+ base, _ = os.path.splitext(os.path.basename(src))
444
+ rc_file = os.path.join(rc_dir, base + '.rc')
445
+ # then compile .RC to .RES file
446
+ self.spawn([self.rc, "/fo" + obj, rc_file])
447
+
448
+ except DistutilsExecError as msg:
449
+ raise CompileError(msg)
450
+ continue
451
+ else:
452
+ # how to handle this file?
453
+ raise CompileError(f"Don't know how to compile {src} to {obj}")
454
+
455
+ args = [self.cc] + compile_opts + pp_opts + d1trimfile_opts
456
+ if add_cpp_opts:
457
+ args.append('/EHsc')
458
+ args.extend((input_opt, "/Fo" + obj))
459
+ args.extend(extra_postargs)
460
+
461
+ try:
462
+ self.spawn(args)
463
+ except DistutilsExecError as msg:
464
+ raise CompileError(msg)
465
+
466
+ return objects
467
+
468
+ def create_static_lib(
469
+ self, objects, output_libname, output_dir=None, debug=False, target_lang=None
470
+ ):
471
+ if not self.initialized:
472
+ self.initialize()
473
+ objects, output_dir = self._fix_object_args(objects, output_dir)
474
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
475
+
476
+ if self._need_link(objects, output_filename):
477
+ lib_args = objects + ['/OUT:' + output_filename]
478
+ if debug:
479
+ pass # XXX what goes here?
480
+ try:
481
+ log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
482
+ self.spawn([self.lib] + lib_args)
483
+ except DistutilsExecError as msg:
484
+ raise LibError(msg)
485
+ else:
486
+ log.debug("skipping %s (up-to-date)", output_filename)
487
+
488
+ def link(
489
+ self,
490
+ target_desc,
491
+ objects,
492
+ output_filename,
493
+ output_dir=None,
494
+ libraries=None,
495
+ library_dirs=None,
496
+ runtime_library_dirs=None,
497
+ export_symbols=None,
498
+ debug=False,
499
+ extra_preargs=None,
500
+ extra_postargs=None,
501
+ build_temp=None,
502
+ target_lang=None,
503
+ ):
504
+ if not self.initialized:
505
+ self.initialize()
506
+ objects, output_dir = self._fix_object_args(objects, output_dir)
507
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
508
+ libraries, library_dirs, runtime_library_dirs = fixed_args
509
+
510
+ if runtime_library_dirs:
511
+ self.warn(
512
+ "I don't know what to do with 'runtime_library_dirs': "
513
+ + str(runtime_library_dirs)
514
+ )
515
+
516
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
517
+ if output_dir is not None:
518
+ output_filename = os.path.join(output_dir, output_filename)
519
+
520
+ if self._need_link(objects, output_filename):
521
+ ldflags = self._ldflags[target_desc, debug]
522
+
523
+ export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
524
+
525
+ ld_args = (
526
+ ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
527
+ )
528
+
529
+ # The MSVC linker generates .lib and .exp files, which cannot be
530
+ # suppressed by any linker switches. The .lib files may even be
531
+ # needed! Make sure they are generated in the temporary build
532
+ # directory. Since they have different names for debug and release
533
+ # builds, they can go into the same directory.
534
+ build_temp = os.path.dirname(objects[0])
535
+ if export_symbols is not None:
536
+ (dll_name, dll_ext) = os.path.splitext(
537
+ os.path.basename(output_filename)
538
+ )
539
+ implib_file = os.path.join(build_temp, self.library_filename(dll_name))
540
+ ld_args.append('/IMPLIB:' + implib_file)
541
+
542
+ if extra_preargs:
543
+ ld_args[:0] = extra_preargs
544
+ if extra_postargs:
545
+ ld_args.extend(extra_postargs)
546
+
547
+ output_dir = os.path.dirname(os.path.abspath(output_filename))
548
+ self.mkpath(output_dir)
549
+ try:
550
+ log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
551
+ self.spawn([self.linker] + ld_args)
552
+ except DistutilsExecError as msg:
553
+ raise LinkError(msg)
554
+ else:
555
+ log.debug("skipping %s (up-to-date)", output_filename)
556
+
557
+ def spawn(self, cmd):
558
+ env = dict(os.environ, PATH=self._paths)
559
+ with self._fallback_spawn(cmd, env) as fallback:
560
+ return super().spawn(cmd, env=env)
561
+ return fallback.value
562
+
563
+ @contextlib.contextmanager
564
+ def _fallback_spawn(self, cmd, env):
565
+ """
566
+ Discovered in pypa/distutils#15, some tools monkeypatch the compiler,
567
+ so the 'env' kwarg causes a TypeError. Detect this condition and
568
+ restore the legacy, unsafe behavior.
569
+ """
570
+ bag = type('Bag', (), {})()
571
+ try:
572
+ yield bag
573
+ except TypeError as exc:
574
+ if "unexpected keyword argument 'env'" not in str(exc):
575
+ raise
576
+ else:
577
+ return
578
+ warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
579
+ with mock.patch.dict('os.environ', env):
580
+ bag.value = super().spawn(cmd)
581
+
582
+ # -- Miscellaneous methods -----------------------------------------
583
+ # These are all used by the 'gen_lib_options() function, in
584
+ # ccompiler.py.
585
+
586
+ def library_dir_option(self, dir):
587
+ return "/LIBPATH:" + dir
588
+
589
+ def runtime_library_dir_option(self, dir):
590
+ raise DistutilsPlatformError(
591
+ "don't know how to set runtime library search path for MSVC"
592
+ )
593
+
594
+ def library_option(self, lib):
595
+ return self.library_filename(lib)
596
+
597
+ def find_library_file(self, dirs, lib, debug=False):
598
+ # Prefer a debugging library if found (and requested), but deal
599
+ # with it if we don't have one.
600
+ if debug:
601
+ try_names = [lib + "_d", lib]
602
+ else:
603
+ try_names = [lib]
604
+ for dir in dirs:
605
+ for name in try_names:
606
+ libfile = os.path.join(dir, self.library_filename(name))
607
+ if os.path.isfile(libfile):
608
+ return libfile
609
+ else:
610
+ # Oops, didn't find it in *any* of 'dirs'
611
+ return None
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/archive_util.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.archive_util
2
+
3
+ Utility functions for creating archive files (tarballs, zip files,
4
+ that sort of thing)."""
5
+
6
+ import os
7
+
8
+ try:
9
+ import zipfile
10
+ except ImportError:
11
+ zipfile = None
12
+
13
+
14
+ from ._log import log
15
+ from .dir_util import mkpath
16
+ from .errors import DistutilsExecError
17
+ from .spawn import spawn
18
+
19
+ try:
20
+ from pwd import getpwnam
21
+ except ImportError:
22
+ getpwnam = None
23
+
24
+ try:
25
+ from grp import getgrnam
26
+ except ImportError:
27
+ getgrnam = None
28
+
29
+
30
+ def _get_gid(name):
31
+ """Returns a gid, given a group name."""
32
+ if getgrnam is None or name is None:
33
+ return None
34
+ try:
35
+ result = getgrnam(name)
36
+ except KeyError:
37
+ result = None
38
+ if result is not None:
39
+ return result[2]
40
+ return None
41
+
42
+
43
+ def _get_uid(name):
44
+ """Returns an uid, given a user name."""
45
+ if getpwnam is None or name is None:
46
+ return None
47
+ try:
48
+ result = getpwnam(name)
49
+ except KeyError:
50
+ result = None
51
+ if result is not None:
52
+ return result[2]
53
+ return None
54
+
55
+
56
+ def make_tarball(
57
+ base_name,
58
+ base_dir,
59
+ compress="gzip",
60
+ verbose=False,
61
+ dry_run=False,
62
+ owner=None,
63
+ group=None,
64
+ ):
65
+ """Create a (possibly compressed) tar file from all the files under
66
+ 'base_dir'.
67
+
68
+ 'compress' must be "gzip" (the default), "bzip2", "xz", or None.
69
+
70
+ 'owner' and 'group' can be used to define an owner and a group for the
71
+ archive that is being built. If not provided, the current owner and group
72
+ will be used.
73
+
74
+ The output tar file will be named 'base_dir' + ".tar", possibly plus
75
+ the appropriate compression extension (".gz", ".bz2", ".xz" or ".Z").
76
+
77
+ Returns the output filename.
78
+ """
79
+ tar_compression = {
80
+ 'gzip': 'gz',
81
+ 'bzip2': 'bz2',
82
+ 'xz': 'xz',
83
+ None: '',
84
+ }
85
+ compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'}
86
+
87
+ # flags for compression program, each element of list will be an argument
88
+ if compress is not None and compress not in compress_ext.keys():
89
+ raise ValueError(
90
+ "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'"
91
+ )
92
+
93
+ archive_name = base_name + '.tar'
94
+ archive_name += compress_ext.get(compress, '')
95
+
96
+ mkpath(os.path.dirname(archive_name), dry_run=dry_run)
97
+
98
+ # creating the tarball
99
+ import tarfile # late import so Python build itself doesn't break
100
+
101
+ log.info('Creating tar archive')
102
+
103
+ uid = _get_uid(owner)
104
+ gid = _get_gid(group)
105
+
106
+ def _set_uid_gid(tarinfo):
107
+ if gid is not None:
108
+ tarinfo.gid = gid
109
+ tarinfo.gname = group
110
+ if uid is not None:
111
+ tarinfo.uid = uid
112
+ tarinfo.uname = owner
113
+ return tarinfo
114
+
115
+ if not dry_run:
116
+ tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}')
117
+ try:
118
+ tar.add(base_dir, filter=_set_uid_gid)
119
+ finally:
120
+ tar.close()
121
+
122
+ return archive_name
123
+
124
+
125
+ def make_zipfile(base_name, base_dir, verbose=False, dry_run=False): # noqa: C901
126
+ """Create a zip file from all the files under 'base_dir'.
127
+
128
+ The output zip file will be named 'base_name' + ".zip". Uses either the
129
+ "zipfile" Python module (if available) or the InfoZIP "zip" utility
130
+ (if installed and found on the default search path). If neither tool is
131
+ available, raises DistutilsExecError. Returns the name of the output zip
132
+ file.
133
+ """
134
+ zip_filename = base_name + ".zip"
135
+ mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
136
+
137
+ # If zipfile module is not available, try spawning an external
138
+ # 'zip' command.
139
+ if zipfile is None:
140
+ if verbose:
141
+ zipoptions = "-r"
142
+ else:
143
+ zipoptions = "-rq"
144
+
145
+ try:
146
+ spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
147
+ except DistutilsExecError:
148
+ # XXX really should distinguish between "couldn't find
149
+ # external 'zip' command" and "zip failed".
150
+ raise DistutilsExecError(
151
+ f"unable to create zip file '{zip_filename}': "
152
+ "could neither import the 'zipfile' module nor "
153
+ "find a standalone zip utility"
154
+ )
155
+
156
+ else:
157
+ log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
158
+
159
+ if not dry_run:
160
+ try:
161
+ zip = zipfile.ZipFile(
162
+ zip_filename, "w", compression=zipfile.ZIP_DEFLATED
163
+ )
164
+ except RuntimeError:
165
+ zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED)
166
+
167
+ with zip:
168
+ if base_dir != os.curdir:
169
+ path = os.path.normpath(os.path.join(base_dir, ''))
170
+ zip.write(path, path)
171
+ log.info("adding '%s'", path)
172
+ for dirpath, dirnames, filenames in os.walk(base_dir):
173
+ for name in dirnames:
174
+ path = os.path.normpath(os.path.join(dirpath, name, ''))
175
+ zip.write(path, path)
176
+ log.info("adding '%s'", path)
177
+ for name in filenames:
178
+ path = os.path.normpath(os.path.join(dirpath, name))
179
+ if os.path.isfile(path):
180
+ zip.write(path, path)
181
+ log.info("adding '%s'", path)
182
+
183
+ return zip_filename
184
+
185
+
186
+ ARCHIVE_FORMATS = {
187
+ 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
188
+ 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
189
+ 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"),
190
+ 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
191
+ 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
192
+ 'zip': (make_zipfile, [], "ZIP file"),
193
+ }
194
+
195
+
196
+ def check_archive_formats(formats):
197
+ """Returns the first format from the 'format' list that is unknown.
198
+
199
+ If all formats are known, returns None
200
+ """
201
+ for format in formats:
202
+ if format not in ARCHIVE_FORMATS:
203
+ return format
204
+ return None
205
+
206
+
207
+ def make_archive(
208
+ base_name,
209
+ format,
210
+ root_dir=None,
211
+ base_dir=None,
212
+ verbose=False,
213
+ dry_run=False,
214
+ owner=None,
215
+ group=None,
216
+ ):
217
+ """Create an archive file (eg. zip or tar).
218
+
219
+ 'base_name' is the name of the file to create, minus any format-specific
220
+ extension; 'format' is the archive format: one of "zip", "tar", "gztar",
221
+ "bztar", "xztar", or "ztar".
222
+
223
+ 'root_dir' is a directory that will be the root directory of the
224
+ archive; ie. we typically chdir into 'root_dir' before creating the
225
+ archive. 'base_dir' is the directory where we start archiving from;
226
+ ie. 'base_dir' will be the common prefix of all files and
227
+ directories in the archive. 'root_dir' and 'base_dir' both default
228
+ to the current directory. Returns the name of the archive file.
229
+
230
+ 'owner' and 'group' are used when creating a tar archive. By default,
231
+ uses the current owner and group.
232
+ """
233
+ save_cwd = os.getcwd()
234
+ if root_dir is not None:
235
+ log.debug("changing into '%s'", root_dir)
236
+ base_name = os.path.abspath(base_name)
237
+ if not dry_run:
238
+ os.chdir(root_dir)
239
+
240
+ if base_dir is None:
241
+ base_dir = os.curdir
242
+
243
+ kwargs = {'dry_run': dry_run}
244
+
245
+ try:
246
+ format_info = ARCHIVE_FORMATS[format]
247
+ except KeyError:
248
+ raise ValueError(f"unknown archive format '{format}'")
249
+
250
+ func = format_info[0]
251
+ kwargs.update(format_info[1])
252
+
253
+ if format != 'zip':
254
+ kwargs['owner'] = owner
255
+ kwargs['group'] = group
256
+
257
+ try:
258
+ filename = func(base_name, base_dir, **kwargs)
259
+ finally:
260
+ if root_dir is not None:
261
+ log.debug("changing back to '%s'", save_cwd)
262
+ os.chdir(save_cwd)
263
+
264
+ return filename
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/ccompiler.py ADDED
@@ -0,0 +1,1263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.ccompiler
2
+
3
+ Contains CCompiler, an abstract base class that defines the interface
4
+ for the Distutils compiler abstraction model."""
5
+
6
+ import os
7
+ import pathlib
8
+ import re
9
+ import sys
10
+ import types
11
+ import warnings
12
+
13
+ from more_itertools import always_iterable
14
+
15
+ from ._log import log
16
+ from ._modified import newer_group
17
+ from .dir_util import mkpath
18
+ from .errors import (
19
+ CompileError,
20
+ DistutilsModuleError,
21
+ DistutilsPlatformError,
22
+ LinkError,
23
+ UnknownFileError,
24
+ )
25
+ from .file_util import move_file
26
+ from .spawn import spawn
27
+ from .util import execute, is_mingw, split_quoted
28
+
29
+
30
+ class CCompiler:
31
+ """Abstract base class to define the interface that must be implemented
32
+ by real compiler classes. Also has some utility methods used by
33
+ several compiler classes.
34
+
35
+ The basic idea behind a compiler abstraction class is that each
36
+ instance can be used for all the compile/link steps in building a
37
+ single project. Thus, attributes common to all of those compile and
38
+ link steps -- include directories, macros to define, libraries to link
39
+ against, etc. -- are attributes of the compiler instance. To allow for
40
+ variability in how individual files are treated, most of those
41
+ attributes may be varied on a per-compilation or per-link basis.
42
+ """
43
+
44
+ # 'compiler_type' is a class attribute that identifies this class. It
45
+ # keeps code that wants to know what kind of compiler it's dealing with
46
+ # from having to import all possible compiler classes just to do an
47
+ # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
48
+ # should really, really be one of the keys of the 'compiler_class'
49
+ # dictionary (see below -- used by the 'new_compiler()' factory
50
+ # function) -- authors of new compiler interface classes are
51
+ # responsible for updating 'compiler_class'!
52
+ compiler_type = None
53
+
54
+ # XXX things not handled by this compiler abstraction model:
55
+ # * client can't provide additional options for a compiler,
56
+ # e.g. warning, optimization, debugging flags. Perhaps this
57
+ # should be the domain of concrete compiler abstraction classes
58
+ # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
59
+ # class should have methods for the common ones.
60
+ # * can't completely override the include or library searchg
61
+ # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
62
+ # I'm not sure how widely supported this is even by Unix
63
+ # compilers, much less on other platforms. And I'm even less
64
+ # sure how useful it is; maybe for cross-compiling, but
65
+ # support for that is a ways off. (And anyways, cross
66
+ # compilers probably have a dedicated binary with the
67
+ # right paths compiled in. I hope.)
68
+ # * can't do really freaky things with the library list/library
69
+ # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
70
+ # different versions of libfoo.a in different locations. I
71
+ # think this is useless without the ability to null out the
72
+ # library search path anyways.
73
+
74
+ # Subclasses that rely on the standard filename generation methods
75
+ # implemented below should override these; see the comment near
76
+ # those methods ('object_filenames()' et. al.) for details:
77
+ src_extensions = None # list of strings
78
+ obj_extension = None # string
79
+ static_lib_extension = None
80
+ shared_lib_extension = None # string
81
+ static_lib_format = None # format string
82
+ shared_lib_format = None # prob. same as static_lib_format
83
+ exe_extension = None # string
84
+
85
+ # Default language settings. language_map is used to detect a source
86
+ # file or Extension target language, checking source filenames.
87
+ # language_order is used to detect the language precedence, when deciding
88
+ # what language to use when mixing source types. For example, if some
89
+ # extension has two files with ".c" extension, and one with ".cpp", it
90
+ # is still linked as c++.
91
+ language_map = {
92
+ ".c": "c",
93
+ ".cc": "c++",
94
+ ".cpp": "c++",
95
+ ".cxx": "c++",
96
+ ".m": "objc",
97
+ }
98
+ language_order = ["c++", "objc", "c"]
99
+
100
+ include_dirs = []
101
+ """
102
+ include dirs specific to this compiler class
103
+ """
104
+
105
+ library_dirs = []
106
+ """
107
+ library dirs specific to this compiler class
108
+ """
109
+
110
+ def __init__(self, verbose=False, dry_run=False, force=False):
111
+ self.dry_run = dry_run
112
+ self.force = force
113
+ self.verbose = verbose
114
+
115
+ # 'output_dir': a common output directory for object, library,
116
+ # shared object, and shared library files
117
+ self.output_dir = None
118
+
119
+ # 'macros': a list of macro definitions (or undefinitions). A
120
+ # macro definition is a 2-tuple (name, value), where the value is
121
+ # either a string or None (no explicit value). A macro
122
+ # undefinition is a 1-tuple (name,).
123
+ self.macros = []
124
+
125
+ # 'include_dirs': a list of directories to search for include files
126
+ self.include_dirs = []
127
+
128
+ # 'libraries': a list of libraries to include in any link
129
+ # (library names, not filenames: eg. "foo" not "libfoo.a")
130
+ self.libraries = []
131
+
132
+ # 'library_dirs': a list of directories to search for libraries
133
+ self.library_dirs = []
134
+
135
+ # 'runtime_library_dirs': a list of directories to search for
136
+ # shared libraries/objects at runtime
137
+ self.runtime_library_dirs = []
138
+
139
+ # 'objects': a list of object files (or similar, such as explicitly
140
+ # named library files) to include on any link
141
+ self.objects = []
142
+
143
+ for key in self.executables.keys():
144
+ self.set_executable(key, self.executables[key])
145
+
146
+ def set_executables(self, **kwargs):
147
+ """Define the executables (and options for them) that will be run
148
+ to perform the various stages of compilation. The exact set of
149
+ executables that may be specified here depends on the compiler
150
+ class (via the 'executables' class attribute), but most will have:
151
+ compiler the C/C++ compiler
152
+ linker_so linker used to create shared objects and libraries
153
+ linker_exe linker used to create binary executables
154
+ archiver static library creator
155
+
156
+ On platforms with a command-line (Unix, DOS/Windows), each of these
157
+ is a string that will be split into executable name and (optional)
158
+ list of arguments. (Splitting the string is done similarly to how
159
+ Unix shells operate: words are delimited by spaces, but quotes and
160
+ backslashes can override this. See
161
+ 'distutils.util.split_quoted()'.)
162
+ """
163
+
164
+ # Note that some CCompiler implementation classes will define class
165
+ # attributes 'cpp', 'cc', etc. with hard-coded executable names;
166
+ # this is appropriate when a compiler class is for exactly one
167
+ # compiler/OS combination (eg. MSVCCompiler). Other compiler
168
+ # classes (UnixCCompiler, in particular) are driven by information
169
+ # discovered at run-time, since there are many different ways to do
170
+ # basically the same things with Unix C compilers.
171
+
172
+ for key in kwargs:
173
+ if key not in self.executables:
174
+ raise ValueError(
175
+ f"unknown executable '{key}' for class {self.__class__.__name__}"
176
+ )
177
+ self.set_executable(key, kwargs[key])
178
+
179
+ def set_executable(self, key, value):
180
+ if isinstance(value, str):
181
+ setattr(self, key, split_quoted(value))
182
+ else:
183
+ setattr(self, key, value)
184
+
185
+ def _find_macro(self, name):
186
+ i = 0
187
+ for defn in self.macros:
188
+ if defn[0] == name:
189
+ return i
190
+ i += 1
191
+ return None
192
+
193
+ def _check_macro_definitions(self, definitions):
194
+ """Ensure that every element of 'definitions' is valid."""
195
+ for defn in definitions:
196
+ self._check_macro_definition(*defn)
197
+
198
+ def _check_macro_definition(self, defn):
199
+ """
200
+ Raise a TypeError if defn is not valid.
201
+
202
+ A valid definition is either a (name, value) 2-tuple or a (name,) tuple.
203
+ """
204
+ if not isinstance(defn, tuple) or not self._is_valid_macro(*defn):
205
+ raise TypeError(
206
+ f"invalid macro definition '{defn}': "
207
+ "must be tuple (string,), (string, string), or (string, None)"
208
+ )
209
+
210
+ @staticmethod
211
+ def _is_valid_macro(name, value=None):
212
+ """
213
+ A valid macro is a ``name : str`` and a ``value : str | None``.
214
+ """
215
+ return isinstance(name, str) and isinstance(value, (str, types.NoneType))
216
+
217
+ # -- Bookkeeping methods -------------------------------------------
218
+
219
+ def define_macro(self, name, value=None):
220
+ """Define a preprocessor macro for all compilations driven by this
221
+ compiler object. The optional parameter 'value' should be a
222
+ string; if it is not supplied, then the macro will be defined
223
+ without an explicit value and the exact outcome depends on the
224
+ compiler used (XXX true? does ANSI say anything about this?)
225
+ """
226
+ # Delete from the list of macro definitions/undefinitions if
227
+ # already there (so that this one will take precedence).
228
+ i = self._find_macro(name)
229
+ if i is not None:
230
+ del self.macros[i]
231
+
232
+ self.macros.append((name, value))
233
+
234
+ def undefine_macro(self, name):
235
+ """Undefine a preprocessor macro for all compilations driven by
236
+ this compiler object. If the same macro is defined by
237
+ 'define_macro()' and undefined by 'undefine_macro()' the last call
238
+ takes precedence (including multiple redefinitions or
239
+ undefinitions). If the macro is redefined/undefined on a
240
+ per-compilation basis (ie. in the call to 'compile()'), then that
241
+ takes precedence.
242
+ """
243
+ # Delete from the list of macro definitions/undefinitions if
244
+ # already there (so that this one will take precedence).
245
+ i = self._find_macro(name)
246
+ if i is not None:
247
+ del self.macros[i]
248
+
249
+ undefn = (name,)
250
+ self.macros.append(undefn)
251
+
252
+ def add_include_dir(self, dir):
253
+ """Add 'dir' to the list of directories that will be searched for
254
+ header files. The compiler is instructed to search directories in
255
+ the order in which they are supplied by successive calls to
256
+ 'add_include_dir()'.
257
+ """
258
+ self.include_dirs.append(dir)
259
+
260
+ def set_include_dirs(self, dirs):
261
+ """Set the list of directories that will be searched to 'dirs' (a
262
+ list of strings). Overrides any preceding calls to
263
+ 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
264
+ to the list passed to 'set_include_dirs()'. This does not affect
265
+ any list of standard include directories that the compiler may
266
+ search by default.
267
+ """
268
+ self.include_dirs = dirs[:]
269
+
270
+ def add_library(self, libname):
271
+ """Add 'libname' to the list of libraries that will be included in
272
+ all links driven by this compiler object. Note that 'libname'
273
+ should *not* be the name of a file containing a library, but the
274
+ name of the library itself: the actual filename will be inferred by
275
+ the linker, the compiler, or the compiler class (depending on the
276
+ platform).
277
+
278
+ The linker will be instructed to link against libraries in the
279
+ order they were supplied to 'add_library()' and/or
280
+ 'set_libraries()'. It is perfectly valid to duplicate library
281
+ names; the linker will be instructed to link against libraries as
282
+ many times as they are mentioned.
283
+ """
284
+ self.libraries.append(libname)
285
+
286
+ def set_libraries(self, libnames):
287
+ """Set the list of libraries to be included in all links driven by
288
+ this compiler object to 'libnames' (a list of strings). This does
289
+ not affect any standard system libraries that the linker may
290
+ include by default.
291
+ """
292
+ self.libraries = libnames[:]
293
+
294
+ def add_library_dir(self, dir):
295
+ """Add 'dir' to the list of directories that will be searched for
296
+ libraries specified to 'add_library()' and 'set_libraries()'. The
297
+ linker will be instructed to search for libraries in the order they
298
+ are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
299
+ """
300
+ self.library_dirs.append(dir)
301
+
302
+ def set_library_dirs(self, dirs):
303
+ """Set the list of library search directories to 'dirs' (a list of
304
+ strings). This does not affect any standard library search path
305
+ that the linker may search by default.
306
+ """
307
+ self.library_dirs = dirs[:]
308
+
309
+ def add_runtime_library_dir(self, dir):
310
+ """Add 'dir' to the list of directories that will be searched for
311
+ shared libraries at runtime.
312
+ """
313
+ self.runtime_library_dirs.append(dir)
314
+
315
+ def set_runtime_library_dirs(self, dirs):
316
+ """Set the list of directories to search for shared libraries at
317
+ runtime to 'dirs' (a list of strings). This does not affect any
318
+ standard search path that the runtime linker may search by
319
+ default.
320
+ """
321
+ self.runtime_library_dirs = dirs[:]
322
+
323
+ def add_link_object(self, object):
324
+ """Add 'object' to the list of object files (or analogues, such as
325
+ explicitly named library files or the output of "resource
326
+ compilers") to be included in every link driven by this compiler
327
+ object.
328
+ """
329
+ self.objects.append(object)
330
+
331
+ def set_link_objects(self, objects):
332
+ """Set the list of object files (or analogues) to be included in
333
+ every link to 'objects'. This does not affect any standard object
334
+ files that the linker may include by default (such as system
335
+ libraries).
336
+ """
337
+ self.objects = objects[:]
338
+
339
+ # -- Private utility methods --------------------------------------
340
+ # (here for the convenience of subclasses)
341
+
342
+ # Helper method to prep compiler in subclass compile() methods
343
+
344
+ def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):
345
+ """Process arguments and decide which source files to compile."""
346
+ outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)
347
+
348
+ if extra is None:
349
+ extra = []
350
+
351
+ # Get the list of expected output (object) files
352
+ objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir)
353
+ assert len(objects) == len(sources)
354
+
355
+ pp_opts = gen_preprocess_options(macros, incdirs)
356
+
357
+ build = {}
358
+ for i in range(len(sources)):
359
+ src = sources[i]
360
+ obj = objects[i]
361
+ ext = os.path.splitext(src)[1]
362
+ self.mkpath(os.path.dirname(obj))
363
+ build[obj] = (src, ext)
364
+
365
+ return macros, objects, extra, pp_opts, build
366
+
367
+ def _get_cc_args(self, pp_opts, debug, before):
368
+ # works for unixccompiler, cygwinccompiler
369
+ cc_args = pp_opts + ['-c']
370
+ if debug:
371
+ cc_args[:0] = ['-g']
372
+ if before:
373
+ cc_args[:0] = before
374
+ return cc_args
375
+
376
+ def _fix_compile_args(self, output_dir, macros, include_dirs):
377
+ """Typecheck and fix-up some of the arguments to the 'compile()'
378
+ method, and return fixed-up values. Specifically: if 'output_dir'
379
+ is None, replaces it with 'self.output_dir'; ensures that 'macros'
380
+ is a list, and augments it with 'self.macros'; ensures that
381
+ 'include_dirs' is a list, and augments it with 'self.include_dirs'.
382
+ Guarantees that the returned values are of the correct type,
383
+ i.e. for 'output_dir' either string or None, and for 'macros' and
384
+ 'include_dirs' either list or None.
385
+ """
386
+ if output_dir is None:
387
+ output_dir = self.output_dir
388
+ elif not isinstance(output_dir, str):
389
+ raise TypeError("'output_dir' must be a string or None")
390
+
391
+ if macros is None:
392
+ macros = list(self.macros)
393
+ elif isinstance(macros, list):
394
+ macros = macros + (self.macros or [])
395
+ else:
396
+ raise TypeError("'macros' (if supplied) must be a list of tuples")
397
+
398
+ if include_dirs is None:
399
+ include_dirs = list(self.include_dirs)
400
+ elif isinstance(include_dirs, (list, tuple)):
401
+ include_dirs = list(include_dirs) + (self.include_dirs or [])
402
+ else:
403
+ raise TypeError("'include_dirs' (if supplied) must be a list of strings")
404
+
405
+ # add include dirs for class
406
+ include_dirs += self.__class__.include_dirs
407
+
408
+ return output_dir, macros, include_dirs
409
+
410
+ def _prep_compile(self, sources, output_dir, depends=None):
411
+ """Decide which source files must be recompiled.
412
+
413
+ Determine the list of object files corresponding to 'sources',
414
+ and figure out which ones really need to be recompiled.
415
+ Return a list of all object files and a dictionary telling
416
+ which source files can be skipped.
417
+ """
418
+ # Get the list of expected output (object) files
419
+ objects = self.object_filenames(sources, output_dir=output_dir)
420
+ assert len(objects) == len(sources)
421
+
422
+ # Return an empty dict for the "which source files can be skipped"
423
+ # return value to preserve API compatibility.
424
+ return objects, {}
425
+
426
+ def _fix_object_args(self, objects, output_dir):
427
+ """Typecheck and fix up some arguments supplied to various methods.
428
+ Specifically: ensure that 'objects' is a list; if output_dir is
429
+ None, replace with self.output_dir. Return fixed versions of
430
+ 'objects' and 'output_dir'.
431
+ """
432
+ if not isinstance(objects, (list, tuple)):
433
+ raise TypeError("'objects' must be a list or tuple of strings")
434
+ objects = list(objects)
435
+
436
+ if output_dir is None:
437
+ output_dir = self.output_dir
438
+ elif not isinstance(output_dir, str):
439
+ raise TypeError("'output_dir' must be a string or None")
440
+
441
+ return (objects, output_dir)
442
+
443
+ def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
444
+ """Typecheck and fix up some of the arguments supplied to the
445
+ 'link_*' methods. Specifically: ensure that all arguments are
446
+ lists, and augment them with their permanent versions
447
+ (eg. 'self.libraries' augments 'libraries'). Return a tuple with
448
+ fixed versions of all arguments.
449
+ """
450
+ if libraries is None:
451
+ libraries = list(self.libraries)
452
+ elif isinstance(libraries, (list, tuple)):
453
+ libraries = list(libraries) + (self.libraries or [])
454
+ else:
455
+ raise TypeError("'libraries' (if supplied) must be a list of strings")
456
+
457
+ if library_dirs is None:
458
+ library_dirs = list(self.library_dirs)
459
+ elif isinstance(library_dirs, (list, tuple)):
460
+ library_dirs = list(library_dirs) + (self.library_dirs or [])
461
+ else:
462
+ raise TypeError("'library_dirs' (if supplied) must be a list of strings")
463
+
464
+ # add library dirs for class
465
+ library_dirs += self.__class__.library_dirs
466
+
467
+ if runtime_library_dirs is None:
468
+ runtime_library_dirs = list(self.runtime_library_dirs)
469
+ elif isinstance(runtime_library_dirs, (list, tuple)):
470
+ runtime_library_dirs = list(runtime_library_dirs) + (
471
+ self.runtime_library_dirs or []
472
+ )
473
+ else:
474
+ raise TypeError(
475
+ "'runtime_library_dirs' (if supplied) must be a list of strings"
476
+ )
477
+
478
+ return (libraries, library_dirs, runtime_library_dirs)
479
+
480
+ def _need_link(self, objects, output_file):
481
+ """Return true if we need to relink the files listed in 'objects'
482
+ to recreate 'output_file'.
483
+ """
484
+ if self.force:
485
+ return True
486
+ else:
487
+ if self.dry_run:
488
+ newer = newer_group(objects, output_file, missing='newer')
489
+ else:
490
+ newer = newer_group(objects, output_file)
491
+ return newer
492
+
493
+ def detect_language(self, sources):
494
+ """Detect the language of a given file, or list of files. Uses
495
+ language_map, and language_order to do the job.
496
+ """
497
+ if not isinstance(sources, list):
498
+ sources = [sources]
499
+ lang = None
500
+ index = len(self.language_order)
501
+ for source in sources:
502
+ base, ext = os.path.splitext(source)
503
+ extlang = self.language_map.get(ext)
504
+ try:
505
+ extindex = self.language_order.index(extlang)
506
+ if extindex < index:
507
+ lang = extlang
508
+ index = extindex
509
+ except ValueError:
510
+ pass
511
+ return lang
512
+
513
+ # -- Worker methods ------------------------------------------------
514
+ # (must be implemented by subclasses)
515
+
516
+ def preprocess(
517
+ self,
518
+ source,
519
+ output_file=None,
520
+ macros=None,
521
+ include_dirs=None,
522
+ extra_preargs=None,
523
+ extra_postargs=None,
524
+ ):
525
+ """Preprocess a single C/C++ source file, named in 'source'.
526
+ Output will be written to file named 'output_file', or stdout if
527
+ 'output_file' not supplied. 'macros' is a list of macro
528
+ definitions as for 'compile()', which will augment the macros set
529
+ with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
530
+ list of directory names that will be added to the default list.
531
+
532
+ Raises PreprocessError on failure.
533
+ """
534
+ pass
535
+
536
+ def compile(
537
+ self,
538
+ sources,
539
+ output_dir=None,
540
+ macros=None,
541
+ include_dirs=None,
542
+ debug=False,
543
+ extra_preargs=None,
544
+ extra_postargs=None,
545
+ depends=None,
546
+ ):
547
+ """Compile one or more source files.
548
+
549
+ 'sources' must be a list of filenames, most likely C/C++
550
+ files, but in reality anything that can be handled by a
551
+ particular compiler and compiler class (eg. MSVCCompiler can
552
+ handle resource files in 'sources'). Return a list of object
553
+ filenames, one per source filename in 'sources'. Depending on
554
+ the implementation, not all source files will necessarily be
555
+ compiled, but all corresponding object filenames will be
556
+ returned.
557
+
558
+ If 'output_dir' is given, object files will be put under it, while
559
+ retaining their original path component. That is, "foo/bar.c"
560
+ normally compiles to "foo/bar.o" (for a Unix implementation); if
561
+ 'output_dir' is "build", then it would compile to
562
+ "build/foo/bar.o".
563
+
564
+ 'macros', if given, must be a list of macro definitions. A macro
565
+ definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
566
+ The former defines a macro; if the value is None, the macro is
567
+ defined without an explicit value. The 1-tuple case undefines a
568
+ macro. Later definitions/redefinitions/ undefinitions take
569
+ precedence.
570
+
571
+ 'include_dirs', if given, must be a list of strings, the
572
+ directories to add to the default include file search path for this
573
+ compilation only.
574
+
575
+ 'debug' is a boolean; if true, the compiler will be instructed to
576
+ output debug symbols in (or alongside) the object file(s).
577
+
578
+ 'extra_preargs' and 'extra_postargs' are implementation- dependent.
579
+ On platforms that have the notion of a command-line (e.g. Unix,
580
+ DOS/Windows), they are most likely lists of strings: extra
581
+ command-line arguments to prepend/append to the compiler command
582
+ line. On other platforms, consult the implementation class
583
+ documentation. In any event, they are intended as an escape hatch
584
+ for those occasions when the abstract compiler framework doesn't
585
+ cut the mustard.
586
+
587
+ 'depends', if given, is a list of filenames that all targets
588
+ depend on. If a source file is older than any file in
589
+ depends, then the source file will be recompiled. This
590
+ supports dependency tracking, but only at a coarse
591
+ granularity.
592
+
593
+ Raises CompileError on failure.
594
+ """
595
+ # A concrete compiler class can either override this method
596
+ # entirely or implement _compile().
597
+ macros, objects, extra_postargs, pp_opts, build = self._setup_compile(
598
+ output_dir, macros, include_dirs, sources, depends, extra_postargs
599
+ )
600
+ cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
601
+
602
+ for obj in objects:
603
+ try:
604
+ src, ext = build[obj]
605
+ except KeyError:
606
+ continue
607
+ self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
608
+
609
+ # Return *all* object filenames, not just the ones we just built.
610
+ return objects
611
+
612
+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
613
+ """Compile 'src' to product 'obj'."""
614
+ # A concrete compiler class that does not override compile()
615
+ # should implement _compile().
616
+ pass
617
+
618
+ def create_static_lib(
619
+ self, objects, output_libname, output_dir=None, debug=False, target_lang=None
620
+ ):
621
+ """Link a bunch of stuff together to create a static library file.
622
+ The "bunch of stuff" consists of the list of object files supplied
623
+ as 'objects', the extra object files supplied to
624
+ 'add_link_object()' and/or 'set_link_objects()', the libraries
625
+ supplied to 'add_library()' and/or 'set_libraries()', and the
626
+ libraries supplied as 'libraries' (if any).
627
+
628
+ 'output_libname' should be a library name, not a filename; the
629
+ filename will be inferred from the library name. 'output_dir' is
630
+ the directory where the library file will be put.
631
+
632
+ 'debug' is a boolean; if true, debugging information will be
633
+ included in the library (note that on most platforms, it is the
634
+ compile step where this matters: the 'debug' flag is included here
635
+ just for consistency).
636
+
637
+ 'target_lang' is the target language for which the given objects
638
+ are being compiled. This allows specific linkage time treatment of
639
+ certain languages.
640
+
641
+ Raises LibError on failure.
642
+ """
643
+ pass
644
+
645
+ # values for target_desc parameter in link()
646
+ SHARED_OBJECT = "shared_object"
647
+ SHARED_LIBRARY = "shared_library"
648
+ EXECUTABLE = "executable"
649
+
650
+ def link(
651
+ self,
652
+ target_desc,
653
+ objects,
654
+ output_filename,
655
+ output_dir=None,
656
+ libraries=None,
657
+ library_dirs=None,
658
+ runtime_library_dirs=None,
659
+ export_symbols=None,
660
+ debug=False,
661
+ extra_preargs=None,
662
+ extra_postargs=None,
663
+ build_temp=None,
664
+ target_lang=None,
665
+ ):
666
+ """Link a bunch of stuff together to create an executable or
667
+ shared library file.
668
+
669
+ The "bunch of stuff" consists of the list of object files supplied
670
+ as 'objects'. 'output_filename' should be a filename. If
671
+ 'output_dir' is supplied, 'output_filename' is relative to it
672
+ (i.e. 'output_filename' can provide directory components if
673
+ needed).
674
+
675
+ 'libraries' is a list of libraries to link against. These are
676
+ library names, not filenames, since they're translated into
677
+ filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
678
+ on Unix and "foo.lib" on DOS/Windows). However, they can include a
679
+ directory component, which means the linker will look in that
680
+ specific directory rather than searching all the normal locations.
681
+
682
+ 'library_dirs', if supplied, should be a list of directories to
683
+ search for libraries that were specified as bare library names
684
+ (ie. no directory component). These are on top of the system
685
+ default and those supplied to 'add_library_dir()' and/or
686
+ 'set_library_dirs()'. 'runtime_library_dirs' is a list of
687
+ directories that will be embedded into the shared library and used
688
+ to search for other shared libraries that *it* depends on at
689
+ run-time. (This may only be relevant on Unix.)
690
+
691
+ 'export_symbols' is a list of symbols that the shared library will
692
+ export. (This appears to be relevant only on Windows.)
693
+
694
+ 'debug' is as for 'compile()' and 'create_static_lib()', with the
695
+ slight distinction that it actually matters on most platforms (as
696
+ opposed to 'create_static_lib()', which includes a 'debug' flag
697
+ mostly for form's sake).
698
+
699
+ 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
700
+ of course that they supply command-line arguments for the
701
+ particular linker being used).
702
+
703
+ 'target_lang' is the target language for which the given objects
704
+ are being compiled. This allows specific linkage time treatment of
705
+ certain languages.
706
+
707
+ Raises LinkError on failure.
708
+ """
709
+ raise NotImplementedError
710
+
711
+ # Old 'link_*()' methods, rewritten to use the new 'link()' method.
712
+
713
+ def link_shared_lib(
714
+ self,
715
+ objects,
716
+ output_libname,
717
+ output_dir=None,
718
+ libraries=None,
719
+ library_dirs=None,
720
+ runtime_library_dirs=None,
721
+ export_symbols=None,
722
+ debug=False,
723
+ extra_preargs=None,
724
+ extra_postargs=None,
725
+ build_temp=None,
726
+ target_lang=None,
727
+ ):
728
+ self.link(
729
+ CCompiler.SHARED_LIBRARY,
730
+ objects,
731
+ self.library_filename(output_libname, lib_type='shared'),
732
+ output_dir,
733
+ libraries,
734
+ library_dirs,
735
+ runtime_library_dirs,
736
+ export_symbols,
737
+ debug,
738
+ extra_preargs,
739
+ extra_postargs,
740
+ build_temp,
741
+ target_lang,
742
+ )
743
+
744
+ def link_shared_object(
745
+ self,
746
+ objects,
747
+ output_filename,
748
+ output_dir=None,
749
+ libraries=None,
750
+ library_dirs=None,
751
+ runtime_library_dirs=None,
752
+ export_symbols=None,
753
+ debug=False,
754
+ extra_preargs=None,
755
+ extra_postargs=None,
756
+ build_temp=None,
757
+ target_lang=None,
758
+ ):
759
+ self.link(
760
+ CCompiler.SHARED_OBJECT,
761
+ objects,
762
+ output_filename,
763
+ output_dir,
764
+ libraries,
765
+ library_dirs,
766
+ runtime_library_dirs,
767
+ export_symbols,
768
+ debug,
769
+ extra_preargs,
770
+ extra_postargs,
771
+ build_temp,
772
+ target_lang,
773
+ )
774
+
775
+ def link_executable(
776
+ self,
777
+ objects,
778
+ output_progname,
779
+ output_dir=None,
780
+ libraries=None,
781
+ library_dirs=None,
782
+ runtime_library_dirs=None,
783
+ debug=False,
784
+ extra_preargs=None,
785
+ extra_postargs=None,
786
+ target_lang=None,
787
+ ):
788
+ self.link(
789
+ CCompiler.EXECUTABLE,
790
+ objects,
791
+ self.executable_filename(output_progname),
792
+ output_dir,
793
+ libraries,
794
+ library_dirs,
795
+ runtime_library_dirs,
796
+ None,
797
+ debug,
798
+ extra_preargs,
799
+ extra_postargs,
800
+ None,
801
+ target_lang,
802
+ )
803
+
804
+ # -- Miscellaneous methods -----------------------------------------
805
+ # These are all used by the 'gen_lib_options() function; there is
806
+ # no appropriate default implementation so subclasses should
807
+ # implement all of these.
808
+
809
+ def library_dir_option(self, dir):
810
+ """Return the compiler option to add 'dir' to the list of
811
+ directories searched for libraries.
812
+ """
813
+ raise NotImplementedError
814
+
815
+ def runtime_library_dir_option(self, dir):
816
+ """Return the compiler option to add 'dir' to the list of
817
+ directories searched for runtime libraries.
818
+ """
819
+ raise NotImplementedError
820
+
821
+ def library_option(self, lib):
822
+ """Return the compiler option to add 'lib' to the list of libraries
823
+ linked into the shared library or executable.
824
+ """
825
+ raise NotImplementedError
826
+
827
+ def has_function( # noqa: C901
828
+ self,
829
+ funcname,
830
+ includes=None,
831
+ include_dirs=None,
832
+ libraries=None,
833
+ library_dirs=None,
834
+ ):
835
+ """Return a boolean indicating whether funcname is provided as
836
+ a symbol on the current platform. The optional arguments can
837
+ be used to augment the compilation environment.
838
+
839
+ The libraries argument is a list of flags to be passed to the
840
+ linker to make additional symbol definitions available for
841
+ linking.
842
+
843
+ The includes and include_dirs arguments are deprecated.
844
+ Usually, supplying include files with function declarations
845
+ will cause function detection to fail even in cases where the
846
+ symbol is available for linking.
847
+
848
+ """
849
+ # this can't be included at module scope because it tries to
850
+ # import math which might not be available at that point - maybe
851
+ # the necessary logic should just be inlined?
852
+ import tempfile
853
+
854
+ if includes is None:
855
+ includes = []
856
+ else:
857
+ warnings.warn("includes is deprecated", DeprecationWarning)
858
+ if include_dirs is None:
859
+ include_dirs = []
860
+ else:
861
+ warnings.warn("include_dirs is deprecated", DeprecationWarning)
862
+ if libraries is None:
863
+ libraries = []
864
+ if library_dirs is None:
865
+ library_dirs = []
866
+ fd, fname = tempfile.mkstemp(".c", funcname, text=True)
867
+ with os.fdopen(fd, "w", encoding='utf-8') as f:
868
+ for incl in includes:
869
+ f.write(f"""#include "{incl}"\n""")
870
+ if not includes:
871
+ # Use "char func(void);" as the prototype to follow
872
+ # what autoconf does. This prototype does not match
873
+ # any well-known function the compiler might recognize
874
+ # as a builtin, so this ends up as a true link test.
875
+ # Without a fake prototype, the test would need to
876
+ # know the exact argument types, and the has_function
877
+ # interface does not provide that level of information.
878
+ f.write(
879
+ f"""\
880
+ #ifdef __cplusplus
881
+ extern "C"
882
+ #endif
883
+ char {funcname}(void);
884
+ """
885
+ )
886
+ f.write(
887
+ f"""\
888
+ int main (int argc, char **argv) {{
889
+ {funcname}();
890
+ return 0;
891
+ }}
892
+ """
893
+ )
894
+
895
+ try:
896
+ objects = self.compile([fname], include_dirs=include_dirs)
897
+ except CompileError:
898
+ return False
899
+ finally:
900
+ os.remove(fname)
901
+
902
+ try:
903
+ self.link_executable(
904
+ objects, "a.out", libraries=libraries, library_dirs=library_dirs
905
+ )
906
+ except (LinkError, TypeError):
907
+ return False
908
+ else:
909
+ os.remove(
910
+ self.executable_filename("a.out", output_dir=self.output_dir or '')
911
+ )
912
+ finally:
913
+ for fn in objects:
914
+ os.remove(fn)
915
+ return True
916
+
917
+ def find_library_file(self, dirs, lib, debug=False):
918
+ """Search the specified list of directories for a static or shared
919
+ library file 'lib' and return the full path to that file. If
920
+ 'debug' true, look for a debugging version (if that makes sense on
921
+ the current platform). Return None if 'lib' wasn't found in any of
922
+ the specified directories.
923
+ """
924
+ raise NotImplementedError
925
+
926
+ # -- Filename generation methods -----------------------------------
927
+
928
+ # The default implementation of the filename generating methods are
929
+ # prejudiced towards the Unix/DOS/Windows view of the world:
930
+ # * object files are named by replacing the source file extension
931
+ # (eg. .c/.cpp -> .o/.obj)
932
+ # * library files (shared or static) are named by plugging the
933
+ # library name and extension into a format string, eg.
934
+ # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
935
+ # * executables are named by appending an extension (possibly
936
+ # empty) to the program name: eg. progname + ".exe" for
937
+ # Windows
938
+ #
939
+ # To reduce redundant code, these methods expect to find
940
+ # several attributes in the current object (presumably defined
941
+ # as class attributes):
942
+ # * src_extensions -
943
+ # list of C/C++ source file extensions, eg. ['.c', '.cpp']
944
+ # * obj_extension -
945
+ # object file extension, eg. '.o' or '.obj'
946
+ # * static_lib_extension -
947
+ # extension for static library files, eg. '.a' or '.lib'
948
+ # * shared_lib_extension -
949
+ # extension for shared library/object files, eg. '.so', '.dll'
950
+ # * static_lib_format -
951
+ # format string for generating static library filenames,
952
+ # eg. 'lib%s.%s' or '%s.%s'
953
+ # * shared_lib_format
954
+ # format string for generating shared library filenames
955
+ # (probably same as static_lib_format, since the extension
956
+ # is one of the intended parameters to the format string)
957
+ # * exe_extension -
958
+ # extension for executable files, eg. '' or '.exe'
959
+
960
+ def object_filenames(self, source_filenames, strip_dir=False, output_dir=''):
961
+ if output_dir is None:
962
+ output_dir = ''
963
+ return list(
964
+ self._make_out_path(output_dir, strip_dir, src_name)
965
+ for src_name in source_filenames
966
+ )
967
+
968
+ @property
969
+ def out_extensions(self):
970
+ return dict.fromkeys(self.src_extensions, self.obj_extension)
971
+
972
+ def _make_out_path(self, output_dir, strip_dir, src_name):
973
+ return self._make_out_path_exts(
974
+ output_dir, strip_dir, src_name, self.out_extensions
975
+ )
976
+
977
+ @classmethod
978
+ def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions):
979
+ r"""
980
+ >>> exts = {'.c': '.o'}
981
+ >>> CCompiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/')
982
+ './foo/bar.o'
983
+ >>> CCompiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/')
984
+ './bar.o'
985
+ """
986
+ src = pathlib.PurePath(src_name)
987
+ # Ensure base is relative to honor output_dir (python/cpython#37775).
988
+ base = cls._make_relative(src)
989
+ try:
990
+ new_ext = extensions[src.suffix]
991
+ except LookupError:
992
+ raise UnknownFileError(f"unknown file type '{src.suffix}' (from '{src}')")
993
+ if strip_dir:
994
+ base = pathlib.PurePath(base.name)
995
+ return os.path.join(output_dir, base.with_suffix(new_ext))
996
+
997
+ @staticmethod
998
+ def _make_relative(base: pathlib.Path):
999
+ return base.relative_to(base.anchor)
1000
+
1001
+ def shared_object_filename(self, basename, strip_dir=False, output_dir=''):
1002
+ assert output_dir is not None
1003
+ if strip_dir:
1004
+ basename = os.path.basename(basename)
1005
+ return os.path.join(output_dir, basename + self.shared_lib_extension)
1006
+
1007
+ def executable_filename(self, basename, strip_dir=False, output_dir=''):
1008
+ assert output_dir is not None
1009
+ if strip_dir:
1010
+ basename = os.path.basename(basename)
1011
+ return os.path.join(output_dir, basename + (self.exe_extension or ''))
1012
+
1013
+ def library_filename(
1014
+ self,
1015
+ libname,
1016
+ lib_type='static',
1017
+ strip_dir=False,
1018
+ output_dir='', # or 'shared'
1019
+ ):
1020
+ assert output_dir is not None
1021
+ expected = '"static", "shared", "dylib", "xcode_stub"'
1022
+ if lib_type not in eval(expected):
1023
+ raise ValueError(f"'lib_type' must be {expected}")
1024
+ fmt = getattr(self, lib_type + "_lib_format")
1025
+ ext = getattr(self, lib_type + "_lib_extension")
1026
+
1027
+ dir, base = os.path.split(libname)
1028
+ filename = fmt % (base, ext)
1029
+ if strip_dir:
1030
+ dir = ''
1031
+
1032
+ return os.path.join(output_dir, dir, filename)
1033
+
1034
+ # -- Utility methods -----------------------------------------------
1035
+
1036
+ def announce(self, msg, level=1):
1037
+ log.debug(msg)
1038
+
1039
+ def debug_print(self, msg):
1040
+ from distutils.debug import DEBUG
1041
+
1042
+ if DEBUG:
1043
+ print(msg)
1044
+
1045
+ def warn(self, msg):
1046
+ sys.stderr.write(f"warning: {msg}\n")
1047
+
1048
+ def execute(self, func, args, msg=None, level=1):
1049
+ execute(func, args, msg, self.dry_run)
1050
+
1051
+ def spawn(self, cmd, **kwargs):
1052
+ spawn(cmd, dry_run=self.dry_run, **kwargs)
1053
+
1054
+ def move_file(self, src, dst):
1055
+ return move_file(src, dst, dry_run=self.dry_run)
1056
+
1057
+ def mkpath(self, name, mode=0o777):
1058
+ mkpath(name, mode, dry_run=self.dry_run)
1059
+
1060
+
1061
+ # Map a sys.platform/os.name ('posix', 'nt') to the default compiler
1062
+ # type for that platform. Keys are interpreted as re match
1063
+ # patterns. Order is important; platform mappings are preferred over
1064
+ # OS names.
1065
+ _default_compilers = (
1066
+ # Platform string mappings
1067
+ # on a cygwin built python we can use gcc like an ordinary UNIXish
1068
+ # compiler
1069
+ ('cygwin.*', 'unix'),
1070
+ ('zos', 'zos'),
1071
+ # OS name mappings
1072
+ ('posix', 'unix'),
1073
+ ('nt', 'msvc'),
1074
+ )
1075
+
1076
+
1077
+ def get_default_compiler(osname=None, platform=None):
1078
+ """Determine the default compiler to use for the given platform.
1079
+
1080
+ osname should be one of the standard Python OS names (i.e. the
1081
+ ones returned by os.name) and platform the common value
1082
+ returned by sys.platform for the platform in question.
1083
+
1084
+ The default values are os.name and sys.platform in case the
1085
+ parameters are not given.
1086
+ """
1087
+ if osname is None:
1088
+ osname = os.name
1089
+ if platform is None:
1090
+ platform = sys.platform
1091
+ # Mingw is a special case where sys.platform is 'win32' but we
1092
+ # want to use the 'mingw32' compiler, so check it first
1093
+ if is_mingw():
1094
+ return 'mingw32'
1095
+ for pattern, compiler in _default_compilers:
1096
+ if (
1097
+ re.match(pattern, platform) is not None
1098
+ or re.match(pattern, osname) is not None
1099
+ ):
1100
+ return compiler
1101
+ # Default to Unix compiler
1102
+ return 'unix'
1103
+
1104
+
1105
+ # Map compiler types to (module_name, class_name) pairs -- ie. where to
1106
+ # find the code that implements an interface to this compiler. (The module
1107
+ # is assumed to be in the 'distutils' package.)
1108
+ compiler_class = {
1109
+ 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"),
1110
+ 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"),
1111
+ 'cygwin': (
1112
+ 'cygwinccompiler',
1113
+ 'CygwinCCompiler',
1114
+ "Cygwin port of GNU C Compiler for Win32",
1115
+ ),
1116
+ 'mingw32': (
1117
+ 'cygwinccompiler',
1118
+ 'Mingw32CCompiler',
1119
+ "Mingw32 port of GNU C Compiler for Win32",
1120
+ ),
1121
+ 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"),
1122
+ 'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'),
1123
+ }
1124
+
1125
+
1126
+ def show_compilers():
1127
+ """Print list of available compilers (used by the "--help-compiler"
1128
+ options to "build", "build_ext", "build_clib").
1129
+ """
1130
+ # XXX this "knows" that the compiler option it's describing is
1131
+ # "--compiler", which just happens to be the case for the three
1132
+ # commands that use it.
1133
+ from distutils.fancy_getopt import FancyGetopt
1134
+
1135
+ compilers = sorted(
1136
+ ("compiler=" + compiler, None, compiler_class[compiler][2])
1137
+ for compiler in compiler_class.keys()
1138
+ )
1139
+ pretty_printer = FancyGetopt(compilers)
1140
+ pretty_printer.print_help("List of available compilers:")
1141
+
1142
+
1143
+ def new_compiler(plat=None, compiler=None, verbose=False, dry_run=False, force=False):
1144
+ """Generate an instance of some CCompiler subclass for the supplied
1145
+ platform/compiler combination. 'plat' defaults to 'os.name'
1146
+ (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
1147
+ for that platform. Currently only 'posix' and 'nt' are supported, and
1148
+ the default compilers are "traditional Unix interface" (UnixCCompiler
1149
+ class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
1150
+ possible to ask for a Unix compiler object under Windows, and a
1151
+ Microsoft compiler object under Unix -- if you supply a value for
1152
+ 'compiler', 'plat' is ignored.
1153
+ """
1154
+ if plat is None:
1155
+ plat = os.name
1156
+
1157
+ try:
1158
+ if compiler is None:
1159
+ compiler = get_default_compiler(plat)
1160
+
1161
+ (module_name, class_name, long_description) = compiler_class[compiler]
1162
+ except KeyError:
1163
+ msg = f"don't know how to compile C/C++ code on platform '{plat}'"
1164
+ if compiler is not None:
1165
+ msg = msg + f" with '{compiler}' compiler"
1166
+ raise DistutilsPlatformError(msg)
1167
+
1168
+ try:
1169
+ module_name = "distutils." + module_name
1170
+ __import__(module_name)
1171
+ module = sys.modules[module_name]
1172
+ klass = vars(module)[class_name]
1173
+ except ImportError:
1174
+ raise DistutilsModuleError(
1175
+ f"can't compile C/C++ code: unable to load module '{module_name}'"
1176
+ )
1177
+ except KeyError:
1178
+ raise DistutilsModuleError(
1179
+ f"can't compile C/C++ code: unable to find class '{class_name}' "
1180
+ f"in module '{module_name}'"
1181
+ )
1182
+
1183
+ # XXX The None is necessary to preserve backwards compatibility
1184
+ # with classes that expect verbose to be the first positional
1185
+ # argument.
1186
+ return klass(None, dry_run, force)
1187
+
1188
+
1189
+ def gen_preprocess_options(macros, include_dirs):
1190
+ """Generate C pre-processor options (-D, -U, -I) as used by at least
1191
+ two types of compilers: the typical Unix compiler and Visual C++.
1192
+ 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
1193
+ means undefine (-U) macro 'name', and (name,value) means define (-D)
1194
+ macro 'name' to 'value'. 'include_dirs' is just a list of directory
1195
+ names to be added to the header file search path (-I). Returns a list
1196
+ of command-line options suitable for either Unix compilers or Visual
1197
+ C++.
1198
+ """
1199
+ # XXX it would be nice (mainly aesthetic, and so we don't generate
1200
+ # stupid-looking command lines) to go over 'macros' and eliminate
1201
+ # redundant definitions/undefinitions (ie. ensure that only the
1202
+ # latest mention of a particular macro winds up on the command
1203
+ # line). I don't think it's essential, though, since most (all?)
1204
+ # Unix C compilers only pay attention to the latest -D or -U
1205
+ # mention of a macro on their command line. Similar situation for
1206
+ # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
1207
+ # redundancies like this should probably be the province of
1208
+ # CCompiler, since the data structures used are inherited from it
1209
+ # and therefore common to all CCompiler classes.
1210
+ pp_opts = []
1211
+ for macro in macros:
1212
+ if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
1213
+ raise TypeError(
1214
+ f"bad macro definition '{macro}': "
1215
+ "each element of 'macros' list must be a 1- or 2-tuple"
1216
+ )
1217
+
1218
+ if len(macro) == 1: # undefine this macro
1219
+ pp_opts.append(f"-U{macro[0]}")
1220
+ elif len(macro) == 2:
1221
+ if macro[1] is None: # define with no explicit value
1222
+ pp_opts.append(f"-D{macro[0]}")
1223
+ else:
1224
+ # XXX *don't* need to be clever about quoting the
1225
+ # macro value here, because we're going to avoid the
1226
+ # shell at all costs when we spawn the command!
1227
+ pp_opts.append("-D{}={}".format(*macro))
1228
+
1229
+ pp_opts.extend(f"-I{dir}" for dir in include_dirs)
1230
+ return pp_opts
1231
+
1232
+
1233
+ def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
1234
+ """Generate linker options for searching library directories and
1235
+ linking with specific libraries. 'libraries' and 'library_dirs' are,
1236
+ respectively, lists of library names (not filenames!) and search
1237
+ directories. Returns a list of command-line options suitable for use
1238
+ with some compiler (depending on the two format strings passed in).
1239
+ """
1240
+ lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs]
1241
+
1242
+ for dir in runtime_library_dirs:
1243
+ lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir)))
1244
+
1245
+ # XXX it's important that we *not* remove redundant library mentions!
1246
+ # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
1247
+ # resolve all symbols. I just hope we never have to say "-lfoo obj.o
1248
+ # -lbar" to get things to work -- that's certainly a possibility, but a
1249
+ # pretty nasty way to arrange your C code.
1250
+
1251
+ for lib in libraries:
1252
+ (lib_dir, lib_name) = os.path.split(lib)
1253
+ if lib_dir:
1254
+ lib_file = compiler.find_library_file([lib_dir], lib_name)
1255
+ if lib_file:
1256
+ lib_opts.append(lib_file)
1257
+ else:
1258
+ compiler.warn(
1259
+ f"no library file corresponding to '{lib}' found (skipping)"
1260
+ )
1261
+ else:
1262
+ lib_opts.append(compiler.library_option(lib))
1263
+ return lib_opts
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/cmd.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 collections.abc import Callable
14
+ from typing import Any, ClassVar, TypeVar, overload
15
+
16
+ from . import _modified, archive_util, dir_util, file_util, util
17
+ from ._log import log
18
+ from .errors import DistutilsOptionError
19
+
20
+ _CommandT = TypeVar("_CommandT", bound="Command")
21
+
22
+
23
+ class Command:
24
+ """Abstract base class for defining command classes, the "worker bees"
25
+ of the Distutils. A useful analogy for command classes is to think of
26
+ them as subroutines with local variables called "options". The options
27
+ are "declared" in 'initialize_options()' and "defined" (given their
28
+ final values, aka "finalized") in 'finalize_options()', both of which
29
+ must be defined by every command class. The distinction between the
30
+ two is necessary because option values might come from the outside
31
+ world (command line, config file, ...), and any options dependent on
32
+ other options must be computed *after* these outside influences have
33
+ been processed -- hence 'finalize_options()'. The "body" of the
34
+ subroutine, where it does all its work based on the values of its
35
+ options, is the 'run()' method, which must also be implemented by every
36
+ command class.
37
+ """
38
+
39
+ # 'sub_commands' formalizes the notion of a "family" of commands,
40
+ # eg. "install" as the parent with sub-commands "install_lib",
41
+ # "install_headers", etc. The parent of a family of commands
42
+ # defines 'sub_commands' as a class attribute; it's a list of
43
+ # (command_name : string, predicate : unbound_method | string | None)
44
+ # tuples, where 'predicate' is a method of the parent command that
45
+ # determines whether the corresponding command is applicable in the
46
+ # current situation. (Eg. we "install_headers" is only applicable if
47
+ # we have any C header files to install.) If 'predicate' is None,
48
+ # that command is always applicable.
49
+ #
50
+ # 'sub_commands' is usually defined at the *end* of a class, because
51
+ # predicates can be unbound methods, so they must already have been
52
+ # defined. The canonical example is the "install" command.
53
+ sub_commands: ClassVar[ # Any to work around variance issues
54
+ list[tuple[str, Callable[[Any], bool] | None]]
55
+ ] = []
56
+
57
+ user_options: ClassVar[
58
+ # Specifying both because list is invariant. Avoids mypy override assignment issues
59
+ list[tuple[str, str, str]] | list[tuple[str, str | None, str]]
60
+ ] = []
61
+
62
+ # -- Creation/initialization methods -------------------------------
63
+
64
+ def __init__(self, dist):
65
+ """Create and initialize a new Command object. Most importantly,
66
+ invokes the 'initialize_options()' method, which is the real
67
+ initializer and depends on the actual command being
68
+ instantiated.
69
+ """
70
+ # late import because of mutual dependence between these classes
71
+ from distutils.dist import Distribution
72
+
73
+ if not isinstance(dist, Distribution):
74
+ raise TypeError("dist must be a Distribution instance")
75
+ if self.__class__ is Command:
76
+ raise RuntimeError("Command is an abstract class")
77
+
78
+ self.distribution = dist
79
+ self.initialize_options()
80
+
81
+ # Per-command versions of the global flags, so that the user can
82
+ # customize Distutils' behaviour command-by-command and let some
83
+ # commands fall back on the Distribution's behaviour. None means
84
+ # "not defined, check self.distribution's copy", while 0 or 1 mean
85
+ # false and true (duh). Note that this means figuring out the real
86
+ # value of each flag is a touch complicated -- hence "self._dry_run"
87
+ # will be handled by __getattr__, below.
88
+ # XXX This needs to be fixed.
89
+ self._dry_run = None
90
+
91
+ # verbose is largely ignored, but needs to be set for
92
+ # backwards compatibility (I think)?
93
+ self.verbose = dist.verbose
94
+
95
+ # Some commands define a 'self.force' option to ignore file
96
+ # timestamps, but methods defined *here* assume that
97
+ # 'self.force' exists for all commands. So define it here
98
+ # just to be safe.
99
+ self.force = None
100
+
101
+ # The 'help' flag is just used for command-line parsing, so
102
+ # none of that complicated bureaucracy is needed.
103
+ self.help = False
104
+
105
+ # 'finalized' records whether or not 'finalize_options()' has been
106
+ # called. 'finalize_options()' itself should not pay attention to
107
+ # this flag: it is the business of 'ensure_finalized()', which
108
+ # always calls 'finalize_options()', to respect/update it.
109
+ self.finalized = False
110
+
111
+ # XXX A more explicit way to customize dry_run would be better.
112
+ def __getattr__(self, attr):
113
+ if attr == 'dry_run':
114
+ myval = getattr(self, "_" + attr)
115
+ if myval is None:
116
+ return getattr(self.distribution, attr)
117
+ else:
118
+ return myval
119
+ else:
120
+ raise AttributeError(attr)
121
+
122
+ def ensure_finalized(self):
123
+ if not self.finalized:
124
+ self.finalize_options()
125
+ self.finalized = True
126
+
127
+ # Subclasses must define:
128
+ # initialize_options()
129
+ # provide default values for all options; may be customized by
130
+ # setup script, by options from config file(s), or by command-line
131
+ # options
132
+ # finalize_options()
133
+ # decide on the final values for all options; this is called
134
+ # after all possible intervention from the outside world
135
+ # (command-line, option file, etc.) has been processed
136
+ # run()
137
+ # run the command: do whatever it is we're here to do,
138
+ # controlled by the command's various option values
139
+
140
+ def initialize_options(self):
141
+ """Set default values for all the options that this command
142
+ supports. Note that these defaults may be overridden by other
143
+ commands, by the setup script, by config files, or by the
144
+ command-line. Thus, this is not the place to code dependencies
145
+ between options; generally, 'initialize_options()' implementations
146
+ are just a bunch of "self.foo = None" assignments.
147
+
148
+ This method must be implemented by all command classes.
149
+ """
150
+ raise RuntimeError(
151
+ f"abstract method -- subclass {self.__class__} must override"
152
+ )
153
+
154
+ def finalize_options(self):
155
+ """Set final values for all the options that this command supports.
156
+ This is always called as late as possible, ie. after any option
157
+ assignments from the command-line or from other commands have been
158
+ done. Thus, this is the place to code option dependencies: if
159
+ 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
160
+ long as 'foo' still has the same value it was assigned in
161
+ 'initialize_options()'.
162
+
163
+ This method must be implemented by all command classes.
164
+ """
165
+ raise RuntimeError(
166
+ f"abstract method -- subclass {self.__class__} must override"
167
+ )
168
+
169
+ def dump_options(self, header=None, indent=""):
170
+ from distutils.fancy_getopt import longopt_xlate
171
+
172
+ if header is None:
173
+ header = f"command options for '{self.get_command_name()}':"
174
+ self.announce(indent + header, level=logging.INFO)
175
+ indent = indent + " "
176
+ for option, _, _ in self.user_options:
177
+ option = option.translate(longopt_xlate)
178
+ if option[-1] == "=":
179
+ option = option[:-1]
180
+ value = getattr(self, option)
181
+ self.announce(indent + f"{option} = {value}", level=logging.INFO)
182
+
183
+ def run(self):
184
+ """A command's raison d'etre: carry out the action it exists to
185
+ perform, controlled by the options initialized in
186
+ 'initialize_options()', customized by other commands, the setup
187
+ script, the command-line, and config files, and finalized in
188
+ 'finalize_options()'. All terminal output and filesystem
189
+ interaction should be done by 'run()'.
190
+
191
+ This method must be implemented by all command classes.
192
+ """
193
+ raise RuntimeError(
194
+ f"abstract method -- subclass {self.__class__} must override"
195
+ )
196
+
197
+ def announce(self, msg, level=logging.DEBUG):
198
+ log.log(level, msg)
199
+
200
+ def debug_print(self, msg):
201
+ """Print 'msg' to stdout if the global DEBUG (taken from the
202
+ DISTUTILS_DEBUG environment variable) flag is true.
203
+ """
204
+ from distutils.debug import DEBUG
205
+
206
+ if DEBUG:
207
+ print(msg)
208
+ sys.stdout.flush()
209
+
210
+ # -- Option validation methods -------------------------------------
211
+ # (these are very handy in writing the 'finalize_options()' method)
212
+ #
213
+ # NB. the general philosophy here is to ensure that a particular option
214
+ # value meets certain type and value constraints. If not, we try to
215
+ # force it into conformance (eg. if we expect a list but have a string,
216
+ # split the string on comma and/or whitespace). If we can't force the
217
+ # option into conformance, raise DistutilsOptionError. Thus, command
218
+ # classes need do nothing more than (eg.)
219
+ # self.ensure_string_list('foo')
220
+ # and they can be guaranteed that thereafter, self.foo will be
221
+ # a list of strings.
222
+
223
+ def _ensure_stringlike(self, option, what, default=None):
224
+ val = getattr(self, option)
225
+ if val is None:
226
+ setattr(self, option, default)
227
+ return default
228
+ elif not isinstance(val, str):
229
+ raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
230
+ return val
231
+
232
+ def ensure_string(self, option, default=None):
233
+ """Ensure that 'option' is a string; if not defined, set it to
234
+ 'default'.
235
+ """
236
+ self._ensure_stringlike(option, "string", default)
237
+
238
+ def ensure_string_list(self, option):
239
+ r"""Ensure that 'option' is a list of strings. If 'option' is
240
+ currently a string, we split it either on /,\s*/ or /\s+/, so
241
+ "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
242
+ ["foo", "bar", "baz"].
243
+ """
244
+ val = getattr(self, option)
245
+ if val is None:
246
+ return
247
+ elif isinstance(val, str):
248
+ setattr(self, option, re.split(r',\s*|\s+', val))
249
+ else:
250
+ if isinstance(val, list):
251
+ ok = all(isinstance(v, str) for v in val)
252
+ else:
253
+ ok = False
254
+ if not ok:
255
+ raise DistutilsOptionError(
256
+ f"'{option}' must be a list of strings (got {val!r})"
257
+ )
258
+
259
+ def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
260
+ val = self._ensure_stringlike(option, what, default)
261
+ if val is not None and not tester(val):
262
+ raise DistutilsOptionError(
263
+ ("error in '%s' option: " + error_fmt) % (option, val)
264
+ )
265
+
266
+ def ensure_filename(self, option):
267
+ """Ensure that 'option' is the name of an existing file."""
268
+ self._ensure_tested_string(
269
+ option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
270
+ )
271
+
272
+ def ensure_dirname(self, option):
273
+ self._ensure_tested_string(
274
+ option,
275
+ os.path.isdir,
276
+ "directory name",
277
+ "'%s' does not exist or is not a directory",
278
+ )
279
+
280
+ # -- Convenience methods for commands ------------------------------
281
+
282
+ def get_command_name(self):
283
+ if hasattr(self, 'command_name'):
284
+ return self.command_name
285
+ else:
286
+ return self.__class__.__name__
287
+
288
+ def set_undefined_options(self, src_cmd, *option_pairs):
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
+ def get_finalized_command(self, command, create=True):
310
+ """Wrapper around Distribution's 'get_command_obj()' method: find
311
+ (create if necessary and 'create' is true) the command object for
312
+ 'command', call its 'ensure_finalized()' method, and return the
313
+ finalized command object.
314
+ """
315
+ cmd_obj = self.distribution.get_command_obj(command, create)
316
+ cmd_obj.ensure_finalized()
317
+ return cmd_obj
318
+
319
+ # XXX rename to 'get_reinitialized_command()'? (should do the
320
+ # same in dist.py, if so)
321
+ @overload
322
+ def reinitialize_command(
323
+ self, command: str, reinit_subcommands: bool = False
324
+ ) -> Command: ...
325
+ @overload
326
+ def reinitialize_command(
327
+ self, command: _CommandT, reinit_subcommands: bool = False
328
+ ) -> _CommandT: ...
329
+ def reinitialize_command(
330
+ self, command: str | Command, reinit_subcommands=False
331
+ ) -> Command:
332
+ return self.distribution.reinitialize_command(command, reinit_subcommands)
333
+
334
+ def run_command(self, command):
335
+ """Run some other command: uses the 'run_command()' method of
336
+ Distribution, which creates and finalizes the command object if
337
+ necessary and then invokes its 'run()' method.
338
+ """
339
+ self.distribution.run_command(command)
340
+
341
+ def get_sub_commands(self):
342
+ """Determine the sub-commands that are relevant in the current
343
+ distribution (ie., that need to be run). This is based on the
344
+ 'sub_commands' class attribute: each tuple in that list may include
345
+ a method that we call to determine if the subcommand needs to be
346
+ run for the current distribution. Return a list of command names.
347
+ """
348
+ commands = []
349
+ for cmd_name, method in self.sub_commands:
350
+ if method is None or method(self):
351
+ commands.append(cmd_name)
352
+ return commands
353
+
354
+ # -- External world manipulation -----------------------------------
355
+
356
+ def warn(self, msg):
357
+ log.warning("warning: %s: %s\n", self.get_command_name(), msg)
358
+
359
+ def execute(self, func, args, msg=None, level=1):
360
+ util.execute(func, args, msg, dry_run=self.dry_run)
361
+
362
+ def mkpath(self, name, mode=0o777):
363
+ dir_util.mkpath(name, mode, dry_run=self.dry_run)
364
+
365
+ def copy_file(
366
+ self,
367
+ infile,
368
+ outfile,
369
+ preserve_mode=True,
370
+ preserve_times=True,
371
+ link=None,
372
+ level=1,
373
+ ):
374
+ """Copy a file respecting verbose, dry-run and force flags. (The
375
+ former two default to whatever is in the Distribution object, and
376
+ the latter defaults to false for commands that don't define it.)"""
377
+ return file_util.copy_file(
378
+ infile,
379
+ outfile,
380
+ preserve_mode,
381
+ preserve_times,
382
+ not self.force,
383
+ link,
384
+ dry_run=self.dry_run,
385
+ )
386
+
387
+ def copy_tree(
388
+ self,
389
+ infile,
390
+ outfile,
391
+ preserve_mode=True,
392
+ preserve_times=True,
393
+ preserve_symlinks=False,
394
+ level=1,
395
+ ):
396
+ """Copy an entire directory tree respecting verbose, dry-run,
397
+ and force flags.
398
+ """
399
+ return dir_util.copy_tree(
400
+ infile,
401
+ outfile,
402
+ preserve_mode,
403
+ preserve_times,
404
+ preserve_symlinks,
405
+ not self.force,
406
+ dry_run=self.dry_run,
407
+ )
408
+
409
+ def move_file(self, src, dst, level=1):
410
+ """Move a file respecting dry-run flag."""
411
+ return file_util.move_file(src, dst, dry_run=self.dry_run)
412
+
413
+ def spawn(self, cmd, search_path=True, level=1):
414
+ """Spawn an external command respecting dry-run flag."""
415
+ from distutils.spawn import spawn
416
+
417
+ spawn(cmd, search_path, dry_run=self.dry_run)
418
+
419
+ def make_archive(
420
+ self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None
421
+ ):
422
+ return archive_util.make_archive(
423
+ base_name,
424
+ format,
425
+ root_dir,
426
+ base_dir,
427
+ dry_run=self.dry_run,
428
+ owner=owner,
429
+ group=group,
430
+ )
431
+
432
+ def make_file(
433
+ self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1
434
+ ):
435
+ """Special case of 'execute()' for operations that process one or
436
+ more input files and generate one output file. Works just like
437
+ 'execute()', except the operation is skipped and a different
438
+ message printed if 'outfile' already exists and is newer than all
439
+ files listed in 'infiles'. If the command defined 'self.force',
440
+ and it is true, then the command is unconditionally run -- does no
441
+ timestamp checks.
442
+ """
443
+ if skip_msg is None:
444
+ skip_msg = f"skipping {outfile} (inputs unchanged)"
445
+
446
+ # Allow 'infiles' to be a single string
447
+ if isinstance(infiles, str):
448
+ infiles = (infiles,)
449
+ elif not isinstance(infiles, (list, tuple)):
450
+ raise TypeError("'infiles' must be a string, or a list or tuple of strings")
451
+
452
+ if exec_msg is None:
453
+ exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles))
454
+
455
+ # If 'outfile' must be regenerated (either because it doesn't
456
+ # exist, is out-of-date, or the 'force' flag is true) then
457
+ # perform the action that presumably regenerates it
458
+ if self.force or _modified.newer_group(infiles, outfile):
459
+ self.execute(func, args, exec_msg, level)
460
+ # Otherwise, print the "skip" message
461
+ else:
462
+ log.debug(skip_msg)
evalkit_llava/lib/python3.10/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 ()
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/cygwinccompiler.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.cygwinccompiler
2
+
3
+ Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
4
+ handles the Cygwin port of the GNU C compiler to Windows. It also contains
5
+ the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
6
+ cygwin in no-cygwin mode).
7
+ """
8
+
9
+ import copy
10
+ import os
11
+ import pathlib
12
+ import shlex
13
+ import sys
14
+ import warnings
15
+ from subprocess import check_output
16
+
17
+ from .errors import (
18
+ CCompilerError,
19
+ CompileError,
20
+ DistutilsExecError,
21
+ DistutilsPlatformError,
22
+ )
23
+ from .file_util import write_file
24
+ from .sysconfig import get_config_vars
25
+ from .unixccompiler import UnixCCompiler
26
+ from .version import LooseVersion, suppress_known_deprecation
27
+
28
+
29
+ def get_msvcr():
30
+ """No longer needed, but kept for backward compatibility."""
31
+ return []
32
+
33
+
34
+ _runtime_library_dirs_msg = (
35
+ "Unable to set runtime library search path on Windows, "
36
+ "usually indicated by `runtime_library_dirs` parameter to Extension"
37
+ )
38
+
39
+
40
+ class CygwinCCompiler(UnixCCompiler):
41
+ """Handles the Cygwin port of the GNU C compiler to Windows."""
42
+
43
+ compiler_type = 'cygwin'
44
+ obj_extension = ".o"
45
+ static_lib_extension = ".a"
46
+ shared_lib_extension = ".dll.a"
47
+ dylib_lib_extension = ".dll"
48
+ static_lib_format = "lib%s%s"
49
+ shared_lib_format = "lib%s%s"
50
+ dylib_lib_format = "cyg%s%s"
51
+ exe_extension = ".exe"
52
+
53
+ def __init__(self, verbose=False, dry_run=False, force=False):
54
+ super().__init__(verbose, dry_run, force)
55
+
56
+ status, details = check_config_h()
57
+ self.debug_print(f"Python's GCC status: {status} (details: {details})")
58
+ if status is not CONFIG_H_OK:
59
+ self.warn(
60
+ "Python's pyconfig.h doesn't seem to support your compiler. "
61
+ f"Reason: {details}. "
62
+ "Compiling may fail because of undefined preprocessor macros."
63
+ )
64
+
65
+ self.cc, self.cxx = get_config_vars('CC', 'CXX')
66
+
67
+ # Override 'CC' and 'CXX' environment variables for
68
+ # building using MINGW compiler for MSVC python.
69
+ self.cc = os.environ.get('CC', self.cc or 'gcc')
70
+ self.cxx = os.environ.get('CXX', self.cxx or 'g++')
71
+
72
+ self.linker_dll = self.cc
73
+ self.linker_dll_cxx = self.cxx
74
+ shared_option = "-shared"
75
+
76
+ self.set_executables(
77
+ compiler=f'{self.cc} -mcygwin -O -Wall',
78
+ compiler_so=f'{self.cc} -mcygwin -mdll -O -Wall',
79
+ compiler_cxx=f'{self.cxx} -mcygwin -O -Wall',
80
+ compiler_so_cxx=f'{self.cxx} -mcygwin -mdll -O -Wall',
81
+ linker_exe=f'{self.cc} -mcygwin',
82
+ linker_so=f'{self.linker_dll} -mcygwin {shared_option}',
83
+ linker_exe_cxx=f'{self.cxx} -mcygwin',
84
+ linker_so_cxx=f'{self.linker_dll_cxx} -mcygwin {shared_option}',
85
+ )
86
+
87
+ self.dll_libraries = get_msvcr()
88
+
89
+ @property
90
+ def gcc_version(self):
91
+ # Older numpy depended on this existing to check for ancient
92
+ # gcc versions. This doesn't make much sense with clang etc so
93
+ # just hardcode to something recent.
94
+ # https://github.com/numpy/numpy/pull/20333
95
+ warnings.warn(
96
+ "gcc_version attribute of CygwinCCompiler is deprecated. "
97
+ "Instead of returning actual gcc version a fixed value 11.2.0 is returned.",
98
+ DeprecationWarning,
99
+ stacklevel=2,
100
+ )
101
+ with suppress_known_deprecation():
102
+ return LooseVersion("11.2.0")
103
+
104
+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
105
+ """Compiles the source by spawning GCC and windres if needed."""
106
+ if ext in ('.rc', '.res'):
107
+ # gcc needs '.res' and '.rc' compiled to object files !!!
108
+ try:
109
+ self.spawn(["windres", "-i", src, "-o", obj])
110
+ except DistutilsExecError as msg:
111
+ raise CompileError(msg)
112
+ else: # for other files use the C-compiler
113
+ try:
114
+ if self.detect_language(src) == 'c++':
115
+ self.spawn(
116
+ self.compiler_so_cxx
117
+ + cc_args
118
+ + [src, '-o', obj]
119
+ + extra_postargs
120
+ )
121
+ else:
122
+ self.spawn(
123
+ self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs
124
+ )
125
+ except DistutilsExecError as msg:
126
+ raise CompileError(msg)
127
+
128
+ def link(
129
+ self,
130
+ target_desc,
131
+ objects,
132
+ output_filename,
133
+ output_dir=None,
134
+ libraries=None,
135
+ library_dirs=None,
136
+ runtime_library_dirs=None,
137
+ export_symbols=None,
138
+ debug=False,
139
+ extra_preargs=None,
140
+ extra_postargs=None,
141
+ build_temp=None,
142
+ target_lang=None,
143
+ ):
144
+ """Link the objects."""
145
+ # use separate copies, so we can modify the lists
146
+ extra_preargs = copy.copy(extra_preargs or [])
147
+ libraries = copy.copy(libraries or [])
148
+ objects = copy.copy(objects or [])
149
+
150
+ if runtime_library_dirs:
151
+ self.warn(_runtime_library_dirs_msg)
152
+
153
+ # Additional libraries
154
+ libraries.extend(self.dll_libraries)
155
+
156
+ # handle export symbols by creating a def-file
157
+ # with executables this only works with gcc/ld as linker
158
+ if (export_symbols is not None) and (
159
+ target_desc != self.EXECUTABLE or self.linker_dll == "gcc"
160
+ ):
161
+ # (The linker doesn't do anything if output is up-to-date.
162
+ # So it would probably better to check if we really need this,
163
+ # but for this we had to insert some unchanged parts of
164
+ # UnixCCompiler, and this is not what we want.)
165
+
166
+ # we want to put some files in the same directory as the
167
+ # object files are, build_temp doesn't help much
168
+ # where are the object files
169
+ temp_dir = os.path.dirname(objects[0])
170
+ # name of dll to give the helper files the same base name
171
+ (dll_name, dll_extension) = os.path.splitext(
172
+ os.path.basename(output_filename)
173
+ )
174
+
175
+ # generate the filenames for these files
176
+ def_file = os.path.join(temp_dir, dll_name + ".def")
177
+
178
+ # Generate .def file
179
+ contents = [f"LIBRARY {os.path.basename(output_filename)}", "EXPORTS"]
180
+ contents.extend(export_symbols)
181
+ self.execute(write_file, (def_file, contents), f"writing {def_file}")
182
+
183
+ # next add options for def-file
184
+
185
+ # for gcc/ld the def-file is specified as any object files
186
+ objects.append(def_file)
187
+
188
+ # end: if ((export_symbols is not None) and
189
+ # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
190
+
191
+ # who wants symbols and a many times larger output file
192
+ # should explicitly switch the debug mode on
193
+ # otherwise we let ld strip the output file
194
+ # (On my machine: 10KiB < stripped_file < ??100KiB
195
+ # unstripped_file = stripped_file + XXX KiB
196
+ # ( XXX=254 for a typical python extension))
197
+ if not debug:
198
+ extra_preargs.append("-s")
199
+
200
+ UnixCCompiler.link(
201
+ self,
202
+ target_desc,
203
+ objects,
204
+ output_filename,
205
+ output_dir,
206
+ libraries,
207
+ library_dirs,
208
+ runtime_library_dirs,
209
+ None, # export_symbols, we do this in our def-file
210
+ debug,
211
+ extra_preargs,
212
+ extra_postargs,
213
+ build_temp,
214
+ target_lang,
215
+ )
216
+
217
+ def runtime_library_dir_option(self, dir):
218
+ # cygwin doesn't support rpath. While in theory we could error
219
+ # out like MSVC does, code might expect it to work like on Unix, so
220
+ # just warn and hope for the best.
221
+ self.warn(_runtime_library_dirs_msg)
222
+ return []
223
+
224
+ # -- Miscellaneous methods -----------------------------------------
225
+
226
+ def _make_out_path(self, output_dir, strip_dir, src_name):
227
+ # use normcase to make sure '.rc' is really '.rc' and not '.RC'
228
+ norm_src_name = os.path.normcase(src_name)
229
+ return super()._make_out_path(output_dir, strip_dir, norm_src_name)
230
+
231
+ @property
232
+ def out_extensions(self):
233
+ """
234
+ Add support for rc and res files.
235
+ """
236
+ return {
237
+ **super().out_extensions,
238
+ **{ext: ext + self.obj_extension for ext in ('.res', '.rc')},
239
+ }
240
+
241
+
242
+ # the same as cygwin plus some additional parameters
243
+ class Mingw32CCompiler(CygwinCCompiler):
244
+ """Handles the Mingw32 port of the GNU C compiler to Windows."""
245
+
246
+ compiler_type = 'mingw32'
247
+
248
+ def __init__(self, verbose=False, dry_run=False, force=False):
249
+ super().__init__(verbose, dry_run, force)
250
+
251
+ shared_option = "-shared"
252
+
253
+ if is_cygwincc(self.cc):
254
+ raise CCompilerError('Cygwin gcc cannot be used with --compiler=mingw32')
255
+
256
+ self.set_executables(
257
+ compiler=f'{self.cc} -O -Wall',
258
+ compiler_so=f'{self.cc} -shared -O -Wall',
259
+ compiler_so_cxx=f'{self.cxx} -shared -O -Wall',
260
+ compiler_cxx=f'{self.cxx} -O -Wall',
261
+ linker_exe=f'{self.cc}',
262
+ linker_so=f'{self.linker_dll} {shared_option}',
263
+ linker_exe_cxx=f'{self.cxx}',
264
+ linker_so_cxx=f'{self.linker_dll_cxx} {shared_option}',
265
+ )
266
+
267
+ def runtime_library_dir_option(self, dir):
268
+ raise DistutilsPlatformError(_runtime_library_dirs_msg)
269
+
270
+
271
+ # Because these compilers aren't configured in Python's pyconfig.h file by
272
+ # default, we should at least warn the user if he is using an unmodified
273
+ # version.
274
+
275
+ CONFIG_H_OK = "ok"
276
+ CONFIG_H_NOTOK = "not ok"
277
+ CONFIG_H_UNCERTAIN = "uncertain"
278
+
279
+
280
+ def check_config_h():
281
+ """Check if the current Python installation appears amenable to building
282
+ extensions with GCC.
283
+
284
+ Returns a tuple (status, details), where 'status' is one of the following
285
+ constants:
286
+
287
+ - CONFIG_H_OK: all is well, go ahead and compile
288
+ - CONFIG_H_NOTOK: doesn't look good
289
+ - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
290
+
291
+ 'details' is a human-readable string explaining the situation.
292
+
293
+ Note there are two ways to conclude "OK": either 'sys.version' contains
294
+ the string "GCC" (implying that this Python was built with GCC), or the
295
+ installed "pyconfig.h" contains the string "__GNUC__".
296
+ """
297
+
298
+ # XXX since this function also checks sys.version, it's not strictly a
299
+ # "pyconfig.h" check -- should probably be renamed...
300
+
301
+ from distutils import sysconfig
302
+
303
+ # if sys.version contains GCC then python was compiled with GCC, and the
304
+ # pyconfig.h file should be OK
305
+ if "GCC" in sys.version:
306
+ return CONFIG_H_OK, "sys.version mentions 'GCC'"
307
+
308
+ # Clang would also work
309
+ if "Clang" in sys.version:
310
+ return CONFIG_H_OK, "sys.version mentions 'Clang'"
311
+
312
+ # let's see if __GNUC__ is mentioned in python.h
313
+ fn = sysconfig.get_config_h_filename()
314
+ try:
315
+ config_h = pathlib.Path(fn).read_text(encoding='utf-8')
316
+ except OSError as exc:
317
+ return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}")
318
+ else:
319
+ substring = '__GNUC__'
320
+ if substring in config_h:
321
+ code = CONFIG_H_OK
322
+ mention_inflected = 'mentions'
323
+ else:
324
+ code = CONFIG_H_NOTOK
325
+ mention_inflected = 'does not mention'
326
+ return code, f"{fn!r} {mention_inflected} {substring!r}"
327
+
328
+
329
+ def is_cygwincc(cc):
330
+ """Try to determine if the compiler that would be used is from cygwin."""
331
+ out_string = check_output(shlex.split(cc) + ['-dumpmachine'])
332
+ return out_string.strip().endswith(b'cygwin')
333
+
334
+
335
+ get_versions = None
336
+ """
337
+ A stand-in for the previous get_versions() function to prevent failures
338
+ when monkeypatched. See pypa/setuptools#2969.
339
+ """
evalkit_llava/lib/python3.10/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')
evalkit_llava/lib/python3.10/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)
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/dir_util.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, dry_run=False) -> 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
+ dry_run or 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, dry_run=False):
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', 'verbose' and
87
+ 'dry_run' 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, dry_run=dry_run)
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
+ dry_run=False,
106
+ ):
107
+ """Copy an entire directory tree 'src' to a new location 'dst'.
108
+
109
+ Both 'src' and 'dst' must be directory names. If 'src' is not a
110
+ directory, raise DistutilsFileError. If 'dst' does not exist, it is
111
+ created with 'mkpath()'. The end result of the copy is that every
112
+ file in 'src' is copied to 'dst', and directories under 'src' are
113
+ recursively copied to 'dst'. Return the list of files that were
114
+ copied or might have been copied, using their output name. The
115
+ return value is unaffected by 'update' or 'dry_run': it is simply
116
+ the list of all files under 'src', with the names changed to be
117
+ under 'dst'.
118
+
119
+ 'preserve_mode' and 'preserve_times' are the same as for
120
+ 'copy_file'; note that they only apply to regular files, not to
121
+ directories. If 'preserve_symlinks' is true, symlinks will be
122
+ copied as symlinks (on platforms that support them!); otherwise
123
+ (the default), the destination of the symlink will be copied.
124
+ 'update' and 'verbose' are the same as for 'copy_file'.
125
+ """
126
+ if not dry_run and not os.path.isdir(src):
127
+ raise DistutilsFileError(f"cannot copy tree '{src}': not a directory")
128
+ try:
129
+ names = os.listdir(src)
130
+ except OSError as e:
131
+ if dry_run:
132
+ names = []
133
+ else:
134
+ raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
135
+
136
+ if not dry_run:
137
+ mkpath(dst, verbose=verbose)
138
+
139
+ copy_one = functools.partial(
140
+ _copy_one,
141
+ src=src,
142
+ dst=dst,
143
+ preserve_symlinks=preserve_symlinks,
144
+ verbose=verbose,
145
+ dry_run=dry_run,
146
+ preserve_mode=preserve_mode,
147
+ preserve_times=preserve_times,
148
+ update=update,
149
+ )
150
+ return list(itertools.chain.from_iterable(map(copy_one, names)))
151
+
152
+
153
+ def _copy_one(
154
+ name,
155
+ *,
156
+ src,
157
+ dst,
158
+ preserve_symlinks,
159
+ verbose,
160
+ dry_run,
161
+ preserve_mode,
162
+ preserve_times,
163
+ update,
164
+ ):
165
+ src_name = os.path.join(src, name)
166
+ dst_name = os.path.join(dst, name)
167
+
168
+ if name.startswith('.nfs'):
169
+ # skip NFS rename files
170
+ return
171
+
172
+ if preserve_symlinks and os.path.islink(src_name):
173
+ link_dest = os.readlink(src_name)
174
+ if verbose >= 1:
175
+ log.info("linking %s -> %s", dst_name, link_dest)
176
+ if not dry_run:
177
+ os.symlink(link_dest, dst_name)
178
+ yield dst_name
179
+
180
+ elif os.path.isdir(src_name):
181
+ yield from copy_tree(
182
+ src_name,
183
+ dst_name,
184
+ preserve_mode,
185
+ preserve_times,
186
+ preserve_symlinks,
187
+ update,
188
+ verbose=verbose,
189
+ dry_run=dry_run,
190
+ )
191
+ else:
192
+ file_util.copy_file(
193
+ src_name,
194
+ dst_name,
195
+ preserve_mode,
196
+ preserve_times,
197
+ update,
198
+ verbose=verbose,
199
+ dry_run=dry_run,
200
+ )
201
+ yield dst_name
202
+
203
+
204
+ def _build_cmdtuple(path, cmdtuples):
205
+ """Helper for remove_tree()."""
206
+ for f in os.listdir(path):
207
+ real_f = os.path.join(path, f)
208
+ if os.path.isdir(real_f) and not os.path.islink(real_f):
209
+ _build_cmdtuple(real_f, cmdtuples)
210
+ else:
211
+ cmdtuples.append((os.remove, real_f))
212
+ cmdtuples.append((os.rmdir, path))
213
+
214
+
215
+ def remove_tree(directory, verbose=True, dry_run=False):
216
+ """Recursively remove an entire directory tree.
217
+
218
+ Any errors are ignored (apart from being reported to stdout if 'verbose'
219
+ is true).
220
+ """
221
+ if verbose >= 1:
222
+ log.info("removing '%s' (and everything under it)", directory)
223
+ if dry_run:
224
+ return
225
+ cmdtuples = []
226
+ _build_cmdtuple(directory, cmdtuples)
227
+ for cmd in cmdtuples:
228
+ try:
229
+ cmd[0](cmd[1])
230
+ # Clear the cache
231
+ SkipRepeatAbsolutePaths.clear()
232
+ except OSError as exc:
233
+ log.warning("error removing %s: %s", directory, exc)
234
+
235
+
236
+ def ensure_relative(path):
237
+ """Take the full path 'path', and make it a relative path.
238
+
239
+ This is useful to make 'path' the second argument to os.path.join().
240
+ """
241
+ drive, path = os.path.splitdrive(path)
242
+ if path[0:1] == os.sep:
243
+ path = drive + path[1:]
244
+ return path
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/dist.py ADDED
@@ -0,0 +1,1317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
17
+ from email import message_from_file
18
+ from typing import TYPE_CHECKING, Literal, TypeVar, overload
19
+
20
+ from packaging.utils import canonicalize_name, canonicalize_version
21
+
22
+ from ._log import log
23
+ from .debug import DEBUG
24
+ from .errors import (
25
+ DistutilsArgError,
26
+ DistutilsClassError,
27
+ DistutilsModuleError,
28
+ DistutilsOptionError,
29
+ )
30
+ from .fancy_getopt import FancyGetopt, translate_longopt
31
+ from .util import check_environ, rfc822_escape, strtobool
32
+
33
+ if TYPE_CHECKING:
34
+ # type-only import because of mutual dependence between these modules
35
+ from .cmd import Command
36
+
37
+ _CommandT = TypeVar("_CommandT", bound="Command")
38
+
39
+ # Regex to define acceptable Distutils command names. This is not *quite*
40
+ # the same as a Python NAME -- I don't allow leading underscores. The fact
41
+ # that they're very similar is no coincidence; the default naming scheme is
42
+ # to look for a Python module named after the command.
43
+ command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
44
+
45
+
46
+ def _ensure_list(value, fieldname):
47
+ if isinstance(value, str):
48
+ # a string containing comma separated values is okay. It will
49
+ # be converted to a list by Distribution.finalize_options().
50
+ pass
51
+ elif not isinstance(value, list):
52
+ # passing a tuple or an iterator perhaps, warn and convert
53
+ typename = type(value).__name__
54
+ msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"
55
+ msg = msg.format(**locals())
56
+ log.warning(msg)
57
+ value = list(value)
58
+ return value
59
+
60
+
61
+ class Distribution:
62
+ """The core of the Distutils. Most of the work hiding behind 'setup'
63
+ is really done within a Distribution instance, which farms the work out
64
+ to the Distutils commands specified on the command line.
65
+
66
+ Setup scripts will almost never instantiate Distribution directly,
67
+ unless the 'setup()' function is totally inadequate to their needs.
68
+ However, it is conceivable that a setup script might wish to subclass
69
+ Distribution for some specialized purpose, and then pass the subclass
70
+ to 'setup()' as the 'distclass' keyword argument. If so, it is
71
+ necessary to respect the expectations that 'setup' has of Distribution.
72
+ See the code for 'setup()', in core.py, for details.
73
+ """
74
+
75
+ # 'global_options' describes the command-line options that may be
76
+ # supplied to the setup script prior to any actual commands.
77
+ # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
78
+ # these global options. This list should be kept to a bare minimum,
79
+ # since every global option is also valid as a command option -- and we
80
+ # don't want to pollute the commands with too many options that they
81
+ # have minimal control over.
82
+ # The fourth entry for verbose means that it can be repeated.
83
+ global_options = [
84
+ ('verbose', 'v', "run verbosely (default)", 1),
85
+ ('quiet', 'q', "run quietly (turns verbosity off)"),
86
+ ('dry-run', 'n', "don't actually do anything"),
87
+ ('help', 'h', "show detailed help message"),
88
+ ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
89
+ ]
90
+
91
+ # 'common_usage' is a short (2-3 line) string describing the common
92
+ # usage of the setup script.
93
+ common_usage = """\
94
+ Common commands: (see '--help-commands' for more)
95
+
96
+ setup.py build will build the package underneath 'build/'
97
+ setup.py install will install the package
98
+ """
99
+
100
+ # options that are not propagated to the commands
101
+ display_options = [
102
+ ('help-commands', None, "list all available commands"),
103
+ ('name', None, "print package name"),
104
+ ('version', 'V', "print package version"),
105
+ ('fullname', None, "print <package name>-<version>"),
106
+ ('author', None, "print the author's name"),
107
+ ('author-email', None, "print the author's email address"),
108
+ ('maintainer', None, "print the maintainer's name"),
109
+ ('maintainer-email', None, "print the maintainer's email address"),
110
+ ('contact', None, "print the maintainer's name if known, else the author's"),
111
+ (
112
+ 'contact-email',
113
+ None,
114
+ "print the maintainer's email address if known, else the author's",
115
+ ),
116
+ ('url', None, "print the URL for this package"),
117
+ ('license', None, "print the license of the package"),
118
+ ('licence', None, "alias for --license"),
119
+ ('description', None, "print the package description"),
120
+ ('long-description', None, "print the long package description"),
121
+ ('platforms', None, "print the list of platforms"),
122
+ ('classifiers', None, "print the list of classifiers"),
123
+ ('keywords', None, "print the list of keywords"),
124
+ ('provides', None, "print the list of packages/modules provided"),
125
+ ('requires', None, "print the list of packages/modules required"),
126
+ ('obsoletes', None, "print the list of packages/modules made obsolete"),
127
+ ]
128
+ display_option_names = [translate_longopt(x[0]) for x in display_options]
129
+
130
+ # negative options are options that exclude other options
131
+ negative_opt = {'quiet': 'verbose'}
132
+
133
+ # -- Creation/initialization methods -------------------------------
134
+
135
+ def __init__(self, attrs=None): # noqa: C901
136
+ """Construct a new Distribution instance: initialize all the
137
+ attributes of a Distribution, and then use 'attrs' (a dictionary
138
+ mapping attribute names to values) to assign some of those
139
+ attributes their "real" values. (Any attributes not mentioned in
140
+ 'attrs' will be assigned to some null value: 0, None, an empty list
141
+ or dictionary, etc.) Most importantly, initialize the
142
+ 'command_obj' attribute to the empty dictionary; this will be
143
+ filled in with real command objects by 'parse_command_line()'.
144
+ """
145
+
146
+ # Default values for our command-line options
147
+ self.verbose = True
148
+ self.dry_run = False
149
+ self.help = False
150
+ for attr in self.display_option_names:
151
+ setattr(self, attr, False)
152
+
153
+ # Store the distribution meta-data (name, version, author, and so
154
+ # forth) in a separate object -- we're getting to have enough
155
+ # information here (and enough command-line options) that it's
156
+ # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
157
+ # object in a sneaky and underhanded (but efficient!) way.
158
+ self.metadata = DistributionMetadata()
159
+ for basename in self.metadata._METHOD_BASENAMES:
160
+ method_name = "get_" + basename
161
+ setattr(self, method_name, getattr(self.metadata, method_name))
162
+
163
+ # 'cmdclass' maps command names to class objects, so we
164
+ # can 1) quickly figure out which class to instantiate when
165
+ # we need to create a new command object, and 2) have a way
166
+ # for the setup script to override command classes
167
+ self.cmdclass = {}
168
+
169
+ # 'command_packages' is a list of packages in which commands
170
+ # are searched for. The factory for command 'foo' is expected
171
+ # to be named 'foo' in the module 'foo' in one of the packages
172
+ # named here. This list is searched from the left; an error
173
+ # is raised if no named package provides the command being
174
+ # searched for. (Always access using get_command_packages().)
175
+ self.command_packages = None
176
+
177
+ # 'script_name' and 'script_args' are usually set to sys.argv[0]
178
+ # and sys.argv[1:], but they can be overridden when the caller is
179
+ # not necessarily a setup script run from the command-line.
180
+ self.script_name = None
181
+ self.script_args: list[str] | None = None
182
+
183
+ # 'command_options' is where we store command options between
184
+ # parsing them (from config files, the command-line, etc.) and when
185
+ # they are actually needed -- ie. when the command in question is
186
+ # instantiated. It is a dictionary of dictionaries of 2-tuples:
187
+ # command_options = { command_name : { option : (source, value) } }
188
+ self.command_options = {}
189
+
190
+ # 'dist_files' is the list of (command, pyversion, file) that
191
+ # have been created by any dist commands run so far. This is
192
+ # filled regardless of whether the run is dry or not. pyversion
193
+ # gives sysconfig.get_python_version() if the dist file is
194
+ # specific to a Python version, 'any' if it is good for all
195
+ # Python versions on the target platform, and '' for a source
196
+ # file. pyversion should not be used to specify minimum or
197
+ # maximum required Python versions; use the metainfo for that
198
+ # instead.
199
+ self.dist_files = []
200
+
201
+ # These options are really the business of various commands, rather
202
+ # than of the Distribution itself. We provide aliases for them in
203
+ # Distribution as a convenience to the developer.
204
+ self.packages = None
205
+ self.package_data = {}
206
+ self.package_dir = None
207
+ self.py_modules = None
208
+ self.libraries = None
209
+ self.headers = None
210
+ self.ext_modules = None
211
+ self.ext_package = None
212
+ self.include_dirs = None
213
+ self.extra_path = None
214
+ self.scripts = None
215
+ self.data_files = None
216
+ self.password = ''
217
+
218
+ # And now initialize bookkeeping stuff that can't be supplied by
219
+ # the caller at all. 'command_obj' maps command names to
220
+ # Command instances -- that's how we enforce that every command
221
+ # class is a singleton.
222
+ self.command_obj = {}
223
+
224
+ # 'have_run' maps command names to boolean values; it keeps track
225
+ # of whether we have actually run a particular command, to make it
226
+ # cheap to "run" a command whenever we think we might need to -- if
227
+ # it's already been done, no need for expensive filesystem
228
+ # operations, we just check the 'have_run' dictionary and carry on.
229
+ # It's only safe to query 'have_run' for a command class that has
230
+ # been instantiated -- a false value will be inserted when the
231
+ # command object is created, and replaced with a true value when
232
+ # the command is successfully run. Thus it's probably best to use
233
+ # '.get()' rather than a straight lookup.
234
+ self.have_run = {}
235
+
236
+ # Now we'll use the attrs dictionary (ultimately, keyword args from
237
+ # the setup script) to possibly override any or all of these
238
+ # distribution options.
239
+
240
+ if attrs:
241
+ # Pull out the set of command options and work on them
242
+ # specifically. Note that this order guarantees that aliased
243
+ # command options will override any supplied redundantly
244
+ # through the general options dictionary.
245
+ options = attrs.get('options')
246
+ if options is not None:
247
+ del attrs['options']
248
+ for command, cmd_options in options.items():
249
+ opt_dict = self.get_option_dict(command)
250
+ for opt, val in cmd_options.items():
251
+ opt_dict[opt] = ("setup script", val)
252
+
253
+ if 'licence' in attrs:
254
+ attrs['license'] = attrs['licence']
255
+ del attrs['licence']
256
+ msg = "'licence' distribution option is deprecated; use 'license'"
257
+ warnings.warn(msg)
258
+
259
+ # Now work on the rest of the attributes. Any attribute that's
260
+ # not already defined is invalid!
261
+ for key, val in attrs.items():
262
+ if hasattr(self.metadata, "set_" + key):
263
+ getattr(self.metadata, "set_" + key)(val)
264
+ elif hasattr(self.metadata, key):
265
+ setattr(self.metadata, key, val)
266
+ elif hasattr(self, key):
267
+ setattr(self, key, val)
268
+ else:
269
+ msg = f"Unknown distribution option: {key!r}"
270
+ warnings.warn(msg)
271
+
272
+ # no-user-cfg is handled before other command line args
273
+ # because other args override the config files, and this
274
+ # one is needed before we can load the config files.
275
+ # If attrs['script_args'] wasn't passed, assume false.
276
+ #
277
+ # This also make sure we just look at the global options
278
+ self.want_user_cfg = True
279
+
280
+ if self.script_args is not None:
281
+ # Coerce any possible iterable from attrs into a list
282
+ self.script_args = list(self.script_args)
283
+ for arg in self.script_args:
284
+ if not arg.startswith('-'):
285
+ break
286
+ if arg == '--no-user-cfg':
287
+ self.want_user_cfg = False
288
+ break
289
+
290
+ self.finalize_options()
291
+
292
+ def get_option_dict(self, command):
293
+ """Get the option dictionary for a given command. If that
294
+ command's option dictionary hasn't been created yet, then create it
295
+ and return the new dictionary; otherwise, return the existing
296
+ option dictionary.
297
+ """
298
+ dict = self.command_options.get(command)
299
+ if dict is None:
300
+ dict = self.command_options[command] = {}
301
+ return dict
302
+
303
+ def dump_option_dicts(self, header=None, commands=None, indent=""):
304
+ from pprint import pformat
305
+
306
+ if commands is None: # dump all command option dicts
307
+ commands = sorted(self.command_options.keys())
308
+
309
+ if header is not None:
310
+ self.announce(indent + header)
311
+ indent = indent + " "
312
+
313
+ if not commands:
314
+ self.announce(indent + "no commands known yet")
315
+ return
316
+
317
+ for cmd_name in commands:
318
+ opt_dict = self.command_options.get(cmd_name)
319
+ if opt_dict is None:
320
+ self.announce(indent + f"no option dict for '{cmd_name}' command")
321
+ else:
322
+ self.announce(indent + f"option dict for '{cmd_name}' command:")
323
+ out = pformat(opt_dict)
324
+ for line in out.split('\n'):
325
+ self.announce(indent + " " + line)
326
+
327
+ # -- Config file finding/parsing methods ---------------------------
328
+
329
+ def find_config_files(self):
330
+ """Find as many configuration files as should be processed for this
331
+ platform, and return a list of filenames in the order in which they
332
+ should be parsed. The filenames returned are guaranteed to exist
333
+ (modulo nasty race conditions).
334
+
335
+ There are multiple possible config files:
336
+ - distutils.cfg in the Distutils installation directory (i.e.
337
+ where the top-level Distutils __inst__.py file lives)
338
+ - a file in the user's home directory named .pydistutils.cfg
339
+ on Unix and pydistutils.cfg on Windows/Mac; may be disabled
340
+ with the ``--no-user-cfg`` option
341
+ - setup.cfg in the current directory
342
+ - a file named by an environment variable
343
+ """
344
+ check_environ()
345
+ files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
346
+
347
+ if DEBUG:
348
+ self.announce("using config files: {}".format(', '.join(files)))
349
+
350
+ return files
351
+
352
+ def _gen_paths(self):
353
+ # The system-wide Distutils config file
354
+ sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent
355
+ yield sys_dir / "distutils.cfg"
356
+
357
+ # The per-user config file
358
+ prefix = '.' * (os.name == 'posix')
359
+ filename = prefix + 'pydistutils.cfg'
360
+ if self.want_user_cfg:
361
+ with contextlib.suppress(RuntimeError):
362
+ yield pathlib.Path('~').expanduser() / filename
363
+
364
+ # All platforms support local setup.cfg
365
+ yield pathlib.Path('setup.cfg')
366
+
367
+ # Additional config indicated in the environment
368
+ with contextlib.suppress(TypeError):
369
+ yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG"))
370
+
371
+ def parse_config_files(self, filenames=None): # noqa: C901
372
+ from configparser import ConfigParser
373
+
374
+ # Ignore install directory options if we have a venv
375
+ if sys.prefix != sys.base_prefix:
376
+ ignore_options = [
377
+ 'install-base',
378
+ 'install-platbase',
379
+ 'install-lib',
380
+ 'install-platlib',
381
+ 'install-purelib',
382
+ 'install-headers',
383
+ 'install-scripts',
384
+ 'install-data',
385
+ 'prefix',
386
+ 'exec-prefix',
387
+ 'home',
388
+ 'user',
389
+ 'root',
390
+ ]
391
+ else:
392
+ ignore_options = []
393
+
394
+ ignore_options = frozenset(ignore_options)
395
+
396
+ if filenames is None:
397
+ filenames = self.find_config_files()
398
+
399
+ if DEBUG:
400
+ self.announce("Distribution.parse_config_files():")
401
+
402
+ parser = ConfigParser()
403
+ for filename in filenames:
404
+ if DEBUG:
405
+ self.announce(f" reading {filename}")
406
+ parser.read(filename, encoding='utf-8')
407
+ for section in parser.sections():
408
+ options = parser.options(section)
409
+ opt_dict = self.get_option_dict(section)
410
+
411
+ for opt in options:
412
+ if opt != '__name__' and opt not in ignore_options:
413
+ val = parser.get(section, opt)
414
+ opt = opt.replace('-', '_')
415
+ opt_dict[opt] = (filename, val)
416
+
417
+ # Make the ConfigParser forget everything (so we retain
418
+ # the original filenames that options come from)
419
+ parser.__init__()
420
+
421
+ # If there was a "global" section in the config file, use it
422
+ # to set Distribution options.
423
+
424
+ if 'global' in self.command_options:
425
+ for opt, (_src, val) in self.command_options['global'].items():
426
+ alias = self.negative_opt.get(opt)
427
+ try:
428
+ if alias:
429
+ setattr(self, alias, not strtobool(val))
430
+ elif opt in ('verbose', 'dry_run'): # ugh!
431
+ setattr(self, opt, strtobool(val))
432
+ else:
433
+ setattr(self, opt, val)
434
+ except ValueError as msg:
435
+ raise DistutilsOptionError(msg)
436
+
437
+ # -- Command-line parsing methods ----------------------------------
438
+
439
+ def parse_command_line(self):
440
+ """Parse the setup script's command line, taken from the
441
+ 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
442
+ -- see 'setup()' in core.py). This list is first processed for
443
+ "global options" -- options that set attributes of the Distribution
444
+ instance. Then, it is alternately scanned for Distutils commands
445
+ and options for that command. Each new command terminates the
446
+ options for the previous command. The allowed options for a
447
+ command are determined by the 'user_options' attribute of the
448
+ command class -- thus, we have to be able to load command classes
449
+ in order to parse the command line. Any error in that 'options'
450
+ attribute raises DistutilsGetoptError; any error on the
451
+ command-line raises DistutilsArgError. If no Distutils commands
452
+ were found on the command line, raises DistutilsArgError. Return
453
+ true if command-line was successfully parsed and we should carry
454
+ on with executing commands; false if no errors but we shouldn't
455
+ execute commands (currently, this only happens if user asks for
456
+ help).
457
+ """
458
+ #
459
+ # We now have enough information to show the Macintosh dialog
460
+ # that allows the user to interactively specify the "command line".
461
+ #
462
+ toplevel_options = self._get_toplevel_options()
463
+
464
+ # We have to parse the command line a bit at a time -- global
465
+ # options, then the first command, then its options, and so on --
466
+ # because each command will be handled by a different class, and
467
+ # the options that are valid for a particular class aren't known
468
+ # until we have loaded the command class, which doesn't happen
469
+ # until we know what the command is.
470
+
471
+ self.commands = []
472
+ parser = FancyGetopt(toplevel_options + self.display_options)
473
+ parser.set_negative_aliases(self.negative_opt)
474
+ parser.set_aliases({'licence': 'license'})
475
+ args = parser.getopt(args=self.script_args, object=self)
476
+ option_order = parser.get_option_order()
477
+ logging.getLogger().setLevel(logging.WARN - 10 * self.verbose)
478
+
479
+ # for display options we return immediately
480
+ if self.handle_display_options(option_order):
481
+ return
482
+ while args:
483
+ args = self._parse_command_opts(parser, args)
484
+ if args is None: # user asked for help (and got it)
485
+ return
486
+
487
+ # Handle the cases of --help as a "global" option, ie.
488
+ # "setup.py --help" and "setup.py --help command ...". For the
489
+ # former, we show global options (--verbose, --dry-run, etc.)
490
+ # and display-only options (--name, --version, etc.); for the
491
+ # latter, we omit the display-only options and show help for
492
+ # each command listed on the command line.
493
+ if self.help:
494
+ self._show_help(
495
+ parser, display_options=len(self.commands) == 0, commands=self.commands
496
+ )
497
+ return
498
+
499
+ # Oops, no commands found -- an end-user error
500
+ if not self.commands:
501
+ raise DistutilsArgError("no commands supplied")
502
+
503
+ # All is well: return true
504
+ return True
505
+
506
+ def _get_toplevel_options(self):
507
+ """Return the non-display options recognized at the top level.
508
+
509
+ This includes options that are recognized *only* at the top
510
+ level as well as options recognized for commands.
511
+ """
512
+ return self.global_options + [
513
+ (
514
+ "command-packages=",
515
+ None,
516
+ "list of packages that provide distutils commands",
517
+ ),
518
+ ]
519
+
520
+ def _parse_command_opts(self, parser, args): # noqa: C901
521
+ """Parse the command-line options for a single command.
522
+ 'parser' must be a FancyGetopt instance; 'args' must be the list
523
+ of arguments, starting with the current command (whose options
524
+ we are about to parse). Returns a new version of 'args' with
525
+ the next command at the front of the list; will be the empty
526
+ list if there are no more commands on the command line. Returns
527
+ None if the user asked for help on this command.
528
+ """
529
+ # late import because of mutual dependence between these modules
530
+ from distutils.cmd import Command
531
+
532
+ # Pull the current command from the head of the command line
533
+ command = args[0]
534
+ if not command_re.match(command):
535
+ raise SystemExit(f"invalid command name '{command}'")
536
+ self.commands.append(command)
537
+
538
+ # Dig up the command class that implements this command, so we
539
+ # 1) know that it's a valid command, and 2) know which options
540
+ # it takes.
541
+ try:
542
+ cmd_class = self.get_command_class(command)
543
+ except DistutilsModuleError as msg:
544
+ raise DistutilsArgError(msg)
545
+
546
+ # Require that the command class be derived from Command -- want
547
+ # to be sure that the basic "command" interface is implemented.
548
+ if not issubclass(cmd_class, Command):
549
+ raise DistutilsClassError(
550
+ f"command class {cmd_class} must subclass Command"
551
+ )
552
+
553
+ # Also make sure that the command object provides a list of its
554
+ # known options.
555
+ if not (
556
+ hasattr(cmd_class, 'user_options')
557
+ and isinstance(cmd_class.user_options, list)
558
+ ):
559
+ msg = (
560
+ "command class %s must provide "
561
+ "'user_options' attribute (a list of tuples)"
562
+ )
563
+ raise DistutilsClassError(msg % cmd_class)
564
+
565
+ # If the command class has a list of negative alias options,
566
+ # merge it in with the global negative aliases.
567
+ negative_opt = self.negative_opt
568
+ if hasattr(cmd_class, 'negative_opt'):
569
+ negative_opt = negative_opt.copy()
570
+ negative_opt.update(cmd_class.negative_opt)
571
+
572
+ # Check for help_options in command class. They have a different
573
+ # format (tuple of four) so we need to preprocess them here.
574
+ if hasattr(cmd_class, 'help_options') and isinstance(
575
+ cmd_class.help_options, list
576
+ ):
577
+ help_options = fix_help_options(cmd_class.help_options)
578
+ else:
579
+ help_options = []
580
+
581
+ # All commands support the global options too, just by adding
582
+ # in 'global_options'.
583
+ parser.set_option_table(
584
+ self.global_options + cmd_class.user_options + help_options
585
+ )
586
+ parser.set_negative_aliases(negative_opt)
587
+ (args, opts) = parser.getopt(args[1:])
588
+ if hasattr(opts, 'help') and opts.help:
589
+ self._show_help(parser, display_options=False, commands=[cmd_class])
590
+ return
591
+
592
+ if hasattr(cmd_class, 'help_options') and isinstance(
593
+ cmd_class.help_options, list
594
+ ):
595
+ help_option_found = 0
596
+ for help_option, _short, _desc, func in cmd_class.help_options:
597
+ if hasattr(opts, parser.get_attr_name(help_option)):
598
+ help_option_found = 1
599
+ if callable(func):
600
+ func()
601
+ else:
602
+ raise DistutilsClassError(
603
+ f"invalid help function {func!r} for help option '{help_option}': "
604
+ "must be a callable object (function, etc.)"
605
+ )
606
+
607
+ if help_option_found:
608
+ return
609
+
610
+ # Put the options from the command-line into their official
611
+ # holding pen, the 'command_options' dictionary.
612
+ opt_dict = self.get_option_dict(command)
613
+ for name, value in vars(opts).items():
614
+ opt_dict[name] = ("command line", value)
615
+
616
+ return args
617
+
618
+ def finalize_options(self):
619
+ """Set final values for all the options on the Distribution
620
+ instance, analogous to the .finalize_options() method of Command
621
+ objects.
622
+ """
623
+ for attr in ('keywords', 'platforms'):
624
+ value = getattr(self.metadata, attr)
625
+ if value is None:
626
+ continue
627
+ if isinstance(value, str):
628
+ value = [elm.strip() for elm in value.split(',')]
629
+ setattr(self.metadata, attr, value)
630
+
631
+ def _show_help(
632
+ self, parser, global_options=True, display_options=True, commands: Iterable = ()
633
+ ):
634
+ """Show help for the setup script command-line in the form of
635
+ several lists of command-line options. 'parser' should be a
636
+ FancyGetopt instance; do not expect it to be returned in the
637
+ same state, as its option table will be reset to make it
638
+ generate the correct help text.
639
+
640
+ If 'global_options' is true, lists the global options:
641
+ --verbose, --dry-run, etc. If 'display_options' is true, lists
642
+ the "display-only" options: --name, --version, etc. Finally,
643
+ lists per-command help for every command name or command class
644
+ in 'commands'.
645
+ """
646
+ # late import because of mutual dependence between these modules
647
+ from distutils.cmd import Command
648
+ from distutils.core import gen_usage
649
+
650
+ if global_options:
651
+ if display_options:
652
+ options = self._get_toplevel_options()
653
+ else:
654
+ options = self.global_options
655
+ parser.set_option_table(options)
656
+ parser.print_help(self.common_usage + "\nGlobal options:")
657
+ print()
658
+
659
+ if display_options:
660
+ parser.set_option_table(self.display_options)
661
+ parser.print_help(
662
+ "Information display options (just display information, ignore any commands)"
663
+ )
664
+ print()
665
+
666
+ for command in commands:
667
+ if isinstance(command, type) and issubclass(command, Command):
668
+ klass = command
669
+ else:
670
+ klass = self.get_command_class(command)
671
+ if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
672
+ parser.set_option_table(
673
+ klass.user_options + fix_help_options(klass.help_options)
674
+ )
675
+ else:
676
+ parser.set_option_table(klass.user_options)
677
+ parser.print_help(f"Options for '{klass.__name__}' command:")
678
+ print()
679
+
680
+ print(gen_usage(self.script_name))
681
+
682
+ def handle_display_options(self, option_order):
683
+ """If there were any non-global "display-only" options
684
+ (--help-commands or the metadata display options) on the command
685
+ line, display the requested info and return true; else return
686
+ false.
687
+ """
688
+ from distutils.core import gen_usage
689
+
690
+ # User just wants a list of commands -- we'll print it out and stop
691
+ # processing now (ie. if they ran "setup --help-commands foo bar",
692
+ # we ignore "foo bar").
693
+ if self.help_commands:
694
+ self.print_commands()
695
+ print()
696
+ print(gen_usage(self.script_name))
697
+ return 1
698
+
699
+ # If user supplied any of the "display metadata" options, then
700
+ # display that metadata in the order in which the user supplied the
701
+ # metadata options.
702
+ any_display_options = 0
703
+ is_display_option = set()
704
+ for option in self.display_options:
705
+ is_display_option.add(option[0])
706
+
707
+ for opt, val in option_order:
708
+ if val and opt in is_display_option:
709
+ opt = translate_longopt(opt)
710
+ value = getattr(self.metadata, "get_" + opt)()
711
+ if opt in ('keywords', 'platforms'):
712
+ print(','.join(value))
713
+ elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
714
+ print('\n'.join(value))
715
+ else:
716
+ print(value)
717
+ any_display_options = 1
718
+
719
+ return any_display_options
720
+
721
+ def print_command_list(self, commands, header, max_length):
722
+ """Print a subset of the list of all commands -- used by
723
+ 'print_commands()'.
724
+ """
725
+ print(header + ":")
726
+
727
+ for cmd in commands:
728
+ klass = self.cmdclass.get(cmd)
729
+ if not klass:
730
+ klass = self.get_command_class(cmd)
731
+ try:
732
+ description = klass.description
733
+ except AttributeError:
734
+ description = "(no description available)"
735
+
736
+ print(f" {cmd:<{max_length}} {description}")
737
+
738
+ def print_commands(self):
739
+ """Print out a help message listing all available commands with a
740
+ description of each. The list is divided into "standard commands"
741
+ (listed in distutils.command.__all__) and "extra commands"
742
+ (mentioned in self.cmdclass, but not a standard command). The
743
+ descriptions come from the command class attribute
744
+ 'description'.
745
+ """
746
+ import distutils.command
747
+
748
+ std_commands = distutils.command.__all__
749
+ is_std = set(std_commands)
750
+
751
+ extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
752
+
753
+ max_length = 0
754
+ for cmd in std_commands + extra_commands:
755
+ if len(cmd) > max_length:
756
+ max_length = len(cmd)
757
+
758
+ self.print_command_list(std_commands, "Standard commands", max_length)
759
+ if extra_commands:
760
+ print()
761
+ self.print_command_list(extra_commands, "Extra commands", max_length)
762
+
763
+ def get_command_list(self):
764
+ """Get a list of (command, description) tuples.
765
+ The list is divided into "standard commands" (listed in
766
+ distutils.command.__all__) and "extra commands" (mentioned in
767
+ self.cmdclass, but not a standard command). The descriptions come
768
+ from the command class attribute 'description'.
769
+ """
770
+ # Currently this is only used on Mac OS, for the Mac-only GUI
771
+ # Distutils interface (by Jack Jansen)
772
+ import distutils.command
773
+
774
+ std_commands = distutils.command.__all__
775
+ is_std = set(std_commands)
776
+
777
+ extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
778
+
779
+ rv = []
780
+ for cmd in std_commands + extra_commands:
781
+ klass = self.cmdclass.get(cmd)
782
+ if not klass:
783
+ klass = self.get_command_class(cmd)
784
+ try:
785
+ description = klass.description
786
+ except AttributeError:
787
+ description = "(no description available)"
788
+ rv.append((cmd, description))
789
+ return rv
790
+
791
+ # -- Command class/object methods ----------------------------------
792
+
793
+ def get_command_packages(self):
794
+ """Return a list of packages from which commands are loaded."""
795
+ pkgs = self.command_packages
796
+ if not isinstance(pkgs, list):
797
+ if pkgs is None:
798
+ pkgs = ''
799
+ pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
800
+ if "distutils.command" not in pkgs:
801
+ pkgs.insert(0, "distutils.command")
802
+ self.command_packages = pkgs
803
+ return pkgs
804
+
805
+ def get_command_class(self, command):
806
+ """Return the class that implements the Distutils command named by
807
+ 'command'. First we check the 'cmdclass' dictionary; if the
808
+ command is mentioned there, we fetch the class object from the
809
+ dictionary and return it. Otherwise we load the command module
810
+ ("distutils.command." + command) and fetch the command class from
811
+ the module. The loaded class is also stored in 'cmdclass'
812
+ to speed future calls to 'get_command_class()'.
813
+
814
+ Raises DistutilsModuleError if the expected module could not be
815
+ found, or if that module does not define the expected class.
816
+ """
817
+ klass = self.cmdclass.get(command)
818
+ if klass:
819
+ return klass
820
+
821
+ for pkgname in self.get_command_packages():
822
+ module_name = f"{pkgname}.{command}"
823
+ klass_name = command
824
+
825
+ try:
826
+ __import__(module_name)
827
+ module = sys.modules[module_name]
828
+ except ImportError:
829
+ continue
830
+
831
+ try:
832
+ klass = getattr(module, klass_name)
833
+ except AttributeError:
834
+ raise DistutilsModuleError(
835
+ f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')"
836
+ )
837
+
838
+ self.cmdclass[command] = klass
839
+ return klass
840
+
841
+ raise DistutilsModuleError(f"invalid command '{command}'")
842
+
843
+ @overload
844
+ def get_command_obj(
845
+ self, command: str, create: Literal[True] = True
846
+ ) -> Command: ...
847
+ @overload
848
+ def get_command_obj(
849
+ self, command: str, create: Literal[False]
850
+ ) -> Command | None: ...
851
+ def get_command_obj(self, command: str, create: bool = True) -> Command | None:
852
+ """Return the command object for 'command'. Normally this object
853
+ is cached on a previous call to 'get_command_obj()'; if no command
854
+ object for 'command' is in the cache, then we either create and
855
+ return it (if 'create' is true) or return None.
856
+ """
857
+ cmd_obj = self.command_obj.get(command)
858
+ if not cmd_obj and create:
859
+ if DEBUG:
860
+ self.announce(
861
+ "Distribution.get_command_obj(): "
862
+ f"creating '{command}' command object"
863
+ )
864
+
865
+ klass = self.get_command_class(command)
866
+ cmd_obj = self.command_obj[command] = klass(self)
867
+ self.have_run[command] = False
868
+
869
+ # Set any options that were supplied in config files
870
+ # or on the command line. (NB. support for error
871
+ # reporting is lame here: any errors aren't reported
872
+ # until 'finalize_options()' is called, which means
873
+ # we won't report the source of the error.)
874
+ options = self.command_options.get(command)
875
+ if options:
876
+ self._set_command_options(cmd_obj, options)
877
+
878
+ return cmd_obj
879
+
880
+ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
881
+ """Set the options for 'command_obj' from 'option_dict'. Basically
882
+ this means copying elements of a dictionary ('option_dict') to
883
+ attributes of an instance ('command').
884
+
885
+ 'command_obj' must be a Command instance. If 'option_dict' is not
886
+ supplied, uses the standard option dictionary for this command
887
+ (from 'self.command_options').
888
+ """
889
+ command_name = command_obj.get_command_name()
890
+ if option_dict is None:
891
+ option_dict = self.get_option_dict(command_name)
892
+
893
+ if DEBUG:
894
+ self.announce(f" setting options for '{command_name}' command:")
895
+ for option, (source, value) in option_dict.items():
896
+ if DEBUG:
897
+ self.announce(f" {option} = {value} (from {source})")
898
+ try:
899
+ bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
900
+ except AttributeError:
901
+ bool_opts = []
902
+ try:
903
+ neg_opt = command_obj.negative_opt
904
+ except AttributeError:
905
+ neg_opt = {}
906
+
907
+ try:
908
+ is_string = isinstance(value, str)
909
+ if option in neg_opt and is_string:
910
+ setattr(command_obj, neg_opt[option], not strtobool(value))
911
+ elif option in bool_opts and is_string:
912
+ setattr(command_obj, option, strtobool(value))
913
+ elif hasattr(command_obj, option):
914
+ setattr(command_obj, option, value)
915
+ else:
916
+ raise DistutilsOptionError(
917
+ f"error in {source}: command '{command_name}' has no such option '{option}'"
918
+ )
919
+ except ValueError as msg:
920
+ raise DistutilsOptionError(msg)
921
+
922
+ @overload
923
+ def reinitialize_command(
924
+ self, command: str, reinit_subcommands: bool = False
925
+ ) -> Command: ...
926
+ @overload
927
+ def reinitialize_command(
928
+ self, command: _CommandT, reinit_subcommands: bool = False
929
+ ) -> _CommandT: ...
930
+ def reinitialize_command(
931
+ self, command: str | Command, reinit_subcommands=False
932
+ ) -> Command:
933
+ """Reinitializes a command to the state it was in when first
934
+ returned by 'get_command_obj()': ie., initialized but not yet
935
+ finalized. This provides the opportunity to sneak option
936
+ values in programmatically, overriding or supplementing
937
+ user-supplied values from the config files and command line.
938
+ You'll have to re-finalize the command object (by calling
939
+ 'finalize_options()' or 'ensure_finalized()') before using it for
940
+ real.
941
+
942
+ 'command' should be a command name (string) or command object. If
943
+ 'reinit_subcommands' is true, also reinitializes the command's
944
+ sub-commands, as declared by the 'sub_commands' class attribute (if
945
+ it has one). See the "install" command for an example. Only
946
+ reinitializes the sub-commands that actually matter, ie. those
947
+ whose test predicates return true.
948
+
949
+ Returns the reinitialized command object.
950
+ """
951
+ from distutils.cmd import Command
952
+
953
+ if not isinstance(command, Command):
954
+ command_name = command
955
+ command = self.get_command_obj(command_name)
956
+ else:
957
+ command_name = command.get_command_name()
958
+
959
+ if not command.finalized:
960
+ return command
961
+ command.initialize_options()
962
+ command.finalized = False
963
+ self.have_run[command_name] = False
964
+ self._set_command_options(command)
965
+
966
+ if reinit_subcommands:
967
+ for sub in command.get_sub_commands():
968
+ self.reinitialize_command(sub, reinit_subcommands)
969
+
970
+ return command
971
+
972
+ # -- Methods that operate on the Distribution ----------------------
973
+
974
+ def announce(self, msg, level=logging.INFO):
975
+ log.log(level, msg)
976
+
977
+ def run_commands(self):
978
+ """Run each command that was seen on the setup script command line.
979
+ Uses the list of commands found and cache of command objects
980
+ created by 'get_command_obj()'.
981
+ """
982
+ for cmd in self.commands:
983
+ self.run_command(cmd)
984
+
985
+ # -- Methods that operate on its Commands --------------------------
986
+
987
+ def run_command(self, command):
988
+ """Do whatever it takes to run a command (including nothing at all,
989
+ if the command has already been run). Specifically: if we have
990
+ already created and run the command named by 'command', return
991
+ silently without doing anything. If the command named by 'command'
992
+ doesn't even have a command object yet, create one. Then invoke
993
+ 'run()' on that command object (or an existing one).
994
+ """
995
+ # Already been here, done that? then return silently.
996
+ if self.have_run.get(command):
997
+ return
998
+
999
+ log.info("running %s", command)
1000
+ cmd_obj = self.get_command_obj(command)
1001
+ cmd_obj.ensure_finalized()
1002
+ cmd_obj.run()
1003
+ self.have_run[command] = True
1004
+
1005
+ # -- Distribution query methods ------------------------------------
1006
+
1007
+ def has_pure_modules(self):
1008
+ return len(self.packages or self.py_modules or []) > 0
1009
+
1010
+ def has_ext_modules(self):
1011
+ return self.ext_modules and len(self.ext_modules) > 0
1012
+
1013
+ def has_c_libraries(self):
1014
+ return self.libraries and len(self.libraries) > 0
1015
+
1016
+ def has_modules(self):
1017
+ return self.has_pure_modules() or self.has_ext_modules()
1018
+
1019
+ def has_headers(self):
1020
+ return self.headers and len(self.headers) > 0
1021
+
1022
+ def has_scripts(self):
1023
+ return self.scripts and len(self.scripts) > 0
1024
+
1025
+ def has_data_files(self):
1026
+ return self.data_files and len(self.data_files) > 0
1027
+
1028
+ def is_pure(self):
1029
+ return (
1030
+ self.has_pure_modules()
1031
+ and not self.has_ext_modules()
1032
+ and not self.has_c_libraries()
1033
+ )
1034
+
1035
+ # -- Metadata query methods ----------------------------------------
1036
+
1037
+ # If you're looking for 'get_name()', 'get_version()', and so forth,
1038
+ # they are defined in a sneaky way: the constructor binds self.get_XXX
1039
+ # to self.metadata.get_XXX. The actual code is in the
1040
+ # DistributionMetadata class, below.
1041
+
1042
+
1043
+ class DistributionMetadata:
1044
+ """Dummy class to hold the distribution meta-data: name, version,
1045
+ author, and so forth.
1046
+ """
1047
+
1048
+ _METHOD_BASENAMES = (
1049
+ "name",
1050
+ "version",
1051
+ "author",
1052
+ "author_email",
1053
+ "maintainer",
1054
+ "maintainer_email",
1055
+ "url",
1056
+ "license",
1057
+ "description",
1058
+ "long_description",
1059
+ "keywords",
1060
+ "platforms",
1061
+ "fullname",
1062
+ "contact",
1063
+ "contact_email",
1064
+ "classifiers",
1065
+ "download_url",
1066
+ # PEP 314
1067
+ "provides",
1068
+ "requires",
1069
+ "obsoletes",
1070
+ )
1071
+
1072
+ def __init__(self, path=None):
1073
+ if path is not None:
1074
+ self.read_pkg_file(open(path))
1075
+ else:
1076
+ self.name = None
1077
+ self.version = None
1078
+ self.author = None
1079
+ self.author_email = None
1080
+ self.maintainer = None
1081
+ self.maintainer_email = None
1082
+ self.url = None
1083
+ self.license = None
1084
+ self.description = None
1085
+ self.long_description = None
1086
+ self.keywords = None
1087
+ self.platforms = None
1088
+ self.classifiers = None
1089
+ self.download_url = None
1090
+ # PEP 314
1091
+ self.provides = None
1092
+ self.requires = None
1093
+ self.obsoletes = None
1094
+
1095
+ def read_pkg_file(self, file):
1096
+ """Reads the metadata values from a file object."""
1097
+ msg = message_from_file(file)
1098
+
1099
+ def _read_field(name):
1100
+ value = msg[name]
1101
+ if value and value != "UNKNOWN":
1102
+ return value
1103
+
1104
+ def _read_list(name):
1105
+ values = msg.get_all(name, None)
1106
+ if values == []:
1107
+ return None
1108
+ return values
1109
+
1110
+ metadata_version = msg['metadata-version']
1111
+ self.name = _read_field('name')
1112
+ self.version = _read_field('version')
1113
+ self.description = _read_field('summary')
1114
+ # we are filling author only.
1115
+ self.author = _read_field('author')
1116
+ self.maintainer = None
1117
+ self.author_email = _read_field('author-email')
1118
+ self.maintainer_email = None
1119
+ self.url = _read_field('home-page')
1120
+ self.license = _read_field('license')
1121
+
1122
+ if 'download-url' in msg:
1123
+ self.download_url = _read_field('download-url')
1124
+ else:
1125
+ self.download_url = None
1126
+
1127
+ self.long_description = _read_field('description')
1128
+ self.description = _read_field('summary')
1129
+
1130
+ if 'keywords' in msg:
1131
+ self.keywords = _read_field('keywords').split(',')
1132
+
1133
+ self.platforms = _read_list('platform')
1134
+ self.classifiers = _read_list('classifier')
1135
+
1136
+ # PEP 314 - these fields only exist in 1.1
1137
+ if metadata_version == '1.1':
1138
+ self.requires = _read_list('requires')
1139
+ self.provides = _read_list('provides')
1140
+ self.obsoletes = _read_list('obsoletes')
1141
+ else:
1142
+ self.requires = None
1143
+ self.provides = None
1144
+ self.obsoletes = None
1145
+
1146
+ def write_pkg_info(self, base_dir):
1147
+ """Write the PKG-INFO file into the release tree."""
1148
+ with open(
1149
+ os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
1150
+ ) as pkg_info:
1151
+ self.write_pkg_file(pkg_info)
1152
+
1153
+ def write_pkg_file(self, file):
1154
+ """Write the PKG-INFO format data to a file object."""
1155
+ version = '1.0'
1156
+ if (
1157
+ self.provides
1158
+ or self.requires
1159
+ or self.obsoletes
1160
+ or self.classifiers
1161
+ or self.download_url
1162
+ ):
1163
+ version = '1.1'
1164
+
1165
+ # required fields
1166
+ file.write(f'Metadata-Version: {version}\n')
1167
+ file.write(f'Name: {self.get_name()}\n')
1168
+ file.write(f'Version: {self.get_version()}\n')
1169
+
1170
+ def maybe_write(header, val):
1171
+ if val:
1172
+ file.write(f"{header}: {val}\n")
1173
+
1174
+ # optional fields
1175
+ maybe_write("Summary", self.get_description())
1176
+ maybe_write("Home-page", self.get_url())
1177
+ maybe_write("Author", self.get_contact())
1178
+ maybe_write("Author-email", self.get_contact_email())
1179
+ maybe_write("License", self.get_license())
1180
+ maybe_write("Download-URL", self.download_url)
1181
+ maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
1182
+ maybe_write("Keywords", ",".join(self.get_keywords()))
1183
+
1184
+ self._write_list(file, 'Platform', self.get_platforms())
1185
+ self._write_list(file, 'Classifier', self.get_classifiers())
1186
+
1187
+ # PEP 314
1188
+ self._write_list(file, 'Requires', self.get_requires())
1189
+ self._write_list(file, 'Provides', self.get_provides())
1190
+ self._write_list(file, 'Obsoletes', self.get_obsoletes())
1191
+
1192
+ def _write_list(self, file, name, values):
1193
+ values = values or []
1194
+ for value in values:
1195
+ file.write(f'{name}: {value}\n')
1196
+
1197
+ # -- Metadata query methods ----------------------------------------
1198
+
1199
+ def get_name(self):
1200
+ return self.name or "UNKNOWN"
1201
+
1202
+ def get_version(self):
1203
+ return self.version or "0.0.0"
1204
+
1205
+ def get_fullname(self):
1206
+ return self._fullname(self.get_name(), self.get_version())
1207
+
1208
+ @staticmethod
1209
+ def _fullname(name: str, version: str) -> str:
1210
+ """
1211
+ >>> DistributionMetadata._fullname('setup.tools', '1.0-2')
1212
+ 'setup_tools-1.0.post2'
1213
+ >>> DistributionMetadata._fullname('setup-tools', '1.2post2')
1214
+ 'setup_tools-1.2.post2'
1215
+ >>> DistributionMetadata._fullname('setup-tools', '1.0-r2')
1216
+ 'setup_tools-1.0.post2'
1217
+ >>> DistributionMetadata._fullname('setup.tools', '1.0.post')
1218
+ 'setup_tools-1.0.post0'
1219
+ >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1')
1220
+ 'setup_tools-1.0+ubuntu.1'
1221
+ """
1222
+ return "{}-{}".format(
1223
+ canonicalize_name(name).replace('-', '_'),
1224
+ canonicalize_version(version, strip_trailing_zero=False),
1225
+ )
1226
+
1227
+ def get_author(self):
1228
+ return self.author
1229
+
1230
+ def get_author_email(self):
1231
+ return self.author_email
1232
+
1233
+ def get_maintainer(self):
1234
+ return self.maintainer
1235
+
1236
+ def get_maintainer_email(self):
1237
+ return self.maintainer_email
1238
+
1239
+ def get_contact(self):
1240
+ return self.maintainer or self.author
1241
+
1242
+ def get_contact_email(self):
1243
+ return self.maintainer_email or self.author_email
1244
+
1245
+ def get_url(self):
1246
+ return self.url
1247
+
1248
+ def get_license(self):
1249
+ return self.license
1250
+
1251
+ get_licence = get_license
1252
+
1253
+ def get_description(self):
1254
+ return self.description
1255
+
1256
+ def get_long_description(self):
1257
+ return self.long_description
1258
+
1259
+ def get_keywords(self):
1260
+ return self.keywords or []
1261
+
1262
+ def set_keywords(self, value):
1263
+ self.keywords = _ensure_list(value, 'keywords')
1264
+
1265
+ def get_platforms(self):
1266
+ return self.platforms
1267
+
1268
+ def set_platforms(self, value):
1269
+ self.platforms = _ensure_list(value, 'platforms')
1270
+
1271
+ def get_classifiers(self):
1272
+ return self.classifiers or []
1273
+
1274
+ def set_classifiers(self, value):
1275
+ self.classifiers = _ensure_list(value, 'classifiers')
1276
+
1277
+ def get_download_url(self):
1278
+ return self.download_url
1279
+
1280
+ # PEP 314
1281
+ def get_requires(self):
1282
+ return self.requires or []
1283
+
1284
+ def set_requires(self, value):
1285
+ import distutils.versionpredicate
1286
+
1287
+ for v in value:
1288
+ distutils.versionpredicate.VersionPredicate(v)
1289
+ self.requires = list(value)
1290
+
1291
+ def get_provides(self):
1292
+ return self.provides or []
1293
+
1294
+ def set_provides(self, value):
1295
+ value = [v.strip() for v in value]
1296
+ for v in value:
1297
+ import distutils.versionpredicate
1298
+
1299
+ distutils.versionpredicate.split_provision(v)
1300
+ self.provides = value
1301
+
1302
+ def get_obsoletes(self):
1303
+ return self.obsoletes or []
1304
+
1305
+ def set_obsoletes(self, value):
1306
+ import distutils.versionpredicate
1307
+
1308
+ for v in value:
1309
+ distutils.versionpredicate.VersionPredicate(v)
1310
+ self.obsoletes = list(value)
1311
+
1312
+
1313
+ def fix_help_options(options):
1314
+ """Convert a 4-tuple 'help_options' list as found in various command
1315
+ classes to the 3-tuple form required by FancyGetopt.
1316
+ """
1317
+ return [opt[0:3] for opt in options]
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/errors.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ class DistutilsError(Exception):
10
+ """The root of all Distutils evil."""
11
+
12
+ pass
13
+
14
+
15
+ class DistutilsModuleError(DistutilsError):
16
+ """Unable to load an expected module, or to find an expected class
17
+ within some module (in particular, command modules and classes)."""
18
+
19
+ pass
20
+
21
+
22
+ class DistutilsClassError(DistutilsError):
23
+ """Some command class (or possibly distribution class, if anyone
24
+ feels a need to subclass Distribution) is found not to be holding
25
+ up its end of the bargain, ie. implementing some part of the
26
+ "command "interface."""
27
+
28
+ pass
29
+
30
+
31
+ class DistutilsGetoptError(DistutilsError):
32
+ """The option table provided to 'fancy_getopt()' is bogus."""
33
+
34
+ pass
35
+
36
+
37
+ class DistutilsArgError(DistutilsError):
38
+ """Raised by fancy_getopt in response to getopt.error -- ie. an
39
+ error in the command line usage."""
40
+
41
+ pass
42
+
43
+
44
+ class DistutilsFileError(DistutilsError):
45
+ """Any problems in the filesystem: expected file not found, etc.
46
+ Typically this is for problems that we detect before OSError
47
+ could be raised."""
48
+
49
+ pass
50
+
51
+
52
+ class DistutilsOptionError(DistutilsError):
53
+ """Syntactic/semantic errors in command options, such as use of
54
+ mutually conflicting options, or inconsistent options,
55
+ badly-spelled values, etc. No distinction is made between option
56
+ values originating in the setup script, the command line, config
57
+ files, or what-have-you -- but if we *know* something originated in
58
+ the setup script, we'll raise DistutilsSetupError instead."""
59
+
60
+ pass
61
+
62
+
63
+ class DistutilsSetupError(DistutilsError):
64
+ """For errors that can be definitely blamed on the setup script,
65
+ such as invalid keyword arguments to 'setup()'."""
66
+
67
+ pass
68
+
69
+
70
+ class DistutilsPlatformError(DistutilsError):
71
+ """We don't know how to do something on the current platform (but
72
+ we do know how to do it on some platform) -- eg. trying to compile
73
+ C files on a platform not supported by a CCompiler subclass."""
74
+
75
+ pass
76
+
77
+
78
+ class DistutilsExecError(DistutilsError):
79
+ """Any problems executing an external program (such as the C
80
+ compiler, when compiling C files)."""
81
+
82
+ pass
83
+
84
+
85
+ class DistutilsInternalError(DistutilsError):
86
+ """Internal inconsistencies or impossibilities (obviously, this
87
+ should never be seen if the code is working!)."""
88
+
89
+ pass
90
+
91
+
92
+ class DistutilsTemplateError(DistutilsError):
93
+ """Syntax error in a file list template."""
94
+
95
+
96
+ class DistutilsByteCompileError(DistutilsError):
97
+ """Byte compile error."""
98
+
99
+
100
+ # Exception classes used by the CCompiler implementation classes
101
+ class CCompilerError(Exception):
102
+ """Some compile/link operation failed."""
103
+
104
+
105
+ class PreprocessError(CCompilerError):
106
+ """Failure to preprocess one or more C/C++ files."""
107
+
108
+
109
+ class CompileError(CCompilerError):
110
+ """Failure to compile one or more C/C++ source files."""
111
+
112
+
113
+ class LibError(CCompilerError):
114
+ """Failure to create a static library from one or more C/C++ object
115
+ files."""
116
+
117
+
118
+ class LinkError(CCompilerError):
119
+ """Failure to link one or more C/C++ object files into an executable
120
+ or shared library file."""
121
+
122
+
123
+ class UnknownFileError(CCompilerError):
124
+ """Attempt to process an unknown file type."""
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/extension.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.extension
2
+
3
+ Provides the Extension class, used to describe C/C++ extension
4
+ modules in setup scripts."""
5
+
6
+ import os
7
+ import warnings
8
+
9
+ # This class is really only used by the "build_ext" command, so it might
10
+ # make sense to put it in distutils.command.build_ext. However, that
11
+ # module is already big enough, and I want to make this class a bit more
12
+ # complex to simplify some common cases ("foo" module in "foo.c") and do
13
+ # better error-checking ("foo.c" actually exists).
14
+ #
15
+ # Also, putting this in build_ext.py means every setup script would have to
16
+ # import that large-ish module (indirectly, through distutils.core) in
17
+ # order to do anything.
18
+
19
+
20
+ class Extension:
21
+ """Just a collection of attributes that describes an extension
22
+ module and everything needed to build it (hopefully in a portable
23
+ way, but there are hooks that let you be as unportable as you need).
24
+
25
+ Instance attributes:
26
+ name : string
27
+ the full name of the extension, including any packages -- ie.
28
+ *not* a filename or pathname, but Python dotted name
29
+ sources : Iterable[string | os.PathLike]
30
+ iterable of source filenames (except strings, which could be misinterpreted
31
+ as a single filename), relative to the distribution root (where the setup
32
+ script lives), in Unix form (slash-separated) for portability. Can be any
33
+ non-string iterable (list, tuple, set, etc.) containing strings or
34
+ PathLike objects. Source files may be C, C++, SWIG (.i), platform-specific
35
+ resource files, or whatever else is recognized by the "build_ext" command
36
+ as source for a Python extension.
37
+ include_dirs : [string]
38
+ list of directories to search for C/C++ header files (in Unix
39
+ form for portability)
40
+ define_macros : [(name : string, value : string|None)]
41
+ list of macros to define; each macro is defined using a 2-tuple,
42
+ where 'value' is either the string to define it to or None to
43
+ define it without a particular value (equivalent of "#define
44
+ FOO" in source or -DFOO on Unix C compiler command line)
45
+ undef_macros : [string]
46
+ list of macros to undefine explicitly
47
+ library_dirs : [string]
48
+ list of directories to search for C/C++ libraries at link time
49
+ libraries : [string]
50
+ list of library names (not filenames or paths) to link against
51
+ runtime_library_dirs : [string]
52
+ list of directories to search for C/C++ libraries at run time
53
+ (for shared extensions, this is when the extension is loaded)
54
+ extra_objects : [string]
55
+ list of extra files to link with (eg. object files not implied
56
+ by 'sources', static library that must be explicitly specified,
57
+ binary resource files, etc.)
58
+ extra_compile_args : [string]
59
+ any extra platform- and compiler-specific information to use
60
+ when compiling the source files in 'sources'. For platforms and
61
+ compilers where "command line" makes sense, this is typically a
62
+ list of command-line arguments, but for other platforms it could
63
+ be anything.
64
+ extra_link_args : [string]
65
+ any extra platform- and compiler-specific information to use
66
+ when linking object files together to create the extension (or
67
+ to create a new static Python interpreter). Similar
68
+ interpretation as for 'extra_compile_args'.
69
+ export_symbols : [string]
70
+ list of symbols to be exported from a shared extension. Not
71
+ used on all platforms, and not generally necessary for Python
72
+ extensions, which typically export exactly one symbol: "init" +
73
+ extension_name.
74
+ swig_opts : [string]
75
+ any extra options to pass to SWIG if a source file has the .i
76
+ extension.
77
+ depends : [string]
78
+ list of files that the extension depends on
79
+ language : string
80
+ extension language (i.e. "c", "c++", "objc"). Will be detected
81
+ from the source extensions if not provided.
82
+ optional : boolean
83
+ specifies that a build failure in the extension should not abort the
84
+ build process, but simply not install the failing extension.
85
+ """
86
+
87
+ # When adding arguments to this constructor, be sure to update
88
+ # setup_keywords in core.py.
89
+ def __init__(
90
+ self,
91
+ name,
92
+ sources,
93
+ include_dirs=None,
94
+ define_macros=None,
95
+ undef_macros=None,
96
+ library_dirs=None,
97
+ libraries=None,
98
+ runtime_library_dirs=None,
99
+ extra_objects=None,
100
+ extra_compile_args=None,
101
+ extra_link_args=None,
102
+ export_symbols=None,
103
+ swig_opts=None,
104
+ depends=None,
105
+ language=None,
106
+ optional=None,
107
+ **kw, # To catch unknown keywords
108
+ ):
109
+ if not isinstance(name, str):
110
+ raise TypeError("'name' must be a string")
111
+
112
+ # handle the string case first; since strings are iterable, disallow them
113
+ if isinstance(sources, str):
114
+ raise TypeError(
115
+ "'sources' must be an iterable of strings or PathLike objects, not a string"
116
+ )
117
+
118
+ # now we check if it's iterable and contains valid types
119
+ try:
120
+ self.sources = list(map(os.fspath, sources))
121
+ except TypeError:
122
+ raise TypeError(
123
+ "'sources' must be an iterable of strings or PathLike objects"
124
+ )
125
+
126
+ self.name = name
127
+ self.include_dirs = include_dirs or []
128
+ self.define_macros = define_macros or []
129
+ self.undef_macros = undef_macros or []
130
+ self.library_dirs = library_dirs or []
131
+ self.libraries = libraries or []
132
+ self.runtime_library_dirs = runtime_library_dirs or []
133
+ self.extra_objects = extra_objects or []
134
+ self.extra_compile_args = extra_compile_args or []
135
+ self.extra_link_args = extra_link_args or []
136
+ self.export_symbols = export_symbols or []
137
+ self.swig_opts = swig_opts or []
138
+ self.depends = depends or []
139
+ self.language = language
140
+ self.optional = optional
141
+
142
+ # If there are unknown keyword options, warn about them
143
+ if len(kw) > 0:
144
+ options = [repr(option) for option in kw]
145
+ options = ', '.join(sorted(options))
146
+ msg = f"Unknown Extension options: {options}"
147
+ warnings.warn(msg)
148
+
149
+ def __repr__(self):
150
+ return f'<{self.__class__.__module__}.{self.__class__.__qualname__}({self.name!r}) at {id(self):#x}>'
151
+
152
+
153
+ def read_setup_file(filename): # noqa: C901
154
+ """Reads a Setup file and returns Extension instances."""
155
+ from distutils.sysconfig import _variable_rx, expand_makefile_vars, parse_makefile
156
+ from distutils.text_file import TextFile
157
+ from distutils.util import split_quoted
158
+
159
+ # First pass over the file to gather "VAR = VALUE" assignments.
160
+ vars = parse_makefile(filename)
161
+
162
+ # Second pass to gobble up the real content: lines of the form
163
+ # <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
164
+ file = TextFile(
165
+ filename,
166
+ strip_comments=True,
167
+ skip_blanks=True,
168
+ join_lines=True,
169
+ lstrip_ws=True,
170
+ rstrip_ws=True,
171
+ )
172
+ try:
173
+ extensions = []
174
+
175
+ while True:
176
+ line = file.readline()
177
+ if line is None: # eof
178
+ break
179
+ if _variable_rx.match(line): # VAR=VALUE, handled in first pass
180
+ continue
181
+
182
+ if line[0] == line[-1] == "*":
183
+ file.warn(f"'{line}' lines not handled yet")
184
+ continue
185
+
186
+ line = expand_makefile_vars(line, vars)
187
+ words = split_quoted(line)
188
+
189
+ # NB. this parses a slightly different syntax than the old
190
+ # makesetup script: here, there must be exactly one extension per
191
+ # line, and it must be the first word of the line. I have no idea
192
+ # why the old syntax supported multiple extensions per line, as
193
+ # they all wind up being the same.
194
+
195
+ module = words[0]
196
+ ext = Extension(module, [])
197
+ append_next_word = None
198
+
199
+ for word in words[1:]:
200
+ if append_next_word is not None:
201
+ append_next_word.append(word)
202
+ append_next_word = None
203
+ continue
204
+
205
+ suffix = os.path.splitext(word)[1]
206
+ switch = word[0:2]
207
+ value = word[2:]
208
+
209
+ if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
210
+ # hmm, should we do something about C vs. C++ sources?
211
+ # or leave it up to the CCompiler implementation to
212
+ # worry about?
213
+ ext.sources.append(word)
214
+ elif switch == "-I":
215
+ ext.include_dirs.append(value)
216
+ elif switch == "-D":
217
+ equals = value.find("=")
218
+ if equals == -1: # bare "-DFOO" -- no value
219
+ ext.define_macros.append((value, None))
220
+ else: # "-DFOO=blah"
221
+ ext.define_macros.append((value[0:equals], value[equals + 2 :]))
222
+ elif switch == "-U":
223
+ ext.undef_macros.append(value)
224
+ elif switch == "-C": # only here 'cause makesetup has it!
225
+ ext.extra_compile_args.append(word)
226
+ elif switch == "-l":
227
+ ext.libraries.append(value)
228
+ elif switch == "-L":
229
+ ext.library_dirs.append(value)
230
+ elif switch == "-R":
231
+ ext.runtime_library_dirs.append(value)
232
+ elif word == "-rpath":
233
+ append_next_word = ext.runtime_library_dirs
234
+ elif word == "-Xlinker":
235
+ append_next_word = ext.extra_link_args
236
+ elif word == "-Xcompiler":
237
+ append_next_word = ext.extra_compile_args
238
+ elif switch == "-u":
239
+ ext.extra_link_args.append(word)
240
+ if not value:
241
+ append_next_word = ext.extra_link_args
242
+ elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
243
+ # NB. a really faithful emulation of makesetup would
244
+ # append a .o file to extra_objects only if it
245
+ # had a slash in it; otherwise, it would s/.o/.c/
246
+ # and append it to sources. Hmmmm.
247
+ ext.extra_objects.append(word)
248
+ else:
249
+ file.warn(f"unrecognized argument '{word}'")
250
+
251
+ extensions.append(ext)
252
+ finally:
253
+ file.close()
254
+
255
+ return extensions
evalkit_llava/lib/python3.10/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()
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/file_util.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ dry_run=False,
72
+ ):
73
+ """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
74
+ copied there with the same name; otherwise, it must be a filename. (If
75
+ the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
76
+ is true (the default), the file's mode (type and permission bits, or
77
+ whatever is analogous on the current platform) is copied. If
78
+ 'preserve_times' is true (the default), the last-modified and
79
+ last-access times are copied as well. If 'update' is true, 'src' will
80
+ only be copied if 'dst' does not exist, or if 'dst' does exist but is
81
+ older than 'src'.
82
+
83
+ 'link' allows you to make hard links (os.link) or symbolic links
84
+ (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
85
+ None (the default), files are copied. Don't set 'link' on systems that
86
+ don't support it: 'copy_file()' doesn't check if hard or symbolic
87
+ linking is available. If hardlink fails, falls back to
88
+ _copy_file_contents().
89
+
90
+ Under Mac OS, uses the native file copy function in macostools; on
91
+ other systems, uses '_copy_file_contents()' to copy file contents.
92
+
93
+ Return a tuple (dest_name, copied): 'dest_name' is the actual name of
94
+ the output file, and 'copied' is true if the file was copied (or would
95
+ have been copied, if 'dry_run' true).
96
+ """
97
+ # XXX if the destination file already exists, we clobber it if
98
+ # copying, but blow up if linking. Hmmm. And I don't know what
99
+ # macostools.copyfile() does. Should definitely be consistent, and
100
+ # should probably blow up if destination exists and we would be
101
+ # changing it (ie. it's not already a hard/soft link to src OR
102
+ # (not update) and (src newer than dst).
103
+
104
+ from distutils._modified import newer
105
+ from stat import S_IMODE, ST_ATIME, ST_MODE, ST_MTIME
106
+
107
+ if not os.path.isfile(src):
108
+ raise DistutilsFileError(
109
+ f"can't copy '{src}': doesn't exist or not a regular file"
110
+ )
111
+
112
+ if os.path.isdir(dst):
113
+ dir = dst
114
+ dst = os.path.join(dst, os.path.basename(src))
115
+ else:
116
+ dir = os.path.dirname(dst)
117
+
118
+ if update and not newer(src, dst):
119
+ if verbose >= 1:
120
+ log.debug("not copying %s (output up-to-date)", src)
121
+ return (dst, False)
122
+
123
+ try:
124
+ action = _copy_action[link]
125
+ except KeyError:
126
+ raise ValueError(f"invalid value '{link}' for 'link' argument")
127
+
128
+ if verbose >= 1:
129
+ if os.path.basename(dst) == os.path.basename(src):
130
+ log.info("%s %s -> %s", action, src, dir)
131
+ else:
132
+ log.info("%s %s -> %s", action, src, dst)
133
+
134
+ if dry_run:
135
+ return (dst, True)
136
+
137
+ # If linking (hard or symbolic), use the appropriate system call
138
+ # (Unix only, of course, but that's the caller's responsibility)
139
+ elif link == 'hard':
140
+ if not (os.path.exists(dst) and os.path.samefile(src, dst)):
141
+ try:
142
+ os.link(src, dst)
143
+ except OSError:
144
+ # If hard linking fails, fall back on copying file
145
+ # (some special filesystems don't support hard linking
146
+ # even under Unix, see issue #8876).
147
+ pass
148
+ else:
149
+ return (dst, True)
150
+ elif link == 'sym':
151
+ if not (os.path.exists(dst) and os.path.samefile(src, dst)):
152
+ os.symlink(src, dst)
153
+ return (dst, True)
154
+
155
+ # Otherwise (non-Mac, not linking), copy the file contents and
156
+ # (optionally) copy the times and mode.
157
+ _copy_file_contents(src, dst)
158
+ if preserve_mode or preserve_times:
159
+ st = os.stat(src)
160
+
161
+ # According to David Ascher <da@ski.org>, utime() should be done
162
+ # before chmod() (at least under NT).
163
+ if preserve_times:
164
+ os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
165
+ if preserve_mode:
166
+ os.chmod(dst, S_IMODE(st[ST_MODE]))
167
+
168
+ return (dst, True)
169
+
170
+
171
+ # XXX I suspect this is Unix-specific -- need porting help!
172
+ def move_file(src, dst, verbose=True, dry_run=False): # noqa: C901
173
+ """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
174
+ be moved into it with the same name; otherwise, 'src' is just renamed
175
+ to 'dst'. Return the new full name of the file.
176
+
177
+ Handles cross-device moves on Unix using 'copy_file()'. What about
178
+ other systems???
179
+ """
180
+ import errno
181
+ from os.path import basename, dirname, exists, isdir, isfile
182
+
183
+ if verbose >= 1:
184
+ log.info("moving %s -> %s", src, dst)
185
+
186
+ if dry_run:
187
+ return dst
188
+
189
+ if not isfile(src):
190
+ raise DistutilsFileError(f"can't move '{src}': not a regular file")
191
+
192
+ if isdir(dst):
193
+ dst = os.path.join(dst, basename(src))
194
+ elif exists(dst):
195
+ raise DistutilsFileError(
196
+ f"can't move '{src}': destination '{dst}' already exists"
197
+ )
198
+
199
+ if not isdir(dirname(dst)):
200
+ raise DistutilsFileError(
201
+ f"can't move '{src}': destination '{dst}' not a valid path"
202
+ )
203
+
204
+ copy_it = False
205
+ try:
206
+ os.rename(src, dst)
207
+ except OSError as e:
208
+ (num, msg) = e.args
209
+ if num == errno.EXDEV:
210
+ copy_it = True
211
+ else:
212
+ raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}")
213
+
214
+ if copy_it:
215
+ copy_file(src, dst, verbose=verbose)
216
+ try:
217
+ os.unlink(src)
218
+ except OSError as e:
219
+ (num, msg) = e.args
220
+ try:
221
+ os.unlink(dst)
222
+ except OSError:
223
+ pass
224
+ raise DistutilsFileError(
225
+ f"couldn't move '{src}' to '{dst}' by copy/delete: "
226
+ f"delete '{src}' failed: {msg}"
227
+ )
228
+ return dst
229
+
230
+
231
+ def write_file(filename, contents):
232
+ """Create a file with the specified name and write 'contents' (a
233
+ sequence of strings without line terminators) to it.
234
+ """
235
+ with open(filename, 'w', encoding='utf-8') as f:
236
+ f.writelines(line + '\n' for line in contents)
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/filelist.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.filelist
2
+
3
+ Provides the FileList class, used for poking about the filesystem
4
+ and building lists of files.
5
+ """
6
+
7
+ import fnmatch
8
+ import functools
9
+ import os
10
+ import re
11
+
12
+ from ._log import log
13
+ from .errors import DistutilsInternalError, DistutilsTemplateError
14
+ from .util import convert_path
15
+
16
+
17
+ class FileList:
18
+ """A list of files built by on exploring the filesystem and filtered by
19
+ applying various patterns to what we find there.
20
+
21
+ Instance attributes:
22
+ dir
23
+ directory from which files will be taken -- only used if
24
+ 'allfiles' not supplied to constructor
25
+ files
26
+ list of filenames currently being built/filtered/manipulated
27
+ allfiles
28
+ complete list of files under consideration (ie. without any
29
+ filtering applied)
30
+ """
31
+
32
+ def __init__(self, warn=None, debug_print=None):
33
+ # ignore argument to FileList, but keep them for backwards
34
+ # compatibility
35
+ self.allfiles = None
36
+ self.files = []
37
+
38
+ def set_allfiles(self, allfiles):
39
+ self.allfiles = allfiles
40
+
41
+ def findall(self, dir=os.curdir):
42
+ self.allfiles = findall(dir)
43
+
44
+ def debug_print(self, msg):
45
+ """Print 'msg' to stdout if the global DEBUG (taken from the
46
+ DISTUTILS_DEBUG environment variable) flag is true.
47
+ """
48
+ from distutils.debug import DEBUG
49
+
50
+ if DEBUG:
51
+ print(msg)
52
+
53
+ # Collection methods
54
+
55
+ def append(self, item):
56
+ self.files.append(item)
57
+
58
+ def extend(self, items):
59
+ self.files.extend(items)
60
+
61
+ def sort(self):
62
+ # Not a strict lexical sort!
63
+ sortable_files = sorted(map(os.path.split, self.files))
64
+ self.files = []
65
+ for sort_tuple in sortable_files:
66
+ self.files.append(os.path.join(*sort_tuple))
67
+
68
+ # Other miscellaneous utility methods
69
+
70
+ def remove_duplicates(self):
71
+ # Assumes list has been sorted!
72
+ for i in range(len(self.files) - 1, 0, -1):
73
+ if self.files[i] == self.files[i - 1]:
74
+ del self.files[i]
75
+
76
+ # "File template" methods
77
+
78
+ def _parse_template_line(self, line):
79
+ words = line.split()
80
+ action = words[0]
81
+
82
+ patterns = dir = dir_pattern = None
83
+
84
+ if action in ('include', 'exclude', 'global-include', 'global-exclude'):
85
+ if len(words) < 2:
86
+ raise DistutilsTemplateError(
87
+ f"'{action}' expects <pattern1> <pattern2> ..."
88
+ )
89
+ patterns = [convert_path(w) for w in words[1:]]
90
+ elif action in ('recursive-include', 'recursive-exclude'):
91
+ if len(words) < 3:
92
+ raise DistutilsTemplateError(
93
+ f"'{action}' expects <dir> <pattern1> <pattern2> ..."
94
+ )
95
+ dir = convert_path(words[1])
96
+ patterns = [convert_path(w) for w in words[2:]]
97
+ elif action in ('graft', 'prune'):
98
+ if len(words) != 2:
99
+ raise DistutilsTemplateError(
100
+ f"'{action}' expects a single <dir_pattern>"
101
+ )
102
+ dir_pattern = convert_path(words[1])
103
+ else:
104
+ raise DistutilsTemplateError(f"unknown action '{action}'")
105
+
106
+ return (action, patterns, dir, dir_pattern)
107
+
108
+ def process_template_line(self, line): # noqa: C901
109
+ # Parse the line: split it up, make sure the right number of words
110
+ # is there, and return the relevant words. 'action' is always
111
+ # defined: it's the first word of the line. Which of the other
112
+ # three are defined depends on the action; it'll be either
113
+ # patterns, (dir and patterns), or (dir_pattern).
114
+ (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
115
+
116
+ # OK, now we know that the action is valid and we have the
117
+ # right number of words on the line for that action -- so we
118
+ # can proceed with minimal error-checking.
119
+ if action == 'include':
120
+ self.debug_print("include " + ' '.join(patterns))
121
+ for pattern in patterns:
122
+ if not self.include_pattern(pattern, anchor=True):
123
+ log.warning("warning: no files found matching '%s'", pattern)
124
+
125
+ elif action == 'exclude':
126
+ self.debug_print("exclude " + ' '.join(patterns))
127
+ for pattern in patterns:
128
+ if not self.exclude_pattern(pattern, anchor=True):
129
+ log.warning(
130
+ "warning: no previously-included files found matching '%s'",
131
+ pattern,
132
+ )
133
+
134
+ elif action == 'global-include':
135
+ self.debug_print("global-include " + ' '.join(patterns))
136
+ for pattern in patterns:
137
+ if not self.include_pattern(pattern, anchor=False):
138
+ log.warning(
139
+ (
140
+ "warning: no files found matching '%s' "
141
+ "anywhere in distribution"
142
+ ),
143
+ pattern,
144
+ )
145
+
146
+ elif action == 'global-exclude':
147
+ self.debug_print("global-exclude " + ' '.join(patterns))
148
+ for pattern in patterns:
149
+ if not self.exclude_pattern(pattern, anchor=False):
150
+ log.warning(
151
+ (
152
+ "warning: no previously-included files matching "
153
+ "'%s' found anywhere in distribution"
154
+ ),
155
+ pattern,
156
+ )
157
+
158
+ elif action == 'recursive-include':
159
+ self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns)))
160
+ for pattern in patterns:
161
+ if not self.include_pattern(pattern, prefix=dir):
162
+ msg = "warning: no files found matching '%s' under directory '%s'"
163
+ log.warning(msg, pattern, dir)
164
+
165
+ elif action == 'recursive-exclude':
166
+ self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns)))
167
+ for pattern in patterns:
168
+ if not self.exclude_pattern(pattern, prefix=dir):
169
+ log.warning(
170
+ (
171
+ "warning: no previously-included files matching "
172
+ "'%s' found under directory '%s'"
173
+ ),
174
+ pattern,
175
+ dir,
176
+ )
177
+
178
+ elif action == 'graft':
179
+ self.debug_print("graft " + dir_pattern)
180
+ if not self.include_pattern(None, prefix=dir_pattern):
181
+ log.warning("warning: no directories found matching '%s'", dir_pattern)
182
+
183
+ elif action == 'prune':
184
+ self.debug_print("prune " + dir_pattern)
185
+ if not self.exclude_pattern(None, prefix=dir_pattern):
186
+ log.warning(
187
+ ("no previously-included directories found matching '%s'"),
188
+ dir_pattern,
189
+ )
190
+ else:
191
+ raise DistutilsInternalError(
192
+ f"this cannot happen: invalid action '{action}'"
193
+ )
194
+
195
+ # Filtering/selection methods
196
+
197
+ def include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False):
198
+ """Select strings (presumably filenames) from 'self.files' that
199
+ match 'pattern', a Unix-style wildcard (glob) pattern. Patterns
200
+ are not quite the same as implemented by the 'fnmatch' module: '*'
201
+ and '?' match non-special characters, where "special" is platform-
202
+ dependent: slash on Unix; colon, slash, and backslash on
203
+ DOS/Windows; and colon on Mac OS.
204
+
205
+ If 'anchor' is true (the default), then the pattern match is more
206
+ stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
207
+ 'anchor' is false, both of these will match.
208
+
209
+ If 'prefix' is supplied, then only filenames starting with 'prefix'
210
+ (itself a pattern) and ending with 'pattern', with anything in between
211
+ them, will match. 'anchor' is ignored in this case.
212
+
213
+ If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
214
+ 'pattern' is assumed to be either a string containing a regex or a
215
+ regex object -- no translation is done, the regex is just compiled
216
+ and used as-is.
217
+
218
+ Selected strings will be added to self.files.
219
+
220
+ Return True if files are found, False otherwise.
221
+ """
222
+ # XXX docstring lying about what the special chars are?
223
+ files_found = False
224
+ pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
225
+ self.debug_print(f"include_pattern: applying regex r'{pattern_re.pattern}'")
226
+
227
+ # delayed loading of allfiles list
228
+ if self.allfiles is None:
229
+ self.findall()
230
+
231
+ for name in self.allfiles:
232
+ if pattern_re.search(name):
233
+ self.debug_print(" adding " + name)
234
+ self.files.append(name)
235
+ files_found = True
236
+ return files_found
237
+
238
+ def exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False):
239
+ """Remove strings (presumably filenames) from 'files' that match
240
+ 'pattern'. Other parameters are the same as for
241
+ 'include_pattern()', above.
242
+ The list 'self.files' is modified in place.
243
+ Return True if files are found, False otherwise.
244
+ """
245
+ files_found = False
246
+ pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
247
+ self.debug_print(f"exclude_pattern: applying regex r'{pattern_re.pattern}'")
248
+ for i in range(len(self.files) - 1, -1, -1):
249
+ if pattern_re.search(self.files[i]):
250
+ self.debug_print(" removing " + self.files[i])
251
+ del self.files[i]
252
+ files_found = True
253
+ return files_found
254
+
255
+
256
+ # Utility functions
257
+
258
+
259
+ def _find_all_simple(path):
260
+ """
261
+ Find all files under 'path'
262
+ """
263
+ all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))
264
+ results = (
265
+ os.path.join(base, file) for base, dirs, files in all_unique for file in files
266
+ )
267
+ return filter(os.path.isfile, results)
268
+
269
+
270
+ class _UniqueDirs(set):
271
+ """
272
+ Exclude previously-seen dirs from walk results,
273
+ avoiding infinite recursion.
274
+ Ref https://bugs.python.org/issue44497.
275
+ """
276
+
277
+ def __call__(self, walk_item):
278
+ """
279
+ Given an item from an os.walk result, determine
280
+ if the item represents a unique dir for this instance
281
+ and if not, prevent further traversal.
282
+ """
283
+ base, dirs, files = walk_item
284
+ stat = os.stat(base)
285
+ candidate = stat.st_dev, stat.st_ino
286
+ found = candidate in self
287
+ if found:
288
+ del dirs[:]
289
+ self.add(candidate)
290
+ return not found
291
+
292
+ @classmethod
293
+ def filter(cls, items):
294
+ return filter(cls(), items)
295
+
296
+
297
+ def findall(dir=os.curdir):
298
+ """
299
+ Find all files under 'dir' and return the list of full filenames.
300
+ Unless dir is '.', return full filenames with dir prepended.
301
+ """
302
+ files = _find_all_simple(dir)
303
+ if dir == os.curdir:
304
+ make_rel = functools.partial(os.path.relpath, start=dir)
305
+ files = map(make_rel, files)
306
+ return list(files)
307
+
308
+
309
+ def glob_to_re(pattern):
310
+ """Translate a shell-like glob pattern to a regular expression; return
311
+ a string containing the regex. Differs from 'fnmatch.translate()' in
312
+ that '*' does not match "special characters" (which are
313
+ platform-specific).
314
+ """
315
+ pattern_re = fnmatch.translate(pattern)
316
+
317
+ # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
318
+ # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
319
+ # and by extension they shouldn't match such "special characters" under
320
+ # any OS. So change all non-escaped dots in the RE to match any
321
+ # character except the special characters (currently: just os.sep).
322
+ sep = os.sep
323
+ if os.sep == '\\':
324
+ # we're using a regex to manipulate a regex, so we need
325
+ # to escape the backslash twice
326
+ sep = r'\\\\'
327
+ escaped = rf'\1[^{sep}]'
328
+ pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
329
+ return pattern_re
330
+
331
+
332
+ def translate_pattern(pattern, anchor=True, prefix=None, is_regex=False):
333
+ """Translate a shell-like wildcard pattern to a compiled regular
334
+ expression. Return the compiled regex. If 'is_regex' true,
335
+ then 'pattern' is directly compiled to a regex (if it's a string)
336
+ or just returned as-is (assumes it's a regex object).
337
+ """
338
+ if is_regex:
339
+ if isinstance(pattern, str):
340
+ return re.compile(pattern)
341
+ else:
342
+ return pattern
343
+
344
+ # ditch start and end characters
345
+ start, _, end = glob_to_re('_').partition('_')
346
+
347
+ if pattern:
348
+ pattern_re = glob_to_re(pattern)
349
+ assert pattern_re.startswith(start) and pattern_re.endswith(end)
350
+ else:
351
+ pattern_re = ''
352
+
353
+ if prefix is not None:
354
+ prefix_re = glob_to_re(prefix)
355
+ assert prefix_re.startswith(start) and prefix_re.endswith(end)
356
+ prefix_re = prefix_re[len(start) : len(prefix_re) - len(end)]
357
+ sep = os.sep
358
+ if os.sep == '\\':
359
+ sep = r'\\'
360
+ pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]
361
+ pattern_re = rf'{start}\A{prefix_re}{sep}.*{pattern_re}{end}'
362
+ else: # no prefix -- respect anchor flag
363
+ if anchor:
364
+ pattern_re = rf'{start}\A{pattern_re[len(start) :]}'
365
+
366
+ return re.compile(pattern_re)
evalkit_llava/lib/python3.10/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
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/spawn.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
16
+
17
+ from ._log import log
18
+ from .debug import DEBUG
19
+ from .errors import DistutilsExecError
20
+
21
+
22
+ def _debug(cmd):
23
+ """
24
+ Render a subprocess command differently depending on DEBUG.
25
+ """
26
+ return cmd if DEBUG else cmd[0]
27
+
28
+
29
+ def _inject_macos_ver(env: Mapping[str:str] | None) -> Mapping[str:str] | None:
30
+ if platform.system() != 'Darwin':
31
+ return env
32
+
33
+ from .util import MACOSX_VERSION_VAR, get_macosx_target_ver
34
+
35
+ target_ver = get_macosx_target_ver()
36
+ update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {}
37
+ return {**_resolve(env), **update}
38
+
39
+
40
+ def _resolve(env: Mapping[str:str] | None) -> Mapping[str:str]:
41
+ return os.environ if env is None else env
42
+
43
+
44
+ def spawn(cmd, search_path=True, verbose=False, dry_run=False, env=None):
45
+ """Run another program, specified as a command list 'cmd', in a new process.
46
+
47
+ 'cmd' is just the argument list for the new process, ie.
48
+ cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
49
+ There is no way to run a program with a name different from that of its
50
+ executable.
51
+
52
+ If 'search_path' is true (the default), the system's executable
53
+ search path will be used to find the program; otherwise, cmd[0]
54
+ must be the exact path to the executable. If 'dry_run' is true,
55
+ the command will not actually be run.
56
+
57
+ Raise DistutilsExecError if running the program fails in any way; just
58
+ return on success.
59
+ """
60
+ log.info(subprocess.list2cmdline(cmd))
61
+ if dry_run:
62
+ return
63
+
64
+ if search_path:
65
+ executable = shutil.which(cmd[0])
66
+ if executable is not None:
67
+ cmd[0] = executable
68
+
69
+ try:
70
+ subprocess.check_call(cmd, env=_inject_macos_ver(env))
71
+ except OSError as exc:
72
+ raise DistutilsExecError(
73
+ f"command {_debug(cmd)!r} failed: {exc.args[-1]}"
74
+ ) from exc
75
+ except subprocess.CalledProcessError as err:
76
+ raise DistutilsExecError(
77
+ f"command {_debug(cmd)!r} failed with exit code {err.returncode}"
78
+ ) from err
79
+
80
+
81
+ def find_executable(executable, path=None):
82
+ """Tries to find 'executable' in the directories listed in 'path'.
83
+
84
+ A string listing directories separated by 'os.pathsep'; defaults to
85
+ os.environ['PATH']. Returns the complete filename or None if not found.
86
+ """
87
+ warnings.warn(
88
+ 'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2
89
+ )
90
+ _, ext = os.path.splitext(executable)
91
+ if (sys.platform == 'win32') and (ext != '.exe'):
92
+ executable = executable + '.exe'
93
+
94
+ if os.path.isfile(executable):
95
+ return executable
96
+
97
+ if path is None:
98
+ path = os.environ.get('PATH', None)
99
+ # bpo-35755: Don't fall through if PATH is the empty string
100
+ if path is None:
101
+ try:
102
+ path = os.confstr("CS_PATH")
103
+ except (AttributeError, ValueError):
104
+ # os.confstr() or CS_PATH is not available
105
+ path = os.defpath
106
+
107
+ # PATH='' doesn't match, whereas PATH=':' looks in the current directory
108
+ if not path:
109
+ return None
110
+
111
+ paths = path.split(os.pathsep)
112
+ for p in paths:
113
+ f = os.path.join(p, executable)
114
+ if os.path.isfile(f):
115
+ # the file exists, we have a shot at spawn working
116
+ return f
117
+ return None
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/sysconfig.py ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import functools
13
+ import os
14
+ import pathlib
15
+ import re
16
+ import sys
17
+ import sysconfig
18
+
19
+ from jaraco.functools import pass_none
20
+
21
+ from .compat import py39
22
+ from .errors import DistutilsPlatformError
23
+ from .util import is_mingw
24
+
25
+ IS_PYPY = '__pypy__' in sys.builtin_module_names
26
+
27
+ # These are needed in a couple of spots, so just compute them once.
28
+ PREFIX = os.path.normpath(sys.prefix)
29
+ EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
30
+ BASE_PREFIX = os.path.normpath(sys.base_prefix)
31
+ BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
32
+
33
+ # Path to the base directory of the project. On Windows the binary may
34
+ # live in project/PCbuild/win32 or project/PCbuild/amd64.
35
+ # set for cross builds
36
+ if "_PYTHON_PROJECT_BASE" in os.environ:
37
+ project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
38
+ else:
39
+ if sys.executable:
40
+ project_base = os.path.dirname(os.path.abspath(sys.executable))
41
+ else:
42
+ # sys.executable can be empty if argv[0] has been changed and Python is
43
+ # unable to retrieve the real program name
44
+ project_base = os.getcwd()
45
+
46
+
47
+ def _is_python_source_dir(d):
48
+ """
49
+ Return True if the target directory appears to point to an
50
+ un-installed Python.
51
+ """
52
+ modules = pathlib.Path(d).joinpath('Modules')
53
+ return any(modules.joinpath(fn).is_file() for fn in ('Setup', 'Setup.local'))
54
+
55
+
56
+ _sys_home = getattr(sys, '_home', None)
57
+
58
+
59
+ def _is_parent(dir_a, dir_b):
60
+ """
61
+ Return True if a is a parent of b.
62
+ """
63
+ return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b))
64
+
65
+
66
+ if os.name == 'nt':
67
+
68
+ @pass_none
69
+ def _fix_pcbuild(d):
70
+ # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX.
71
+ prefixes = PREFIX, BASE_PREFIX
72
+ matched = (
73
+ prefix
74
+ for prefix in prefixes
75
+ if _is_parent(d, os.path.join(prefix, "PCbuild"))
76
+ )
77
+ return next(matched, d)
78
+
79
+ project_base = _fix_pcbuild(project_base)
80
+ _sys_home = _fix_pcbuild(_sys_home)
81
+
82
+
83
+ def _python_build():
84
+ if _sys_home:
85
+ return _is_python_source_dir(_sys_home)
86
+ return _is_python_source_dir(project_base)
87
+
88
+
89
+ python_build = _python_build()
90
+
91
+
92
+ # Calculate the build qualifier flags if they are defined. Adding the flags
93
+ # to the include and lib directories only makes sense for an installation, not
94
+ # an in-source build.
95
+ build_flags = ''
96
+ try:
97
+ if not python_build:
98
+ build_flags = sys.abiflags
99
+ except AttributeError:
100
+ # It's not a configure-based build, so the sys module doesn't have
101
+ # this attribute, which is fine.
102
+ pass
103
+
104
+
105
+ def get_python_version():
106
+ """Return a string containing the major and minor Python version,
107
+ leaving off the patchlevel. Sample return values could be '1.5'
108
+ or '2.2'.
109
+ """
110
+ return f'{sys.version_info.major}.{sys.version_info.minor}'
111
+
112
+
113
+ def get_python_inc(plat_specific=False, prefix=None):
114
+ """Return the directory containing installed Python header files.
115
+
116
+ If 'plat_specific' is false (the default), this is the path to the
117
+ non-platform-specific header files, i.e. Python.h and so on;
118
+ otherwise, this is the path to platform-specific header files
119
+ (namely pyconfig.h).
120
+
121
+ If 'prefix' is supplied, use it instead of sys.base_prefix or
122
+ sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
123
+ """
124
+ default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX
125
+ resolved_prefix = prefix if prefix is not None else default_prefix
126
+ # MinGW imitates posix like layout, but os.name != posix
127
+ os_name = "posix" if is_mingw() else os.name
128
+ try:
129
+ getter = globals()[f'_get_python_inc_{os_name}']
130
+ except KeyError:
131
+ raise DistutilsPlatformError(
132
+ "I don't know where Python installs its C header files "
133
+ f"on platform '{os.name}'"
134
+ )
135
+ return getter(resolved_prefix, prefix, plat_specific)
136
+
137
+
138
+ @pass_none
139
+ def _extant(path):
140
+ """
141
+ Replace path with None if it doesn't exist.
142
+ """
143
+ return path if os.path.exists(path) else None
144
+
145
+
146
+ def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
147
+ if IS_PYPY and sys.version_info < (3, 8):
148
+ return os.path.join(prefix, 'include')
149
+ return (
150
+ _get_python_inc_posix_python(plat_specific)
151
+ or _extant(_get_python_inc_from_config(plat_specific, spec_prefix))
152
+ or _get_python_inc_posix_prefix(prefix)
153
+ )
154
+
155
+
156
+ def _get_python_inc_posix_python(plat_specific):
157
+ """
158
+ Assume the executable is in the build directory. The
159
+ pyconfig.h file should be in the same directory. Since
160
+ the build directory may not be the source directory,
161
+ use "srcdir" from the makefile to find the "Include"
162
+ directory.
163
+ """
164
+ if not python_build:
165
+ return
166
+ if plat_specific:
167
+ return _sys_home or project_base
168
+ incdir = os.path.join(get_config_var('srcdir'), 'Include')
169
+ return os.path.normpath(incdir)
170
+
171
+
172
+ def _get_python_inc_from_config(plat_specific, spec_prefix):
173
+ """
174
+ If no prefix was explicitly specified, provide the include
175
+ directory from the config vars. Useful when
176
+ cross-compiling, since the config vars may come from
177
+ the host
178
+ platform Python installation, while the current Python
179
+ executable is from the build platform installation.
180
+
181
+ >>> monkeypatch = getfixture('monkeypatch')
182
+ >>> gpifc = _get_python_inc_from_config
183
+ >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower)
184
+ >>> gpifc(False, '/usr/bin/')
185
+ >>> gpifc(False, '')
186
+ >>> gpifc(False, None)
187
+ 'includepy'
188
+ >>> gpifc(True, None)
189
+ 'confincludepy'
190
+ """
191
+ if spec_prefix is None:
192
+ return get_config_var('CONF' * plat_specific + 'INCLUDEPY')
193
+
194
+
195
+ def _get_python_inc_posix_prefix(prefix):
196
+ implementation = 'pypy' if IS_PYPY else 'python'
197
+ python_dir = implementation + get_python_version() + build_flags
198
+ return os.path.join(prefix, "include", python_dir)
199
+
200
+
201
+ def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
202
+ if python_build:
203
+ # Include both include dirs to ensure we can find pyconfig.h
204
+ return (
205
+ os.path.join(prefix, "include")
206
+ + os.path.pathsep
207
+ + os.path.dirname(sysconfig.get_config_h_filename())
208
+ )
209
+ return os.path.join(prefix, "include")
210
+
211
+
212
+ # allow this behavior to be monkey-patched. Ref pypa/distutils#2.
213
+ def _posix_lib(standard_lib, libpython, early_prefix, prefix):
214
+ if standard_lib:
215
+ return libpython
216
+ else:
217
+ return os.path.join(libpython, "site-packages")
218
+
219
+
220
+ def get_python_lib(plat_specific=False, standard_lib=False, prefix=None):
221
+ """Return the directory containing the Python library (standard or
222
+ site additions).
223
+
224
+ If 'plat_specific' is true, return the directory containing
225
+ platform-specific modules, i.e. any module from a non-pure-Python
226
+ module distribution; otherwise, return the platform-shared library
227
+ directory. If 'standard_lib' is true, return the directory
228
+ containing standard Python library modules; otherwise, return the
229
+ directory for site-specific modules.
230
+
231
+ If 'prefix' is supplied, use it instead of sys.base_prefix or
232
+ sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
233
+ """
234
+
235
+ if IS_PYPY and sys.version_info < (3, 8):
236
+ # PyPy-specific schema
237
+ if prefix is None:
238
+ prefix = PREFIX
239
+ if standard_lib:
240
+ return os.path.join(prefix, "lib-python", sys.version_info.major)
241
+ return os.path.join(prefix, 'site-packages')
242
+
243
+ early_prefix = prefix
244
+
245
+ if prefix is None:
246
+ if standard_lib:
247
+ prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
248
+ else:
249
+ prefix = plat_specific and EXEC_PREFIX or PREFIX
250
+
251
+ if os.name == "posix" or is_mingw():
252
+ if plat_specific or standard_lib:
253
+ # Platform-specific modules (any module from a non-pure-Python
254
+ # module distribution) or standard Python library modules.
255
+ libdir = getattr(sys, "platlibdir", "lib")
256
+ else:
257
+ # Pure Python
258
+ libdir = "lib"
259
+ implementation = 'pypy' if IS_PYPY else 'python'
260
+ libpython = os.path.join(prefix, libdir, implementation + get_python_version())
261
+ return _posix_lib(standard_lib, libpython, early_prefix, prefix)
262
+ elif os.name == "nt":
263
+ if standard_lib:
264
+ return os.path.join(prefix, "Lib")
265
+ else:
266
+ return os.path.join(prefix, "Lib", "site-packages")
267
+ else:
268
+ raise DistutilsPlatformError(
269
+ f"I don't know where Python installs its library on platform '{os.name}'"
270
+ )
271
+
272
+
273
+ @functools.lru_cache
274
+ def _customize_macos():
275
+ """
276
+ Perform first-time customization of compiler-related
277
+ config vars on macOS. Use after a compiler is known
278
+ to be needed. This customization exists primarily to support Pythons
279
+ from binary installers. The kind and paths to build tools on
280
+ the user system may vary significantly from the system
281
+ that Python itself was built on. Also the user OS
282
+ version and build tools may not support the same set
283
+ of CPU architectures for universal builds.
284
+ """
285
+
286
+ sys.platform == "darwin" and __import__('_osx_support').customize_compiler(
287
+ get_config_vars()
288
+ )
289
+
290
+
291
+ def customize_compiler(compiler):
292
+ """Do any platform-specific customization of a CCompiler instance.
293
+
294
+ Mainly needed on Unix, so we can plug in the information that
295
+ varies across Unices and is stored in Python's Makefile.
296
+ """
297
+ if compiler.compiler_type in ["unix", "cygwin"] or (
298
+ compiler.compiler_type == "mingw32" and is_mingw()
299
+ ):
300
+ _customize_macos()
301
+
302
+ (
303
+ cc,
304
+ cxx,
305
+ cflags,
306
+ ccshared,
307
+ ldshared,
308
+ ldcxxshared,
309
+ shlib_suffix,
310
+ ar,
311
+ ar_flags,
312
+ ) = get_config_vars(
313
+ 'CC',
314
+ 'CXX',
315
+ 'CFLAGS',
316
+ 'CCSHARED',
317
+ 'LDSHARED',
318
+ 'LDCXXSHARED',
319
+ 'SHLIB_SUFFIX',
320
+ 'AR',
321
+ 'ARFLAGS',
322
+ )
323
+
324
+ cxxflags = cflags
325
+
326
+ if 'CC' in os.environ:
327
+ newcc = os.environ['CC']
328
+ if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
329
+ # If CC is overridden, use that as the default
330
+ # command for LDSHARED as well
331
+ ldshared = newcc + ldshared[len(cc) :]
332
+ cc = newcc
333
+ cxx = os.environ.get('CXX', cxx)
334
+ ldshared = os.environ.get('LDSHARED', ldshared)
335
+ ldcxxshared = os.environ.get('LDCXXSHARED', ldcxxshared)
336
+ cpp = os.environ.get(
337
+ 'CPP',
338
+ cc + " -E", # not always
339
+ )
340
+
341
+ ldshared = _add_flags(ldshared, 'LD')
342
+ ldcxxshared = _add_flags(ldcxxshared, 'LD')
343
+ cflags = os.environ.get('CFLAGS', cflags)
344
+ ldshared = _add_flags(ldshared, 'C')
345
+ cxxflags = os.environ.get('CXXFLAGS', cxxflags)
346
+ ldcxxshared = _add_flags(ldcxxshared, 'CXX')
347
+ cpp = _add_flags(cpp, 'CPP')
348
+ cflags = _add_flags(cflags, 'CPP')
349
+ cxxflags = _add_flags(cxxflags, 'CPP')
350
+ ldshared = _add_flags(ldshared, 'CPP')
351
+ ldcxxshared = _add_flags(ldcxxshared, 'CPP')
352
+
353
+ ar = os.environ.get('AR', ar)
354
+
355
+ archiver = ar + ' ' + os.environ.get('ARFLAGS', ar_flags)
356
+ cc_cmd = cc + ' ' + cflags
357
+ cxx_cmd = cxx + ' ' + cxxflags
358
+
359
+ compiler.set_executables(
360
+ preprocessor=cpp,
361
+ compiler=cc_cmd,
362
+ compiler_so=cc_cmd + ' ' + ccshared,
363
+ compiler_cxx=cxx_cmd,
364
+ compiler_so_cxx=cxx_cmd + ' ' + ccshared,
365
+ linker_so=ldshared,
366
+ linker_so_cxx=ldcxxshared,
367
+ linker_exe=cc,
368
+ linker_exe_cxx=cxx,
369
+ archiver=archiver,
370
+ )
371
+
372
+ if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
373
+ compiler.set_executables(ranlib=os.environ['RANLIB'])
374
+
375
+ compiler.shared_lib_extension = shlib_suffix
376
+
377
+
378
+ def get_config_h_filename():
379
+ """Return full pathname of installed pyconfig.h file."""
380
+ return sysconfig.get_config_h_filename()
381
+
382
+
383
+ def get_makefile_filename():
384
+ """Return full pathname of installed Makefile from the Python build."""
385
+ return sysconfig.get_makefile_filename()
386
+
387
+
388
+ def parse_config_h(fp, g=None):
389
+ """Parse a config.h-style file.
390
+
391
+ A dictionary containing name/value pairs is returned. If an
392
+ optional dictionary is passed in as the second argument, it is
393
+ used instead of a new dictionary.
394
+ """
395
+ return sysconfig.parse_config_h(fp, vars=g)
396
+
397
+
398
+ # Regexes needed for parsing Makefile (and similar syntaxes,
399
+ # like old-style Setup files).
400
+ _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
401
+ _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
402
+ _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
403
+
404
+
405
+ def parse_makefile(fn, g=None): # noqa: C901
406
+ """Parse a Makefile-style file.
407
+
408
+ A dictionary containing name/value pairs is returned. If an
409
+ optional dictionary is passed in as the second argument, it is
410
+ used instead of a new dictionary.
411
+ """
412
+ from distutils.text_file import TextFile
413
+
414
+ fp = TextFile(
415
+ fn,
416
+ strip_comments=True,
417
+ skip_blanks=True,
418
+ join_lines=True,
419
+ errors="surrogateescape",
420
+ )
421
+
422
+ if g is None:
423
+ g = {}
424
+ done = {}
425
+ notdone = {}
426
+
427
+ while True:
428
+ line = fp.readline()
429
+ if line is None: # eof
430
+ break
431
+ m = _variable_rx.match(line)
432
+ if m:
433
+ n, v = m.group(1, 2)
434
+ v = v.strip()
435
+ # `$$' is a literal `$' in make
436
+ tmpv = v.replace('$$', '')
437
+
438
+ if "$" in tmpv:
439
+ notdone[n] = v
440
+ else:
441
+ try:
442
+ v = int(v)
443
+ except ValueError:
444
+ # insert literal `$'
445
+ done[n] = v.replace('$$', '$')
446
+ else:
447
+ done[n] = v
448
+
449
+ # Variables with a 'PY_' prefix in the makefile. These need to
450
+ # be made available without that prefix through sysconfig.
451
+ # Special care is needed to ensure that variable expansion works, even
452
+ # if the expansion uses the name without a prefix.
453
+ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
454
+
455
+ # do variable interpolation here
456
+ while notdone:
457
+ for name in list(notdone):
458
+ value = notdone[name]
459
+ m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
460
+ if m:
461
+ n = m.group(1)
462
+ found = True
463
+ if n in done:
464
+ item = str(done[n])
465
+ elif n in notdone:
466
+ # get it on a subsequent round
467
+ found = False
468
+ elif n in os.environ:
469
+ # do it like make: fall back to environment
470
+ item = os.environ[n]
471
+
472
+ elif n in renamed_variables:
473
+ if name.startswith('PY_') and name[3:] in renamed_variables:
474
+ item = ""
475
+
476
+ elif 'PY_' + n in notdone:
477
+ found = False
478
+
479
+ else:
480
+ item = str(done['PY_' + n])
481
+ else:
482
+ done[n] = item = ""
483
+ if found:
484
+ after = value[m.end() :]
485
+ value = value[: m.start()] + item + after
486
+ if "$" in after:
487
+ notdone[name] = value
488
+ else:
489
+ try:
490
+ value = int(value)
491
+ except ValueError:
492
+ done[name] = value.strip()
493
+ else:
494
+ done[name] = value
495
+ del notdone[name]
496
+
497
+ if name.startswith('PY_') and name[3:] in renamed_variables:
498
+ name = name[3:]
499
+ if name not in done:
500
+ done[name] = value
501
+ else:
502
+ # bogus variable reference; just drop it since we can't deal
503
+ del notdone[name]
504
+
505
+ fp.close()
506
+
507
+ # strip spurious spaces
508
+ for k, v in done.items():
509
+ if isinstance(v, str):
510
+ done[k] = v.strip()
511
+
512
+ # save the results in the global dictionary
513
+ g.update(done)
514
+ return g
515
+
516
+
517
+ def expand_makefile_vars(s, vars):
518
+ """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
519
+ 'string' according to 'vars' (a dictionary mapping variable names to
520
+ values). Variables not present in 'vars' are silently expanded to the
521
+ empty string. The variable values in 'vars' should not contain further
522
+ variable expansions; if 'vars' is the output of 'parse_makefile()',
523
+ you're fine. Returns a variable-expanded version of 's'.
524
+ """
525
+
526
+ # This algorithm does multiple expansion, so if vars['foo'] contains
527
+ # "${bar}", it will expand ${foo} to ${bar}, and then expand
528
+ # ${bar}... and so forth. This is fine as long as 'vars' comes from
529
+ # 'parse_makefile()', which takes care of such expansions eagerly,
530
+ # according to make's variable expansion semantics.
531
+
532
+ while True:
533
+ m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
534
+ if m:
535
+ (beg, end) = m.span()
536
+ s = s[0:beg] + vars.get(m.group(1)) + s[end:]
537
+ else:
538
+ break
539
+ return s
540
+
541
+
542
+ _config_vars = None
543
+
544
+
545
+ def get_config_vars(*args):
546
+ """With no arguments, return a dictionary of all configuration
547
+ variables relevant for the current platform. Generally this includes
548
+ everything needed to build extensions and install both pure modules and
549
+ extensions. On Unix, this means every variable defined in Python's
550
+ installed Makefile; on Windows it's a much smaller set.
551
+
552
+ With arguments, return a list of values that result from looking up
553
+ each argument in the configuration variable dictionary.
554
+ """
555
+ global _config_vars
556
+ if _config_vars is None:
557
+ _config_vars = sysconfig.get_config_vars().copy()
558
+ py39.add_ext_suffix(_config_vars)
559
+
560
+ return [_config_vars.get(name) for name in args] if args else _config_vars
561
+
562
+
563
+ def get_config_var(name):
564
+ """Return the value of a single variable using the dictionary
565
+ returned by 'get_config_vars()'. Equivalent to
566
+ get_config_vars().get(name)
567
+ """
568
+ if name == 'SO':
569
+ import warnings
570
+
571
+ warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
572
+ return get_config_vars().get(name)
573
+
574
+
575
+ @pass_none
576
+ def _add_flags(value: str, type: str) -> str:
577
+ """
578
+ Add any flags from the environment for the given type.
579
+
580
+ type is the prefix to FLAGS in the environment key (e.g. "C" for "CFLAGS").
581
+ """
582
+ flags = os.environ.get(f'{type}FLAGS')
583
+ return f'{value} {flags}' if flags else value
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test suite for distutils.
3
+
4
+ Tests for the command classes in the distutils.command package are
5
+ included in distutils.tests as well, instead of using a separate
6
+ distutils.command.tests package, since command identification is done
7
+ by import rather than matching pre-defined names.
8
+ """
9
+
10
+ import shutil
11
+ from collections.abc import Sequence
12
+
13
+
14
+ def missing_compiler_executable(cmd_names: Sequence[str] = []): # pragma: no cover
15
+ """Check if the compiler components used to build the interpreter exist.
16
+
17
+ Check for the existence of the compiler executables whose names are listed
18
+ in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
19
+ and return the first missing executable or None when none is found
20
+ missing.
21
+
22
+ """
23
+ from distutils import ccompiler, errors, sysconfig
24
+
25
+ compiler = ccompiler.new_compiler()
26
+ sysconfig.customize_compiler(compiler)
27
+ if compiler.compiler_type == "msvc":
28
+ # MSVC has no executables, so check whether initialization succeeds
29
+ try:
30
+ compiler.initialize()
31
+ except errors.DistutilsPlatformError:
32
+ return "msvc"
33
+ for name in compiler.executables:
34
+ if cmd_names and name not in cmd_names:
35
+ continue
36
+ cmd = getattr(compiler, name)
37
+ if cmd_names:
38
+ assert cmd is not None, f"the '{name}' executable is not configured"
39
+ elif not cmd:
40
+ continue
41
+ if shutil.which(cmd[0]) is None:
42
+ return cmd[0]
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_cmd.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.cmd."""
2
+
3
+ import os
4
+ from distutils import debug
5
+ from distutils.cmd import Command
6
+ from distutils.dist import Distribution
7
+ from distutils.errors import DistutilsOptionError
8
+
9
+ import pytest
10
+
11
+
12
+ class MyCmd(Command):
13
+ def initialize_options(self):
14
+ pass
15
+
16
+
17
+ @pytest.fixture
18
+ def cmd(request):
19
+ return MyCmd(Distribution())
20
+
21
+
22
+ class TestCommand:
23
+ def test_ensure_string_list(self, cmd):
24
+ cmd.not_string_list = ['one', 2, 'three']
25
+ cmd.yes_string_list = ['one', 'two', 'three']
26
+ cmd.not_string_list2 = object()
27
+ cmd.yes_string_list2 = 'ok'
28
+ cmd.ensure_string_list('yes_string_list')
29
+ cmd.ensure_string_list('yes_string_list2')
30
+
31
+ with pytest.raises(DistutilsOptionError):
32
+ cmd.ensure_string_list('not_string_list')
33
+
34
+ with pytest.raises(DistutilsOptionError):
35
+ cmd.ensure_string_list('not_string_list2')
36
+
37
+ cmd.option1 = 'ok,dok'
38
+ cmd.ensure_string_list('option1')
39
+ assert cmd.option1 == ['ok', 'dok']
40
+
41
+ cmd.option2 = ['xxx', 'www']
42
+ cmd.ensure_string_list('option2')
43
+
44
+ cmd.option3 = ['ok', 2]
45
+ with pytest.raises(DistutilsOptionError):
46
+ cmd.ensure_string_list('option3')
47
+
48
+ def test_make_file(self, cmd):
49
+ # making sure it raises when infiles is not a string or a list/tuple
50
+ with pytest.raises(TypeError):
51
+ cmd.make_file(infiles=True, outfile='', func='func', args=())
52
+
53
+ # making sure execute gets called properly
54
+ def _execute(func, args, exec_msg, level):
55
+ assert exec_msg == 'generating out from in'
56
+
57
+ cmd.force = True
58
+ cmd.execute = _execute
59
+ cmd.make_file(infiles='in', outfile='out', func='func', args=())
60
+
61
+ def test_dump_options(self, cmd):
62
+ msgs = []
63
+
64
+ def _announce(msg, level):
65
+ msgs.append(msg)
66
+
67
+ cmd.announce = _announce
68
+ cmd.option1 = 1
69
+ cmd.option2 = 1
70
+ cmd.user_options = [('option1', '', ''), ('option2', '', '')]
71
+ cmd.dump_options()
72
+
73
+ wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1']
74
+ assert msgs == wanted
75
+
76
+ def test_ensure_string(self, cmd):
77
+ cmd.option1 = 'ok'
78
+ cmd.ensure_string('option1')
79
+
80
+ cmd.option2 = None
81
+ cmd.ensure_string('option2', 'xxx')
82
+ assert hasattr(cmd, 'option2')
83
+
84
+ cmd.option3 = 1
85
+ with pytest.raises(DistutilsOptionError):
86
+ cmd.ensure_string('option3')
87
+
88
+ def test_ensure_filename(self, cmd):
89
+ cmd.option1 = __file__
90
+ cmd.ensure_filename('option1')
91
+ cmd.option2 = 'xxx'
92
+ with pytest.raises(DistutilsOptionError):
93
+ cmd.ensure_filename('option2')
94
+
95
+ def test_ensure_dirname(self, cmd):
96
+ cmd.option1 = os.path.dirname(__file__) or os.curdir
97
+ cmd.ensure_dirname('option1')
98
+ cmd.option2 = 'xxx'
99
+ with pytest.raises(DistutilsOptionError):
100
+ cmd.ensure_dirname('option2')
101
+
102
+ def test_debug_print(self, cmd, capsys, monkeypatch):
103
+ cmd.debug_print('xxx')
104
+ assert capsys.readouterr().out == ''
105
+ monkeypatch.setattr(debug, 'DEBUG', True)
106
+ cmd.debug_print('xxx')
107
+ assert capsys.readouterr().out == 'xxx\n'
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_data.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.install_data."""
2
+
3
+ import os
4
+ import pathlib
5
+ from distutils.command.install_data import install_data
6
+ from distutils.tests import support
7
+
8
+ import pytest
9
+
10
+
11
+ @pytest.mark.usefixtures('save_env')
12
+ class TestInstallData(
13
+ support.TempdirManager,
14
+ ):
15
+ def test_simple_run(self):
16
+ pkg_dir, dist = self.create_dist()
17
+ cmd = install_data(dist)
18
+ cmd.install_dir = inst = os.path.join(pkg_dir, 'inst')
19
+
20
+ # data_files can contain
21
+ # - simple files
22
+ # - a Path object
23
+ # - a tuple with a path, and a list of file
24
+ one = os.path.join(pkg_dir, 'one')
25
+ self.write_file(one, 'xxx')
26
+ inst2 = os.path.join(pkg_dir, 'inst2')
27
+ two = os.path.join(pkg_dir, 'two')
28
+ self.write_file(two, 'xxx')
29
+ three = pathlib.Path(pkg_dir) / 'three'
30
+ self.write_file(three, 'xxx')
31
+
32
+ cmd.data_files = [one, (inst2, [two]), three]
33
+ assert cmd.get_inputs() == [one, (inst2, [two]), three]
34
+
35
+ # let's run the command
36
+ cmd.ensure_finalized()
37
+ cmd.run()
38
+
39
+ # let's check the result
40
+ assert len(cmd.get_outputs()) == 3
41
+ rthree = os.path.split(one)[-1]
42
+ assert os.path.exists(os.path.join(inst, rthree))
43
+ rtwo = os.path.split(two)[-1]
44
+ assert os.path.exists(os.path.join(inst2, rtwo))
45
+ rone = os.path.split(one)[-1]
46
+ assert os.path.exists(os.path.join(inst, rone))
47
+ cmd.outfiles = []
48
+
49
+ # let's try with warn_dir one
50
+ cmd.warn_dir = True
51
+ cmd.ensure_finalized()
52
+ cmd.run()
53
+
54
+ # let's check the result
55
+ assert len(cmd.get_outputs()) == 3
56
+ assert os.path.exists(os.path.join(inst, rthree))
57
+ assert os.path.exists(os.path.join(inst2, rtwo))
58
+ assert os.path.exists(os.path.join(inst, rone))
59
+ cmd.outfiles = []
60
+
61
+ # now using root and empty dir
62
+ cmd.root = os.path.join(pkg_dir, 'root')
63
+ inst5 = os.path.join(pkg_dir, 'inst5')
64
+ four = os.path.join(cmd.install_dir, 'four')
65
+ self.write_file(four, 'xx')
66
+ cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])]
67
+ cmd.ensure_finalized()
68
+ cmd.run()
69
+
70
+ # let's check the result
71
+ assert len(cmd.get_outputs()) == 5
72
+ assert os.path.exists(os.path.join(inst, rthree))
73
+ assert os.path.exists(os.path.join(inst2, rtwo))
74
+ assert os.path.exists(os.path.join(inst, rone))
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_sysconfig.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.sysconfig."""
2
+
3
+ import contextlib
4
+ import distutils
5
+ import os
6
+ import pathlib
7
+ import subprocess
8
+ import sys
9
+ from distutils import sysconfig
10
+ from distutils.ccompiler import new_compiler # noqa: F401
11
+ from distutils.unixccompiler import UnixCCompiler
12
+
13
+ import jaraco.envs
14
+ import path
15
+ import pytest
16
+ from jaraco.text import trim
17
+ from test.support import swap_item
18
+
19
+
20
+ def _gen_makefile(root, contents):
21
+ jaraco.path.build({'Makefile': trim(contents)}, root)
22
+ return root / 'Makefile'
23
+
24
+
25
+ @pytest.mark.usefixtures('save_env')
26
+ class TestSysconfig:
27
+ def test_get_config_h_filename(self):
28
+ config_h = sysconfig.get_config_h_filename()
29
+ assert os.path.isfile(config_h)
30
+
31
+ @pytest.mark.skipif("platform.system() == 'Windows'")
32
+ @pytest.mark.skipif("sys.implementation.name != 'cpython'")
33
+ def test_get_makefile_filename(self):
34
+ makefile = sysconfig.get_makefile_filename()
35
+ assert os.path.isfile(makefile)
36
+
37
+ def test_get_python_lib(self, tmp_path):
38
+ assert sysconfig.get_python_lib() != sysconfig.get_python_lib(prefix=tmp_path)
39
+
40
+ def test_get_config_vars(self):
41
+ cvars = sysconfig.get_config_vars()
42
+ assert isinstance(cvars, dict)
43
+ assert cvars
44
+
45
+ @pytest.mark.skipif('sysconfig.IS_PYPY')
46
+ @pytest.mark.skipif('sysconfig.python_build')
47
+ @pytest.mark.xfail('platform.system() == "Windows"')
48
+ def test_srcdir_simple(self):
49
+ # See #15364.
50
+ srcdir = pathlib.Path(sysconfig.get_config_var('srcdir'))
51
+
52
+ assert srcdir.absolute()
53
+ assert srcdir.is_dir()
54
+
55
+ makefile = pathlib.Path(sysconfig.get_makefile_filename())
56
+ assert makefile.parent.samefile(srcdir)
57
+
58
+ @pytest.mark.skipif('sysconfig.IS_PYPY')
59
+ @pytest.mark.skipif('not sysconfig.python_build')
60
+ def test_srcdir_python_build(self):
61
+ # See #15364.
62
+ srcdir = pathlib.Path(sysconfig.get_config_var('srcdir'))
63
+
64
+ # The python executable has not been installed so srcdir
65
+ # should be a full source checkout.
66
+ Python_h = srcdir.joinpath('Include', 'Python.h')
67
+ assert Python_h.is_file()
68
+ assert sysconfig._is_python_source_dir(srcdir)
69
+ assert sysconfig._is_python_source_dir(str(srcdir))
70
+
71
+ def test_srcdir_independent_of_cwd(self):
72
+ """
73
+ srcdir should be independent of the current working directory
74
+ """
75
+ # See #15364.
76
+ srcdir = sysconfig.get_config_var('srcdir')
77
+ with path.Path('..'):
78
+ srcdir2 = sysconfig.get_config_var('srcdir')
79
+ assert srcdir == srcdir2
80
+
81
+ def customize_compiler(self):
82
+ # make sure AR gets caught
83
+ class compiler:
84
+ compiler_type = 'unix'
85
+ executables = UnixCCompiler.executables
86
+
87
+ def __init__(self):
88
+ self.exes = {}
89
+
90
+ def set_executables(self, **kw):
91
+ for k, v in kw.items():
92
+ self.exes[k] = v
93
+
94
+ sysconfig_vars = {
95
+ 'AR': 'sc_ar',
96
+ 'CC': 'sc_cc',
97
+ 'CXX': 'sc_cxx',
98
+ 'ARFLAGS': '--sc-arflags',
99
+ 'CFLAGS': '--sc-cflags',
100
+ 'CCSHARED': '--sc-ccshared',
101
+ 'LDSHARED': 'sc_ldshared',
102
+ 'SHLIB_SUFFIX': 'sc_shutil_suffix',
103
+ }
104
+
105
+ comp = compiler()
106
+ with contextlib.ExitStack() as cm:
107
+ for key, value in sysconfig_vars.items():
108
+ cm.enter_context(swap_item(sysconfig._config_vars, key, value))
109
+ sysconfig.customize_compiler(comp)
110
+
111
+ return comp
112
+
113
+ @pytest.mark.skipif("not isinstance(new_compiler(), UnixCCompiler)")
114
+ @pytest.mark.usefixtures('disable_macos_customization')
115
+ def test_customize_compiler(self):
116
+ # Make sure that sysconfig._config_vars is initialized
117
+ sysconfig.get_config_vars()
118
+
119
+ os.environ['AR'] = 'env_ar'
120
+ os.environ['CC'] = 'env_cc'
121
+ os.environ['CPP'] = 'env_cpp'
122
+ os.environ['CXX'] = 'env_cxx --env-cxx-flags'
123
+ os.environ['LDSHARED'] = 'env_ldshared'
124
+ os.environ['LDFLAGS'] = '--env-ldflags'
125
+ os.environ['ARFLAGS'] = '--env-arflags'
126
+ os.environ['CFLAGS'] = '--env-cflags'
127
+ os.environ['CPPFLAGS'] = '--env-cppflags'
128
+ os.environ['RANLIB'] = 'env_ranlib'
129
+
130
+ comp = self.customize_compiler()
131
+ assert comp.exes['archiver'] == 'env_ar --env-arflags'
132
+ assert comp.exes['preprocessor'] == 'env_cpp --env-cppflags'
133
+ assert comp.exes['compiler'] == 'env_cc --env-cflags --env-cppflags'
134
+ assert comp.exes['compiler_so'] == (
135
+ 'env_cc --env-cflags --env-cppflags --sc-ccshared'
136
+ )
137
+ assert (
138
+ comp.exes['compiler_cxx']
139
+ == 'env_cxx --env-cxx-flags --sc-cflags --env-cppflags'
140
+ )
141
+ assert comp.exes['linker_exe'] == 'env_cc'
142
+ assert comp.exes['linker_so'] == (
143
+ 'env_ldshared --env-ldflags --env-cflags --env-cppflags'
144
+ )
145
+ assert comp.shared_lib_extension == 'sc_shutil_suffix'
146
+
147
+ if sys.platform == "darwin":
148
+ assert comp.exes['ranlib'] == 'env_ranlib'
149
+ else:
150
+ assert 'ranlib' not in comp.exes
151
+
152
+ del os.environ['AR']
153
+ del os.environ['CC']
154
+ del os.environ['CPP']
155
+ del os.environ['CXX']
156
+ del os.environ['LDSHARED']
157
+ del os.environ['LDFLAGS']
158
+ del os.environ['ARFLAGS']
159
+ del os.environ['CFLAGS']
160
+ del os.environ['CPPFLAGS']
161
+ del os.environ['RANLIB']
162
+
163
+ comp = self.customize_compiler()
164
+ assert comp.exes['archiver'] == 'sc_ar --sc-arflags'
165
+ assert comp.exes['preprocessor'] == 'sc_cc -E'
166
+ assert comp.exes['compiler'] == 'sc_cc --sc-cflags'
167
+ assert comp.exes['compiler_so'] == 'sc_cc --sc-cflags --sc-ccshared'
168
+ assert comp.exes['compiler_cxx'] == 'sc_cxx --sc-cflags'
169
+ assert comp.exes['linker_exe'] == 'sc_cc'
170
+ assert comp.exes['linker_so'] == 'sc_ldshared'
171
+ assert comp.shared_lib_extension == 'sc_shutil_suffix'
172
+ assert 'ranlib' not in comp.exes
173
+
174
+ def test_parse_makefile_base(self, tmp_path):
175
+ makefile = _gen_makefile(
176
+ tmp_path,
177
+ """
178
+ CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'
179
+ VAR=$OTHER
180
+ OTHER=foo
181
+ """,
182
+ )
183
+ d = sysconfig.parse_makefile(makefile)
184
+ assert d == {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 'OTHER': 'foo'}
185
+
186
+ def test_parse_makefile_literal_dollar(self, tmp_path):
187
+ makefile = _gen_makefile(
188
+ tmp_path,
189
+ """
190
+ CONFIG_ARGS= '--arg1=optarg1' 'ENV=\\$$LIB'
191
+ VAR=$OTHER
192
+ OTHER=foo
193
+ """,
194
+ )
195
+ d = sysconfig.parse_makefile(makefile)
196
+ assert d == {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 'OTHER': 'foo'}
197
+
198
+ def test_sysconfig_module(self):
199
+ import sysconfig as global_sysconfig
200
+
201
+ assert global_sysconfig.get_config_var('CFLAGS') == sysconfig.get_config_var(
202
+ 'CFLAGS'
203
+ )
204
+ assert global_sysconfig.get_config_var('LDFLAGS') == sysconfig.get_config_var(
205
+ 'LDFLAGS'
206
+ )
207
+
208
+ # On macOS, binary installers support extension module building on
209
+ # various levels of the operating system with differing Xcode
210
+ # configurations, requiring customization of some of the
211
+ # compiler configuration directives to suit the environment on
212
+ # the installed machine. Some of these customizations may require
213
+ # running external programs and are thus deferred until needed by
214
+ # the first extension module build. Only
215
+ # the Distutils version of sysconfig is used for extension module
216
+ # builds, which happens earlier in the Distutils tests. This may
217
+ # cause the following tests to fail since no tests have caused
218
+ # the global version of sysconfig to call the customization yet.
219
+ # The solution for now is to simply skip this test in this case.
220
+ # The longer-term solution is to only have one version of sysconfig.
221
+ @pytest.mark.skipif("sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER')")
222
+ def test_sysconfig_compiler_vars(self):
223
+ import sysconfig as global_sysconfig
224
+
225
+ if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'):
226
+ pytest.skip('compiler flags customized')
227
+ assert global_sysconfig.get_config_var('LDSHARED') == sysconfig.get_config_var(
228
+ 'LDSHARED'
229
+ )
230
+ assert global_sysconfig.get_config_var('CC') == sysconfig.get_config_var('CC')
231
+
232
+ @pytest.mark.skipif("not sysconfig.get_config_var('EXT_SUFFIX')")
233
+ def test_SO_deprecation(self):
234
+ with pytest.warns(DeprecationWarning):
235
+ sysconfig.get_config_var('SO')
236
+
237
+ def test_customize_compiler_before_get_config_vars(self, tmp_path):
238
+ # Issue #21923: test that a Distribution compiler
239
+ # instance can be called without an explicit call to
240
+ # get_config_vars().
241
+ jaraco.path.build(
242
+ {
243
+ 'file': trim("""
244
+ from distutils.core import Distribution
245
+ config = Distribution().get_command_obj('config')
246
+ # try_compile may pass or it may fail if no compiler
247
+ # is found but it should not raise an exception.
248
+ rc = config.try_compile('int x;')
249
+ """)
250
+ },
251
+ tmp_path,
252
+ )
253
+ p = subprocess.Popen(
254
+ [sys.executable, tmp_path / 'file'],
255
+ stdout=subprocess.PIPE,
256
+ stderr=subprocess.STDOUT,
257
+ universal_newlines=True,
258
+ encoding='utf-8',
259
+ )
260
+ outs, errs = p.communicate()
261
+ assert 0 == p.returncode, "Subprocess failed: " + outs
262
+
263
+ def test_parse_config_h(self):
264
+ config_h = sysconfig.get_config_h_filename()
265
+ input = {}
266
+ with open(config_h, encoding="utf-8") as f:
267
+ result = sysconfig.parse_config_h(f, g=input)
268
+ assert input is result
269
+ with open(config_h, encoding="utf-8") as f:
270
+ result = sysconfig.parse_config_h(f)
271
+ assert isinstance(result, dict)
272
+
273
+ @pytest.mark.skipif("platform.system() != 'Windows'")
274
+ @pytest.mark.skipif("sys.implementation.name != 'cpython'")
275
+ def test_win_ext_suffix(self):
276
+ assert sysconfig.get_config_var("EXT_SUFFIX").endswith(".pyd")
277
+ assert sysconfig.get_config_var("EXT_SUFFIX") != ".pyd"
278
+
279
+ @pytest.mark.skipif("platform.system() != 'Windows'")
280
+ @pytest.mark.skipif("sys.implementation.name != 'cpython'")
281
+ @pytest.mark.skipif(
282
+ '\\PCbuild\\'.casefold() not in sys.executable.casefold(),
283
+ reason='Need sys.executable to be in a source tree',
284
+ )
285
+ def test_win_build_venv_from_source_tree(self, tmp_path):
286
+ """Ensure distutils.sysconfig detects venvs from source tree builds."""
287
+ env = jaraco.envs.VEnv()
288
+ env.create_opts = env.clean_opts
289
+ env.root = tmp_path
290
+ env.ensure_env()
291
+ cmd = [
292
+ env.exe(),
293
+ "-c",
294
+ "import distutils.sysconfig; print(distutils.sysconfig.python_build)",
295
+ ]
296
+ distutils_path = os.path.dirname(os.path.dirname(distutils.__file__))
297
+ out = subprocess.check_output(
298
+ cmd, env={**os.environ, "PYTHONPATH": distutils_path}
299
+ )
300
+ assert out == "True"
301
+
302
+ def test_get_python_inc_missing_config_dir(self, monkeypatch):
303
+ """
304
+ In portable Python installations, the sysconfig will be broken,
305
+ pointing to the directories where the installation was built and
306
+ not where it currently is. In this case, ensure that the missing
307
+ directory isn't used for get_python_inc.
308
+
309
+ See pypa/distutils#178.
310
+ """
311
+
312
+ def override(name):
313
+ if name == 'INCLUDEPY':
314
+ return '/does-not-exist'
315
+ return sysconfig.get_config_var(name)
316
+
317
+ monkeypatch.setattr(sysconfig, 'get_config_var', override)
318
+
319
+ assert os.path.exists(sysconfig.get_python_inc())
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/tests/test_util.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.util."""
2
+
3
+ import email
4
+ import email.generator
5
+ import email.policy
6
+ import io
7
+ import os
8
+ import pathlib
9
+ import sys
10
+ import sysconfig as stdlib_sysconfig
11
+ import unittest.mock as mock
12
+ from copy import copy
13
+ from distutils import sysconfig, util
14
+ from distutils.errors import DistutilsByteCompileError, DistutilsPlatformError
15
+ from distutils.util import (
16
+ byte_compile,
17
+ change_root,
18
+ check_environ,
19
+ convert_path,
20
+ get_host_platform,
21
+ get_platform,
22
+ grok_environment_error,
23
+ rfc822_escape,
24
+ split_quoted,
25
+ strtobool,
26
+ )
27
+
28
+ import pytest
29
+
30
+
31
+ @pytest.fixture(autouse=True)
32
+ def environment(monkeypatch):
33
+ monkeypatch.setattr(os, 'name', os.name)
34
+ monkeypatch.setattr(sys, 'platform', sys.platform)
35
+ monkeypatch.setattr(sys, 'version', sys.version)
36
+ monkeypatch.setattr(os, 'sep', os.sep)
37
+ monkeypatch.setattr(os.path, 'join', os.path.join)
38
+ monkeypatch.setattr(os.path, 'isabs', os.path.isabs)
39
+ monkeypatch.setattr(os.path, 'splitdrive', os.path.splitdrive)
40
+ monkeypatch.setattr(sysconfig, '_config_vars', copy(sysconfig._config_vars))
41
+
42
+
43
+ @pytest.mark.usefixtures('save_env')
44
+ class TestUtil:
45
+ def test_get_host_platform(self):
46
+ with mock.patch('os.name', 'nt'):
47
+ with mock.patch('sys.version', '... [... (ARM64)]'):
48
+ assert get_host_platform() == 'win-arm64'
49
+ with mock.patch('sys.version', '... [... (ARM)]'):
50
+ assert get_host_platform() == 'win-arm32'
51
+
52
+ with mock.patch('sys.version_info', (3, 9, 0, 'final', 0)):
53
+ assert get_host_platform() == stdlib_sysconfig.get_platform()
54
+
55
+ def test_get_platform(self):
56
+ with mock.patch('os.name', 'nt'):
57
+ with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}):
58
+ assert get_platform() == 'win32'
59
+ with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}):
60
+ assert get_platform() == 'win-amd64'
61
+ with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}):
62
+ assert get_platform() == 'win-arm32'
63
+ with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}):
64
+ assert get_platform() == 'win-arm64'
65
+
66
+ def test_convert_path(self):
67
+ expected = os.sep.join(('', 'home', 'to', 'my', 'stuff'))
68
+ assert convert_path('/home/to/my/stuff') == expected
69
+ assert convert_path(pathlib.Path('/home/to/my/stuff')) == expected
70
+ assert convert_path('.') == os.curdir
71
+
72
+ def test_change_root(self):
73
+ # linux/mac
74
+ os.name = 'posix'
75
+
76
+ def _isabs(path):
77
+ return path[0] == '/'
78
+
79
+ os.path.isabs = _isabs
80
+
81
+ def _join(*path):
82
+ return '/'.join(path)
83
+
84
+ os.path.join = _join
85
+
86
+ assert change_root('/root', '/old/its/here') == '/root/old/its/here'
87
+ assert change_root('/root', 'its/here') == '/root/its/here'
88
+
89
+ # windows
90
+ os.name = 'nt'
91
+ os.sep = '\\'
92
+
93
+ def _isabs(path):
94
+ return path.startswith('c:\\')
95
+
96
+ os.path.isabs = _isabs
97
+
98
+ def _splitdrive(path):
99
+ if path.startswith('c:'):
100
+ return ('', path.replace('c:', ''))
101
+ return ('', path)
102
+
103
+ os.path.splitdrive = _splitdrive
104
+
105
+ def _join(*path):
106
+ return '\\'.join(path)
107
+
108
+ os.path.join = _join
109
+
110
+ assert (
111
+ change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here'
112
+ )
113
+ assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here'
114
+
115
+ # BugsBunny os (it's a great os)
116
+ os.name = 'BugsBunny'
117
+ with pytest.raises(DistutilsPlatformError):
118
+ change_root('c:\\root', 'its\\here')
119
+
120
+ # XXX platforms to be covered: mac
121
+
122
+ def test_check_environ(self):
123
+ util.check_environ.cache_clear()
124
+ os.environ.pop('HOME', None)
125
+
126
+ check_environ()
127
+
128
+ assert os.environ['PLAT'] == get_platform()
129
+
130
+ @pytest.mark.skipif("os.name != 'posix'")
131
+ def test_check_environ_getpwuid(self):
132
+ util.check_environ.cache_clear()
133
+ os.environ.pop('HOME', None)
134
+
135
+ import pwd
136
+
137
+ # only set pw_dir field, other fields are not used
138
+ result = pwd.struct_passwd((
139
+ None,
140
+ None,
141
+ None,
142
+ None,
143
+ None,
144
+ '/home/distutils',
145
+ None,
146
+ ))
147
+ with mock.patch.object(pwd, 'getpwuid', return_value=result):
148
+ check_environ()
149
+ assert os.environ['HOME'] == '/home/distutils'
150
+
151
+ util.check_environ.cache_clear()
152
+ os.environ.pop('HOME', None)
153
+
154
+ # bpo-10496: Catch pwd.getpwuid() error
155
+ with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError):
156
+ check_environ()
157
+ assert 'HOME' not in os.environ
158
+
159
+ def test_split_quoted(self):
160
+ assert split_quoted('""one"" "two" \'three\' \\four') == [
161
+ 'one',
162
+ 'two',
163
+ 'three',
164
+ 'four',
165
+ ]
166
+
167
+ def test_strtobool(self):
168
+ yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
169
+ no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N')
170
+
171
+ for y in yes:
172
+ assert strtobool(y)
173
+
174
+ for n in no:
175
+ assert not strtobool(n)
176
+
177
+ indent = 8 * ' '
178
+
179
+ @pytest.mark.parametrize(
180
+ "given,wanted",
181
+ [
182
+ # 0x0b, 0x0c, ..., etc are also considered a line break by Python
183
+ ("hello\x0b\nworld\n", f"hello\x0b{indent}\n{indent}world\n{indent}"),
184
+ ("hello\x1eworld", f"hello\x1e{indent}world"),
185
+ ("", ""),
186
+ (
187
+ "I am a\npoor\nlonesome\nheader\n",
188
+ f"I am a\n{indent}poor\n{indent}lonesome\n{indent}header\n{indent}",
189
+ ),
190
+ ],
191
+ )
192
+ def test_rfc822_escape(self, given, wanted):
193
+ """
194
+ We want to ensure a multi-line header parses correctly.
195
+
196
+ For interoperability, the escaped value should also "round-trip" over
197
+ `email.generator.Generator.flatten` and `email.message_from_*`
198
+ (see pypa/setuptools#4033).
199
+
200
+ The main issue is that internally `email.policy.EmailPolicy` uses
201
+ `splitlines` which will split on some control chars. If all the new lines
202
+ are not prefixed with spaces, the parser will interrupt reading
203
+ the current header and produce an incomplete value, while
204
+ incorrectly interpreting the rest of the headers as part of the payload.
205
+ """
206
+ res = rfc822_escape(given)
207
+
208
+ policy = email.policy.EmailPolicy(
209
+ utf8=True,
210
+ mangle_from_=False,
211
+ max_line_length=0,
212
+ )
213
+ with io.StringIO() as buffer:
214
+ raw = f"header: {res}\nother-header: 42\n\npayload\n"
215
+ orig = email.message_from_string(raw)
216
+ email.generator.Generator(buffer, policy=policy).flatten(orig)
217
+ buffer.seek(0)
218
+ regen = email.message_from_file(buffer)
219
+
220
+ for msg in (orig, regen):
221
+ assert msg.get_payload() == "payload\n"
222
+ assert msg["other-header"] == "42"
223
+ # Generator may replace control chars with `\n`
224
+ assert set(msg["header"].splitlines()) == set(res.splitlines())
225
+
226
+ assert res == wanted
227
+
228
+ def test_dont_write_bytecode(self):
229
+ # makes sure byte_compile raise a DistutilsError
230
+ # if sys.dont_write_bytecode is True
231
+ old_dont_write_bytecode = sys.dont_write_bytecode
232
+ sys.dont_write_bytecode = True
233
+ try:
234
+ with pytest.raises(DistutilsByteCompileError):
235
+ byte_compile([])
236
+ finally:
237
+ sys.dont_write_bytecode = old_dont_write_bytecode
238
+
239
+ def test_grok_environment_error(self):
240
+ # test obsolete function to ensure backward compat (#4931)
241
+ exc = OSError("Unable to find batch file")
242
+ msg = grok_environment_error(exc)
243
+ assert msg == "error: Unable to find batch file"
evalkit_llava/lib/python3.10/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)
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/unixccompiler.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.unixccompiler
2
+
3
+ Contains the UnixCCompiler class, a subclass of CCompiler that handles
4
+ the "typical" Unix-style command-line C compiler:
5
+ * macros defined with -Dname[=value]
6
+ * macros undefined with -Uname
7
+ * include search directories specified with -Idir
8
+ * libraries specified with -lllib
9
+ * library search directories specified with -Ldir
10
+ * compile handled by 'cc' (or similar) executable with -c option:
11
+ compiles .c to .o
12
+ * link static library handled by 'ar' command (possibly with 'ranlib')
13
+ * link shared library handled by 'cc -shared'
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import itertools
19
+ import os
20
+ import re
21
+ import shlex
22
+ import sys
23
+
24
+ from . import sysconfig
25
+ from ._log import log
26
+ from ._macos_compat import compiler_fixup
27
+ from ._modified import newer
28
+ from .ccompiler import CCompiler, gen_lib_options, gen_preprocess_options
29
+ from .compat import consolidate_linker_args
30
+ from .errors import CompileError, DistutilsExecError, LibError, LinkError
31
+
32
+ # XXX Things not currently handled:
33
+ # * optimization/debug/warning flags; we just use whatever's in Python's
34
+ # Makefile and live with it. Is this adequate? If not, we might
35
+ # have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
36
+ # SunCCompiler, and I suspect down that road lies madness.
37
+ # * even if we don't know a warning flag from an optimization flag,
38
+ # we need some way for outsiders to feed preprocessor/compiler/linker
39
+ # flags in to us -- eg. a sysadmin might want to mandate certain flags
40
+ # via a site config file, or a user might want to set something for
41
+ # compiling this module distribution only via the setup.py command
42
+ # line, whatever. As long as these options come from something on the
43
+ # current system, they can be as system-dependent as they like, and we
44
+ # should just happily stuff them into the preprocessor/compiler/linker
45
+ # options and carry on.
46
+
47
+
48
+ def _split_env(cmd):
49
+ """
50
+ For macOS, split command into 'env' portion (if any)
51
+ and the rest of the linker command.
52
+
53
+ >>> _split_env(['a', 'b', 'c'])
54
+ ([], ['a', 'b', 'c'])
55
+ >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
56
+ (['/usr/bin/env', 'A=3'], ['gcc'])
57
+ """
58
+ pivot = 0
59
+ if os.path.basename(cmd[0]) == "env":
60
+ pivot = 1
61
+ while '=' in cmd[pivot]:
62
+ pivot += 1
63
+ return cmd[:pivot], cmd[pivot:]
64
+
65
+
66
+ def _split_aix(cmd):
67
+ """
68
+ AIX platforms prefix the compiler with the ld_so_aix
69
+ script, so split that from the linker command.
70
+
71
+ >>> _split_aix(['a', 'b', 'c'])
72
+ ([], ['a', 'b', 'c'])
73
+ >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
74
+ (['/bin/foo/ld_so_aix'], ['gcc'])
75
+ """
76
+ pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
77
+ return cmd[:pivot], cmd[pivot:]
78
+
79
+
80
+ def _linker_params(linker_cmd, compiler_cmd):
81
+ """
82
+ The linker command usually begins with the compiler
83
+ command (possibly multiple elements), followed by zero or more
84
+ params for shared library building.
85
+
86
+ If the LDSHARED env variable overrides the linker command,
87
+ however, the commands may not match.
88
+
89
+ Return the best guess of the linker parameters by stripping
90
+ the linker command. If the compiler command does not
91
+ match the linker command, assume the linker command is
92
+ just the first element.
93
+
94
+ >>> _linker_params('gcc foo bar'.split(), ['gcc'])
95
+ ['foo', 'bar']
96
+ >>> _linker_params('gcc foo bar'.split(), ['other'])
97
+ ['foo', 'bar']
98
+ >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
99
+ ['foo', 'bar']
100
+ >>> _linker_params(['gcc'], ['gcc'])
101
+ []
102
+ """
103
+ c_len = len(compiler_cmd)
104
+ pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
105
+ return linker_cmd[pivot:]
106
+
107
+
108
+ class UnixCCompiler(CCompiler):
109
+ compiler_type = 'unix'
110
+
111
+ # These are used by CCompiler in two places: the constructor sets
112
+ # instance attributes 'preprocessor', 'compiler', etc. from them, and
113
+ # 'set_executable()' allows any of these to be set. The defaults here
114
+ # are pretty generic; they will probably have to be set by an outsider
115
+ # (eg. using information discovered by the sysconfig about building
116
+ # Python extensions).
117
+ executables = {
118
+ 'preprocessor': None,
119
+ 'compiler': ["cc"],
120
+ 'compiler_so': ["cc"],
121
+ 'compiler_cxx': ["c++"],
122
+ 'compiler_so_cxx': ["c++"],
123
+ 'linker_so': ["cc", "-shared"],
124
+ 'linker_so_cxx': ["c++", "-shared"],
125
+ 'linker_exe': ["cc"],
126
+ 'linker_exe_cxx': ["c++", "-shared"],
127
+ 'archiver': ["ar", "-cr"],
128
+ 'ranlib': None,
129
+ }
130
+
131
+ if sys.platform[:6] == "darwin":
132
+ executables['ranlib'] = ["ranlib"]
133
+
134
+ # Needed for the filename generation methods provided by the base
135
+ # class, CCompiler. NB. whoever instantiates/uses a particular
136
+ # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
137
+ # reasonable common default here, but it's not necessarily used on all
138
+ # Unices!
139
+
140
+ src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
141
+ obj_extension = ".o"
142
+ static_lib_extension = ".a"
143
+ shared_lib_extension = ".so"
144
+ dylib_lib_extension = ".dylib"
145
+ xcode_stub_lib_extension = ".tbd"
146
+ static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
147
+ xcode_stub_lib_format = dylib_lib_format
148
+ if sys.platform == "cygwin":
149
+ exe_extension = ".exe"
150
+ shared_lib_extension = ".dll.a"
151
+ dylib_lib_extension = ".dll"
152
+ dylib_lib_format = "cyg%s%s"
153
+
154
+ def preprocess(
155
+ self,
156
+ source,
157
+ output_file=None,
158
+ macros=None,
159
+ include_dirs=None,
160
+ extra_preargs=None,
161
+ extra_postargs=None,
162
+ ):
163
+ fixed_args = self._fix_compile_args(None, macros, include_dirs)
164
+ ignore, macros, include_dirs = fixed_args
165
+ pp_opts = gen_preprocess_options(macros, include_dirs)
166
+ pp_args = self.preprocessor + pp_opts
167
+ if output_file:
168
+ pp_args.extend(['-o', output_file])
169
+ if extra_preargs:
170
+ pp_args[:0] = extra_preargs
171
+ if extra_postargs:
172
+ pp_args.extend(extra_postargs)
173
+ pp_args.append(source)
174
+
175
+ # reasons to preprocess:
176
+ # - force is indicated
177
+ # - output is directed to stdout
178
+ # - source file is newer than the target
179
+ preprocess = self.force or output_file is None or newer(source, output_file)
180
+ if not preprocess:
181
+ return
182
+
183
+ if output_file:
184
+ self.mkpath(os.path.dirname(output_file))
185
+
186
+ try:
187
+ self.spawn(pp_args)
188
+ except DistutilsExecError as msg:
189
+ raise CompileError(msg)
190
+
191
+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
192
+ compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
193
+ compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs)
194
+ try:
195
+ if self.detect_language(src) == 'c++':
196
+ self.spawn(
197
+ compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs
198
+ )
199
+ else:
200
+ self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
201
+ except DistutilsExecError as msg:
202
+ raise CompileError(msg)
203
+
204
+ def create_static_lib(
205
+ self, objects, output_libname, output_dir=None, debug=False, target_lang=None
206
+ ):
207
+ objects, output_dir = self._fix_object_args(objects, output_dir)
208
+
209
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
210
+
211
+ if self._need_link(objects, output_filename):
212
+ self.mkpath(os.path.dirname(output_filename))
213
+ self.spawn(self.archiver + [output_filename] + objects + self.objects)
214
+
215
+ # Not many Unices required ranlib anymore -- SunOS 4.x is, I
216
+ # think the only major Unix that does. Maybe we need some
217
+ # platform intelligence here to skip ranlib if it's not
218
+ # needed -- or maybe Python's configure script took care of
219
+ # it for us, hence the check for leading colon.
220
+ if self.ranlib:
221
+ try:
222
+ self.spawn(self.ranlib + [output_filename])
223
+ except DistutilsExecError as msg:
224
+ raise LibError(msg)
225
+ else:
226
+ log.debug("skipping %s (up-to-date)", output_filename)
227
+
228
+ def link(
229
+ self,
230
+ target_desc,
231
+ objects,
232
+ output_filename,
233
+ output_dir=None,
234
+ libraries=None,
235
+ library_dirs=None,
236
+ runtime_library_dirs=None,
237
+ export_symbols=None,
238
+ debug=False,
239
+ extra_preargs=None,
240
+ extra_postargs=None,
241
+ build_temp=None,
242
+ target_lang=None,
243
+ ):
244
+ objects, output_dir = self._fix_object_args(objects, output_dir)
245
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
246
+ libraries, library_dirs, runtime_library_dirs = fixed_args
247
+
248
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
249
+ if not isinstance(output_dir, (str, type(None))):
250
+ raise TypeError("'output_dir' must be a string or None")
251
+ if output_dir is not None:
252
+ output_filename = os.path.join(output_dir, output_filename)
253
+
254
+ if self._need_link(objects, output_filename):
255
+ ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
256
+ if debug:
257
+ ld_args[:0] = ['-g']
258
+ if extra_preargs:
259
+ ld_args[:0] = extra_preargs
260
+ if extra_postargs:
261
+ ld_args.extend(extra_postargs)
262
+ self.mkpath(os.path.dirname(output_filename))
263
+ try:
264
+ # Select a linker based on context: linker_exe when
265
+ # building an executable or linker_so (with shared options)
266
+ # when building a shared library.
267
+ building_exe = target_desc == CCompiler.EXECUTABLE
268
+ linker = (
269
+ self.linker_exe
270
+ if building_exe
271
+ else (
272
+ self.linker_so_cxx if target_lang == "c++" else self.linker_so
273
+ )
274
+ )[:]
275
+
276
+ if target_lang == "c++" and self.compiler_cxx:
277
+ env, linker_ne = _split_env(linker)
278
+ aix, linker_na = _split_aix(linker_ne)
279
+ _, compiler_cxx_ne = _split_env(self.compiler_cxx)
280
+ _, linker_exe_ne = _split_env(self.linker_exe)
281
+
282
+ params = _linker_params(linker_na, linker_exe_ne)
283
+ linker = env + aix + compiler_cxx_ne + params
284
+
285
+ linker = compiler_fixup(linker, ld_args)
286
+
287
+ self.spawn(linker + ld_args)
288
+ except DistutilsExecError as msg:
289
+ raise LinkError(msg)
290
+ else:
291
+ log.debug("skipping %s (up-to-date)", output_filename)
292
+
293
+ # -- Miscellaneous methods -----------------------------------------
294
+ # These are all used by the 'gen_lib_options() function, in
295
+ # ccompiler.py.
296
+
297
+ def library_dir_option(self, dir):
298
+ return "-L" + dir
299
+
300
+ def _is_gcc(self):
301
+ cc_var = sysconfig.get_config_var("CC")
302
+ compiler = os.path.basename(shlex.split(cc_var)[0])
303
+ return "gcc" in compiler or "g++" in compiler
304
+
305
+ def runtime_library_dir_option(self, dir: str) -> str | list[str]:
306
+ # XXX Hackish, at the very least. See Python bug #445902:
307
+ # https://bugs.python.org/issue445902
308
+ # Linkers on different platforms need different options to
309
+ # specify that directories need to be added to the list of
310
+ # directories searched for dependencies when a dynamic library
311
+ # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to
312
+ # be told to pass the -R option through to the linker, whereas
313
+ # other compilers and gcc on other systems just know this.
314
+ # Other compilers may need something slightly different. At
315
+ # this time, there's no way to determine this information from
316
+ # the configuration data stored in the Python installation, so
317
+ # we use this hack.
318
+ if sys.platform[:6] == "darwin":
319
+ from distutils.util import get_macosx_target_ver, split_version
320
+
321
+ macosx_target_ver = get_macosx_target_ver()
322
+ if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
323
+ return "-Wl,-rpath," + dir
324
+ else: # no support for -rpath on earlier macOS versions
325
+ return "-L" + dir
326
+ elif sys.platform[:7] == "freebsd":
327
+ return "-Wl,-rpath=" + dir
328
+ elif sys.platform[:5] == "hp-ux":
329
+ return [
330
+ "-Wl,+s" if self._is_gcc() else "+s",
331
+ "-L" + dir,
332
+ ]
333
+
334
+ # For all compilers, `-Wl` is the presumed way to pass a
335
+ # compiler option to the linker
336
+ if sysconfig.get_config_var("GNULD") == "yes":
337
+ return consolidate_linker_args([
338
+ # Force RUNPATH instead of RPATH
339
+ "-Wl,--enable-new-dtags",
340
+ "-Wl,-rpath," + dir,
341
+ ])
342
+ else:
343
+ return "-Wl,-R" + dir
344
+
345
+ def library_option(self, lib):
346
+ return "-l" + lib
347
+
348
+ @staticmethod
349
+ def _library_root(dir):
350
+ """
351
+ macOS users can specify an alternate SDK using'-isysroot'.
352
+ Calculate the SDK root if it is specified.
353
+
354
+ Note that, as of Xcode 7, Apple SDKs may contain textual stub
355
+ libraries with .tbd extensions rather than the normal .dylib
356
+ shared libraries installed in /. The Apple compiler tool
357
+ chain handles this transparently but it can cause problems
358
+ for programs that are being built with an SDK and searching
359
+ for specific libraries. Callers of find_library_file need to
360
+ keep in mind that the base filename of the returned SDK library
361
+ file might have a different extension from that of the library
362
+ file installed on the running system, for example:
363
+ /Applications/Xcode.app/Contents/Developer/Platforms/
364
+ MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
365
+ usr/lib/libedit.tbd
366
+ vs
367
+ /usr/lib/libedit.dylib
368
+ """
369
+ cflags = sysconfig.get_config_var('CFLAGS')
370
+ match = re.search(r'-isysroot\s*(\S+)', cflags)
371
+
372
+ apply_root = (
373
+ sys.platform == 'darwin'
374
+ and match
375
+ and (
376
+ dir.startswith('/System/')
377
+ or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
378
+ )
379
+ )
380
+
381
+ return os.path.join(match.group(1), dir[1:]) if apply_root else dir
382
+
383
+ def find_library_file(self, dirs, lib, debug=False):
384
+ """
385
+ Second-guess the linker with not much hard
386
+ data to go on: GCC seems to prefer the shared library, so
387
+ assume that *all* Unix C compilers do,
388
+ ignoring even GCC's "-static" option.
389
+ """
390
+ lib_names = (
391
+ self.library_filename(lib, lib_type=type)
392
+ for type in 'dylib xcode_stub shared static'.split()
393
+ )
394
+
395
+ roots = map(self._library_root, dirs)
396
+
397
+ searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names))
398
+
399
+ found = filter(os.path.exists, searched)
400
+
401
+ # Return None if it could not be found in any dir.
402
+ return next(found, None)
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/util.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
20
+ from jaraco.functools import pass_none
21
+
22
+ from ._log import log
23
+ from ._modified import newer
24
+ from .errors import DistutilsByteCompileError, DistutilsPlatformError
25
+ from .spawn import spawn
26
+
27
+
28
+ def get_host_platform() -> str:
29
+ """
30
+ Return a string that identifies the current platform. Use this
31
+ function to distinguish platform-specific build directories and
32
+ platform-specific built distributions.
33
+ """
34
+
35
+ # This function initially exposed platforms as defined in Python 3.9
36
+ # even with older Python versions when distutils was split out.
37
+ # Now it delegates to stdlib sysconfig.
38
+
39
+ return sysconfig.get_platform()
40
+
41
+
42
+ def get_platform():
43
+ if os.name == 'nt':
44
+ TARGET_TO_PLAT = {
45
+ 'x86': 'win32',
46
+ 'x64': 'win-amd64',
47
+ 'arm': 'win-arm32',
48
+ 'arm64': 'win-arm64',
49
+ }
50
+ target = os.environ.get('VSCMD_ARG_TGT_ARCH')
51
+ return TARGET_TO_PLAT.get(target) or get_host_platform()
52
+ return get_host_platform()
53
+
54
+
55
+ if sys.platform == 'darwin':
56
+ _syscfg_macosx_ver = None # cache the version pulled from sysconfig
57
+ MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'
58
+
59
+
60
+ def _clear_cached_macosx_ver():
61
+ """For testing only. Do not call."""
62
+ global _syscfg_macosx_ver
63
+ _syscfg_macosx_ver = None
64
+
65
+
66
+ def get_macosx_target_ver_from_syscfg():
67
+ """Get the version of macOS latched in the Python interpreter configuration.
68
+ Returns the version as a string or None if can't obtain one. Cached."""
69
+ global _syscfg_macosx_ver
70
+ if _syscfg_macosx_ver is None:
71
+ from distutils import sysconfig
72
+
73
+ ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''
74
+ if ver:
75
+ _syscfg_macosx_ver = ver
76
+ return _syscfg_macosx_ver
77
+
78
+
79
+ def get_macosx_target_ver():
80
+ """Return the version of macOS for which we are building.
81
+
82
+ The target version defaults to the version in sysconfig latched at time
83
+ the Python interpreter was built, unless overridden by an environment
84
+ variable. If neither source has a value, then None is returned"""
85
+
86
+ syscfg_ver = get_macosx_target_ver_from_syscfg()
87
+ env_ver = os.environ.get(MACOSX_VERSION_VAR)
88
+
89
+ if env_ver:
90
+ # Validate overridden version against sysconfig version, if have both.
91
+ # Ensure that the deployment target of the build process is not less
92
+ # than 10.3 if the interpreter was built for 10.3 or later. This
93
+ # ensures extension modules are built with correct compatibility
94
+ # values, specifically LDSHARED which can use
95
+ # '-undefined dynamic_lookup' which only works on >= 10.3.
96
+ if (
97
+ syscfg_ver
98
+ and split_version(syscfg_ver) >= [10, 3]
99
+ and split_version(env_ver) < [10, 3]
100
+ ):
101
+ my_msg = (
102
+ '$' + MACOSX_VERSION_VAR + ' mismatch: '
103
+ f'now "{env_ver}" but "{syscfg_ver}" during configure; '
104
+ 'must use 10.3 or later'
105
+ )
106
+ raise DistutilsPlatformError(my_msg)
107
+ return env_ver
108
+ return syscfg_ver
109
+
110
+
111
+ def split_version(s):
112
+ """Convert a dot-separated string into a list of numbers for comparisons"""
113
+ return [int(n) for n in s.split('.')]
114
+
115
+
116
+ @pass_none
117
+ def convert_path(pathname: str | os.PathLike) -> str:
118
+ r"""
119
+ Allow for pathlib.Path inputs, coax to a native path string.
120
+
121
+ If None is passed, will just pass it through as
122
+ Setuptools relies on this behavior.
123
+
124
+ >>> convert_path(None) is None
125
+ True
126
+
127
+ Removes empty paths.
128
+
129
+ >>> convert_path('foo/./bar').replace('\\', '/')
130
+ 'foo/bar'
131
+ """
132
+ return os.fspath(pathlib.PurePath(pathname))
133
+
134
+
135
+ def change_root(new_root, pathname):
136
+ """Return 'pathname' with 'new_root' prepended. If 'pathname' is
137
+ relative, this is equivalent to "os.path.join(new_root,pathname)".
138
+ Otherwise, it requires making 'pathname' relative and then joining the
139
+ two, which is tricky on DOS/Windows and Mac OS.
140
+ """
141
+ if os.name == 'posix':
142
+ if not os.path.isabs(pathname):
143
+ return os.path.join(new_root, pathname)
144
+ else:
145
+ return os.path.join(new_root, pathname[1:])
146
+
147
+ elif os.name == 'nt':
148
+ (drive, path) = os.path.splitdrive(pathname)
149
+ if path[0] == os.sep:
150
+ path = path[1:]
151
+ return os.path.join(new_root, path)
152
+
153
+ raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
154
+
155
+
156
+ @functools.lru_cache
157
+ def check_environ():
158
+ """Ensure that 'os.environ' has all the environment variables we
159
+ guarantee that users can use in config files, command-line options,
160
+ etc. Currently this includes:
161
+ HOME - user's home directory (Unix only)
162
+ PLAT - description of the current platform, including hardware
163
+ and OS (see 'get_platform()')
164
+ """
165
+ if os.name == 'posix' and 'HOME' not in os.environ:
166
+ try:
167
+ import pwd
168
+
169
+ os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
170
+ except (ImportError, KeyError):
171
+ # bpo-10496: if the current user identifier doesn't exist in the
172
+ # password database, do nothing
173
+ pass
174
+
175
+ if 'PLAT' not in os.environ:
176
+ os.environ['PLAT'] = get_platform()
177
+
178
+
179
+ def subst_vars(s, local_vars):
180
+ """
181
+ Perform variable substitution on 'string'.
182
+ Variables are indicated by format-style braces ("{var}").
183
+ Variable is substituted by the value found in the 'local_vars'
184
+ dictionary or in 'os.environ' if it's not in 'local_vars'.
185
+ 'os.environ' is first checked/augmented to guarantee that it contains
186
+ certain values: see 'check_environ()'. Raise ValueError for any
187
+ variables not found in either 'local_vars' or 'os.environ'.
188
+ """
189
+ check_environ()
190
+ lookup = dict(os.environ)
191
+ lookup.update((name, str(value)) for name, value in local_vars.items())
192
+ try:
193
+ return _subst_compat(s).format_map(lookup)
194
+ except KeyError as var:
195
+ raise ValueError(f"invalid variable {var}")
196
+
197
+
198
+ def _subst_compat(s):
199
+ """
200
+ Replace shell/Perl-style variable substitution with
201
+ format-style. For compatibility.
202
+ """
203
+
204
+ def _subst(match):
205
+ return f'{{{match.group(1)}}}'
206
+
207
+ repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
208
+ if repl != s:
209
+ import warnings
210
+
211
+ warnings.warn(
212
+ "shell/Perl-style substitutions are deprecated",
213
+ DeprecationWarning,
214
+ )
215
+ return repl
216
+
217
+
218
+ def grok_environment_error(exc, prefix="error: "):
219
+ # Function kept for backward compatibility.
220
+ # Used to try clever things with EnvironmentErrors,
221
+ # but nowadays str(exception) produces good messages.
222
+ return prefix + str(exc)
223
+
224
+
225
+ # Needed by 'split_quoted()'
226
+ _wordchars_re = _squote_re = _dquote_re = None
227
+
228
+
229
+ def _init_regex():
230
+ global _wordchars_re, _squote_re, _dquote_re
231
+ _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*')
232
+ _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
233
+ _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
234
+
235
+
236
+ def split_quoted(s):
237
+ """Split a string up according to Unix shell-like rules for quotes and
238
+ backslashes. In short: words are delimited by spaces, as long as those
239
+ spaces are not escaped by a backslash, or inside a quoted string.
240
+ Single and double quotes are equivalent, and the quote characters can
241
+ be backslash-escaped. The backslash is stripped from any two-character
242
+ escape sequence, leaving only the escaped character. The quote
243
+ characters are stripped from any quoted string. Returns a list of
244
+ words.
245
+ """
246
+
247
+ # This is a nice algorithm for splitting up a single string, since it
248
+ # doesn't require character-by-character examination. It was a little
249
+ # bit of a brain-bender to get it working right, though...
250
+ if _wordchars_re is None:
251
+ _init_regex()
252
+
253
+ s = s.strip()
254
+ words = []
255
+ pos = 0
256
+
257
+ while s:
258
+ m = _wordchars_re.match(s, pos)
259
+ end = m.end()
260
+ if end == len(s):
261
+ words.append(s[:end])
262
+ break
263
+
264
+ if s[end] in string.whitespace:
265
+ # unescaped, unquoted whitespace: now
266
+ # we definitely have a word delimiter
267
+ words.append(s[:end])
268
+ s = s[end:].lstrip()
269
+ pos = 0
270
+
271
+ elif s[end] == '\\':
272
+ # preserve whatever is being escaped;
273
+ # will become part of the current word
274
+ s = s[:end] + s[end + 1 :]
275
+ pos = end + 1
276
+
277
+ else:
278
+ if s[end] == "'": # slurp singly-quoted string
279
+ m = _squote_re.match(s, end)
280
+ elif s[end] == '"': # slurp doubly-quoted string
281
+ m = _dquote_re.match(s, end)
282
+ else:
283
+ raise RuntimeError(f"this can't happen (bad char '{s[end]}')")
284
+
285
+ if m is None:
286
+ raise ValueError(f"bad string (mismatched {s[end]} quotes?)")
287
+
288
+ (beg, end) = m.span()
289
+ s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
290
+ pos = m.end() - 2
291
+
292
+ if pos >= len(s):
293
+ words.append(s)
294
+ break
295
+
296
+ return words
297
+
298
+
299
+ # split_quoted ()
300
+
301
+
302
+ def execute(func, args, msg=None, verbose=False, dry_run=False):
303
+ """Perform some action that affects the outside world (eg. by
304
+ writing to the filesystem). Such actions are special because they
305
+ are disabled by the 'dry_run' flag. This method takes care of all
306
+ that bureaucracy for you; all you have to do is supply the
307
+ function to call and an argument tuple for it (to embody the
308
+ "external action" being performed), and an optional message to
309
+ print.
310
+ """
311
+ if msg is None:
312
+ msg = f"{func.__name__}{args!r}"
313
+ if msg[-2:] == ',)': # correct for singleton tuple
314
+ msg = msg[0:-2] + ')'
315
+
316
+ log.info(msg)
317
+ if not dry_run:
318
+ func(*args)
319
+
320
+
321
+ def strtobool(val):
322
+ """Convert a string representation of truth to true (1) or false (0).
323
+
324
+ True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
325
+ are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
326
+ 'val' is anything else.
327
+ """
328
+ val = val.lower()
329
+ if val in ('y', 'yes', 't', 'true', 'on', '1'):
330
+ return 1
331
+ elif val in ('n', 'no', 'f', 'false', 'off', '0'):
332
+ return 0
333
+ else:
334
+ raise ValueError(f"invalid truth value {val!r}")
335
+
336
+
337
+ def byte_compile( # noqa: C901
338
+ py_files,
339
+ optimize=0,
340
+ force=False,
341
+ prefix=None,
342
+ base_dir=None,
343
+ verbose=True,
344
+ dry_run=False,
345
+ direct=None,
346
+ ):
347
+ """Byte-compile a collection of Python source files to .pyc
348
+ files in a __pycache__ subdirectory. 'py_files' is a list
349
+ of files to compile; any files that don't end in ".py" are silently
350
+ skipped. 'optimize' must be one of the following:
351
+ 0 - don't optimize
352
+ 1 - normal optimization (like "python -O")
353
+ 2 - extra optimization (like "python -OO")
354
+ If 'force' is true, all files are recompiled regardless of
355
+ timestamps.
356
+
357
+ The source filename encoded in each bytecode file defaults to the
358
+ filenames listed in 'py_files'; you can modify these with 'prefix' and
359
+ 'basedir'. 'prefix' is a string that will be stripped off of each
360
+ source filename, and 'base_dir' is a directory name that will be
361
+ prepended (after 'prefix' is stripped). You can supply either or both
362
+ (or neither) of 'prefix' and 'base_dir', as you wish.
363
+
364
+ If 'dry_run' is true, doesn't actually do anything that would
365
+ affect the filesystem.
366
+
367
+ Byte-compilation is either done directly in this interpreter process
368
+ with the standard py_compile module, or indirectly by writing a
369
+ temporary script and executing it. Normally, you should let
370
+ 'byte_compile()' figure out to use direct compilation or not (see
371
+ the source for details). The 'direct' flag is used by the script
372
+ generated in indirect mode; unless you know what you're doing, leave
373
+ it set to None.
374
+ """
375
+
376
+ # nothing is done if sys.dont_write_bytecode is True
377
+ if sys.dont_write_bytecode:
378
+ raise DistutilsByteCompileError('byte-compiling is disabled.')
379
+
380
+ # First, if the caller didn't force us into direct or indirect mode,
381
+ # figure out which mode we should be in. We take a conservative
382
+ # approach: choose direct mode *only* if the current interpreter is
383
+ # in debug mode and optimize is 0. If we're not in debug mode (-O
384
+ # or -OO), we don't know which level of optimization this
385
+ # interpreter is running with, so we can't do direct
386
+ # byte-compilation and be certain that it's the right thing. Thus,
387
+ # always compile indirectly if the current interpreter is in either
388
+ # optimize mode, or if either optimization level was requested by
389
+ # the caller.
390
+ if direct is None:
391
+ direct = __debug__ and optimize == 0
392
+
393
+ # "Indirect" byte-compilation: write a temporary script and then
394
+ # run it with the appropriate flags.
395
+ if not direct:
396
+ (script_fd, script_name) = tempfile.mkstemp(".py")
397
+ log.info("writing byte-compilation script '%s'", script_name)
398
+ if not dry_run:
399
+ script = os.fdopen(script_fd, "w", encoding='utf-8')
400
+
401
+ with script:
402
+ script.write(
403
+ """\
404
+ from distutils.util import byte_compile
405
+ files = [
406
+ """
407
+ )
408
+
409
+ # XXX would be nice to write absolute filenames, just for
410
+ # safety's sake (script should be more robust in the face of
411
+ # chdir'ing before running it). But this requires abspath'ing
412
+ # 'prefix' as well, and that breaks the hack in build_lib's
413
+ # 'byte_compile()' method that carefully tacks on a trailing
414
+ # slash (os.sep really) to make sure the prefix here is "just
415
+ # right". This whole prefix business is rather delicate -- the
416
+ # problem is that it's really a directory, but I'm treating it
417
+ # as a dumb string, so trailing slashes and so forth matter.
418
+
419
+ script.write(",\n".join(map(repr, py_files)) + "]\n")
420
+ script.write(
421
+ f"""
422
+ byte_compile(files, optimize={optimize!r}, force={force!r},
423
+ prefix={prefix!r}, base_dir={base_dir!r},
424
+ verbose={verbose!r}, dry_run=False,
425
+ direct=True)
426
+ """
427
+ )
428
+
429
+ cmd = [sys.executable]
430
+ cmd.extend(subprocess._optim_args_from_interpreter_flags())
431
+ cmd.append(script_name)
432
+ spawn(cmd, dry_run=dry_run)
433
+ execute(os.remove, (script_name,), f"removing {script_name}", dry_run=dry_run)
434
+
435
+ # "Direct" byte-compilation: use the py_compile module to compile
436
+ # right here, right now. Note that the script generated in indirect
437
+ # mode simply calls 'byte_compile()' in direct mode, a weird sort of
438
+ # cross-process recursion. Hey, it works!
439
+ else:
440
+ from py_compile import compile
441
+
442
+ for file in py_files:
443
+ if file[-3:] != ".py":
444
+ # This lets us be lazy and not filter filenames in
445
+ # the "install_lib" command.
446
+ continue
447
+
448
+ # Terminology from the py_compile module:
449
+ # cfile - byte-compiled file
450
+ # dfile - purported source filename (same as 'file' by default)
451
+ if optimize >= 0:
452
+ opt = '' if optimize == 0 else optimize
453
+ cfile = importlib.util.cache_from_source(file, optimization=opt)
454
+ else:
455
+ cfile = importlib.util.cache_from_source(file)
456
+ dfile = file
457
+ if prefix:
458
+ if file[: len(prefix)] != prefix:
459
+ raise ValueError(
460
+ f"invalid prefix: filename {file!r} doesn't start with {prefix!r}"
461
+ )
462
+ dfile = dfile[len(prefix) :]
463
+ if base_dir:
464
+ dfile = os.path.join(base_dir, dfile)
465
+
466
+ cfile_base = os.path.basename(cfile)
467
+ if direct:
468
+ if force or newer(file, cfile):
469
+ log.info("byte-compiling %s to %s", file, cfile_base)
470
+ if not dry_run:
471
+ compile(file, cfile, dfile)
472
+ else:
473
+ log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
474
+
475
+
476
+ def rfc822_escape(header):
477
+ """Return a version of the string escaped for inclusion in an
478
+ RFC-822 header, by ensuring there are 8 spaces space after each newline.
479
+ """
480
+ indent = 8 * " "
481
+ lines = header.splitlines(keepends=True)
482
+
483
+ # Emulate the behaviour of `str.split`
484
+ # (the terminal line break in `splitlines` does not result in an extra line):
485
+ ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1]
486
+ suffix = indent if ends_in_newline else ""
487
+
488
+ return indent.join(lines) + suffix
489
+
490
+
491
+ def is_mingw():
492
+ """Returns True if the current platform is mingw.
493
+
494
+ Python compiled with Mingw-w64 has sys.platform == 'win32' and
495
+ get_platform() starts with 'mingw'.
496
+ """
497
+ return sys.platform == 'win32' and get_platform().startswith('mingw')
498
+
499
+
500
+ def is_freethreaded():
501
+ """Return True if the Python interpreter is built with free threading support."""
502
+ return bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
evalkit_llava/lib/python3.10/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
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/versionpredicate.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for parsing and testing package version predicate strings."""
2
+
3
+ import operator
4
+ import re
5
+
6
+ from . import version
7
+
8
+ re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
9
+ # (package) (rest)
10
+
11
+ re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
12
+ re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
13
+ # (comp) (version)
14
+
15
+
16
+ def splitUp(pred):
17
+ """Parse a single version comparison.
18
+
19
+ Return (comparison string, StrictVersion)
20
+ """
21
+ res = re_splitComparison.match(pred)
22
+ if not res:
23
+ raise ValueError(f"bad package restriction syntax: {pred!r}")
24
+ comp, verStr = res.groups()
25
+ with version.suppress_known_deprecation():
26
+ other = version.StrictVersion(verStr)
27
+ return (comp, other)
28
+
29
+
30
+ compmap = {
31
+ "<": operator.lt,
32
+ "<=": operator.le,
33
+ "==": operator.eq,
34
+ ">": operator.gt,
35
+ ">=": operator.ge,
36
+ "!=": operator.ne,
37
+ }
38
+
39
+
40
+ class VersionPredicate:
41
+ """Parse and test package version predicates.
42
+
43
+ >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')
44
+
45
+ The `name` attribute provides the full dotted name that is given::
46
+
47
+ >>> v.name
48
+ 'pyepat.abc'
49
+
50
+ The str() of a `VersionPredicate` provides a normalized
51
+ human-readable version of the expression::
52
+
53
+ >>> print(v)
54
+ pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
55
+
56
+ The `satisfied_by()` method can be used to determine with a given
57
+ version number is included in the set described by the version
58
+ restrictions::
59
+
60
+ >>> v.satisfied_by('1.1')
61
+ True
62
+ >>> v.satisfied_by('1.4')
63
+ True
64
+ >>> v.satisfied_by('1.0')
65
+ False
66
+ >>> v.satisfied_by('4444.4')
67
+ False
68
+ >>> v.satisfied_by('1555.1b3')
69
+ False
70
+
71
+ `VersionPredicate` is flexible in accepting extra whitespace::
72
+
73
+ >>> v = VersionPredicate(' pat( == 0.1 ) ')
74
+ >>> v.name
75
+ 'pat'
76
+ >>> v.satisfied_by('0.1')
77
+ True
78
+ >>> v.satisfied_by('0.2')
79
+ False
80
+
81
+ If any version numbers passed in do not conform to the
82
+ restrictions of `StrictVersion`, a `ValueError` is raised::
83
+
84
+ >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')
85
+ Traceback (most recent call last):
86
+ ...
87
+ ValueError: invalid version number '1.2zb3'
88
+
89
+ It the module or package name given does not conform to what's
90
+ allowed as a legal module or package name, `ValueError` is
91
+ raised::
92
+
93
+ >>> v = VersionPredicate('foo-bar')
94
+ Traceback (most recent call last):
95
+ ...
96
+ ValueError: expected parenthesized list: '-bar'
97
+
98
+ >>> v = VersionPredicate('foo bar (12.21)')
99
+ Traceback (most recent call last):
100
+ ...
101
+ ValueError: expected parenthesized list: 'bar (12.21)'
102
+
103
+ """
104
+
105
+ def __init__(self, versionPredicateStr):
106
+ """Parse a version predicate string."""
107
+ # Fields:
108
+ # name: package name
109
+ # pred: list of (comparison string, StrictVersion)
110
+
111
+ versionPredicateStr = versionPredicateStr.strip()
112
+ if not versionPredicateStr:
113
+ raise ValueError("empty package restriction")
114
+ match = re_validPackage.match(versionPredicateStr)
115
+ if not match:
116
+ raise ValueError(f"bad package name in {versionPredicateStr!r}")
117
+ self.name, paren = match.groups()
118
+ paren = paren.strip()
119
+ if paren:
120
+ match = re_paren.match(paren)
121
+ if not match:
122
+ raise ValueError(f"expected parenthesized list: {paren!r}")
123
+ str = match.groups()[0]
124
+ self.pred = [splitUp(aPred) for aPred in str.split(",")]
125
+ if not self.pred:
126
+ raise ValueError(f"empty parenthesized list in {versionPredicateStr!r}")
127
+ else:
128
+ self.pred = []
129
+
130
+ def __str__(self):
131
+ if self.pred:
132
+ seq = [cond + " " + str(ver) for cond, ver in self.pred]
133
+ return self.name + " (" + ", ".join(seq) + ")"
134
+ else:
135
+ return self.name
136
+
137
+ def satisfied_by(self, version):
138
+ """True if version is compatible with all the predicates in self.
139
+ The parameter version must be acceptable to the StrictVersion
140
+ constructor. It may be either a string or StrictVersion.
141
+ """
142
+ for cond, ver in self.pred:
143
+ if not compmap[cond](version, ver):
144
+ return False
145
+ return True
146
+
147
+
148
+ _provision_rx = None
149
+
150
+
151
+ def split_provision(value):
152
+ """Return the name and optional version number of a provision.
153
+
154
+ The version number, if given, will be returned as a `StrictVersion`
155
+ instance, otherwise it will be `None`.
156
+
157
+ >>> split_provision('mypkg')
158
+ ('mypkg', None)
159
+ >>> split_provision(' mypkg( 1.2 ) ')
160
+ ('mypkg', StrictVersion ('1.2'))
161
+ """
162
+ global _provision_rx
163
+ if _provision_rx is None:
164
+ _provision_rx = re.compile(
165
+ r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII
166
+ )
167
+ value = value.strip()
168
+ m = _provision_rx.match(value)
169
+ if not m:
170
+ raise ValueError(f"illegal provides specification: {value!r}")
171
+ ver = m.group(2) or None
172
+ if ver:
173
+ with version.suppress_known_deprecation():
174
+ ver = version.StrictVersion(ver)
175
+ return m.group(1), ver
evalkit_llava/lib/python3.10/site-packages/setuptools/_distutils/zosccompiler.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.zosccompiler
2
+
3
+ Contains the selection of the c & c++ compilers on z/OS. There are several
4
+ different c compilers on z/OS, all of them are optional, so the correct
5
+ one needs to be chosen based on the users input. This is compatible with
6
+ the following compilers:
7
+
8
+ IBM C/C++ For Open Enterprise Languages on z/OS 2.0
9
+ IBM Open XL C/C++ 1.1 for z/OS
10
+ IBM XL C/C++ V2.4.1 for z/OS 2.4 and 2.5
11
+ IBM z/OS XL C/C++
12
+ """
13
+
14
+ import os
15
+
16
+ from . import sysconfig
17
+ from .errors import CompileError, DistutilsExecError
18
+ from .unixccompiler import UnixCCompiler
19
+
20
+ _cc_args = {
21
+ 'ibm-openxl': [
22
+ '-m64',
23
+ '-fvisibility=default',
24
+ '-fzos-le-char-mode=ascii',
25
+ '-fno-short-enums',
26
+ ],
27
+ 'ibm-xlclang': [
28
+ '-q64',
29
+ '-qexportall',
30
+ '-qascii',
31
+ '-qstrict',
32
+ '-qnocsect',
33
+ '-Wa,asa,goff',
34
+ '-Wa,xplink',
35
+ '-qgonumber',
36
+ '-qenum=int',
37
+ '-Wc,DLL',
38
+ ],
39
+ 'ibm-xlc': [
40
+ '-q64',
41
+ '-qexportall',
42
+ '-qascii',
43
+ '-qstrict',
44
+ '-qnocsect',
45
+ '-Wa,asa,goff',
46
+ '-Wa,xplink',
47
+ '-qgonumber',
48
+ '-qenum=int',
49
+ '-Wc,DLL',
50
+ '-qlanglvl=extc99',
51
+ ],
52
+ }
53
+
54
+ _cxx_args = {
55
+ 'ibm-openxl': [
56
+ '-m64',
57
+ '-fvisibility=default',
58
+ '-fzos-le-char-mode=ascii',
59
+ '-fno-short-enums',
60
+ ],
61
+ 'ibm-xlclang': [
62
+ '-q64',
63
+ '-qexportall',
64
+ '-qascii',
65
+ '-qstrict',
66
+ '-qnocsect',
67
+ '-Wa,asa,goff',
68
+ '-Wa,xplink',
69
+ '-qgonumber',
70
+ '-qenum=int',
71
+ '-Wc,DLL',
72
+ ],
73
+ 'ibm-xlc': [
74
+ '-q64',
75
+ '-qexportall',
76
+ '-qascii',
77
+ '-qstrict',
78
+ '-qnocsect',
79
+ '-Wa,asa,goff',
80
+ '-Wa,xplink',
81
+ '-qgonumber',
82
+ '-qenum=int',
83
+ '-Wc,DLL',
84
+ '-qlanglvl=extended0x',
85
+ ],
86
+ }
87
+
88
+ _asm_args = {
89
+ 'ibm-openxl': ['-fasm', '-fno-integrated-as', '-Wa,--ASA', '-Wa,--GOFF'],
90
+ 'ibm-xlclang': [],
91
+ 'ibm-xlc': [],
92
+ }
93
+
94
+ _ld_args = {
95
+ 'ibm-openxl': [],
96
+ 'ibm-xlclang': ['-Wl,dll', '-q64'],
97
+ 'ibm-xlc': ['-Wl,dll', '-q64'],
98
+ }
99
+
100
+
101
+ # Python on z/OS is built with no compiler specific options in it's CFLAGS.
102
+ # But each compiler requires it's own specific options to build successfully,
103
+ # though some of the options are common between them
104
+ class zOSCCompiler(UnixCCompiler):
105
+ src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s']
106
+ _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C']
107
+ _asm_extensions = ['.s']
108
+
109
+ def _get_zos_compiler_name(self):
110
+ zos_compiler_names = [
111
+ os.path.basename(binary)
112
+ for envvar in ('CC', 'CXX', 'LDSHARED')
113
+ if (binary := os.environ.get(envvar, None))
114
+ ]
115
+ if len(zos_compiler_names) == 0:
116
+ return 'ibm-openxl'
117
+
118
+ zos_compilers = {}
119
+ for compiler in (
120
+ 'ibm-clang',
121
+ 'ibm-clang64',
122
+ 'ibm-clang++',
123
+ 'ibm-clang++64',
124
+ 'clang',
125
+ 'clang++',
126
+ 'clang-14',
127
+ ):
128
+ zos_compilers[compiler] = 'ibm-openxl'
129
+
130
+ for compiler in ('xlclang', 'xlclang++', 'njsc', 'njsc++'):
131
+ zos_compilers[compiler] = 'ibm-xlclang'
132
+
133
+ for compiler in ('xlc', 'xlC', 'xlc++'):
134
+ zos_compilers[compiler] = 'ibm-xlc'
135
+
136
+ return zos_compilers.get(zos_compiler_names[0], 'ibm-openxl')
137
+
138
+ def __init__(self, verbose=False, dry_run=False, force=False):
139
+ super().__init__(verbose, dry_run, force)
140
+ self.zos_compiler = self._get_zos_compiler_name()
141
+ sysconfig.customize_compiler(self)
142
+
143
+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
144
+ local_args = []
145
+ if ext in self._cpp_extensions:
146
+ compiler = self.compiler_cxx
147
+ local_args.extend(_cxx_args[self.zos_compiler])
148
+ elif ext in self._asm_extensions:
149
+ compiler = self.compiler_so
150
+ local_args.extend(_cc_args[self.zos_compiler])
151
+ local_args.extend(_asm_args[self.zos_compiler])
152
+ else:
153
+ compiler = self.compiler_so
154
+ local_args.extend(_cc_args[self.zos_compiler])
155
+ local_args.extend(cc_args)
156
+
157
+ try:
158
+ self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs)
159
+ except DistutilsExecError as msg:
160
+ raise CompileError(msg)
161
+
162
+ def runtime_library_dir_option(self, dir):
163
+ return '-L' + dir
164
+
165
+ def link(
166
+ self,
167
+ target_desc,
168
+ objects,
169
+ output_filename,
170
+ output_dir=None,
171
+ libraries=None,
172
+ library_dirs=None,
173
+ runtime_library_dirs=None,
174
+ export_symbols=None,
175
+ debug=False,
176
+ extra_preargs=None,
177
+ extra_postargs=None,
178
+ build_temp=None,
179
+ target_lang=None,
180
+ ):
181
+ # For a built module to use functions from cpython, it needs to use Pythons
182
+ # side deck file. The side deck is located beside the libpython3.xx.so
183
+ ldversion = sysconfig.get_config_var('LDVERSION')
184
+ if sysconfig.python_build:
185
+ side_deck_path = os.path.join(
186
+ sysconfig.get_config_var('abs_builddir'),
187
+ f'libpython{ldversion}.x',
188
+ )
189
+ else:
190
+ side_deck_path = os.path.join(
191
+ sysconfig.get_config_var('installed_base'),
192
+ sysconfig.get_config_var('platlibdir'),
193
+ f'libpython{ldversion}.x',
194
+ )
195
+
196
+ if os.path.exists(side_deck_path):
197
+ if extra_postargs:
198
+ extra_postargs.append(side_deck_path)
199
+ else:
200
+ extra_postargs = [side_deck_path]
201
+
202
+ # Check and replace libraries included side deck files
203
+ if runtime_library_dirs:
204
+ for dir in runtime_library_dirs:
205
+ for library in libraries[:]:
206
+ library_side_deck = os.path.join(dir, f'{library}.x')
207
+ if os.path.exists(library_side_deck):
208
+ libraries.remove(library)
209
+ extra_postargs.append(library_side_deck)
210
+ break
211
+
212
+ # Any required ld args for the given compiler
213
+ extra_postargs.extend(_ld_args[self.zos_compiler])
214
+
215
+ super().link(
216
+ target_desc,
217
+ objects,
218
+ output_filename,
219
+ output_dir,
220
+ libraries,
221
+ library_dirs,
222
+ runtime_library_dirs,
223
+ export_symbols,
224
+ debug,
225
+ extra_preargs,
226
+ extra_postargs,
227
+ build_temp,
228
+ target_lang,
229
+ )
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (457 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/contexts.cpython-310.pyc ADDED
Binary file (3.93 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/namespaces.cpython-310.pyc ADDED
Binary file (2.73 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc ADDED
Binary file (174 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc ADDED
Binary file (1.15 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc ADDED
Binary file (1.03 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc ADDED
Binary file (2.36 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc ADDED
Binary file (9.37 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc ADDED
Binary file (20.5 kB). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_depends.cpython-310.pyc ADDED
Binary file (759 Bytes). View file
 
evalkit_llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_develop.cpython-310.pyc ADDED
Binary file (5.69 kB). View file