[bumpversion]
-current_version = 63.1.0
+current_version = 63.3.0
commit = True
tag = True
distutils:
- local
python:
- # Build on pre-releases until stable, then stable releases.
- # actions/setup-python#213
- - ~3.7.0-0
- - ~3.10.0-0
+ - 3.7-dev
+ - 3.10-dev
# disabled due to #3365
- # - ~3.11.0-0
+ # - 3.11-dev
- pypy-3.7
platform:
- ubuntu-latest
- name: Setup Python
uses: actions/setup-python@v3
with:
- python-version: "3.10"
+ python-version: "3.11-dev"
- name: Install tox
run: |
python -m pip install tox
+v63.3.0
+-------
+
+
+Changes
+^^^^^^^
+* #3460: <<<<<<< HEAD
+ Limit the scope of the _distutils_hack workaround for pip.
+ =======
+ Remove the pip workaround in _distutils_hack.
+ >>>>>>> 46344cf0 (Remove pip workaround in _distutils_hack.)
+* #3475: Merge with pypa/distutils@129480b, including substantial delinting and cleanup, some refactoring around compiler logic, better messaging in cygwincompiler (pypa/distutils#161).
+
+
+v63.2.0
+-------
+
+
+Changes
+^^^^^^^
+* #3395: Included a performance optimization: ``setuptools.build_meta`` no longer tries
+ to :func:`compile` the setup script code before :func:`exec`-ing it.
+
+Misc
+^^^^
+* #3435: Corrected issue in macOS framework builds on Python 3.9 not installed by homebrew (pypa/distutils#158).
+
+
v63.1.0
-------
--- /dev/null
+Merge with pypa/distutils@129480b, including substantial delinting and cleanup, some refactoring around compiler logic, better messaging in cygwincompiler (pypa/distutils#161).
.. code-block:: toml
[build-system]
- requires = ["setuptools", "wheel"]
+ requires = ["setuptools"]
build-backend = "backend"
backend-path = ["_custom_build"]
* ``setuptools`` projects without ``setup.py`` (e.g., ``setup.cfg``-only)::
- python -c "import setuptools; setup()" --help
+ python -c "from setuptools import setup; setup()" --help
* ``distutils`` projects (with a ``setup.py`` importing ``distutils``)::
[build-system]
requires = [
"setuptools >= 40.9.0",
- "wheel",
]
build-backend = "setuptools.build_meta"
mypackage
├── pyproject.toml
- | # setup.cfg or setup.py (depending on the confuguration method)
+ | # setup.cfg or setup.py (depending on the configuration method)
| # README.rst or README.md (a nice description of your package)
| # LICENCE (properly chosen license information, e.g. MIT, BSD-3, GPL-3, MPL-2, etc...)
└── mypackage
.. code-block:: ini
[options]
- packages = find: # OR `find_namespaces:` if you want to use namespaces
+ packages = find: # OR `find_namespace:` if you want to use namespaces
- [options.packages.find] # (always `find` even if `find_namespaces:` was used before)
+ [options.packages.find] # (always `find` even if `find_namespace:` was used before)
# This section is optional
# Each entry in this section is optional, and if not specified, the default values are:
# `where=.`, `include=*` and `exclude=` (empty).
[tool.pytest-enabler.cov]
addopts = "--cov"
-[pytest.enabler.xdist]
+[tool.pytest-enabler.xdist]
addopts = "-n auto"
[tool.towncrier]
[metadata]
name = setuptools
-version = 63.1.0
+version = 63.3.0
author = Python Packaging Authority
author_email = distutils-sig@python.org
description = Easily download, build, install, upgrade, and uninstall Python packages
pytest >= 6
pytest-checkdocs >= 2.4
pytest-flake8
+ # workaround for tholo/pytest-flake8#87
+ flake8 < 5
pytest-black >= 0.3.7; \
# workaround for jaraco/skeleton#22
python_implementation != "PyPy"
return list(map(make_out_path, source_filenames))
- def compile(
+ def compile( # noqa: C901
self,
sources,
output_dir=None,
return archive_name
-def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
+def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): # 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
# -- Worker methods ------------------------------------------------
- def compile(
+ def compile( # noqa: C901
self,
sources,
output_dir=None,
# create_static_lib ()
- def link(
+ def link( # noqa: C901
self,
target_desc,
objects,
else:
objects.append(file)
- for l in library_dirs:
- ld_args.append("/L%s" % os.path.normpath(l))
+ for ell in library_dirs:
+ ld_args.append("/L%s" % os.path.normpath(ell))
ld_args.append("/L.") # we sometimes use relative paths
# list of object files
Contains CCompiler, an abstract base class that defines the interface
for the Distutils compiler abstraction model."""
-import sys, os, re
-from distutils.errors import *
+import sys
+import os
+import re
+from distutils.errors import (
+ CompileError,
+ LinkError,
+ UnknownFileError,
+ DistutilsPlatformError,
+ DistutilsModuleError,
+)
from distutils.spawn import spawn
from distutils.file_util import move_file
from distutils.dir_util import mkpath
"""
raise NotImplementedError
- def has_function(
+ def has_function( # noqa: C901
self,
funcname,
includes=None,
self, libname, lib_type='static', strip_dir=0, output_dir='' # or 'shared'
):
assert output_dir is not None
- if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
- raise ValueError(
- "'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\""
- )
+ 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")
in the distutils.command package.
"""
-import sys, os, re
+import sys
+import os
+import re
from distutils.errors import DistutilsOptionError
from distutils import util, dir_util, file_util, archive_util, dep_util
from distutils import log
Package containing implementation of all the standard Distutils
commands."""
-__all__ = [
+__all__ = [ # noqa: F822
'build',
'build_py',
'build_ext',
'bdist_wininst',
'check',
'upload',
- # These two are reserved for future use:
- #'bdist_sdux',
- #'bdist_pkgtool',
- # Note:
- # bdist_packager is not included because it only provides
- # an abstract base class
]
import os
import functools
import subprocess
+import sysconfig
@functools.lru_cache()
def enabled():
"""
- Only enabled for Python 3.9 framework builds except ensurepip and venv.
+ Only enabled for Python 3.9 framework homebrew builds
+ except ensurepip and venv.
"""
PY39 = (3, 9) < sys.version_info < (3, 10)
framework = sys.platform == 'darwin' and sys._framework
+ homebrew = "Cellar" in sysconfig.get_config_var('projectbase')
venv = sys.prefix != sys.base_prefix
ensurepip = os.environ.get("ENSUREPIP_OPTIONS")
- return PY39 and framework and not venv and not ensurepip
+ return PY39 and framework and homebrew and not venv and not ensurepip
schemes = dict(
import os
from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsPlatformError, DistutilsOptionError
from distutils.util import get_platform
formats = []
for format in bdist.format_commands:
- formats.append(("formats=" + format, None, bdist.format_command[format][1]))
+ formats.append(("formats=" + format, None, bdist.format_commands[format][1]))
pretty_printer = FancyGetopt(formats)
pretty_printer.print_help("List of available distribution formats:")
+class ListCompat(dict):
+ # adapter to allow for Setuptools compatibility in format_commands
+ def append(self, item):
+ return
+
+
class bdist(Command):
description = "create a built (binary) distribution"
# Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
default_format = {'posix': 'gztar', 'nt': 'zip'}
- # Establish the preferred order (for the --help-formats option).
- format_commands = [
- 'rpm',
- 'gztar',
- 'bztar',
- 'xztar',
- 'ztar',
- 'tar',
- 'wininst',
- 'zip',
- 'msi',
- ]
-
- # And the real information.
- format_command = {
- 'rpm': ('bdist_rpm', "RPM distribution"),
- 'gztar': ('bdist_dumb', "gzip'ed tar file"),
- 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
- 'xztar': ('bdist_dumb', "xz'ed tar file"),
- 'ztar': ('bdist_dumb', "compressed tar file"),
- 'tar': ('bdist_dumb', "tar file"),
- 'wininst': ('bdist_wininst', "Windows executable installer"),
- 'zip': ('bdist_dumb', "ZIP file"),
- 'msi': ('bdist_msi', "Microsoft Installer"),
- }
+ # Define commands in preferred order for the --help-formats option
+ format_commands = ListCompat(
+ {
+ 'rpm': ('bdist_rpm', "RPM distribution"),
+ 'gztar': ('bdist_dumb', "gzip'ed tar file"),
+ 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
+ 'xztar': ('bdist_dumb', "xz'ed tar file"),
+ 'ztar': ('bdist_dumb', "compressed tar file"),
+ 'tar': ('bdist_dumb', "tar file"),
+ 'wininst': ('bdist_wininst', "Windows executable installer"),
+ 'zip': ('bdist_dumb', "ZIP file"),
+ 'msi': ('bdist_msi', "Microsoft Installer"),
+ }
+ )
+
+ # for compatibility until Setuptools references only format_commands
+ format_command = format_commands
def initialize_options(self):
self.bdist_base = None
commands = []
for format in self.formats:
try:
- commands.append(self.format_command[format][0])
+ commands.append(self.format_commands[format][0])
except KeyError:
raise DistutilsOptionError("invalid format '%s'" % format)
from distutils.core import Command
from distutils.util import get_platform
from distutils.dir_util import remove_tree, ensure_relative
-from distutils.errors import *
+from distutils.errors import DistutilsPlatformError
from distutils.sysconfig import get_python_version
from distutils import log
default, cancel, bitmap=true)"""
super().__init__(*args)
ruler = self.h - 36
- bmwidth = 152 * ruler / 328
- # if kw.get("bitmap", True):
- # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
self.line("BottomLine", 0, ruler, self.w, 0)
def title(self, title):
)
self.install_script_key = None
- def run(self):
+ def run(self): # noqa: C901
if not self.skip_build:
self.run_command('build')
if not self.keep_temp:
remove_tree(self.bdist_dir, dry_run=self.dry_run)
- def add_files(self):
+ def add_files(self): # noqa: C901
db = self.db
cab = msilib.CAB("distfiles")
rootdir = os.path.abspath(self.bdist_dir)
exe_action = "PythonExe" + ver
target_dir_prop = "TARGETDIR" + ver
exe_prop = "PYTHON" + ver
- if msilib.Win64:
- # type: msidbLocatorTypeRawValue + msidbLocatorType64bit
- Type = 2 + 16
- else:
- Type = 2
+
+ # Type: msidbLocatorTypeRawValue + msidbLocatorType64bit
+ Type = 2 + 16 * bool(msilib.Win64)
add_data(
self.db,
"RegLocator",
# see "Dialog Style Bits"
modal = 3 # visible | modal
modeless = 1 # visible
- track_disk_space = 32
# UI customization properties
add_data(
320,
80,
0x30003,
- "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.",
+ "[ProductName] setup ended prematurely because of an error. "
+ "Your system has not been modified. To install this program "
+ "at a later time, please run the installation again.",
)
fatal.text(
"Description2",
80,
0x30003,
"[ProductName] setup was interrupted. Your system has not been modified. "
- "To install this program at a later time, please run the installation again.",
+ "To install this program at a later time, please run the installation "
+ "again.",
)
user_exit.text(
"Description2",
330,
50,
3,
- "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.",
+ "The following applications are using files that need to be updated by "
+ "this "
+ "setup. Close these applications and then click Retry to continue the "
+ "installation or Cancel to exit it.",
)
inuse.control(
"List",
None,
)
error.text("ErrorText", 50, 9, 280, 48, 3, "")
- # error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
error.pushbutton("N", 120, 72, 81, 21, 3, "No", None).event(
"EndDialog", "ErrorNo"
)
194,
30,
3,
- "Please wait while the installer finishes determining your disk space requirements.",
+ "Please wait while the installer finishes determining your disk space "
+ "requirements.",
)
c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None)
c.event("EndDialog", "Exit")
320,
40,
0x30003,
- "Please wait while the Installer prepares to guide you through the installation.",
+ "Please wait while the Installer prepares to guide you through the "
+ "installation.",
)
prep.title("Welcome to the [ProductName] Installer")
c = prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...")
# Close dialog when maintenance action scheduled
c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20)
- # c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
Implements the Distutils 'bdist_rpm' command (create RPM source and binary
distributions)."""
-import subprocess, sys, os
+import subprocess
+import sys
+import os
+
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.file_util import write_file
-from distutils.errors import *
+from distutils.errors import (
+ DistutilsOptionError,
+ DistutilsPlatformError,
+ DistutilsFileError,
+ DistutilsExecError,
+)
from distutils.sysconfig import get_python_version
from distutils import log
self.ensure_string('force_arch')
- def run(self):
+ def run(self): # noqa: C901
if DEBUG:
print("before _get_package_data():")
print("vendor =", self.vendor)
line = out.readline()
if not line:
break
- l = line.strip().split()
- assert len(l) == 2
- binary_rpms.append(l[1])
+ ell = line.strip().split()
+ assert len(ell) == 2
+ binary_rpms.append(ell[1])
# The source rpm is named after the first entry in the spec file
if source_rpm is None:
- source_rpm = l[0]
+ source_rpm = ell[0]
status = out.close()
if status:
def _dist_path(self, path):
return os.path.join(self.dist_dir, os.path.basename(path))
- def _make_spec_file(self):
+ def _make_spec_file(self): # noqa: C901
"""Generate the text of an RPM spec file and return it as a
list of strings (one per line).
"""
from distutils.core import Command
from distutils.util import get_platform
from distutils.dir_util import remove_tree
-from distutils.errors import *
+from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.sysconfig import get_python_version
from distutils import log
)
return installer_name
- def get_exe_bytes(self):
+ def get_exe_bytes(self): # noqa: C901
# If a target-version other than the current version has been
# specified, then using the MSVC version from *this* build is no good.
# Without actually finding and executing the target version and parsing
Implements the Distutils 'build' command."""
-import sys, os
+import sys
+import os
from distutils.core import Command
from distutils.errors import DistutilsOptionError
from distutils.util import get_platform
self.executable = None
self.parallel = None
- def finalize_options(self):
+ def finalize_options(self): # noqa: C901
if self.plat_name is None:
self.plat_name = get_platform()
else:
import os
from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsSetupError
from distutils.sysconfig import customize_compiler
from distutils import log
import re
import sys
from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import (
+ DistutilsOptionError,
+ DistutilsSetupError,
+ CCompilerError,
+ DistutilsError,
+ CompileError,
+ DistutilsPlatformError,
+)
from distutils.sysconfig import customize_compiler, get_python_version
from distutils.sysconfig import get_config_h_filename
from distutils.dep_util import newer_group
self.user = None
self.parallel = None
- def finalize_options(self):
+ def finalize_options(self): # noqa: C901
from distutils import sysconfig
self.set_undefined_options(
except ValueError:
raise DistutilsOptionError("parallel should be an integer")
- def run(self):
+ def run(self): # noqa: C901
from distutils.ccompiler import new_compiler
# 'self.extensions', as supplied by setup.py, is a list of
# Now actually compile and link everything.
self.build_extensions()
- def check_extensions_list(self, extensions):
+ def check_extensions_list(self, extensions): # noqa: C901
"""Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
ext.export_symbols.append(initfunc_name)
return ext.export_symbols
- def get_libraries(self, ext):
+ def get_libraries(self, ext): # noqa: C901
"""Return the list of libraries to link against when building a
shared extension. On most platforms, this is just 'ext.libraries';
on Windows, we add the Python library (eg. python20.dll).
import glob
from distutils.core import Command
-from distutils.errors import *
+from distutils.errors import DistutilsOptionError, DistutilsFileError
from distutils.util import convert_path
from distutils import log
def build_package_data(self):
"""Copy data files into build directory"""
- lastdir = None
for package, src_dir, build_dir, filenames in self.data_files:
for filename in filenames:
target = os.path.join(build_dir, filename)
return outfiles, updated_files
- def _copy_script(self, script, outfiles, updated_files):
+ def _copy_script(self, script, outfiles, updated_files): # noqa: C901
shebang_match = None
script = convert_path(script)
outfile = os.path.join(self.build_dir, os.path.basename(script))
Implements the Distutils 'check' command.
"""
-from email.utils import getaddresses
-
from distutils.core import Command
from distutils.errors import DistutilsSetupError
this header file lives".
"""
-import os, re
+import os
+import re
from distutils.core import Command
from distutils.errors import DistutilsExecError
from distutils.core import Command
from distutils.debug import DEBUG
from distutils.sysconfig import get_config_vars
-from distutils.errors import DistutilsPlatformError
from distutils.file_util import write_file
from distutils.util import convert_path, subst_vars, change_root
from distutils.util import get_platform
-from distutils.errors import DistutilsOptionError
+from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from . import _framework_compat as fw
from .. import _collections
INSTALL_SCHEMES = {
'posix_prefix': {
'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',
- 'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',
- 'headers': '{base}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
+ 'platlib': '{platbase}/{platlibdir}/{implementation_lower}'
+ '{py_version_short}/site-packages',
+ 'headers': '{base}/include/{implementation_lower}'
+ '{py_version_short}{abiflags}/{dist_name}',
'scripts': '{base}/bin',
'data': '{base}',
},
INSTALL_SCHEMES['nt_user'] = {
'purelib': '{usersite}',
'platlib': '{usersite}',
- 'headers': '{userbase}/{implementation}{py_version_nodot_plat}/Include/{dist_name}',
+ 'headers': '{userbase}/{implementation}{py_version_nodot_plat}'
+ '/Include/{dist_name}',
'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',
'data': '{userbase}',
}
INSTALL_SCHEMES['posix_user'] = {
'purelib': '{usersite}',
'platlib': '{usersite}',
- 'headers': '{userbase}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',
+ 'headers': '{userbase}/include/{implementation_lower}'
+ '{py_version_short}{abiflags}/{dist_name}',
'scripts': '{userbase}/bin',
'data': '{userbase}',
}
# party Python modules on various platforms given a wide
# array of user input is decided. Yes, it's quite complex!)
- def finalize_options(self):
+ def finalize_options(self): # noqa: C901
"""Finalizes options."""
# This method (and its helpers, like 'finalize_unix()',
# 'finalize_other()', and 'select_scheme()') is where the default
-"""distutils.command.install_egg_info
+"""
+distutils.command.install_egg_info
Implements the Distutils 'install_egg_info' command, for installing
-a package's PKG-INFO metadata."""
+a package's PKG-INFO metadata.
+"""
+import os
+import sys
+import re
from distutils.cmd import Command
from distutils import log, dir_util
-import os, sys, re
class install_egg_info(Command):
import getpass
import io
-import urllib.parse, urllib.request
+import urllib.parse
+import urllib.request
from warnings import warn
from distutils.core import PyPIRCCommand
-from distutils.errors import *
from distutils import log
(code, result) = self.post_to_server(self.build_post_data('verify'))
log.info('Server response (%s): %s', code, result)
- def send_metadata(self):
+ def send_metadata(self): # noqa: C901
'''Send the metadata to the package index server.
Well, do the following:
data['metadata_version'] = '1.1'
return data
- def post_to_server(self, data, auth=None):
+ def post_to_server(self, data, auth=None): # noqa: C901
'''Post a query to the server, and return a string response.'''
if 'name' in data:
self.announce(
from distutils.filelist import FileList
from distutils import log
from distutils.util import convert_path
-from distutils.errors import DistutilsTemplateError, DistutilsOptionError
+from distutils.errors import DistutilsOptionError, DistutilsTemplateError
def show_formats():
for command, pyversion, filename in self.distribution.dist_files:
self.upload_file(command, pyversion, filename)
- def upload_file(self, command, pyversion, filename):
+ def upload_file(self, command, pyversion, filename): # noqa: C901
# Makes sure the repository URL is compliant
schema, netloc, url, params, query, fragments = urlparse(self.repository)
if params or query or fragments:
with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f:
f.write(DEFAULT_PYPIRC % (username, password))
- def _read_pypirc(self):
+ def _read_pypirc(self): # noqa: C901
"""Reads the .pypirc file."""
rc = self._get_rc_file()
if os.path.exists(rc):
import tokenize
from distutils.debug import DEBUG
-from distutils.errors import *
+from distutils.errors import (
+ DistutilsSetupError,
+ DistutilsError,
+ CCompilerError,
+ DistutilsArgError,
+)
# Mainly import these so setup scripts can "from distutils.core import" them.
from distutils.dist import Distribution
from distutils.config import PyPIRCCommand
from distutils.extension import Extension
+
+__all__ = ['Distribution', 'Command', 'PyPIRCCommand', '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,
def gen_usage(script_name):
script = os.path.basename(script_name)
- return USAGE % vars()
+ return USAGE % locals()
# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
)
-def setup(**attrs):
+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
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
+_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."""
objects = copy.copy(objects or [])
if runtime_library_dirs:
- self.warn(
- "I don't know what to do with 'runtime_library_dirs': "
- + str(runtime_library_dirs)
- )
+ self.warn(_runtime_library_dirs_msg)
# Additional libraries
libraries.extend(self.dll_libraries)
# generate the filenames for these files
def_file = os.path.join(temp_dir, dll_name + ".def")
- lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
# Generate .def file
contents = ["LIBRARY %s" % os.path.basename(output_filename), "EXPORTS"]
contents.append(sym)
self.execute(write_file, (def_file, contents), "writing %s" % def_file)
- # next add options for def-file and to creating import libraries
+ # next add options for def-file
- # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
- # extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
# for gcc/ld the def-file is specified as any object files
objects.append(def_file)
# 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("don't know how to set runtime library search path on Windows")
+ self.warn(_runtime_library_dirs_msg)
return []
# -- Miscellaneous methods -----------------------------------------
self.dll_libraries = get_msvcr()
def runtime_library_dir_option(self, dir):
- raise DistutilsPlatformError(
- "don't know how to set runtime library search path on Windows"
- )
+ raise DistutilsPlatformError(_runtime_library_dirs_msg)
# Because these compilers aren't configured in Python's pyconfig.h file by
if missing == 'error': # blow up when we stat() the file
pass
elif missing == 'ignore': # missing source dropped from
- continue # target's dependency list
+ continue # target's dependency list
elif missing == 'newer': # missing source means target is
- return 1 # out-of-date
+ return 1 # out-of-date
source_mtime = os.stat(source)[ST_MTIME]
if source_mtime > target_mtime:
import os
import errno
-from distutils.errors import DistutilsFileError, DistutilsInternalError
+from distutils.errors import DistutilsInternalError, DistutilsFileError
from distutils import log
# cache for by mkpath() -- in addition to cheapening redundant calls,
# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
_path_created = {}
-# I don't use os.makedirs because a) it's new to Python 1.5.2, and
-# b) it blows up if the directory already exists (I want to silently
-# succeed in that case).
-def mkpath(name, mode=0o777, verbose=1, dry_run=0):
+
+def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901
"""Create a directory and any missing ancestor directories.
If the directory already exists (or if 'name' is the empty string, which
(eg. some sub-path exists, but is a file rather than a directory).
If 'verbose' is true, print a one-line summary of each mkdir to stdout.
Return the list of directories actually created.
+
+ os.makedirs is not used because:
+
+ a) It's new to Python 1.5.2, and
+ b) it blows up if the directory already exists (in which case it should
+ silently succeed).
"""
global _path_created
mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
-def copy_tree(
+def copy_tree( # noqa: C901
src,
dst,
preserve_mode=1,
except ImportError:
warnings = None
-from distutils.errors import *
+from distutils.errors import (
+ DistutilsOptionError,
+ DistutilsModuleError,
+ DistutilsArgError,
+ DistutilsClassError,
+)
from distutils.fancy_getopt import FancyGetopt, translate_longopt
from distutils.util import check_environ, strtobool, rfc822_escape
from distutils import log
# -- Creation/initialization methods -------------------------------
- def __init__(self, attrs=None):
+ 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
return files
- def parse_config_files(self, filenames=None):
+ def parse_config_files(self, filenames=None): # noqa: C901
from configparser import ConfigParser
# Ignore install directory options if we have a venv
),
]
- def _parse_command_opts(self, parser, args):
+ 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
return cmd_obj
- def _set_command_options(self, command_obj, option_dict=None):
+ 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').
)
-def read_setup_file(filename):
+def read_setup_file(filename): # noqa: C901
"""Reads a Setup file and returns Extension instances."""
from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx
* options set attributes of a passed-in object
"""
-import sys, string, re
+import sys
+import string
+import re
import getopt
-from distutils.errors import *
+from distutils.errors import DistutilsGetoptError, DistutilsArgError
# Much like command_re in distutils.core, this is close to but not quite
# the same as a Python NAME -- except, in the spirit of most GNU
self._check_alias_dict(negative_alias, "negative alias")
self.negative_alias = negative_alias
- def _grok_option_table(self):
+ def _grok_option_table(self): # noqa: C901
"""Populate the various data structures that keep tabs on the
option table. Called by 'getopt()' before it can do anything
worthwhile.
self.short_opts.append(short)
self.short2long[short[0]] = long
- def getopt(self, args=None, object=None):
+ def getopt(self, args=None, object=None): # noqa: C901
"""Parse command-line options in args. Store as attributes on object.
If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
else:
return self.option_order
- def generate_help(self, header=None):
+ def generate_help(self, header=None): # noqa: C901
"""Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
"""
for option in self.option_table:
long = option[0]
short = option[1]
- l = len(long)
+ ell = len(long)
if long[-1] == '=':
- l = l - 1
+ ell = ell - 1
if short is not None:
- l = l + 5 # " (-x)" where short == 'x'
- if l > max_opt:
- max_opt = l
+ ell = ell + 5 # " (-x)" where short == 'x'
+ if ell > max_opt:
+ max_opt = ell
opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
else:
lines.append(" --%-*s" % opt_names)
- for l in text[1:]:
- lines.append(big_indent + l)
+ for ell in text[1:]:
+ lines.append(big_indent + ell)
return lines
def print_help(self, header=None, file=None):
cur_len = 0 # length of current line
while chunks:
- l = len(chunks[0])
- if cur_len + l <= width: # can squeeze (at least) this chunk in
+ ell = len(chunks[0])
+ if cur_len + ell <= width: # can squeeze (at least) this chunk in
cur_line.append(chunks[0])
del chunks[0]
- cur_len = cur_len + l
+ cur_len = cur_len + ell
else: # this line is full
# drop last chunk if all space
if cur_line and cur_line[-1][0] == ' ':
_copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}
-def _copy_file_contents(src, dst, buffer_size=16 * 1024):
+def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901
"""Copy the file 'src' to 'dst'; both must be filenames. Any error
opening either file, reading from 'src', or writing to 'dst', raises
DistutilsFileError. Data is read/written in chunks of 'buffer_size'
fsrc.close()
-def copy_file(
+def copy_file( # noqa: C901
src,
dst,
preserve_mode=1,
# XXX I suspect this is Unix-specific -- need porting help!
-def move_file(src, dst, verbose=1, dry_run=0):
+def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901
"""Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
be moved into it with the same name; otherwise, 'src' is just renamed
return (action, patterns, dir, dir_pattern)
- def process_template_line(self, line):
+ def process_template_line(self, line): # noqa: C901
# Parse the line: split it up, make sure the right number of words
# is there, and return the relevant words. 'action' is always
# defined: it's the first word of the line. Which of the other
self.__arch = None # deprecated name
self.initialized = False
- def initialize(self, plat_name=None):
+ def initialize(self, plat_name=None): # noqa: C901
# multi-init means we would need to check platform same each time...
assert not self.initialized, "don't init multiple times"
if self.__version < 8.0:
obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
- def compile(
+ def compile( # noqa: C901
self,
sources,
output_dir=None,
else:
log.debug("skipping %s (up-to-date)", output_filename)
- def link(
+ def link( # noqa: C901
self,
target_desc,
objects,
# hacked by Robin Becker and Thomas Heller to do a better job of
# finding DevStudio (through the registry)
-import sys, os
+import sys
+import os
from distutils.errors import (
DistutilsExecError,
DistutilsPlatformError,
self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
else:
self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
- except KeyError as exc: #
+ except KeyError:
raise DistutilsPlatformError(
"""Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
obj_names.append(os.path.join(output_dir, base + self.obj_extension))
return obj_names
- def compile(
+ def compile( # noqa: C901
self,
sources,
output_dir=None,
else:
log.debug("skipping %s (up-to-date)", output_filename)
- def link(
+ def link( # noqa: C901
self,
target_desc,
objects,
from distutils.msvc9compiler import MSVCCompiler
# get_build_architecture not really relevant now we support cross-compile
- from distutils.msvc9compiler import MacroExpander
+ from distutils.msvc9compiler import MacroExpander # noqa: F811
from distutils import log
-def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):
+def spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None): # noqa: C901
"""Run another program, specified as a command list 'cmd', in a new process.
'cmd' is just the argument list for the new process, ie.
)
-def customize_compiler(compiler):
+def customize_compiler(compiler): # noqa: C901
"""Do any platform-specific customization of a CCompiler instance.
Mainly needed on Unix, so we can plug in the information that
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
-def parse_makefile(fn, g=None):
+def parse_makefile(fn, g=None): # noqa: C901
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
-"""Test suite for distutils.
-
-This test suite consists of a collection of test modules in the
-distutils.tests package. Each test module has a name starting with
-'test' and contains a function test_suite(). The function is expected
-to return an initialized unittest.TestSuite instance.
+"""
+Test suite for distutils.
Tests for the command classes in the distutils.command package are
included in distutils.tests as well, instead of using a separate
distutils.command.tests package, since command identification is done
by import rather than matching pre-defined names.
-
"""
-
-import os
-import sys
-import unittest
-from test.support import run_unittest
-
-from .py38compat import save_restore_warnings_filters
-
-
-here = os.path.dirname(__file__) or os.curdir
-
-
-def test_suite():
- suite = unittest.TestSuite()
- for fn in os.listdir(here):
- if fn.startswith("test") and fn.endswith(".py"):
- modname = "distutils.tests." + fn[:-3]
- # bpo-40055: Save/restore warnings filters to leave them unchanged.
- # Importing tests imports docutils which imports pkg_resources
- # which adds a warnings filter.
- with save_restore_warnings_filters():
- __import__(modname)
- module = sys.modules[modname]
- suite.addTest(module.test_suite())
- return suite
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
)
-# From Python 3.9
-@contextlib.contextmanager
-def _save_restore_warnings_filters():
- old_filters = warnings.filters[:]
- try:
- yield
- finally:
- warnings.filters[:] = old_filters
-
-
-try:
- from test.support.warnings_helper import save_restore_warnings_filters
-except (ModuleNotFoundError, ImportError):
- save_restore_warnings_filters = _save_restore_warnings_filters
-
-
if sys.version_info < (3, 9):
requires_zlib = lambda: test.support.requires_zlib
import tempfile
import unittest
import sysconfig
-from copy import deepcopy
from . import py38compat as os_helper
pass
-class EnvironGuard(object):
- def setUp(self):
- super(EnvironGuard, self).setUp()
- self.old_environ = deepcopy(os.environ)
-
- def tearDown(self):
- for key, value in self.old_environ.items():
- if os.environ.get(key) != value:
- os.environ[key] = value
-
- for key in tuple(os.environ.keys()):
- if key not in self.old_environ:
- del os.environ[key]
-
- super(EnvironGuard, self).tearDown()
-
-
def copy_xxmodule_c(directory):
"""Helper for tests that need the xxmodule.c source file.
from os.path import splitdrive
import warnings
+import pytest
+
from distutils import archive_util
from distutils.archive_util import (
check_archive_formats,
)
from distutils.spawn import find_executable, spawn
from distutils.tests import support
-from test.support import run_unittest, patch
+from test.support import patch
from .unix_compat import require_unix_id, require_uid_0, grp, pwd, UID_0_SUPPORT
from .py38compat import change_cwd
except ImportError:
ZIP_SUPPORT = find_executable('zip')
-try:
- import zlib
-
- ZLIB_SUPPORT = True
-except ImportError:
- ZLIB_SUPPORT = False
-
try:
import bz2
except ImportError:
class ArchiveUtilTestCase(
support.TempdirManager, support.LoggingSilencer, unittest.TestCase
):
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_make_tarball(self, name='archive'):
# creating something to tar
tmpdir = self._create_files()
# trying an uncompressed one
self._make_tarball(tmpdir, name, '.tar', compress=None)
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_make_tarball_gzip(self):
tmpdir = self._create_files()
self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip')
os.mkdir(os.path.join(dist, 'sub2'))
return tmpdir
+ @pytest.mark.usefixtures('needs_zlib')
@unittest.skipUnless(
- find_executable('tar') and find_executable('gzip') and ZLIB_SUPPORT,
- 'Need the tar, gzip and zlib command to run',
+ find_executable('tar') and find_executable('gzip'),
+ 'Need the tar and gzip commands to run',
)
def test_tarfile_vs_tar(self):
tmpdir = self._create_files()
self.assertFalse(os.path.exists(tarball))
self.assertEqual(len(w.warnings), 1)
- @unittest.skipUnless(
- ZIP_SUPPORT and ZLIB_SUPPORT, 'Need zip and zlib support to run'
- )
+ @pytest.mark.usefixtures('needs_zlib')
+ @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
def test_make_zipfile(self):
# creating something to tar
tmpdir = self._create_files()
try:
try:
make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
- except:
+ except Exception:
pass
self.assertEqual(os.getcwd(), current_dir)
finally:
self.assertEqual(os.path.basename(res), 'archive.tar')
self.assertEqual(self._tarinfo(res), self._created_files)
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_make_archive_gztar(self):
base_dir = self._create_files()
base_name = os.path.join(self.mkdtemp(), 'archive')
)
self.assertTrue(os.path.exists(res))
- @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
+ @pytest.mark.usefixtures('needs_zlib')
@require_unix_id
@require_uid_0
def test_tarfile_root_owner(self):
self.assertEqual(member.gid, 0)
finally:
archive.close()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(ArchiveUtilTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
"""Tests for distutils.command.bdist."""
import os
import unittest
-from test.support import run_unittest
import warnings
from distutils.command.bdist import bdist
'zip',
'ztar',
]
- found = sorted(cmd.format_command)
+ found = sorted(cmd.format_commands)
self.assertEqual(found, formats)
def test_skip_build(self):
self.assertTrue(
subcmd.skip_build, '%s should take --skip-build from bdist' % name
)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import sys
import zipfile
import unittest
-from test.support import run_unittest
+
+import pytest
from distutils.core import Distribution
from distutils.command.bdist_dumb import bdist_dumb
"""
-try:
- import zlib
-
- ZLIB_SUPPORT = True
-except ImportError:
- ZLIB_SUPPORT = False
-
+@pytest.mark.usefixtures('save_env')
class BuildDumbTestCase(
support.TempdirManager,
support.LoggingSilencer,
- support.EnvironGuard,
unittest.TestCase,
):
def setUp(self):
sys.argv[:] = self.old_sys_argv[1]
super(BuildDumbTestCase, self).tearDown()
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_simple_built(self):
# let's create a simple package
if not sys.dont_write_bytecode:
wanted.append('foo.%s.pyc' % sys.implementation.cache_tag)
self.assertEqual(contents, sorted(wanted))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildDumbTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
"""Tests for distutils.command.bdist_msi."""
import sys
import unittest
-from test.support import run_unittest
from distutils.tests import support
from .py38compat import check_warnings
with check_warnings(("", DeprecationWarning)):
cmd = bdist_msi(dist)
cmd.ensure_finalized()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BDistMSITestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import unittest
import sys
import os
-from test.support import run_unittest
+
+import pytest
from distutils.core import Distribution
from distutils.command.bdist_rpm import bdist_rpm
"""
+@pytest.mark.usefixtures('save_env')
class BuildRpmTestCase(
support.TempdirManager,
- support.EnvironGuard,
support.LoggingSilencer,
unittest.TestCase,
):
)
os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildRpmTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import sys
import platform
import unittest
-from test.support import run_unittest
from .py38compat import check_warnings
# no matter what platform we have
exe_file = cmd.get_exe_bytes()
self.assertGreater(len(exe_file), 10)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildWinInstTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import unittest
import os
import sys
-from test.support import run_unittest
from distutils.command.build import build
from distutils.tests import support
# executable is os.path.normpath(sys.executable)
self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import sys
-from test.support import run_unittest, missing_compiler_executable
+from test.support import missing_compiler_executable
from distutils.command.build_clib import build_clib
from distutils.errors import DistutilsSetupError
# let's check the result
self.assertIn('libfoo.a', os.listdir(build_temp))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildCLibTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
cmd = self.build_ext(dist)
cmd.finalize_options()
- #'extensions' option must be a list of Extension instances
+ # 'extensions' option must be a list of Extension instances
self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, 'foo')
# each element of 'ext_modules' option must be an
build_ext = super().build_ext(*args, **kwargs)
build_ext.parallel = True
return build_ext
-
-
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.TestLoader().loadTestsFromTestCase(BuildExtTestCase))
- suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ParallelBuildExtTestCase))
- return suite
-
-
-if __name__ == '__main__':
- support.run_unittest(__name__)
from unittest.mock import patch
from distutils.tests import support
-from test.support import run_unittest
class BuildPyTestCase(
cmd.run()
# Test should complete successfully with no exception
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildPyTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils import sysconfig
from distutils.tests import support
-from test.support import run_unittest
class BuildScriptsTestCase(
built = os.listdir(target)
for name in expected:
self.assertIn(name, built)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(BuildScriptsTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import textwrap
import unittest
-from test.support import run_unittest
from distutils.command.check import check, HAS_DOCUTILS
from distutils.tests import support
)
def test_check_all(self):
-
- metadata = {'url': 'xxx', 'author': 'xxx'}
self.assertRaises(
DistutilsSetupError, self._run, {}, **{'strict': 1, 'restructuredtext': 1}
)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(CheckTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils.command.clean import clean
from distutils.tests import support
-from test.support import run_unittest
class cleanTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase):
cmd.all = 1
cmd.ensure_finalized()
cmd.run()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(cleanTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
"""Tests for distutils.cmd."""
import unittest
import os
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
from distutils.cmd import Command
from distutils.dist import Distribution
self.assertEqual(stdout.read(), 'xxx\n')
finally:
debug.DEBUG = False
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(CommandTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import os
import unittest
+import pytest
+
from distutils.core import PyPIRCCommand
from distutils.core import Distribution
from distutils.log import set_threshold
from distutils.log import WARN
from distutils.tests import support
-from test.support import run_unittest
PYPIRC = """\
[distutils]
"""
+@pytest.mark.usefixtures('save_env')
class BasePyPIRCCommandTestCase(
support.TempdirManager,
support.LoggingSilencer,
- support.EnvironGuard,
unittest.TestCase,
):
def setUp(self):
('username', 'cbiggles'),
]
self.assertEqual(config, waited)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(PyPIRCCommandTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import unittest
import os
import sys
-from test.support import run_unittest, missing_compiler_executable
+from test.support import missing_compiler_executable
from distutils.command.config import dump_file, config
from distutils.tests import support
for f in (f1, f2):
self.assertFalse(os.path.exists(f))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(ConfigTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import shutil
import sys
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
+
+import pytest
+
from . import py38compat as os_helper
import unittest
-from distutils.tests import support
from distutils import log
from distutils.dist import Distribution
"""
-class CoreTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class CoreTestCase(unittest.TestCase):
def setUp(self):
super(CoreTestCase, self).setUp()
self.old_stdout = sys.stdout
stdout.seek(0)
wanted = "options (after parsing config files):\n"
self.assertEqual(stdout.readlines()[0], wanted)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(CoreTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import unittest
import sys
import os
-from test.support import run_unittest
from distutils.cygwinccompiler import (
check_config_h,
@unittest.skipIf(sys.platform != "cygwin", "Not running on Cygwin")
def test_runtime_library_dir_option(self):
from distutils.cygwinccompiler import CygwinCCompiler
+
compiler = CygwinCCompiler()
self.assertEqual(compiler.runtime_library_dir_option('/foo'), [])
)
self.assertEqual(get_msvcr(), ['msvcr90'])
- sys.version = '3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 18:46:30) [MSC v.1929 32 bit (Intel)]'
+ sys.version = (
+ '3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 18:46:30) '
+ '[MSC v.1929 32 bit (Intel)]'
+ )
self.assertEqual(get_msvcr(), ['ucrt', 'vcruntime140'])
# unknown
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' '[MSC v.2000 32 bits (Intel)]'
)
self.assertRaises(ValueError, get_msvcr)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(CygwinCCompilerTestCase)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
from distutils.dep_util import newer, newer_pairwise, newer_group
from distutils.errors import DistutilsFileError
from distutils.tests import support
-from test.support import run_unittest
class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
self.assertFalse(newer_group([one, two, old_file], three, missing='ignore'))
self.assertTrue(newer_group([one, two, old_file], three, missing='newer'))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(DepUtilTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils import log
from distutils.tests import support
-from test.support import run_unittest
class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
):
src = self.tempdirs[-1]
dir_util.copy_tree(src, None)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(DirUtilTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from unittest import mock
+import pytest
+
from distutils.dist import Distribution, fix_help_options
from distutils.cmd import Command
-from test.support import captured_stdout, captured_stderr, run_unittest
+from test.support import captured_stdout, captured_stderr
from .py38compat import TESTFN
from distutils.tests import support
from distutils import log
return self._config_files
+@pytest.mark.usefixtures('save_env')
class DistributionTestCase(
support.LoggingSilencer,
support.TempdirManager,
- support.EnvironGuard,
unittest.TestCase,
):
def setUp(self):
)
# Base case: Not in a Virtual Environment
- with mock.patch.multiple(sys, prefix='/a', base_prefix='/a') as values:
+ with mock.patch.multiple(sys, prefix='/a', base_prefix='/a'):
d = self.create_distribution([TESTFN])
option_tuple = (TESTFN, fakepath)
self.assertEqual(value, result_dict[key])
# Test case: In a Virtual Environment
- with mock.patch.multiple(sys, prefix='/a', base_prefix='/b') as values:
+ with mock.patch.multiple(sys, prefix='/a', base_prefix='/b'):
d = self.create_distribution([TESTFN])
for key in result_dict.keys():
self.assertEqual(len(all_files) - 1, len(files))
-class MetadataTestCase(support.TempdirManager, support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class MetadataTestCase(support.TempdirManager, unittest.TestCase):
def setUp(self):
super(MetadataTestCase, self).setUp()
self.argv = sys.argv, sys.argv[:]
self.assertEqual(metadata.platforms, None)
self.assertEqual(metadata.obsoletes, None)
self.assertEqual(metadata.requires, ['foo'])
-
-
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.TestLoader().loadTestsFromTestCase(DistributionTestCase))
- suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MetadataTestCase))
- return suite
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import warnings
-from test.support import run_unittest
from distutils.extension import read_setup_file, Extension
from .py38compat import check_warnings
self.assertEqual(
str(w.warnings[0].message), "Unknown Extension options: 'chic'"
)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(ExtensionTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils import log
from distutils.tests import support
from distutils.errors import DistutilsFileError
-from test.support import run_unittest
from .py38compat import unlink
for fn in (self.source, self.target):
with open(fn, 'r') as f:
self.assertEqual(f.read(), 'some content')
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(FileUtilTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils.filelist import glob_to_re, translate_pattern, FileList
from distutils import filelist
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
from distutils.tests import support
from . import py38compat as os_helper
os.symlink('.', link)
files = filelist.findall(temp_dir)
assert len(files) == 1
-
-
-def test_suite():
- return unittest.TestSuite(
- [
- unittest.TestLoader().loadTestsFromTestCase(FileListTestCase),
- unittest.TestLoader().loadTestsFromTestCase(FindAllTestCase),
- ]
- )
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import unittest
import site
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
+
+import pytest
from distutils import sysconfig
from distutils.command.install import install
from distutils.tests import support
from test import support as test_support
-import pytest
-
def _make_ext_name(modname):
return modname + sysconfig.get_config_var('EXT_SUFFIX')
+@pytest.mark.usefixtures('save_env')
class InstallTestCase(
support.TempdirManager,
- support.EnvironGuard,
support.LoggingSilencer,
unittest.TestCase,
):
finally:
install_module.DEBUG = False
self.assertGreater(len(self.logs), old_logs_len)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(InstallTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import unittest
+import pytest
+
from distutils.command.install_data import install_data
from distutils.tests import support
-from test.support import run_unittest
+@pytest.mark.usefixtures('save_env')
class InstallDataTestCase(
support.TempdirManager,
support.LoggingSilencer,
- support.EnvironGuard,
unittest.TestCase,
):
def test_simple_run(self):
# now using root and empty dir
cmd.root = os.path.join(pkg_dir, 'root')
- inst3 = os.path.join(cmd.install_dir, 'inst3')
inst4 = os.path.join(pkg_dir, 'inst4')
three = os.path.join(cmd.install_dir, 'three')
self.write_file(three, 'xx')
self.assertEqual(len(cmd.get_outputs()), 4)
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone)))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(InstallDataTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import unittest
+import pytest
+
from distutils.command.install_headers import install_headers
from distutils.tests import support
-from test.support import run_unittest
+@pytest.mark.usefixtures('save_env')
class InstallHeadersTestCase(
support.TempdirManager,
support.LoggingSilencer,
- support.EnvironGuard,
unittest.TestCase,
):
def test_simple_run(self):
# let's check the results
self.assertEqual(len(cmd.get_outputs()), 2)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(InstallHeadersTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import importlib.util
import unittest
+import pytest
+
from distutils.command.install_lib import install_lib
from distutils.extension import Extension
from distutils.tests import support
from distutils.errors import DistutilsOptionError
-from test.support import run_unittest
+@pytest.mark.usefixtures('save_env')
class InstallLibTestCase(
support.TempdirManager,
support.LoggingSilencer,
- support.EnvironGuard,
unittest.TestCase,
):
def test_finalize_options(self):
sys.dont_write_bytecode = old_dont_write_bytecode
self.assertIn('byte-compiling is disabled', self.logs[0][1] % self.logs[0][2])
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(InstallLibTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils.core import Distribution
from distutils.tests import support
-from test.support import run_unittest
class InstallScriptsTestCase(
installed = os.listdir(target)
for name in expected:
self.assertIn(name, installed)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(InstallScriptsTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import io
import sys
import unittest
-from test.support import swap_attr, run_unittest
+from test.support import swap_attr
from distutils import log
if errors == 'ignore'
else 'Fαtal\t\\xc8rr\\u014dr',
)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(TestLog)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
from distutils.errors import DistutilsPlatformError
from distutils.tests import support
-from test.support import run_unittest
# A manifest with the only assembly reference being the msvcrt assembly, so
# should have the assembly completely stripped. Note that although the
compiler = MSVCCompiler()
got = compiler._remove_visual_c_ref(manifest)
self.assertIsNone(got)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(msvc9compilerTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import threading
+import pytest
+
from distutils.errors import DistutilsPlatformError
from distutils.tests import support
-from test.support import run_unittest
+from distutils import _msvccompiler
-SKIP_MESSAGE = None if sys.platform == "win32" else "These tests are only for win32"
+needs_winreg = pytest.mark.skipif('not hasattr(_msvccompiler, "winreg")')
-@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
class msvccompilerTestCase(support.TempdirManager, unittest.TestCase):
def test_no_compiler(self):
- import distutils._msvccompiler as _msvccompiler
-
# makes sure query_vcvarsall raises
# a DistutilsPlatformError if the compiler
# is not found
finally:
_msvccompiler._find_vcvarsall = old_find_vcvarsall
+ @needs_winreg
def test_get_vc_env_unicode(self):
- import distutils._msvccompiler as _msvccompiler
-
test_var = 'ṰḖṤṪ┅ṼẨṜ'
test_value = '₃⁴₅'
if old_distutils_use_sdk:
os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk
+ @needs_winreg
def test_get_vc2017(self):
- import distutils._msvccompiler as _msvccompiler
-
# This function cannot be mocked, so pass it if we find VS 2017
# and mark it skipped if we do not.
version, path = _msvccompiler._find_vc2017()
else:
raise unittest.SkipTest("VS 2017 is not installed")
+ @needs_winreg
def test_get_vc2015(self):
- import distutils._msvccompiler as _msvccompiler
-
# This function cannot be mocked, so pass it if we find VS 2015
# and mark it skipped if we do not.
version, path = _msvccompiler._find_vc2015()
"""
Concurrent calls to spawn should have consistent results.
"""
- import distutils._msvccompiler as _msvccompiler
-
compiler = _msvccompiler.MSVCCompiler()
compiler._paths = "expected"
inner_cmd = 'import os; assert os.environ["PATH"] == "expected"'
If CCompiler.spawn has been monkey-patched without support
for an env, it should still execute.
"""
- import distutils._msvccompiler as _msvccompiler
from distutils import ccompiler
compiler = _msvccompiler.MSVCCompiler()
compiler.spawn(["n/a"])
assert os.environ.get("PATH") != "expected"
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(msvccompilerTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import urllib
import warnings
-from test.support import run_unittest
from .py38compat import check_warnings
results = self.get_logs(INFO)
self.assertEqual(results[3], 75 * '-' + '\nxxx\n' + 75 * '-')
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(RegisterTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import zipfile
from os.path import join
from textwrap import dedent
-from test.support import captured_stdout, run_unittest
+from test.support import captured_stdout
from .unix_compat import require_unix_id, require_uid_0, pwd, grp
-from .py38compat import check_warnings
-
-try:
- import zlib
+import pytest
- ZLIB_SUPPORT = True
-except ImportError:
- ZLIB_SUPPORT = False
+from .py38compat import check_warnings
from distutils.command.sdist import sdist, show_formats
from distutils.core import Distribution
cmd.dist_dir = 'dist'
return dist, cmd
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_prune_file_list(self):
# this test creates a project with some VCS dirs and an NFS rename
# file, then launches sdist to check they get pruned on all systems
]
self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected])
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
@unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
@unittest.skipIf(find_executable('gzip') is None, "The gzip command is not found")
def test_make_distribution(self):
result.sort()
self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_add_defaults(self):
# http://bugs.python.org/issue2279
f.close()
self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_metadata_check_option(self):
# testing the `medata-check` option
dist, cmd = self.get_cmd(metadata={})
# this used to crash instead of raising a warning: #8286
self._check_template('include examples/')
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_get_file_list(self):
# make sure MANIFEST is recalculated
dist, cmd = self.get_cmd()
self.assertEqual(len(manifest2), 6)
self.assertIn('doc2.txt', manifest2[-1])
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_manifest_marker(self):
# check that autogenerated MANIFESTs have a marker
dist, cmd = self.get_cmd()
self.assertEqual(manifest[0], '# file GENERATED by distutils, do NOT edit')
- @unittest.skipUnless(ZLIB_SUPPORT, "Need zlib support to run")
+ @pytest.mark.usefixtures('needs_zlib')
def test_manifest_comments(self):
# make sure comments don't cause exceptions or wrong includes
contents = dedent(
cmd.run()
self.assertEqual(cmd.filelist.files, ['good.py'])
- @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
+ @pytest.mark.usefixtures('needs_zlib')
def test_manual_manifest(self):
# check that a MANIFEST without a marker is left alone
dist, cmd = self.get_cmd()
['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual'],
)
- @unittest.skipUnless(ZLIB_SUPPORT, "requires zlib")
+ @pytest.mark.usefixtures('needs_zlib')
@require_unix_id
@require_uid_0
@unittest.skipIf(find_executable('tar') is None, "The tar command is not found")
self.assertEqual(member.uid, os.getuid())
finally:
archive.close()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(SDistTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import stat
import sys
import unittest.mock
-from test.support import run_unittest, unix_shell
+from test.support import unix_shell
from . import py38compat as os_helper
with self.assertRaises(DistutilsExecError) as ctx:
spawn(['does-not-exist'])
self.assertIn("command 'does-not-exist' failed", str(ctx.exception))
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(SpawnTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import textwrap
import unittest
+import pytest
import jaraco.envs
import distutils
from distutils import sysconfig
from distutils.ccompiler import get_default_compiler
from distutils.unixccompiler import UnixCCompiler
-from distutils.tests import support
-from test.support import run_unittest, swap_item
+from test.support import swap_item
from .py38compat import TESTFN
-class SysconfigTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class SysconfigTestCase(unittest.TestCase):
def setUp(self):
super(SysconfigTestCase, self).setUp()
self.makefile = None
cmd, env={**os.environ, "PYTHONPATH": distutils_path}
)
assert out == "True"
-
-
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.TestLoader().loadTestsFromTestCase(SysconfigTestCase))
- return suite
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
import unittest
from distutils.text_file import TextFile
from distutils.tests import support
-from test.support import run_unittest
TEST_DATA = """# test file
test_input(6, "join lines with collapsing", in_file, result6)
finally:
in_file.close()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(TextFileTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import os
import sys
import unittest
-from test.support import run_unittest
from unittest.mock import patch
from .py38compat import EnvironmentVarGuard
sysconfig.get_config_vars = self._backup_get_config_vars
@unittest.skipIf(sys.platform == 'win32', "can't test on Windows")
- def test_runtime_libdir_option(self):
+ def test_runtime_libdir_option(self): # noqa: C901
# Issue #5900; GitHub Issue #37
#
# Ensure RUNPATH is added to extension modules with RPATH if
self.cc.output_dir = 'scratch'
os.chdir(self.mkdtemp())
self.cc.has_function('abort', includes=['stdlib.h'])
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(UnixCCompilerTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
"""Tests for distutils.command.upload."""
import os
-import unittest
import unittest.mock as mock
from urllib.request import HTTPError
-from test.support import run_unittest
from distutils.command import upload as upload_mod
from distutils.command.upload import upload
results = self.get_logs(ERROR)
self.assertIn(expected, results[-1])
self.clear_logs()
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(uploadTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import unittest
import sysconfig as stdlib_sysconfig
from copy import copy
-from test.support import run_unittest
from unittest import mock
-from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
+import pytest
+
from distutils.util import (
get_platform,
convert_path,
)
from distutils import util # used to patch _environ_checked
from distutils import sysconfig
-from distutils.tests import support
+from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
-class UtilTestCase(support.EnvironGuard, unittest.TestCase):
+@pytest.mark.usefixtures('save_env')
+class UtilTestCase(unittest.TestCase):
def setUp(self):
super(UtilTestCase, self).setUp()
# saving the environment
exc = IOError("Unable to find batch file")
msg = grok_environment_error(exc)
self.assertEqual(msg, "error: Unable to find batch file")
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(UtilTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
import distutils
from distutils.version import LooseVersion
from distutils.version import StrictVersion
-from test.support import run_unittest
class VersionTestCase(unittest.TestCase):
NotImplemented,
'cmp(%s, %s) should be NotImplemented, got %s' % (v1, v2, res),
)
-
-
-def test_suite():
- return unittest.TestLoader().loadTestsFromTestCase(VersionTestCase)
-
-
-if __name__ == "__main__":
- run_unittest(test_suite())
-"""Tests harness for distutils.versionpredicate.
-
-"""
-
-import distutils.versionpredicate
-import doctest
-from test.support import run_unittest
-
-
-def test_suite():
- return doctest.DocTestSuite(distutils.versionpredicate)
-
-
-if __name__ == '__main__':
- run_unittest(test_suite())
that (optionally) takes care of stripping comments, ignoring blank
lines, and joining lines with backslashes."""
-import sys, io
+import sys
+import io
class TextFile:
line."""
sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
- def readline(self):
+ def readline(self): # noqa: C901
"""Read and return a single logical line from the current file (or
from an internal buffer if lines have previously been "unread"
with 'unreadline()'). If the 'join_lines' option is true, this
* link shared library handled by 'cc -shared'
"""
-import os, sys, re, shlex
+import os
+import sys
+import re
+import shlex
from distutils import sysconfig
from distutils.dep_util import newer
pp_args.extend(extra_postargs)
pp_args.append(source)
- # We need to preprocess: either we're being forced to, or we're
- # generating output to stdout, or there's a target output file and
- # the source file is newer than the target (or the target doesn't
- # exist).
- if self.force or output_file is None or newer(source, output_file):
- if output_file:
- self.mkpath(os.path.dirname(output_file))
- try:
- self.spawn(pp_args)
- except DistutilsExecError as msg:
- raise CompileError(msg)
+ # 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)
def library_option(self, lib):
return "-l" + lib
- def find_library_file(self, dirs, lib, debug=0):
- shared_f = self.library_filename(lib, lib_type='shared')
- dylib_f = self.library_filename(lib, lib_type='dylib')
- xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
- static_f = self.library_filename(lib, lib_type='static')
-
- if sys.platform == 'darwin':
- # On OSX users can specify an alternate SDK using
- # '-isysroot', calculate the SDK root if it is specified
- # (and use it further on)
- #
- # 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')
- m = re.search(r'-isysroot\s*(\S+)', cflags)
- if m is None:
- sysroot = '/'
- else:
- sysroot = m.group(1)
-
- for dir in dirs:
- shared = os.path.join(dir, shared_f)
- dylib = os.path.join(dir, dylib_f)
- static = os.path.join(dir, static_f)
- xcode_stub = os.path.join(dir, xcode_stub_f)
-
- if sys.platform == 'darwin' and (
+ @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/'))
- ):
-
- shared = os.path.join(sysroot, dir[1:], shared_f)
- dylib = os.path.join(sysroot, dir[1:], dylib_f)
- static = os.path.join(sysroot, dir[1:], static_f)
- xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)
-
- # We're second-guessing the linker here, with not much hard
- # data to go on: GCC seems to prefer the shared library, so I'm
- # assuming that *all* Unix C compilers do. And of course I'm
- # ignoring even GCC's "-static" option. So sue me.
- if os.path.exists(dylib):
- return dylib
- elif os.path.exists(xcode_stub):
- return xcode_stub
- elif os.path.exists(shared):
- return shared
- elif os.path.exists(static):
- return static
-
- # Oops, didn't find it in *any* of 'dirs'
- return None
+ )
+ )
+
+ return os.path.join(match.group(1), dir[1:]) if apply_root else dir
+
+ def find_library_file(self, dirs, lib, debug=0):
+ """
+ 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()
+ )
+
+ searched = (
+ os.path.join(root, lib_name)
+ for root in map(self._library_root, dirs)
+ for lib_name in lib_names
+ )
+
+ found = filter(os.path.exists, searched)
+
+ # Return None if it could not be found in any dir.
+ return next(found, None)
import subprocess
import sys
import sysconfig
-from distutils.errors import DistutilsPlatformError
+from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
from distutils.dep_util import newer
from distutils.spawn import spawn
from distutils import log
-from distutils.errors import DistutilsByteCompileError
def get_host_platform():
raise ValueError("invalid truth value %r" % (val,))
-def byte_compile(
+def byte_compile( # noqa: C901
py_files,
optimize=0,
force=0,
return vstring
- def _cmp(self, other):
+ def _cmp(self, other): # noqa: C901
if isinstance(other, str):
with suppress_known_deprecation():
other = StrictVersion(other)
with _open_setup_script(__file__) as f:
code = f.read().replace(r'\r\n', r'\n')
- exec(compile(code, __file__, 'exec'), locals())
+ exec(code, locals())
def get_requires_for_build_wheel(self, config_settings=None):
return self._get_build_requires(
import sys
if 'egg' not in bdist.format_commands:
- bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
- bdist.format_commands.append('egg')
+ try:
+ bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
+ except TypeError:
+ # For backward compatibility with older distutils (stdlib)
+ bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
+ bdist.format_commands.append('egg')
del bdist, sys
to access a backward compatible API, but this module is provisional
and might be removed in the future.
"""
- warnings.warn(dedent(msg), SetuptoolsDeprecationWarning)
+ warnings.warn(dedent(msg), SetuptoolsDeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return cast(Fn, _wrapper)
pytestmark = pytest.mark.integration
-LATEST, = list(Enum("v", "LATEST"))
+LATEST, = Enum("v", "LATEST")
"""Default version to be checked"""
# There are positive and negative aspects of checking the latest version of the
# packages.
# means it will download the previous stable version of setuptools.
# `pip` flags can avoid that (the version of setuptools under test
# should be the one to be used)
-SDIST_OPTIONS = (
+INSTALL_OPTIONS = (
"--ignore-installed",
"--no-build-isolation",
- # We don't need "--no-binary :all:" since we specify the path to the sdist.
- # It also helps with performance, since dependencies can come from wheels.
+ # Omit "--no-binary :all:" the sdist is supplied directly.
+ # Allows dependencies as wheels.
)
# The downside of `--no-build-isolation` is that pip will not download build
# dependencies. The test script will have to also handle that.
# Use a virtualenv to simulate PEP 517 isolation
# but install fresh setuptools wheel to ensure the version under development
run([*venv_pip, "install", "-I", setuptools_wheel])
- run([*venv_pip, "install", *SDIST_OPTIONS, sdist])
+ run([*venv_pip, "install", *INSTALL_OPTIONS, sdist])
# Execute a simple script to make sure the package was installed correctly
script = f"import {package}; print(getattr({package}, '__version__', 0))"
raise ValueError(f"Release for {package} {version} was yanked")
version = metadata["info"]["version"]
- release = metadata["releases"][version]
- dists = [d for d in release if d["packagetype"] == "sdist"]
- if len(dists) == 0:
- raise ValueError(f"No sdist found for {package} {version}")
-
- for dist in dists:
- if dist["filename"].endswith(".tar.gz"):
- return dist
-
- # Not all packages are publishing tar.gz
- return dist
+ release = metadata["releases"][version] if version is LATEST else metadata["urls"]
+ sdist, = filter(lambda d: d["packagetype"] == "sdist", release)
+ return sdist
def download(url, dest, md5_digest):
def build_deps(package, sdist_file):
"""Find out what are the build dependencies for a package.
- We need to "manually" install them, since pip will not install build
+ "Manually" install them, since pip will not install build
deps with `--no-build-isolation`.
"""
import tomli as toml
# testenv without tomli
archive = Archive(sdist_file)
- pyproject = _read_pyproject(archive)
-
- info = toml.loads(pyproject)
+ info = toml.loads(_read_pyproject(archive))
deps = info.get("build-system", {}).get("requires", [])
deps += EXTRA_BUILD_DEPS.get(package, [])
# Remove setuptools from requirements (and deduplicate)
def _read_pyproject(archive):
- for member in archive:
- if os.path.basename(archive.get_name(member)) == "pyproject.toml":
- return archive.get_content(member)
- return ""
+ contents = (
+ archive.get_content(member)
+ for member in archive
+ if os.path.basename(archive.get_name(member)) == "pyproject.toml"
+ )
+ return next(contents, "")
'arg5 a\\\\b',
]
proc = subprocess.Popen(
- cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
- stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii'))
- actual = stdout.decode('ascii').replace('\r\n', '\n')
+ cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True)
+ stdout, stderr = proc.communicate('hello\nworld\n')
+ actual = stdout.replace('\r\n', '\n')
expected = textwrap.dedent(r"""
\foo-script.py
['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']
cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
- stderr=subprocess.STDOUT)
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
stdout, stderr = proc.communicate()
- actual = stdout.decode('ascii').replace('\r\n', '\n')
+ actual = stdout.replace('\r\n', '\n')
expected = textwrap.dedent(r"""
\foo-script.py
[]
]
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
- stderr=subprocess.STDOUT)
+ stderr=subprocess.STDOUT, text=True)
stdout, stderr = proc.communicate()
assert not stdout
assert not stderr
setenv =
PROJECT_ROOT = {toxinidir}
commands =
- pytest --integration {posargs:-vv --durations=10 setuptools/tests/integration}
+ pytest --integration {posargs:-vv --durations=10} setuptools/tests/integration
# use verbose mode by default to facilitate debugging from CI logs
[testenv:docs]