[bumpversion]
-current_version = 49.6.0
+current_version = 50.0.0
commit = True
tag = True
+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
-------
"""
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'
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):
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()
egg-info command to flesh out the egg-info directory.
"""
-from __future__ import unicode_literals
-
import os
import sys
import textwrap
"""
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)
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('')
-# coding: utf-8
"""
Package resource API
--------------------
method.
"""
-from __future__ import absolute_import
-
import sys
import os
import io
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:
__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
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)
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:
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())
"""
def __bool__(self):
return False
- if six.PY2:
- __nonzero__ = __bool__
def __call__(self, fullpath):
return iter(())
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 ()
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
)
)
- 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(
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
+++ /dev/null
-"""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 <benjamin@python.org>"
-__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)
packaging==20.4
pyparsing==2.2.1
-six==1.10.0
appdirs==1.4.3
sys.meta_path.append(self)
-names = 'packaging', 'pyparsing', 'six', 'appdirs'
+names = 'packaging', 'pyparsing', 'appdirs'
VendorImporter(__name__, names).install()
-# coding: utf-8
-from __future__ import unicode_literals
-
import sys
import tempfile
import os
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):
"""
return time.mktime(dt.timetuple())
-class EggRemover(text_type):
+class EggRemover(str):
def __call__(self):
if self in sys.path:
sys.path.remove(self)
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
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)
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
-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
from .test_resources import Metadata
-__metaclass__ = type
-
def strip_comments(s):
return '\n'.join(
[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
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
_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', '; ')
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
find_packages = PackageFinder.find
-
-if PY3:
- find_namespace_packages = PEP420PackageFinder.find
+find_namespace_packages = PEP420PackageFinder.find
def _install_setup_requires(attrs):
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
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:
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
+++ /dev/null
-"""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 <benjamin@python.org>"
-__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)
packaging==20.4
pyparsing==2.2.1
-six==1.10.0
ordered-set==3.1.1
import tokenize
import shutil
import contextlib
+import tempfile
import setuptools
import distutils
-from setuptools.py31compat import TemporaryDirectory
from pkg_resources import parse_requirements
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))]
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()
# 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"])
from distutils.errors import DistutilsOptionError
-from setuptools.extern.six.moves import map
-
from setuptools.command.setopt import edit_config, option_base, config_file
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):
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
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):
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
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
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)]
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:
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:
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:
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"""
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
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 (
)
import pkg_resources
-__metaclass__ = type
-
# Turn on PEP440Warnings
warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
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):
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 = []
# 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:
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)
# 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'):
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'):
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):
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):
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
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)
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):
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))
from distutils.util import convert_path
from distutils.command import sdist
-from setuptools.extern.six.moves import filter
-
class sdist_add_defaults:
"""
import os
import shutil
-from setuptools.extern import six
-
from setuptools import 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(',')
]
import io
import contextlib
-from setuptools.extern import six, ordered_set
+from setuptools.extern import ordered_set
from .py36compat import sdist_add_defaults
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')
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")
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:
from distutils.errors import DistutilsOptionError
import distutils
import os
-
-from setuptools.extern.six.moves import configparser
+import configparser
from setuptools import Command
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):
@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:
# 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 = []
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):
}
# 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)
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)
-from __future__ import absolute_import, unicode_literals
import ast
import io
import os
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:
"""
include_directive = 'file:'
- if not isinstance(value, string_types):
+ if not isinstance(value, str):
return value
if not value.startswith(include_directive):
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:
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(
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__ = [
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)
const = default
- for byte_code in Bytecode(code):
+ for byte_code in dis.Bytecode(code):
op = byte_code.opcode
arg = byte_code.arg
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
"""
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())
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")
"{!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)
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:
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',
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)
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
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:
"""
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)
import distutils.errors
import distutils.extension
-from setuptools.extern.six.moves import map
-
from .monkey import get_unpatched
sys.meta_path.append(self)
-names = 'six', 'packaging', 'pyparsing', 'ordered_set',
+names = 'packaging', 'pyparsing', 'ordered_set',
VendorImporter(__name__, names, 'setuptools._vendor').install()
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
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',
Customized Mixin2to3 support:
- adds support for converting doctests
-
-
-This module raises an ImportError on Python 2.
"""
import warnings
from importlib import import_module
import inspect
-from setuptools.extern import six
-
import setuptools
__all__ = []
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
)
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.
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:
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, )
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:
from distutils import log
import itertools
-from setuptools.extern.six.moves import map
-
flatten = itertools.chain.from_iterable
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
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,
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(
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:
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:
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)
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:
'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:
def decode_entity(match):
what = match.group(0)
- return unescape(what)
+ return html.unescape(what)
def htmldecode(text):
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='
# 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)
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)
+++ /dev/null
-"""
-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]
+++ /dev/null
-__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
+++ /dev/null
-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
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
return
type, exc = map(pickle.loads, self._saved)
- six.reraise(type, exc, self._tb)
+ raise exc.with_traceback(self._tb)
@contextlib.contextmanager
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]:
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
try:
HTTPSHandler = urllib.request.HTTPSHandler
- HTTPSConnection = http_client.HTTPSConnection
+ HTTPSConnection = http.client.HTTPSConnection
except AttributeError:
HTTPSHandler = HTTPSConnection = object
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')
import sys
import contextlib
import site
+import io
-from setuptools.extern import six
import pkg_resources
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:
-from __future__ import absolute_import, unicode_literals
-
import textwrap
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::
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
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.
"""
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)
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
import tarfile
import io
-from setuptools.extern import six
-
import pytest
from setuptools import archive_util
data = b""
filename = "testimäge.png"
- if six.PY2:
- filename = filename.decode('utf-8')
t = tarfile.TarInfo(filename)
t.size = len(data)
@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))
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
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')
-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:
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
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
import contextlib
+import configparser
import pytest
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
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'
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,
"""develop tests
"""
-from __future__ import absolute_import, unicode_literals
-
import os
import site
import sys
import subprocess
import platform
-from setuptools.extern import six
from setuptools.command import test
import pytest
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):
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):
-# -*- 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,
)
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
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)
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():
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)
"""Test .dist-info style distributions.
"""
-from __future__ import unicode_literals
-
-from setuptools.extern.six.moves import map
-
import pytest
import pkg_resources
"""
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)
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)
-# -*- coding: utf-8 -*-
"""Easy install Tests
"""
-from __future__ import absolute_import, unicode_literals
import sys
import os
import time
import re
-from setuptools.extern import six
-
import pytest
from setuptools import sandbox
from .files import build_files
from .textwrap import DALS
-__metaclass__ = type
-
class FakeDist:
def get_entry_map(self, group):
)
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):
egg_info, manifest_maker, EggInfoDeprecationWarning, get_pkg_info_revision,
)
from setuptools.dist import Distribution
-from setuptools.extern.six.moves import map
import pytest
from .textwrap import DALS
from . import contexts
-__metaclass__ = type
-
class Environment(str):
pass
"""
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()
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
from setuptools import Distribution
from setuptools.extern import ordered_set
-from setuptools.tests import py3_only
def test_reimport_extern():
assert o1 == o2
-@py3_only
def test_distribution_picklable():
pickle.loads(pickle.dumps(Distribution()))
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
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'))
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
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"""
@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:
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
-from __future__ import absolute_import, unicode_literals
-
import sys
import subprocess
-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
)
def _urlopen(*args):
- raise http_client.BadStatusLine('line')
+ raise http.client.BadStatusLine('line')
index.opener = _urlopen
url = 'http://example.com'
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
-# -*- coding: utf-8 -*-
"""sdist tests"""
-from __future__ import print_function, unicode_literals
-
import os
import sys
import tempfile
import contextlib
import io
-from setuptools.extern import six
-from setuptools.extern.six.moves import map
-
import pytest
import pkg_resources
from setuptools.dist import Distribution
from setuptools.tests import fail_on_ascii
from .text import Filenames
-from . import py3_only
SETUP_ATTRS = {
@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:
# 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, '/')
# 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')
# 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.
# 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
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.
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
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):
"""
-# 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:
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
import setuptools.dist
import setuptools.depends as dep
from setuptools.depends import Require
-from setuptools.extern import six
def makeSetup(**args):
x = "test"
y = z
- fc = six.get_function_code(f1)
+ fc = f1.__code__
# unrecognized name
assert dep.extract_constant(fc, 'q', -1) is None
-# -*- coding: utf-8 -*-
-
-from __future__ import unicode_literals
-
import mock
from distutils import log
import os
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):
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):
"""
from .files import build_files
from .textwrap import DALS
-__metaclass__ = type
-
WHEEL_INFO_TESTS = (
('invalid.whl', ValueError),
are to wrap.
"""
-from __future__ import absolute_import
-
import sys
import textwrap
import subprocess
-# -*- coding: utf-8 -*-
-
-from __future__ import unicode_literals
-
-
class Filenames:
unicode = 'smörbröd.py'
latin_1 = unicode.encode('latin-1')
-from __future__ import absolute_import
-
import textwrap
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')
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'
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<project_name>.+?)-(?P<version>\d.*?)
((-(?P<build>\d.*?))?-(?P<py_version>.+?)-(?P<abi>.+?)-(?P<platform>.+?)
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')
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():
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)