From 3d217cae2c410490dbf05c62b77a1509fc8b8d67 Mon Sep 17 00:00:00 2001 From: DongHun Kwak Date: Wed, 30 Dec 2020 07:08:21 +0900 Subject: [PATCH] Imported Upstream version 50.0.0 --- .bumpversion.cfg | 2 +- CHANGES.rst | 7 + _distutils_hack/__init__.py | 20 +- bootstrap.py | 2 - pavement.py | 7 +- pkg_resources/__init__.py | 39 +- .../_vendor/packaging/requirements.py | 2 +- pkg_resources/_vendor/six.py | 868 ------------------ pkg_resources/_vendor/vendored.txt | 1 - pkg_resources/extern/__init__.py | 2 +- pkg_resources/tests/test_pkg_resources.py | 38 +- pkg_resources/tests/test_resources.py | 4 - pkg_resources/tests/test_working_set.py | 2 - setup.cfg | 3 +- setup.py | 3 +- setuptools/__init__.py | 20 +- setuptools/_vendor/packaging/requirements.py | 2 +- setuptools/_vendor/six.py | 868 ------------------ setuptools/_vendor/vendored.txt | 1 - setuptools/build_meta.py | 21 +- setuptools/command/alias.py | 2 - setuptools/command/bdist_egg.py | 20 +- setuptools/command/build_ext.py | 16 +- setuptools/command/build_py.py | 8 +- setuptools/command/develop.py | 6 +- setuptools/command/easy_install.py | 55 +- setuptools/command/egg_info.py | 12 +- setuptools/command/py36compat.py | 2 - setuptools/command/rotate.py | 4 +- setuptools/command/sdist.py | 46 +- setuptools/command/setopt.py | 3 +- setuptools/command/test.py | 10 +- setuptools/command/upload_docs.py | 16 +- setuptools/config.py | 12 +- setuptools/depends.py | 13 +- setuptools/dist.py | 48 +- setuptools/extension.py | 2 - setuptools/extern/__init__.py | 2 +- setuptools/installer.py | 8 +- setuptools/lib2to3_ex.py | 3 - setuptools/monkey.py | 4 +- setuptools/msvc.py | 13 +- setuptools/namespaces.py | 4 - setuptools/package_index.py | 33 +- setuptools/py27compat.py | 60 -- setuptools/py31compat.py | 32 - setuptools/py33compat.py | 59 -- setuptools/sandbox.py | 15 +- setuptools/ssl_support.py | 5 +- setuptools/tests/__init__.py | 9 +- setuptools/tests/contexts.py | 6 +- setuptools/tests/namespaces.py | 2 - setuptools/tests/server.py | 21 +- setuptools/tests/test_archive_util.py | 6 +- setuptools/tests/test_build_ext.py | 4 +- setuptools/tests/test_build_meta.py | 20 +- setuptools/tests/test_config.py | 24 +- setuptools/tests/test_develop.py | 7 +- setuptools/tests/test_dist.py | 20 +- setuptools/tests/test_dist_info.py | 4 - setuptools/tests/test_distutils_adoption.py | 9 +- setuptools/tests/test_easy_install.py | 8 - setuptools/tests/test_egg_info.py | 52 +- setuptools/tests/test_extern.py | 2 - setuptools/tests/test_find_packages.py | 11 +- setuptools/tests/test_integration.py | 2 +- setuptools/tests/test_manifest.py | 6 +- setuptools/tests/test_msvc14.py | 2 - setuptools/tests/test_namespaces.py | 2 - setuptools/tests/test_packageindex.py | 11 +- setuptools/tests/test_sdist.py | 77 +- setuptools/tests/test_setopt.py | 10 +- setuptools/tests/test_setuptools.py | 3 +- setuptools/tests/test_test.py | 5 - setuptools/tests/test_virtualenv.py | 11 - setuptools/tests/test_wheel.py | 2 - setuptools/tests/test_windows_wrappers.py | 2 - setuptools/tests/text.py | 5 - setuptools/tests/textwrap.py | 2 - setuptools/unicode_utils.py | 6 +- setuptools/wheel.py | 6 +- tools/tox_pip.py | 14 +- 82 files changed, 230 insertions(+), 2566 deletions(-) delete mode 100644 pkg_resources/_vendor/six.py delete mode 100644 setuptools/_vendor/six.py delete mode 100644 setuptools/py27compat.py delete mode 100644 setuptools/py31compat.py delete mode 100644 setuptools/py33compat.py diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 4bbe60c..a50c3ba 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 49.6.0 +current_version = 50.0.0 commit = True tag = True diff --git a/CHANGES.rst b/CHANGES.rst index 2d49707..9dd77e1 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,10 @@ +v50.0.0 +------- + +* #2232: Once again, Setuptools overrides the stdlib distutils on import. For environments or invocations where this behavior is undesirable, users are provided with a temporary escape hatch. If the environment variable ``SETUPTOOLS_USE_DISTUTILS`` is set to ``stdlib``, Setuptools will fall back to the legacy behavior. Use of this escape hatch is discouraged, but it is provided to ease the transition while proper fixes for edge cases can be addressed. +* #2334: In MSVC module, refine text in error message. + + v49.6.0 ------- diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py index 1e7b294..074bd5e 100644 --- a/_distutils_hack/__init__.py +++ b/_distutils_hack/__init__.py @@ -37,7 +37,7 @@ def enabled(): """ Allow selection of distutils by environment variable. """ - which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') + which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local') return which == 'local' @@ -66,12 +66,14 @@ def do_override(): class DistutilsMetaFinder: def find_spec(self, fullname, path, target=None): - if path is not None or fullname != "distutils": - return None + if path is not None: + return - return self.get_distutils_spec() + method_name = 'spec_for_{fullname}'.format(**locals()) + method = getattr(self, method_name, lambda: None) + return method() - def get_distutils_spec(self): + def spec_for_distutils(self): import importlib.util class DistutilsLoader(importlib.util.abc.Loader): @@ -84,6 +86,14 @@ class DistutilsMetaFinder: return importlib.util.spec_from_loader('distutils', DistutilsLoader()) + def spec_for_pip(self): + """ + Ensure stdlib distutils when running under pip. + See pypa/pip#8761 for rationale. + """ + clear_distutils() + self.spec_for_distutils = lambda: None + DISTUTILS_FINDER = DistutilsMetaFinder() diff --git a/bootstrap.py b/bootstrap.py index 8fa9e4b..118671f 100644 --- a/bootstrap.py +++ b/bootstrap.py @@ -5,8 +5,6 @@ environment by creating a minimal egg-info directory and then invoking the egg-info command to flesh out the egg-info directory. """ -from __future__ import unicode_literals - import os import sys import textwrap diff --git a/pavement.py b/pavement.py index b5220d1..81ff6f1 100644 --- a/pavement.py +++ b/pavement.py @@ -22,7 +22,11 @@ def rewrite_packaging(pkg_files, new_root): """ for file in pkg_files.glob('*.py'): text = file.text() - text = re.sub(r' (pyparsing|six)', rf' {new_root}.\1', text) + text = re.sub(r' (pyparsing)', rf' {new_root}.\1', text) + text = text.replace( + 'from six.moves.urllib import parse', + 'from urllib import parse', + ) file.write_text(text) @@ -50,6 +54,7 @@ def install(vendor): subprocess.check_call(install_args) remove_all(vendor.glob('*.dist-info')) remove_all(vendor.glob('*.egg-info')) + remove_all(vendor.glob('six.py')) (vendor / '__init__.py').write_text('') diff --git a/pkg_resources/__init__.py b/pkg_resources/__init__.py index b585e85..737f4d5 100644 --- a/pkg_resources/__init__.py +++ b/pkg_resources/__init__.py @@ -1,4 +1,3 @@ -# coding: utf-8 """ Package resource API -------------------- @@ -15,8 +14,6 @@ The package resource API is designed to work with normal filesystem packages, method. """ -from __future__ import absolute_import - import sys import os import io @@ -54,9 +51,6 @@ try: except NameError: FileExistsError = OSError -from pkg_resources.extern import six -from pkg_resources.extern.six.moves import map, filter - # capture these to bypass sandboxing from os import utime try: @@ -83,18 +77,9 @@ __import__('pkg_resources.extern.packaging.specifiers') __import__('pkg_resources.extern.packaging.requirements') __import__('pkg_resources.extern.packaging.markers') - -__metaclass__ = type - - -if (3, 0) < sys.version_info < (3, 5): +if sys.version_info < (3, 5): raise RuntimeError("Python 3.5 or later is required") -if six.PY2: - # Those builtin exceptions are only defined in Python 3 - PermissionError = None - NotADirectoryError = None - # declare some globals that will be defined later to # satisfy the linters. require = None @@ -474,7 +459,7 @@ run_main = run_script def get_distribution(dist): """Return a current distribution object for a Requirement or string""" - if isinstance(dist, six.string_types): + if isinstance(dist, str): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) @@ -1418,8 +1403,6 @@ class NullProvider: return "" path = self._get_metadata_path(name) value = self._get(path) - if six.PY2: - return value try: return value.decode('utf-8') except UnicodeDecodeError as exc: @@ -1910,8 +1893,7 @@ class FileMetadata(EmptyProvider): return metadata def _warn_on_replacement(self, metadata): - # Python 2.7 compat for: replacement_char = '�' - replacement_char = b'\xef\xbf\xbd'.decode('utf-8') + replacement_char = '�' if replacement_char in metadata: tmpl = "{self.path} could not be properly decoded in UTF-8" msg = tmpl.format(**locals()) @@ -2109,8 +2091,6 @@ class NoDists: """ def __bool__(self): return False - if six.PY2: - __nonzero__ = __bool__ def __call__(self, fullpath): return iter(()) @@ -2127,12 +2107,7 @@ def safe_listdir(path): except OSError as e: # Ignore the directory if does not exist, not a directory or # permission denied - ignorable = ( - e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT) - # Python 2 on Windows needs to be handled this way :( - or getattr(e, "winerror", None) == 267 - ) - if not ignorable: + if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT): raise return () @@ -2406,7 +2381,7 @@ def _set_parent_ns(packageName): def yield_lines(strs): """Yield non-empty/non-comment lines of a string or sequence""" - if isinstance(strs, six.string_types): + if isinstance(strs, str): for s in strs.splitlines(): s = s.strip() # skip blank lines/comments @@ -2844,10 +2819,6 @@ class Distribution: ) ) - if not hasattr(object, '__dir__'): - # python 2.7 not supported - del __dir__ - @classmethod def from_filename(cls, filename, metadata=None, **kw): return cls.from_location( diff --git a/pkg_resources/_vendor/packaging/requirements.py b/pkg_resources/_vendor/packaging/requirements.py index 8282a63..9495a1d 100644 --- a/pkg_resources/_vendor/packaging/requirements.py +++ b/pkg_resources/_vendor/packaging/requirements.py @@ -9,7 +9,7 @@ import re from pkg_resources.extern.pyparsing import stringStart, stringEnd, originalTextFor, ParseException from pkg_resources.extern.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine from pkg_resources.extern.pyparsing import Literal as L # noqa -from pkg_resources.extern.six.moves.urllib import parse as urlparse +from urllib import parse as urlparse from ._typing import TYPE_CHECKING from .markers import MARKER_EXPR, Marker diff --git a/pkg_resources/_vendor/six.py b/pkg_resources/_vendor/six.py deleted file mode 100644 index 190c023..0000000 --- a/pkg_resources/_vendor/six.py +++ /dev/null @@ -1,868 +0,0 @@ -"""Utilities for writing code that runs on Python 2 and 3""" - -# Copyright (c) 2010-2015 Benjamin Peterson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -from __future__ import absolute_import - -import functools -import itertools -import operator -import sys -import types - -__author__ = "Benjamin Peterson " -__version__ = "1.10.0" - - -# Useful for very coarse version differentiation. -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 -PY34 = sys.version_info[0:2] >= (3, 4) - -if PY3: - string_types = str, - integer_types = int, - class_types = type, - text_type = str - binary_type = bytes - - MAXSIZE = sys.maxsize -else: - string_types = basestring, - integer_types = (int, long) - class_types = (type, types.ClassType) - text_type = unicode - binary_type = str - - if sys.platform.startswith("java"): - # Jython always uses 32 bits. - MAXSIZE = int((1 << 31) - 1) - else: - # It's possible to have sizeof(long) != sizeof(Py_ssize_t). - class X(object): - - def __len__(self): - return 1 << 31 - try: - len(X()) - except OverflowError: - # 32-bit - MAXSIZE = int((1 << 31) - 1) - else: - # 64-bit - MAXSIZE = int((1 << 63) - 1) - del X - - -def _add_doc(func, doc): - """Add documentation to a function.""" - func.__doc__ = doc - - -def _import_module(name): - """Import module, returning the module after the last dot.""" - __import__(name) - return sys.modules[name] - - -class _LazyDescr(object): - - def __init__(self, name): - self.name = name - - def __get__(self, obj, tp): - result = self._resolve() - setattr(obj, self.name, result) # Invokes __set__. - try: - # This is a bit ugly, but it avoids running this again by - # removing this descriptor. - delattr(obj.__class__, self.name) - except AttributeError: - pass - return result - - -class MovedModule(_LazyDescr): - - def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) - if PY3: - if new is None: - new = name - self.mod = new - else: - self.mod = old - - def _resolve(self): - return _import_module(self.mod) - - def __getattr__(self, attr): - _module = self._resolve() - value = getattr(_module, attr) - setattr(self, attr, value) - return value - - -class _LazyModule(types.ModuleType): - - def __init__(self, name): - super(_LazyModule, self).__init__(name) - self.__doc__ = self.__class__.__doc__ - - def __dir__(self): - attrs = ["__doc__", "__name__"] - attrs += [attr.name for attr in self._moved_attributes] - return attrs - - # Subclasses should override this - _moved_attributes = [] - - -class MovedAttribute(_LazyDescr): - - def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) - if PY3: - if new_mod is None: - new_mod = name - self.mod = new_mod - if new_attr is None: - if old_attr is None: - new_attr = name - else: - new_attr = old_attr - self.attr = new_attr - else: - self.mod = old_mod - if old_attr is None: - old_attr = name - self.attr = old_attr - - def _resolve(self): - module = _import_module(self.mod) - return getattr(module, self.attr) - - -class _SixMetaPathImporter(object): - - """ - A meta path importer to import six.moves and its submodules. - - This class implements a PEP302 finder and loader. It should be compatible - with Python 2.5 and all existing versions of Python3 - """ - - def __init__(self, six_module_name): - self.name = six_module_name - self.known_modules = {} - - def _add_module(self, mod, *fullnames): - for fullname in fullnames: - self.known_modules[self.name + "." + fullname] = mod - - def _get_module(self, fullname): - return self.known_modules[self.name + "." + fullname] - - def find_module(self, fullname, path=None): - if fullname in self.known_modules: - return self - return None - - def __get_module(self, fullname): - try: - return self.known_modules[fullname] - except KeyError: - raise ImportError("This loader does not know module " + fullname) - - def load_module(self, fullname): - try: - # in case of a reload - return sys.modules[fullname] - except KeyError: - pass - mod = self.__get_module(fullname) - if isinstance(mod, MovedModule): - mod = mod._resolve() - else: - mod.__loader__ = self - sys.modules[fullname] = mod - return mod - - def is_package(self, fullname): - """ - Return true, if the named module is a package. - - We need this method to get correct spec objects with - Python 3.4 (see PEP451) - """ - return hasattr(self.__get_module(fullname), "__path__") - - def get_code(self, fullname): - """Return None - - Required, if is_package is implemented""" - self.__get_module(fullname) # eventually raises ImportError - return None - get_source = get_code # same as get_code - -_importer = _SixMetaPathImporter(__name__) - - -class _MovedItems(_LazyModule): - - """Lazy loading of moved objects""" - __path__ = [] # mark as package - - -_moved_attributes = [ - MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), - MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), - MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), - MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), - MovedAttribute("intern", "__builtin__", "sys"), - MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), - MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), - MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), - MovedAttribute("reduce", "__builtin__", "functools"), - MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), - MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserDict", "UserDict", "collections"), - MovedAttribute("UserList", "UserList", "collections"), - MovedAttribute("UserString", "UserString", "collections"), - MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - MovedModule("builtins", "__builtin__"), - MovedModule("configparser", "ConfigParser"), - MovedModule("copyreg", "copy_reg"), - MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), - MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), - MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), - MovedModule("http_cookies", "Cookie", "http.cookies"), - MovedModule("html_entities", "htmlentitydefs", "html.entities"), - MovedModule("html_parser", "HTMLParser", "html.parser"), - MovedModule("http_client", "httplib", "http.client"), - MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), - MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), - MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), - MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), - MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), - MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), - MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), - MovedModule("cPickle", "cPickle", "pickle"), - MovedModule("queue", "Queue"), - MovedModule("reprlib", "repr"), - MovedModule("socketserver", "SocketServer"), - MovedModule("_thread", "thread", "_thread"), - MovedModule("tkinter", "Tkinter"), - MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), - MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), - MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), - MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), - MovedModule("tkinter_tix", "Tix", "tkinter.tix"), - MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), - MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), - MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), - MovedModule("tkinter_colorchooser", "tkColorChooser", - "tkinter.colorchooser"), - MovedModule("tkinter_commondialog", "tkCommonDialog", - "tkinter.commondialog"), - MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), - MovedModule("tkinter_font", "tkFont", "tkinter.font"), - MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), - MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", - "tkinter.simpledialog"), - MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), - MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), - MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), - MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), - MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), -] -# Add windows specific modules. -if sys.platform == "win32": - _moved_attributes += [ - MovedModule("winreg", "_winreg"), - ] - -for attr in _moved_attributes: - setattr(_MovedItems, attr.name, attr) - if isinstance(attr, MovedModule): - _importer._add_module(attr, "moves." + attr.name) -del attr - -_MovedItems._moved_attributes = _moved_attributes - -moves = _MovedItems(__name__ + ".moves") -_importer._add_module(moves, "moves") - - -class Module_six_moves_urllib_parse(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_parse""" - - -_urllib_parse_moved_attributes = [ - MovedAttribute("ParseResult", "urlparse", "urllib.parse"), - MovedAttribute("SplitResult", "urlparse", "urllib.parse"), - MovedAttribute("parse_qs", "urlparse", "urllib.parse"), - MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), - MovedAttribute("urldefrag", "urlparse", "urllib.parse"), - MovedAttribute("urljoin", "urlparse", "urllib.parse"), - MovedAttribute("urlparse", "urlparse", "urllib.parse"), - MovedAttribute("urlsplit", "urlparse", "urllib.parse"), - MovedAttribute("urlunparse", "urlparse", "urllib.parse"), - MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), - MovedAttribute("quote", "urllib", "urllib.parse"), - MovedAttribute("quote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote", "urllib", "urllib.parse"), - MovedAttribute("unquote_plus", "urllib", "urllib.parse"), - MovedAttribute("urlencode", "urllib", "urllib.parse"), - MovedAttribute("splitquery", "urllib", "urllib.parse"), - MovedAttribute("splittag", "urllib", "urllib.parse"), - MovedAttribute("splituser", "urllib", "urllib.parse"), - MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), - MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), - MovedAttribute("uses_params", "urlparse", "urllib.parse"), - MovedAttribute("uses_query", "urlparse", "urllib.parse"), - MovedAttribute("uses_relative", "urlparse", "urllib.parse"), -] -for attr in _urllib_parse_moved_attributes: - setattr(Module_six_moves_urllib_parse, attr.name, attr) -del attr - -Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes - -_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), - "moves.urllib_parse", "moves.urllib.parse") - - -class Module_six_moves_urllib_error(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_error""" - - -_urllib_error_moved_attributes = [ - MovedAttribute("URLError", "urllib2", "urllib.error"), - MovedAttribute("HTTPError", "urllib2", "urllib.error"), - MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), -] -for attr in _urllib_error_moved_attributes: - setattr(Module_six_moves_urllib_error, attr.name, attr) -del attr - -Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes - -_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), - "moves.urllib_error", "moves.urllib.error") - - -class Module_six_moves_urllib_request(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_request""" - - -_urllib_request_moved_attributes = [ - MovedAttribute("urlopen", "urllib2", "urllib.request"), - MovedAttribute("install_opener", "urllib2", "urllib.request"), - MovedAttribute("build_opener", "urllib2", "urllib.request"), - MovedAttribute("pathname2url", "urllib", "urllib.request"), - MovedAttribute("url2pathname", "urllib", "urllib.request"), - MovedAttribute("getproxies", "urllib", "urllib.request"), - MovedAttribute("Request", "urllib2", "urllib.request"), - MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), - MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), - MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), - MovedAttribute("BaseHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), - MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), - MovedAttribute("FileHandler", "urllib2", "urllib.request"), - MovedAttribute("FTPHandler", "urllib2", "urllib.request"), - MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), - MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), - MovedAttribute("urlretrieve", "urllib", "urllib.request"), - MovedAttribute("urlcleanup", "urllib", "urllib.request"), - MovedAttribute("URLopener", "urllib", "urllib.request"), - MovedAttribute("FancyURLopener", "urllib", "urllib.request"), - MovedAttribute("proxy_bypass", "urllib", "urllib.request"), -] -for attr in _urllib_request_moved_attributes: - setattr(Module_six_moves_urllib_request, attr.name, attr) -del attr - -Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes - -_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), - "moves.urllib_request", "moves.urllib.request") - - -class Module_six_moves_urllib_response(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_response""" - - -_urllib_response_moved_attributes = [ - MovedAttribute("addbase", "urllib", "urllib.response"), - MovedAttribute("addclosehook", "urllib", "urllib.response"), - MovedAttribute("addinfo", "urllib", "urllib.response"), - MovedAttribute("addinfourl", "urllib", "urllib.response"), -] -for attr in _urllib_response_moved_attributes: - setattr(Module_six_moves_urllib_response, attr.name, attr) -del attr - -Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes - -_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), - "moves.urllib_response", "moves.urllib.response") - - -class Module_six_moves_urllib_robotparser(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_robotparser""" - - -_urllib_robotparser_moved_attributes = [ - MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), -] -for attr in _urllib_robotparser_moved_attributes: - setattr(Module_six_moves_urllib_robotparser, attr.name, attr) -del attr - -Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes - -_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), - "moves.urllib_robotparser", "moves.urllib.robotparser") - - -class Module_six_moves_urllib(types.ModuleType): - - """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - __path__ = [] # mark as package - parse = _importer._get_module("moves.urllib_parse") - error = _importer._get_module("moves.urllib_error") - request = _importer._get_module("moves.urllib_request") - response = _importer._get_module("moves.urllib_response") - robotparser = _importer._get_module("moves.urllib_robotparser") - - def __dir__(self): - return ['parse', 'error', 'request', 'response', 'robotparser'] - -_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), - "moves.urllib") - - -def add_move(move): - """Add an item to six.moves.""" - setattr(_MovedItems, move.name, move) - - -def remove_move(name): - """Remove item from six.moves.""" - try: - delattr(_MovedItems, name) - except AttributeError: - try: - del moves.__dict__[name] - except KeyError: - raise AttributeError("no such move, %r" % (name,)) - - -if PY3: - _meth_func = "__func__" - _meth_self = "__self__" - - _func_closure = "__closure__" - _func_code = "__code__" - _func_defaults = "__defaults__" - _func_globals = "__globals__" -else: - _meth_func = "im_func" - _meth_self = "im_self" - - _func_closure = "func_closure" - _func_code = "func_code" - _func_defaults = "func_defaults" - _func_globals = "func_globals" - - -try: - advance_iterator = next -except NameError: - def advance_iterator(it): - return it.next() -next = advance_iterator - - -try: - callable = callable -except NameError: - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) - - -if PY3: - def get_unbound_function(unbound): - return unbound - - create_bound_method = types.MethodType - - def create_unbound_method(func, cls): - return func - - Iterator = object -else: - def get_unbound_function(unbound): - return unbound.im_func - - def create_bound_method(func, obj): - return types.MethodType(func, obj, obj.__class__) - - def create_unbound_method(func, cls): - return types.MethodType(func, None, cls) - - class Iterator(object): - - def next(self): - return type(self).__next__(self) - - callable = callable -_add_doc(get_unbound_function, - """Get the function out of a possibly unbound function""") - - -get_method_function = operator.attrgetter(_meth_func) -get_method_self = operator.attrgetter(_meth_self) -get_function_closure = operator.attrgetter(_func_closure) -get_function_code = operator.attrgetter(_func_code) -get_function_defaults = operator.attrgetter(_func_defaults) -get_function_globals = operator.attrgetter(_func_globals) - - -if PY3: - def iterkeys(d, **kw): - return iter(d.keys(**kw)) - - def itervalues(d, **kw): - return iter(d.values(**kw)) - - def iteritems(d, **kw): - return iter(d.items(**kw)) - - def iterlists(d, **kw): - return iter(d.lists(**kw)) - - viewkeys = operator.methodcaller("keys") - - viewvalues = operator.methodcaller("values") - - viewitems = operator.methodcaller("items") -else: - def iterkeys(d, **kw): - return d.iterkeys(**kw) - - def itervalues(d, **kw): - return d.itervalues(**kw) - - def iteritems(d, **kw): - return d.iteritems(**kw) - - def iterlists(d, **kw): - return d.iterlists(**kw) - - viewkeys = operator.methodcaller("viewkeys") - - viewvalues = operator.methodcaller("viewvalues") - - viewitems = operator.methodcaller("viewitems") - -_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") -_add_doc(itervalues, "Return an iterator over the values of a dictionary.") -_add_doc(iteritems, - "Return an iterator over the (key, value) pairs of a dictionary.") -_add_doc(iterlists, - "Return an iterator over the (key, [values]) pairs of a dictionary.") - - -if PY3: - def b(s): - return s.encode("latin-1") - - def u(s): - return s - unichr = chr - import struct - int2byte = struct.Struct(">B").pack - del struct - byte2int = operator.itemgetter(0) - indexbytes = operator.getitem - iterbytes = iter - import io - StringIO = io.StringIO - BytesIO = io.BytesIO - _assertCountEqual = "assertCountEqual" - if sys.version_info[1] <= 1: - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" - else: - _assertRaisesRegex = "assertRaisesRegex" - _assertRegex = "assertRegex" -else: - def b(s): - return s - # Workaround for standalone backslash - - def u(s): - return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") - unichr = unichr - int2byte = chr - - def byte2int(bs): - return ord(bs[0]) - - def indexbytes(buf, i): - return ord(buf[i]) - iterbytes = functools.partial(itertools.imap, ord) - import StringIO - StringIO = BytesIO = StringIO.StringIO - _assertCountEqual = "assertItemsEqual" - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" -_add_doc(b, """Byte literal""") -_add_doc(u, """Text literal""") - - -def assertCountEqual(self, *args, **kwargs): - return getattr(self, _assertCountEqual)(*args, **kwargs) - - -def assertRaisesRegex(self, *args, **kwargs): - return getattr(self, _assertRaisesRegex)(*args, **kwargs) - - -def assertRegex(self, *args, **kwargs): - return getattr(self, _assertRegex)(*args, **kwargs) - - -if PY3: - exec_ = getattr(moves.builtins, "exec") - - def reraise(tp, value, tb=None): - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - -else: - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - exec_("""def reraise(tp, value, tb=None): - raise tp, value, tb -""") - - -if sys.version_info[:2] == (3, 2): - exec_("""def raise_from(value, from_value): - if from_value is None: - raise value - raise value from from_value -""") -elif sys.version_info[:2] > (3, 2): - exec_("""def raise_from(value, from_value): - raise value from from_value -""") -else: - def raise_from(value, from_value): - raise value - - -print_ = getattr(moves.builtins, "print", None) -if print_ is None: - def print_(*args, **kwargs): - """The new-style print function for Python 2.4 and 2.5.""" - fp = kwargs.pop("file", sys.stdout) - if fp is None: - return - - def write(data): - if not isinstance(data, basestring): - data = str(data) - # If the file has an encoding, encode unicode with it. - if (isinstance(fp, file) and - isinstance(data, unicode) and - fp.encoding is not None): - errors = getattr(fp, "errors", None) - if errors is None: - errors = "strict" - data = data.encode(fp.encoding, errors) - fp.write(data) - want_unicode = False - sep = kwargs.pop("sep", None) - if sep is not None: - if isinstance(sep, unicode): - want_unicode = True - elif not isinstance(sep, str): - raise TypeError("sep must be None or a string") - end = kwargs.pop("end", None) - if end is not None: - if isinstance(end, unicode): - want_unicode = True - elif not isinstance(end, str): - raise TypeError("end must be None or a string") - if kwargs: - raise TypeError("invalid keyword arguments to print()") - if not want_unicode: - for arg in args: - if isinstance(arg, unicode): - want_unicode = True - break - if want_unicode: - newline = unicode("\n") - space = unicode(" ") - else: - newline = "\n" - space = " " - if sep is None: - sep = space - if end is None: - end = newline - for i, arg in enumerate(args): - if i: - write(sep) - write(arg) - write(end) -if sys.version_info[:2] < (3, 3): - _print = print_ - - def print_(*args, **kwargs): - fp = kwargs.get("file", sys.stdout) - flush = kwargs.pop("flush", False) - _print(*args, **kwargs) - if flush and fp is not None: - fp.flush() - -_add_doc(reraise, """Reraise an exception.""") - -if sys.version_info[0:2] < (3, 4): - def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, - updated=functools.WRAPPER_UPDATES): - def wrapper(f): - f = functools.wraps(wrapped, assigned, updated)(f) - f.__wrapped__ = wrapped - return f - return wrapper -else: - wraps = functools.wraps - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a dummy - # metaclass for one level of class instantiation that replaces itself with - # the actual metaclass. - class metaclass(meta): - - def __new__(cls, name, this_bases, d): - return meta(name, bases, d) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -def add_metaclass(metaclass): - """Class decorator for creating a class with a metaclass.""" - def wrapper(cls): - orig_vars = cls.__dict__.copy() - slots = orig_vars.get('__slots__') - if slots is not None: - if isinstance(slots, str): - slots = [slots] - for slots_var in slots: - orig_vars.pop(slots_var) - orig_vars.pop('__dict__', None) - orig_vars.pop('__weakref__', None) - return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper - - -def python_2_unicode_compatible(klass): - """ - A decorator that defines __unicode__ and __str__ methods under Python 2. - Under Python 3 it does nothing. - - To support Python 2 and 3 with a single code base, define a __str__ method - returning text and apply this decorator to the class. - """ - if PY2: - if '__str__' not in klass.__dict__: - raise ValueError("@python_2_unicode_compatible cannot be applied " - "to %s because it doesn't define __str__()." % - klass.__name__) - klass.__unicode__ = klass.__str__ - klass.__str__ = lambda self: self.__unicode__().encode('utf-8') - return klass - - -# Complete the moves implementation. -# This code is at the end of this module to speed up module loading. -# Turn this module into a package. -__path__ = [] # required for PEP 302 and PEP 451 -__package__ = __name__ # see PEP 366 @ReservedAssignment -if globals().get("__spec__") is not None: - __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable -# Remove other six meta path importers, since they cause problems. This can -# happen if six is removed from sys.modules and then reloaded. (Setuptools does -# this for some reason.) -if sys.meta_path: - for i, importer in enumerate(sys.meta_path): - # Here's some real nastiness: Another "instance" of the six module might - # be floating around. Therefore, we can't use isinstance() to check for - # the six meta path importer, since the other six instance will have - # inserted an importer with different class. - if (type(importer).__name__ == "_SixMetaPathImporter" and - importer.name == __name__): - del sys.meta_path[i] - break - del i, importer -# Finally, add the importer to the meta path import hook. -sys.meta_path.append(_importer) diff --git a/pkg_resources/_vendor/vendored.txt b/pkg_resources/_vendor/vendored.txt index 7862a3c..da7a198 100644 --- a/pkg_resources/_vendor/vendored.txt +++ b/pkg_resources/_vendor/vendored.txt @@ -1,4 +1,3 @@ packaging==20.4 pyparsing==2.2.1 -six==1.10.0 appdirs==1.4.3 diff --git a/pkg_resources/extern/__init__.py b/pkg_resources/extern/__init__.py index bf98d8f..4dc3beb 100644 --- a/pkg_resources/extern/__init__.py +++ b/pkg_resources/extern/__init__.py @@ -62,5 +62,5 @@ class VendorImporter: sys.meta_path.append(self) -names = 'packaging', 'pyparsing', 'six', 'appdirs' +names = 'packaging', 'pyparsing', 'appdirs' VendorImporter(__name__, names).install() diff --git a/pkg_resources/tests/test_pkg_resources.py b/pkg_resources/tests/test_pkg_resources.py index 189a866..6518820 100644 --- a/pkg_resources/tests/test_pkg_resources.py +++ b/pkg_resources/tests/test_pkg_resources.py @@ -1,6 +1,3 @@ -# coding: utf-8 -from __future__ import unicode_literals - import sys import tempfile import os @@ -20,16 +17,11 @@ except ImportError: from pkg_resources import ( DistInfoDistribution, Distribution, EggInfoDistribution, ) -from setuptools.extern import six -from pkg_resources.extern.six.moves import map -from pkg_resources.extern.six import text_type, string_types import pytest import pkg_resources -__metaclass__ = type - def timestamp(dt): """ @@ -42,7 +34,7 @@ def timestamp(dt): return time.mktime(dt.timetuple()) -class EggRemover(text_type): +class EggRemover(str): def __call__(self): if self in sys.path: sys.path.remove(self) @@ -143,7 +135,7 @@ class TestResourceManager: path = mgr.get_cache_path('foo') type_ = str(type(path)) message = "Unexpected type from get_cache_path: " + type_ - assert isinstance(path, string_types), message + assert isinstance(path, str), message def test_get_cache_path_race(self, tmpdir): # Patch to os.path.isdir to create a race condition @@ -225,13 +217,6 @@ def test_get_metadata__bad_utf8(tmpdir): metadata = 'née'.encode('iso-8859-1') dist = make_test_distribution(metadata_path, metadata=metadata) - if six.PY2: - # In Python 2, get_metadata() doesn't do any decoding. - actual = dist.get_metadata(filename) - assert actual == metadata - return - - # Otherwise, we are in the Python 3 case. with pytest.raises(UnicodeDecodeError) as excinfo: dist.get_metadata(filename) @@ -247,25 +232,18 @@ def test_get_metadata__bad_utf8(tmpdir): assert actual.endswith(metadata_path), 'actual: {}'.format(actual) -# TODO: remove this in favor of Path.touch() when Python 2 is dropped. -def touch_file(path): - """ - Create an empty file. - """ - with open(path, 'w'): - pass - - def make_distribution_no_version(tmpdir, basename): """ Create a distribution directory with no file containing the version. """ - # Convert the LocalPath object to a string before joining. - dist_dir = os.path.join(str(tmpdir), basename) - os.mkdir(dist_dir) + dist_dir = tmpdir / basename + dist_dir.ensure_dir() # Make the directory non-empty so distributions_from_metadata() # will detect it and yield it. - touch_file(os.path.join(dist_dir, 'temp.txt')) + dist_dir.join('temp.txt').ensure() + + if sys.version_info < (3, 6): + dist_dir = str(dist_dir) dists = list(pkg_resources.distributions_from_metadata(dist_dir)) assert len(dists) == 1 diff --git a/pkg_resources/tests/test_resources.py b/pkg_resources/tests/test_resources.py index ed7cdfc..b08bb29 100644 --- a/pkg_resources/tests/test_resources.py +++ b/pkg_resources/tests/test_resources.py @@ -1,13 +1,9 @@ -from __future__ import unicode_literals - import os import sys import string import platform import itertools -from pkg_resources.extern.six.moves import map - import pytest from pkg_resources.extern import packaging diff --git a/pkg_resources/tests/test_working_set.py b/pkg_resources/tests/test_working_set.py index 7a759bb..db13c71 100644 --- a/pkg_resources/tests/test_working_set.py +++ b/pkg_resources/tests/test_working_set.py @@ -9,8 +9,6 @@ import pkg_resources from .test_resources import Metadata -__metaclass__ = type - def strip_comments(s): return '\n'.join( diff --git a/setup.cfg b/setup.cfg index 3c8f867..577e23c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,7 +16,7 @@ formats = zip [metadata] name = setuptools -version = 49.6.0 +version = 50.0.0 description = Easily download, build, install, upgrade, and uninstall Python packages author = Python Packaging Authority author_email = distutils-sig@python.org @@ -70,7 +70,6 @@ tests = coverage>=4.5.1 pytest-cov>=2.5.1 paver; python_version>="3.6" - futures; python_version=="2.7" pip>=19.1 # For proper file:// URLs support. jaraco.envs diff --git a/setup.py b/setup.py index 5d98c02..34654e1 100755 --- a/setup.py +++ b/setup.py @@ -99,7 +99,8 @@ class install_with_pth(install): _pth_name = 'distutils-precedence' _pth_contents = textwrap.dedent(""" import os - enabled = os.environ.get('SETUPTOOLS_USE_DISTUTILS') == 'local' + var = 'SETUPTOOLS_USE_DISTUTILS' + enabled = os.environ.get(var, 'local') == 'local' enabled and __import__('_distutils_hack').add_shim() """).lstrip().replace('\n', '; ') diff --git a/setuptools/__init__.py b/setuptools/__init__.py index 9909423..4d9b835 100644 --- a/setuptools/__init__.py +++ b/setuptools/__init__.py @@ -13,27 +13,19 @@ from distutils.util import convert_path from ._deprecation_warning import SetuptoolsDeprecationWarning -from setuptools.extern.six import PY3, string_types -from setuptools.extern.six.moves import filter, map - import setuptools.version from setuptools.extension import Extension from setuptools.dist import Distribution from setuptools.depends import Require from . import monkey -__metaclass__ = type - __all__ = [ 'setup', 'Distribution', 'Command', 'Extension', 'Require', 'SetuptoolsDeprecationWarning', - 'find_packages' + 'find_packages', 'find_namespace_packages', ] -if PY3: - __all__.append('find_namespace_packages') - __version__ = setuptools.version.__version__ bootstrap_install_from = None @@ -122,9 +114,7 @@ class PEP420PackageFinder(PackageFinder): find_packages = PackageFinder.find - -if PY3: - find_namespace_packages = PEP420PackageFinder.find +find_namespace_packages = PEP420PackageFinder.find def _install_setup_requires(attrs): @@ -187,7 +177,7 @@ class Command(_Command): if val is None: setattr(self, option, default) return default - elif not isinstance(val, string_types): + elif not isinstance(val, str): raise DistutilsOptionError("'%s' must be a %s (got `%s`)" % (option, what, val)) return val @@ -201,11 +191,11 @@ class Command(_Command): val = getattr(self, option) if val is None: return - elif isinstance(val, string_types): + elif isinstance(val, str): setattr(self, option, re.split(r',\s*|\s+', val)) else: if isinstance(val, list): - ok = all(isinstance(v, string_types) for v in val) + ok = all(isinstance(v, str) for v in val) else: ok = False if not ok: diff --git a/setuptools/_vendor/packaging/requirements.py b/setuptools/_vendor/packaging/requirements.py index 06b1748..5d50c7d 100644 --- a/setuptools/_vendor/packaging/requirements.py +++ b/setuptools/_vendor/packaging/requirements.py @@ -9,7 +9,7 @@ import re from setuptools.extern.pyparsing import stringStart, stringEnd, originalTextFor, ParseException from setuptools.extern.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine from setuptools.extern.pyparsing import Literal as L # noqa -from setuptools.extern.six.moves.urllib import parse as urlparse +from urllib import parse as urlparse from ._typing import TYPE_CHECKING from .markers import MARKER_EXPR, Marker diff --git a/setuptools/_vendor/six.py b/setuptools/_vendor/six.py deleted file mode 100644 index 190c023..0000000 --- a/setuptools/_vendor/six.py +++ /dev/null @@ -1,868 +0,0 @@ -"""Utilities for writing code that runs on Python 2 and 3""" - -# Copyright (c) 2010-2015 Benjamin Peterson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -from __future__ import absolute_import - -import functools -import itertools -import operator -import sys -import types - -__author__ = "Benjamin Peterson " -__version__ = "1.10.0" - - -# Useful for very coarse version differentiation. -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 -PY34 = sys.version_info[0:2] >= (3, 4) - -if PY3: - string_types = str, - integer_types = int, - class_types = type, - text_type = str - binary_type = bytes - - MAXSIZE = sys.maxsize -else: - string_types = basestring, - integer_types = (int, long) - class_types = (type, types.ClassType) - text_type = unicode - binary_type = str - - if sys.platform.startswith("java"): - # Jython always uses 32 bits. - MAXSIZE = int((1 << 31) - 1) - else: - # It's possible to have sizeof(long) != sizeof(Py_ssize_t). - class X(object): - - def __len__(self): - return 1 << 31 - try: - len(X()) - except OverflowError: - # 32-bit - MAXSIZE = int((1 << 31) - 1) - else: - # 64-bit - MAXSIZE = int((1 << 63) - 1) - del X - - -def _add_doc(func, doc): - """Add documentation to a function.""" - func.__doc__ = doc - - -def _import_module(name): - """Import module, returning the module after the last dot.""" - __import__(name) - return sys.modules[name] - - -class _LazyDescr(object): - - def __init__(self, name): - self.name = name - - def __get__(self, obj, tp): - result = self._resolve() - setattr(obj, self.name, result) # Invokes __set__. - try: - # This is a bit ugly, but it avoids running this again by - # removing this descriptor. - delattr(obj.__class__, self.name) - except AttributeError: - pass - return result - - -class MovedModule(_LazyDescr): - - def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) - if PY3: - if new is None: - new = name - self.mod = new - else: - self.mod = old - - def _resolve(self): - return _import_module(self.mod) - - def __getattr__(self, attr): - _module = self._resolve() - value = getattr(_module, attr) - setattr(self, attr, value) - return value - - -class _LazyModule(types.ModuleType): - - def __init__(self, name): - super(_LazyModule, self).__init__(name) - self.__doc__ = self.__class__.__doc__ - - def __dir__(self): - attrs = ["__doc__", "__name__"] - attrs += [attr.name for attr in self._moved_attributes] - return attrs - - # Subclasses should override this - _moved_attributes = [] - - -class MovedAttribute(_LazyDescr): - - def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) - if PY3: - if new_mod is None: - new_mod = name - self.mod = new_mod - if new_attr is None: - if old_attr is None: - new_attr = name - else: - new_attr = old_attr - self.attr = new_attr - else: - self.mod = old_mod - if old_attr is None: - old_attr = name - self.attr = old_attr - - def _resolve(self): - module = _import_module(self.mod) - return getattr(module, self.attr) - - -class _SixMetaPathImporter(object): - - """ - A meta path importer to import six.moves and its submodules. - - This class implements a PEP302 finder and loader. It should be compatible - with Python 2.5 and all existing versions of Python3 - """ - - def __init__(self, six_module_name): - self.name = six_module_name - self.known_modules = {} - - def _add_module(self, mod, *fullnames): - for fullname in fullnames: - self.known_modules[self.name + "." + fullname] = mod - - def _get_module(self, fullname): - return self.known_modules[self.name + "." + fullname] - - def find_module(self, fullname, path=None): - if fullname in self.known_modules: - return self - return None - - def __get_module(self, fullname): - try: - return self.known_modules[fullname] - except KeyError: - raise ImportError("This loader does not know module " + fullname) - - def load_module(self, fullname): - try: - # in case of a reload - return sys.modules[fullname] - except KeyError: - pass - mod = self.__get_module(fullname) - if isinstance(mod, MovedModule): - mod = mod._resolve() - else: - mod.__loader__ = self - sys.modules[fullname] = mod - return mod - - def is_package(self, fullname): - """ - Return true, if the named module is a package. - - We need this method to get correct spec objects with - Python 3.4 (see PEP451) - """ - return hasattr(self.__get_module(fullname), "__path__") - - def get_code(self, fullname): - """Return None - - Required, if is_package is implemented""" - self.__get_module(fullname) # eventually raises ImportError - return None - get_source = get_code # same as get_code - -_importer = _SixMetaPathImporter(__name__) - - -class _MovedItems(_LazyModule): - - """Lazy loading of moved objects""" - __path__ = [] # mark as package - - -_moved_attributes = [ - MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), - MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), - MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), - MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), - MovedAttribute("intern", "__builtin__", "sys"), - MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), - MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), - MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), - MovedAttribute("reduce", "__builtin__", "functools"), - MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), - MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserDict", "UserDict", "collections"), - MovedAttribute("UserList", "UserList", "collections"), - MovedAttribute("UserString", "UserString", "collections"), - MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - MovedModule("builtins", "__builtin__"), - MovedModule("configparser", "ConfigParser"), - MovedModule("copyreg", "copy_reg"), - MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), - MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), - MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), - MovedModule("http_cookies", "Cookie", "http.cookies"), - MovedModule("html_entities", "htmlentitydefs", "html.entities"), - MovedModule("html_parser", "HTMLParser", "html.parser"), - MovedModule("http_client", "httplib", "http.client"), - MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), - MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), - MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), - MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), - MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), - MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), - MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), - MovedModule("cPickle", "cPickle", "pickle"), - MovedModule("queue", "Queue"), - MovedModule("reprlib", "repr"), - MovedModule("socketserver", "SocketServer"), - MovedModule("_thread", "thread", "_thread"), - MovedModule("tkinter", "Tkinter"), - MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), - MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), - MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), - MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), - MovedModule("tkinter_tix", "Tix", "tkinter.tix"), - MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), - MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), - MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), - MovedModule("tkinter_colorchooser", "tkColorChooser", - "tkinter.colorchooser"), - MovedModule("tkinter_commondialog", "tkCommonDialog", - "tkinter.commondialog"), - MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), - MovedModule("tkinter_font", "tkFont", "tkinter.font"), - MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), - MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", - "tkinter.simpledialog"), - MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), - MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), - MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), - MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), - MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), -] -# Add windows specific modules. -if sys.platform == "win32": - _moved_attributes += [ - MovedModule("winreg", "_winreg"), - ] - -for attr in _moved_attributes: - setattr(_MovedItems, attr.name, attr) - if isinstance(attr, MovedModule): - _importer._add_module(attr, "moves." + attr.name) -del attr - -_MovedItems._moved_attributes = _moved_attributes - -moves = _MovedItems(__name__ + ".moves") -_importer._add_module(moves, "moves") - - -class Module_six_moves_urllib_parse(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_parse""" - - -_urllib_parse_moved_attributes = [ - MovedAttribute("ParseResult", "urlparse", "urllib.parse"), - MovedAttribute("SplitResult", "urlparse", "urllib.parse"), - MovedAttribute("parse_qs", "urlparse", "urllib.parse"), - MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), - MovedAttribute("urldefrag", "urlparse", "urllib.parse"), - MovedAttribute("urljoin", "urlparse", "urllib.parse"), - MovedAttribute("urlparse", "urlparse", "urllib.parse"), - MovedAttribute("urlsplit", "urlparse", "urllib.parse"), - MovedAttribute("urlunparse", "urlparse", "urllib.parse"), - MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), - MovedAttribute("quote", "urllib", "urllib.parse"), - MovedAttribute("quote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote", "urllib", "urllib.parse"), - MovedAttribute("unquote_plus", "urllib", "urllib.parse"), - MovedAttribute("urlencode", "urllib", "urllib.parse"), - MovedAttribute("splitquery", "urllib", "urllib.parse"), - MovedAttribute("splittag", "urllib", "urllib.parse"), - MovedAttribute("splituser", "urllib", "urllib.parse"), - MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), - MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), - MovedAttribute("uses_params", "urlparse", "urllib.parse"), - MovedAttribute("uses_query", "urlparse", "urllib.parse"), - MovedAttribute("uses_relative", "urlparse", "urllib.parse"), -] -for attr in _urllib_parse_moved_attributes: - setattr(Module_six_moves_urllib_parse, attr.name, attr) -del attr - -Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes - -_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), - "moves.urllib_parse", "moves.urllib.parse") - - -class Module_six_moves_urllib_error(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_error""" - - -_urllib_error_moved_attributes = [ - MovedAttribute("URLError", "urllib2", "urllib.error"), - MovedAttribute("HTTPError", "urllib2", "urllib.error"), - MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), -] -for attr in _urllib_error_moved_attributes: - setattr(Module_six_moves_urllib_error, attr.name, attr) -del attr - -Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes - -_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), - "moves.urllib_error", "moves.urllib.error") - - -class Module_six_moves_urllib_request(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_request""" - - -_urllib_request_moved_attributes = [ - MovedAttribute("urlopen", "urllib2", "urllib.request"), - MovedAttribute("install_opener", "urllib2", "urllib.request"), - MovedAttribute("build_opener", "urllib2", "urllib.request"), - MovedAttribute("pathname2url", "urllib", "urllib.request"), - MovedAttribute("url2pathname", "urllib", "urllib.request"), - MovedAttribute("getproxies", "urllib", "urllib.request"), - MovedAttribute("Request", "urllib2", "urllib.request"), - MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), - MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), - MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), - MovedAttribute("BaseHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), - MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), - MovedAttribute("FileHandler", "urllib2", "urllib.request"), - MovedAttribute("FTPHandler", "urllib2", "urllib.request"), - MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), - MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), - MovedAttribute("urlretrieve", "urllib", "urllib.request"), - MovedAttribute("urlcleanup", "urllib", "urllib.request"), - MovedAttribute("URLopener", "urllib", "urllib.request"), - MovedAttribute("FancyURLopener", "urllib", "urllib.request"), - MovedAttribute("proxy_bypass", "urllib", "urllib.request"), -] -for attr in _urllib_request_moved_attributes: - setattr(Module_six_moves_urllib_request, attr.name, attr) -del attr - -Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes - -_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), - "moves.urllib_request", "moves.urllib.request") - - -class Module_six_moves_urllib_response(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_response""" - - -_urllib_response_moved_attributes = [ - MovedAttribute("addbase", "urllib", "urllib.response"), - MovedAttribute("addclosehook", "urllib", "urllib.response"), - MovedAttribute("addinfo", "urllib", "urllib.response"), - MovedAttribute("addinfourl", "urllib", "urllib.response"), -] -for attr in _urllib_response_moved_attributes: - setattr(Module_six_moves_urllib_response, attr.name, attr) -del attr - -Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes - -_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), - "moves.urllib_response", "moves.urllib.response") - - -class Module_six_moves_urllib_robotparser(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_robotparser""" - - -_urllib_robotparser_moved_attributes = [ - MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), -] -for attr in _urllib_robotparser_moved_attributes: - setattr(Module_six_moves_urllib_robotparser, attr.name, attr) -del attr - -Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes - -_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), - "moves.urllib_robotparser", "moves.urllib.robotparser") - - -class Module_six_moves_urllib(types.ModuleType): - - """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - __path__ = [] # mark as package - parse = _importer._get_module("moves.urllib_parse") - error = _importer._get_module("moves.urllib_error") - request = _importer._get_module("moves.urllib_request") - response = _importer._get_module("moves.urllib_response") - robotparser = _importer._get_module("moves.urllib_robotparser") - - def __dir__(self): - return ['parse', 'error', 'request', 'response', 'robotparser'] - -_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), - "moves.urllib") - - -def add_move(move): - """Add an item to six.moves.""" - setattr(_MovedItems, move.name, move) - - -def remove_move(name): - """Remove item from six.moves.""" - try: - delattr(_MovedItems, name) - except AttributeError: - try: - del moves.__dict__[name] - except KeyError: - raise AttributeError("no such move, %r" % (name,)) - - -if PY3: - _meth_func = "__func__" - _meth_self = "__self__" - - _func_closure = "__closure__" - _func_code = "__code__" - _func_defaults = "__defaults__" - _func_globals = "__globals__" -else: - _meth_func = "im_func" - _meth_self = "im_self" - - _func_closure = "func_closure" - _func_code = "func_code" - _func_defaults = "func_defaults" - _func_globals = "func_globals" - - -try: - advance_iterator = next -except NameError: - def advance_iterator(it): - return it.next() -next = advance_iterator - - -try: - callable = callable -except NameError: - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) - - -if PY3: - def get_unbound_function(unbound): - return unbound - - create_bound_method = types.MethodType - - def create_unbound_method(func, cls): - return func - - Iterator = object -else: - def get_unbound_function(unbound): - return unbound.im_func - - def create_bound_method(func, obj): - return types.MethodType(func, obj, obj.__class__) - - def create_unbound_method(func, cls): - return types.MethodType(func, None, cls) - - class Iterator(object): - - def next(self): - return type(self).__next__(self) - - callable = callable -_add_doc(get_unbound_function, - """Get the function out of a possibly unbound function""") - - -get_method_function = operator.attrgetter(_meth_func) -get_method_self = operator.attrgetter(_meth_self) -get_function_closure = operator.attrgetter(_func_closure) -get_function_code = operator.attrgetter(_func_code) -get_function_defaults = operator.attrgetter(_func_defaults) -get_function_globals = operator.attrgetter(_func_globals) - - -if PY3: - def iterkeys(d, **kw): - return iter(d.keys(**kw)) - - def itervalues(d, **kw): - return iter(d.values(**kw)) - - def iteritems(d, **kw): - return iter(d.items(**kw)) - - def iterlists(d, **kw): - return iter(d.lists(**kw)) - - viewkeys = operator.methodcaller("keys") - - viewvalues = operator.methodcaller("values") - - viewitems = operator.methodcaller("items") -else: - def iterkeys(d, **kw): - return d.iterkeys(**kw) - - def itervalues(d, **kw): - return d.itervalues(**kw) - - def iteritems(d, **kw): - return d.iteritems(**kw) - - def iterlists(d, **kw): - return d.iterlists(**kw) - - viewkeys = operator.methodcaller("viewkeys") - - viewvalues = operator.methodcaller("viewvalues") - - viewitems = operator.methodcaller("viewitems") - -_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") -_add_doc(itervalues, "Return an iterator over the values of a dictionary.") -_add_doc(iteritems, - "Return an iterator over the (key, value) pairs of a dictionary.") -_add_doc(iterlists, - "Return an iterator over the (key, [values]) pairs of a dictionary.") - - -if PY3: - def b(s): - return s.encode("latin-1") - - def u(s): - return s - unichr = chr - import struct - int2byte = struct.Struct(">B").pack - del struct - byte2int = operator.itemgetter(0) - indexbytes = operator.getitem - iterbytes = iter - import io - StringIO = io.StringIO - BytesIO = io.BytesIO - _assertCountEqual = "assertCountEqual" - if sys.version_info[1] <= 1: - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" - else: - _assertRaisesRegex = "assertRaisesRegex" - _assertRegex = "assertRegex" -else: - def b(s): - return s - # Workaround for standalone backslash - - def u(s): - return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") - unichr = unichr - int2byte = chr - - def byte2int(bs): - return ord(bs[0]) - - def indexbytes(buf, i): - return ord(buf[i]) - iterbytes = functools.partial(itertools.imap, ord) - import StringIO - StringIO = BytesIO = StringIO.StringIO - _assertCountEqual = "assertItemsEqual" - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" -_add_doc(b, """Byte literal""") -_add_doc(u, """Text literal""") - - -def assertCountEqual(self, *args, **kwargs): - return getattr(self, _assertCountEqual)(*args, **kwargs) - - -def assertRaisesRegex(self, *args, **kwargs): - return getattr(self, _assertRaisesRegex)(*args, **kwargs) - - -def assertRegex(self, *args, **kwargs): - return getattr(self, _assertRegex)(*args, **kwargs) - - -if PY3: - exec_ = getattr(moves.builtins, "exec") - - def reraise(tp, value, tb=None): - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - -else: - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - exec_("""def reraise(tp, value, tb=None): - raise tp, value, tb -""") - - -if sys.version_info[:2] == (3, 2): - exec_("""def raise_from(value, from_value): - if from_value is None: - raise value - raise value from from_value -""") -elif sys.version_info[:2] > (3, 2): - exec_("""def raise_from(value, from_value): - raise value from from_value -""") -else: - def raise_from(value, from_value): - raise value - - -print_ = getattr(moves.builtins, "print", None) -if print_ is None: - def print_(*args, **kwargs): - """The new-style print function for Python 2.4 and 2.5.""" - fp = kwargs.pop("file", sys.stdout) - if fp is None: - return - - def write(data): - if not isinstance(data, basestring): - data = str(data) - # If the file has an encoding, encode unicode with it. - if (isinstance(fp, file) and - isinstance(data, unicode) and - fp.encoding is not None): - errors = getattr(fp, "errors", None) - if errors is None: - errors = "strict" - data = data.encode(fp.encoding, errors) - fp.write(data) - want_unicode = False - sep = kwargs.pop("sep", None) - if sep is not None: - if isinstance(sep, unicode): - want_unicode = True - elif not isinstance(sep, str): - raise TypeError("sep must be None or a string") - end = kwargs.pop("end", None) - if end is not None: - if isinstance(end, unicode): - want_unicode = True - elif not isinstance(end, str): - raise TypeError("end must be None or a string") - if kwargs: - raise TypeError("invalid keyword arguments to print()") - if not want_unicode: - for arg in args: - if isinstance(arg, unicode): - want_unicode = True - break - if want_unicode: - newline = unicode("\n") - space = unicode(" ") - else: - newline = "\n" - space = " " - if sep is None: - sep = space - if end is None: - end = newline - for i, arg in enumerate(args): - if i: - write(sep) - write(arg) - write(end) -if sys.version_info[:2] < (3, 3): - _print = print_ - - def print_(*args, **kwargs): - fp = kwargs.get("file", sys.stdout) - flush = kwargs.pop("flush", False) - _print(*args, **kwargs) - if flush and fp is not None: - fp.flush() - -_add_doc(reraise, """Reraise an exception.""") - -if sys.version_info[0:2] < (3, 4): - def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, - updated=functools.WRAPPER_UPDATES): - def wrapper(f): - f = functools.wraps(wrapped, assigned, updated)(f) - f.__wrapped__ = wrapped - return f - return wrapper -else: - wraps = functools.wraps - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a dummy - # metaclass for one level of class instantiation that replaces itself with - # the actual metaclass. - class metaclass(meta): - - def __new__(cls, name, this_bases, d): - return meta(name, bases, d) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -def add_metaclass(metaclass): - """Class decorator for creating a class with a metaclass.""" - def wrapper(cls): - orig_vars = cls.__dict__.copy() - slots = orig_vars.get('__slots__') - if slots is not None: - if isinstance(slots, str): - slots = [slots] - for slots_var in slots: - orig_vars.pop(slots_var) - orig_vars.pop('__dict__', None) - orig_vars.pop('__weakref__', None) - return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper - - -def python_2_unicode_compatible(klass): - """ - A decorator that defines __unicode__ and __str__ methods under Python 2. - Under Python 3 it does nothing. - - To support Python 2 and 3 with a single code base, define a __str__ method - returning text and apply this decorator to the class. - """ - if PY2: - if '__str__' not in klass.__dict__: - raise ValueError("@python_2_unicode_compatible cannot be applied " - "to %s because it doesn't define __str__()." % - klass.__name__) - klass.__unicode__ = klass.__str__ - klass.__str__ = lambda self: self.__unicode__().encode('utf-8') - return klass - - -# Complete the moves implementation. -# This code is at the end of this module to speed up module loading. -# Turn this module into a package. -__path__ = [] # required for PEP 302 and PEP 451 -__package__ = __name__ # see PEP 366 @ReservedAssignment -if globals().get("__spec__") is not None: - __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable -# Remove other six meta path importers, since they cause problems. This can -# happen if six is removed from sys.modules and then reloaded. (Setuptools does -# this for some reason.) -if sys.meta_path: - for i, importer in enumerate(sys.meta_path): - # Here's some real nastiness: Another "instance" of the six module might - # be floating around. Therefore, we can't use isinstance() to check for - # the six meta path importer, since the other six instance will have - # inserted an importer with different class. - if (type(importer).__name__ == "_SixMetaPathImporter" and - importer.name == __name__): - del sys.meta_path[i] - break - del i, importer -# Finally, add the importer to the meta path import hook. -sys.meta_path.append(_importer) diff --git a/setuptools/_vendor/vendored.txt b/setuptools/_vendor/vendored.txt index 288d077..b119043 100644 --- a/setuptools/_vendor/vendored.txt +++ b/setuptools/_vendor/vendored.txt @@ -1,4 +1,3 @@ packaging==20.4 pyparsing==2.2.1 -six==1.10.0 ordered-set==3.1.1 diff --git a/setuptools/build_meta.py b/setuptools/build_meta.py index 3713218..b9e8a2b 100644 --- a/setuptools/build_meta.py +++ b/setuptools/build_meta.py @@ -32,10 +32,10 @@ import sys import tokenize import shutil import contextlib +import tempfile import setuptools import distutils -from setuptools.py31compat import TemporaryDirectory from pkg_resources import parse_requirements @@ -91,19 +91,6 @@ def no_install_setup_requires(): setuptools._install_setup_requires = orig -def _to_str(s): - """ - Convert a filename to a string (on Python 2, explicitly - a byte string, not Unicode) as distutils checks for the - exact type str. - """ - if sys.version_info[0] == 2 and not isinstance(s, str): - # Assume it's Unicode, as that's what the PEP says - # should be provided. - return s.encode(sys.getfilesystemencoding()) - return s - - 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))] @@ -168,8 +155,8 @@ class _BuildMetaBackend(object): def prepare_metadata_for_build_wheel(self, metadata_directory, config_settings=None): - sys.argv = sys.argv[:1] + ['dist_info', '--egg-base', - _to_str(metadata_directory)] + sys.argv = sys.argv[:1] + [ + 'dist_info', '--egg-base', metadata_directory] with no_install_setup_requires(): self.run_setup() @@ -207,7 +194,7 @@ class _BuildMetaBackend(object): # Build in a temporary directory, then copy to the target. os.makedirs(result_directory, exist_ok=True) - with TemporaryDirectory(dir=result_directory) as tmp_dist_dir: + with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir: sys.argv = (sys.argv[:1] + setup_command + ['--dist-dir', tmp_dist_dir] + config_settings["--global-option"]) diff --git a/setuptools/command/alias.py b/setuptools/command/alias.py index 4532b1c..452a924 100644 --- a/setuptools/command/alias.py +++ b/setuptools/command/alias.py @@ -1,7 +1,5 @@ from distutils.errors import DistutilsOptionError -from setuptools.extern.six.moves import map - from setuptools.command.setopt import edit_config, option_base, config_file diff --git a/setuptools/command/bdist_egg.py b/setuptools/command/bdist_egg.py index 4be1545..a88efb4 100644 --- a/setuptools/command/bdist_egg.py +++ b/setuptools/command/bdist_egg.py @@ -13,24 +13,16 @@ import textwrap import marshal import warnings -from setuptools.extern import six - from pkg_resources import get_build_platform, Distribution, ensure_directory from pkg_resources import EntryPoint from setuptools.extension import Library from setuptools import Command, SetuptoolsDeprecationWarning -try: - # Python 2.7 or >=3.2 - from sysconfig import get_path, get_python_version +from sysconfig import get_path, get_python_version - def _get_purelib(): - return get_path("purelib") -except ImportError: - from distutils.sysconfig import get_python_lib, get_python_version - def _get_purelib(): - return get_python_lib(False) +def _get_purelib(): + return get_path("purelib") def strip_module(filename): @@ -420,9 +412,7 @@ def scan_module(egg_dir, base, name, stubs): return True # Extension module pkg = base[len(egg_dir) + 1:].replace(os.sep, '.') module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0] - if six.PY2: - skip = 8 # skip magic & date - elif sys.version_info < (3, 7): + if sys.version_info < (3, 7): skip = 12 # skip magic & date & file size else: skip = 16 # skip magic & reserved? & date & file size @@ -453,7 +443,7 @@ def iter_symbols(code): for name in code.co_names: yield name for const in code.co_consts: - if isinstance(const, six.string_types): + if isinstance(const, str): yield const elif isinstance(const, CodeType): for name in iter_symbols(const): diff --git a/setuptools/command/build_ext.py b/setuptools/command/build_ext.py index 89a0e32..03a72b4 100644 --- a/setuptools/command/build_ext.py +++ b/setuptools/command/build_ext.py @@ -1,6 +1,7 @@ import os import sys import itertools +from importlib.machinery import EXTENSION_SUFFIXES from distutils.command.build_ext import build_ext as _du_build_ext from distutils.file_util import copy_file from distutils.ccompiler import new_compiler @@ -9,15 +10,6 @@ from distutils.errors import DistutilsError from distutils import log from setuptools.extension import Library -from setuptools.extern import six - -if six.PY2: - import imp - - EXTENSION_SUFFIXES = [ - s for s, _, tp in imp.get_suffixes() if tp == imp.C_EXTENSION] -else: - from importlib.machinery import EXTENSION_SUFFIXES try: # Attempt to use Cython for building extensions, if available @@ -115,11 +107,7 @@ class build_ext(_build_ext): filename = _build_ext.get_ext_filename(self, fullname) if fullname in self.ext_map: ext = self.ext_map[fullname] - use_abi3 = ( - not six.PY2 - and getattr(ext, 'py_limited_api') - and get_abi3_suffix() - ) + use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix() if use_abi3: so_ext = get_config_var('EXT_SUFFIX') filename = filename[:-len(so_ext)] diff --git a/setuptools/command/build_py.py b/setuptools/command/build_py.py index 9d0288a..4709679 100644 --- a/setuptools/command/build_py.py +++ b/setuptools/command/build_py.py @@ -9,9 +9,6 @@ import distutils.errors import itertools import stat -from setuptools.extern import six -from setuptools.extern.six.moves import map, filter, filterfalse - try: from setuptools.lib2to3_ex import Mixin2to3 except ImportError: @@ -73,9 +70,6 @@ class build_py(orig.build_py, Mixin2to3): return orig.build_py.__getattr__(self, attr) def build_module(self, module, module_file, package): - if six.PY2 and isinstance(package, six.string_types): - # avoid errors on Python 2 when unicode is passed (#190) - package = package.split('.') outfile, copied = orig.build_py.build_module(self, module, module_file, package) if copied: @@ -249,7 +243,7 @@ def _unique_everseen(iterable, key=None): seen = set() seen_add = seen.add if key is None: - for element in filterfalse(seen.__contains__, iterable): + for element in itertools.filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: diff --git a/setuptools/command/develop.py b/setuptools/command/develop.py index e7e03cd..faf8c98 100644 --- a/setuptools/command/develop.py +++ b/setuptools/command/develop.py @@ -5,15 +5,11 @@ import os import glob import io -from setuptools.extern import six - import pkg_resources from setuptools.command.easy_install import easy_install from setuptools import namespaces import setuptools -__metaclass__ = type - class develop(namespaces.DevelopInstaller, easy_install): """Set up package for development""" @@ -108,7 +104,7 @@ class develop(namespaces.DevelopInstaller, easy_install): return path_to_setup def install_for_development(self): - if not six.PY2 and getattr(self.distribution, 'use_2to3', False): + if getattr(self.distribution, 'use_2to3', False): # If we run 2to3 we can not do this inplace: # Ensure metadata is up-to-date diff --git a/setuptools/command/easy_install.py b/setuptools/command/easy_install.py index bcbd4f5..9ec83b7 100644 --- a/setuptools/command/easy_install.py +++ b/setuptools/command/easy_install.py @@ -38,18 +38,15 @@ import contextlib import subprocess import shlex import io +import configparser from sysconfig import get_config_vars, get_path from setuptools import SetuptoolsDeprecationWarning -from setuptools.extern import six -from setuptools.extern.six.moves import configparser, map - from setuptools import Command from setuptools.sandbox import run_setup -from setuptools.py27compat import rmtree_safe from setuptools.command import setopt from setuptools.archive_util import unpack_archive from setuptools.package_index import ( @@ -65,8 +62,6 @@ from pkg_resources import ( ) import pkg_resources -__metaclass__ = type - # Turn on PEP440Warnings warnings.filterwarnings("default", category=pkg_resources.PEP440Warning) @@ -96,28 +91,16 @@ def samefile(p1, p2): return norm_p1 == norm_p2 -if six.PY2: - - def _to_bytes(s): - return s - - def isascii(s): - try: - six.text_type(s, 'ascii') - return True - except UnicodeError: - return False -else: +def _to_bytes(s): + return s.encode('utf8') - def _to_bytes(s): - return s.encode('utf8') - def isascii(s): - try: - s.encode('ascii') - return True - except UnicodeError: - return False +def isascii(s): + try: + s.encode('ascii') + return True + except UnicodeError: + return False def _one_liner(text): @@ -341,7 +324,7 @@ class easy_install(Command): self.local_index = Environment(self.shadow_path + sys.path) if self.find_links is not None: - if isinstance(self.find_links, six.string_types): + if isinstance(self.find_links, str): self.find_links = self.find_links.split() else: self.find_links = [] @@ -650,7 +633,7 @@ class easy_install(Command): # cast to str as workaround for #709 and #710 and #712 yield str(tmpdir) finally: - os.path.exists(tmpdir) and rmtree(rmtree_safe(tmpdir)) + os.path.exists(tmpdir) and rmtree(tmpdir) def easy_install(self, spec, deps=False): with self._tmpdir() as tmpdir: @@ -1318,7 +1301,7 @@ class easy_install(Command): if not self.user: return home = convert_path(os.path.expanduser("~")) - for name, path in six.iteritems(self.config_vars): + for name, path in self.config_vars.items(): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700) @@ -1499,7 +1482,7 @@ def extract_wininst_cfg(dist_filename): # Now the config is in bytes, but for RawConfigParser, it should # be text, so decode it. config = config.decode(sys.getfilesystemencoding()) - cfg.readfp(six.StringIO(config)) + cfg.readfp(io.StringIO(config)) except configparser.Error: return None if not cfg.has_section('metadata') or not cfg.has_section('Setup'): @@ -1534,9 +1517,7 @@ def get_exe_prefixes(exe_filename): if name.endswith('-nspkg.pth'): continue if parts[0].upper() in ('PURELIB', 'PLATLIB'): - contents = z.read(name) - if not six.PY2: - contents = contents.decode() + contents = z.read(name).decode() for pth in yield_lines(contents): pth = pth.strip().replace('\\', '/') if not pth.startswith('import'): @@ -1700,7 +1681,8 @@ def auto_chmod(func, arg, exc): chmod(arg, stat.S_IWRITE) return func(arg) et, ev, _ = sys.exc_info() - six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg)))) + # TODO: This code doesn't make sense. What is it trying to do? + raise (ev[0], ev[1] + (" %s %s" % (func, arg))) def update_dist_caches(dist_path, fix_zipimporter_caches): @@ -2263,10 +2245,7 @@ def get_win_launcher(type): def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') - if six.PY2: - return manifest % vars() - else: - return manifest.decode('utf-8') % vars() + return manifest.decode('utf-8') % vars() def rmtree(path, ignore_errors=False, onerror=auto_chmod): diff --git a/setuptools/command/egg_info.py b/setuptools/command/egg_info.py index 0855207..c957154 100644 --- a/setuptools/command/egg_info.py +++ b/setuptools/command/egg_info.py @@ -16,9 +16,6 @@ import warnings import time import collections -from setuptools.extern import six -from setuptools.extern.six.moves import map - from setuptools import Command from setuptools.command.sdist import sdist from setuptools.command.sdist import walk_revctrl @@ -267,8 +264,7 @@ class egg_info(InfoCommon, Command): to the file. """ log.info("writing %s to %s", what, filename) - if not six.PY2: - data = data.encode("utf-8") + data = data.encode("utf-8") if not self.dry_run: f = open(filename, 'wb') f.write(data) @@ -647,7 +643,7 @@ def _write_requirements(stream, reqs): def write_requirements(cmd, basename, filename): dist = cmd.distribution - data = six.StringIO() + data = io.StringIO() _write_requirements(data, dist.install_requires) extras_require = dist.extras_require or {} for extra in sorted(extras_require): @@ -687,12 +683,12 @@ def write_arg(cmd, basename, filename, force=False): def write_entries(cmd, basename, filename): ep = cmd.distribution.entry_points - if isinstance(ep, six.string_types) or ep is None: + if isinstance(ep, str) or ep is None: data = ep elif ep is not None: data = [] for section, contents in sorted(ep.items()): - if not isinstance(contents, six.string_types): + if not isinstance(contents, str): contents = EntryPoint.parse_group(section, contents) contents = '\n'.join(sorted(map(str, contents.values()))) data.append('[%s]\n%s\n\n' % (section, contents)) diff --git a/setuptools/command/py36compat.py b/setuptools/command/py36compat.py index 2886055..343547a 100644 --- a/setuptools/command/py36compat.py +++ b/setuptools/command/py36compat.py @@ -3,8 +3,6 @@ from glob import glob from distutils.util import convert_path from distutils.command import sdist -from setuptools.extern.six.moves import filter - class sdist_add_defaults: """ diff --git a/setuptools/command/rotate.py b/setuptools/command/rotate.py index e398834..74795ba 100644 --- a/setuptools/command/rotate.py +++ b/setuptools/command/rotate.py @@ -4,8 +4,6 @@ from distutils.errors import DistutilsOptionError import os import shutil -from setuptools.extern import six - from setuptools import Command @@ -38,7 +36,7 @@ class rotate(Command): self.keep = int(self.keep) except ValueError as e: raise DistutilsOptionError("--keep must be an integer") from e - if isinstance(self.match, six.string_types): + if isinstance(self.match, str): self.match = [ convert_path(p.strip()) for p in self.match.split(',') ] diff --git a/setuptools/command/sdist.py b/setuptools/command/sdist.py index 8c3438e..887b7ef 100644 --- a/setuptools/command/sdist.py +++ b/setuptools/command/sdist.py @@ -5,7 +5,7 @@ import sys import io import contextlib -from setuptools.extern import six, ordered_set +from setuptools.extern import ordered_set from .py36compat import sdist_add_defaults @@ -98,34 +98,8 @@ class sdist(sdist_add_defaults, orig.sdist): if orig_val is not NoValue: setattr(os, 'link', orig_val) - def __read_template_hack(self): - # This grody hack closes the template file (MANIFEST.in) if an - # exception occurs during read_template. - # Doing so prevents an error when easy_install attempts to delete the - # file. - try: - orig.sdist.read_template(self) - except Exception: - _, _, tb = sys.exc_info() - tb.tb_next.tb_frame.f_locals['template'].close() - raise - - # Beginning with Python 2.7.2, 3.1.4, and 3.2.1, this leaky file handle - # has been fixed, so only override the method if we're using an earlier - # Python. - has_leaky_handle = ( - sys.version_info < (2, 7, 2) - or (3, 0) <= sys.version_info < (3, 1, 4) - or (3, 2) <= sys.version_info < (3, 2, 1) - ) - if has_leaky_handle: - read_template = __read_template_hack - def _add_defaults_optional(self): - if six.PY2: - sdist_add_defaults._add_defaults_optional(self) - else: - super()._add_defaults_optional() + super()._add_defaults_optional() if os.path.isfile('pyproject.toml'): self.filelist.append('pyproject.toml') @@ -158,10 +132,7 @@ class sdist(sdist_add_defaults, orig.sdist): def _add_defaults_data_files(self): try: - if six.PY2: - sdist_add_defaults._add_defaults_data_files(self) - else: - super()._add_defaults_data_files() + super()._add_defaults_data_files() except TypeError: log.warn("data_files contains unexpected objects") @@ -207,12 +178,11 @@ class sdist(sdist_add_defaults, orig.sdist): manifest = open(self.manifest, 'rb') for line in manifest: # The manifest must contain UTF-8. See #303. - if not six.PY2: - try: - line = line.decode('UTF-8') - except UnicodeDecodeError: - log.warn("%r not UTF-8 decodable -- skipping" % line) - continue + try: + line = line.decode('UTF-8') + except UnicodeDecodeError: + log.warn("%r not UTF-8 decodable -- skipping" % line) + continue # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: diff --git a/setuptools/command/setopt.py b/setuptools/command/setopt.py index 7e57cc0..e18057c 100644 --- a/setuptools/command/setopt.py +++ b/setuptools/command/setopt.py @@ -3,8 +3,7 @@ from distutils import log from distutils.errors import DistutilsOptionError import distutils import os - -from setuptools.extern.six.moves import configparser +import configparser from setuptools import Command diff --git a/setuptools/command/test.py b/setuptools/command/test.py index 2d83967..cf71ad0 100644 --- a/setuptools/command/test.py +++ b/setuptools/command/test.py @@ -8,17 +8,12 @@ from distutils.errors import DistutilsError, DistutilsOptionError from distutils import log from unittest import TestLoader -from setuptools.extern import six -from setuptools.extern.six.moves import map, filter - from pkg_resources import (resource_listdir, resource_exists, normalize_path, working_set, _namespace_packages, evaluate_marker, add_activation_listener, require, EntryPoint) from setuptools import Command from .build_py import _unique_everseen -__metaclass__ = type - class ScanningLoader(TestLoader): @@ -129,8 +124,7 @@ class test(Command): @contextlib.contextmanager def project_on_sys_path(self, include_dists=[]): - with_2to3 = not six.PY2 and getattr( - self.distribution, 'use_2to3', False) + with_2to3 = getattr(self.distribution, 'use_2to3', False) if with_2to3: # If we run 2to3 we can not do this inplace: @@ -241,7 +235,7 @@ class test(Command): # Purge modules under test from sys.modules. The test loader will # re-import them from the build location. Required when 2to3 is used # with namespace packages. - if not six.PY2 and getattr(self.distribution, 'use_2to3', False): + if getattr(self.distribution, 'use_2to3', False): module = self.test_suite.split('.')[0] if module in _namespace_packages: del_modules = [] diff --git a/setuptools/command/upload_docs.py b/setuptools/command/upload_docs.py index 0351da7..2559458 100644 --- a/setuptools/command/upload_docs.py +++ b/setuptools/command/upload_docs.py @@ -15,17 +15,15 @@ import tempfile import shutil import itertools import functools - -from setuptools.extern import six -from setuptools.extern.six.moves import http_client, urllib +import http.client +import urllib.parse from pkg_resources import iter_entry_points from .upload import upload def _encode(s): - errors = 'strict' if six.PY2 else 'surrogateescape' - return s.encode('utf-8', errors) + return s.encode('utf-8', 'surrogateescape') class upload_docs(upload): @@ -152,9 +150,7 @@ class upload_docs(upload): } # set up the authentication credentials = _encode(self.username + ':' + self.password) - credentials = standard_b64encode(credentials) - if not six.PY2: - credentials = credentials.decode('ascii') + credentials = standard_b64encode(credentials).decode('ascii') auth = "Basic " + credentials body, ct = self._build_multipart(data) @@ -169,9 +165,9 @@ class upload_docs(upload): urllib.parse.urlparse(self.repository) assert not params and not query and not fragments if schema == 'http': - conn = http_client.HTTPConnection(netloc) + conn = http.client.HTTPConnection(netloc) elif schema == 'https': - conn = http_client.HTTPSConnection(netloc) + conn = http.client.HTTPSConnection(netloc) else: raise AssertionError("unsupported schema " + schema) diff --git a/setuptools/config.py b/setuptools/config.py index a8f8b6b..af3a3bc 100644 --- a/setuptools/config.py +++ b/setuptools/config.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import, unicode_literals import ast import io import os @@ -15,10 +14,6 @@ import contextlib from distutils.errors import DistutilsOptionError, DistutilsFileError from setuptools.extern.packaging.version import LegacyVersion, parse from setuptools.extern.packaging.specifiers import SpecifierSet -from setuptools.extern.six import string_types, PY3 - - -__metaclass__ = type class StaticModule: @@ -324,7 +319,7 @@ class ConfigHandler: """ include_directive = 'file:' - if not isinstance(value, string_types): + if not isinstance(value, str): return value if not value.startswith(include_directive): @@ -559,7 +554,7 @@ class ConfigMetadataHandler(ConfigHandler): if callable(version): version = version() - if not isinstance(version, string_types): + if not isinstance(version, str): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: @@ -614,9 +609,6 @@ class ConfigOptionsHandler(ConfigHandler): return self._parse_list(value) findns = trimmed_value == find_directives[1] - if findns and not PY3: - raise DistutilsOptionError( - 'find_namespace: directive is unsupported on Python < 3.3') # Read function arguments from a dedicated section. find_kwargs = self.parse_section_packages__find( diff --git a/setuptools/depends.py b/setuptools/depends.py index a37675c..8be6928 100644 --- a/setuptools/depends.py +++ b/setuptools/depends.py @@ -1,12 +1,11 @@ import sys import marshal import contextlib +import dis from distutils.version import StrictVersion -from .py33compat import Bytecode - -from .py27compat import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE -from . import py27compat +from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE +from . import _imp __all__ = [ @@ -111,12 +110,12 @@ def get_module_constant(module, symbol, default=-1, paths=None): f.read(8) # skip magic & date code = marshal.load(f) elif kind == PY_FROZEN: - code = py27compat.get_frozen_object(module, paths) + code = _imp.get_frozen_object(module, paths) elif kind == PY_SOURCE: code = compile(f.read(), path, 'exec') else: # Not something we can parse; we'll have to import it. :( - imported = py27compat.get_module(module, paths, info) + imported = _imp.get_module(module, paths, info) return getattr(imported, symbol, None) return extract_constant(code, symbol, default) @@ -146,7 +145,7 @@ def extract_constant(code, symbol, default=-1): const = default - for byte_code in Bytecode(code): + for byte_code in dis.Bytecode(code): op = byte_code.opcode arg = byte_code.arg diff --git a/setuptools/dist.py b/setuptools/dist.py index e813b11..2c088ef 100644 --- a/setuptools/dist.py +++ b/setuptools/dist.py @@ -23,10 +23,8 @@ from distutils.errors import DistutilsOptionError, DistutilsSetupError from distutils.util import rfc822_escape from distutils.version import StrictVersion -from setuptools.extern import six from setuptools.extern import packaging from setuptools.extern import ordered_set -from setuptools.extern.six.moves import map, filter, filterfalse from . import SetuptoolsDeprecationWarning @@ -126,12 +124,8 @@ def write_pkg_file(self, file): """ version = self.get_metadata_version() - if six.PY2: - def write_field(key, value): - file.write("%s: %s\n" % (key, self._encode_field(value))) - else: - def write_field(key, value): - file.write("%s: %s\n" % (key, value)) + def write_field(key, value): + file.write("%s: %s\n" % (key, value)) write_field('Metadata-Version', str(version)) write_field('Name', self.get_name()) @@ -308,7 +302,7 @@ def check_entry_points(dist, attr, value): def check_test_suite(dist, attr, value): - if not isinstance(value, six.string_types): + if not isinstance(value, str): raise DistutilsSetupError("test_suite must be a string") @@ -319,7 +313,7 @@ def check_package_data(dist, attr, value): "{!r} must be a dictionary mapping package names to lists of " "string wildcard patterns".format(attr)) for k, v in value.items(): - if not isinstance(k, six.string_types): + if not isinstance(k, str): raise DistutilsSetupError( "keys of {!r} dict must be strings (got {!r})" .format(attr, k) @@ -537,7 +531,7 @@ class Distribution(_Distribution): spec_inst_reqs = getattr(self, 'install_requires', None) or () inst_reqs = list(pkg_resources.parse_requirements(spec_inst_reqs)) simple_reqs = filter(is_simple_req, inst_reqs) - complex_reqs = filterfalse(is_simple_req, inst_reqs) + complex_reqs = itertools.filterfalse(is_simple_req, inst_reqs) self.install_requires = list(map(str, simple_reqs)) for r in complex_reqs: @@ -560,10 +554,10 @@ class Distribution(_Distribution): this method provides the same functionality in subtly-improved ways. """ - from setuptools.extern.six.moves.configparser import ConfigParser + from configparser import ConfigParser # Ignore install directory options if we have a venv - if not six.PY2 and sys.prefix != sys.base_prefix: + if sys.prefix != sys.base_prefix: ignore_options = [ 'install-base', 'install-platbase', 'install-lib', 'install-platlib', 'install-purelib', 'install-headers', @@ -585,14 +579,14 @@ class Distribution(_Distribution): with io.open(filename, encoding='utf-8') as reader: if DEBUG: self.announce(" reading {filename}".format(**locals())) - (parser.readfp if six.PY2 else parser.read_file)(reader) + parser.read_file(reader) for section in parser.sections(): options = parser.options(section) opt_dict = self.get_option_dict(section) for opt in options: if opt != '__name__' and opt not in ignore_options: - val = self._try_str(parser.get(section, opt)) + val = parser.get(section, opt) opt = opt.replace('-', '_') opt_dict[opt] = (filename, val) @@ -616,26 +610,6 @@ class Distribution(_Distribution): except ValueError as e: raise DistutilsOptionError(e) from e - @staticmethod - def _try_str(val): - """ - On Python 2, much of distutils relies on string values being of - type 'str' (bytes) and not unicode text. If the value can be safely - encoded to bytes using the default encoding, prefer that. - - Why the default encoding? Because that value can be implicitly - decoded back to text if needed. - - Ref #1653 - """ - if not six.PY2: - return val - try: - return val.encode() - except UnicodeEncodeError: - pass - return val - def _set_command_options(self, command_obj, option_dict=None): """ Set the options for 'command_obj' from 'option_dict'. Basically @@ -669,7 +643,7 @@ class Distribution(_Distribution): neg_opt = {} try: - is_string = isinstance(value, six.string_types) + is_string = isinstance(value, str) if option in neg_opt and is_string: setattr(command_obj, neg_opt[option], not strtobool(value)) elif option in bool_opts and is_string: @@ -1003,7 +977,7 @@ class Distribution(_Distribution): """ import sys - if six.PY2 or self.help_commands: + if self.help_commands: return _Distribution.handle_display_options(self, option_order) # Stdout may be StringIO (e.g. in tests) diff --git a/setuptools/extension.py b/setuptools/extension.py index 2946889..1820722 100644 --- a/setuptools/extension.py +++ b/setuptools/extension.py @@ -4,8 +4,6 @@ import distutils.core import distutils.errors import distutils.extension -from setuptools.extern.six.moves import map - from .monkey import get_unpatched diff --git a/setuptools/extern/__init__.py b/setuptools/extern/__init__.py index 4e79aa1..b7f30dc 100644 --- a/setuptools/extern/__init__.py +++ b/setuptools/extern/__init__.py @@ -62,5 +62,5 @@ class VendorImporter: sys.meta_path.append(self) -names = 'six', 'packaging', 'pyparsing', 'ordered_set', +names = 'packaging', 'pyparsing', 'ordered_set', VendorImporter(__name__, names, 'setuptools._vendor').install() diff --git a/setuptools/installer.py b/setuptools/installer.py index e5acec2..e630b87 100644 --- a/setuptools/installer.py +++ b/setuptools/installer.py @@ -2,20 +2,18 @@ import glob import os import subprocess import sys +import tempfile from distutils import log from distutils.errors import DistutilsError import pkg_resources from setuptools.command.easy_install import easy_install -from setuptools.extern import six from setuptools.wheel import Wheel -from .py31compat import TemporaryDirectory - def _fixup_find_links(find_links): """Ensure find-links option end-up being a list of strings.""" - if isinstance(find_links, six.string_types): + if isinstance(find_links, str): return find_links.split() assert isinstance(find_links, (tuple, list)) return find_links @@ -103,7 +101,7 @@ def fetch_build_egg(dist, req): for egg_dist in pkg_resources.find_distributions(eggs_dir): if egg_dist in req and environment.can_add(egg_dist): return egg_dist - with TemporaryDirectory() as tmpdir: + with tempfile.TemporaryDirectory() as tmpdir: cmd = [ sys.executable, '-m', 'pip', '--disable-pip-version-check', diff --git a/setuptools/lib2to3_ex.py b/setuptools/lib2to3_ex.py index 017f728..c176abf 100644 --- a/setuptools/lib2to3_ex.py +++ b/setuptools/lib2to3_ex.py @@ -2,9 +2,6 @@ Customized Mixin2to3 support: - adds support for converting doctests - - -This module raises an ImportError on Python 2. """ import warnings diff --git a/setuptools/monkey.py b/setuptools/monkey.py index e5f1377..fb36dc1 100644 --- a/setuptools/monkey.py +++ b/setuptools/monkey.py @@ -10,8 +10,6 @@ import functools from importlib import import_module import inspect -from setuptools.extern import six - import setuptools __all__ = [] @@ -37,7 +35,7 @@ def _get_mro(cls): def get_unpatched(item): lookup = ( - get_unpatched_class if isinstance(item, six.class_types) else + get_unpatched_class if isinstance(item, type) else get_unpatched_function if isinstance(item, types.FunctionType) else lambda item: None ) diff --git a/setuptools/msvc.py b/setuptools/msvc.py index 72383eb..1ead72b 100644 --- a/setuptools/msvc.py +++ b/setuptools/msvc.py @@ -30,12 +30,10 @@ import subprocess import distutils.errors from setuptools.extern.packaging.version import LegacyVersion -from setuptools.extern.six.moves import filterfalse - from .monkey import get_unpatched if platform.system() == 'Windows': - from setuptools.extern.six.moves import winreg + import winreg from os import environ else: # Mock winreg and environ so the module can be imported on this platform. @@ -340,7 +338,7 @@ def _augment_exception(exc, version, arch=''): if "vcvarsall" in message.lower() or "visual c" in message.lower(): # Special error message if MSVC++ not installed - tmpl = 'Microsoft Visual C++ {version:0.1f} is required.' + tmpl = 'Microsoft Visual C++ {version:0.1f} or greater is required.' message = tmpl.format(**locals()) msdownload = 'www.microsoft.com/download/details.aspx?id=%d' if version == 9.0: @@ -360,8 +358,9 @@ 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 "Build Tools for Visual Studio": ' - r'https://visualstudio.microsoft.com/downloads/') + message += (' Get it with "Microsoft C++ Build Tools": ' + r'https://visualstudio.microsoft.com' + r'/visual-cpp-build-tools/') exc.args = (message, ) @@ -1820,7 +1819,7 @@ class EnvironmentInfo: seen = set() seen_add = seen.add if key is None: - for element in filterfalse(seen.__contains__, iterable): + for element in itertools.filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: diff --git a/setuptools/namespaces.py b/setuptools/namespaces.py index 5f403c9..44939e1 100644 --- a/setuptools/namespaces.py +++ b/setuptools/namespaces.py @@ -2,8 +2,6 @@ import os from distutils import log import itertools -from setuptools.extern.six.moves import map - flatten = itertools.chain.from_iterable @@ -72,8 +70,6 @@ class Installer: return "sys._getframe(1).f_locals['sitedir']" def _gen_nspkg_line(self, pkg): - # ensure pkg is not a unicode string under Python 2.7 - pkg = str(pkg) pth = tuple(pkg.split('.')) root = self._get_root() tmpl_lines = self._nspkg_tmpl diff --git a/setuptools/package_index.py b/setuptools/package_index.py index 1702c7c..3979b13 100644 --- a/setuptools/package_index.py +++ b/setuptools/package_index.py @@ -2,17 +2,21 @@ import sys import os import re +import io import shutil import socket import base64 import hashlib import itertools import warnings +import configparser +import html +import http.client +import urllib.parse +import urllib.request +import urllib.error from functools import wraps -from setuptools.extern import six -from setuptools.extern.six.moves import urllib, http_client, configparser, map - import setuptools from pkg_resources import ( CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST, @@ -23,12 +27,8 @@ from setuptools import ssl_support from distutils import log from distutils.errors import DistutilsError from fnmatch import translate -from setuptools.py27compat import get_all_headers -from setuptools.py33compat import unescape from setuptools.wheel import Wheel -__metaclass__ = type - EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$') HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I) PYPI_MD5 = re.compile( @@ -191,7 +191,7 @@ def unique_everseen(iterable, key=None): seen = set() seen_add = seen.add if key is None: - for element in six.moves.filterfalse(seen.__contains__, iterable): + for element in itertools.filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: @@ -740,7 +740,7 @@ class PackageIndex(Environment): size = -1 if "content-length" in headers: # Some servers return multiple Content-Length headers :( - sizes = get_all_headers(headers, 'Content-Length') + sizes = headers.get_all('Content-Length') size = max(map(int, sizes)) self.reporthook(url, filename, blocknum, bs, size) with open(filename, 'wb') as tfp: @@ -767,7 +767,7 @@ class PackageIndex(Environment): return local_open(url) try: return open_with_auth(url, self.opener) - except (ValueError, http_client.InvalidURL) as v: + except (ValueError, http.client.InvalidURL) as v: msg = ' '.join([str(arg) for arg in v.args]) if warning: self.warn(warning, msg) @@ -781,7 +781,7 @@ class PackageIndex(Environment): else: raise DistutilsError("Download error for %s: %s" % (url, v.reason)) from v - except http_client.BadStatusLine as v: + except http.client.BadStatusLine as v: if warning: self.warn(warning, v.line) else: @@ -790,7 +790,7 @@ class PackageIndex(Environment): 'down, %s' % (url, v.line) ) from v - except (http_client.HTTPException, socket.error) as v: + except (http.client.HTTPException, socket.error) as v: if warning: self.warn(warning, v) else: @@ -940,7 +940,7 @@ entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub def decode_entity(match): what = match.group(0) - return unescape(what) + return html.unescape(what) def htmldecode(text): @@ -972,8 +972,7 @@ def socket_timeout(timeout=15): def _encode_auth(auth): """ - A function compatible with Python 2.3-3.3 that will encode - auth from a URL suitable for an HTTP header. + Encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' @@ -1056,7 +1055,7 @@ def open_with_auth(url, opener=urllib.request.urlopen): # Double scheme does not raise on macOS as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): - raise http_client.InvalidURL("nonnumeric port: ''") + raise http.client.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, address = _splituser(netloc) @@ -1136,5 +1135,5 @@ def local_open(url): status, message, body = 404, "Path not found", "Not found" headers = {'content-type': 'text/html'} - body_stream = six.StringIO(body) + body_stream = io.StringIO(body) return urllib.error.HTTPError(url, status, message, headers, body_stream) diff --git a/setuptools/py27compat.py b/setuptools/py27compat.py deleted file mode 100644 index ba39af5..0000000 --- a/setuptools/py27compat.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -Compatibility Support for Python 2.7 and earlier -""" - -import sys -import platform - -from setuptools.extern import six - - -def get_all_headers(message, key): - """ - Given an HTTPMessage, return all headers matching a given key. - """ - return message.get_all(key) - - -if six.PY2: - def get_all_headers(message, key): # noqa - return message.getheaders(key) - - -linux_py2_ascii = ( - platform.system() == 'Linux' and - six.PY2 -) - -rmtree_safe = str if linux_py2_ascii else lambda x: x -"""Workaround for http://bugs.python.org/issue24672""" - - -try: - from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE - from ._imp import get_frozen_object, get_module -except ImportError: - import imp - from imp import PY_COMPILED, PY_FROZEN, PY_SOURCE # noqa - - def find_module(module, paths=None): - """Just like 'imp.find_module()', but with package support""" - parts = module.split('.') - while parts: - part = parts.pop(0) - f, path, (suffix, mode, kind) = info = imp.find_module(part, paths) - - if kind == imp.PKG_DIRECTORY: - parts = parts or ['__init__'] - paths = [path] - - elif parts: - raise ImportError("Can't find %r in %s" % (parts, module)) - - return info - - def get_frozen_object(module, paths): - return imp.get_frozen_object(module) - - def get_module(module, paths, info): - imp.load_module(module, *info) - return sys.modules[module] diff --git a/setuptools/py31compat.py b/setuptools/py31compat.py deleted file mode 100644 index e1da7ee..0000000 --- a/setuptools/py31compat.py +++ /dev/null @@ -1,32 +0,0 @@ -__all__ = [] - -__metaclass__ = type - - -try: - # Python >=3.2 - from tempfile import TemporaryDirectory -except ImportError: - import shutil - import tempfile - - class TemporaryDirectory: - """ - Very simple temporary directory context manager. - Will try to delete afterward, but will also ignore OS and similar - errors on deletion. - """ - - def __init__(self, **kwargs): - self.name = None # Handle mkdtemp raising an exception - self.name = tempfile.mkdtemp(**kwargs) - - def __enter__(self): - return self.name - - def __exit__(self, exctype, excvalue, exctrace): - try: - shutil.rmtree(self.name, True) - except OSError: # removal errors are not the only possible - pass - self.name = None diff --git a/setuptools/py33compat.py b/setuptools/py33compat.py deleted file mode 100644 index cb69443..0000000 --- a/setuptools/py33compat.py +++ /dev/null @@ -1,59 +0,0 @@ -import dis -import array -import collections - -try: - import html -except ImportError: - html = None - -from setuptools.extern import six -from setuptools.extern.six.moves import html_parser - -__metaclass__ = type - -OpArg = collections.namedtuple('OpArg', 'opcode arg') - - -class Bytecode_compat: - def __init__(self, code): - self.code = code - - def __iter__(self): - """Yield '(op,arg)' pair for each operation in code object 'code'""" - - bytes = array.array('b', self.code.co_code) - eof = len(self.code.co_code) - - ptr = 0 - extended_arg = 0 - - while ptr < eof: - - op = bytes[ptr] - - if op >= dis.HAVE_ARGUMENT: - - arg = bytes[ptr + 1] + bytes[ptr + 2] * 256 + extended_arg - ptr += 3 - - if op == dis.EXTENDED_ARG: - long_type = six.integer_types[-1] - extended_arg = arg * long_type(65536) - continue - - else: - arg = None - ptr += 1 - - yield OpArg(op, arg) - - -Bytecode = getattr(dis, 'Bytecode', Bytecode_compat) - - -unescape = getattr(html, 'unescape', None) -if unescape is None: - # HTMLParser.unescape is deprecated since Python 3.4, and will be removed - # from 3.9. - unescape = html_parser.HTMLParser().unescape diff --git a/setuptools/sandbox.py b/setuptools/sandbox.py index 24a3608..91b960d 100644 --- a/setuptools/sandbox.py +++ b/setuptools/sandbox.py @@ -8,9 +8,7 @@ import re import contextlib import pickle import textwrap - -from setuptools.extern import six -from setuptools.extern.six.moves import builtins, map +import builtins import pkg_resources from distutils.errors import DistutilsError @@ -138,7 +136,7 @@ class ExceptionSaver: return type, exc = map(pickle.loads, self._saved) - six.reraise(type, exc, self._tb) + raise exc.with_traceback(self._tb) @contextlib.contextmanager @@ -251,15 +249,8 @@ def run_setup(setup_script, args): working_set.__init__() working_set.callbacks.append(lambda dist: dist.activate()) - # __file__ should be a byte string on Python 2 (#712) - dunder_file = ( - setup_script - if isinstance(setup_script, str) else - setup_script.encode(sys.getfilesystemencoding()) - ) - with DirectorySandbox(setup_dir): - ns = dict(__file__=dunder_file, __name__='__main__') + ns = dict(__file__=setup_script, __name__='__main__') _execfile(setup_script, ns) except SystemExit as v: if v.args and v.args[0]: diff --git a/setuptools/ssl_support.py b/setuptools/ssl_support.py index 17c14c4..eac5e65 100644 --- a/setuptools/ssl_support.py +++ b/setuptools/ssl_support.py @@ -3,8 +3,9 @@ import socket import atexit import re import functools +import urllib.request +import http.client -from setuptools.extern.six.moves import urllib, http_client, map, filter from pkg_resources import ResolutionError, ExtractionError @@ -31,7 +32,7 @@ cert_paths = """ try: HTTPSHandler = urllib.request.HTTPSHandler - HTTPSConnection = http_client.HTTPSConnection + HTTPSConnection = http.client.HTTPSConnection except AttributeError: HTTPSHandler = HTTPSConnection = object diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py index 6377d78..a7a2112 100644 --- a/setuptools/tests/__init__.py +++ b/setuptools/tests/__init__.py @@ -2,19 +2,12 @@ import locale import pytest -from setuptools.extern.six import PY2, PY3 - -__all__ = [ - 'fail_on_ascii', 'py2_only', 'py3_only', 'ack_2to3' -] +__all__ = ['fail_on_ascii', 'ack_2to3'] is_ascii = locale.getpreferredencoding() == 'ANSI_X3.4-1968' fail_on_ascii = pytest.mark.xfail(is_ascii, reason="Test fails in this locale") -py2_only = pytest.mark.skipif(not PY2, reason="Test runs on Python 2 only") -py3_only = pytest.mark.skipif(not PY3, reason="Test runs on Python 3 only") - ack_2to3 = pytest.mark.filterwarnings('ignore:2to3 support is deprecated') diff --git a/setuptools/tests/contexts.py b/setuptools/tests/contexts.py index 535ae10..51ce898 100644 --- a/setuptools/tests/contexts.py +++ b/setuptools/tests/contexts.py @@ -4,8 +4,8 @@ import shutil import sys import contextlib import site +import io -from setuptools.extern import six import pkg_resources @@ -58,8 +58,8 @@ def quiet(): old_stdout = sys.stdout old_stderr = sys.stderr - new_stdout = sys.stdout = six.StringIO() - new_stderr = sys.stderr = six.StringIO() + new_stdout = sys.stdout = io.StringIO() + new_stderr = sys.stderr = io.StringIO() try: yield new_stdout, new_stderr finally: diff --git a/setuptools/tests/namespaces.py b/setuptools/tests/namespaces.py index ef5ecda..245cf8e 100644 --- a/setuptools/tests/namespaces.py +++ b/setuptools/tests/namespaces.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, unicode_literals - import textwrap diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py index 8b17b08..7e21323 100644 --- a/setuptools/tests/server.py +++ b/setuptools/tests/server.py @@ -4,13 +4,12 @@ import os import time import threading +import http.server +import urllib.parse +import urllib.request -from setuptools.extern.six.moves import BaseHTTPServer, SimpleHTTPServer -from setuptools.extern.six.moves.urllib_parse import urljoin -from setuptools.extern.six.moves.urllib.request import pathname2url - -class IndexServer(BaseHTTPServer.HTTPServer): +class IndexServer(http.server.HTTPServer): """Basic single-threaded http server simulating a package index You can use this server in unittest like this:: @@ -24,8 +23,8 @@ class IndexServer(BaseHTTPServer.HTTPServer): def __init__( self, server_address=('', 0), - RequestHandlerClass=SimpleHTTPServer.SimpleHTTPRequestHandler): - BaseHTTPServer.HTTPServer.__init__( + RequestHandlerClass=http.server.SimpleHTTPRequestHandler): + http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass) self._run = True @@ -48,14 +47,14 @@ class IndexServer(BaseHTTPServer.HTTPServer): return 'http://127.0.0.1:%s/setuptools/tests/indexes/' % port -class RequestRecorder(BaseHTTPServer.BaseHTTPRequestHandler): +class RequestRecorder(http.server.BaseHTTPRequestHandler): def do_GET(self): requests = vars(self.server).setdefault('requests', []) requests.append(self) self.send_response(200, 'OK') -class MockServer(BaseHTTPServer.HTTPServer, threading.Thread): +class MockServer(http.server.HTTPServer, threading.Thread): """ A simple HTTP Server that records the requests made to it. """ @@ -63,7 +62,7 @@ class MockServer(BaseHTTPServer.HTTPServer, threading.Thread): def __init__( self, server_address=('', 0), RequestHandlerClass=RequestRecorder): - BaseHTTPServer.HTTPServer.__init__( + http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass) threading.Thread.__init__(self) self.setDaemon(True) @@ -87,5 +86,5 @@ def path_to_url(path, authority=None): base = 'file:' if authority is not None: base += '//' + authority - url = urljoin(base, pathname2url(path)) + url = urllib.parse.urljoin(base, urllib.request.pathname2url(path)) return url diff --git a/setuptools/tests/test_archive_util.py b/setuptools/tests/test_archive_util.py index b789e9a..7f99624 100644 --- a/setuptools/tests/test_archive_util.py +++ b/setuptools/tests/test_archive_util.py @@ -3,8 +3,6 @@ import tarfile import io -from setuptools.extern import six - import pytest from setuptools import archive_util @@ -22,8 +20,6 @@ def tarfile_with_unicode(tmpdir): data = b"" filename = "testimäge.png" - if six.PY2: - filename = filename.decode('utf-8') t = tarfile.TarInfo(filename) t.size = len(data) @@ -39,4 +35,4 @@ def tarfile_with_unicode(tmpdir): @pytest.mark.xfail(reason="#710 and #712") def test_unicode_files(tarfile_with_unicode, tmpdir): target = tmpdir / 'out' - archive_util.unpack_archive(tarfile_with_unicode, six.text_type(target)) + archive_util.unpack_archive(tarfile_with_unicode, str(target)) diff --git a/setuptools/tests/test_build_ext.py b/setuptools/tests/test_build_ext.py index 2ef8521..838fdb4 100644 --- a/setuptools/tests/test_build_ext.py +++ b/setuptools/tests/test_build_ext.py @@ -2,8 +2,6 @@ import sys import distutils.command.build_ext as orig from distutils.sysconfig import get_config_var -from setuptools.extern import six - from setuptools.command.build_ext import build_ext, get_abi3_suffix from setuptools.dist import Distribution from setuptools.extension import Extension @@ -41,7 +39,7 @@ class TestBuildExt: assert 'spam.eggs' in cmd.ext_map res = cmd.get_ext_filename('spam.eggs') - if six.PY2 or not get_abi3_suffix(): + if not get_abi3_suffix(): assert res.endswith(get_config_var('EXT_SUFFIX')) elif sys.platform == 'win32': assert res.endswith('eggs.pyd') diff --git a/setuptools/tests/test_build_meta.py b/setuptools/tests/test_build_meta.py index fdb4b95..5462b26 100644 --- a/setuptools/tests/test_build_meta.py +++ b/setuptools/tests/test_build_meta.py @@ -1,20 +1,13 @@ -from __future__ import unicode_literals - import os import shutil import tarfile +import importlib +from concurrent import futures import pytest from .files import build_files from .textwrap import DALS -from . import py2_only - -__metaclass__ = type - -# Backports on Python 2.7 -import importlib -from concurrent import futures class BuildBackendBase: @@ -220,15 +213,6 @@ class TestBuildMetaBackend: assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA')) - @py2_only - def test_prepare_metadata_for_build_wheel_with_str(self, build_backend): - dist_dir = os.path.abspath(str('pip-dist-info')) - os.makedirs(dist_dir) - - dist_info = build_backend.prepare_metadata_for_build_wheel(dist_dir) - - assert os.path.isfile(os.path.join(dist_dir, dist_info, 'METADATA')) - def test_build_sdist_explicit_dist(self, build_backend): # explicitly specifying the dist folder should work # the folder sdist_directory and the ``--dist-dir`` can be the same diff --git a/setuptools/tests/test_config.py b/setuptools/tests/test_config.py index 67992c0..1dee127 100644 --- a/setuptools/tests/test_config.py +++ b/setuptools/tests/test_config.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import contextlib +import configparser import pytest @@ -9,9 +7,6 @@ from distutils.errors import DistutilsOptionError, DistutilsFileError from mock import patch from setuptools.dist import Distribution, _Distribution from setuptools.config import ConfigHandler, read_configuration -from setuptools.extern.six.moves import configparser -from setuptools.extern import six -from . import py2_only, py3_only from .textwrap import DALS @@ -311,10 +306,6 @@ class TestMetadata: with get_dist(tmpdir) as dist: assert dist.metadata.version == '2016.11.26' - if six.PY2: - # static version loading is unsupported on Python 2 - return - config.write( '[metadata]\n' 'version = attr: fake_package.subpkg_b.mod.VERSION\n' @@ -719,19 +710,6 @@ class TestOptions: assert set(dist.packages) == set( ['fake_package', 'fake_package.sub_two']) - @py2_only - def test_find_namespace_directive_fails_on_py2(self, tmpdir): - dir_package, config = fake_env( - tmpdir, - '[options]\n' - 'packages = find_namespace:\n' - ) - - with pytest.raises(DistutilsOptionError): - with get_dist(tmpdir) as dist: - dist.parse_config_files() - - @py3_only def test_find_namespace_directive(self, tmpdir): dir_package, config = fake_env( tmpdir, diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py index bb89a86..9854420 100644 --- a/setuptools/tests/test_develop.py +++ b/setuptools/tests/test_develop.py @@ -1,8 +1,6 @@ """develop tests """ -from __future__ import absolute_import, unicode_literals - import os import site import sys @@ -10,7 +8,6 @@ import io import subprocess import platform -from setuptools.extern import six from setuptools.command import test import pytest @@ -97,7 +94,7 @@ class TestDevelop: with io.open(fn) as init_file: init = init_file.read().strip() - expected = 'print "foo"' if six.PY2 else 'print("foo")' + expected = 'print("foo")' assert init == expected def test_console_scripts(self, tmpdir): @@ -163,7 +160,7 @@ class TestNamespaces: reason="https://github.com/pypa/setuptools/issues/851", ) @pytest.mark.skipif( - platform.python_implementation() == 'PyPy' and not six.PY2, + platform.python_implementation() == 'PyPy', reason="https://github.com/pypa/setuptools/issues/1202", ) def test_namespace_package_importable(self, tmpdir): diff --git a/setuptools/tests/test_dist.py b/setuptools/tests/test_dist.py index 531ea1b..cb47fb5 100644 --- a/setuptools/tests/test_dist.py +++ b/setuptools/tests/test_dist.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - import io import collections import re import functools +import urllib.request +import urllib.parse from distutils.errors import DistutilsSetupError from setuptools.dist import ( _get_unpatched, @@ -14,9 +12,6 @@ from setuptools.dist import ( ) from setuptools import sic from setuptools import Distribution -from setuptools.extern.six.moves.urllib.request import pathname2url -from setuptools.extern.six.moves.urllib_parse import urljoin -from setuptools.extern import six from .textwrap import DALS from .test_easy_install import make_nspkg_sdist @@ -29,7 +24,8 @@ def test_dist_fetch_build_egg(tmpdir): Check multiple calls to `Distribution.fetch_build_egg` work as expected. """ index = tmpdir.mkdir('index') - index_url = urljoin('file://', pathname2url(str(index))) + index_url = urllib.parse.urljoin( + 'file://', urllib.request.pathname2url(str(index))) def sdist_with_index(distname, version): dist_dir = index.mkdir(distname) @@ -63,8 +59,7 @@ def test_dist_fetch_build_egg(tmpdir): dist.fetch_build_egg(r) for r in reqs ] - # noqa below because on Python 2 it causes flakes - assert [dist.key for dist in resolved_dists if dist] == reqs # noqa + assert [dist.key for dist in resolved_dists if dist] == reqs def test_dist__get_unpatched_deprecated(): @@ -150,10 +145,7 @@ def test_read_metadata(name, attrs): dist_class = metadata_out.__class__ # Write to PKG_INFO and then load into a new metadata object - if six.PY2: - PKG_INFO = io.BytesIO() - else: - PKG_INFO = io.StringIO() + PKG_INFO = io.StringIO() metadata_out.write_pkg_file(PKG_INFO) diff --git a/setuptools/tests/test_dist_info.py b/setuptools/tests/test_dist_info.py index f7e7d2b..29fbd09 100644 --- a/setuptools/tests/test_dist_info.py +++ b/setuptools/tests/test_dist_info.py @@ -1,10 +1,6 @@ """Test .dist-info style distributions. """ -from __future__ import unicode_literals - -from setuptools.extern.six.moves import map - import pytest import pkg_resources diff --git a/setuptools/tests/test_distutils_adoption.py b/setuptools/tests/test_distutils_adoption.py index daccc47..8edd3f9 100644 --- a/setuptools/tests/test_distutils_adoption.py +++ b/setuptools/tests/test_distutils_adoption.py @@ -48,15 +48,15 @@ def test_distutils_stdlib(venv): """ Ensure stdlib distutils is used when appropriate. """ - assert venv.name not in find_distutils(venv, env=dict()).split(os.sep) + env = dict(SETUPTOOLS_USE_DISTUTILS='stdlib') + assert venv.name not in find_distutils(venv, env=env).split(os.sep) def test_distutils_local_with_setuptools(venv): """ Ensure local distutils is used when appropriate. """ - env = dict(SETUPTOOLS_USE_DISTUTILS='local') - loc = find_distutils(venv, imports='setuptools, distutils', env=env) + loc = find_distutils(venv, imports='setuptools, distutils', env=dict()) assert venv.name in loc.split(os.sep) @@ -66,5 +66,4 @@ def test_distutils_local(venv): Even without importing, the setuptools-local copy of distutils is preferred. """ - env = dict(SETUPTOOLS_USE_DISTUTILS='local') - assert venv.name in find_distutils(venv, env=env).split(os.sep) + assert venv.name in find_distutils(venv, env=dict()).split(os.sep) diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py index c07b5be..26a5e9a 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- """Easy install Tests """ -from __future__ import absolute_import, unicode_literals import sys import os @@ -18,8 +16,6 @@ import mock import time import re -from setuptools.extern import six - import pytest from setuptools import sandbox @@ -41,8 +37,6 @@ from . import contexts from .files import build_files from .textwrap import DALS -__metaclass__ = type - class FakeDist: def get_entry_map(self, group): @@ -984,8 +978,6 @@ def create_setup_requires_package(path, distname='foobar', version='0.1', ) class TestScriptHeader: non_ascii_exe = '/Users/José/bin/python' - if six.PY2: - non_ascii_exe = non_ascii_exe.encode('utf-8') exe_with_spaces = r'C:\Program Files\Python36\python.exe' def test_get_script_header(self): diff --git a/setuptools/tests/test_egg_info.py b/setuptools/tests/test_egg_info.py index 109f913..dc472af 100644 --- a/setuptools/tests/test_egg_info.py +++ b/setuptools/tests/test_egg_info.py @@ -10,7 +10,6 @@ from setuptools.command.egg_info import ( egg_info, manifest_maker, EggInfoDeprecationWarning, get_pkg_info_revision, ) from setuptools.dist import Distribution -from setuptools.extern.six.moves import map import pytest @@ -19,8 +18,6 @@ from .files import build_files from .textwrap import DALS from . import contexts -__metaclass__ = type - class Environment(str): pass @@ -73,8 +70,7 @@ class TestEggInfo: """ When the egg_info section is empty or not present, running save_version_info should add the settings to the setup.cfg - in a deterministic order, consistent with the ordering found - on Python 2.7 with PYTHONHASHSEED=0. + in a deterministic order. """ setup_cfg = os.path.join(env.paths['home'], 'setup.cfg') dist = Distribution() @@ -906,49 +902,3 @@ class TestEggInfo: def test_get_pkg_info_revision_deprecated(self): pytest.warns(EggInfoDeprecationWarning, get_pkg_info_revision) - - EGG_INFO_TESTS = ( - # Check for issue #1136: invalid string type when - # reading declarative `setup.cfg` under Python 2. - { - 'setup.py': DALS( - """ - from setuptools import setup - setup( - name="foo", - ) - """), - 'setup.cfg': DALS( - """ - [options] - package_dir = - = src - """), - 'src': {}, - }, - # Check Unicode can be used in `setup.py` under Python 2. - { - 'setup.py': DALS( - """ - # -*- coding: utf-8 -*- - from __future__ import unicode_literals - from setuptools import setup, find_packages - setup( - name="foo", - package_dir={'': 'src'}, - ) - """), - 'src': {}, - } - ) - - @pytest.mark.parametrize('package_files', EGG_INFO_TESTS) - def test_egg_info(self, tmpdir_cwd, env, package_files): - """ - """ - build_files(package_files) - code, data = environment.run_setup_py( - cmd=['egg_info'], - data_stream=1, - ) - assert not code, data diff --git a/setuptools/tests/test_extern.py b/setuptools/tests/test_extern.py index 3519a68..0d6b164 100644 --- a/setuptools/tests/test_extern.py +++ b/setuptools/tests/test_extern.py @@ -3,7 +3,6 @@ import pickle from setuptools import Distribution from setuptools.extern import ordered_set -from setuptools.tests import py3_only def test_reimport_extern(): @@ -17,6 +16,5 @@ def test_orderedset_pickle_roundtrip(): assert o1 == o2 -@py3_only def test_distribution_picklable(): pickle.loads(pickle.dumps(Distribution())) diff --git a/setuptools/tests/test_find_packages.py b/setuptools/tests/test_find_packages.py index ab26b4f..906713f 100644 --- a/setuptools/tests/test_find_packages.py +++ b/setuptools/tests/test_find_packages.py @@ -7,12 +7,8 @@ import platform import pytest -from . import py3_only - -from setuptools.extern.six import PY3 from setuptools import find_packages -if PY3: - from setuptools import find_namespace_packages +from setuptools import find_namespace_packages # modeled after CPython's test.support.can_symlink @@ -154,34 +150,29 @@ class TestFindPackages: def _assert_packages(self, actual, expected): assert set(actual) == set(expected) - @py3_only def test_pep420_ns_package(self): packages = find_namespace_packages( self.dist_dir, include=['pkg*'], exclude=['pkg.subpkg.assets']) self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_includes(self): packages = find_namespace_packages( self.dist_dir, exclude=['pkg.subpkg.assets']) self._assert_packages( packages, ['docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_includes_or_excludes(self): packages = find_namespace_packages(self.dist_dir) expected = [ 'docs', 'pkg', 'pkg.nspkg', 'pkg.subpkg', 'pkg.subpkg.assets'] self._assert_packages(packages, expected) - @py3_only def test_regular_package_with_nested_pep420_ns_packages(self): self._touch('__init__.py', self.pkg_dir) packages = find_namespace_packages( self.dist_dir, exclude=['docs', 'pkg.subpkg.assets']) self._assert_packages(packages, ['pkg', 'pkg.nspkg', 'pkg.subpkg']) - @py3_only def test_pep420_ns_package_no_non_package_dirs(self): shutil.rmtree(self.docs_dir) shutil.rmtree(os.path.join(self.dist_dir, 'pkg/subpkg/assets')) diff --git a/setuptools/tests/test_integration.py b/setuptools/tests/test_integration.py index f1a27f8..24cef48 100644 --- a/setuptools/tests/test_integration.py +++ b/setuptools/tests/test_integration.py @@ -11,8 +11,8 @@ import subprocess import functools import tarfile import zipfile +import urllib.request -from setuptools.extern.six.moves import urllib import pytest from setuptools.command.easy_install import easy_install diff --git a/setuptools/tests/test_manifest.py b/setuptools/tests/test_manifest.py index 042a8b1..82bdb9c 100644 --- a/setuptools/tests/test_manifest.py +++ b/setuptools/tests/test_manifest.py @@ -7,18 +7,16 @@ import shutil import sys import tempfile import itertools +import io from distutils import log from distutils.errors import DistutilsTemplateError from setuptools.command.egg_info import FileList, egg_info, translate_pattern from setuptools.dist import Distribution -from setuptools.extern import six from setuptools.tests.textwrap import DALS import pytest -__metaclass__ = type - def make_local_path(s): """Converts '/' in a string to os.sep""" @@ -41,7 +39,7 @@ setup(**%r) @contextlib.contextmanager def quiet(): old_stdout, old_stderr = sys.stdout, sys.stderr - sys.stdout, sys.stderr = six.StringIO(), six.StringIO() + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() try: yield finally: diff --git a/setuptools/tests/test_msvc14.py b/setuptools/tests/test_msvc14.py index 7833aab..1aca12d 100644 --- a/setuptools/tests/test_msvc14.py +++ b/setuptools/tests/test_msvc14.py @@ -31,8 +31,6 @@ class TestMSVC14: finally: _msvccompiler._msvc14_find_vcvarsall = old_find_vcvarsall - @pytest.mark.skipif(sys.version_info[0] < 3, - reason="Unicode requires encode/decode on Python 2") def test_get_vc_env_unicode(self): import setuptools.msvc as _msvccompiler diff --git a/setuptools/tests/test_namespaces.py b/setuptools/tests/test_namespaces.py index f937d98..6c8c522 100644 --- a/setuptools/tests/test_namespaces.py +++ b/setuptools/tests/test_namespaces.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import, unicode_literals - import sys import subprocess diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py index 29aace1..8e9435e 100644 --- a/setuptools/tests/test_packageindex.py +++ b/setuptools/tests/test_packageindex.py @@ -1,12 +1,11 @@ -from __future__ import absolute_import - import sys import os import distutils.errors import platform +import urllib.request +import urllib.error +import http.client -from setuptools.extern import six -from setuptools.extern.six.moves import urllib, http_client import mock import pytest @@ -60,7 +59,7 @@ class TestPackageIndex: ) def _urlopen(*args): - raise http_client.BadStatusLine('line') + raise http.client.BadStatusLine('line') index.opener = _urlopen url = 'http://example.com' @@ -84,7 +83,7 @@ class TestPackageIndex: try: index.open_url(url) except distutils.errors.DistutilsError as error: - msg = six.text_type(error) + msg = str(error) assert ( 'nonnumeric port' in msg or 'getaddrinfo failed' in msg diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index 0bea53d..049fdcc 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -1,8 +1,5 @@ -# -*- coding: utf-8 -*- """sdist tests""" -from __future__ import print_function, unicode_literals - import os import sys import tempfile @@ -10,9 +7,6 @@ import unicodedata import contextlib import io -from setuptools.extern import six -from setuptools.extern.six.moves import map - import pytest import pkg_resources @@ -21,7 +15,6 @@ from setuptools.command.egg_info import manifest_maker from setuptools.dist import Distribution from setuptools.tests import fail_on_ascii from .text import Filenames -from . import py3_only SETUP_ATTRS = { @@ -42,7 +35,7 @@ setup(**%r) @contextlib.contextmanager def quiet(): old_stdout, old_stderr = sys.stdout, sys.stderr - sys.stdout, sys.stderr = six.StringIO(), six.StringIO() + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() try: yield finally: @@ -51,7 +44,7 @@ def quiet(): # Convert to POSIX path def posix(path): - if not six.PY2 and not isinstance(path, str): + if not isinstance(path, str): return path.replace(os.sep.encode('ascii'), b'/') else: return path.replace(os.sep, '/') @@ -59,7 +52,7 @@ def posix(path): # HFS Plus uses decomposed UTF-8 def decompose(path): - if isinstance(path, six.text_type): + if isinstance(path, str): return unicodedata.normalize('NFD', path) try: path = path.decode('utf-8') @@ -231,7 +224,6 @@ class TestSdistTest: # The manifest should contain the UTF-8 filename assert posix(filename) in u_contents - @py3_only @fail_on_ascii def test_write_manifest_allows_utf8_filenames(self): # Test for #303. @@ -265,7 +257,6 @@ class TestSdistTest: # The filelist should have been updated as well assert u_filename in mm.filelist.files - @py3_only def test_write_manifest_skips_non_utf8_filenames(self): """ Files that cannot be encoded to UTF-8 (specifically, those that @@ -329,11 +320,9 @@ class TestSdistTest: cmd.read_manifest() # The filelist should contain the UTF-8 filename - if not six.PY2: - filename = filename.decode('utf-8') + filename = filename.decode('utf-8') assert filename in cmd.filelist.files - @py3_only @fail_on_latin1_encoded_filenames def test_read_manifest_skips_non_utf8_filenames(self): # Test for #303. @@ -383,21 +372,18 @@ class TestSdistTest: if sys.platform == 'darwin': filename = decompose(filename) - if not six.PY2: - fs_enc = sys.getfilesystemencoding() + fs_enc = sys.getfilesystemencoding() - if sys.platform == 'win32': - if fs_enc == 'cp1252': - # Python 3 mangles the UTF-8 filename - filename = filename.decode('cp1252') - assert filename in cmd.filelist.files - else: - filename = filename.decode('mbcs') - assert filename in cmd.filelist.files + if sys.platform == 'win32': + if fs_enc == 'cp1252': + # Python mangles the UTF-8 filename + filename = filename.decode('cp1252') + assert filename in cmd.filelist.files else: - filename = filename.decode('utf-8') + filename = filename.decode('mbcs') assert filename in cmd.filelist.files else: + filename = filename.decode('utf-8') assert filename in cmd.filelist.files @classmethod @@ -425,33 +411,20 @@ class TestSdistTest: with quiet(): cmd.run() - if six.PY2: - # Under Python 2 there seems to be no decoded string in the - # filelist. However, due to decode and encoding of the - # file name to get utf-8 Manifest the latin1 maybe excluded - try: - # fs_enc should match how one is expect the decoding to - # be proformed for the manifest output. - fs_enc = sys.getfilesystemencoding() - filename.decode(fs_enc) - assert filename in cmd.filelist.files - except UnicodeDecodeError: - filename not in cmd.filelist.files - else: - # not all windows systems have a default FS encoding of cp1252 - if sys.platform == 'win32': - # Latin-1 is similar to Windows-1252 however - # on mbcs filesys it is not in latin-1 encoding - fs_enc = sys.getfilesystemencoding() - if fs_enc != 'mbcs': - fs_enc = 'latin-1' - filename = filename.decode(fs_enc) + # not all windows systems have a default FS encoding of cp1252 + if sys.platform == 'win32': + # Latin-1 is similar to Windows-1252 however + # on mbcs filesys it is not in latin-1 encoding + fs_enc = sys.getfilesystemencoding() + if fs_enc != 'mbcs': + fs_enc = 'latin-1' + filename = filename.decode(fs_enc) - assert filename in cmd.filelist.files - else: - # The Latin-1 filename should have been skipped - filename = filename.decode('latin-1') - filename not in cmd.filelist.files + assert filename in cmd.filelist.files + else: + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + filename not in cmd.filelist.files def test_pyproject_toml_in_sdist(self, tmpdir): """ diff --git a/setuptools/tests/test_setopt.py b/setuptools/tests/test_setopt.py index 1b03895..0163f9a 100644 --- a/setuptools/tests/test_setopt.py +++ b/setuptools/tests/test_setopt.py @@ -1,13 +1,7 @@ -# coding: utf-8 - -from __future__ import unicode_literals - import io - -import six +import configparser from setuptools.command import setopt -from setuptools.extern.six.moves import configparser class TestEdit: @@ -15,7 +9,7 @@ class TestEdit: def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: - (parser.readfp if six.PY2 else parser.read_file)(reader) + parser.read_file(reader) return parser @staticmethod diff --git a/setuptools/tests/test_setuptools.py b/setuptools/tests/test_setuptools.py index 08d263a..42f8e18 100644 --- a/setuptools/tests/test_setuptools.py +++ b/setuptools/tests/test_setuptools.py @@ -15,7 +15,6 @@ import setuptools import setuptools.dist import setuptools.depends as dep from setuptools.depends import Require -from setuptools.extern import six def makeSetup(**args): @@ -49,7 +48,7 @@ class TestDepends: x = "test" y = z - fc = six.get_function_code(f1) + fc = f1.__code__ # unrecognized name assert dep.extract_constant(fc, 'q', -1) is None diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py index 892fd12..180562e 100644 --- a/setuptools/tests/test_test.py +++ b/setuptools/tests/test_test.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - import mock from distutils import log import os @@ -110,7 +106,6 @@ def test_tests_are_run_once(capfd): with open('dummy/test_dummy.py', 'wt') as f: f.write(DALS( """ - from __future__ import print_function import unittest class TestTest(unittest.TestCase): def test_test(self): diff --git a/setuptools/tests/test_virtualenv.py b/setuptools/tests/test_virtualenv.py index 555273a..b555ce4 100644 --- a/setuptools/tests/test_virtualenv.py +++ b/setuptools/tests/test_virtualenv.py @@ -12,17 +12,6 @@ from .textwrap import DALS from .test_easy_install import make_nspkg_sdist -@pytest.fixture(autouse=True) -def disable_requires_python(monkeypatch): - """ - Disable Requires-Python on Python 2.7 - """ - if sys.version_info > (3,): - return - - monkeypatch.setenv('PIP_IGNORE_REQUIRES_PYTHON', 'true') - - @pytest.fixture(autouse=True) def pytest_virtualenv_works(virtualenv): """ diff --git a/setuptools/tests/test_wheel.py b/setuptools/tests/test_wheel.py index f72ccbb..e56eac1 100644 --- a/setuptools/tests/test_wheel.py +++ b/setuptools/tests/test_wheel.py @@ -25,8 +25,6 @@ from .contexts import tempdir from .files import build_files from .textwrap import DALS -__metaclass__ = type - WHEEL_INFO_TESTS = ( ('invalid.whl', ValueError), diff --git a/setuptools/tests/test_windows_wrappers.py b/setuptools/tests/test_windows_wrappers.py index 2553394..fa647de 100644 --- a/setuptools/tests/test_windows_wrappers.py +++ b/setuptools/tests/test_windows_wrappers.py @@ -12,8 +12,6 @@ the script they are to wrap and with the same name as the script they are to wrap. """ -from __future__ import absolute_import - import sys import textwrap import subprocess diff --git a/setuptools/tests/text.py b/setuptools/tests/text.py index ad2c624..e05cc63 100644 --- a/setuptools/tests/text.py +++ b/setuptools/tests/text.py @@ -1,8 +1,3 @@ -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - - class Filenames: unicode = 'smörbröd.py' latin_1 = unicode.encode('latin-1') diff --git a/setuptools/tests/textwrap.py b/setuptools/tests/textwrap.py index 5cd9e5b..5e39618 100644 --- a/setuptools/tests/textwrap.py +++ b/setuptools/tests/textwrap.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import textwrap diff --git a/setuptools/unicode_utils.py b/setuptools/unicode_utils.py index 7c63efd..e84e65e 100644 --- a/setuptools/unicode_utils.py +++ b/setuptools/unicode_utils.py @@ -1,12 +1,10 @@ import unicodedata import sys -from setuptools.extern import six - # HFS Plus uses decomposed UTF-8 def decompose(path): - if isinstance(path, six.text_type): + if isinstance(path, str): return unicodedata.normalize('NFD', path) try: path = path.decode('utf-8') @@ -23,7 +21,7 @@ def filesys_decode(path): NONE when no expected encoding works """ - if isinstance(path, six.text_type): + if isinstance(path, str): return path fs_enc = sys.getfilesystemencoding() or 'utf-8' diff --git a/setuptools/wheel.py b/setuptools/wheel.py index ca09bd1..0be811a 100644 --- a/setuptools/wheel.py +++ b/setuptools/wheel.py @@ -14,13 +14,9 @@ import setuptools from pkg_resources import parse_version from setuptools.extern.packaging.tags import sys_tags from setuptools.extern.packaging.utils import canonicalize_name -from setuptools.extern.six import PY3 from setuptools.command.egg_info import write_requirements -__metaclass__ = type - - WHEEL_NAME = re.compile( r"""^(?P.+?)-(?P\d.*?) ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) @@ -112,7 +108,7 @@ class Wheel: def _convert_metadata(zf, destination_eggdir, dist_info, egg_info): def get_metadata(name): with zf.open(posixpath.join(dist_info, name)) as fp: - value = fp.read().decode('utf-8') if PY3 else fp.read() + value = fp.read().decode('utf-8') return email.parser.Parser().parsestr(value) wheel_metadata = get_metadata('WHEEL') diff --git a/tools/tox_pip.py b/tools/tox_pip.py index 9fe4f90..be2ff1d 100644 --- a/tools/tox_pip.py +++ b/tools/tox_pip.py @@ -12,7 +12,7 @@ def remove_setuptools(): cmd = [sys.executable, '-m', 'pip', 'uninstall', '-y', 'setuptools'] # set cwd to something other than '.' to avoid detecting # '.' as the installed package. - subprocess.check_call(cmd, cwd='.tox') + subprocess.check_call(cmd, cwd=os.environ['TOX_WORK_DIR']) def bootstrap(): @@ -56,24 +56,12 @@ def test_dependencies(): return filter(None, map(clean, raw)) -def disable_python_requires(): - """ - On Python 2, install the dependencies that are selective - on Python version while honoring REQUIRES_PYTHON, then - disable REQUIRES_PYTHON so that pip can install this - checkout of setuptools. - """ - pip('install', *test_dependencies()) - os.environ['PIP_IGNORE_REQUIRES_PYTHON'] = 'true' - - def run(args): os.environ['PIP_USE_PEP517'] = 'true' if is_install_self(args): remove_setuptools() bootstrap() - sys.version_info > (3,) or disable_python_requires() pip(*args) -- 2.34.1