diff --git a/.gitattributes b/.gitattributes index b55484d82e83f8350071db48d5b0bb1747f35bc8..dc72d1440ffeb0f38a03225417dd13ac6abc85cb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -538,3 +538,4 @@ mantis_evalkit/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_ mantis_evalkit/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text mantis_evalkit/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/kiwisolver/_cext.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +mantis_evalkit/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/__init__.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e374d5c5604d0eeed555e68b7523bfac72fd9101 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/__init__.py @@ -0,0 +1,14 @@ +import importlib +import sys + +__version__, _, _ = sys.version.partition(' ') + + +try: + # Allow Debian and pkgsrc (only) to customize system + # behavior. Ref pypa/distutils#2 and pypa/distutils#16. + # This hook is deprecated and no other environments + # should use it. + importlib.import_module('_distutils_system_mod') +except ImportError: + pass diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_log.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_log.py new file mode 100644 index 0000000000000000000000000000000000000000..0148f157ff3bf8bd728c82f49cd3d1cd9cb5a43e --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_log.py @@ -0,0 +1,3 @@ +import logging + +log = logging.getLogger() diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_macos_compat.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_macos_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..76ecb96abe478313ce7d09342b2643bf4a765331 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_macos_compat.py @@ -0,0 +1,12 @@ +import importlib +import sys + + +def bypass_compiler_fixup(cmd, args): + return cmd + + +if sys.platform == 'darwin': + compiler_fixup = importlib.import_module('_osx_support').compiler_fixup +else: + compiler_fixup = bypass_compiler_fixup diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_modified.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_modified.py new file mode 100644 index 0000000000000000000000000000000000000000..7cdca9398f487bf405e0db0272f8aa9672d30b5e --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_modified.py @@ -0,0 +1,73 @@ +"""Timestamp comparison of files and groups of files.""" + +import functools +import os.path + +from jaraco.functools import splat + +from .compat.py39 import zip_strict +from .errors import DistutilsFileError + + +def _newer(source, target): + return not os.path.exists(target) or ( + os.path.getmtime(source) > os.path.getmtime(target) + ) + + +def newer(source, target): + """ + Is source modified more recently than target. + + Returns True if 'source' is modified more recently than + 'target' or if 'target' does not exist. + + Raises DistutilsFileError if 'source' does not exist. + """ + if not os.path.exists(source): + raise DistutilsFileError(f"file '{os.path.abspath(source)}' does not exist") + + return _newer(source, target) + + +def newer_pairwise(sources, targets, newer=newer): + """ + Filter filenames where sources are newer than targets. + + Walk two filename iterables in parallel, testing if each source is newer + than its corresponding target. Returns a pair of lists (sources, + targets) where source is newer than target, according to the semantics + of 'newer()'. + """ + newer_pairs = filter(splat(newer), zip_strict(sources, targets)) + return tuple(map(list, zip(*newer_pairs))) or ([], []) + + +def newer_group(sources, target, missing='error'): + """ + Is target out-of-date with respect to any file in sources. + + Return True if 'target' is out-of-date with respect to any file + listed in 'sources'. In other words, if 'target' exists and is newer + than every file in 'sources', return False; otherwise return True. + ``missing`` controls how to handle a missing source file: + + - error (default): allow the ``stat()`` call to fail. + - ignore: silently disregard any missing source files. + - newer: treat missing source files as "target out of date". This + mode is handy in "dry-run" mode: it will pretend to carry out + commands that wouldn't work because inputs are missing, but + that doesn't matter because dry-run won't run the commands. + """ + + def missing_as_newer(source): + return missing == 'newer' and not os.path.exists(source) + + ignored = os.path.exists if missing == 'ignore' else None + return not os.path.exists(target) or any( + missing_as_newer(source) or _newer(source, target) + for source in filter(ignored, sources) + ) + + +newer_pairwise_group = functools.partial(newer_pairwise, newer=newer_group) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_msvccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_msvccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..849aa7597b7a94d26da337e8d7bc1438d7703514 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/_msvccompiler.py @@ -0,0 +1,611 @@ +"""distutils._msvccompiler + +Contains MSVCCompiler, an implementation of the abstract CCompiler class +for Microsoft Visual Studio 2015. + +This module requires VS 2015 or later. +""" + +# Written by Perry Stoll +# hacked by Robin Becker and Thomas Heller to do a better job of +# finding DevStudio (through the registry) +# ported to VS 2005 and VS 2008 by Christian Heimes +# ported to VS 2015 by Steve Dower + +import contextlib +import os +import subprocess +import unittest.mock as mock +import warnings + +with contextlib.suppress(ImportError): + import winreg + +from itertools import count + +from ._log import log +from .ccompiler import CCompiler, gen_lib_options +from .errors import ( + CompileError, + DistutilsExecError, + DistutilsPlatformError, + LibError, + LinkError, +) +from .util import get_host_platform, get_platform + + +def _find_vc2015(): + try: + key = winreg.OpenKeyEx( + winreg.HKEY_LOCAL_MACHINE, + r"Software\Microsoft\VisualStudio\SxS\VC7", + access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY, + ) + except OSError: + log.debug("Visual C++ is not registered") + return None, None + + best_version = 0 + best_dir = None + with key: + for i in count(): + try: + v, vc_dir, vt = winreg.EnumValue(key, i) + except OSError: + break + if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir): + try: + version = int(float(v)) + except (ValueError, TypeError): + continue + if version >= 14 and version > best_version: + best_version, best_dir = version, vc_dir + return best_version, best_dir + + +def _find_vc2017(): + """Returns "15, path" based on the result of invoking vswhere.exe + If no install is found, returns "None, None" + + The version is returned to avoid unnecessarily changing the function + result. It may be ignored when the path is not None. + + If vswhere.exe is not available, by definition, VS 2017 is not + installed. + """ + root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles") + if not root: + return None, None + + variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64' + suitable_components = ( + f"Microsoft.VisualStudio.Component.VC.Tools.{variant}", + "Microsoft.VisualStudio.Workload.WDExpress", + ) + + for component in suitable_components: + # Workaround for `-requiresAny` (only available on VS 2017 > 15.6) + with contextlib.suppress( + subprocess.CalledProcessError, OSError, UnicodeDecodeError + ): + path = ( + subprocess.check_output([ + os.path.join( + root, "Microsoft Visual Studio", "Installer", "vswhere.exe" + ), + "-latest", + "-prerelease", + "-requires", + component, + "-property", + "installationPath", + "-products", + "*", + ]) + .decode(encoding="mbcs", errors="strict") + .strip() + ) + + path = os.path.join(path, "VC", "Auxiliary", "Build") + if os.path.isdir(path): + return 15, path + + return None, None # no suitable component found + + +PLAT_SPEC_TO_RUNTIME = { + 'x86': 'x86', + 'x86_amd64': 'x64', + 'x86_arm': 'arm', + 'x86_arm64': 'arm64', +} + + +def _find_vcvarsall(plat_spec): + # bpo-38597: Removed vcruntime return value + _, best_dir = _find_vc2017() + + if not best_dir: + best_version, best_dir = _find_vc2015() + + if not best_dir: + log.debug("No suitable Visual C++ version found") + return None, None + + vcvarsall = os.path.join(best_dir, "vcvarsall.bat") + if not os.path.isfile(vcvarsall): + log.debug("%s cannot be found", vcvarsall) + return None, None + + return vcvarsall, None + + +def _get_vc_env(plat_spec): + if os.getenv("DISTUTILS_USE_SDK"): + return {key.lower(): value for key, value in os.environ.items()} + + vcvarsall, _ = _find_vcvarsall(plat_spec) + if not vcvarsall: + raise DistutilsPlatformError( + 'Microsoft Visual C++ 14.0 or greater is required. ' + 'Get it with "Microsoft C++ Build Tools": ' + 'https://visualstudio.microsoft.com/visual-cpp-build-tools/' + ) + + try: + out = subprocess.check_output( + f'cmd /u /c "{vcvarsall}" {plat_spec} && set', + stderr=subprocess.STDOUT, + ).decode('utf-16le', errors='replace') + except subprocess.CalledProcessError as exc: + log.error(exc.output) + raise DistutilsPlatformError(f"Error executing {exc.cmd}") + + env = { + key.lower(): value + for key, _, value in (line.partition('=') for line in out.splitlines()) + if key and value + } + + return env + + +def _find_exe(exe, paths=None): + """Return path to an MSVC executable program. + + Tries to find the program in several places: first, one of the + MSVC program search paths from the registry; next, the directories + in the PATH environment variable. If any of those work, return an + absolute path that is known to exist. If none of them work, just + return the original program name, 'exe'. + """ + if not paths: + paths = os.getenv('path').split(os.pathsep) + for p in paths: + fn = os.path.join(os.path.abspath(p), exe) + if os.path.isfile(fn): + return fn + return exe + + +_vcvars_names = { + 'win32': 'x86', + 'win-amd64': 'amd64', + 'win-arm32': 'arm', + 'win-arm64': 'arm64', +} + + +def _get_vcvars_spec(host_platform, platform): + """ + Given a host platform and platform, determine the spec for vcvarsall. + + Uses the native MSVC host if the host platform would need expensive + emulation for x86. + + >>> _get_vcvars_spec('win-arm64', 'win32') + 'arm64_x86' + >>> _get_vcvars_spec('win-arm64', 'win-amd64') + 'arm64_amd64' + + Otherwise, always cross-compile from x86 to work with the + lighter-weight MSVC installs that do not include native 64-bit tools. + + >>> _get_vcvars_spec('win32', 'win32') + 'x86' + >>> _get_vcvars_spec('win-arm32', 'win-arm32') + 'x86_arm' + >>> _get_vcvars_spec('win-amd64', 'win-arm64') + 'x86_arm64' + """ + if host_platform != 'win-arm64': + host_platform = 'win32' + vc_hp = _vcvars_names[host_platform] + vc_plat = _vcvars_names[platform] + return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}' + + +class MSVCCompiler(CCompiler): + """Concrete class that implements an interface to Microsoft Visual C++, + as defined by the CCompiler abstract class.""" + + compiler_type = 'msvc' + + # Just set this so CCompiler's constructor doesn't barf. We currently + # don't use the 'set_executables()' bureaucracy provided by CCompiler, + # as it really isn't necessary for this sort of single-compiler class. + # Would be nice to have a consistent interface with UnixCCompiler, + # though, so it's worth thinking about. + executables = {} + + # Private class data (need to distinguish C from C++ source for compiler) + _c_extensions = ['.c'] + _cpp_extensions = ['.cc', '.cpp', '.cxx'] + _rc_extensions = ['.rc'] + _mc_extensions = ['.mc'] + + # Needed for the filename generation methods provided by the + # base class, CCompiler. + src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions + res_extension = '.res' + obj_extension = '.obj' + static_lib_extension = '.lib' + shared_lib_extension = '.dll' + static_lib_format = shared_lib_format = '%s%s' + exe_extension = '.exe' + + def __init__(self, verbose=False, dry_run=False, force=False): + super().__init__(verbose, dry_run, force) + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.initialized = False + + @classmethod + def _configure(cls, vc_env): + """ + Set class-level include/lib dirs. + """ + cls.include_dirs = cls._parse_path(vc_env.get('include', '')) + cls.library_dirs = cls._parse_path(vc_env.get('lib', '')) + + @staticmethod + def _parse_path(val): + return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir] + + def initialize(self, plat_name=None): + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + if plat_name not in _vcvars_names: + raise DistutilsPlatformError( + f"--plat-name must be one of {tuple(_vcvars_names)}" + ) + + plat_spec = _get_vcvars_spec(get_host_platform(), plat_name) + + vc_env = _get_vc_env(plat_spec) + if not vc_env: + raise DistutilsPlatformError( + "Unable to find a compatible Visual Studio installation." + ) + self._configure(vc_env) + + self._paths = vc_env.get('path', '') + paths = self._paths.split(os.pathsep) + self.cc = _find_exe("cl.exe", paths) + self.linker = _find_exe("link.exe", paths) + self.lib = _find_exe("lib.exe", paths) + self.rc = _find_exe("rc.exe", paths) # resource compiler + self.mc = _find_exe("mc.exe", paths) # message compiler + self.mt = _find_exe("mt.exe", paths) # message compiler + + self.preprocess_options = None + # bpo-38597: Always compile with dynamic linking + # Future releases of Python 3.x will include all past + # versions of vcruntime*.dll for compatibility. + self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD'] + + self.compile_options_debug = [ + '/nologo', + '/Od', + '/MDd', + '/Zi', + '/W3', + '/D_DEBUG', + ] + + ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG'] + + ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL'] + + self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1'] + self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1'] + self.ldflags_shared = [ + *ldflags, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_shared_debug = [ + *ldflags_debug, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_static = [*ldflags] + self.ldflags_static_debug = [*ldflags_debug] + + self._ldflags = { + (CCompiler.EXECUTABLE, None): self.ldflags_exe, + (CCompiler.EXECUTABLE, False): self.ldflags_exe, + (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug, + (CCompiler.SHARED_OBJECT, None): self.ldflags_shared, + (CCompiler.SHARED_OBJECT, False): self.ldflags_shared, + (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug, + (CCompiler.SHARED_LIBRARY, None): self.ldflags_static, + (CCompiler.SHARED_LIBRARY, False): self.ldflags_static, + (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug, + } + + self.initialized = True + + # -- Worker methods ------------------------------------------------ + + @property + def out_extensions(self): + return { + **super().out_extensions, + **{ + ext: self.res_extension + for ext in self._rc_extensions + self._mc_extensions + }, + } + + def compile( # noqa: C901 + self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + if not self.initialized: + self.initialize() + compile_info = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + macros, objects, extra_postargs, pp_opts, build = compile_info + + compile_opts = extra_preargs or [] + compile_opts.append('/c') + if debug: + compile_opts.extend(self.compile_options_debug) + else: + compile_opts.extend(self.compile_options) + + add_cpp_opts = False + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + if debug: + # pass the full pathname to MSVC in debug mode, + # this allows the debugger to find the source file + # without asking the user to browse for it + src = os.path.abspath(src) + + # Anaconda/conda-forge customisation, we want our pdbs to be + # relocatable: + # https://developercommunity.visualstudio.com/comments/623156/view.html + d1trimfile_opts = [] + if 'SRC_DIR' in os.environ and os.path.basename(self.cc) == "cl.exe": + d1trimfile_opts.append("/d1trimfile:" + os.environ['SRC_DIR']) + + if ext in self._c_extensions: + input_opt = "/Tc" + src + elif ext in self._cpp_extensions: + input_opt = "/Tp" + src + add_cpp_opts = True + elif ext in self._rc_extensions: + # compile .RC to .RES file + input_opt = src + output_opt = "/fo" + obj + try: + self.spawn([self.rc] + pp_opts + [output_opt, input_opt]) + except DistutilsExecError as msg: + raise CompileError(msg) + continue + elif ext in self._mc_extensions: + # Compile .MC to .RC file to .RES file. + # * '-h dir' specifies the directory for the + # generated include file + # * '-r dir' specifies the target directory of the + # generated RC file and the binary message resource + # it includes + # + # For now (since there are no options to change this), + # we use the source-directory for the include file and + # the build directory for the RC file and message + # resources. This works at least for win32all. + h_dir = os.path.dirname(src) + rc_dir = os.path.dirname(obj) + try: + # first compile .MC to .RC and .H file + self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src]) + base, _ = os.path.splitext(os.path.basename(src)) + rc_file = os.path.join(rc_dir, base + '.rc') + # then compile .RC to .RES file + self.spawn([self.rc, "/fo" + obj, rc_file]) + + except DistutilsExecError as msg: + raise CompileError(msg) + continue + else: + # how to handle this file? + raise CompileError(f"Don't know how to compile {src} to {obj}") + + args = [self.cc] + compile_opts + pp_opts + d1trimfile_opts + if add_cpp_opts: + args.append('/EHsc') + args.extend((input_opt, "/Fo" + obj)) + args.extend(extra_postargs) + + try: + self.spawn(args) + except DistutilsExecError as msg: + raise CompileError(msg) + + return objects + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + output_filename = self.library_filename(output_libname, output_dir=output_dir) + + if self._need_link(objects, output_filename): + lib_args = objects + ['/OUT:' + output_filename] + if debug: + pass # XXX what goes here? + try: + log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args)) + self.spawn([self.lib] + lib_args) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + + if runtime_library_dirs: + self.warn( + "I don't know what to do with 'runtime_library_dirs': " + + str(runtime_library_dirs) + ) + + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + ldflags = self._ldflags[target_desc, debug] + + export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])] + + ld_args = ( + ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename] + ) + + # The MSVC linker generates .lib and .exp files, which cannot be + # suppressed by any linker switches. The .lib files may even be + # needed! Make sure they are generated in the temporary build + # directory. Since they have different names for debug and release + # builds, they can go into the same directory. + build_temp = os.path.dirname(objects[0]) + if export_symbols is not None: + (dll_name, dll_ext) = os.path.splitext( + os.path.basename(output_filename) + ) + implib_file = os.path.join(build_temp, self.library_filename(dll_name)) + ld_args.append('/IMPLIB:' + implib_file) + + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + + output_dir = os.path.dirname(os.path.abspath(output_filename)) + self.mkpath(output_dir) + try: + log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args)) + self.spawn([self.linker] + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def spawn(self, cmd): + env = dict(os.environ, PATH=self._paths) + with self._fallback_spawn(cmd, env) as fallback: + return super().spawn(cmd, env=env) + return fallback.value + + @contextlib.contextmanager + def _fallback_spawn(self, cmd, env): + """ + Discovered in pypa/distutils#15, some tools monkeypatch the compiler, + so the 'env' kwarg causes a TypeError. Detect this condition and + restore the legacy, unsafe behavior. + """ + bag = type('Bag', (), {})() + try: + yield bag + except TypeError as exc: + if "unexpected keyword argument 'env'" not in str(exc): + raise + else: + return + warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.") + with mock.patch.dict('os.environ', env): + bag.value = super().spawn(cmd) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "/LIBPATH:" + dir + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError( + "don't know how to set runtime library search path for MSVC" + ) + + def library_option(self, lib): + return self.library_filename(lib) + + def find_library_file(self, dirs, lib, debug=False): + # Prefer a debugging library if found (and requested), but deal + # with it if we don't have one. + if debug: + try_names = [lib + "_d", lib] + else: + try_names = [lib] + for dir in dirs: + for name in try_names: + libfile = os.path.join(dir, self.library_filename(name)) + if os.path.isfile(libfile): + return libfile + else: + # Oops, didn't find it in *any* of 'dirs' + return None diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/archive_util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb6df763de0bd7f242e3bb786f6a9cd68bb78fe --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/archive_util.py @@ -0,0 +1,264 @@ +"""distutils.archive_util + +Utility functions for creating archive files (tarballs, zip files, +that sort of thing).""" + +import os + +try: + import zipfile +except ImportError: + zipfile = None + + +from ._log import log +from .dir_util import mkpath +from .errors import DistutilsExecError +from .spawn import spawn + +try: + from pwd import getpwnam +except ImportError: + getpwnam = None + +try: + from grp import getgrnam +except ImportError: + getgrnam = None + + +def _get_gid(name): + """Returns a gid, given a group name.""" + if getgrnam is None or name is None: + return None + try: + result = getgrnam(name) + except KeyError: + result = None + if result is not None: + return result[2] + return None + + +def _get_uid(name): + """Returns an uid, given a user name.""" + if getpwnam is None or name is None: + return None + try: + result = getpwnam(name) + except KeyError: + result = None + if result is not None: + return result[2] + return None + + +def make_tarball( + base_name, + base_dir, + compress="gzip", + verbose=False, + dry_run=False, + owner=None, + group=None, +): + """Create a (possibly compressed) tar file from all the files under + 'base_dir'. + + 'compress' must be "gzip" (the default), "bzip2", "xz", or None. + + 'owner' and 'group' can be used to define an owner and a group for the + archive that is being built. If not provided, the current owner and group + will be used. + + The output tar file will be named 'base_dir' + ".tar", possibly plus + the appropriate compression extension (".gz", ".bz2", ".xz" or ".Z"). + + Returns the output filename. + """ + tar_compression = { + 'gzip': 'gz', + 'bzip2': 'bz2', + 'xz': 'xz', + None: '', + } + compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'} + + # flags for compression program, each element of list will be an argument + if compress is not None and compress not in compress_ext.keys(): + raise ValueError( + "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'" + ) + + archive_name = base_name + '.tar' + archive_name += compress_ext.get(compress, '') + + mkpath(os.path.dirname(archive_name), dry_run=dry_run) + + # creating the tarball + import tarfile # late import so Python build itself doesn't break + + log.info('Creating tar archive') + + uid = _get_uid(owner) + gid = _get_gid(group) + + def _set_uid_gid(tarinfo): + if gid is not None: + tarinfo.gid = gid + tarinfo.gname = group + if uid is not None: + tarinfo.uid = uid + tarinfo.uname = owner + return tarinfo + + if not dry_run: + tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}') + try: + tar.add(base_dir, filter=_set_uid_gid) + finally: + tar.close() + + return archive_name + + +def make_zipfile(base_name, base_dir, verbose=False, dry_run=False): # noqa: C901 + """Create a zip file from all the files under 'base_dir'. + + The output zip file will be named 'base_name' + ".zip". Uses either the + "zipfile" Python module (if available) or the InfoZIP "zip" utility + (if installed and found on the default search path). If neither tool is + available, raises DistutilsExecError. Returns the name of the output zip + file. + """ + zip_filename = base_name + ".zip" + mkpath(os.path.dirname(zip_filename), dry_run=dry_run) + + # If zipfile module is not available, try spawning an external + # 'zip' command. + if zipfile is None: + if verbose: + zipoptions = "-r" + else: + zipoptions = "-rq" + + try: + spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) + except DistutilsExecError: + # XXX really should distinguish between "couldn't find + # external 'zip' command" and "zip failed". + raise DistutilsExecError( + f"unable to create zip file '{zip_filename}': " + "could neither import the 'zipfile' module nor " + "find a standalone zip utility" + ) + + else: + log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) + + if not dry_run: + try: + zip = zipfile.ZipFile( + zip_filename, "w", compression=zipfile.ZIP_DEFLATED + ) + except RuntimeError: + zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED) + + with zip: + if base_dir != os.curdir: + path = os.path.normpath(os.path.join(base_dir, '')) + zip.write(path, path) + log.info("adding '%s'", path) + for dirpath, dirnames, filenames in os.walk(base_dir): + for name in dirnames: + path = os.path.normpath(os.path.join(dirpath, name, '')) + zip.write(path, path) + log.info("adding '%s'", path) + for name in filenames: + path = os.path.normpath(os.path.join(dirpath, name)) + if os.path.isfile(path): + zip.write(path, path) + log.info("adding '%s'", path) + + return zip_filename + + +ARCHIVE_FORMATS = { + 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), + 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), + 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"), + 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"), + 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"), + 'zip': (make_zipfile, [], "ZIP file"), +} + + +def check_archive_formats(formats): + """Returns the first format from the 'format' list that is unknown. + + If all formats are known, returns None + """ + for format in formats: + if format not in ARCHIVE_FORMATS: + return format + return None + + +def make_archive( + base_name, + format, + root_dir=None, + base_dir=None, + verbose=False, + dry_run=False, + owner=None, + group=None, +): + """Create an archive file (eg. zip or tar). + + 'base_name' is the name of the file to create, minus any format-specific + extension; 'format' is the archive format: one of "zip", "tar", "gztar", + "bztar", "xztar", or "ztar". + + 'root_dir' is a directory that will be the root directory of the + archive; ie. we typically chdir into 'root_dir' before creating the + archive. 'base_dir' is the directory where we start archiving from; + ie. 'base_dir' will be the common prefix of all files and + directories in the archive. 'root_dir' and 'base_dir' both default + to the current directory. Returns the name of the archive file. + + 'owner' and 'group' are used when creating a tar archive. By default, + uses the current owner and group. + """ + save_cwd = os.getcwd() + if root_dir is not None: + log.debug("changing into '%s'", root_dir) + base_name = os.path.abspath(base_name) + if not dry_run: + os.chdir(root_dir) + + if base_dir is None: + base_dir = os.curdir + + kwargs = {'dry_run': dry_run} + + try: + format_info = ARCHIVE_FORMATS[format] + except KeyError: + raise ValueError(f"unknown archive format '{format}'") + + func = format_info[0] + kwargs.update(format_info[1]) + + if format != 'zip': + kwargs['owner'] = owner + kwargs['group'] = group + + try: + filename = func(base_name, base_dir, **kwargs) + finally: + if root_dir is not None: + log.debug("changing back to '%s'", save_cwd) + os.chdir(save_cwd) + + return filename diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/ccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/ccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..714f13d8d30060542139ccf94c798e34134c0d98 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/ccompiler.py @@ -0,0 +1,1263 @@ +"""distutils.ccompiler + +Contains CCompiler, an abstract base class that defines the interface +for the Distutils compiler abstraction model.""" + +import os +import pathlib +import re +import sys +import types +import warnings + +from more_itertools import always_iterable + +from ._log import log +from ._modified import newer_group +from .dir_util import mkpath +from .errors import ( + CompileError, + DistutilsModuleError, + DistutilsPlatformError, + LinkError, + UnknownFileError, +) +from .file_util import move_file +from .spawn import spawn +from .util import execute, is_mingw, split_quoted + + +class CCompiler: + """Abstract base class to define the interface that must be implemented + by real compiler classes. Also has some utility methods used by + several compiler classes. + + The basic idea behind a compiler abstraction class is that each + instance can be used for all the compile/link steps in building a + single project. Thus, attributes common to all of those compile and + link steps -- include directories, macros to define, libraries to link + against, etc. -- are attributes of the compiler instance. To allow for + variability in how individual files are treated, most of those + attributes may be varied on a per-compilation or per-link basis. + """ + + # 'compiler_type' is a class attribute that identifies this class. It + # keeps code that wants to know what kind of compiler it's dealing with + # from having to import all possible compiler classes just to do an + # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type' + # should really, really be one of the keys of the 'compiler_class' + # dictionary (see below -- used by the 'new_compiler()' factory + # function) -- authors of new compiler interface classes are + # responsible for updating 'compiler_class'! + compiler_type = None + + # XXX things not handled by this compiler abstraction model: + # * client can't provide additional options for a compiler, + # e.g. warning, optimization, debugging flags. Perhaps this + # should be the domain of concrete compiler abstraction classes + # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base + # class should have methods for the common ones. + # * can't completely override the include or library searchg + # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2". + # I'm not sure how widely supported this is even by Unix + # compilers, much less on other platforms. And I'm even less + # sure how useful it is; maybe for cross-compiling, but + # support for that is a ways off. (And anyways, cross + # compilers probably have a dedicated binary with the + # right paths compiled in. I hope.) + # * can't do really freaky things with the library list/library + # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against + # different versions of libfoo.a in different locations. I + # think this is useless without the ability to null out the + # library search path anyways. + + # Subclasses that rely on the standard filename generation methods + # implemented below should override these; see the comment near + # those methods ('object_filenames()' et. al.) for details: + src_extensions = None # list of strings + obj_extension = None # string + static_lib_extension = None + shared_lib_extension = None # string + static_lib_format = None # format string + shared_lib_format = None # prob. same as static_lib_format + exe_extension = None # string + + # Default language settings. language_map is used to detect a source + # file or Extension target language, checking source filenames. + # language_order is used to detect the language precedence, when deciding + # what language to use when mixing source types. For example, if some + # extension has two files with ".c" extension, and one with ".cpp", it + # is still linked as c++. + language_map = { + ".c": "c", + ".cc": "c++", + ".cpp": "c++", + ".cxx": "c++", + ".m": "objc", + } + language_order = ["c++", "objc", "c"] + + include_dirs = [] + """ + include dirs specific to this compiler class + """ + + library_dirs = [] + """ + library dirs specific to this compiler class + """ + + def __init__(self, verbose=False, dry_run=False, force=False): + self.dry_run = dry_run + self.force = force + self.verbose = verbose + + # 'output_dir': a common output directory for object, library, + # shared object, and shared library files + self.output_dir = None + + # 'macros': a list of macro definitions (or undefinitions). A + # macro definition is a 2-tuple (name, value), where the value is + # either a string or None (no explicit value). A macro + # undefinition is a 1-tuple (name,). + self.macros = [] + + # 'include_dirs': a list of directories to search for include files + self.include_dirs = [] + + # 'libraries': a list of libraries to include in any link + # (library names, not filenames: eg. "foo" not "libfoo.a") + self.libraries = [] + + # 'library_dirs': a list of directories to search for libraries + self.library_dirs = [] + + # 'runtime_library_dirs': a list of directories to search for + # shared libraries/objects at runtime + self.runtime_library_dirs = [] + + # 'objects': a list of object files (or similar, such as explicitly + # named library files) to include on any link + self.objects = [] + + for key in self.executables.keys(): + self.set_executable(key, self.executables[key]) + + def set_executables(self, **kwargs): + """Define the executables (and options for them) that will be run + to perform the various stages of compilation. The exact set of + executables that may be specified here depends on the compiler + class (via the 'executables' class attribute), but most will have: + compiler the C/C++ compiler + linker_so linker used to create shared objects and libraries + linker_exe linker used to create binary executables + archiver static library creator + + On platforms with a command-line (Unix, DOS/Windows), each of these + is a string that will be split into executable name and (optional) + list of arguments. (Splitting the string is done similarly to how + Unix shells operate: words are delimited by spaces, but quotes and + backslashes can override this. See + 'distutils.util.split_quoted()'.) + """ + + # Note that some CCompiler implementation classes will define class + # attributes 'cpp', 'cc', etc. with hard-coded executable names; + # this is appropriate when a compiler class is for exactly one + # compiler/OS combination (eg. MSVCCompiler). Other compiler + # classes (UnixCCompiler, in particular) are driven by information + # discovered at run-time, since there are many different ways to do + # basically the same things with Unix C compilers. + + for key in kwargs: + if key not in self.executables: + raise ValueError( + f"unknown executable '{key}' for class {self.__class__.__name__}" + ) + self.set_executable(key, kwargs[key]) + + def set_executable(self, key, value): + if isinstance(value, str): + setattr(self, key, split_quoted(value)) + else: + setattr(self, key, value) + + def _find_macro(self, name): + i = 0 + for defn in self.macros: + if defn[0] == name: + return i + i += 1 + return None + + def _check_macro_definitions(self, definitions): + """Ensure that every element of 'definitions' is valid.""" + for defn in definitions: + self._check_macro_definition(*defn) + + def _check_macro_definition(self, defn): + """ + Raise a TypeError if defn is not valid. + + A valid definition is either a (name, value) 2-tuple or a (name,) tuple. + """ + if not isinstance(defn, tuple) or not self._is_valid_macro(*defn): + raise TypeError( + f"invalid macro definition '{defn}': " + "must be tuple (string,), (string, string), or (string, None)" + ) + + @staticmethod + def _is_valid_macro(name, value=None): + """ + A valid macro is a ``name : str`` and a ``value : str | None``. + """ + return isinstance(name, str) and isinstance(value, (str, types.NoneType)) + + # -- Bookkeeping methods ------------------------------------------- + + def define_macro(self, name, value=None): + """Define a preprocessor macro for all compilations driven by this + compiler object. The optional parameter 'value' should be a + string; if it is not supplied, then the macro will be defined + without an explicit value and the exact outcome depends on the + compiler used (XXX true? does ANSI say anything about this?) + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + self.macros.append((name, value)) + + def undefine_macro(self, name): + """Undefine a preprocessor macro for all compilations driven by + this compiler object. If the same macro is defined by + 'define_macro()' and undefined by 'undefine_macro()' the last call + takes precedence (including multiple redefinitions or + undefinitions). If the macro is redefined/undefined on a + per-compilation basis (ie. in the call to 'compile()'), then that + takes precedence. + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + undefn = (name,) + self.macros.append(undefn) + + def add_include_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + header files. The compiler is instructed to search directories in + the order in which they are supplied by successive calls to + 'add_include_dir()'. + """ + self.include_dirs.append(dir) + + def set_include_dirs(self, dirs): + """Set the list of directories that will be searched to 'dirs' (a + list of strings). Overrides any preceding calls to + 'add_include_dir()'; subsequence calls to 'add_include_dir()' add + to the list passed to 'set_include_dirs()'. This does not affect + any list of standard include directories that the compiler may + search by default. + """ + self.include_dirs = dirs[:] + + def add_library(self, libname): + """Add 'libname' to the list of libraries that will be included in + all links driven by this compiler object. Note that 'libname' + should *not* be the name of a file containing a library, but the + name of the library itself: the actual filename will be inferred by + the linker, the compiler, or the compiler class (depending on the + platform). + + The linker will be instructed to link against libraries in the + order they were supplied to 'add_library()' and/or + 'set_libraries()'. It is perfectly valid to duplicate library + names; the linker will be instructed to link against libraries as + many times as they are mentioned. + """ + self.libraries.append(libname) + + def set_libraries(self, libnames): + """Set the list of libraries to be included in all links driven by + this compiler object to 'libnames' (a list of strings). This does + not affect any standard system libraries that the linker may + include by default. + """ + self.libraries = libnames[:] + + def add_library_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + libraries specified to 'add_library()' and 'set_libraries()'. The + linker will be instructed to search for libraries in the order they + are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. + """ + self.library_dirs.append(dir) + + def set_library_dirs(self, dirs): + """Set the list of library search directories to 'dirs' (a list of + strings). This does not affect any standard library search path + that the linker may search by default. + """ + self.library_dirs = dirs[:] + + def add_runtime_library_dir(self, dir): + """Add 'dir' to the list of directories that will be searched for + shared libraries at runtime. + """ + self.runtime_library_dirs.append(dir) + + def set_runtime_library_dirs(self, dirs): + """Set the list of directories to search for shared libraries at + runtime to 'dirs' (a list of strings). This does not affect any + standard search path that the runtime linker may search by + default. + """ + self.runtime_library_dirs = dirs[:] + + def add_link_object(self, object): + """Add 'object' to the list of object files (or analogues, such as + explicitly named library files or the output of "resource + compilers") to be included in every link driven by this compiler + object. + """ + self.objects.append(object) + + def set_link_objects(self, objects): + """Set the list of object files (or analogues) to be included in + every link to 'objects'. This does not affect any standard object + files that the linker may include by default (such as system + libraries). + """ + self.objects = objects[:] + + # -- Private utility methods -------------------------------------- + # (here for the convenience of subclasses) + + # Helper method to prep compiler in subclass compile() methods + + def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): + """Process arguments and decide which source files to compile.""" + outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs) + + if extra is None: + extra = [] + + # Get the list of expected output (object) files + objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir) + assert len(objects) == len(sources) + + pp_opts = gen_preprocess_options(macros, incdirs) + + build = {} + for i in range(len(sources)): + src = sources[i] + obj = objects[i] + ext = os.path.splitext(src)[1] + self.mkpath(os.path.dirname(obj)) + build[obj] = (src, ext) + + return macros, objects, extra, pp_opts, build + + def _get_cc_args(self, pp_opts, debug, before): + # works for unixccompiler, cygwinccompiler + cc_args = pp_opts + ['-c'] + if debug: + cc_args[:0] = ['-g'] + if before: + cc_args[:0] = before + return cc_args + + def _fix_compile_args(self, output_dir, macros, include_dirs): + """Typecheck and fix-up some of the arguments to the 'compile()' + method, and return fixed-up values. Specifically: if 'output_dir' + is None, replaces it with 'self.output_dir'; ensures that 'macros' + is a list, and augments it with 'self.macros'; ensures that + 'include_dirs' is a list, and augments it with 'self.include_dirs'. + Guarantees that the returned values are of the correct type, + i.e. for 'output_dir' either string or None, and for 'macros' and + 'include_dirs' either list or None. + """ + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + if macros is None: + macros = list(self.macros) + elif isinstance(macros, list): + macros = macros + (self.macros or []) + else: + raise TypeError("'macros' (if supplied) must be a list of tuples") + + if include_dirs is None: + include_dirs = list(self.include_dirs) + elif isinstance(include_dirs, (list, tuple)): + include_dirs = list(include_dirs) + (self.include_dirs or []) + else: + raise TypeError("'include_dirs' (if supplied) must be a list of strings") + + # add include dirs for class + include_dirs += self.__class__.include_dirs + + return output_dir, macros, include_dirs + + def _prep_compile(self, sources, output_dir, depends=None): + """Decide which source files must be recompiled. + + Determine the list of object files corresponding to 'sources', + and figure out which ones really need to be recompiled. + Return a list of all object files and a dictionary telling + which source files can be skipped. + """ + # Get the list of expected output (object) files + objects = self.object_filenames(sources, output_dir=output_dir) + assert len(objects) == len(sources) + + # Return an empty dict for the "which source files can be skipped" + # return value to preserve API compatibility. + return objects, {} + + def _fix_object_args(self, objects, output_dir): + """Typecheck and fix up some arguments supplied to various methods. + Specifically: ensure that 'objects' is a list; if output_dir is + None, replace with self.output_dir. Return fixed versions of + 'objects' and 'output_dir'. + """ + if not isinstance(objects, (list, tuple)): + raise TypeError("'objects' must be a list or tuple of strings") + objects = list(objects) + + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + return (objects, output_dir) + + def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs): + """Typecheck and fix up some of the arguments supplied to the + 'link_*' methods. Specifically: ensure that all arguments are + lists, and augment them with their permanent versions + (eg. 'self.libraries' augments 'libraries'). Return a tuple with + fixed versions of all arguments. + """ + if libraries is None: + libraries = list(self.libraries) + elif isinstance(libraries, (list, tuple)): + libraries = list(libraries) + (self.libraries or []) + else: + raise TypeError("'libraries' (if supplied) must be a list of strings") + + if library_dirs is None: + library_dirs = list(self.library_dirs) + elif isinstance(library_dirs, (list, tuple)): + library_dirs = list(library_dirs) + (self.library_dirs or []) + else: + raise TypeError("'library_dirs' (if supplied) must be a list of strings") + + # add library dirs for class + library_dirs += self.__class__.library_dirs + + if runtime_library_dirs is None: + runtime_library_dirs = list(self.runtime_library_dirs) + elif isinstance(runtime_library_dirs, (list, tuple)): + runtime_library_dirs = list(runtime_library_dirs) + ( + self.runtime_library_dirs or [] + ) + else: + raise TypeError( + "'runtime_library_dirs' (if supplied) must be a list of strings" + ) + + return (libraries, library_dirs, runtime_library_dirs) + + def _need_link(self, objects, output_file): + """Return true if we need to relink the files listed in 'objects' + to recreate 'output_file'. + """ + if self.force: + return True + else: + if self.dry_run: + newer = newer_group(objects, output_file, missing='newer') + else: + newer = newer_group(objects, output_file) + return newer + + def detect_language(self, sources): + """Detect the language of a given file, or list of files. Uses + language_map, and language_order to do the job. + """ + if not isinstance(sources, list): + sources = [sources] + lang = None + index = len(self.language_order) + for source in sources: + base, ext = os.path.splitext(source) + extlang = self.language_map.get(ext) + try: + extindex = self.language_order.index(extlang) + if extindex < index: + lang = extlang + index = extindex + except ValueError: + pass + return lang + + # -- Worker methods ------------------------------------------------ + # (must be implemented by subclasses) + + def preprocess( + self, + source, + output_file=None, + macros=None, + include_dirs=None, + extra_preargs=None, + extra_postargs=None, + ): + """Preprocess a single C/C++ source file, named in 'source'. + Output will be written to file named 'output_file', or stdout if + 'output_file' not supplied. 'macros' is a list of macro + definitions as for 'compile()', which will augment the macros set + with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a + list of directory names that will be added to the default list. + + Raises PreprocessError on failure. + """ + pass + + def compile( + self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + """Compile one or more source files. + + 'sources' must be a list of filenames, most likely C/C++ + files, but in reality anything that can be handled by a + particular compiler and compiler class (eg. MSVCCompiler can + handle resource files in 'sources'). Return a list of object + filenames, one per source filename in 'sources'. Depending on + the implementation, not all source files will necessarily be + compiled, but all corresponding object filenames will be + returned. + + If 'output_dir' is given, object files will be put under it, while + retaining their original path component. That is, "foo/bar.c" + normally compiles to "foo/bar.o" (for a Unix implementation); if + 'output_dir' is "build", then it would compile to + "build/foo/bar.o". + + 'macros', if given, must be a list of macro definitions. A macro + definition is either a (name, value) 2-tuple or a (name,) 1-tuple. + The former defines a macro; if the value is None, the macro is + defined without an explicit value. The 1-tuple case undefines a + macro. Later definitions/redefinitions/ undefinitions take + precedence. + + 'include_dirs', if given, must be a list of strings, the + directories to add to the default include file search path for this + compilation only. + + 'debug' is a boolean; if true, the compiler will be instructed to + output debug symbols in (or alongside) the object file(s). + + 'extra_preargs' and 'extra_postargs' are implementation- dependent. + On platforms that have the notion of a command-line (e.g. Unix, + DOS/Windows), they are most likely lists of strings: extra + command-line arguments to prepend/append to the compiler command + line. On other platforms, consult the implementation class + documentation. In any event, they are intended as an escape hatch + for those occasions when the abstract compiler framework doesn't + cut the mustard. + + 'depends', if given, is a list of filenames that all targets + depend on. If a source file is older than any file in + depends, then the source file will be recompiled. This + supports dependency tracking, but only at a coarse + granularity. + + Raises CompileError on failure. + """ + # A concrete compiler class can either override this method + # entirely or implement _compile(). + macros, objects, extra_postargs, pp_opts, build = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) + + # Return *all* object filenames, not just the ones we just built. + return objects + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compile 'src' to product 'obj'.""" + # A concrete compiler class that does not override compile() + # should implement _compile(). + pass + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + """Link a bunch of stuff together to create a static library file. + The "bunch of stuff" consists of the list of object files supplied + as 'objects', the extra object files supplied to + 'add_link_object()' and/or 'set_link_objects()', the libraries + supplied to 'add_library()' and/or 'set_libraries()', and the + libraries supplied as 'libraries' (if any). + + 'output_libname' should be a library name, not a filename; the + filename will be inferred from the library name. 'output_dir' is + the directory where the library file will be put. + + 'debug' is a boolean; if true, debugging information will be + included in the library (note that on most platforms, it is the + compile step where this matters: the 'debug' flag is included here + just for consistency). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LibError on failure. + """ + pass + + # values for target_desc parameter in link() + SHARED_OBJECT = "shared_object" + SHARED_LIBRARY = "shared_library" + EXECUTABLE = "executable" + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + """Link a bunch of stuff together to create an executable or + shared library file. + + The "bunch of stuff" consists of the list of object files supplied + as 'objects'. 'output_filename' should be a filename. If + 'output_dir' is supplied, 'output_filename' is relative to it + (i.e. 'output_filename' can provide directory components if + needed). + + 'libraries' is a list of libraries to link against. These are + library names, not filenames, since they're translated into + filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" + on Unix and "foo.lib" on DOS/Windows). However, they can include a + directory component, which means the linker will look in that + specific directory rather than searching all the normal locations. + + 'library_dirs', if supplied, should be a list of directories to + search for libraries that were specified as bare library names + (ie. no directory component). These are on top of the system + default and those supplied to 'add_library_dir()' and/or + 'set_library_dirs()'. 'runtime_library_dirs' is a list of + directories that will be embedded into the shared library and used + to search for other shared libraries that *it* depends on at + run-time. (This may only be relevant on Unix.) + + 'export_symbols' is a list of symbols that the shared library will + export. (This appears to be relevant only on Windows.) + + 'debug' is as for 'compile()' and 'create_static_lib()', with the + slight distinction that it actually matters on most platforms (as + opposed to 'create_static_lib()', which includes a 'debug' flag + mostly for form's sake). + + 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except + of course that they supply command-line arguments for the + particular linker being used). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LinkError on failure. + """ + raise NotImplementedError + + # Old 'link_*()' methods, rewritten to use the new 'link()' method. + + def link_shared_lib( + self, + objects, + output_libname, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + self.link( + CCompiler.SHARED_LIBRARY, + objects, + self.library_filename(output_libname, lib_type='shared'), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_shared_object( + self, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + self.link( + CCompiler.SHARED_OBJECT, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_executable( + self, + objects, + output_progname, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + target_lang=None, + ): + self.link( + CCompiler.EXECUTABLE, + objects, + self.executable_filename(output_progname), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, + debug, + extra_preargs, + extra_postargs, + None, + target_lang, + ) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function; there is + # no appropriate default implementation so subclasses should + # implement all of these. + + def library_dir_option(self, dir): + """Return the compiler option to add 'dir' to the list of + directories searched for libraries. + """ + raise NotImplementedError + + def runtime_library_dir_option(self, dir): + """Return the compiler option to add 'dir' to the list of + directories searched for runtime libraries. + """ + raise NotImplementedError + + def library_option(self, lib): + """Return the compiler option to add 'lib' to the list of libraries + linked into the shared library or executable. + """ + raise NotImplementedError + + def has_function( # noqa: C901 + self, + funcname, + includes=None, + include_dirs=None, + libraries=None, + library_dirs=None, + ): + """Return a boolean indicating whether funcname is provided as + a symbol on the current platform. The optional arguments can + be used to augment the compilation environment. + + The libraries argument is a list of flags to be passed to the + linker to make additional symbol definitions available for + linking. + + The includes and include_dirs arguments are deprecated. + Usually, supplying include files with function declarations + will cause function detection to fail even in cases where the + symbol is available for linking. + + """ + # this can't be included at module scope because it tries to + # import math which might not be available at that point - maybe + # the necessary logic should just be inlined? + import tempfile + + if includes is None: + includes = [] + else: + warnings.warn("includes is deprecated", DeprecationWarning) + if include_dirs is None: + include_dirs = [] + else: + warnings.warn("include_dirs is deprecated", DeprecationWarning) + if libraries is None: + libraries = [] + if library_dirs is None: + library_dirs = [] + fd, fname = tempfile.mkstemp(".c", funcname, text=True) + with os.fdopen(fd, "w", encoding='utf-8') as f: + for incl in includes: + f.write(f"""#include "{incl}"\n""") + if not includes: + # Use "char func(void);" as the prototype to follow + # what autoconf does. This prototype does not match + # any well-known function the compiler might recognize + # as a builtin, so this ends up as a true link test. + # Without a fake prototype, the test would need to + # know the exact argument types, and the has_function + # interface does not provide that level of information. + f.write( + f"""\ +#ifdef __cplusplus +extern "C" +#endif +char {funcname}(void); +""" + ) + f.write( + f"""\ +int main (int argc, char **argv) {{ + {funcname}(); + return 0; +}} +""" + ) + + try: + objects = self.compile([fname], include_dirs=include_dirs) + except CompileError: + return False + finally: + os.remove(fname) + + try: + self.link_executable( + objects, "a.out", libraries=libraries, library_dirs=library_dirs + ) + except (LinkError, TypeError): + return False + else: + os.remove( + self.executable_filename("a.out", output_dir=self.output_dir or '') + ) + finally: + for fn in objects: + os.remove(fn) + return True + + def find_library_file(self, dirs, lib, debug=False): + """Search the specified list of directories for a static or shared + library file 'lib' and return the full path to that file. If + 'debug' true, look for a debugging version (if that makes sense on + the current platform). Return None if 'lib' wasn't found in any of + the specified directories. + """ + raise NotImplementedError + + # -- Filename generation methods ----------------------------------- + + # The default implementation of the filename generating methods are + # prejudiced towards the Unix/DOS/Windows view of the world: + # * object files are named by replacing the source file extension + # (eg. .c/.cpp -> .o/.obj) + # * library files (shared or static) are named by plugging the + # library name and extension into a format string, eg. + # "lib%s.%s" % (lib_name, ".a") for Unix static libraries + # * executables are named by appending an extension (possibly + # empty) to the program name: eg. progname + ".exe" for + # Windows + # + # To reduce redundant code, these methods expect to find + # several attributes in the current object (presumably defined + # as class attributes): + # * src_extensions - + # list of C/C++ source file extensions, eg. ['.c', '.cpp'] + # * obj_extension - + # object file extension, eg. '.o' or '.obj' + # * static_lib_extension - + # extension for static library files, eg. '.a' or '.lib' + # * shared_lib_extension - + # extension for shared library/object files, eg. '.so', '.dll' + # * static_lib_format - + # format string for generating static library filenames, + # eg. 'lib%s.%s' or '%s.%s' + # * shared_lib_format + # format string for generating shared library filenames + # (probably same as static_lib_format, since the extension + # is one of the intended parameters to the format string) + # * exe_extension - + # extension for executable files, eg. '' or '.exe' + + def object_filenames(self, source_filenames, strip_dir=False, output_dir=''): + if output_dir is None: + output_dir = '' + return list( + self._make_out_path(output_dir, strip_dir, src_name) + for src_name in source_filenames + ) + + @property + def out_extensions(self): + return dict.fromkeys(self.src_extensions, self.obj_extension) + + def _make_out_path(self, output_dir, strip_dir, src_name): + return self._make_out_path_exts( + output_dir, strip_dir, src_name, self.out_extensions + ) + + @classmethod + def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions): + r""" + >>> exts = {'.c': '.o'} + >>> CCompiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/') + './foo/bar.o' + >>> CCompiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/') + './bar.o' + """ + src = pathlib.PurePath(src_name) + # Ensure base is relative to honor output_dir (python/cpython#37775). + base = cls._make_relative(src) + try: + new_ext = extensions[src.suffix] + except LookupError: + raise UnknownFileError(f"unknown file type '{src.suffix}' (from '{src}')") + if strip_dir: + base = pathlib.PurePath(base.name) + return os.path.join(output_dir, base.with_suffix(new_ext)) + + @staticmethod + def _make_relative(base: pathlib.Path): + return base.relative_to(base.anchor) + + def shared_object_filename(self, basename, strip_dir=False, output_dir=''): + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + self.shared_lib_extension) + + def executable_filename(self, basename, strip_dir=False, output_dir=''): + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + (self.exe_extension or '')) + + def library_filename( + self, + libname, + lib_type='static', + strip_dir=False, + output_dir='', # or 'shared' + ): + assert output_dir is not None + expected = '"static", "shared", "dylib", "xcode_stub"' + if lib_type not in eval(expected): + raise ValueError(f"'lib_type' must be {expected}") + fmt = getattr(self, lib_type + "_lib_format") + ext = getattr(self, lib_type + "_lib_extension") + + dir, base = os.path.split(libname) + filename = fmt % (base, ext) + if strip_dir: + dir = '' + + return os.path.join(output_dir, dir, filename) + + # -- Utility methods ----------------------------------------------- + + def announce(self, msg, level=1): + log.debug(msg) + + def debug_print(self, msg): + from distutils.debug import DEBUG + + if DEBUG: + print(msg) + + def warn(self, msg): + sys.stderr.write(f"warning: {msg}\n") + + def execute(self, func, args, msg=None, level=1): + execute(func, args, msg, self.dry_run) + + def spawn(self, cmd, **kwargs): + spawn(cmd, dry_run=self.dry_run, **kwargs) + + def move_file(self, src, dst): + return move_file(src, dst, dry_run=self.dry_run) + + def mkpath(self, name, mode=0o777): + mkpath(name, mode, dry_run=self.dry_run) + + +# Map a sys.platform/os.name ('posix', 'nt') to the default compiler +# type for that platform. Keys are interpreted as re match +# patterns. Order is important; platform mappings are preferred over +# OS names. +_default_compilers = ( + # Platform string mappings + # on a cygwin built python we can use gcc like an ordinary UNIXish + # compiler + ('cygwin.*', 'unix'), + ('zos', 'zos'), + # OS name mappings + ('posix', 'unix'), + ('nt', 'msvc'), +) + + +def get_default_compiler(osname=None, platform=None): + """Determine the default compiler to use for the given platform. + + osname should be one of the standard Python OS names (i.e. the + ones returned by os.name) and platform the common value + returned by sys.platform for the platform in question. + + The default values are os.name and sys.platform in case the + parameters are not given. + """ + if osname is None: + osname = os.name + if platform is None: + platform = sys.platform + # Mingw is a special case where sys.platform is 'win32' but we + # want to use the 'mingw32' compiler, so check it first + if is_mingw(): + return 'mingw32' + for pattern, compiler in _default_compilers: + if ( + re.match(pattern, platform) is not None + or re.match(pattern, osname) is not None + ): + return compiler + # Default to Unix compiler + return 'unix' + + +# Map compiler types to (module_name, class_name) pairs -- ie. where to +# find the code that implements an interface to this compiler. (The module +# is assumed to be in the 'distutils' package.) +compiler_class = { + 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"), + 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"), + 'cygwin': ( + 'cygwinccompiler', + 'CygwinCCompiler', + "Cygwin port of GNU C Compiler for Win32", + ), + 'mingw32': ( + 'cygwinccompiler', + 'Mingw32CCompiler', + "Mingw32 port of GNU C Compiler for Win32", + ), + 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"), + 'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'), +} + + +def show_compilers(): + """Print list of available compilers (used by the "--help-compiler" + options to "build", "build_ext", "build_clib"). + """ + # XXX this "knows" that the compiler option it's describing is + # "--compiler", which just happens to be the case for the three + # commands that use it. + from distutils.fancy_getopt import FancyGetopt + + compilers = sorted( + ("compiler=" + compiler, None, compiler_class[compiler][2]) + for compiler in compiler_class.keys() + ) + pretty_printer = FancyGetopt(compilers) + pretty_printer.print_help("List of available compilers:") + + +def new_compiler(plat=None, compiler=None, verbose=False, dry_run=False, force=False): + """Generate an instance of some CCompiler subclass for the supplied + platform/compiler combination. 'plat' defaults to 'os.name' + (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler + for that platform. Currently only 'posix' and 'nt' are supported, and + the default compilers are "traditional Unix interface" (UnixCCompiler + class) and Visual C++ (MSVCCompiler class). Note that it's perfectly + possible to ask for a Unix compiler object under Windows, and a + Microsoft compiler object under Unix -- if you supply a value for + 'compiler', 'plat' is ignored. + """ + if plat is None: + plat = os.name + + try: + if compiler is None: + compiler = get_default_compiler(plat) + + (module_name, class_name, long_description) = compiler_class[compiler] + except KeyError: + msg = f"don't know how to compile C/C++ code on platform '{plat}'" + if compiler is not None: + msg = msg + f" with '{compiler}' compiler" + raise DistutilsPlatformError(msg) + + try: + module_name = "distutils." + module_name + __import__(module_name) + module = sys.modules[module_name] + klass = vars(module)[class_name] + except ImportError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to load module '{module_name}'" + ) + except KeyError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to find class '{class_name}' " + f"in module '{module_name}'" + ) + + # XXX The None is necessary to preserve backwards compatibility + # with classes that expect verbose to be the first positional + # argument. + return klass(None, dry_run, force) + + +def gen_preprocess_options(macros, include_dirs): + """Generate C pre-processor options (-D, -U, -I) as used by at least + two types of compilers: the typical Unix compiler and Visual C++. + 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) + means undefine (-U) macro 'name', and (name,value) means define (-D) + macro 'name' to 'value'. 'include_dirs' is just a list of directory + names to be added to the header file search path (-I). Returns a list + of command-line options suitable for either Unix compilers or Visual + C++. + """ + # XXX it would be nice (mainly aesthetic, and so we don't generate + # stupid-looking command lines) to go over 'macros' and eliminate + # redundant definitions/undefinitions (ie. ensure that only the + # latest mention of a particular macro winds up on the command + # line). I don't think it's essential, though, since most (all?) + # Unix C compilers only pay attention to the latest -D or -U + # mention of a macro on their command line. Similar situation for + # 'include_dirs'. I'm punting on both for now. Anyways, weeding out + # redundancies like this should probably be the province of + # CCompiler, since the data structures used are inherited from it + # and therefore common to all CCompiler classes. + pp_opts = [] + for macro in macros: + if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2): + raise TypeError( + f"bad macro definition '{macro}': " + "each element of 'macros' list must be a 1- or 2-tuple" + ) + + if len(macro) == 1: # undefine this macro + pp_opts.append(f"-U{macro[0]}") + elif len(macro) == 2: + if macro[1] is None: # define with no explicit value + pp_opts.append(f"-D{macro[0]}") + else: + # XXX *don't* need to be clever about quoting the + # macro value here, because we're going to avoid the + # shell at all costs when we spawn the command! + pp_opts.append("-D{}={}".format(*macro)) + + pp_opts.extend(f"-I{dir}" for dir in include_dirs) + return pp_opts + + +def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): + """Generate linker options for searching library directories and + linking with specific libraries. 'libraries' and 'library_dirs' are, + respectively, lists of library names (not filenames!) and search + directories. Returns a list of command-line options suitable for use + with some compiler (depending on the two format strings passed in). + """ + lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs] + + for dir in runtime_library_dirs: + lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir))) + + # XXX it's important that we *not* remove redundant library mentions! + # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to + # resolve all symbols. I just hope we never have to say "-lfoo obj.o + # -lbar" to get things to work -- that's certainly a possibility, but a + # pretty nasty way to arrange your C code. + + for lib in libraries: + (lib_dir, lib_name) = os.path.split(lib) + if lib_dir: + lib_file = compiler.find_library_file([lib_dir], lib_name) + if lib_file: + lib_opts.append(lib_file) + else: + compiler.warn( + f"no library file corresponding to '{lib}' found (skipping)" + ) + else: + lib_opts.append(compiler.library_option(lib)) + return lib_opts diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/core.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/core.py new file mode 100644 index 0000000000000000000000000000000000000000..bd62546bdd9d35dcc46e0b46a46b0c61a43fd0ba --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/core.py @@ -0,0 +1,289 @@ +"""distutils.core + +The only module that needs to be imported to use the Distutils; provides +the 'setup' function (which is to be called from the setup script). Also +indirectly provides the Distribution and Command classes, although they are +really defined in distutils.dist and distutils.cmd. +""" + +from __future__ import annotations + +import os +import sys +import tokenize +from collections.abc import Iterable + +from .cmd import Command +from .debug import DEBUG + +# Mainly import these so setup scripts can "from distutils.core import" them. +from .dist import Distribution +from .errors import ( + CCompilerError, + DistutilsArgError, + DistutilsError, + DistutilsSetupError, +) +from .extension import Extension + +__all__ = ['Distribution', 'Command', 'Extension', 'setup'] + +# This is a barebones help message generated displayed when the user +# runs the setup script with no arguments at all. More useful help +# is generated with various --help options: global help, list commands, +# and per-command help. +USAGE = """\ +usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] + or: %(script)s --help [cmd1 cmd2 ...] + or: %(script)s --help-commands + or: %(script)s cmd --help +""" + + +def gen_usage(script_name): + script = os.path.basename(script_name) + return USAGE % locals() + + +# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'. +_setup_stop_after = None +_setup_distribution = None + +# Legal keyword arguments for the setup() function +setup_keywords = ( + 'distclass', + 'script_name', + 'script_args', + 'options', + 'name', + 'version', + 'author', + 'author_email', + 'maintainer', + 'maintainer_email', + 'url', + 'license', + 'description', + 'long_description', + 'keywords', + 'platforms', + 'classifiers', + 'download_url', + 'requires', + 'provides', + 'obsoletes', +) + +# Legal keyword arguments for the Extension constructor +extension_keywords = ( + 'name', + 'sources', + 'include_dirs', + 'define_macros', + 'undef_macros', + 'library_dirs', + 'libraries', + 'runtime_library_dirs', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + 'swig_opts', + 'export_symbols', + 'depends', + 'language', +) + + +def setup(**attrs): # noqa: C901 + """The gateway to the Distutils: do everything your setup script needs + to do, in a highly flexible and user-driven way. Briefly: create a + Distribution instance; find and parse config files; parse the command + line; run each Distutils command found there, customized by the options + supplied to 'setup()' (as keyword arguments), in config files, and on + the command line. + + The Distribution instance might be an instance of a class supplied via + the 'distclass' keyword argument to 'setup'; if no such class is + supplied, then the Distribution class (in dist.py) is instantiated. + All other arguments to 'setup' (except for 'cmdclass') are used to set + attributes of the Distribution instance. + + The 'cmdclass' argument, if supplied, is a dictionary mapping command + names to command classes. Each command encountered on the command line + will be turned into a command class, which is in turn instantiated; any + class found in 'cmdclass' is used in place of the default, which is + (for command 'foo_bar') class 'foo_bar' in module + 'distutils.command.foo_bar'. The command class must provide a + 'user_options' attribute which is a list of option specifiers for + 'distutils.fancy_getopt'. Any command-line options between the current + and the next command are used to set attributes of the current command + object. + + When the entire command-line has been successfully parsed, calls the + 'run()' method on each command object in turn. This method will be + driven entirely by the Distribution object (which each command object + has a reference to, thanks to its constructor), and the + command-specific options that became attributes of each command + object. + """ + + global _setup_stop_after, _setup_distribution + + # Determine the distribution class -- either caller-supplied or + # our Distribution (see below). + klass = attrs.get('distclass') + if klass: + attrs.pop('distclass') + else: + klass = Distribution + + if 'script_name' not in attrs: + attrs['script_name'] = os.path.basename(sys.argv[0]) + if 'script_args' not in attrs: + attrs['script_args'] = sys.argv[1:] + + # Create the Distribution instance, using the remaining arguments + # (ie. everything except distclass) to initialize it + try: + _setup_distribution = dist = klass(attrs) + except DistutilsSetupError as msg: + if 'name' not in attrs: + raise SystemExit(f"error in setup command: {msg}") + else: + raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg)) + + if _setup_stop_after == "init": + return dist + + # Find and parse the config file(s): they will override options from + # the setup script, but be overridden by the command line. + dist.parse_config_files() + + if DEBUG: + print("options (after parsing config files):") + dist.dump_option_dicts() + + if _setup_stop_after == "config": + return dist + + # Parse the command line and override config files; any + # command-line errors are the end user's fault, so turn them into + # SystemExit to suppress tracebacks. + try: + ok = dist.parse_command_line() + except DistutilsArgError as msg: + raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}") + + if DEBUG: + print("options (after parsing command line):") + dist.dump_option_dicts() + + if _setup_stop_after == "commandline": + return dist + + # And finally, run all the commands found on the command line. + if ok: + return run_commands(dist) + + return dist + + +# setup () + + +def run_commands(dist): + """Given a Distribution object run all the commands, + raising ``SystemExit`` errors in the case of failure. + + This function assumes that either ``sys.argv`` or ``dist.script_args`` + is already set accordingly. + """ + try: + dist.run_commands() + except KeyboardInterrupt: + raise SystemExit("interrupted") + except OSError as exc: + if DEBUG: + sys.stderr.write(f"error: {exc}\n") + raise + else: + raise SystemExit(f"error: {exc}") + + except (DistutilsError, CCompilerError) as msg: + if DEBUG: + raise + else: + raise SystemExit("error: " + str(msg)) + + return dist + + +def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"): + """Run a setup script in a somewhat controlled environment, and + return the Distribution instance that drives things. This is useful + if you need to find out the distribution meta-data (passed as + keyword args from 'script' to 'setup()', or the contents of the + config files or command-line. + + 'script_name' is a file that will be read and run with 'exec()'; + 'sys.argv[0]' will be replaced with 'script' for the duration of the + call. 'script_args' is a list of strings; if supplied, + 'sys.argv[1:]' will be replaced by 'script_args' for the duration of + the call. + + 'stop_after' tells 'setup()' when to stop processing; possible + values: + init + stop after the Distribution instance has been created and + populated with the keyword arguments to 'setup()' + config + stop after config files have been parsed (and their data + stored in the Distribution instance) + commandline + stop after the command-line ('sys.argv[1:]' or 'script_args') + have been parsed (and the data stored in the Distribution) + run [default] + stop after all commands have been run (the same as if 'setup()' + had been called in the usual way + + Returns the Distribution instance, which provides all information + used to drive the Distutils. + """ + if stop_after not in ('init', 'config', 'commandline', 'run'): + raise ValueError(f"invalid value for 'stop_after': {stop_after!r}") + + global _setup_stop_after, _setup_distribution + _setup_stop_after = stop_after + + save_argv = sys.argv.copy() + g = {'__file__': script_name, '__name__': '__main__'} + try: + try: + sys.argv[0] = script_name + if script_args is not None: + sys.argv[1:] = script_args + # tokenize.open supports automatic encoding detection + with tokenize.open(script_name) as f: + code = f.read().replace(r'\r\n', r'\n') + exec(code, g) + finally: + sys.argv = save_argv + _setup_stop_after = None + except SystemExit: + # Hmm, should we do something if exiting with a non-zero code + # (ie. error)? + pass + + if _setup_distribution is None: + raise RuntimeError( + "'distutils.core.setup()' was never called -- " + f"perhaps '{script_name}' is not a Distutils setup script?" + ) + + # I wonder if the setup script's namespace -- g and l -- would be of + # any interest to callers? + # print "_setup_distribution:", _setup_distribution + return _setup_distribution + + +# run_setup () diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/cygwinccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/cygwinccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..3c67524e6d969c529d2fd87f2777225378eca39f --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/cygwinccompiler.py @@ -0,0 +1,339 @@ +"""distutils.cygwinccompiler + +Provides the CygwinCCompiler class, a subclass of UnixCCompiler that +handles the Cygwin port of the GNU C compiler to Windows. It also contains +the Mingw32CCompiler class which handles the mingw32 port of GCC (same as +cygwin in no-cygwin mode). +""" + +import copy +import os +import pathlib +import shlex +import sys +import warnings +from subprocess import check_output + +from .errors import ( + CCompilerError, + CompileError, + DistutilsExecError, + DistutilsPlatformError, +) +from .file_util import write_file +from .sysconfig import get_config_vars +from .unixccompiler import UnixCCompiler +from .version import LooseVersion, suppress_known_deprecation + + +def get_msvcr(): + """No longer needed, but kept for backward compatibility.""" + return [] + + +_runtime_library_dirs_msg = ( + "Unable to set runtime library search path on Windows, " + "usually indicated by `runtime_library_dirs` parameter to Extension" +) + + +class CygwinCCompiler(UnixCCompiler): + """Handles the Cygwin port of the GNU C compiler to Windows.""" + + compiler_type = 'cygwin' + obj_extension = ".o" + static_lib_extension = ".a" + shared_lib_extension = ".dll.a" + dylib_lib_extension = ".dll" + static_lib_format = "lib%s%s" + shared_lib_format = "lib%s%s" + dylib_lib_format = "cyg%s%s" + exe_extension = ".exe" + + def __init__(self, verbose=False, dry_run=False, force=False): + super().__init__(verbose, dry_run, force) + + status, details = check_config_h() + self.debug_print(f"Python's GCC status: {status} (details: {details})") + if status is not CONFIG_H_OK: + self.warn( + "Python's pyconfig.h doesn't seem to support your compiler. " + f"Reason: {details}. " + "Compiling may fail because of undefined preprocessor macros." + ) + + self.cc, self.cxx = get_config_vars('CC', 'CXX') + + # Override 'CC' and 'CXX' environment variables for + # building using MINGW compiler for MSVC python. + self.cc = os.environ.get('CC', self.cc or 'gcc') + self.cxx = os.environ.get('CXX', self.cxx or 'g++') + + self.linker_dll = self.cc + self.linker_dll_cxx = self.cxx + shared_option = "-shared" + + self.set_executables( + compiler=f'{self.cc} -mcygwin -O -Wall', + compiler_so=f'{self.cc} -mcygwin -mdll -O -Wall', + compiler_cxx=f'{self.cxx} -mcygwin -O -Wall', + compiler_so_cxx=f'{self.cxx} -mcygwin -mdll -O -Wall', + linker_exe=f'{self.cc} -mcygwin', + linker_so=f'{self.linker_dll} -mcygwin {shared_option}', + linker_exe_cxx=f'{self.cxx} -mcygwin', + linker_so_cxx=f'{self.linker_dll_cxx} -mcygwin {shared_option}', + ) + + self.dll_libraries = get_msvcr() + + @property + def gcc_version(self): + # Older numpy depended on this existing to check for ancient + # gcc versions. This doesn't make much sense with clang etc so + # just hardcode to something recent. + # https://github.com/numpy/numpy/pull/20333 + warnings.warn( + "gcc_version attribute of CygwinCCompiler is deprecated. " + "Instead of returning actual gcc version a fixed value 11.2.0 is returned.", + DeprecationWarning, + stacklevel=2, + ) + with suppress_known_deprecation(): + return LooseVersion("11.2.0") + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compiles the source by spawning GCC and windres if needed.""" + if ext in ('.rc', '.res'): + # gcc needs '.res' and '.rc' compiled to object files !!! + try: + self.spawn(["windres", "-i", src, "-o", obj]) + except DistutilsExecError as msg: + raise CompileError(msg) + else: # for other files use the C-compiler + try: + if self.detect_language(src) == 'c++': + self.spawn( + self.compiler_so_cxx + + cc_args + + [src, '-o', obj] + + extra_postargs + ) + else: + self.spawn( + self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs + ) + except DistutilsExecError as msg: + raise CompileError(msg) + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + """Link the objects.""" + # use separate copies, so we can modify the lists + extra_preargs = copy.copy(extra_preargs or []) + libraries = copy.copy(libraries or []) + objects = copy.copy(objects or []) + + if runtime_library_dirs: + self.warn(_runtime_library_dirs_msg) + + # Additional libraries + libraries.extend(self.dll_libraries) + + # handle export symbols by creating a def-file + # with executables this only works with gcc/ld as linker + if (export_symbols is not None) and ( + target_desc != self.EXECUTABLE or self.linker_dll == "gcc" + ): + # (The linker doesn't do anything if output is up-to-date. + # So it would probably better to check if we really need this, + # but for this we had to insert some unchanged parts of + # UnixCCompiler, and this is not what we want.) + + # we want to put some files in the same directory as the + # object files are, build_temp doesn't help much + # where are the object files + temp_dir = os.path.dirname(objects[0]) + # name of dll to give the helper files the same base name + (dll_name, dll_extension) = os.path.splitext( + os.path.basename(output_filename) + ) + + # generate the filenames for these files + def_file = os.path.join(temp_dir, dll_name + ".def") + + # Generate .def file + contents = [f"LIBRARY {os.path.basename(output_filename)}", "EXPORTS"] + contents.extend(export_symbols) + self.execute(write_file, (def_file, contents), f"writing {def_file}") + + # next add options for def-file + + # for gcc/ld the def-file is specified as any object files + objects.append(def_file) + + # end: if ((export_symbols is not None) and + # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")): + + # who wants symbols and a many times larger output file + # should explicitly switch the debug mode on + # otherwise we let ld strip the output file + # (On my machine: 10KiB < stripped_file < ??100KiB + # unstripped_file = stripped_file + XXX KiB + # ( XXX=254 for a typical python extension)) + if not debug: + extra_preargs.append("-s") + + UnixCCompiler.link( + self, + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, # export_symbols, we do this in our def-file + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def runtime_library_dir_option(self, dir): + # cygwin doesn't support rpath. While in theory we could error + # out like MSVC does, code might expect it to work like on Unix, so + # just warn and hope for the best. + self.warn(_runtime_library_dirs_msg) + return [] + + # -- Miscellaneous methods ----------------------------------------- + + def _make_out_path(self, output_dir, strip_dir, src_name): + # use normcase to make sure '.rc' is really '.rc' and not '.RC' + norm_src_name = os.path.normcase(src_name) + return super()._make_out_path(output_dir, strip_dir, norm_src_name) + + @property + def out_extensions(self): + """ + Add support for rc and res files. + """ + return { + **super().out_extensions, + **{ext: ext + self.obj_extension for ext in ('.res', '.rc')}, + } + + +# the same as cygwin plus some additional parameters +class Mingw32CCompiler(CygwinCCompiler): + """Handles the Mingw32 port of the GNU C compiler to Windows.""" + + compiler_type = 'mingw32' + + def __init__(self, verbose=False, dry_run=False, force=False): + super().__init__(verbose, dry_run, force) + + shared_option = "-shared" + + if is_cygwincc(self.cc): + raise CCompilerError('Cygwin gcc cannot be used with --compiler=mingw32') + + self.set_executables( + compiler=f'{self.cc} -O -Wall', + compiler_so=f'{self.cc} -shared -O -Wall', + compiler_so_cxx=f'{self.cxx} -shared -O -Wall', + compiler_cxx=f'{self.cxx} -O -Wall', + linker_exe=f'{self.cc}', + linker_so=f'{self.linker_dll} {shared_option}', + linker_exe_cxx=f'{self.cxx}', + linker_so_cxx=f'{self.linker_dll_cxx} {shared_option}', + ) + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError(_runtime_library_dirs_msg) + + +# Because these compilers aren't configured in Python's pyconfig.h file by +# default, we should at least warn the user if he is using an unmodified +# version. + +CONFIG_H_OK = "ok" +CONFIG_H_NOTOK = "not ok" +CONFIG_H_UNCERTAIN = "uncertain" + + +def check_config_h(): + """Check if the current Python installation appears amenable to building + extensions with GCC. + + Returns a tuple (status, details), where 'status' is one of the following + constants: + + - CONFIG_H_OK: all is well, go ahead and compile + - CONFIG_H_NOTOK: doesn't look good + - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h + + 'details' is a human-readable string explaining the situation. + + Note there are two ways to conclude "OK": either 'sys.version' contains + the string "GCC" (implying that this Python was built with GCC), or the + installed "pyconfig.h" contains the string "__GNUC__". + """ + + # XXX since this function also checks sys.version, it's not strictly a + # "pyconfig.h" check -- should probably be renamed... + + from distutils import sysconfig + + # if sys.version contains GCC then python was compiled with GCC, and the + # pyconfig.h file should be OK + if "GCC" in sys.version: + return CONFIG_H_OK, "sys.version mentions 'GCC'" + + # Clang would also work + if "Clang" in sys.version: + return CONFIG_H_OK, "sys.version mentions 'Clang'" + + # let's see if __GNUC__ is mentioned in python.h + fn = sysconfig.get_config_h_filename() + try: + config_h = pathlib.Path(fn).read_text(encoding='utf-8') + except OSError as exc: + return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}") + else: + substring = '__GNUC__' + if substring in config_h: + code = CONFIG_H_OK + mention_inflected = 'mentions' + else: + code = CONFIG_H_NOTOK + mention_inflected = 'does not mention' + return code, f"{fn!r} {mention_inflected} {substring!r}" + + +def is_cygwincc(cc): + """Try to determine if the compiler that would be used is from cygwin.""" + out_string = check_output(shlex.split(cc) + ['-dumpmachine']) + return out_string.strip().endswith(b'cygwin') + + +get_versions = None +""" +A stand-in for the previous get_versions() function to prevent failures +when monkeypatched. See pypa/setuptools#2969. +""" diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/debug.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..daf1660f0d821143e388d37532a39ddfd2ca0347 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/debug.py @@ -0,0 +1,5 @@ +import os + +# If DISTUTILS_DEBUG is anything other than the empty string, we run in +# debug mode. +DEBUG = os.environ.get('DISTUTILS_DEBUG') diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dep_util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dep_util.py new file mode 100644 index 0000000000000000000000000000000000000000..09a8a2e126c8bb009dbbe61c5c4bd5e358744996 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dep_util.py @@ -0,0 +1,14 @@ +import warnings + +from . import _modified + + +def __getattr__(name): + if name not in ['newer', 'newer_group', 'newer_pairwise']: + raise AttributeError(name) + warnings.warn( + "dep_util is Deprecated. Use functions from setuptools instead.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(_modified, name) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dir_util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dir_util.py new file mode 100644 index 0000000000000000000000000000000000000000..d9782602cfe78d4033fb43846965347de8ad9cdf --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dir_util.py @@ -0,0 +1,244 @@ +"""distutils.dir_util + +Utility functions for manipulating directories and directory trees.""" + +import functools +import itertools +import os +import pathlib + +from . import file_util +from ._log import log +from .errors import DistutilsFileError, DistutilsInternalError + + +class SkipRepeatAbsolutePaths(set): + """ + Cache for mkpath. + + In addition to cheapening redundant calls, eliminates redundant + "creating /foo/bar/baz" messages in dry-run mode. + """ + + def __init__(self): + SkipRepeatAbsolutePaths.instance = self + + @classmethod + def clear(cls): + super(cls, cls.instance).clear() + + def wrap(self, func): + @functools.wraps(func) + def wrapper(path, *args, **kwargs): + if path.absolute() in self: + return + result = func(path, *args, **kwargs) + self.add(path.absolute()) + return result + + return wrapper + + +# Python 3.8 compatibility +wrapper = SkipRepeatAbsolutePaths().wrap + + +@functools.singledispatch +@wrapper +def mkpath(name: pathlib.Path, mode=0o777, verbose=True, dry_run=False) -> None: + """Create a directory and any missing ancestor directories. + + If the directory already exists (or if 'name' is the empty string, which + means the current directory, which of course exists), then do nothing. + Raise DistutilsFileError if unable to create some directory along the way + (eg. some sub-path exists, but is a file rather than a directory). + If 'verbose' is true, log the directory created. + """ + if verbose and not name.is_dir(): + log.info("creating %s", name) + + try: + dry_run or name.mkdir(mode=mode, parents=True, exist_ok=True) + except OSError as exc: + raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}") + + +@mkpath.register +def _(name: str, *args, **kwargs): + return mkpath(pathlib.Path(name), *args, **kwargs) + + +@mkpath.register +def _(name: None, *args, **kwargs): + """ + Detect a common bug -- name is None. + """ + raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})") + + +def create_tree(base_dir, files, mode=0o777, verbose=True, dry_run=False): + """Create all the empty directories under 'base_dir' needed to put 'files' + there. + + 'base_dir' is just the name of a directory which doesn't necessarily + exist yet; 'files' is a list of filenames to be interpreted relative to + 'base_dir'. 'base_dir' + the directory portion of every file in 'files' + will be created if it doesn't already exist. 'mode', 'verbose' and + 'dry_run' flags are as for 'mkpath()'. + """ + # First get the list of directories to create + need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files) + + # Now create them + for dir in sorted(need_dir): + mkpath(dir, mode, verbose=verbose, dry_run=dry_run) + + +def copy_tree( + src, + dst, + preserve_mode=True, + preserve_times=True, + preserve_symlinks=False, + update=False, + verbose=True, + dry_run=False, +): + """Copy an entire directory tree 'src' to a new location 'dst'. + + Both 'src' and 'dst' must be directory names. If 'src' is not a + directory, raise DistutilsFileError. If 'dst' does not exist, it is + created with 'mkpath()'. The end result of the copy is that every + file in 'src' is copied to 'dst', and directories under 'src' are + recursively copied to 'dst'. Return the list of files that were + copied or might have been copied, using their output name. The + return value is unaffected by 'update' or 'dry_run': it is simply + the list of all files under 'src', with the names changed to be + under 'dst'. + + 'preserve_mode' and 'preserve_times' are the same as for + 'copy_file'; note that they only apply to regular files, not to + directories. If 'preserve_symlinks' is true, symlinks will be + copied as symlinks (on platforms that support them!); otherwise + (the default), the destination of the symlink will be copied. + 'update' and 'verbose' are the same as for 'copy_file'. + """ + if not dry_run and not os.path.isdir(src): + raise DistutilsFileError(f"cannot copy tree '{src}': not a directory") + try: + names = os.listdir(src) + except OSError as e: + if dry_run: + names = [] + else: + raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}") + + if not dry_run: + mkpath(dst, verbose=verbose) + + copy_one = functools.partial( + _copy_one, + src=src, + dst=dst, + preserve_symlinks=preserve_symlinks, + verbose=verbose, + dry_run=dry_run, + preserve_mode=preserve_mode, + preserve_times=preserve_times, + update=update, + ) + return list(itertools.chain.from_iterable(map(copy_one, names))) + + +def _copy_one( + name, + *, + src, + dst, + preserve_symlinks, + verbose, + dry_run, + preserve_mode, + preserve_times, + update, +): + src_name = os.path.join(src, name) + dst_name = os.path.join(dst, name) + + if name.startswith('.nfs'): + # skip NFS rename files + return + + if preserve_symlinks and os.path.islink(src_name): + link_dest = os.readlink(src_name) + if verbose >= 1: + log.info("linking %s -> %s", dst_name, link_dest) + if not dry_run: + os.symlink(link_dest, dst_name) + yield dst_name + + elif os.path.isdir(src_name): + yield from copy_tree( + src_name, + dst_name, + preserve_mode, + preserve_times, + preserve_symlinks, + update, + verbose=verbose, + dry_run=dry_run, + ) + else: + file_util.copy_file( + src_name, + dst_name, + preserve_mode, + preserve_times, + update, + verbose=verbose, + dry_run=dry_run, + ) + yield dst_name + + +def _build_cmdtuple(path, cmdtuples): + """Helper for remove_tree().""" + for f in os.listdir(path): + real_f = os.path.join(path, f) + if os.path.isdir(real_f) and not os.path.islink(real_f): + _build_cmdtuple(real_f, cmdtuples) + else: + cmdtuples.append((os.remove, real_f)) + cmdtuples.append((os.rmdir, path)) + + +def remove_tree(directory, verbose=True, dry_run=False): + """Recursively remove an entire directory tree. + + Any errors are ignored (apart from being reported to stdout if 'verbose' + is true). + """ + if verbose >= 1: + log.info("removing '%s' (and everything under it)", directory) + if dry_run: + return + cmdtuples = [] + _build_cmdtuple(directory, cmdtuples) + for cmd in cmdtuples: + try: + cmd[0](cmd[1]) + # Clear the cache + SkipRepeatAbsolutePaths.clear() + except OSError as exc: + log.warning("error removing %s: %s", directory, exc) + + +def ensure_relative(path): + """Take the full path 'path', and make it a relative path. + + This is useful to make 'path' the second argument to os.path.join(). + """ + drive, path = os.path.splitdrive(path) + if path[0:1] == os.sep: + path = drive + path[1:] + return path diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dist.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..33ed8ebd7a0e60cc1949274b1c9854c6fd72ffa5 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/dist.py @@ -0,0 +1,1317 @@ +"""distutils.dist + +Provides the Distribution class, which represents the module distribution +being built/installed/distributed. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import pathlib +import re +import sys +import warnings +from collections.abc import Iterable +from email import message_from_file +from typing import TYPE_CHECKING, Literal, TypeVar, overload + +from packaging.utils import canonicalize_name, canonicalize_version + +from ._log import log +from .debug import DEBUG +from .errors import ( + DistutilsArgError, + DistutilsClassError, + DistutilsModuleError, + DistutilsOptionError, +) +from .fancy_getopt import FancyGetopt, translate_longopt +from .util import check_environ, rfc822_escape, strtobool + +if TYPE_CHECKING: + # type-only import because of mutual dependence between these modules + from .cmd import Command + +_CommandT = TypeVar("_CommandT", bound="Command") + +# Regex to define acceptable Distutils command names. This is not *quite* +# the same as a Python NAME -- I don't allow leading underscores. The fact +# that they're very similar is no coincidence; the default naming scheme is +# to look for a Python module named after the command. +command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$') + + +def _ensure_list(value, fieldname): + if isinstance(value, str): + # a string containing comma separated values is okay. It will + # be converted to a list by Distribution.finalize_options(). + pass + elif not isinstance(value, list): + # passing a tuple or an iterator perhaps, warn and convert + typename = type(value).__name__ + msg = "Warning: '{fieldname}' should be a list, got type '{typename}'" + msg = msg.format(**locals()) + log.warning(msg) + value = list(value) + return value + + +class Distribution: + """The core of the Distutils. Most of the work hiding behind 'setup' + is really done within a Distribution instance, which farms the work out + to the Distutils commands specified on the command line. + + Setup scripts will almost never instantiate Distribution directly, + unless the 'setup()' function is totally inadequate to their needs. + However, it is conceivable that a setup script might wish to subclass + Distribution for some specialized purpose, and then pass the subclass + to 'setup()' as the 'distclass' keyword argument. If so, it is + necessary to respect the expectations that 'setup' has of Distribution. + See the code for 'setup()', in core.py, for details. + """ + + # 'global_options' describes the command-line options that may be + # supplied to the setup script prior to any actual commands. + # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of + # these global options. This list should be kept to a bare minimum, + # since every global option is also valid as a command option -- and we + # don't want to pollute the commands with too many options that they + # have minimal control over. + # The fourth entry for verbose means that it can be repeated. + global_options = [ + ('verbose', 'v', "run verbosely (default)", 1), + ('quiet', 'q', "run quietly (turns verbosity off)"), + ('dry-run', 'n', "don't actually do anything"), + ('help', 'h', "show detailed help message"), + ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'), + ] + + # 'common_usage' is a short (2-3 line) string describing the common + # usage of the setup script. + common_usage = """\ +Common commands: (see '--help-commands' for more) + + setup.py build will build the package underneath 'build/' + setup.py install will install the package +""" + + # options that are not propagated to the commands + display_options = [ + ('help-commands', None, "list all available commands"), + ('name', None, "print package name"), + ('version', 'V', "print package version"), + ('fullname', None, "print -"), + ('author', None, "print the author's name"), + ('author-email', None, "print the author's email address"), + ('maintainer', None, "print the maintainer's name"), + ('maintainer-email', None, "print the maintainer's email address"), + ('contact', None, "print the maintainer's name if known, else the author's"), + ( + 'contact-email', + None, + "print the maintainer's email address if known, else the author's", + ), + ('url', None, "print the URL for this package"), + ('license', None, "print the license of the package"), + ('licence', None, "alias for --license"), + ('description', None, "print the package description"), + ('long-description', None, "print the long package description"), + ('platforms', None, "print the list of platforms"), + ('classifiers', None, "print the list of classifiers"), + ('keywords', None, "print the list of keywords"), + ('provides', None, "print the list of packages/modules provided"), + ('requires', None, "print the list of packages/modules required"), + ('obsoletes', None, "print the list of packages/modules made obsolete"), + ] + display_option_names = [translate_longopt(x[0]) for x in display_options] + + # negative options are options that exclude other options + negative_opt = {'quiet': 'verbose'} + + # -- Creation/initialization methods ------------------------------- + + def __init__(self, attrs=None): # noqa: C901 + """Construct a new Distribution instance: initialize all the + attributes of a Distribution, and then use 'attrs' (a dictionary + mapping attribute names to values) to assign some of those + attributes their "real" values. (Any attributes not mentioned in + 'attrs' will be assigned to some null value: 0, None, an empty list + or dictionary, etc.) Most importantly, initialize the + 'command_obj' attribute to the empty dictionary; this will be + filled in with real command objects by 'parse_command_line()'. + """ + + # Default values for our command-line options + self.verbose = True + self.dry_run = False + self.help = False + for attr in self.display_option_names: + setattr(self, attr, False) + + # Store the distribution meta-data (name, version, author, and so + # forth) in a separate object -- we're getting to have enough + # information here (and enough command-line options) that it's + # worth it. Also delegate 'get_XXX()' methods to the 'metadata' + # object in a sneaky and underhanded (but efficient!) way. + self.metadata = DistributionMetadata() + for basename in self.metadata._METHOD_BASENAMES: + method_name = "get_" + basename + setattr(self, method_name, getattr(self.metadata, method_name)) + + # 'cmdclass' maps command names to class objects, so we + # can 1) quickly figure out which class to instantiate when + # we need to create a new command object, and 2) have a way + # for the setup script to override command classes + self.cmdclass = {} + + # 'command_packages' is a list of packages in which commands + # are searched for. The factory for command 'foo' is expected + # to be named 'foo' in the module 'foo' in one of the packages + # named here. This list is searched from the left; an error + # is raised if no named package provides the command being + # searched for. (Always access using get_command_packages().) + self.command_packages = None + + # 'script_name' and 'script_args' are usually set to sys.argv[0] + # and sys.argv[1:], but they can be overridden when the caller is + # not necessarily a setup script run from the command-line. + self.script_name = None + self.script_args: list[str] | None = None + + # 'command_options' is where we store command options between + # parsing them (from config files, the command-line, etc.) and when + # they are actually needed -- ie. when the command in question is + # instantiated. It is a dictionary of dictionaries of 2-tuples: + # command_options = { command_name : { option : (source, value) } } + self.command_options = {} + + # 'dist_files' is the list of (command, pyversion, file) that + # have been created by any dist commands run so far. This is + # filled regardless of whether the run is dry or not. pyversion + # gives sysconfig.get_python_version() if the dist file is + # specific to a Python version, 'any' if it is good for all + # Python versions on the target platform, and '' for a source + # file. pyversion should not be used to specify minimum or + # maximum required Python versions; use the metainfo for that + # instead. + self.dist_files = [] + + # These options are really the business of various commands, rather + # than of the Distribution itself. We provide aliases for them in + # Distribution as a convenience to the developer. + self.packages = None + self.package_data = {} + self.package_dir = None + self.py_modules = None + self.libraries = None + self.headers = None + self.ext_modules = None + self.ext_package = None + self.include_dirs = None + self.extra_path = None + self.scripts = None + self.data_files = None + self.password = '' + + # And now initialize bookkeeping stuff that can't be supplied by + # the caller at all. 'command_obj' maps command names to + # Command instances -- that's how we enforce that every command + # class is a singleton. + self.command_obj = {} + + # 'have_run' maps command names to boolean values; it keeps track + # of whether we have actually run a particular command, to make it + # cheap to "run" a command whenever we think we might need to -- if + # it's already been done, no need for expensive filesystem + # operations, we just check the 'have_run' dictionary and carry on. + # It's only safe to query 'have_run' for a command class that has + # been instantiated -- a false value will be inserted when the + # command object is created, and replaced with a true value when + # the command is successfully run. Thus it's probably best to use + # '.get()' rather than a straight lookup. + self.have_run = {} + + # Now we'll use the attrs dictionary (ultimately, keyword args from + # the setup script) to possibly override any or all of these + # distribution options. + + if attrs: + # Pull out the set of command options and work on them + # specifically. Note that this order guarantees that aliased + # command options will override any supplied redundantly + # through the general options dictionary. + options = attrs.get('options') + if options is not None: + del attrs['options'] + for command, cmd_options in options.items(): + opt_dict = self.get_option_dict(command) + for opt, val in cmd_options.items(): + opt_dict[opt] = ("setup script", val) + + if 'licence' in attrs: + attrs['license'] = attrs['licence'] + del attrs['licence'] + msg = "'licence' distribution option is deprecated; use 'license'" + warnings.warn(msg) + + # Now work on the rest of the attributes. Any attribute that's + # not already defined is invalid! + for key, val in attrs.items(): + if hasattr(self.metadata, "set_" + key): + getattr(self.metadata, "set_" + key)(val) + elif hasattr(self.metadata, key): + setattr(self.metadata, key, val) + elif hasattr(self, key): + setattr(self, key, val) + else: + msg = f"Unknown distribution option: {key!r}" + warnings.warn(msg) + + # no-user-cfg is handled before other command line args + # because other args override the config files, and this + # one is needed before we can load the config files. + # If attrs['script_args'] wasn't passed, assume false. + # + # This also make sure we just look at the global options + self.want_user_cfg = True + + if self.script_args is not None: + # Coerce any possible iterable from attrs into a list + self.script_args = list(self.script_args) + for arg in self.script_args: + if not arg.startswith('-'): + break + if arg == '--no-user-cfg': + self.want_user_cfg = False + break + + self.finalize_options() + + def get_option_dict(self, command): + """Get the option dictionary for a given command. If that + command's option dictionary hasn't been created yet, then create it + and return the new dictionary; otherwise, return the existing + option dictionary. + """ + dict = self.command_options.get(command) + if dict is None: + dict = self.command_options[command] = {} + return dict + + def dump_option_dicts(self, header=None, commands=None, indent=""): + from pprint import pformat + + if commands is None: # dump all command option dicts + commands = sorted(self.command_options.keys()) + + if header is not None: + self.announce(indent + header) + indent = indent + " " + + if not commands: + self.announce(indent + "no commands known yet") + return + + for cmd_name in commands: + opt_dict = self.command_options.get(cmd_name) + if opt_dict is None: + self.announce(indent + f"no option dict for '{cmd_name}' command") + else: + self.announce(indent + f"option dict for '{cmd_name}' command:") + out = pformat(opt_dict) + for line in out.split('\n'): + self.announce(indent + " " + line) + + # -- Config file finding/parsing methods --------------------------- + + def find_config_files(self): + """Find as many configuration files as should be processed for this + platform, and return a list of filenames in the order in which they + should be parsed. The filenames returned are guaranteed to exist + (modulo nasty race conditions). + + There are multiple possible config files: + - distutils.cfg in the Distutils installation directory (i.e. + where the top-level Distutils __inst__.py file lives) + - a file in the user's home directory named .pydistutils.cfg + on Unix and pydistutils.cfg on Windows/Mac; may be disabled + with the ``--no-user-cfg`` option + - setup.cfg in the current directory + - a file named by an environment variable + """ + check_environ() + files = [str(path) for path in self._gen_paths() if os.path.isfile(path)] + + if DEBUG: + self.announce("using config files: {}".format(', '.join(files))) + + return files + + def _gen_paths(self): + # The system-wide Distutils config file + sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent + yield sys_dir / "distutils.cfg" + + # The per-user config file + prefix = '.' * (os.name == 'posix') + filename = prefix + 'pydistutils.cfg' + if self.want_user_cfg: + with contextlib.suppress(RuntimeError): + yield pathlib.Path('~').expanduser() / filename + + # All platforms support local setup.cfg + yield pathlib.Path('setup.cfg') + + # Additional config indicated in the environment + with contextlib.suppress(TypeError): + yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG")) + + def parse_config_files(self, filenames=None): # noqa: C901 + from configparser import ConfigParser + + # Ignore install directory options if we have a venv + if sys.prefix != sys.base_prefix: + ignore_options = [ + 'install-base', + 'install-platbase', + 'install-lib', + 'install-platlib', + 'install-purelib', + 'install-headers', + 'install-scripts', + 'install-data', + 'prefix', + 'exec-prefix', + 'home', + 'user', + 'root', + ] + else: + ignore_options = [] + + ignore_options = frozenset(ignore_options) + + if filenames is None: + filenames = self.find_config_files() + + if DEBUG: + self.announce("Distribution.parse_config_files():") + + parser = ConfigParser() + for filename in filenames: + if DEBUG: + self.announce(f" reading {filename}") + parser.read(filename, encoding='utf-8') + for section in parser.sections(): + options = parser.options(section) + opt_dict = self.get_option_dict(section) + + for opt in options: + if opt != '__name__' and opt not in ignore_options: + val = parser.get(section, opt) + opt = opt.replace('-', '_') + opt_dict[opt] = (filename, val) + + # Make the ConfigParser forget everything (so we retain + # the original filenames that options come from) + parser.__init__() + + # If there was a "global" section in the config file, use it + # to set Distribution options. + + if 'global' in self.command_options: + for opt, (_src, val) in self.command_options['global'].items(): + alias = self.negative_opt.get(opt) + try: + if alias: + setattr(self, alias, not strtobool(val)) + elif opt in ('verbose', 'dry_run'): # ugh! + setattr(self, opt, strtobool(val)) + else: + setattr(self, opt, val) + except ValueError as msg: + raise DistutilsOptionError(msg) + + # -- Command-line parsing methods ---------------------------------- + + def parse_command_line(self): + """Parse the setup script's command line, taken from the + 'script_args' instance attribute (which defaults to 'sys.argv[1:]' + -- see 'setup()' in core.py). This list is first processed for + "global options" -- options that set attributes of the Distribution + instance. Then, it is alternately scanned for Distutils commands + and options for that command. Each new command terminates the + options for the previous command. The allowed options for a + command are determined by the 'user_options' attribute of the + command class -- thus, we have to be able to load command classes + in order to parse the command line. Any error in that 'options' + attribute raises DistutilsGetoptError; any error on the + command-line raises DistutilsArgError. If no Distutils commands + were found on the command line, raises DistutilsArgError. Return + true if command-line was successfully parsed and we should carry + on with executing commands; false if no errors but we shouldn't + execute commands (currently, this only happens if user asks for + help). + """ + # + # We now have enough information to show the Macintosh dialog + # that allows the user to interactively specify the "command line". + # + toplevel_options = self._get_toplevel_options() + + # We have to parse the command line a bit at a time -- global + # options, then the first command, then its options, and so on -- + # because each command will be handled by a different class, and + # the options that are valid for a particular class aren't known + # until we have loaded the command class, which doesn't happen + # until we know what the command is. + + self.commands = [] + parser = FancyGetopt(toplevel_options + self.display_options) + parser.set_negative_aliases(self.negative_opt) + parser.set_aliases({'licence': 'license'}) + args = parser.getopt(args=self.script_args, object=self) + option_order = parser.get_option_order() + logging.getLogger().setLevel(logging.WARN - 10 * self.verbose) + + # for display options we return immediately + if self.handle_display_options(option_order): + return + while args: + args = self._parse_command_opts(parser, args) + if args is None: # user asked for help (and got it) + return + + # Handle the cases of --help as a "global" option, ie. + # "setup.py --help" and "setup.py --help command ...". For the + # former, we show global options (--verbose, --dry-run, etc.) + # and display-only options (--name, --version, etc.); for the + # latter, we omit the display-only options and show help for + # each command listed on the command line. + if self.help: + self._show_help( + parser, display_options=len(self.commands) == 0, commands=self.commands + ) + return + + # Oops, no commands found -- an end-user error + if not self.commands: + raise DistutilsArgError("no commands supplied") + + # All is well: return true + return True + + def _get_toplevel_options(self): + """Return the non-display options recognized at the top level. + + This includes options that are recognized *only* at the top + level as well as options recognized for commands. + """ + return self.global_options + [ + ( + "command-packages=", + None, + "list of packages that provide distutils commands", + ), + ] + + def _parse_command_opts(self, parser, args): # noqa: C901 + """Parse the command-line options for a single command. + 'parser' must be a FancyGetopt instance; 'args' must be the list + of arguments, starting with the current command (whose options + we are about to parse). Returns a new version of 'args' with + the next command at the front of the list; will be the empty + list if there are no more commands on the command line. Returns + None if the user asked for help on this command. + """ + # late import because of mutual dependence between these modules + from distutils.cmd import Command + + # Pull the current command from the head of the command line + command = args[0] + if not command_re.match(command): + raise SystemExit(f"invalid command name '{command}'") + self.commands.append(command) + + # Dig up the command class that implements this command, so we + # 1) know that it's a valid command, and 2) know which options + # it takes. + try: + cmd_class = self.get_command_class(command) + except DistutilsModuleError as msg: + raise DistutilsArgError(msg) + + # Require that the command class be derived from Command -- want + # to be sure that the basic "command" interface is implemented. + if not issubclass(cmd_class, Command): + raise DistutilsClassError( + f"command class {cmd_class} must subclass Command" + ) + + # Also make sure that the command object provides a list of its + # known options. + if not ( + hasattr(cmd_class, 'user_options') + and isinstance(cmd_class.user_options, list) + ): + msg = ( + "command class %s must provide " + "'user_options' attribute (a list of tuples)" + ) + raise DistutilsClassError(msg % cmd_class) + + # If the command class has a list of negative alias options, + # merge it in with the global negative aliases. + negative_opt = self.negative_opt + if hasattr(cmd_class, 'negative_opt'): + negative_opt = negative_opt.copy() + negative_opt.update(cmd_class.negative_opt) + + # Check for help_options in command class. They have a different + # format (tuple of four) so we need to preprocess them here. + if hasattr(cmd_class, 'help_options') and isinstance( + cmd_class.help_options, list + ): + help_options = fix_help_options(cmd_class.help_options) + else: + help_options = [] + + # All commands support the global options too, just by adding + # in 'global_options'. + parser.set_option_table( + self.global_options + cmd_class.user_options + help_options + ) + parser.set_negative_aliases(negative_opt) + (args, opts) = parser.getopt(args[1:]) + if hasattr(opts, 'help') and opts.help: + self._show_help(parser, display_options=False, commands=[cmd_class]) + return + + if hasattr(cmd_class, 'help_options') and isinstance( + cmd_class.help_options, list + ): + help_option_found = 0 + for help_option, _short, _desc, func in cmd_class.help_options: + if hasattr(opts, parser.get_attr_name(help_option)): + help_option_found = 1 + if callable(func): + func() + else: + raise DistutilsClassError( + f"invalid help function {func!r} for help option '{help_option}': " + "must be a callable object (function, etc.)" + ) + + if help_option_found: + return + + # Put the options from the command-line into their official + # holding pen, the 'command_options' dictionary. + opt_dict = self.get_option_dict(command) + for name, value in vars(opts).items(): + opt_dict[name] = ("command line", value) + + return args + + def finalize_options(self): + """Set final values for all the options on the Distribution + instance, analogous to the .finalize_options() method of Command + objects. + """ + for attr in ('keywords', 'platforms'): + value = getattr(self.metadata, attr) + if value is None: + continue + if isinstance(value, str): + value = [elm.strip() for elm in value.split(',')] + setattr(self.metadata, attr, value) + + def _show_help( + self, parser, global_options=True, display_options=True, commands: Iterable = () + ): + """Show help for the setup script command-line in the form of + several lists of command-line options. 'parser' should be a + FancyGetopt instance; do not expect it to be returned in the + same state, as its option table will be reset to make it + generate the correct help text. + + If 'global_options' is true, lists the global options: + --verbose, --dry-run, etc. If 'display_options' is true, lists + the "display-only" options: --name, --version, etc. Finally, + lists per-command help for every command name or command class + in 'commands'. + """ + # late import because of mutual dependence between these modules + from distutils.cmd import Command + from distutils.core import gen_usage + + if global_options: + if display_options: + options = self._get_toplevel_options() + else: + options = self.global_options + parser.set_option_table(options) + parser.print_help(self.common_usage + "\nGlobal options:") + print() + + if display_options: + parser.set_option_table(self.display_options) + parser.print_help( + "Information display options (just display information, ignore any commands)" + ) + print() + + for command in commands: + if isinstance(command, type) and issubclass(command, Command): + klass = command + else: + klass = self.get_command_class(command) + if hasattr(klass, 'help_options') and isinstance(klass.help_options, list): + parser.set_option_table( + klass.user_options + fix_help_options(klass.help_options) + ) + else: + parser.set_option_table(klass.user_options) + parser.print_help(f"Options for '{klass.__name__}' command:") + print() + + print(gen_usage(self.script_name)) + + def handle_display_options(self, option_order): + """If there were any non-global "display-only" options + (--help-commands or the metadata display options) on the command + line, display the requested info and return true; else return + false. + """ + from distutils.core import gen_usage + + # User just wants a list of commands -- we'll print it out and stop + # processing now (ie. if they ran "setup --help-commands foo bar", + # we ignore "foo bar"). + if self.help_commands: + self.print_commands() + print() + print(gen_usage(self.script_name)) + return 1 + + # If user supplied any of the "display metadata" options, then + # display that metadata in the order in which the user supplied the + # metadata options. + any_display_options = 0 + is_display_option = set() + for option in self.display_options: + is_display_option.add(option[0]) + + for opt, val in option_order: + if val and opt in is_display_option: + opt = translate_longopt(opt) + value = getattr(self.metadata, "get_" + opt)() + if opt in ('keywords', 'platforms'): + print(','.join(value)) + elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): + print('\n'.join(value)) + else: + print(value) + any_display_options = 1 + + return any_display_options + + def print_command_list(self, commands, header, max_length): + """Print a subset of the list of all commands -- used by + 'print_commands()'. + """ + print(header + ":") + + for cmd in commands: + klass = self.cmdclass.get(cmd) + if not klass: + klass = self.get_command_class(cmd) + try: + description = klass.description + except AttributeError: + description = "(no description available)" + + print(f" {cmd:<{max_length}} {description}") + + def print_commands(self): + """Print out a help message listing all available commands with a + description of each. The list is divided into "standard commands" + (listed in distutils.command.__all__) and "extra commands" + (mentioned in self.cmdclass, but not a standard command). The + descriptions come from the command class attribute + 'description'. + """ + import distutils.command + + std_commands = distutils.command.__all__ + is_std = set(std_commands) + + extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std] + + max_length = 0 + for cmd in std_commands + extra_commands: + if len(cmd) > max_length: + max_length = len(cmd) + + self.print_command_list(std_commands, "Standard commands", max_length) + if extra_commands: + print() + self.print_command_list(extra_commands, "Extra commands", max_length) + + def get_command_list(self): + """Get a list of (command, description) tuples. + The list is divided into "standard commands" (listed in + distutils.command.__all__) and "extra commands" (mentioned in + self.cmdclass, but not a standard command). The descriptions come + from the command class attribute 'description'. + """ + # Currently this is only used on Mac OS, for the Mac-only GUI + # Distutils interface (by Jack Jansen) + import distutils.command + + std_commands = distutils.command.__all__ + is_std = set(std_commands) + + extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std] + + rv = [] + for cmd in std_commands + extra_commands: + klass = self.cmdclass.get(cmd) + if not klass: + klass = self.get_command_class(cmd) + try: + description = klass.description + except AttributeError: + description = "(no description available)" + rv.append((cmd, description)) + return rv + + # -- Command class/object methods ---------------------------------- + + def get_command_packages(self): + """Return a list of packages from which commands are loaded.""" + pkgs = self.command_packages + if not isinstance(pkgs, list): + if pkgs is None: + pkgs = '' + pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != ''] + if "distutils.command" not in pkgs: + pkgs.insert(0, "distutils.command") + self.command_packages = pkgs + return pkgs + + def get_command_class(self, command): + """Return the class that implements the Distutils command named by + 'command'. First we check the 'cmdclass' dictionary; if the + command is mentioned there, we fetch the class object from the + dictionary and return it. Otherwise we load the command module + ("distutils.command." + command) and fetch the command class from + the module. The loaded class is also stored in 'cmdclass' + to speed future calls to 'get_command_class()'. + + Raises DistutilsModuleError if the expected module could not be + found, or if that module does not define the expected class. + """ + klass = self.cmdclass.get(command) + if klass: + return klass + + for pkgname in self.get_command_packages(): + module_name = f"{pkgname}.{command}" + klass_name = command + + try: + __import__(module_name) + module = sys.modules[module_name] + except ImportError: + continue + + try: + klass = getattr(module, klass_name) + except AttributeError: + raise DistutilsModuleError( + f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')" + ) + + self.cmdclass[command] = klass + return klass + + raise DistutilsModuleError(f"invalid command '{command}'") + + @overload + def get_command_obj( + self, command: str, create: Literal[True] = True + ) -> Command: ... + @overload + def get_command_obj( + self, command: str, create: Literal[False] + ) -> Command | None: ... + def get_command_obj(self, command: str, create: bool = True) -> Command | None: + """Return the command object for 'command'. Normally this object + is cached on a previous call to 'get_command_obj()'; if no command + object for 'command' is in the cache, then we either create and + return it (if 'create' is true) or return None. + """ + cmd_obj = self.command_obj.get(command) + if not cmd_obj and create: + if DEBUG: + self.announce( + "Distribution.get_command_obj(): " + f"creating '{command}' command object" + ) + + klass = self.get_command_class(command) + cmd_obj = self.command_obj[command] = klass(self) + self.have_run[command] = False + + # Set any options that were supplied in config files + # or on the command line. (NB. support for error + # reporting is lame here: any errors aren't reported + # until 'finalize_options()' is called, which means + # we won't report the source of the error.) + options = self.command_options.get(command) + if options: + self._set_command_options(cmd_obj, options) + + return cmd_obj + + def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 + """Set the options for 'command_obj' from 'option_dict'. Basically + this means copying elements of a dictionary ('option_dict') to + attributes of an instance ('command'). + + 'command_obj' must be a Command instance. If 'option_dict' is not + supplied, uses the standard option dictionary for this command + (from 'self.command_options'). + """ + command_name = command_obj.get_command_name() + if option_dict is None: + option_dict = self.get_option_dict(command_name) + + if DEBUG: + self.announce(f" setting options for '{command_name}' command:") + for option, (source, value) in option_dict.items(): + if DEBUG: + self.announce(f" {option} = {value} (from {source})") + try: + bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] + except AttributeError: + bool_opts = [] + try: + neg_opt = command_obj.negative_opt + except AttributeError: + neg_opt = {} + + try: + is_string = isinstance(value, str) + if option in neg_opt and is_string: + setattr(command_obj, neg_opt[option], not strtobool(value)) + elif option in bool_opts and is_string: + setattr(command_obj, option, strtobool(value)) + elif hasattr(command_obj, option): + setattr(command_obj, option, value) + else: + raise DistutilsOptionError( + f"error in {source}: command '{command_name}' has no such option '{option}'" + ) + except ValueError as msg: + raise DistutilsOptionError(msg) + + @overload + def reinitialize_command( + self, command: str, reinit_subcommands: bool = False + ) -> Command: ... + @overload + def reinitialize_command( + self, command: _CommandT, reinit_subcommands: bool = False + ) -> _CommandT: ... + def reinitialize_command( + self, command: str | Command, reinit_subcommands=False + ) -> Command: + """Reinitializes a command to the state it was in when first + returned by 'get_command_obj()': ie., initialized but not yet + finalized. This provides the opportunity to sneak option + values in programmatically, overriding or supplementing + user-supplied values from the config files and command line. + You'll have to re-finalize the command object (by calling + 'finalize_options()' or 'ensure_finalized()') before using it for + real. + + 'command' should be a command name (string) or command object. If + 'reinit_subcommands' is true, also reinitializes the command's + sub-commands, as declared by the 'sub_commands' class attribute (if + it has one). See the "install" command for an example. Only + reinitializes the sub-commands that actually matter, ie. those + whose test predicates return true. + + Returns the reinitialized command object. + """ + from distutils.cmd import Command + + if not isinstance(command, Command): + command_name = command + command = self.get_command_obj(command_name) + else: + command_name = command.get_command_name() + + if not command.finalized: + return command + command.initialize_options() + command.finalized = False + self.have_run[command_name] = False + self._set_command_options(command) + + if reinit_subcommands: + for sub in command.get_sub_commands(): + self.reinitialize_command(sub, reinit_subcommands) + + return command + + # -- Methods that operate on the Distribution ---------------------- + + def announce(self, msg, level=logging.INFO): + log.log(level, msg) + + def run_commands(self): + """Run each command that was seen on the setup script command line. + Uses the list of commands found and cache of command objects + created by 'get_command_obj()'. + """ + for cmd in self.commands: + self.run_command(cmd) + + # -- Methods that operate on its Commands -------------------------- + + def run_command(self, command): + """Do whatever it takes to run a command (including nothing at all, + if the command has already been run). Specifically: if we have + already created and run the command named by 'command', return + silently without doing anything. If the command named by 'command' + doesn't even have a command object yet, create one. Then invoke + 'run()' on that command object (or an existing one). + """ + # Already been here, done that? then return silently. + if self.have_run.get(command): + return + + log.info("running %s", command) + cmd_obj = self.get_command_obj(command) + cmd_obj.ensure_finalized() + cmd_obj.run() + self.have_run[command] = True + + # -- Distribution query methods ------------------------------------ + + def has_pure_modules(self): + return len(self.packages or self.py_modules or []) > 0 + + def has_ext_modules(self): + return self.ext_modules and len(self.ext_modules) > 0 + + def has_c_libraries(self): + return self.libraries and len(self.libraries) > 0 + + def has_modules(self): + return self.has_pure_modules() or self.has_ext_modules() + + def has_headers(self): + return self.headers and len(self.headers) > 0 + + def has_scripts(self): + return self.scripts and len(self.scripts) > 0 + + def has_data_files(self): + return self.data_files and len(self.data_files) > 0 + + def is_pure(self): + return ( + self.has_pure_modules() + and not self.has_ext_modules() + and not self.has_c_libraries() + ) + + # -- Metadata query methods ---------------------------------------- + + # If you're looking for 'get_name()', 'get_version()', and so forth, + # they are defined in a sneaky way: the constructor binds self.get_XXX + # to self.metadata.get_XXX. The actual code is in the + # DistributionMetadata class, below. + + +class DistributionMetadata: + """Dummy class to hold the distribution meta-data: name, version, + author, and so forth. + """ + + _METHOD_BASENAMES = ( + "name", + "version", + "author", + "author_email", + "maintainer", + "maintainer_email", + "url", + "license", + "description", + "long_description", + "keywords", + "platforms", + "fullname", + "contact", + "contact_email", + "classifiers", + "download_url", + # PEP 314 + "provides", + "requires", + "obsoletes", + ) + + def __init__(self, path=None): + if path is not None: + self.read_pkg_file(open(path)) + else: + self.name = None + self.version = None + self.author = None + self.author_email = None + self.maintainer = None + self.maintainer_email = None + self.url = None + self.license = None + self.description = None + self.long_description = None + self.keywords = None + self.platforms = None + self.classifiers = None + self.download_url = None + # PEP 314 + self.provides = None + self.requires = None + self.obsoletes = None + + def read_pkg_file(self, file): + """Reads the metadata values from a file object.""" + msg = message_from_file(file) + + def _read_field(name): + value = msg[name] + if value and value != "UNKNOWN": + return value + + def _read_list(name): + values = msg.get_all(name, None) + if values == []: + return None + return values + + metadata_version = msg['metadata-version'] + self.name = _read_field('name') + self.version = _read_field('version') + self.description = _read_field('summary') + # we are filling author only. + self.author = _read_field('author') + self.maintainer = None + self.author_email = _read_field('author-email') + self.maintainer_email = None + self.url = _read_field('home-page') + self.license = _read_field('license') + + if 'download-url' in msg: + self.download_url = _read_field('download-url') + else: + self.download_url = None + + self.long_description = _read_field('description') + self.description = _read_field('summary') + + if 'keywords' in msg: + self.keywords = _read_field('keywords').split(',') + + self.platforms = _read_list('platform') + self.classifiers = _read_list('classifier') + + # PEP 314 - these fields only exist in 1.1 + if metadata_version == '1.1': + self.requires = _read_list('requires') + self.provides = _read_list('provides') + self.obsoletes = _read_list('obsoletes') + else: + self.requires = None + self.provides = None + self.obsoletes = None + + def write_pkg_info(self, base_dir): + """Write the PKG-INFO file into the release tree.""" + with open( + os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8' + ) as pkg_info: + self.write_pkg_file(pkg_info) + + def write_pkg_file(self, file): + """Write the PKG-INFO format data to a file object.""" + version = '1.0' + if ( + self.provides + or self.requires + or self.obsoletes + or self.classifiers + or self.download_url + ): + version = '1.1' + + # required fields + file.write(f'Metadata-Version: {version}\n') + file.write(f'Name: {self.get_name()}\n') + file.write(f'Version: {self.get_version()}\n') + + def maybe_write(header, val): + if val: + file.write(f"{header}: {val}\n") + + # optional fields + maybe_write("Summary", self.get_description()) + maybe_write("Home-page", self.get_url()) + maybe_write("Author", self.get_contact()) + maybe_write("Author-email", self.get_contact_email()) + maybe_write("License", self.get_license()) + maybe_write("Download-URL", self.download_url) + maybe_write("Description", rfc822_escape(self.get_long_description() or "")) + maybe_write("Keywords", ",".join(self.get_keywords())) + + self._write_list(file, 'Platform', self.get_platforms()) + self._write_list(file, 'Classifier', self.get_classifiers()) + + # PEP 314 + self._write_list(file, 'Requires', self.get_requires()) + self._write_list(file, 'Provides', self.get_provides()) + self._write_list(file, 'Obsoletes', self.get_obsoletes()) + + def _write_list(self, file, name, values): + values = values or [] + for value in values: + file.write(f'{name}: {value}\n') + + # -- Metadata query methods ---------------------------------------- + + def get_name(self): + return self.name or "UNKNOWN" + + def get_version(self): + return self.version or "0.0.0" + + def get_fullname(self): + return self._fullname(self.get_name(), self.get_version()) + + @staticmethod + def _fullname(name: str, version: str) -> str: + """ + >>> DistributionMetadata._fullname('setup.tools', '1.0-2') + 'setup_tools-1.0.post2' + >>> DistributionMetadata._fullname('setup-tools', '1.2post2') + 'setup_tools-1.2.post2' + >>> DistributionMetadata._fullname('setup-tools', '1.0-r2') + 'setup_tools-1.0.post2' + >>> DistributionMetadata._fullname('setup.tools', '1.0.post') + 'setup_tools-1.0.post0' + >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1') + 'setup_tools-1.0+ubuntu.1' + """ + return "{}-{}".format( + canonicalize_name(name).replace('-', '_'), + canonicalize_version(version, strip_trailing_zero=False), + ) + + def get_author(self): + return self.author + + def get_author_email(self): + return self.author_email + + def get_maintainer(self): + return self.maintainer + + def get_maintainer_email(self): + return self.maintainer_email + + def get_contact(self): + return self.maintainer or self.author + + def get_contact_email(self): + return self.maintainer_email or self.author_email + + def get_url(self): + return self.url + + def get_license(self): + return self.license + + get_licence = get_license + + def get_description(self): + return self.description + + def get_long_description(self): + return self.long_description + + def get_keywords(self): + return self.keywords or [] + + def set_keywords(self, value): + self.keywords = _ensure_list(value, 'keywords') + + def get_platforms(self): + return self.platforms + + def set_platforms(self, value): + self.platforms = _ensure_list(value, 'platforms') + + def get_classifiers(self): + return self.classifiers or [] + + def set_classifiers(self, value): + self.classifiers = _ensure_list(value, 'classifiers') + + def get_download_url(self): + return self.download_url + + # PEP 314 + def get_requires(self): + return self.requires or [] + + def set_requires(self, value): + import distutils.versionpredicate + + for v in value: + distutils.versionpredicate.VersionPredicate(v) + self.requires = list(value) + + def get_provides(self): + return self.provides or [] + + def set_provides(self, value): + value = [v.strip() for v in value] + for v in value: + import distutils.versionpredicate + + distutils.versionpredicate.split_provision(v) + self.provides = value + + def get_obsoletes(self): + return self.obsoletes or [] + + def set_obsoletes(self, value): + import distutils.versionpredicate + + for v in value: + distutils.versionpredicate.VersionPredicate(v) + self.obsoletes = list(value) + + +def fix_help_options(options): + """Convert a 4-tuple 'help_options' list as found in various command + classes to the 3-tuple form required by FancyGetopt. + """ + return [opt[0:3] for opt in options] diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/errors.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3196a4f0972bbbb08556398e45dd1cef73a69f88 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/errors.py @@ -0,0 +1,124 @@ +""" +Exceptions used by the Distutils modules. + +Distutils modules may raise these or standard exceptions, +including :exc:`SystemExit`. +""" + + +class DistutilsError(Exception): + """The root of all Distutils evil.""" + + pass + + +class DistutilsModuleError(DistutilsError): + """Unable to load an expected module, or to find an expected class + within some module (in particular, command modules and classes).""" + + pass + + +class DistutilsClassError(DistutilsError): + """Some command class (or possibly distribution class, if anyone + feels a need to subclass Distribution) is found not to be holding + up its end of the bargain, ie. implementing some part of the + "command "interface.""" + + pass + + +class DistutilsGetoptError(DistutilsError): + """The option table provided to 'fancy_getopt()' is bogus.""" + + pass + + +class DistutilsArgError(DistutilsError): + """Raised by fancy_getopt in response to getopt.error -- ie. an + error in the command line usage.""" + + pass + + +class DistutilsFileError(DistutilsError): + """Any problems in the filesystem: expected file not found, etc. + Typically this is for problems that we detect before OSError + could be raised.""" + + pass + + +class DistutilsOptionError(DistutilsError): + """Syntactic/semantic errors in command options, such as use of + mutually conflicting options, or inconsistent options, + badly-spelled values, etc. No distinction is made between option + values originating in the setup script, the command line, config + files, or what-have-you -- but if we *know* something originated in + the setup script, we'll raise DistutilsSetupError instead.""" + + pass + + +class DistutilsSetupError(DistutilsError): + """For errors that can be definitely blamed on the setup script, + such as invalid keyword arguments to 'setup()'.""" + + pass + + +class DistutilsPlatformError(DistutilsError): + """We don't know how to do something on the current platform (but + we do know how to do it on some platform) -- eg. trying to compile + C files on a platform not supported by a CCompiler subclass.""" + + pass + + +class DistutilsExecError(DistutilsError): + """Any problems executing an external program (such as the C + compiler, when compiling C files).""" + + pass + + +class DistutilsInternalError(DistutilsError): + """Internal inconsistencies or impossibilities (obviously, this + should never be seen if the code is working!).""" + + pass + + +class DistutilsTemplateError(DistutilsError): + """Syntax error in a file list template.""" + + +class DistutilsByteCompileError(DistutilsError): + """Byte compile error.""" + + +# Exception classes used by the CCompiler implementation classes +class CCompilerError(Exception): + """Some compile/link operation failed.""" + + +class PreprocessError(CCompilerError): + """Failure to preprocess one or more C/C++ files.""" + + +class CompileError(CCompilerError): + """Failure to compile one or more C/C++ source files.""" + + +class LibError(CCompilerError): + """Failure to create a static library from one or more C/C++ object + files.""" + + +class LinkError(CCompilerError): + """Failure to link one or more C/C++ object files into an executable + or shared library file.""" + + +class UnknownFileError(CCompilerError): + """Attempt to process an unknown file type.""" diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/support.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/support.py new file mode 100644 index 0000000000000000000000000000000000000000..9cd2b8a9eedbb9f11a3ed793af57b3290c5febef --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/support.py @@ -0,0 +1,134 @@ +"""Support code for distutils test cases.""" + +import itertools +import os +import pathlib +import shutil +import sys +import sysconfig +import tempfile +from distutils.core import Distribution + +import pytest +from more_itertools import always_iterable + + +@pytest.mark.usefixtures('distutils_managed_tempdir') +class TempdirManager: + """ + Mix-in class that handles temporary directories for test cases. + """ + + def mkdtemp(self): + """Create a temporary directory that will be cleaned up. + + Returns the path of the directory. + """ + d = tempfile.mkdtemp() + self.tempdirs.append(d) + return d + + def write_file(self, path, content='xxx'): + """Writes a file in the given path. + + path can be a string or a sequence. + """ + pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8') + + def create_dist(self, pkg_name='foo', **kw): + """Will generate a test environment. + + This function creates: + - a Distribution instance using keywords + - a temporary directory with a package structure + + It returns the package directory and the distribution + instance. + """ + tmp_dir = self.mkdtemp() + pkg_dir = os.path.join(tmp_dir, pkg_name) + os.mkdir(pkg_dir) + dist = Distribution(attrs=kw) + + return pkg_dir, dist + + +class DummyCommand: + """Class to store options for retrieval via set_undefined_options().""" + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + def ensure_finalized(self): + pass + + +def copy_xxmodule_c(directory): + """Helper for tests that need the xxmodule.c source file. + + Example use: + + def test_compile(self): + copy_xxmodule_c(self.tmpdir) + self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) + + If the source file can be found, it will be copied to *directory*. If not, + the test will be skipped. Errors during copy are not caught. + """ + shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c')) + + +def _get_xxmodule_path(): + source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c' + return os.path.join(os.path.dirname(__file__), source_name) + + +def fixup_build_ext(cmd): + """Function needed to make build_ext tests pass. + + When Python was built with --enable-shared on Unix, -L. is not enough to + find libpython.so, because regrtest runs in a tempdir, not in the + source directory where the .so lives. + + When Python was built with in debug mode on Windows, build_ext commands + need their debug attribute set, and it is not done automatically for + some reason. + + This function handles both of these things. Example use: + + cmd = build_ext(dist) + support.fixup_build_ext(cmd) + cmd.ensure_finalized() + + Unlike most other Unix platforms, Mac OS X embeds absolute paths + to shared libraries into executables, so the fixup is not needed there. + """ + if os.name == 'nt': + cmd.debug = sys.executable.endswith('_d.exe') + elif sysconfig.get_config_var('Py_ENABLE_SHARED'): + # To further add to the shared builds fun on Unix, we can't just add + # library_dirs to the Extension() instance because that doesn't get + # plumbed through to the final compiler command. + runshared = sysconfig.get_config_var('RUNSHARED') + if runshared is None: + cmd.library_dirs = ['.'] + else: + if sys.platform == 'darwin': + cmd.library_dirs = [] + else: + name, equals, value = runshared.partition('=') + cmd.library_dirs = [d for d in value.split(os.pathsep) if d] + + +def combine_markers(cls): + """ + pytest will honor markers as found on the class, but when + markers are on multiple subclasses, only one appears. Use + this decorator to combine those markers. + """ + cls.pytestmark = [ + mark + for base in itertools.chain([cls], cls.__bases__) + for mark in getattr(base, 'pytestmark', []) + ] + return cls diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_archive_util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4ed75a761dc26fc7dc29066138a02531c6e9c3 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_archive_util.py @@ -0,0 +1,353 @@ +"""Tests for distutils.archive_util.""" + +import functools +import operator +import os +import pathlib +import sys +import tarfile +from distutils import archive_util +from distutils.archive_util import ( + ARCHIVE_FORMATS, + check_archive_formats, + make_archive, + make_tarball, + make_zipfile, +) +from distutils.spawn import spawn +from distutils.tests import support +from os.path import splitdrive + +import path +import pytest +from test.support import patch + +from .unix_compat import UID_0_SUPPORT, grp, pwd, require_uid_0, require_unix_id + + +def can_fs_encode(filename): + """ + Return True if the filename can be saved in the file system. + """ + if os.path.supports_unicode_filenames: + return True + try: + filename.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + return False + return True + + +def all_equal(values): + return functools.reduce(operator.eq, values) + + +def same_drive(*paths): + return all_equal(pathlib.Path(path).drive for path in paths) + + +class ArchiveUtilTestCase(support.TempdirManager): + @pytest.mark.usefixtures('needs_zlib') + def test_make_tarball(self, name='archive'): + # creating something to tar + tmpdir = self._create_files() + self._make_tarball(tmpdir, name, '.tar.gz') + # trying an uncompressed one + self._make_tarball(tmpdir, name, '.tar', compress=None) + + @pytest.mark.usefixtures('needs_zlib') + def test_make_tarball_gzip(self): + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip') + + def test_make_tarball_bzip2(self): + pytest.importorskip('bz2') + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.bz2', compress='bzip2') + + def test_make_tarball_xz(self): + pytest.importorskip('lzma') + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz') + + @pytest.mark.skipif("not can_fs_encode('årchiv')") + def test_make_tarball_latin1(self): + """ + Mirror test_make_tarball, except filename contains latin characters. + """ + self.test_make_tarball('årchiv') # note this isn't a real word + + @pytest.mark.skipif("not can_fs_encode('のアーカイブ')") + def test_make_tarball_extended(self): + """ + Mirror test_make_tarball, except filename contains extended + characters outside the latin charset. + """ + self.test_make_tarball('のアーカイブ') # japanese for archive + + def _make_tarball(self, tmpdir, target_name, suffix, **kwargs): + tmpdir2 = self.mkdtemp() + if same_drive(tmpdir, tmpdir2): + pytest.skip("source and target should be on same drive") + + base_name = os.path.join(tmpdir2, target_name) + + # working with relative paths to avoid tar warnings + with path.Path(tmpdir): + make_tarball(splitdrive(base_name)[1], 'dist', **kwargs) + + # check if the compressed tarball was created + tarball = base_name + suffix + assert os.path.exists(tarball) + assert self._tarinfo(tarball) == self._created_files + + def _tarinfo(self, path): + tar = tarfile.open(path) + try: + names = tar.getnames() + names.sort() + return names + finally: + tar.close() + + _zip_created_files = [ + 'dist/', + 'dist/file1', + 'dist/file2', + 'dist/sub/', + 'dist/sub/file3', + 'dist/sub2/', + ] + _created_files = [p.rstrip('/') for p in _zip_created_files] + + def _create_files(self): + # creating something to tar + tmpdir = self.mkdtemp() + dist = os.path.join(tmpdir, 'dist') + os.mkdir(dist) + self.write_file([dist, 'file1'], 'xxx') + self.write_file([dist, 'file2'], 'xxx') + os.mkdir(os.path.join(dist, 'sub')) + self.write_file([dist, 'sub', 'file3'], 'xxx') + os.mkdir(os.path.join(dist, 'sub2')) + return tmpdir + + @pytest.mark.usefixtures('needs_zlib') + @pytest.mark.skipif("not (shutil.which('tar') and shutil.which('gzip'))") + def test_tarfile_vs_tar(self): + tmpdir = self._create_files() + tmpdir2 = self.mkdtemp() + base_name = os.path.join(tmpdir2, 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + make_tarball(base_name, 'dist') + finally: + os.chdir(old_dir) + + # check if the compressed tarball was created + tarball = base_name + '.tar.gz' + assert os.path.exists(tarball) + + # now create another tarball using `tar` + tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') + tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist'] + gzip_cmd = ['gzip', '-f', '-9', 'archive2.tar'] + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + spawn(tar_cmd) + spawn(gzip_cmd) + finally: + os.chdir(old_dir) + + assert os.path.exists(tarball2) + # let's compare both tarballs + assert self._tarinfo(tarball) == self._created_files + assert self._tarinfo(tarball2) == self._created_files + + # trying an uncompressed one + base_name = os.path.join(tmpdir2, 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + make_tarball(base_name, 'dist', compress=None) + finally: + os.chdir(old_dir) + tarball = base_name + '.tar' + assert os.path.exists(tarball) + + # now for a dry_run + base_name = os.path.join(tmpdir2, 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + make_tarball(base_name, 'dist', compress=None, dry_run=True) + finally: + os.chdir(old_dir) + tarball = base_name + '.tar' + assert os.path.exists(tarball) + + @pytest.mark.usefixtures('needs_zlib') + def test_make_zipfile(self): + zipfile = pytest.importorskip('zipfile') + # creating something to tar + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + with path.Path(tmpdir): + make_zipfile(base_name, 'dist') + + # check if the compressed tarball was created + tarball = base_name + '.zip' + assert os.path.exists(tarball) + with zipfile.ZipFile(tarball) as zf: + assert sorted(zf.namelist()) == self._zip_created_files + + def test_make_zipfile_no_zlib(self): + zipfile = pytest.importorskip('zipfile') + patch(self, archive_util.zipfile, 'zlib', None) # force zlib ImportError + + called = [] + zipfile_class = zipfile.ZipFile + + def fake_zipfile(*a, **kw): + if kw.get('compression', None) == zipfile.ZIP_STORED: + called.append((a, kw)) + return zipfile_class(*a, **kw) + + patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile) + + # create something to tar and compress + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + with path.Path(tmpdir): + make_zipfile(base_name, 'dist') + + tarball = base_name + '.zip' + assert called == [((tarball, "w"), {'compression': zipfile.ZIP_STORED})] + assert os.path.exists(tarball) + with zipfile.ZipFile(tarball) as zf: + assert sorted(zf.namelist()) == self._zip_created_files + + def test_check_archive_formats(self): + assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx' + assert ( + check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) + is None + ) + + def test_make_archive(self): + tmpdir = self.mkdtemp() + base_name = os.path.join(tmpdir, 'archive') + with pytest.raises(ValueError): + make_archive(base_name, 'xxx') + + def test_make_archive_cwd(self): + current_dir = os.getcwd() + + def _breaks(*args, **kw): + raise RuntimeError() + + ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file') + try: + try: + make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) + except Exception: + pass + assert os.getcwd() == current_dir + finally: + ARCHIVE_FORMATS.pop('xxx') + + def test_make_archive_tar(self): + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'tar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar' + assert self._tarinfo(res) == self._created_files + + @pytest.mark.usefixtures('needs_zlib') + def test_make_archive_gztar(self): + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'gztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.gz' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_bztar(self): + pytest.importorskip('bz2') + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'bztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.bz2' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_xztar(self): + pytest.importorskip('lzma') + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'xztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.xz' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_owner_group(self): + # testing make_archive with owner and group, with various combinations + # this works even if there's not gid/uid support + if UID_0_SUPPORT: + group = grp.getgrgid(0)[0] + owner = pwd.getpwuid(0)[0] + else: + group = owner = 'root' + + base_dir = self._create_files() + root_dir = self.mkdtemp() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive( + base_name, 'zip', root_dir, base_dir, owner=owner, group=group + ) + assert os.path.exists(res) + + res = make_archive(base_name, 'zip', root_dir, base_dir) + assert os.path.exists(res) + + res = make_archive( + base_name, 'tar', root_dir, base_dir, owner=owner, group=group + ) + assert os.path.exists(res) + + res = make_archive( + base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh' + ) + assert os.path.exists(res) + + @pytest.mark.usefixtures('needs_zlib') + @require_unix_id + @require_uid_0 + def test_tarfile_root_owner(self): + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + group = grp.getgrgid(0)[0] + owner = pwd.getpwuid(0)[0] + try: + archive_name = make_tarball( + base_name, 'dist', compress=None, owner=owner, group=group + ) + finally: + os.chdir(old_dir) + + # check if the compressed tarball was created + assert os.path.exists(archive_name) + + # now checks the rights + archive = tarfile.open(archive_name) + try: + for member in archive.getmembers(): + assert member.uid == 0 + assert member.gid == 0 + finally: + archive.close() diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py new file mode 100644 index 0000000000000000000000000000000000000000..75051430e224c8908e22601133a40f5f82ee455a --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py @@ -0,0 +1,127 @@ +"""Tests for distutils.command.bdist_rpm.""" + +import os +import shutil # noqa: F401 +import sys +from distutils.command.bdist_rpm import bdist_rpm +from distutils.core import Distribution +from distutils.tests import support + +import pytest +from test.support import requires_zlib + +SETUP_PY = """\ +from distutils.core import setup +import foo + +setup(name='foo', version='0.1', py_modules=['foo'], + url='xxx', author='xxx', author_email='xxx') + +""" + + +@pytest.fixture(autouse=True) +def sys_executable_encodable(): + try: + sys.executable.encode('UTF-8') + except UnicodeEncodeError: + pytest.skip("sys.executable is not encodable to UTF-8") + + +mac_woes = pytest.mark.skipif( + "not sys.platform.startswith('linux')", + reason='spurious sdtout/stderr output under macOS', +) + + +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +@pytest.mark.usefixtures('save_cwd') +class TestBuildRpm( + support.TempdirManager, +): + @mac_woes + @requires_zlib() + @pytest.mark.skipif("not shutil.which('rpm')") + @pytest.mark.skipif("not shutil.which('rpmbuild')") + def test_quiet(self): + # let's create a package + tmp_dir = self.mkdtemp() + os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation + pkg_dir = os.path.join(tmp_dir, 'foo') + os.mkdir(pkg_dir) + self.write_file((pkg_dir, 'setup.py'), SETUP_PY) + self.write_file((pkg_dir, 'foo.py'), '#') + self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') + self.write_file((pkg_dir, 'README'), '') + + dist = Distribution({ + 'name': 'foo', + 'version': '0.1', + 'py_modules': ['foo'], + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + }) + dist.script_name = 'setup.py' + os.chdir(pkg_dir) + + sys.argv = ['setup.py'] + cmd = bdist_rpm(dist) + cmd.fix_python = True + + # running in quiet mode + cmd.quiet = True + cmd.ensure_finalized() + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) + assert 'foo-0.1-1.noarch.rpm' in dist_created + + # bug #2945: upload ignores bdist_rpm files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files + + @mac_woes + @requires_zlib() + # https://bugs.python.org/issue1533164 + @pytest.mark.skipif("not shutil.which('rpm')") + @pytest.mark.skipif("not shutil.which('rpmbuild')") + def test_no_optimize_flag(self): + # let's create a package that breaks bdist_rpm + tmp_dir = self.mkdtemp() + os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation + pkg_dir = os.path.join(tmp_dir, 'foo') + os.mkdir(pkg_dir) + self.write_file((pkg_dir, 'setup.py'), SETUP_PY) + self.write_file((pkg_dir, 'foo.py'), '#') + self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') + self.write_file((pkg_dir, 'README'), '') + + dist = Distribution({ + 'name': 'foo', + 'version': '0.1', + 'py_modules': ['foo'], + 'url': 'xxx', + 'author': 'xxx', + 'author_email': 'xxx', + }) + dist.script_name = 'setup.py' + os.chdir(pkg_dir) + + sys.argv = ['setup.py'] + cmd = bdist_rpm(dist) + cmd.fix_python = True + + cmd.quiet = True + cmd.ensure_finalized() + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) + assert 'foo-0.1-1.noarch.rpm' in dist_created + + # bug #2945: upload ignores bdist_rpm files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm') in dist.dist_files + assert ('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm') in dist.dist_files + + os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_dist.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5beebe64eb9d747088cf117082a546330b29f3 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_dist.py @@ -0,0 +1,552 @@ +"""Tests for distutils.dist.""" + +import email +import email.generator +import email.policy +import functools +import io +import os +import sys +import textwrap +import unittest.mock as mock +import warnings +from distutils.cmd import Command +from distutils.dist import Distribution, fix_help_options +from distutils.tests import support +from typing import ClassVar + +import jaraco.path +import pytest + +pydistutils_cfg = '.' * (os.name == 'posix') + 'pydistutils.cfg' + + +class test_dist(Command): + """Sample distutils extension command.""" + + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ("sample-option=", "S", "help text"), + ] + + def initialize_options(self): + self.sample_option = None + + +class TestDistribution(Distribution): + """Distribution subclasses that avoids the default search for + configuration files. + + The ._config_files attribute must be set before + .parse_config_files() is called. + """ + + def find_config_files(self): + return self._config_files + + +@pytest.fixture +def clear_argv(): + del sys.argv[1:] + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +class TestDistributionBehavior(support.TempdirManager): + def create_distribution(self, configfiles=()): + d = TestDistribution() + d._config_files = configfiles + d.parse_config_files() + d.parse_command_line() + return d + + def test_command_packages_unspecified(self, clear_argv): + sys.argv.append("build") + d = self.create_distribution() + assert d.get_command_packages() == ["distutils.command"] + + def test_command_packages_cmdline(self, clear_argv): + from distutils.tests.test_dist import test_dist + + sys.argv.extend([ + "--command-packages", + "foo.bar,distutils.tests", + "test_dist", + "-Ssometext", + ]) + d = self.create_distribution() + # let's actually try to load our test command: + assert d.get_command_packages() == [ + "distutils.command", + "foo.bar", + "distutils.tests", + ] + cmd = d.get_command_obj("test_dist") + assert isinstance(cmd, test_dist) + assert cmd.sample_option == "sometext" + + @pytest.mark.skipif( + 'distutils' not in Distribution.parse_config_files.__module__, + reason='Cannot test when virtualenv has monkey-patched Distribution', + ) + def test_venv_install_options(self, tmp_path, clear_argv): + sys.argv.append("install") + file = str(tmp_path / 'file') + + fakepath = '/somedir' + + jaraco.path.build({ + file: f""" + [install] + install-base = {fakepath} + install-platbase = {fakepath} + install-lib = {fakepath} + install-platlib = {fakepath} + install-purelib = {fakepath} + install-headers = {fakepath} + install-scripts = {fakepath} + install-data = {fakepath} + prefix = {fakepath} + exec-prefix = {fakepath} + home = {fakepath} + user = {fakepath} + root = {fakepath} + """, + }) + + # Base case: Not in a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'): + d = self.create_distribution([file]) + + option_tuple = (file, fakepath) + + result_dict = { + 'install_base': option_tuple, + 'install_platbase': option_tuple, + 'install_lib': option_tuple, + 'install_platlib': option_tuple, + 'install_purelib': option_tuple, + 'install_headers': option_tuple, + 'install_scripts': option_tuple, + 'install_data': option_tuple, + 'prefix': option_tuple, + 'exec_prefix': option_tuple, + 'home': option_tuple, + 'user': option_tuple, + 'root': option_tuple, + } + + assert sorted(d.command_options.get('install').keys()) == sorted( + result_dict.keys() + ) + + for key, value in d.command_options.get('install').items(): + assert value == result_dict[key] + + # Test case: In a Virtual Environment + with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'): + d = self.create_distribution([file]) + + for key in result_dict.keys(): + assert key not in d.command_options.get('install', {}) + + def test_command_packages_configfile(self, tmp_path, clear_argv): + sys.argv.append("build") + file = str(tmp_path / "file") + jaraco.path.build({ + file: """ + [global] + command_packages = foo.bar, splat + """, + }) + + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command", "foo.bar", "splat"] + + # ensure command line overrides config: + sys.argv[1:] = ["--command-packages", "spork", "build"] + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command", "spork"] + + # Setting --command-packages to '' should cause the default to + # be used even if a config file specified something else: + sys.argv[1:] = ["--command-packages", "", "build"] + d = self.create_distribution([file]) + assert d.get_command_packages() == ["distutils.command"] + + def test_empty_options(self, request): + # an empty options dictionary should not stay in the + # list of attributes + + # catching warnings + warns = [] + + def _warn(msg): + warns.append(msg) + + request.addfinalizer( + functools.partial(setattr, warnings, 'warn', warnings.warn) + ) + warnings.warn = _warn + dist = Distribution( + attrs={ + 'author': 'xxx', + 'name': 'xxx', + 'version': 'xxx', + 'url': 'xxxx', + 'options': {}, + } + ) + + assert len(warns) == 0 + assert 'options' not in dir(dist) + + def test_finalize_options(self): + attrs = {'keywords': 'one,two', 'platforms': 'one,two'} + + dist = Distribution(attrs=attrs) + dist.finalize_options() + + # finalize_option splits platforms and keywords + assert dist.metadata.platforms == ['one', 'two'] + assert dist.metadata.keywords == ['one', 'two'] + + attrs = {'keywords': 'foo bar', 'platforms': 'foo bar'} + dist = Distribution(attrs=attrs) + dist.finalize_options() + assert dist.metadata.platforms == ['foo bar'] + assert dist.metadata.keywords == ['foo bar'] + + def test_get_command_packages(self): + dist = Distribution() + assert dist.command_packages is None + cmds = dist.get_command_packages() + assert cmds == ['distutils.command'] + assert dist.command_packages == ['distutils.command'] + + dist.command_packages = 'one,two' + cmds = dist.get_command_packages() + assert cmds == ['distutils.command', 'one', 'two'] + + def test_announce(self): + # make sure the level is known + dist = Distribution() + with pytest.raises(TypeError): + dist.announce('ok', level='ok2') + + def test_find_config_files_disable(self, temp_home): + # Ticket #1180: Allow user to disable their home config file. + jaraco.path.build({pydistutils_cfg: '[distutils]\n'}, temp_home) + + d = Distribution() + all_files = d.find_config_files() + + d = Distribution(attrs={'script_args': ['--no-user-cfg']}) + files = d.find_config_files() + + # make sure --no-user-cfg disables the user cfg file + assert len(all_files) - 1 == len(files) + + def test_script_args_list_coercion(self): + d = Distribution(attrs={'script_args': ('build', '--no-user-cfg')}) + + # make sure script_args is a list even if it started as a different iterable + assert d.script_args == ['build', '--no-user-cfg'] + + @pytest.mark.skipif( + 'platform.system() == "Windows"', + reason='Windows does not honor chmod 000', + ) + def test_find_config_files_permission_error(self, fake_home): + """ + Finding config files should not fail when directory is inaccessible. + """ + fake_home.joinpath(pydistutils_cfg).write_text('', encoding='utf-8') + fake_home.chmod(0o000) + Distribution().find_config_files() + + +@pytest.mark.usefixtures('save_env') +@pytest.mark.usefixtures('save_argv') +class TestMetadata(support.TempdirManager): + def format_metadata(self, dist): + sio = io.StringIO() + dist.metadata.write_pkg_file(sio) + return sio.getvalue() + + def test_simple_metadata(self): + attrs = {"name": "package", "version": "1.0"} + dist = Distribution(attrs) + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.0" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() + + def test_provides(self): + attrs = { + "name": "package", + "version": "1.0", + "provides": ["package", "package.sub"], + } + dist = Distribution(attrs) + assert dist.metadata.get_provides() == ["package", "package.sub"] + assert dist.get_provides() == ["package", "package.sub"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "requires:" not in meta.lower() + assert "obsoletes:" not in meta.lower() + + def test_provides_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]}, + ) + + def test_requires(self): + attrs = { + "name": "package", + "version": "1.0", + "requires": ["other", "another (==1.0)"], + } + dist = Distribution(attrs) + assert dist.metadata.get_requires() == ["other", "another (==1.0)"] + assert dist.get_requires() == ["other", "another (==1.0)"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "Requires: other" in meta + assert "Requires: another (==1.0)" in meta + assert "obsoletes:" not in meta.lower() + + def test_requires_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]}, + ) + + def test_requires_to_list(self): + attrs = {"name": "package", "requires": iter(["other"])} + dist = Distribution(attrs) + assert isinstance(dist.metadata.requires, list) + + def test_obsoletes(self): + attrs = { + "name": "package", + "version": "1.0", + "obsoletes": ["other", "another (<1.0)"], + } + dist = Distribution(attrs) + assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"] + assert dist.get_obsoletes() == ["other", "another (<1.0)"] + meta = self.format_metadata(dist) + assert "Metadata-Version: 1.1" in meta + assert "provides:" not in meta.lower() + assert "requires:" not in meta.lower() + assert "Obsoletes: other" in meta + assert "Obsoletes: another (<1.0)" in meta + + def test_obsoletes_illegal(self): + with pytest.raises(ValueError): + Distribution( + {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]}, + ) + + def test_obsoletes_to_list(self): + attrs = {"name": "package", "obsoletes": iter(["other"])} + dist = Distribution(attrs) + assert isinstance(dist.metadata.obsoletes, list) + + def test_classifier(self): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'classifiers': ['Programming Language :: Python :: 3'], + } + dist = Distribution(attrs) + assert dist.get_classifiers() == ['Programming Language :: Python :: 3'] + meta = self.format_metadata(dist) + assert 'Metadata-Version: 1.1' in meta + + def test_classifier_invalid_type(self, caplog): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'classifiers': ('Programming Language :: Python :: 3',), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.classifiers, list) + assert d.metadata.classifiers == list(attrs['classifiers']) + + def test_keywords(self): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'keywords': ['spam', 'eggs', 'life of brian'], + } + dist = Distribution(attrs) + assert dist.get_keywords() == ['spam', 'eggs', 'life of brian'] + + def test_keywords_invalid_type(self, caplog): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'keywords': ('spam', 'eggs', 'life of brian'), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.keywords, list) + assert d.metadata.keywords == list(attrs['keywords']) + + def test_platforms(self): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'platforms': ['GNU/Linux', 'Some Evil Platform'], + } + dist = Distribution(attrs) + assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform'] + + def test_platforms_invalid_types(self, caplog): + attrs = { + 'name': 'Monty', + 'version': '1.0', + 'platforms': ('GNU/Linux', 'Some Evil Platform'), + } + d = Distribution(attrs) + # should have warning about passing a non-list + assert 'should be a list' in caplog.messages[0] + # should be converted to a list + assert isinstance(d.metadata.platforms, list) + assert d.metadata.platforms == list(attrs['platforms']) + + def test_download_url(self): + attrs = { + 'name': 'Boa', + 'version': '3.0', + 'download_url': 'http://example.org/boa', + } + dist = Distribution(attrs) + meta = self.format_metadata(dist) + assert 'Metadata-Version: 1.1' in meta + + def test_long_description(self): + long_desc = textwrap.dedent( + """\ + example:: + We start here + and continue here + and end here.""" + ) + attrs = {"name": "package", "version": "1.0", "long_description": long_desc} + + dist = Distribution(attrs) + meta = self.format_metadata(dist) + meta = meta.replace('\n' + 8 * ' ', '\n') + assert long_desc in meta + + def test_custom_pydistutils(self, temp_home): + """ + pydistutils.cfg is found + """ + jaraco.path.build({pydistutils_cfg: ''}, temp_home) + config_path = temp_home / pydistutils_cfg + + assert str(config_path) in Distribution().find_config_files() + + def test_extra_pydistutils(self, monkeypatch, tmp_path): + jaraco.path.build({'overrides.cfg': ''}, tmp_path) + filename = tmp_path / 'overrides.cfg' + monkeypatch.setenv('DIST_EXTRA_CONFIG', str(filename)) + assert str(filename) in Distribution().find_config_files() + + def test_fix_help_options(self): + help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] + fancy_options = fix_help_options(help_tuples) + assert fancy_options[0] == ('a', 'b', 'c') + assert fancy_options[1] == (1, 2, 3) + + def test_show_help(self, request, capsys): + # smoke test, just makes sure some help is displayed + dist = Distribution() + sys.argv = [] + dist.help = True + dist.script_name = 'setup.py' + dist.parse_command_line() + + output = [ + line for line in capsys.readouterr().out.split('\n') if line.strip() != '' + ] + assert output + + def test_read_metadata(self): + attrs = { + "name": "package", + "version": "1.0", + "long_description": "desc", + "description": "xxx", + "download_url": "http://example.com", + "keywords": ['one', 'two'], + "requires": ['foo'], + } + + dist = Distribution(attrs) + metadata = dist.metadata + + # write it then reloads it + PKG_INFO = io.StringIO() + metadata.write_pkg_file(PKG_INFO) + PKG_INFO.seek(0) + metadata.read_pkg_file(PKG_INFO) + + assert metadata.name == "package" + assert metadata.version == "1.0" + assert metadata.description == "xxx" + assert metadata.download_url == 'http://example.com' + assert metadata.keywords == ['one', 'two'] + assert metadata.platforms is None + assert metadata.obsoletes is None + assert metadata.requires == ['foo'] + + def test_round_trip_through_email_generator(self): + """ + In pypa/setuptools#4033, it was shown that once PKG-INFO is + re-generated using ``email.generator.Generator``, some control + characters might cause problems. + """ + # Given a PKG-INFO file ... + attrs = { + "name": "package", + "version": "1.0", + "long_description": "hello\x0b\nworld\n", + } + dist = Distribution(attrs) + metadata = dist.metadata + + with io.StringIO() as buffer: + metadata.write_pkg_file(buffer) + msg = buffer.getvalue() + + # ... when it is read and re-written using stdlib's email library, + orig = email.message_from_string(msg) + policy = email.policy.EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with io.StringIO() as buffer: + email.generator.Generator(buffer, policy=policy).flatten(orig) + + buffer.seek(0) + regen = email.message_from_file(buffer) + + # ... then it should be the same as the original + # (except for the specific line break characters) + orig_desc = set(orig["Description"].splitlines()) + regen_desc = set(regen["Description"].splitlines()) + assert regen_desc == orig_desc diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_extension.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8e768223ea40d7a629111db181a946cf8ca5b0 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_extension.py @@ -0,0 +1,117 @@ +"""Tests for distutils.extension.""" + +import os +import pathlib +import warnings +from distutils.extension import Extension, read_setup_file + +import pytest +from test.support.warnings_helper import check_warnings + + +class TestExtension: + def test_read_setup_file(self): + # trying to read a Setup file + # (sample extracted from the PyGame project) + setup = os.path.join(os.path.dirname(__file__), 'Setup.sample') + + exts = read_setup_file(setup) + names = [ext.name for ext in exts] + names.sort() + + # here are the extensions read_setup_file should have created + # out of the file + wanted = [ + '_arraysurfarray', + '_camera', + '_numericsndarray', + '_numericsurfarray', + 'base', + 'bufferproxy', + 'cdrom', + 'color', + 'constants', + 'display', + 'draw', + 'event', + 'fastevent', + 'font', + 'gfxdraw', + 'image', + 'imageext', + 'joystick', + 'key', + 'mask', + 'mixer', + 'mixer_music', + 'mouse', + 'movie', + 'overlay', + 'pixelarray', + 'pypm', + 'rect', + 'rwobject', + 'scrap', + 'surface', + 'surflock', + 'time', + 'transform', + ] + + assert names == wanted + + def test_extension_init(self): + # the first argument, which is the name, must be a string + with pytest.raises(TypeError): + Extension(1, []) + ext = Extension('name', []) + assert ext.name == 'name' + + # the second argument, which is the list of files, must + # be an iterable of strings or PathLike objects, and not a string + with pytest.raises(TypeError): + Extension('name', 'file') + with pytest.raises(TypeError): + Extension('name', ['file', 1]) + ext = Extension('name', ['file1', 'file2']) + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', [pathlib.Path('file1'), pathlib.Path('file2')]) + assert ext.sources == ['file1', 'file2'] + + # any non-string iterable of strings or PathLike objects should work + ext = Extension('name', ('file1', 'file2')) # tuple + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', {'file1', 'file2'}) # set + assert sorted(ext.sources) == ['file1', 'file2'] + ext = Extension('name', iter(['file1', 'file2'])) # iterator + assert ext.sources == ['file1', 'file2'] + ext = Extension('name', [pathlib.Path('file1'), 'file2']) # mixed types + assert ext.sources == ['file1', 'file2'] + + # others arguments have defaults + for attr in ( + 'include_dirs', + 'define_macros', + 'undef_macros', + 'library_dirs', + 'libraries', + 'runtime_library_dirs', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + 'export_symbols', + 'swig_opts', + 'depends', + ): + assert getattr(ext, attr) == [] + + assert ext.language is None + assert ext.optional is None + + # if there are unknown keyword options, warn about them + with check_warnings() as w: + warnings.simplefilter('always') + ext = Extension('name', ['file1', 'file2'], chic=True) + + assert len(w.warnings) == 1 + assert str(w.warnings[0].message) == "Unknown Extension options: 'chic'" diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_file_util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_file_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d4a0317dc717c24f67127370aa87089eeba1a --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_file_util.py @@ -0,0 +1,95 @@ +"""Tests for distutils.file_util.""" + +import errno +import os +import unittest.mock as mock +from distutils.errors import DistutilsFileError +from distutils.file_util import copy_file, move_file + +import jaraco.path +import pytest + + +@pytest.fixture(autouse=True) +def stuff(request, tmp_path): + self = request.instance + self.source = tmp_path / 'f1' + self.target = tmp_path / 'f2' + self.target_dir = tmp_path / 'd1' + + +class TestFileUtil: + def test_move_file_verbosity(self, caplog): + jaraco.path.build({self.source: 'some content'}) + + move_file(self.source, self.target, verbose=False) + assert not caplog.messages + + # back to original state + move_file(self.target, self.source, verbose=False) + + move_file(self.source, self.target, verbose=True) + wanted = [f'moving {self.source} -> {self.target}'] + assert caplog.messages == wanted + + # back to original state + move_file(self.target, self.source, verbose=False) + + caplog.clear() + # now the target is a dir + os.mkdir(self.target_dir) + move_file(self.source, self.target_dir, verbose=True) + wanted = [f'moving {self.source} -> {self.target_dir}'] + assert caplog.messages == wanted + + def test_move_file_exception_unpacking_rename(self): + # see issue 22182 + with ( + mock.patch("os.rename", side_effect=OSError("wrong", 1)), + pytest.raises(DistutilsFileError), + ): + jaraco.path.build({self.source: 'spam eggs'}) + move_file(self.source, self.target, verbose=False) + + def test_move_file_exception_unpacking_unlink(self): + # see issue 22182 + with ( + mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), + mock.patch("os.unlink", side_effect=OSError("wrong", 1)), + pytest.raises(DistutilsFileError), + ): + jaraco.path.build({self.source: 'spam eggs'}) + move_file(self.source, self.target, verbose=False) + + def test_copy_file_hard_link(self): + jaraco.path.build({self.source: 'some content'}) + # Check first that copy_file() will not fall back on copying the file + # instead of creating the hard link. + try: + os.link(self.source, self.target) + except OSError as e: + self.skipTest(f'os.link: {e}') + else: + self.target.unlink() + st = os.stat(self.source) + copy_file(self.source, self.target, link='hard') + st2 = os.stat(self.source) + st3 = os.stat(self.target) + assert os.path.samestat(st, st2), (st, st2) + assert os.path.samestat(st2, st3), (st2, st3) + assert self.source.read_text(encoding='utf-8') == 'some content' + + def test_copy_file_hard_link_failure(self): + # If hard linking fails, copy_file() falls back on copying file + # (some special filesystems don't support hard linking even under + # Unix, see issue #8876). + jaraco.path.build({self.source: 'some content'}) + st = os.stat(self.source) + with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")): + copy_file(self.source, self.target, link='hard') + st2 = os.stat(self.source) + st3 = os.stat(self.target) + assert os.path.samestat(st, st2), (st, st2) + assert not os.path.samestat(st2, st3), (st2, st3) + for fn in (self.source, self.target): + assert fn.read_text(encoding='utf-8') == 'some content' diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ffb2e668ac5a042c5a2889d7b51b5755b73157 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install.py @@ -0,0 +1,245 @@ +"""Tests for distutils.command.install.""" + +import logging +import os +import pathlib +import site +import sys +from distutils import sysconfig +from distutils.command import install as install_module +from distutils.command.build_ext import build_ext +from distutils.command.install import INSTALL_SCHEMES, install +from distutils.core import Distribution +from distutils.errors import DistutilsOptionError +from distutils.extension import Extension +from distutils.tests import missing_compiler_executable, support +from distutils.util import is_mingw + +import pytest + + +def _make_ext_name(modname): + return modname + sysconfig.get_config_var('EXT_SUFFIX') + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +class TestInstall( + support.TempdirManager, +): + @pytest.mark.xfail( + 'platform.system() == "Windows" and sys.version_info > (3, 11)', + reason="pypa/distutils#148", + ) + def test_home_installation_scheme(self): + # This ensure two things: + # - that --home generates the desired set of directory names + # - test --home is supported on all platforms + builddir = self.mkdtemp() + destination = os.path.join(builddir, "installation") + + dist = Distribution({"name": "foopkg"}) + # script_name need not exist, it just need to be initialized + dist.script_name = os.path.join(builddir, "setup.py") + dist.command_obj["build"] = support.DummyCommand( + build_base=builddir, + build_lib=os.path.join(builddir, "lib"), + ) + + cmd = install(dist) + cmd.home = destination + cmd.ensure_finalized() + + assert cmd.install_base == destination + assert cmd.install_platbase == destination + + def check_path(got, expected): + got = os.path.normpath(got) + expected = os.path.normpath(expected) + assert got == expected + + impl_name = sys.implementation.name.replace("cpython", "python") + libdir = os.path.join(destination, "lib", impl_name) + check_path(cmd.install_lib, libdir) + _platlibdir = getattr(sys, "platlibdir", "lib") + platlibdir = os.path.join(destination, _platlibdir, impl_name) + check_path(cmd.install_platlib, platlibdir) + check_path(cmd.install_purelib, libdir) + check_path( + cmd.install_headers, + os.path.join(destination, "include", impl_name, "foopkg"), + ) + check_path(cmd.install_scripts, os.path.join(destination, "bin")) + check_path(cmd.install_data, destination) + + def test_user_site(self, monkeypatch): + # test install with --user + # preparing the environment for the test + self.tmpdir = self.mkdtemp() + orig_site = site.USER_SITE + orig_base = site.USER_BASE + monkeypatch.setattr(site, 'USER_BASE', os.path.join(self.tmpdir, 'B')) + monkeypatch.setattr(site, 'USER_SITE', os.path.join(self.tmpdir, 'S')) + monkeypatch.setattr(install_module, 'USER_BASE', site.USER_BASE) + monkeypatch.setattr(install_module, 'USER_SITE', site.USER_SITE) + + def _expanduser(path): + if path.startswith('~'): + return os.path.normpath(self.tmpdir + path[1:]) + return path + + monkeypatch.setattr(os.path, 'expanduser', _expanduser) + + for key in ('nt_user', 'posix_user'): + assert key in INSTALL_SCHEMES + + dist = Distribution({'name': 'xx'}) + cmd = install(dist) + + # making sure the user option is there + options = [name for name, short, label in cmd.user_options] + assert 'user' in options + + # setting a value + cmd.user = True + + # user base and site shouldn't be created yet + assert not os.path.exists(site.USER_BASE) + assert not os.path.exists(site.USER_SITE) + + # let's run finalize + cmd.ensure_finalized() + + # now they should + assert os.path.exists(site.USER_BASE) + assert os.path.exists(site.USER_SITE) + + assert 'userbase' in cmd.config_vars + assert 'usersite' in cmd.config_vars + + actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE) + if os.name == 'nt' and not is_mingw(): + site_path = os.path.relpath(os.path.dirname(orig_site), orig_base) + include = os.path.join(site_path, 'Include') + else: + include = sysconfig.get_python_inc(0, '') + expect_headers = os.path.join(include, 'xx') + + assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers) + + def test_handle_extra_path(self): + dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) + cmd = install(dist) + + # two elements + cmd.handle_extra_path() + assert cmd.extra_path == ['path', 'dirs'] + assert cmd.extra_dirs == 'dirs' + assert cmd.path_file == 'path' + + # one element + cmd.extra_path = ['path'] + cmd.handle_extra_path() + assert cmd.extra_path == ['path'] + assert cmd.extra_dirs == 'path' + assert cmd.path_file == 'path' + + # none + dist.extra_path = cmd.extra_path = None + cmd.handle_extra_path() + assert cmd.extra_path is None + assert cmd.extra_dirs == '' + assert cmd.path_file is None + + # three elements (no way !) + cmd.extra_path = 'path,dirs,again' + with pytest.raises(DistutilsOptionError): + cmd.handle_extra_path() + + def test_finalize_options(self): + dist = Distribution({'name': 'xx'}) + cmd = install(dist) + + # must supply either prefix/exec-prefix/home or + # install-base/install-platbase -- not both + cmd.prefix = 'prefix' + cmd.install_base = 'base' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + # must supply either home or prefix/exec-prefix -- not both + cmd.install_base = None + cmd.home = 'home' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + # can't combine user with prefix/exec_prefix/home or + # install_(plat)base + cmd.prefix = None + cmd.user = 'user' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + def test_record(self): + install_dir = self.mkdtemp() + project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi']) + os.chdir(project_dir) + self.write_file('hello.py', "def main(): print('o hai')") + self.write_file('sayhi', 'from hello import main; main()') + + cmd = install(dist) + dist.command_obj['install'] = cmd + cmd.root = install_dir + cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + + content = pathlib.Path(cmd.record).read_text(encoding='utf-8') + + found = [pathlib.Path(line).name for line in content.splitlines()] + expected = [ + 'hello.py', + f'hello.{sys.implementation.cache_tag}.pyc', + 'sayhi', + 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]), + ] + assert found == expected + + def test_record_extensions(self): + cmd = missing_compiler_executable() + if cmd is not None: + pytest.skip(f'The {cmd!r} command is not found') + install_dir = self.mkdtemp() + project_dir, dist = self.create_dist( + ext_modules=[Extension('xx', ['xxmodule.c'])] + ) + os.chdir(project_dir) + support.copy_xxmodule_c(project_dir) + + buildextcmd = build_ext(dist) + support.fixup_build_ext(buildextcmd) + buildextcmd.ensure_finalized() + + cmd = install(dist) + dist.command_obj['install'] = cmd + dist.command_obj['build_ext'] = buildextcmd + cmd.root = install_dir + cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + + content = pathlib.Path(cmd.record).read_text(encoding='utf-8') + + found = [pathlib.Path(line).name for line in content.splitlines()] + expected = [ + _make_ext_name('xx'), + 'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]), + ] + assert found == expected + + def test_debug_mode(self, caplog, monkeypatch): + # this covers the code called when DEBUG is set + monkeypatch.setattr(install_module, 'DEBUG', True) + caplog.set_level(logging.DEBUG) + self.test_record() + assert any(rec for rec in caplog.records if rec.levelno == logging.DEBUG) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_lib.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f685a579560ea70bceea221de0e54485975ce180 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_lib.py @@ -0,0 +1,110 @@ +"""Tests for distutils.command.install_data.""" + +import importlib.util +import os +import sys +from distutils.command.install_lib import install_lib +from distutils.errors import DistutilsOptionError +from distutils.extension import Extension +from distutils.tests import support + +import pytest + + +@support.combine_markers +@pytest.mark.usefixtures('save_env') +class TestInstallLib( + support.TempdirManager, +): + def test_finalize_options(self): + dist = self.create_dist()[1] + cmd = install_lib(dist) + + cmd.finalize_options() + assert cmd.compile == 1 + assert cmd.optimize == 0 + + # optimize must be 0, 1, or 2 + cmd.optimize = 'foo' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + cmd.optimize = '4' + with pytest.raises(DistutilsOptionError): + cmd.finalize_options() + + cmd.optimize = '2' + cmd.finalize_options() + assert cmd.optimize == 2 + + @pytest.mark.skipif('sys.dont_write_bytecode') + def test_byte_compile(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + cmd = install_lib(dist) + cmd.compile = cmd.optimize = 1 + + f = os.path.join(project_dir, 'foo.py') + self.write_file(f, '# python file') + cmd.byte_compile([f]) + pyc_file = importlib.util.cache_from_source('foo.py', optimization='') + pyc_opt_file = importlib.util.cache_from_source( + 'foo.py', optimization=cmd.optimize + ) + assert os.path.exists(pyc_file) + assert os.path.exists(pyc_opt_file) + + def test_get_outputs(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') + self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] + cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + + # get_outputs should return 4 elements: spam/__init__.py and .pyc, + # foo.import-tag-abiflags.so / foo.pyd + outputs = cmd.get_outputs() + assert len(outputs) == 4, outputs + + def test_get_inputs(self): + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') + self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] + cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + + # get_inputs should return 2 elements: spam/__init__.py and + # foo.import-tag-abiflags.so / foo.pyd + inputs = cmd.get_inputs() + assert len(inputs) == 2, inputs + + def test_dont_write_bytecode(self, caplog): + # makes sure byte_compile is not used + dist = self.create_dist()[1] + cmd = install_lib(dist) + cmd.compile = True + cmd.optimize = 1 + + old_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + cmd.byte_compile([]) + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + + assert 'byte-compiling is disabled' in caplog.messages[0] diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_msvccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_msvccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb15d3a63aa915c33c3a5c1ebeab67ece5a8e7f --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_msvccompiler.py @@ -0,0 +1,137 @@ +"""Tests for distutils._msvccompiler.""" + +import os +import sys +import sysconfig +import threading +import unittest.mock as mock +from distutils import _msvccompiler +from distutils.errors import DistutilsPlatformError +from distutils.tests import support +from distutils.util import get_platform + +import pytest + +needs_winreg = pytest.mark.skipif('not hasattr(_msvccompiler, "winreg")') + + +class Testmsvccompiler(support.TempdirManager): + def test_no_compiler(self, monkeypatch): + # makes sure query_vcvarsall raises + # a DistutilsPlatformError if the compiler + # is not found + def _find_vcvarsall(plat_spec): + return None, None + + monkeypatch.setattr(_msvccompiler, '_find_vcvarsall', _find_vcvarsall) + + with pytest.raises(DistutilsPlatformError): + _msvccompiler._get_vc_env( + 'wont find this version', + ) + + @pytest.mark.skipif( + not sysconfig.get_platform().startswith("win"), + reason="Only run test for non-mingw Windows platforms", + ) + @pytest.mark.parametrize( + "plat_name, expected", + [ + ("win-arm64", "win-arm64"), + ("win-amd64", "win-amd64"), + (None, get_platform()), + ], + ) + def test_cross_platform_compilation_paths(self, monkeypatch, plat_name, expected): + """ + Ensure a specified target platform is passed to _get_vcvars_spec. + """ + compiler = _msvccompiler.MSVCCompiler() + + def _get_vcvars_spec(host_platform, platform): + assert platform == expected + + monkeypatch.setattr(_msvccompiler, '_get_vcvars_spec', _get_vcvars_spec) + compiler.initialize(plat_name) + + @needs_winreg + def test_get_vc_env_unicode(self): + test_var = 'ṰḖṤṪ┅ṼẨṜ' + test_value = '₃⁴₅' + + # Ensure we don't early exit from _get_vc_env + old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None) + os.environ[test_var] = test_value + try: + env = _msvccompiler._get_vc_env('x86') + assert test_var.lower() in env + assert test_value == env[test_var.lower()] + finally: + os.environ.pop(test_var) + if old_distutils_use_sdk: + os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk + + @needs_winreg + @pytest.mark.parametrize('ver', (2015, 2017)) + def test_get_vc(self, ver): + # This function cannot be mocked, so pass if VC is found + # and skip otherwise. + lookup = getattr(_msvccompiler, f'_find_vc{ver}') + expected_version = {2015: 14, 2017: 15}[ver] + version, path = lookup() + if not version: + pytest.skip(f"VS {ver} is not installed") + assert version >= expected_version + assert os.path.isdir(path) + + +class CheckThread(threading.Thread): + exc_info = None + + def run(self): + try: + super().run() + except Exception: + self.exc_info = sys.exc_info() + + def __bool__(self): + return not self.exc_info + + +class TestSpawn: + def test_concurrent_safe(self): + """ + Concurrent calls to spawn should have consistent results. + """ + compiler = _msvccompiler.MSVCCompiler() + compiler._paths = "expected" + inner_cmd = 'import os; assert os.environ["PATH"] == "expected"' + command = [sys.executable, '-c', inner_cmd] + + threads = [ + CheckThread(target=compiler.spawn, args=[command]) for n in range(100) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert all(threads) + + def test_concurrent_safe_fallback(self): + """ + If CCompiler.spawn has been monkey-patched without support + for an env, it should still execute. + """ + from distutils import ccompiler + + compiler = _msvccompiler.MSVCCompiler() + compiler._paths = "expected" + + def CCompiler_spawn(self, cmd): + "A spawn without an env argument." + assert os.environ["PATH"] == "expected" + + with mock.patch.object(ccompiler.CCompiler, 'spawn', CCompiler_spawn): + compiler.spawn(["n/a"]) + + assert os.environ.get("PATH") != "expected" diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_text_file.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..f51115656135cd3f348a45d4a14f97eeee47fb98 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/tests/test_text_file.py @@ -0,0 +1,127 @@ +"""Tests for distutils.text_file.""" + +from distutils.tests import support +from distutils.text_file import TextFile + +import jaraco.path +import path + +TEST_DATA = """# test file + +line 3 \\ +# intervening comment + continues on next line +""" + + +class TestTextFile(support.TempdirManager): + def test_class(self): + # old tests moved from text_file.__main__ + # so they are really called by the buildbots + + # result 1: no fancy options + result1 = [ + '# test file\n', + '\n', + 'line 3 \\\n', + '# intervening comment\n', + ' continues on next line\n', + ] + + # result 2: just strip comments + result2 = ["\n", "line 3 \\\n", " continues on next line\n"] + + # result 3: just strip blank lines + result3 = [ + "# test file\n", + "line 3 \\\n", + "# intervening comment\n", + " continues on next line\n", + ] + + # result 4: default, strip comments, blank lines, + # and trailing whitespace + result4 = ["line 3 \\", " continues on next line"] + + # result 5: strip comments and blanks, plus join lines (but don't + # "collapse" joined lines + result5 = ["line 3 continues on next line"] + + # result 6: strip comments and blanks, plus join lines (and + # "collapse" joined lines + result6 = ["line 3 continues on next line"] + + def test_input(count, description, file, expected_result): + result = file.readlines() + assert result == expected_result + + tmp_path = path.Path(self.mkdtemp()) + filename = tmp_path / 'test.txt' + jaraco.path.build({filename.name: TEST_DATA}, tmp_path) + + in_file = TextFile( + filename, + strip_comments=False, + skip_blanks=False, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(1, "no processing", in_file, result1) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=False, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(2, "strip comments", in_file, result2) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=False, + skip_blanks=True, + lstrip_ws=False, + rstrip_ws=False, + ) + try: + test_input(3, "strip blanks", in_file, result3) + finally: + in_file.close() + + in_file = TextFile(filename) + try: + test_input(4, "default processing", in_file, result4) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=True, + join_lines=True, + rstrip_ws=True, + ) + try: + test_input(5, "join lines without collapsing", in_file, result5) + finally: + in_file.close() + + in_file = TextFile( + filename, + strip_comments=True, + skip_blanks=True, + join_lines=True, + rstrip_ws=True, + collapse_join=True, + ) + try: + test_input(6, "join lines with collapsing", in_file, result6) + finally: + in_file.close() diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/unixccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/unixccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1116ae8f7f9d54831dc8a9e815c2f212686e3f --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/unixccompiler.py @@ -0,0 +1,402 @@ +"""distutils.unixccompiler + +Contains the UnixCCompiler class, a subclass of CCompiler that handles +the "typical" Unix-style command-line C compiler: + * macros defined with -Dname[=value] + * macros undefined with -Uname + * include search directories specified with -Idir + * libraries specified with -lllib + * library search directories specified with -Ldir + * compile handled by 'cc' (or similar) executable with -c option: + compiles .c to .o + * link static library handled by 'ar' command (possibly with 'ranlib') + * link shared library handled by 'cc -shared' +""" + +from __future__ import annotations + +import itertools +import os +import re +import shlex +import sys + +from . import sysconfig +from ._log import log +from ._macos_compat import compiler_fixup +from ._modified import newer +from .ccompiler import CCompiler, gen_lib_options, gen_preprocess_options +from .compat import consolidate_linker_args +from .errors import CompileError, DistutilsExecError, LibError, LinkError + +# XXX Things not currently handled: +# * optimization/debug/warning flags; we just use whatever's in Python's +# Makefile and live with it. Is this adequate? If not, we might +# have to have a bunch of subclasses GNUCCompiler, SGICCompiler, +# SunCCompiler, and I suspect down that road lies madness. +# * even if we don't know a warning flag from an optimization flag, +# we need some way for outsiders to feed preprocessor/compiler/linker +# flags in to us -- eg. a sysadmin might want to mandate certain flags +# via a site config file, or a user might want to set something for +# compiling this module distribution only via the setup.py command +# line, whatever. As long as these options come from something on the +# current system, they can be as system-dependent as they like, and we +# should just happily stuff them into the preprocessor/compiler/linker +# options and carry on. + + +def _split_env(cmd): + """ + For macOS, split command into 'env' portion (if any) + and the rest of the linker command. + + >>> _split_env(['a', 'b', 'c']) + ([], ['a', 'b', 'c']) + >>> _split_env(['/usr/bin/env', 'A=3', 'gcc']) + (['/usr/bin/env', 'A=3'], ['gcc']) + """ + pivot = 0 + if os.path.basename(cmd[0]) == "env": + pivot = 1 + while '=' in cmd[pivot]: + pivot += 1 + return cmd[:pivot], cmd[pivot:] + + +def _split_aix(cmd): + """ + AIX platforms prefix the compiler with the ld_so_aix + script, so split that from the linker command. + + >>> _split_aix(['a', 'b', 'c']) + ([], ['a', 'b', 'c']) + >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc']) + (['/bin/foo/ld_so_aix'], ['gcc']) + """ + pivot = os.path.basename(cmd[0]) == 'ld_so_aix' + return cmd[:pivot], cmd[pivot:] + + +def _linker_params(linker_cmd, compiler_cmd): + """ + The linker command usually begins with the compiler + command (possibly multiple elements), followed by zero or more + params for shared library building. + + If the LDSHARED env variable overrides the linker command, + however, the commands may not match. + + Return the best guess of the linker parameters by stripping + the linker command. If the compiler command does not + match the linker command, assume the linker command is + just the first element. + + >>> _linker_params('gcc foo bar'.split(), ['gcc']) + ['foo', 'bar'] + >>> _linker_params('gcc foo bar'.split(), ['other']) + ['foo', 'bar'] + >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split()) + ['foo', 'bar'] + >>> _linker_params(['gcc'], ['gcc']) + [] + """ + c_len = len(compiler_cmd) + pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1 + return linker_cmd[pivot:] + + +class UnixCCompiler(CCompiler): + compiler_type = 'unix' + + # These are used by CCompiler in two places: the constructor sets + # instance attributes 'preprocessor', 'compiler', etc. from them, and + # 'set_executable()' allows any of these to be set. The defaults here + # are pretty generic; they will probably have to be set by an outsider + # (eg. using information discovered by the sysconfig about building + # Python extensions). + executables = { + 'preprocessor': None, + 'compiler': ["cc"], + 'compiler_so': ["cc"], + 'compiler_cxx': ["c++"], + 'compiler_so_cxx': ["c++"], + 'linker_so': ["cc", "-shared"], + 'linker_so_cxx': ["c++", "-shared"], + 'linker_exe': ["cc"], + 'linker_exe_cxx': ["c++", "-shared"], + 'archiver': ["ar", "-cr"], + 'ranlib': None, + } + + if sys.platform[:6] == "darwin": + executables['ranlib'] = ["ranlib"] + + # Needed for the filename generation methods provided by the base + # class, CCompiler. NB. whoever instantiates/uses a particular + # UnixCCompiler instance should set 'shared_lib_ext' -- we set a + # reasonable common default here, but it's not necessarily used on all + # Unices! + + src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"] + obj_extension = ".o" + static_lib_extension = ".a" + shared_lib_extension = ".so" + dylib_lib_extension = ".dylib" + xcode_stub_lib_extension = ".tbd" + static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" + xcode_stub_lib_format = dylib_lib_format + if sys.platform == "cygwin": + exe_extension = ".exe" + shared_lib_extension = ".dll.a" + dylib_lib_extension = ".dll" + dylib_lib_format = "cyg%s%s" + + def preprocess( + self, + source, + output_file=None, + macros=None, + include_dirs=None, + extra_preargs=None, + extra_postargs=None, + ): + fixed_args = self._fix_compile_args(None, macros, include_dirs) + ignore, macros, include_dirs = fixed_args + pp_opts = gen_preprocess_options(macros, include_dirs) + pp_args = self.preprocessor + pp_opts + if output_file: + pp_args.extend(['-o', output_file]) + if extra_preargs: + pp_args[:0] = extra_preargs + if extra_postargs: + pp_args.extend(extra_postargs) + pp_args.append(source) + + # reasons to preprocess: + # - force is indicated + # - output is directed to stdout + # - source file is newer than the target + preprocess = self.force or output_file is None or newer(source, output_file) + if not preprocess: + return + + if output_file: + self.mkpath(os.path.dirname(output_file)) + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError(msg) + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs) + compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs) + try: + if self.detect_language(src) == 'c++': + self.spawn( + compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs + ) + else: + self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) + except DistutilsExecError as msg: + raise CompileError(msg) + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + objects, output_dir = self._fix_object_args(objects, output_dir) + + output_filename = self.library_filename(output_libname, output_dir=output_dir) + + if self._need_link(objects, output_filename): + self.mkpath(os.path.dirname(output_filename)) + self.spawn(self.archiver + [output_filename] + objects + self.objects) + + # Not many Unices required ranlib anymore -- SunOS 4.x is, I + # think the only major Unix that does. Maybe we need some + # platform intelligence here to skip ranlib if it's not + # needed -- or maybe Python's configure script took care of + # it for us, hence the check for leading colon. + if self.ranlib: + try: + self.spawn(self.ranlib + [output_filename]) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + objects, output_dir = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) + if not isinstance(output_dir, (str, type(None))): + raise TypeError("'output_dir' must be a string or None") + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + ld_args = objects + self.objects + lib_opts + ['-o', output_filename] + if debug: + ld_args[:0] = ['-g'] + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + self.mkpath(os.path.dirname(output_filename)) + try: + # Select a linker based on context: linker_exe when + # building an executable or linker_so (with shared options) + # when building a shared library. + building_exe = target_desc == CCompiler.EXECUTABLE + linker = ( + self.linker_exe + if building_exe + else ( + self.linker_so_cxx if target_lang == "c++" else self.linker_so + ) + )[:] + + if target_lang == "c++" and self.compiler_cxx: + env, linker_ne = _split_env(linker) + aix, linker_na = _split_aix(linker_ne) + _, compiler_cxx_ne = _split_env(self.compiler_cxx) + _, linker_exe_ne = _split_env(self.linker_exe) + + params = _linker_params(linker_na, linker_exe_ne) + linker = env + aix + compiler_cxx_ne + params + + linker = compiler_fixup(linker, ld_args) + + self.spawn(linker + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "-L" + dir + + def _is_gcc(self): + cc_var = sysconfig.get_config_var("CC") + compiler = os.path.basename(shlex.split(cc_var)[0]) + return "gcc" in compiler or "g++" in compiler + + def runtime_library_dir_option(self, dir: str) -> str | list[str]: + # XXX Hackish, at the very least. See Python bug #445902: + # https://bugs.python.org/issue445902 + # Linkers on different platforms need different options to + # specify that directories need to be added to the list of + # directories searched for dependencies when a dynamic library + # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to + # be told to pass the -R option through to the linker, whereas + # other compilers and gcc on other systems just know this. + # Other compilers may need something slightly different. At + # this time, there's no way to determine this information from + # the configuration data stored in the Python installation, so + # we use this hack. + if sys.platform[:6] == "darwin": + from distutils.util import get_macosx_target_ver, split_version + + macosx_target_ver = get_macosx_target_ver() + if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]: + return "-Wl,-rpath," + dir + else: # no support for -rpath on earlier macOS versions + return "-L" + dir + elif sys.platform[:7] == "freebsd": + return "-Wl,-rpath=" + dir + elif sys.platform[:5] == "hp-ux": + return [ + "-Wl,+s" if self._is_gcc() else "+s", + "-L" + dir, + ] + + # For all compilers, `-Wl` is the presumed way to pass a + # compiler option to the linker + if sysconfig.get_config_var("GNULD") == "yes": + return consolidate_linker_args([ + # Force RUNPATH instead of RPATH + "-Wl,--enable-new-dtags", + "-Wl,-rpath," + dir, + ]) + else: + return "-Wl,-R" + dir + + def library_option(self, lib): + return "-l" + lib + + @staticmethod + def _library_root(dir): + """ + macOS users can specify an alternate SDK using'-isysroot'. + Calculate the SDK root if it is specified. + + Note that, as of Xcode 7, Apple SDKs may contain textual stub + libraries with .tbd extensions rather than the normal .dylib + shared libraries installed in /. The Apple compiler tool + chain handles this transparently but it can cause problems + for programs that are being built with an SDK and searching + for specific libraries. Callers of find_library_file need to + keep in mind that the base filename of the returned SDK library + file might have a different extension from that of the library + file installed on the running system, for example: + /Applications/Xcode.app/Contents/Developer/Platforms/ + MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/ + usr/lib/libedit.tbd + vs + /usr/lib/libedit.dylib + """ + cflags = sysconfig.get_config_var('CFLAGS') + match = re.search(r'-isysroot\s*(\S+)', cflags) + + apply_root = ( + sys.platform == 'darwin' + and match + and ( + dir.startswith('/System/') + or (dir.startswith('/usr/') and not dir.startswith('/usr/local/')) + ) + ) + + return os.path.join(match.group(1), dir[1:]) if apply_root else dir + + def find_library_file(self, dirs, lib, debug=False): + """ + Second-guess the linker with not much hard + data to go on: GCC seems to prefer the shared library, so + assume that *all* Unix C compilers do, + ignoring even GCC's "-static" option. + """ + lib_names = ( + self.library_filename(lib, lib_type=type) + for type in 'dylib xcode_stub shared static'.split() + ) + + roots = map(self._library_root, dirs) + + searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names)) + + found = filter(os.path.exists, searched) + + # Return None if it could not be found in any dir. + return next(found, None) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/util.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/util.py new file mode 100644 index 0000000000000000000000000000000000000000..83ad39e958de67e323b4f92406be623f4aa2da8b --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/util.py @@ -0,0 +1,502 @@ +"""distutils.util + +Miscellaneous utility functions -- anything that doesn't fit into +one of the other *util.py modules. +""" + +from __future__ import annotations + +import functools +import importlib.util +import os +import pathlib +import re +import string +import subprocess +import sys +import sysconfig +import tempfile + +from jaraco.functools import pass_none + +from ._log import log +from ._modified import newer +from .errors import DistutilsByteCompileError, DistutilsPlatformError +from .spawn import spawn + + +def get_host_platform() -> str: + """ + Return a string that identifies the current platform. Use this + function to distinguish platform-specific build directories and + platform-specific built distributions. + """ + + # This function initially exposed platforms as defined in Python 3.9 + # even with older Python versions when distutils was split out. + # Now it delegates to stdlib sysconfig. + + return sysconfig.get_platform() + + +def get_platform(): + if os.name == 'nt': + TARGET_TO_PLAT = { + 'x86': 'win32', + 'x64': 'win-amd64', + 'arm': 'win-arm32', + 'arm64': 'win-arm64', + } + target = os.environ.get('VSCMD_ARG_TGT_ARCH') + return TARGET_TO_PLAT.get(target) or get_host_platform() + return get_host_platform() + + +if sys.platform == 'darwin': + _syscfg_macosx_ver = None # cache the version pulled from sysconfig +MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET' + + +def _clear_cached_macosx_ver(): + """For testing only. Do not call.""" + global _syscfg_macosx_ver + _syscfg_macosx_ver = None + + +def get_macosx_target_ver_from_syscfg(): + """Get the version of macOS latched in the Python interpreter configuration. + Returns the version as a string or None if can't obtain one. Cached.""" + global _syscfg_macosx_ver + if _syscfg_macosx_ver is None: + from distutils import sysconfig + + ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or '' + if ver: + _syscfg_macosx_ver = ver + return _syscfg_macosx_ver + + +def get_macosx_target_ver(): + """Return the version of macOS for which we are building. + + The target version defaults to the version in sysconfig latched at time + the Python interpreter was built, unless overridden by an environment + variable. If neither source has a value, then None is returned""" + + syscfg_ver = get_macosx_target_ver_from_syscfg() + env_ver = os.environ.get(MACOSX_VERSION_VAR) + + if env_ver: + # Validate overridden version against sysconfig version, if have both. + # Ensure that the deployment target of the build process is not less + # than 10.3 if the interpreter was built for 10.3 or later. This + # ensures extension modules are built with correct compatibility + # values, specifically LDSHARED which can use + # '-undefined dynamic_lookup' which only works on >= 10.3. + if ( + syscfg_ver + and split_version(syscfg_ver) >= [10, 3] + and split_version(env_ver) < [10, 3] + ): + my_msg = ( + '$' + MACOSX_VERSION_VAR + ' mismatch: ' + f'now "{env_ver}" but "{syscfg_ver}" during configure; ' + 'must use 10.3 or later' + ) + raise DistutilsPlatformError(my_msg) + return env_ver + return syscfg_ver + + +def split_version(s): + """Convert a dot-separated string into a list of numbers for comparisons""" + return [int(n) for n in s.split('.')] + + +@pass_none +def convert_path(pathname: str | os.PathLike) -> str: + r""" + Allow for pathlib.Path inputs, coax to a native path string. + + If None is passed, will just pass it through as + Setuptools relies on this behavior. + + >>> convert_path(None) is None + True + + Removes empty paths. + + >>> convert_path('foo/./bar').replace('\\', '/') + 'foo/bar' + """ + return os.fspath(pathlib.PurePath(pathname)) + + +def change_root(new_root, pathname): + """Return 'pathname' with 'new_root' prepended. If 'pathname' is + relative, this is equivalent to "os.path.join(new_root,pathname)". + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + """ + if os.name == 'posix': + if not os.path.isabs(pathname): + return os.path.join(new_root, pathname) + else: + return os.path.join(new_root, pathname[1:]) + + elif os.name == 'nt': + (drive, path) = os.path.splitdrive(pathname) + if path[0] == os.sep: + path = path[1:] + return os.path.join(new_root, path) + + raise DistutilsPlatformError(f"nothing known about platform '{os.name}'") + + +@functools.lru_cache +def check_environ(): + """Ensure that 'os.environ' has all the environment variables we + guarantee that users can use in config files, command-line options, + etc. Currently this includes: + HOME - user's home directory (Unix only) + PLAT - description of the current platform, including hardware + and OS (see 'get_platform()') + """ + if os.name == 'posix' and 'HOME' not in os.environ: + try: + import pwd + + os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] + except (ImportError, KeyError): + # bpo-10496: if the current user identifier doesn't exist in the + # password database, do nothing + pass + + if 'PLAT' not in os.environ: + os.environ['PLAT'] = get_platform() + + +def subst_vars(s, local_vars): + """ + Perform variable substitution on 'string'. + Variables are indicated by format-style braces ("{var}"). + Variable is substituted by the value found in the 'local_vars' + dictionary or in 'os.environ' if it's not in 'local_vars'. + 'os.environ' is first checked/augmented to guarantee that it contains + certain values: see 'check_environ()'. Raise ValueError for any + variables not found in either 'local_vars' or 'os.environ'. + """ + check_environ() + lookup = dict(os.environ) + lookup.update((name, str(value)) for name, value in local_vars.items()) + try: + return _subst_compat(s).format_map(lookup) + except KeyError as var: + raise ValueError(f"invalid variable {var}") + + +def _subst_compat(s): + """ + Replace shell/Perl-style variable substitution with + format-style. For compatibility. + """ + + def _subst(match): + return f'{{{match.group(1)}}}' + + repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) + if repl != s: + import warnings + + warnings.warn( + "shell/Perl-style substitutions are deprecated", + DeprecationWarning, + ) + return repl + + +def grok_environment_error(exc, prefix="error: "): + # Function kept for backward compatibility. + # Used to try clever things with EnvironmentErrors, + # but nowadays str(exception) produces good messages. + return prefix + str(exc) + + +# Needed by 'split_quoted()' +_wordchars_re = _squote_re = _dquote_re = None + + +def _init_regex(): + global _wordchars_re, _squote_re, _dquote_re + _wordchars_re = re.compile(rf'[^\\\'\"{string.whitespace} ]*') + _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'") + _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"') + + +def split_quoted(s): + """Split a string up according to Unix shell-like rules for quotes and + backslashes. In short: words are delimited by spaces, as long as those + spaces are not escaped by a backslash, or inside a quoted string. + Single and double quotes are equivalent, and the quote characters can + be backslash-escaped. The backslash is stripped from any two-character + escape sequence, leaving only the escaped character. The quote + characters are stripped from any quoted string. Returns a list of + words. + """ + + # This is a nice algorithm for splitting up a single string, since it + # doesn't require character-by-character examination. It was a little + # bit of a brain-bender to get it working right, though... + if _wordchars_re is None: + _init_regex() + + s = s.strip() + words = [] + pos = 0 + + while s: + m = _wordchars_re.match(s, pos) + end = m.end() + if end == len(s): + words.append(s[:end]) + break + + if s[end] in string.whitespace: + # unescaped, unquoted whitespace: now + # we definitely have a word delimiter + words.append(s[:end]) + s = s[end:].lstrip() + pos = 0 + + elif s[end] == '\\': + # preserve whatever is being escaped; + # will become part of the current word + s = s[:end] + s[end + 1 :] + pos = end + 1 + + else: + if s[end] == "'": # slurp singly-quoted string + m = _squote_re.match(s, end) + elif s[end] == '"': # slurp doubly-quoted string + m = _dquote_re.match(s, end) + else: + raise RuntimeError(f"this can't happen (bad char '{s[end]}')") + + if m is None: + raise ValueError(f"bad string (mismatched {s[end]} quotes?)") + + (beg, end) = m.span() + s = s[:beg] + s[beg + 1 : end - 1] + s[end:] + pos = m.end() - 2 + + if pos >= len(s): + words.append(s) + break + + return words + + +# split_quoted () + + +def execute(func, args, msg=None, verbose=False, dry_run=False): + """Perform some action that affects the outside world (eg. by + writing to the filesystem). Such actions are special because they + are disabled by the 'dry_run' flag. This method takes care of all + that bureaucracy for you; all you have to do is supply the + function to call and an argument tuple for it (to embody the + "external action" being performed), and an optional message to + print. + """ + if msg is None: + msg = f"{func.__name__}{args!r}" + if msg[-2:] == ',)': # correct for singleton tuple + msg = msg[0:-2] + ')' + + log.info(msg) + if not dry_run: + func(*args) + + +def strtobool(val): + """Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + """ + val = val.lower() + if val in ('y', 'yes', 't', 'true', 'on', '1'): + return 1 + elif val in ('n', 'no', 'f', 'false', 'off', '0'): + return 0 + else: + raise ValueError(f"invalid truth value {val!r}") + + +def byte_compile( # noqa: C901 + py_files, + optimize=0, + force=False, + prefix=None, + base_dir=None, + verbose=True, + dry_run=False, + direct=None, +): + """Byte-compile a collection of Python source files to .pyc + files in a __pycache__ subdirectory. 'py_files' is a list + of files to compile; any files that don't end in ".py" are silently + skipped. 'optimize' must be one of the following: + 0 - don't optimize + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") + If 'force' is true, all files are recompiled regardless of + timestamps. + + The source filename encoded in each bytecode file defaults to the + filenames listed in 'py_files'; you can modify these with 'prefix' and + 'basedir'. 'prefix' is a string that will be stripped off of each + source filename, and 'base_dir' is a directory name that will be + prepended (after 'prefix' is stripped). You can supply either or both + (or neither) of 'prefix' and 'base_dir', as you wish. + + If 'dry_run' is true, doesn't actually do anything that would + affect the filesystem. + + Byte-compilation is either done directly in this interpreter process + with the standard py_compile module, or indirectly by writing a + temporary script and executing it. Normally, you should let + 'byte_compile()' figure out to use direct compilation or not (see + the source for details). The 'direct' flag is used by the script + generated in indirect mode; unless you know what you're doing, leave + it set to None. + """ + + # nothing is done if sys.dont_write_bytecode is True + if sys.dont_write_bytecode: + raise DistutilsByteCompileError('byte-compiling is disabled.') + + # First, if the caller didn't force us into direct or indirect mode, + # figure out which mode we should be in. We take a conservative + # approach: choose direct mode *only* if the current interpreter is + # in debug mode and optimize is 0. If we're not in debug mode (-O + # or -OO), we don't know which level of optimization this + # interpreter is running with, so we can't do direct + # byte-compilation and be certain that it's the right thing. Thus, + # always compile indirectly if the current interpreter is in either + # optimize mode, or if either optimization level was requested by + # the caller. + if direct is None: + direct = __debug__ and optimize == 0 + + # "Indirect" byte-compilation: write a temporary script and then + # run it with the appropriate flags. + if not direct: + (script_fd, script_name) = tempfile.mkstemp(".py") + log.info("writing byte-compilation script '%s'", script_name) + if not dry_run: + script = os.fdopen(script_fd, "w", encoding='utf-8') + + with script: + script.write( + """\ +from distutils.util import byte_compile +files = [ +""" + ) + + # XXX would be nice to write absolute filenames, just for + # safety's sake (script should be more robust in the face of + # chdir'ing before running it). But this requires abspath'ing + # 'prefix' as well, and that breaks the hack in build_lib's + # 'byte_compile()' method that carefully tacks on a trailing + # slash (os.sep really) to make sure the prefix here is "just + # right". This whole prefix business is rather delicate -- the + # problem is that it's really a directory, but I'm treating it + # as a dumb string, so trailing slashes and so forth matter. + + script.write(",\n".join(map(repr, py_files)) + "]\n") + script.write( + f""" +byte_compile(files, optimize={optimize!r}, force={force!r}, + prefix={prefix!r}, base_dir={base_dir!r}, + verbose={verbose!r}, dry_run=False, + direct=True) +""" + ) + + cmd = [sys.executable] + cmd.extend(subprocess._optim_args_from_interpreter_flags()) + cmd.append(script_name) + spawn(cmd, dry_run=dry_run) + execute(os.remove, (script_name,), f"removing {script_name}", dry_run=dry_run) + + # "Direct" byte-compilation: use the py_compile module to compile + # right here, right now. Note that the script generated in indirect + # mode simply calls 'byte_compile()' in direct mode, a weird sort of + # cross-process recursion. Hey, it works! + else: + from py_compile import compile + + for file in py_files: + if file[-3:] != ".py": + # This lets us be lazy and not filter filenames in + # the "install_lib" command. + continue + + # Terminology from the py_compile module: + # cfile - byte-compiled file + # dfile - purported source filename (same as 'file' by default) + if optimize >= 0: + opt = '' if optimize == 0 else optimize + cfile = importlib.util.cache_from_source(file, optimization=opt) + else: + cfile = importlib.util.cache_from_source(file) + dfile = file + if prefix: + if file[: len(prefix)] != prefix: + raise ValueError( + f"invalid prefix: filename {file!r} doesn't start with {prefix!r}" + ) + dfile = dfile[len(prefix) :] + if base_dir: + dfile = os.path.join(base_dir, dfile) + + cfile_base = os.path.basename(cfile) + if direct: + if force or newer(file, cfile): + log.info("byte-compiling %s to %s", file, cfile_base) + if not dry_run: + compile(file, cfile, dfile) + else: + log.debug("skipping byte-compilation of %s to %s", file, cfile_base) + + +def rfc822_escape(header): + """Return a version of the string escaped for inclusion in an + RFC-822 header, by ensuring there are 8 spaces space after each newline. + """ + indent = 8 * " " + lines = header.splitlines(keepends=True) + + # Emulate the behaviour of `str.split` + # (the terminal line break in `splitlines` does not result in an extra line): + ends_in_newline = lines and lines[-1].splitlines()[0] != lines[-1] + suffix = indent if ends_in_newline else "" + + return indent.join(lines) + suffix + + +def is_mingw(): + """Returns True if the current platform is mingw. + + Python compiled with Mingw-w64 has sys.platform == 'win32' and + get_platform() starts with 'mingw'. + """ + return sys.platform == 'win32' and get_platform().startswith('mingw') + + +def is_freethreaded(): + """Return True if the Python interpreter is built with free threading support.""" + return bool(sysconfig.get_config_var('Py_GIL_DISABLED')) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/zosccompiler.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/zosccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..af1e7fa5cced7b7ac2f29f3d50c10abaeb111dc0 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/_distutils/zosccompiler.py @@ -0,0 +1,229 @@ +"""distutils.zosccompiler + +Contains the selection of the c & c++ compilers on z/OS. There are several +different c compilers on z/OS, all of them are optional, so the correct +one needs to be chosen based on the users input. This is compatible with +the following compilers: + +IBM C/C++ For Open Enterprise Languages on z/OS 2.0 +IBM Open XL C/C++ 1.1 for z/OS +IBM XL C/C++ V2.4.1 for z/OS 2.4 and 2.5 +IBM z/OS XL C/C++ +""" + +import os + +from . import sysconfig +from .errors import CompileError, DistutilsExecError +from .unixccompiler import UnixCCompiler + +_cc_args = { + 'ibm-openxl': [ + '-m64', + '-fvisibility=default', + '-fzos-le-char-mode=ascii', + '-fno-short-enums', + ], + 'ibm-xlclang': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + ], + 'ibm-xlc': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + '-qlanglvl=extc99', + ], +} + +_cxx_args = { + 'ibm-openxl': [ + '-m64', + '-fvisibility=default', + '-fzos-le-char-mode=ascii', + '-fno-short-enums', + ], + 'ibm-xlclang': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + ], + 'ibm-xlc': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + '-qlanglvl=extended0x', + ], +} + +_asm_args = { + 'ibm-openxl': ['-fasm', '-fno-integrated-as', '-Wa,--ASA', '-Wa,--GOFF'], + 'ibm-xlclang': [], + 'ibm-xlc': [], +} + +_ld_args = { + 'ibm-openxl': [], + 'ibm-xlclang': ['-Wl,dll', '-q64'], + 'ibm-xlc': ['-Wl,dll', '-q64'], +} + + +# Python on z/OS is built with no compiler specific options in it's CFLAGS. +# But each compiler requires it's own specific options to build successfully, +# though some of the options are common between them +class zOSCCompiler(UnixCCompiler): + src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s'] + _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C'] + _asm_extensions = ['.s'] + + def _get_zos_compiler_name(self): + zos_compiler_names = [ + os.path.basename(binary) + for envvar in ('CC', 'CXX', 'LDSHARED') + if (binary := os.environ.get(envvar, None)) + ] + if len(zos_compiler_names) == 0: + return 'ibm-openxl' + + zos_compilers = {} + for compiler in ( + 'ibm-clang', + 'ibm-clang64', + 'ibm-clang++', + 'ibm-clang++64', + 'clang', + 'clang++', + 'clang-14', + ): + zos_compilers[compiler] = 'ibm-openxl' + + for compiler in ('xlclang', 'xlclang++', 'njsc', 'njsc++'): + zos_compilers[compiler] = 'ibm-xlclang' + + for compiler in ('xlc', 'xlC', 'xlc++'): + zos_compilers[compiler] = 'ibm-xlc' + + return zos_compilers.get(zos_compiler_names[0], 'ibm-openxl') + + def __init__(self, verbose=False, dry_run=False, force=False): + super().__init__(verbose, dry_run, force) + self.zos_compiler = self._get_zos_compiler_name() + sysconfig.customize_compiler(self) + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + local_args = [] + if ext in self._cpp_extensions: + compiler = self.compiler_cxx + local_args.extend(_cxx_args[self.zos_compiler]) + elif ext in self._asm_extensions: + compiler = self.compiler_so + local_args.extend(_cc_args[self.zos_compiler]) + local_args.extend(_asm_args[self.zos_compiler]) + else: + compiler = self.compiler_so + local_args.extend(_cc_args[self.zos_compiler]) + local_args.extend(cc_args) + + try: + self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs) + except DistutilsExecError as msg: + raise CompileError(msg) + + def runtime_library_dir_option(self, dir): + return '-L' + dir + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + # For a built module to use functions from cpython, it needs to use Pythons + # side deck file. The side deck is located beside the libpython3.xx.so + ldversion = sysconfig.get_config_var('LDVERSION') + if sysconfig.python_build: + side_deck_path = os.path.join( + sysconfig.get_config_var('abs_builddir'), + f'libpython{ldversion}.x', + ) + else: + side_deck_path = os.path.join( + sysconfig.get_config_var('installed_base'), + sysconfig.get_config_var('platlibdir'), + f'libpython{ldversion}.x', + ) + + if os.path.exists(side_deck_path): + if extra_postargs: + extra_postargs.append(side_deck_path) + else: + extra_postargs = [side_deck_path] + + # Check and replace libraries included side deck files + if runtime_library_dirs: + for dir in runtime_library_dirs: + for library in libraries[:]: + library_side_deck = os.path.join(dir, f'{library}.x') + if os.path.exists(library_side_deck): + libraries.remove(library) + extra_postargs.append(library_side_deck) + break + + # Any required ld args for the given compiler + extra_postargs.extend(_ld_args[self.zos_compiler]) + + super().link( + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/__init__.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6717d0832cdaa2095b4012c18f33f1ef49276068 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/contexts.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/contexts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a60f113220f7e7e41533e3d2f3944a9e960237e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/contexts.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/environment.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/environment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735dde527dab1068b5ad716fa9f8d90f29e3bf7e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/environment.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/fixtures.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/fixtures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d839bf94a1c52b05dce39465502b3b07e1ac1132 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/fixtures.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd2d9f7da5206518c7a4dbebbcc2ca97c96b3aad Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/namespaces.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/namespaces.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d37ea2cd4dc15e1582e76646b606b980d6ab793e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/namespaces.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd96ef9d90dbc7f17c1581012e8f7a05c51c2c70 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e255141827a479f392c46b4deb3d80bc2fee3fa5 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..139a198ee28c32174536885220f376601ddd0e0e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab627377e25928d5e5d60ee45c14318cdc5a44f4 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a47ec177ceca9e228c1d095afaae5cc22dde29e0 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c395919797fbb7741d42cdbf7e277d4a891a7ead Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a42c2f7c315c77b1a5bc8773997132b56c49c822 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84bcfc0e9cf393c5b1526e149fff7f29cdfd8d11 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..098f13cc4a1826e9e1396ef5c3c55f0337c5c975 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e47d5ded36b06ab8b2c372b7cf64547a66146df7 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06b6b7e8ac7644444a870e730cf629ec689cabb4 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_depends.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_depends.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f947bb52a2e0fb53948cbebe711cfddcb64d30b Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_depends.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_develop.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_develop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee8f5377b97b91205fd19e250d3fa7650b8f0afd Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_develop.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c501a74829a4d36ba844753421bcdf74347cc79 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5a219146d4dd369297680ca070d3dc0bbcd2530 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64edb8fc30d522cc990e1915d51493dec5ed07bb Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0275c47483b2881c99f812a5b70e3c7138791fde Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_easy_install.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9661f5457200a1aa10a931ecb193bca42ecf0c37 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39096efe7e3ab0bec668ff8418b1180ba5f6dd3b Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_extern.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_extern.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1ce8bf0b7f4f8608fd676f7e471966942f7892e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_extern.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ca786300adacbc97ee4ee3bee7ae2483514b7a Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e01cb329b66a4feb99b2606f3f212d13260ed845 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_glob.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_glob.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5ac675578a2cedf77a88fe68976a721260504de Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_glob.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99d731c43db5aa7788a4cbf08ff79b7e51ebf9ae Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_logging.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ba35e4c3a8b07b41268436af8abf0646bd5a184 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_logging.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ec6a6d07b33f6950b565549ced5a1e886568acb Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_packageindex.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68fa3aff4f1f420167f4c129048505caabf41ac7 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sandbox.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f4fcdf2a67170730c6f418c792c518583a6c25f Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0079fb7510b602c529eaef1427d868bc0301e61 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09da3772f131c05753039148b2285de8e99a45ef Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..484c0a1517e679d2c2140f7080fb4961d9cfcb58 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fedbb9088bd051dd2059da46ad4220a5d6dc7e2d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..218109dbb94a6a464e4c518c64010b736cadffdd Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcb04ec0140353e85257ec675e2ba1a1f24600d9 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ea5050925bfae6b0d4d7b66be5d6903e5da7a5 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30f5ff5955415d5f4d1bb5363ad540ca82f8587c Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/text.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..663cb3bf63e0e70297b2c2d030857e6ae980486d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/text.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/textwrap.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/textwrap.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00cd32c054b54040ad27eaf409df001ece038d50 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/__pycache__/textwrap.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__init__.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4d68d901a074294e8d942fef21d79776ad023d1 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9838b15c054085e6b065ac6f4c81efc0d28732b8 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/py39.py b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..1fdb9dac1fa3f121a634082515d1a305fc09793c --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/setuptools/tests/compat/py39.py @@ -0,0 +1,3 @@ +from jaraco.test.cpython import from_test_support, try_import + +os_helper = try_import('os_helper') or from_test_support('can_symlink') diff --git a/mantis_evalkit/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz b/mantis_evalkit/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..06446ec67eeede9b6d48f044d8ae402fe11bb90e --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02882c6b02c4e068ef2b16f37f33ae3d5e9dd17ca29d01662c6924e16427eb5d +size 437 diff --git a/mantis_evalkit/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..141b6a347af0b494fbeff842b35edce71b755bb7 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:665776822639b8907a88433e1d058c8962eb4073e294936882c0cb5bae35be6c +size 106668