diff --git a/setuptools/__init__.py b/setuptools/__init__.py index e6334c9e077..35d7bd1c4ac 100644 --- a/setuptools/__init__.py +++ b/setuptools/__init__.py @@ -1,21 +1,25 @@ """Extensions to the 'distutils' for large or complex distributions""" -import distutils.core import functools import os import re + +import _distutils_hack.override # noqa: F401 + +import distutils.core from distutils.errors import DistutilsOptionError from distutils.util import convert_path as _convert_path -import _distutils_hack.override # noqa: F401 +from .warnings import SetuptoolsDeprecationWarning + import setuptools.version +from setuptools.extension import Extension +from setuptools.dist import Distribution from setuptools.depends import Require from setuptools.discovery import PackageFinder, PEP420PackageFinder -from setuptools.dist import Distribution -from setuptools.extension import Extension +from . import monkey +from . import logging -from . import logging, monkey -from .warnings import SetuptoolsDeprecationWarning __all__ = [ 'setup', @@ -253,7 +257,7 @@ def convert_path(pathname): Its direct usage by 3rd-party packages is considered improper and the function may be removed in the future. """, - due_date=(2023, 12, 13), # initial deprecation 2022-03-25, see #3201 + due_date=(2023, 12, 13) # initial deprecation 2022-03-25, see #3201 ) return _convert_path(pathname) diff --git a/setuptools/_entry_points.py b/setuptools/_entry_points.py index dbff285340e..a2346342d62 100644 --- a/setuptools/_entry_points.py +++ b/setuptools/_entry_points.py @@ -1,12 +1,12 @@ import functools -import itertools import operator +import itertools -from ._importlib import metadata -from ._itertools import ensure_unique from .errors import OptionError -from .extern.jaraco.functools import pass_none from .extern.jaraco.text import yield_lines +from .extern.jaraco.functools import pass_none +from ._importlib import metadata +from ._itertools import ensure_unique from .extern.more_itertools import consume @@ -54,8 +54,8 @@ def load(eps): Given a Distribution.entry_points, produce EntryPoints. """ groups = itertools.chain.from_iterable( - load_group(value, group) for group, value in eps.items() - ) + load_group(value, group) + for group, value in eps.items()) return validate(metadata.EntryPoints(groups)) @@ -81,8 +81,14 @@ def render(eps: metadata.EntryPoints): by_group = operator.attrgetter('group') groups = itertools.groupby(sorted(eps, key=by_group), by_group) - return '\n'.join(f'[{group}]\n{render_items(items)}\n' for group, items in groups) + return '\n'.join( + f'[{group}]\n{render_items(items)}\n' + for group, items in groups + ) def render_items(eps): - return '\n'.join(f'{ep.name} = {ep.value}' for ep in sorted(eps)) + return '\n'.join( + f'{ep.name} = {ep.value}' + for ep in sorted(eps) + ) diff --git a/setuptools/_imp.py b/setuptools/_imp.py index 913d16c3f77..6b4890191b8 100644 --- a/setuptools/_imp.py +++ b/setuptools/_imp.py @@ -3,11 +3,13 @@ from the deprecated imp module. """ -import importlib.machinery -import importlib.util import os +import importlib.util +import importlib.machinery + from importlib.util import module_from_spec + PY_SOURCE = 1 PY_COMPILED = 2 C_EXTENSION = 3 @@ -18,8 +20,8 @@ def find_spec(module, paths): finder = ( importlib.machinery.PathFinder().find_spec - if isinstance(paths, list) - else importlib.util.find_spec + if isinstance(paths, list) else + importlib.util.find_spec ) return finder(module, paths) @@ -35,19 +37,13 @@ def find_module(module, paths=None): kind = -1 file = None static = isinstance(spec.loader, type) - if ( - spec.origin == 'frozen' - or static - and issubclass(spec.loader, importlib.machinery.FrozenImporter) - ): + if spec.origin == 'frozen' or static and issubclass( + spec.loader, importlib.machinery.FrozenImporter): kind = PY_FROZEN path = None # imp compabilty suffix = mode = '' # imp compatibility - elif ( - spec.origin == 'built-in' - or static - and issubclass(spec.loader, importlib.machinery.BuiltinImporter) - ): + elif spec.origin == 'built-in' or static and issubclass( + spec.loader, importlib.machinery.BuiltinImporter): kind = C_BUILTIN path = None # imp compabilty suffix = mode = '' # imp compatibility diff --git a/setuptools/_importlib.py b/setuptools/_importlib.py index bd2b01e2b59..5ae94b4739e 100644 --- a/setuptools/_importlib.py +++ b/setuptools/_importlib.py @@ -22,7 +22,7 @@ def disable_importlib_metadata_finder(metadata): This problem is likely to be solved by installing an updated version of `importlib-metadata`. """, - see_url="https://github.com/python/importlib_metadata/issues/396", + see_url="https://github.com/python/importlib_metadata/issues/396" ) # Ensure a descriptive message is shown. raise # This exception can be suppressed by _distutils_hack @@ -39,7 +39,6 @@ def disable_importlib_metadata_finder(metadata): if sys.version_info < (3, 10): from setuptools.extern import importlib_metadata as metadata - disable_importlib_metadata_finder(metadata) else: import importlib.metadata as metadata # noqa: F401 diff --git a/setuptools/_normalization.py b/setuptools/_normalization.py index f872f65020f..31899f7ab1d 100644 --- a/setuptools/_normalization.py +++ b/setuptools/_normalization.py @@ -2,7 +2,6 @@ Helpers for normalization as expected in wheel/sdist/module file names and core metadata """ - import re from pathlib import Path from typing import Union diff --git a/setuptools/_reqs.py b/setuptools/_reqs.py index 3deb0eff243..5d5b927fd87 100644 --- a/setuptools/_reqs.py +++ b/setuptools/_reqs.py @@ -17,11 +17,13 @@ def parse_strings(strs: _StrOrIter) -> Iterator[str]: @overload -def parse(strs: _StrOrIter) -> Iterator[Requirement]: ... +def parse(strs: _StrOrIter) -> Iterator[Requirement]: + ... @overload -def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: ... +def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: + ... def parse(strs, parser=Requirement): diff --git a/setuptools/archive_util.py b/setuptools/archive_util.py index 3ab434cedcc..d8e10c13e15 100644 --- a/setuptools/archive_util.py +++ b/setuptools/archive_util.py @@ -1,23 +1,18 @@ """Utilities for extracting common archive formats""" -import contextlib +import zipfile +import tarfile import os -import posixpath import shutil -import tarfile -import zipfile +import posixpath +import contextlib from distutils.errors import DistutilsError from ._path import ensure_directory __all__ = [ - "unpack_archive", - "unpack_zipfile", - "unpack_tarfile", - "default_filter", - "UnrecognizedFormat", - "extraction_drivers", - "unpack_directory", + "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter", + "UnrecognizedFormat", "extraction_drivers", "unpack_directory", ] @@ -30,7 +25,9 @@ def default_filter(src, dst): return dst -def unpack_archive(filename, extract_dir, progress_filter=default_filter, drivers=None): +def unpack_archive( + filename, extract_dir, progress_filter=default_filter, + drivers=None): """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path @@ -59,11 +56,13 @@ def unpack_archive(filename, extract_dir, progress_filter=default_filter, driver else: return else: - raise UnrecognizedFormat("Not a recognized archive type: %s" % filename) + raise UnrecognizedFormat( + "Not a recognized archive type: %s" % filename + ) def unpack_directory(filename, extract_dir, progress_filter=default_filter): - """ "Unpack" a directory, using the same interface as for archives + """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ @@ -137,8 +136,7 @@ def _unpack_zipfile_obj(zipfile_obj, extract_dir, progress_filter=default_filter def _resolve_tar_file_or_dir(tar_obj, tar_member_obj): """Resolve any links and extract link targets as normal files.""" while tar_member_obj is not None and ( - tar_member_obj.islnk() or tar_member_obj.issym() - ): + tar_member_obj.islnk() or tar_member_obj.issym()): linkpath = tar_member_obj.linkname if tar_member_obj.issym(): base = posixpath.dirname(tar_member_obj.name) @@ -146,8 +144,9 @@ def _resolve_tar_file_or_dir(tar_obj, tar_member_obj): linkpath = posixpath.normpath(linkpath) tar_member_obj = tar_obj._getmember(linkpath) - is_file_or_dir = tar_member_obj is not None and ( - tar_member_obj.isfile() or tar_member_obj.isdir() + is_file_or_dir = ( + tar_member_obj is not None and + (tar_member_obj.isfile() or tar_member_obj.isdir()) ) if is_file_or_dir: return tar_member_obj @@ -199,9 +198,7 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): ) from e for member, final_dst in _iter_open_tar( - tarobj, - extract_dir, - progress_filter, + tarobj, extract_dir, progress_filter, ): try: # XXX Ugh diff --git a/setuptools/build_meta.py b/setuptools/build_meta.py index da640148210..ee8ef13faa1 100644 --- a/setuptools/build_meta.py +++ b/setuptools/build_meta.py @@ -26,39 +26,37 @@ Again, this is not a formal definition! Just a "taste" of the module. """ -import contextlib -import distutils import io import os import shlex -import shutil import sys -import tempfile import tokenize +import shutil +import contextlib +import tempfile import warnings -from distutils.util import strtobool from pathlib import Path from typing import Dict, Iterator, List, Optional, Union import setuptools - +import distutils from . import errors from ._path import same_path from ._reqs import parse_strings from .warnings import SetuptoolsDeprecationWarning +from distutils.util import strtobool + -__all__ = [ - 'get_requires_for_build_sdist', - 'get_requires_for_build_wheel', - 'prepare_metadata_for_build_wheel', - 'build_wheel', - 'build_sdist', - 'get_requires_for_build_editable', - 'prepare_metadata_for_build_editable', - 'build_editable', - '__legacy__', - 'SetupRequirementsError', -] +__all__ = ['get_requires_for_build_sdist', + 'get_requires_for_build_wheel', + 'prepare_metadata_for_build_wheel', + 'build_wheel', + 'build_sdist', + 'get_requires_for_build_editable', + 'prepare_metadata_for_build_editable', + 'build_editable', + '__legacy__', + 'SetupRequirementsError'] SETUPTOOLS_ENABLE_FEATURES = os.getenv("SETUPTOOLS_ENABLE_FEATURES", "").lower() LEGACY_EDITABLE = "legacy-editable" in SETUPTOOLS_ENABLE_FEATURES.replace("_", "-") @@ -108,20 +106,21 @@ def no_install_setup_requires(): def _get_immediate_subdirectories(a_dir): - return [ - name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name)) - ] + return [name for name in os.listdir(a_dir) + if os.path.isdir(os.path.join(a_dir, name))] def _file_with_extension(directory, extension): - matching = (f for f in os.listdir(directory) if f.endswith(extension)) + matching = ( + f for f in os.listdir(directory) + if f.endswith(extension) + ) try: - (file,) = matching + file, = matching except ValueError: raise ValueError( 'No distribution was found. Ensure that `setup.py` ' - 'is not empty and that it calls `setup()`.' - ) + 'is not empty and that it calls `setup()`.') return file @@ -160,7 +159,6 @@ class _ConfigSettingsTranslator: """Translate ``config_settings`` into distutils-style command arguments. Only a limited number of options is currently supported. """ - # See pypa/setuptools#1928 pypa/setuptools#2491 def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]: @@ -369,15 +367,13 @@ def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path: msg = f"No {suffix} directory found in {metadata_directory}" raise errors.InternalError(msg) - def prepare_metadata_for_build_wheel( - self, metadata_directory, config_settings=None - ): + def prepare_metadata_for_build_wheel(self, metadata_directory, + config_settings=None): sys.argv = [ *sys.argv[:1], *self._global_args(config_settings), "dist_info", - "--output-dir", - metadata_directory, + "--output-dir", metadata_directory, "--keep-egg-info", ] with no_install_setup_requires(): @@ -386,9 +382,8 @@ def prepare_metadata_for_build_wheel( self._bubble_up_info_directory(metadata_directory, ".egg-info") return self._bubble_up_info_directory(metadata_directory, ".dist-info") - def _build_with_temp_dir( - self, setup_command, result_extension, result_directory, config_settings - ): + def _build_with_temp_dir(self, setup_command, result_extension, + result_directory, config_settings): result_directory = os.path.abspath(result_directory) # Build in a temporary directory, then copy to the target. @@ -399,14 +394,14 @@ def _build_with_temp_dir( *sys.argv[:1], *self._global_args(config_settings), *setup_command, - "--dist-dir", - tmp_dist_dir, + "--dist-dir", tmp_dist_dir, *self._arbitrary_args(config_settings), ] with no_install_setup_requires(): self.run_setup() - result_basename = _file_with_extension(tmp_dist_dir, result_extension) + result_basename = _file_with_extension( + tmp_dist_dir, result_extension) result_path = os.path.join(result_directory, result_basename) if os.path.exists(result_path): # os.rename will fail overwriting on non-Unix. @@ -415,18 +410,16 @@ def _build_with_temp_dir( return result_basename - def build_wheel( - self, wheel_directory, config_settings=None, metadata_directory=None - ): + def build_wheel(self, wheel_directory, config_settings=None, + metadata_directory=None): with suppress_known_deprecation(): - return self._build_with_temp_dir( - ['bdist_wheel'], '.whl', wheel_directory, config_settings - ) + return self._build_with_temp_dir(['bdist_wheel'], '.whl', + wheel_directory, config_settings) def build_sdist(self, sdist_directory, config_settings=None): - return self._build_with_temp_dir( - ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings - ) + return self._build_with_temp_dir(['sdist', '--formats', 'gztar'], + '.tar.gz', sdist_directory, + config_settings) def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]: if not metadata_directory: @@ -456,9 +449,8 @@ def build_editable( def get_requires_for_build_editable(self, config_settings=None): return self.get_requires_for_build_wheel(config_settings) - def prepare_metadata_for_build_editable( - self, metadata_directory, config_settings=None - ): + def prepare_metadata_for_build_editable(self, metadata_directory, + config_settings=None): return self.prepare_metadata_for_build_wheel( metadata_directory, config_settings ) @@ -475,12 +467,11 @@ class _BuildMetaLegacyBackend(_BuildMetaBackend): packaging mechanism, and will eventually be removed. """ - def run_setup(self, setup_script='setup.py'): # In order to maintain compatibility with scripts assuming that # the setup.py script is in a directory on the PYTHONPATH, inject # '' into sys.path. (pypa/setuptools#1642) - sys_path = list(sys.path) # Save the original path + sys_path = list(sys.path) # Save the original path script_dir = os.path.dirname(os.path.abspath(setup_script)) if script_dir not in sys.path: @@ -493,7 +484,8 @@ def run_setup(self, setup_script='setup.py'): sys.argv[0] = setup_script try: - super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script) + super(_BuildMetaLegacyBackend, + self).run_setup(setup_script=setup_script) finally: # While PEP 517 frontends should be calling each hook in a fresh # subprocess according to the standard (and thus it should not be diff --git a/setuptools/dep_util.py b/setuptools/dep_util.py index dc9ccf62c20..521eb716a5e 100644 --- a/setuptools/dep_util.py +++ b/setuptools/dep_util.py @@ -11,7 +11,8 @@ def newer_pairwise_group(sources_groups, targets): of 'newer_group()'. """ if len(sources_groups) != len(targets): - raise ValueError("'sources_group' and 'targets' must be the same length") + raise ValueError( + "'sources_group' and 'targets' must be the same length") # build a pair of lists (sources_groups, targets) where source is newer n_sources = [] diff --git a/setuptools/depends.py b/setuptools/depends.py index 8bbc0061853..adffd12db8c 100644 --- a/setuptools/depends.py +++ b/setuptools/depends.py @@ -1,22 +1,25 @@ +import sys +import marshal import contextlib import dis -import marshal -import sys from setuptools.extern.packaging import version +from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE from . import _imp -from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module -__all__ = ['Require', 'find_module', 'get_module_constant', 'extract_constant'] + +__all__ = [ + 'Require', 'find_module', 'get_module_constant', 'extract_constant' +] class Require: """A prerequisite to building or installing a distribution""" def __init__( - self, name, requested_version, module, homepage='', attribute=None, format=None - ): + self, name, requested_version, module, homepage='', + attribute=None, format=None): if format is None and requested_version is not None: format = version.Version @@ -37,12 +40,8 @@ def full_name(self): def version_ok(self, version): """Is 'version' sufficiently up-to-date?""" - return ( - self.attribute is None - or self.format is None - or str(version) != "unknown" - and self.format(version) >= self.requested_version - ) + return self.attribute is None or self.format is None or \ + str(version) != "unknown" and self.format(version) >= self.requested_version def get_version(self, paths=None, default="unknown"): """Get version number of installed module, 'None', or 'default' @@ -88,7 +87,6 @@ def maybe_close(f): def empty(): yield return - if not f: return empty() diff --git a/setuptools/discovery.py b/setuptools/discovery.py index d558395ae11..3110b72794f 100644 --- a/setuptools/discovery.py +++ b/setuptools/discovery.py @@ -39,16 +39,26 @@ import itertools import os -from distutils import log -from distutils.util import convert_path from fnmatch import fnmatchcase from glob import glob from pathlib import Path -from typing import (TYPE_CHECKING, Dict, Iterable, Iterator, List, Mapping, Optional, - Tuple, Union) +from typing import ( + TYPE_CHECKING, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Tuple, + Union +) import _distutils_hack.override # noqa: F401 +from distutils import log +from distutils.util import convert_path + _Path = Union[str, os.PathLike] StrIter = Iterator[str] @@ -90,7 +100,7 @@ def find( cls, where: _Path = '.', exclude: Iterable[str] = (), - include: Iterable[str] = ('*',), + include: Iterable[str] = ('*',) ) -> List[str]: """Return a list of all Python items (packages or modules, depending on the finder implementation) found within directory 'where'. @@ -352,8 +362,7 @@ def _explicitly_specified(self, ignore_ext_modules: bool) -> bool: self.dist.packages is not None or self.dist.py_modules is not None or ext_modules - or hasattr(self.dist, "configuration") - and self.dist.configuration + or hasattr(self.dist, "configuration") and self.dist.configuration # ^ Some projects use numpy.distutils.misc_util.Configuration ) @@ -545,7 +554,7 @@ def find_parent_package( packages = sorted(packages, key=len) common_ancestors = [] for i, name in enumerate(packages): - if not all(n.startswith(f"{name}.") for n in packages[i + 1 :]): + if not all(n.startswith(f"{name}.") for n in packages[i+1:]): # Since packages are sorted by length, this condition is able # to find a list of all common ancestors. # When there is divergence (e.g. multiple root packages) diff --git a/setuptools/dist.py b/setuptools/dist.py index e25908ff10b..4458a580337 100644 --- a/setuptools/dist.py +++ b/setuptools/dist.py @@ -1,39 +1,46 @@ __all__ = ['Distribution'] -import distutils.cmd -import distutils.command -import distutils.core -import distutils.dist -import distutils.log import io -import itertools -import numbers -import os -import re import sys -import textwrap -from collections import defaultdict -from contextlib import suppress +import re +import os +import numbers +import distutils.log +import distutils.core +import distutils.cmd +import distutils.dist +import distutils.command +from distutils.util import strtobool from distutils.debug import DEBUG -from distutils.errors import DistutilsOptionError, DistutilsSetupError from distutils.fancy_getopt import translate_longopt -from distutils.util import rfc822_escape, strtobool -from email import message_from_file from glob import iglob +import itertools +import textwrap +from contextlib import suppress +from typing import List, Optional, Set, TYPE_CHECKING from pathlib import Path -from typing import TYPE_CHECKING, List, Optional, Set + +from collections import defaultdict +from email import message_from_file + +from distutils.errors import DistutilsOptionError, DistutilsSetupError +from distutils.util import rfc822_escape + +from setuptools.extern import packaging +from setuptools.extern import ordered_set +from setuptools.extern.more_itertools import unique_everseen, partition import setuptools import setuptools.command from setuptools import windows_support -from setuptools.config import pyprojecttoml, setupcfg -from setuptools.discovery import ConfigDiscovery -from setuptools.extern import ordered_set, packaging -from setuptools.extern.more_itertools import partition, unique_everseen -from setuptools.extern.packaging import version from setuptools.monkey import get_unpatched +from setuptools.config import setupcfg, pyprojecttoml +from setuptools.discovery import ConfigDiscovery -from . import _entry_points, _normalization, _reqs +from setuptools.extern.packaging import version +from . import _reqs +from . import _entry_points +from . import _normalization from ._importlib import metadata from .warnings import InformationOnly, SetuptoolsDeprecationWarning @@ -109,8 +116,9 @@ def read_pkg_file(self, file): self.license = _read_field_unescaped_from_msg(msg, 'license') self.long_description = _read_field_unescaped_from_msg(msg, 'description') - if self.long_description is None and self.metadata_version >= version.Version( - '2.1' + if ( + self.long_description is None and + self.metadata_version >= version.Version('2.1') ): self.long_description = _read_payload_from_msg(msg) self.description = _read_field_from_msg(msg, 'summary') @@ -268,7 +276,7 @@ def check_nsp(dist, attr, value): SetuptoolsDeprecationWarning.emit( "The namespace_packages parameter is deprecated.", "Please replace its usage with implicit namespaces (PEP 420).", - see_docs="references/keywords.html#keyword-namespace-packages", + see_docs="references/keywords.html#keyword-namespace-packages" # TODO: define due_date, it may break old packages that are no longer # maintained (e.g. sphinxcontrib extensions) when installed from source. # Warning officially introduced in May 2022, however the deprecation @@ -748,7 +756,7 @@ def _parse_config_files(self, filenames=None): # noqa: C901 # If there was a "global" section in the config file, use it # to set Distribution options. - for opt, (src, val) in self.command_options['global'].items(): + for (opt, (src, val)) in self.command_options['global'].items(): alias = self.negative_opt.get(opt) if alias: val = not strtobool(val) @@ -768,12 +776,10 @@ def warn_dash_deprecation(self, opt, section): return opt underscore_opt = opt.replace('-', '_') - commands = list( - itertools.chain( - distutils.command.__all__, - self._setuptools_commands(), - ) - ) + commands = list(itertools.chain( + distutils.command.__all__, + self._setuptools_commands(), + )) if ( not section.startswith('options') and section != 'metadata' @@ -837,7 +843,7 @@ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 if DEBUG: self.announce(" setting options for '%s' command:" % command_name) - for option, (source, value) in option_dict.items(): + for (option, (source, value)) in option_dict.items(): if DEBUG: self.announce(" %s = %s (from %s)" % (option, value, source)) try: diff --git a/setuptools/errors.py b/setuptools/errors.py index ea28a268218..ec7fb3b6c48 100644 --- a/setuptools/errors.py +++ b/setuptools/errors.py @@ -5,6 +5,7 @@ from distutils import errors as _distutils_errors + # Re-export errors from distutils to facilitate the migration to PEP632 ByteCompileError = _distutils_errors.DistutilsByteCompileError diff --git a/setuptools/extension.py b/setuptools/extension.py index b37cb458b32..58c023f6b44 100644 --- a/setuptools/extension.py +++ b/setuptools/extension.py @@ -1,8 +1,8 @@ +import re +import functools import distutils.core import distutils.errors import distutils.extension -import functools -import re from .monkey import get_unpatched diff --git a/setuptools/glob.py b/setuptools/glob.py index 9d9c2f485eb..87062b8187f 100644 --- a/setuptools/glob.py +++ b/setuptools/glob.py @@ -6,9 +6,9 @@ * Hidden files are not ignored. """ -import fnmatch import os import re +import fnmatch __all__ = ["glob", "iglob", "escape"] @@ -155,7 +155,8 @@ def _isrecursive(pattern): def escape(pathname): - """Escape all special characters.""" + """Escape all special characters. + """ # Escaping is done by wrapping any of "*?[" between square brackets. # Metacharacters do not work in the drive part and shouldn't be escaped. drive, pathname = os.path.splitdrive(pathname) diff --git a/setuptools/installer.py b/setuptools/installer.py index 1f46b024896..44ed0da2a37 100644 --- a/setuptools/installer.py +++ b/setuptools/installer.py @@ -8,8 +8,8 @@ from functools import partial from . import _reqs -from .warnings import SetuptoolsDeprecationWarning from .wheel import Wheel +from .warnings import SetuptoolsDeprecationWarning def _fixup_find_links(find_links): @@ -55,10 +55,8 @@ def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # # take precedence. opts = dist.get_option_dict('easy_install') if 'allow_hosts' in opts: - raise DistutilsError( - 'the `allow-hosts` option is not supported ' - 'when using pip to install requirements.' - ) + raise DistutilsError('the `allow-hosts` option is not supported ' + 'when using pip to install requirements.') quiet = 'PIP_QUIET' not in os.environ and 'PIP_VERBOSE' not in os.environ if 'PIP_INDEX_URL' in os.environ: index_url = None @@ -67,7 +65,8 @@ def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # else: index_url = None find_links = ( - _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts else [] + _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts + else [] ) if dist.dependency_links: find_links.extend(dist.dependency_links) @@ -78,14 +77,10 @@ def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # return egg_dist with tempfile.TemporaryDirectory() as tmpdir: cmd = [ - sys.executable, - '-m', - 'pip', + sys.executable, '-m', 'pip', '--disable-pip-version-check', - 'wheel', - '--no-deps', - '-w', - tmpdir, + 'wheel', '--no-deps', + '-w', tmpdir, ] if quiet: cmd.append('--quiet') @@ -105,11 +100,9 @@ def _fetch_build_egg_no_warn(dist, req): # noqa: C901 # is too complex (16) # dist_location = os.path.join(eggs_dir, wheel.egg_name()) wheel.install_as_egg(dist_location) dist_metadata = pkg_resources.PathMetadata( - dist_location, os.path.join(dist_location, 'EGG-INFO') - ) + dist_location, os.path.join(dist_location, 'EGG-INFO')) dist = pkg_resources.Distribution.from_filename( - dist_location, metadata=dist_metadata - ) + dist_location, metadata=dist_metadata) return dist diff --git a/setuptools/launch.py b/setuptools/launch.py index 56c7d035f10..0208fdf33b6 100644 --- a/setuptools/launch.py +++ b/setuptools/launch.py @@ -6,8 +6,8 @@ # Note that setuptools gets imported implicitly by the # invocation of this script using python -m setuptools.launch -import sys import tokenize +import sys def run(): diff --git a/setuptools/logging.py b/setuptools/logging.py index af72e170ae9..0653878fc03 100644 --- a/setuptools/logging.py +++ b/setuptools/logging.py @@ -1,8 +1,7 @@ -import distutils.log +import sys import inspect import logging -import sys - +import distutils.log from . import monkey @@ -23,8 +22,7 @@ def configure(): out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( - format="{message}", style='{', handlers=handlers, level=logging.DEBUG - ) + format="{message}", style='{', handlers=handlers, level=logging.DEBUG) if inspect.ismodule(distutils.dist.log): monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` @@ -35,5 +33,5 @@ def configure(): def set_threshold(level): - logging.root.setLevel(level * 10) + logging.root.setLevel(level*10) return set_threshold.unpatched(level) diff --git a/setuptools/monkey.py b/setuptools/monkey.py index e16156bca5c..50653fc7ee4 100644 --- a/setuptools/monkey.py +++ b/setuptools/monkey.py @@ -2,13 +2,13 @@ Monkey patching of distutils. """ +import sys import distutils.filelist -import functools -import inspect import platform -import sys import types +import functools from importlib import import_module +import inspect import setuptools @@ -35,13 +35,9 @@ def _get_mro(cls): def get_unpatched(item): lookup = ( - get_unpatched_class - if isinstance(item, type) - else ( - get_unpatched_function - if isinstance(item, types.FunctionType) - else lambda item: None - ) + get_unpatched_class if isinstance(item, type) else + get_unpatched_function if isinstance(item, types.FunctionType) else + lambda item: None ) return lookup(item) @@ -53,7 +49,9 @@ def get_unpatched_class(cls): first. """ external_bases = ( - cls for cls in _get_mro(cls) if not cls.__module__.startswith('setuptools') + cls + for cls in _get_mro(cls) + if not cls.__module__.startswith('setuptools') ) base = next(external_bases) if not base.__module__.startswith('distutils'): @@ -72,10 +70,11 @@ def patch_all(): # fix findall bug in distutils (http://bugs.python.org/issue12885) distutils.filelist.findall = setuptools.findall - needs_warehouse = (3, 4) < sys.version_info < (3, 4, 6) or ( - 3, - 5, - ) < sys.version_info <= (3, 5, 3) + needs_warehouse = ( + (3, 4) < sys.version_info < (3, 4, 6) + or + (3, 5) < sys.version_info <= (3, 5, 3) + ) if needs_warehouse: warehouse = 'https://upload.pypi.org/legacy/' diff --git a/setuptools/msvc.py b/setuptools/msvc.py index ef953070e07..4a08dffe36e 100644 --- a/setuptools/msvc.py +++ b/setuptools/msvc.py @@ -11,17 +11,16 @@ This may also support compilers shipped with compatible Visual Studio versions. """ -import contextlib -import distutils.errors -import itertools import json -import platform -import subprocess from io import open from os import listdir, pathsep -from os.path import dirname, isdir, isfile, join +from os.path import join, isfile, isdir, dirname from subprocess import CalledProcessError - +import contextlib +import platform +import itertools +import subprocess +import distutils.errors from setuptools.extern.more_itertools import unique_everseen if platform.system() == 'Windows': @@ -46,7 +45,7 @@ def _msvc14_find_vc2015(): winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\VisualStudio\SxS\VC7", 0, - winreg.KEY_READ | winreg.KEY_WOW64_32KEY, + winreg.KEY_READ | winreg.KEY_WOW64_32KEY ) except OSError: return None, None @@ -93,25 +92,14 @@ def _msvc14_find_vc2017(): for component in suitable_components: # Workaround for `-requiresAny` (only available on VS 2017 > 15.6) with contextlib.suppress(CalledProcessError, OSError, UnicodeDecodeError): - path = ( - subprocess.check_output( - [ - join( - root, "Microsoft Visual Studio", "Installer", "vswhere.exe" - ), - "-latest", - "-prerelease", - "-requires", - component, - "-property", - "installationPath", - "-products", - "*", - ] - ) - .decode(encoding="mbcs", errors="strict") - .strip() - ) + path = subprocess.check_output([ + join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"), + "-latest", + "-prerelease", + "-requires", component, + "-property", "installationPath", + "-products", "*", + ]).decode(encoding="mbcs", errors="strict").strip() path = join(path, "VC", "Auxiliary", "Build") if isdir(path): @@ -124,7 +112,7 @@ def _msvc14_find_vc2017(): 'x86': 'x86', 'x86_amd64': 'x64', 'x86_arm': 'arm', - 'x86_arm64': 'arm64', + 'x86_arm64': 'arm64' } @@ -139,20 +127,11 @@ def _msvc14_find_vcvarsall(plat_spec): vcruntime_plat = 'x64' if 'amd64' in plat_spec else 'x86' if best_dir: - vcredist = join( - best_dir, - "..", - "..", - "redist", - "MSVC", - "**", - vcruntime_plat, - "Microsoft.VC14*.CRT", - "vcruntime140.dll", - ) + vcredist = join(best_dir, "..", "..", "redist", "MSVC", "**", + vcruntime_plat, "Microsoft.VC14*.CRT", + "vcruntime140.dll") try: import glob - vcruntime = glob.glob(vcredist, recursive=True)[-1] except (ImportError, OSError, LookupError): vcruntime = None @@ -160,13 +139,8 @@ def _msvc14_find_vcvarsall(plat_spec): if not best_dir: best_version, best_dir = _msvc14_find_vc2015() if best_version: - vcruntime = join( - best_dir, - 'redist', - vcruntime_plat, - "Microsoft.VC140.CRT", - "vcruntime140.dll", - ) + vcruntime = join(best_dir, 'redist', vcruntime_plat, + "Microsoft.VC140.CRT", "vcruntime140.dll") if not best_dir: return None, None @@ -184,11 +158,16 @@ def _msvc14_find_vcvarsall(plat_spec): def _msvc14_get_vc_env(plat_spec): """Python 3.8 "distutils/_msvccompiler.py" backport""" if "DISTUTILS_USE_SDK" in environ: - return {key.lower(): value for key, value in environ.items()} + return { + key.lower(): value + for key, value in environ.items() + } vcvarsall, vcruntime = _msvc14_find_vcvarsall(plat_spec) if not vcvarsall: - raise distutils.errors.DistutilsPlatformError("Unable to find vcvarsall.bat") + raise distutils.errors.DistutilsPlatformError( + "Unable to find vcvarsall.bat" + ) try: out = subprocess.check_output( @@ -202,7 +181,8 @@ def _msvc14_get_vc_env(plat_spec): env = { key.lower(): value - for key, _, value in (line.partition('=') for line in out.splitlines()) + for key, _, value in + (line.partition('=') for line in out.splitlines()) if key and value } @@ -267,13 +247,11 @@ def _augment_exception(exc, version, arch=''): message += msdownload % 8279 elif version >= 14.0: # For VC++ 14.X Redirect user to latest Visual C++ Build Tools - message += ( - ' Get it with "Microsoft C++ Build Tools": ' - r'https://visualstudio.microsoft.com' - r'/visual-cpp-build-tools/' - ) + message += (' Get it with "Microsoft C++ Build Tools": ' + r'https://visualstudio.microsoft.com' + r'/visual-cpp-build-tools/') - exc.args = (message,) + exc.args = (message, ) class PlatformInfo: @@ -285,7 +263,6 @@ class PlatformInfo: arch: str Target architecture. """ - current_cpu = environ.get('processor_architecture', '').lower() def __init__(self, arch): @@ -301,7 +278,7 @@ def target_cpu(self): str Target CPU """ - return self.arch[self.arch.find('_') + 1 :] + return self.arch[self.arch.find('_') + 1:] def target_is_x86(self): """ @@ -342,13 +319,9 @@ def current_dir(self, hidex86=False, x64=False): subfolder: '\target', or '' (see hidex86 parameter) """ return ( - '' - if (self.current_cpu == 'x86' and hidex86) - else ( - r'\x64' - if (self.current_cpu == 'amd64' and x64) - else r'\%s' % self.current_cpu - ) + '' if (self.current_cpu == 'x86' and hidex86) else + r'\x64' if (self.current_cpu == 'amd64' and x64) else + r'\%s' % self.current_cpu ) def target_dir(self, hidex86=False, x64=False): @@ -368,13 +341,9 @@ def target_dir(self, hidex86=False, x64=False): subfolder: '\current', or '' (see hidex86 parameter) """ return ( - '' - if (self.target_cpu == 'x86' and hidex86) - else ( - r'\x64' - if (self.target_cpu == 'amd64' and x64) - else r'\%s' % self.target_cpu - ) + '' if (self.target_cpu == 'x86' and hidex86) else + r'\x64' if (self.target_cpu == 'amd64' and x64) else + r'\%s' % self.target_cpu ) def cross_dir(self, forcex86=False): @@ -395,9 +364,8 @@ def cross_dir(self, forcex86=False): """ current = 'x86' if forcex86 else self.current_cpu return ( - '' - if self.target_cpu == current - else self.target_dir().replace('\\', '\\%s_' % current) + '' if self.target_cpu == current else + self.target_dir().replace('\\', '\\%s_' % current) ) @@ -410,13 +378,10 @@ class RegistryInfo: platform_info: PlatformInfo "PlatformInfo" instance. """ - - HKEYS = ( - winreg.HKEY_USERS, - winreg.HKEY_CURRENT_USER, - winreg.HKEY_LOCAL_MACHINE, - winreg.HKEY_CLASSES_ROOT, - ) + HKEYS = (winreg.HKEY_USERS, + winreg.HKEY_CURRENT_USER, + winreg.HKEY_LOCAL_MACHINE, + winreg.HKEY_CLASSES_ROOT) def __init__(self, platform_info): self.pi = platform_info @@ -614,7 +579,8 @@ def __init__(self, registry_info, vc_ver=None): self.known_vs_paths = self.find_programdata_vs_vers() # Except for VS15+, VC version is aligned with VS version - self.vs_ver = self.vc_ver = vc_ver or self._find_latest_available_vs_ver() + self.vs_ver = self.vc_ver = ( + vc_ver or self._find_latest_available_vs_ver()) def _find_latest_available_vs_ver(self): """ @@ -629,8 +595,7 @@ def _find_latest_available_vs_ver(self): if not (reg_vc_vers or self.known_vs_paths): raise distutils.errors.DistutilsPlatformError( - 'No Microsoft Visual C++ version found' - ) + 'No Microsoft Visual C++ version found') vc_vers = set(reg_vc_vers) vc_vers.update(self.known_vs_paths) @@ -678,7 +643,8 @@ def find_programdata_vs_vers(self): float version as key, path as value. """ vs_versions = {} - instances_dir = r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances' + instances_dir = \ + r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances' try: hashed_names = listdir(instances_dir) @@ -699,9 +665,8 @@ def find_programdata_vs_vers(self): listdir(join(vs_path, r'VC\Tools\MSVC')) # Store version and path - vs_versions[self._as_float_version(state['installationVersion'])] = ( - vs_path - ) + vs_versions[self._as_float_version( + state['installationVersion'])] = vs_path except (OSError, IOError, KeyError): # Skip if "state.json" file is missing or bad format @@ -737,9 +702,8 @@ def VSInstallDir(self): path """ # Default path - default = join( - self.ProgramFilesx86, 'Microsoft Visual Studio %0.1f' % self.vs_ver - ) + default = join(self.ProgramFilesx86, + 'Microsoft Visual Studio %0.1f' % self.vs_ver) # Try to get path from registry, if fail use default path return self.ri.lookup(self.ri.vs, '%0.1f' % self.vs_ver) or default @@ -801,9 +765,8 @@ def _guess_vc_legacy(self): str path """ - default = join( - self.ProgramFilesx86, r'Microsoft Visual Studio %0.1f\VC' % self.vs_ver - ) + default = join(self.ProgramFilesx86, + r'Microsoft Visual Studio %0.1f\VC' % self.vs_ver) # Try to get "VC++ for Python" path from registry as default path reg_path = join(self.ri.vc_for_python, '%0.1f' % self.vs_ver) @@ -872,7 +835,7 @@ def WindowsSdkDir(self): # noqa: C901 # is too complex (12) # FIXME if not sdkdir or not isdir(sdkdir): # If fail, use default new path for ver in self.WindowsSdkVersion: - intver = ver[: ver.rfind('.')] + intver = ver[:ver.rfind('.')] path = r'Microsoft SDKs\Windows Kits\%s' % intver d = join(self.ProgramFiles, path) if isdir(d): @@ -952,7 +915,8 @@ def UniversalCRTSdkDir(self): # Find path of the more recent Kit for ver in vers: - sdkdir = self.ri.lookup(self.ri.windows_kits_roots, 'kitsroot%s' % ver) + sdkdir = self.ri.lookup(self.ri.windows_kits_roots, + 'kitsroot%s' % ver) if sdkdir: return sdkdir or '' @@ -979,11 +943,10 @@ def NetFxSdkVersion(self): versions """ # Set FxSdk versions for specified VS version - return ( - ('4.7.2', '4.7.1', '4.7', '4.6.2', '4.6.1', '4.6', '4.5.2', '4.5.1', '4.5') - if self.vs_ver >= 14.0 - else () - ) + return (('4.7.2', '4.7.1', '4.7', + '4.6.2', '4.6.1', '4.6', + '4.5.2', '4.5.1', '4.5') + if self.vs_ver >= 14.0 else ()) @property def NetFxSdkDir(self): @@ -1108,7 +1071,8 @@ def _use_last_dir_name(path, prefix=''): matching_dirs = ( dir_name for dir_name in reversed(listdir(path)) - if isdir(join(path, dir_name)) and dir_name.startswith(prefix) + if isdir(join(path, dir_name)) and + dir_name.startswith(prefix) ) return next(matching_dirs, None) or '' @@ -1200,10 +1164,8 @@ def VCIncludes(self): list of str paths """ - return [ - join(self.si.VCInstallDir, 'Include'), - join(self.si.VCInstallDir, r'ATLMFC\Include'), - ] + return [join(self.si.VCInstallDir, 'Include'), + join(self.si.VCInstallDir, r'ATLMFC\Include')] @property def VCLibraries(self): @@ -1263,15 +1225,14 @@ def VCTools(self): tools += [join(si.VCInstallDir, path)] elif self.vs_ver >= 15.0: - host_dir = ( - r'bin\HostX86%s' if self.pi.current_is_x86() else r'bin\HostX64%s' - ) - tools += [join(si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))] + host_dir = (r'bin\HostX86%s' if self.pi.current_is_x86() else + r'bin\HostX64%s') + tools += [join( + si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))] if self.pi.current_cpu != self.pi.target_cpu: - tools += [ - join(si.VCInstallDir, host_dir % self.pi.current_dir(x64=True)) - ] + tools += [join( + si.VCInstallDir, host_dir % self.pi.current_dir(x64=True))] else: tools += [join(si.VCInstallDir, 'Bin')] @@ -1318,11 +1279,9 @@ def OSIncludes(self): sdkver = self._sdk_subdir else: sdkver = '' - return [ - join(include, '%sshared' % sdkver), - join(include, '%sum' % sdkver), - join(include, '%swinrt' % sdkver), - ] + return [join(include, '%sshared' % sdkver), + join(include, '%sum' % sdkver), + join(include, '%swinrt' % sdkver)] @property def OSLibpath(self): @@ -1347,18 +1306,16 @@ def OSLibpath(self): libpath += [ ref, join(self.si.WindowsSdkDir, 'UnionMetadata'), - join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'), + join( + ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'), join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'), - join(ref, 'Windows.Networking.Connectivity.WwanContract', '1.0.0.0'), join( - self.si.WindowsSdkDir, - 'ExtensionSDKs', - 'Microsoft.VCLibs', - '%0.1f' % self.vs_ver, - 'References', - 'CommonConfiguration', - 'neutral', - ), + ref, 'Windows.Networking.Connectivity.WwanContract', + '1.0.0.0'), + join( + self.si.WindowsSdkDir, 'ExtensionSDKs', 'Microsoft.VCLibs', + '%0.1f' % self.vs_ver, 'References', 'CommonConfiguration', + 'neutral'), ] return libpath @@ -1459,9 +1416,11 @@ def FxTools(self): tools = [] if include32: - tools += [join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32] + tools += [join(si.FrameworkDir32, ver) + for ver in si.FrameworkVersion32] if include64: - tools += [join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64] + tools += [join(si.FrameworkDir64, ver) + for ver in si.FrameworkVersion64] return tools @property @@ -1637,11 +1596,9 @@ def VCRuntimeRedist(self): prefixes += [join(tools_path, 'redist')] # VS14 legacy path # CRT directory - crt_dirs = ( - 'Microsoft.VC%d.CRT' % (self.vc_ver * 10), - # Sometime store in directory with VS version instead of VC - 'Microsoft.VC%d.CRT' % (int(self.vs_ver) * 10), - ) + crt_dirs = ('Microsoft.VC%d.CRT' % (self.vc_ver * 10), + # Sometime store in directory with VS version instead of VC + 'Microsoft.VC%d.CRT' % (int(self.vs_ver) * 10)) # vcruntime path for prefix, crt_dir in itertools.product(prefixes, crt_dirs): @@ -1664,47 +1621,36 @@ def return_env(self, exists=True): environment """ env = dict( - include=self._build_paths( - 'include', - [ - self.VCIncludes, - self.OSIncludes, - self.UCRTIncludes, - self.NetFxSDKIncludes, - ], - exists, - ), - lib=self._build_paths( - 'lib', - [ - self.VCLibraries, - self.OSLibraries, - self.FxTools, - self.UCRTLibraries, - self.NetFxSDKLibraries, - ], - exists, - ), - libpath=self._build_paths( - 'libpath', - [self.VCLibraries, self.FxTools, self.VCStoreRefs, self.OSLibpath], - exists, - ), - path=self._build_paths( - 'path', - [ - self.VCTools, - self.VSTools, - self.VsTDb, - self.SdkTools, - self.SdkSetup, - self.FxTools, - self.MSBuild, - self.HTMLHelpWorkshop, - self.FSharp, - ], - exists, - ), + include=self._build_paths('include', + [self.VCIncludes, + self.OSIncludes, + self.UCRTIncludes, + self.NetFxSDKIncludes], + exists), + lib=self._build_paths('lib', + [self.VCLibraries, + self.OSLibraries, + self.FxTools, + self.UCRTLibraries, + self.NetFxSDKLibraries], + exists), + libpath=self._build_paths('libpath', + [self.VCLibraries, + self.FxTools, + self.VCStoreRefs, + self.OSLibpath], + exists), + path=self._build_paths('path', + [self.VCTools, + self.VSTools, + self.VsTDb, + self.SdkTools, + self.SdkSetup, + self.FxTools, + self.MSBuild, + self.HTMLHelpWorkshop, + self.FSharp], + exists), ) if self.vs_ver >= 14 and isfile(self.VCRuntimeRedist): env['py_vcruntime_redist'] = self.VCRuntimeRedist diff --git a/setuptools/namespaces.py b/setuptools/namespaces.py index 37f8ab9e221..44939e1c6d4 100644 --- a/setuptools/namespaces.py +++ b/setuptools/namespaces.py @@ -1,6 +1,7 @@ -import itertools import os from distutils import log +import itertools + flatten = itertools.chain.from_iterable @@ -51,13 +52,18 @@ def _get_target(self): "importlib.machinery.PathFinder.find_spec(%(pkg)r, " "[os.path.dirname(p)])))" ), - ("m = m or " "sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"), + ( + "m = m or " + "sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))" + ), "mp = (m or []) and m.__dict__.setdefault('__path__',[])", "(p not in mp) and mp.append(p)", ) "lines for the namespace installer" - _nspkg_tmpl_multi = ('m and setattr(sys.modules[%(parent)r], %(child)r, m)',) + _nspkg_tmpl_multi = ( + 'm and setattr(sys.modules[%(parent)r], %(child)r, m)', + ) "additional line(s) when a parent package is indicated" def _get_root(self): diff --git a/setuptools/py312compat.py b/setuptools/py312compat.py index d15aee0d7ff..28175b1f750 100644 --- a/setuptools/py312compat.py +++ b/setuptools/py312compat.py @@ -1,5 +1,5 @@ -import shutil import sys +import shutil def shutil_rmtree(path, ignore_errors=False, onexc=None): diff --git a/setuptools/sandbox.py b/setuptools/sandbox.py index db36f5d8643..017c897b86a 100644 --- a/setuptools/sandbox.py +++ b/setuptools/sandbox.py @@ -1,17 +1,17 @@ -import builtins -import contextlib -import functools -import itertools -import operator import os -import pickle -import re import sys import tempfile +import operator +import functools +import itertools +import re +import contextlib +import pickle import textwrap -from distutils.errors import DistutilsError +import builtins import pkg_resources +from distutils.errors import DistutilsError from pkg_resources import working_set if sys.platform.startswith('java'): diff --git a/setuptools/unicode_utils.py b/setuptools/unicode_utils.py index d9edd6d17fc..e84e65e3e14 100644 --- a/setuptools/unicode_utils.py +++ b/setuptools/unicode_utils.py @@ -1,5 +1,5 @@ -import sys import unicodedata +import sys # HFS Plus uses decomposed UTF-8 diff --git a/setuptools/warnings.py b/setuptools/warnings.py index b3e252ca57d..4ea782e5099 100644 --- a/setuptools/warnings.py +++ b/setuptools/warnings.py @@ -29,7 +29,7 @@ def emit( see_docs: Optional[str] = None, see_url: Optional[str] = None, stacklevel: int = 2, - **kwargs, + **kwargs ): """Private: reserved for ``setuptools`` internal use only""" # Default values: @@ -63,16 +63,15 @@ def _format( ( f"\nBy {due_date:%Y-%b-%d}, you need to update your project and remove " "deprecated calls\nor your builds will no longer be supported." - if due_date and due_date > today - else None + if due_date and due_date > today else None ), ( "\nThis deprecation is overdue, please update your project and remove " "deprecated\ncalls to avoid build errors in the future." - if due_date and due_date < today - else None + if due_date and due_date < today else None ), - (f"\nSee {see_url} for details." if see_url else None), + (f"\nSee {see_url} for details." if see_url else None) + ] parts = [x for x in possible_parts if x] if parts: diff --git a/setuptools/wheel.py b/setuptools/wheel.py index 2551e2901e3..850e43cd010 100644 --- a/setuptools/wheel.py +++ b/setuptools/wheel.py @@ -1,30 +1,32 @@ """Wheels support.""" -import contextlib import email -import functools import itertools +import functools import os import posixpath import re import zipfile +import contextlib + from distutils.util import get_platform import setuptools -from setuptools.archive_util import _unpack_zipfile_obj -from setuptools.command.egg_info import _egg_basename, write_requirements +from setuptools.extern.packaging.version import Version as parse_version from setuptools.extern.packaging.tags import sys_tags from setuptools.extern.packaging.utils import canonicalize_name -from setuptools.extern.packaging.version import Version as parse_version +from setuptools.command.egg_info import write_requirements, _egg_basename +from setuptools.archive_util import _unpack_zipfile_obj + WHEEL_NAME = re.compile( r"""^(?P.+?)-(?P\d.*?) ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) )\.whl$""", - re.VERBOSE, -).match + re.VERBOSE).match -NAMESPACE_PACKAGE_INIT = "__import__('pkg_resources').declare_namespace(__name__)\n" +NAMESPACE_PACKAGE_INIT = \ + "__import__('pkg_resources').declare_namespace(__name__)\n" @functools.lru_cache(maxsize=None) @@ -63,7 +65,6 @@ def disable_info_traces(): Temporarily disable info traces. """ from distutils import log - saved = log.set_threshold(log.WARN) try: yield @@ -94,22 +95,19 @@ def is_compatible(self): return next((True for t in self.tags() if t in _get_supported_tags()), False) def egg_name(self): - return ( - _egg_basename( - self.project_name, - self.version, - platform=(None if self.platform == 'any' else get_platform()), - ) - + ".egg" - ) + return _egg_basename( + self.project_name, + self.version, + platform=(None if self.platform == 'any' else get_platform()), + ) + ".egg" def get_dist_info(self, zf): # find the correct name of the .dist-info dir in the wheel file for member in zf.namelist(): dirname = posixpath.dirname(member) - if dirname.endswith('.dist-info') and canonicalize_name(dirname).startswith( - canonicalize_name(self.project_name) - ): + if (dirname.endswith('.dist-info') and + canonicalize_name(dirname).startswith( + canonicalize_name(self.project_name))): return dirname raise ValueError("unsupported wheel format. .dist-info not found") @@ -140,16 +138,18 @@ def get_metadata(name): wheel_metadata = get_metadata('WHEEL') # Check wheel format version is supported. wheel_version = parse_version(wheel_metadata.get('Wheel-Version')) - wheel_v1 = parse_version('1.0') <= wheel_version < parse_version('2.0dev0') + wheel_v1 = ( + parse_version('1.0') <= wheel_version < parse_version('2.0dev0') + ) if not wheel_v1: - raise ValueError('unsupported wheel format version: %s' % wheel_version) + raise ValueError( + 'unsupported wheel format version: %s' % wheel_version) # Extract to target directory. _unpack_zipfile_obj(zf, destination_eggdir) # Convert metadata. dist_info = os.path.join(destination_eggdir, dist_info) dist = pkg_resources.Distribution.from_location( - destination_eggdir, - dist_info, + destination_eggdir, dist_info, metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info), ) @@ -159,7 +159,6 @@ def get_metadata(name): def raw_req(req): req.marker = None return str(req) - install_requires = list(map(raw_req, dist.requires())) extras_require = { extra: [ @@ -193,7 +192,8 @@ def _move_data_entries(destination_eggdir, dist_data): dist_data = os.path.join(destination_eggdir, dist_data) dist_data_scripts = os.path.join(dist_data, 'scripts') if os.path.exists(dist_data_scripts): - egg_info_scripts = os.path.join(destination_eggdir, 'EGG-INFO', 'scripts') + egg_info_scripts = os.path.join( + destination_eggdir, 'EGG-INFO', 'scripts') os.mkdir(egg_info_scripts) for entry in os.listdir(dist_data_scripts): # Remove bytecode, as it's not properly handled @@ -206,20 +206,18 @@ def _move_data_entries(destination_eggdir, dist_data): os.path.join(egg_info_scripts, entry), ) os.rmdir(dist_data_scripts) - for subdir in filter( - os.path.exists, - ( - os.path.join(dist_data, d) - for d in ('data', 'headers', 'purelib', 'platlib') - ), - ): + for subdir in filter(os.path.exists, ( + os.path.join(dist_data, d) + for d in ('data', 'headers', 'purelib', 'platlib') + )): unpack(subdir, destination_eggdir) if os.path.exists(dist_data): os.rmdir(dist_data) @staticmethod def _fix_namespace_packages(egg_info, destination_eggdir): - namespace_packages = os.path.join(egg_info, 'namespace_packages.txt') + namespace_packages = os.path.join( + egg_info, 'namespace_packages.txt') if os.path.exists(namespace_packages): with open(namespace_packages) as fp: namespace_packages = fp.read().split() diff --git a/setuptools/windows_support.py b/setuptools/windows_support.py index fdadeb597ca..1ca64fbb54f 100644 --- a/setuptools/windows_support.py +++ b/setuptools/windows_support.py @@ -17,7 +17,6 @@ def hide_file(path): `path` must be text. """ import ctypes - __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD