mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-09 12:54:17 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -13,32 +13,33 @@ The package resource API is designed to work with normal filesystem packages,
|
|||
.zip files and with custom PEP 302 loaders that support the ``get_data()``
|
||||
method.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import os
|
||||
import io
|
||||
import time
|
||||
import re
|
||||
import types
|
||||
import zipfile
|
||||
import zipimport
|
||||
import warnings
|
||||
import stat
|
||||
import functools
|
||||
import pkgutil
|
||||
import operator
|
||||
import platform
|
||||
import collections
|
||||
import plistlib
|
||||
import email.parser
|
||||
import errno
|
||||
import functools
|
||||
import importlib
|
||||
import inspect
|
||||
import io
|
||||
import itertools
|
||||
import ntpath
|
||||
import operator
|
||||
import os
|
||||
import pkgutil
|
||||
import platform
|
||||
import plistlib
|
||||
import posixpath
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import itertools
|
||||
import inspect
|
||||
import ntpath
|
||||
import posixpath
|
||||
import importlib
|
||||
import time
|
||||
import types
|
||||
import warnings
|
||||
import zipfile
|
||||
import zipimport
|
||||
from pkgutil import get_importer
|
||||
|
||||
try:
|
||||
|
|
@ -78,11 +79,6 @@ __import__('pkg_resources.extern.packaging.specifiers')
|
|||
__import__('pkg_resources.extern.packaging.requirements')
|
||||
__import__('pkg_resources.extern.packaging.markers')
|
||||
|
||||
if sys.version_info < (3, 5):
|
||||
raise RuntimeError("Python 3.5 or later is required")
|
||||
|
||||
# declare some globals that will be defined later to
|
||||
# satisfy the linters.
|
||||
require = None
|
||||
working_set = None
|
||||
add_activation_listener = None
|
||||
|
|
@ -174,9 +170,9 @@ def get_supported_platform():
|
|||
"""
|
||||
plat = get_build_platform()
|
||||
m = macosVersionString.match(plat)
|
||||
if m is not None and sys.platform == "darwin":
|
||||
if m is not None and sys.platform == 'darwin':
|
||||
try:
|
||||
plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
|
||||
plat = 'macosx-{}-{}'.format('.'.join(_macos_vers()[:2]), m.group(3))
|
||||
except ValueError:
|
||||
# not macOS
|
||||
pass
|
||||
|
|
@ -248,7 +244,7 @@ class VersionConflict(ResolutionError):
|
|||
Requirement.
|
||||
"""
|
||||
|
||||
_template = "{self.dist} is installed but {self.req} is required"
|
||||
_template = '{self.dist} is installed but {self.req} is required'
|
||||
|
||||
@property
|
||||
def dist(self):
|
||||
|
|
@ -288,8 +284,10 @@ class ContextualVersionConflict(VersionConflict):
|
|||
class DistributionNotFound(ResolutionError):
|
||||
"""A requested distribution was not found"""
|
||||
|
||||
_template = ("The '{self.req}' distribution was not found "
|
||||
"and is required by {self.requirers_str}")
|
||||
_template = (
|
||||
"The '{self.req}' distribution was not found "
|
||||
'and is required by {self.requirers_str}'
|
||||
)
|
||||
|
||||
@property
|
||||
def req(self):
|
||||
|
|
@ -378,11 +376,11 @@ def get_build_platform():
|
|||
from sysconfig import get_platform
|
||||
|
||||
plat = get_platform()
|
||||
if sys.platform == "darwin" and not plat.startswith('macosx-'):
|
||||
if sys.platform == 'darwin' and not plat.startswith('macosx-'):
|
||||
try:
|
||||
version = _macos_vers()
|
||||
machine = os.uname()[4].replace(" ", "_")
|
||||
return "macosx-%d.%d-%s" % (
|
||||
machine = os.uname()[4].replace(' ', '_')
|
||||
return 'macosx-%d.%d-%s' % (
|
||||
int(version[0]), int(version[1]),
|
||||
_macos_arch(machine),
|
||||
)
|
||||
|
|
@ -393,8 +391,8 @@ def get_build_platform():
|
|||
return plat
|
||||
|
||||
|
||||
macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
|
||||
darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
|
||||
macosVersionString = re.compile(r'macosx-(\d+)\.(\d+)-(.*)')
|
||||
darwinVersionString = re.compile(r'darwin-(\d+)\.(\d+)\.(\d+)-(.*)')
|
||||
# XXX backward compat
|
||||
get_platform = get_build_platform
|
||||
|
||||
|
|
@ -423,9 +421,9 @@ def compatible_platforms(provided, required):
|
|||
provDarwin = darwinVersionString.match(provided)
|
||||
if provDarwin:
|
||||
dversion = int(provDarwin.group(1))
|
||||
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
|
||||
if dversion == 7 and macosversion >= "10.3" or \
|
||||
dversion == 8 and macosversion >= "10.4":
|
||||
macosversion = '{}.{}'.format(reqMac.group(1), reqMac.group(2))
|
||||
if dversion == 7 and macosversion >= '10.3' or \
|
||||
dversion == 8 and macosversion >= '10.4':
|
||||
return True
|
||||
# egg isn't macOS or legacy darwin
|
||||
return False
|
||||
|
|
@ -465,7 +463,7 @@ def get_distribution(dist):
|
|||
if isinstance(dist, Requirement):
|
||||
dist = get_provider(dist)
|
||||
if not isinstance(dist, Distribution):
|
||||
raise TypeError("Expected string, Requirement, or Distribution", dist)
|
||||
raise TypeError('Expected string, Requirement, or Distribution', dist)
|
||||
return dist
|
||||
|
||||
|
||||
|
|
@ -698,8 +696,10 @@ class WorkingSet:
|
|||
self._added_new(dist)
|
||||
|
||||
# FIXME: 'WorkingSet.resolve' is too complex (11)
|
||||
def resolve(self, requirements, env=None, installer=None, # noqa: C901
|
||||
replace_conflicting=False, extras=None):
|
||||
def resolve(
|
||||
self, requirements, env=None, installer=None, # noqa: C901
|
||||
replace_conflicting=False, extras=None,
|
||||
):
|
||||
"""List all distributions needed to (recursively) meet `requirements`
|
||||
|
||||
`requirements` must be a sequence of ``Requirement`` objects. `env`,
|
||||
|
|
@ -765,7 +765,7 @@ class WorkingSet:
|
|||
ws = WorkingSet([])
|
||||
dist = best[req.key] = env.best_match(
|
||||
req, ws, installer,
|
||||
replace_conflicting=replace_conflicting
|
||||
replace_conflicting=replace_conflicting,
|
||||
)
|
||||
if dist is None:
|
||||
requirers = required_by.get(req, None)
|
||||
|
|
@ -791,7 +791,8 @@ class WorkingSet:
|
|||
return to_activate
|
||||
|
||||
def find_plugins(
|
||||
self, plugin_env, full_env=None, installer=None, fallback=True):
|
||||
self, plugin_env, full_env=None, installer=None, fallback=True,
|
||||
):
|
||||
"""Find all activatable distributions in `plugin_env`
|
||||
|
||||
Example usage::
|
||||
|
|
@ -911,7 +912,7 @@ class WorkingSet:
|
|||
def __getstate__(self):
|
||||
return (
|
||||
self.entries[:], self.entry_keys.copy(), self.by_key.copy(),
|
||||
self.callbacks[:]
|
||||
self.callbacks[:],
|
||||
)
|
||||
|
||||
def __setstate__(self, e_k_b_c):
|
||||
|
|
@ -947,7 +948,8 @@ class Environment:
|
|||
|
||||
def __init__(
|
||||
self, search_path=None, platform=get_supported_platform(),
|
||||
python=PY_MAJOR):
|
||||
python=PY_MAJOR,
|
||||
):
|
||||
"""Snapshot distributions available on a search path
|
||||
|
||||
Any distributions found on `search_path` are added to the environment.
|
||||
|
|
@ -977,9 +979,9 @@ class Environment:
|
|||
is returned.
|
||||
"""
|
||||
py_compat = (
|
||||
self.python is None
|
||||
or dist.py_version is None
|
||||
or dist.py_version == self.python
|
||||
self.python is None or
|
||||
dist.py_version is None or
|
||||
dist.py_version == self.python
|
||||
)
|
||||
return py_compat and compatible_platforms(dist.platform, self.platform)
|
||||
|
||||
|
|
@ -1023,7 +1025,8 @@ class Environment:
|
|||
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
|
||||
|
||||
def best_match(
|
||||
self, req, working_set, installer=None, replace_conflicting=False):
|
||||
self, req, working_set, installer=None, replace_conflicting=False,
|
||||
):
|
||||
"""Find distribution best matching `req` and usable on `working_set`
|
||||
|
||||
This calls the ``find(req)`` method of the `working_set` to see if a
|
||||
|
|
@ -1077,7 +1080,7 @@ class Environment:
|
|||
for dist in other[project]:
|
||||
self.add(dist)
|
||||
else:
|
||||
raise TypeError("Can't add %r to environment" % (other,))
|
||||
raise TypeError("Can't add {!r} to environment".format(other))
|
||||
return self
|
||||
|
||||
def __add__(self, other):
|
||||
|
|
@ -1122,31 +1125,31 @@ class ResourceManager:
|
|||
def resource_isdir(self, package_or_requirement, resource_name):
|
||||
"""Is the named resource an existing directory?"""
|
||||
return get_provider(package_or_requirement).resource_isdir(
|
||||
resource_name
|
||||
resource_name,
|
||||
)
|
||||
|
||||
def resource_filename(self, package_or_requirement, resource_name):
|
||||
"""Return a true filesystem path for specified resource"""
|
||||
return get_provider(package_or_requirement).get_resource_filename(
|
||||
self, resource_name
|
||||
self, resource_name,
|
||||
)
|
||||
|
||||
def resource_stream(self, package_or_requirement, resource_name):
|
||||
"""Return a readable file-like object for specified resource"""
|
||||
return get_provider(package_or_requirement).get_resource_stream(
|
||||
self, resource_name
|
||||
self, resource_name,
|
||||
)
|
||||
|
||||
def resource_string(self, package_or_requirement, resource_name):
|
||||
"""Return specified resource as a string"""
|
||||
return get_provider(package_or_requirement).get_resource_string(
|
||||
self, resource_name
|
||||
self, resource_name,
|
||||
)
|
||||
|
||||
def resource_listdir(self, package_or_requirement, resource_name):
|
||||
"""List the contents of the named resource directory"""
|
||||
return get_provider(package_or_requirement).resource_listdir(
|
||||
resource_name
|
||||
resource_name,
|
||||
)
|
||||
|
||||
def extraction_error(self):
|
||||
|
|
@ -1220,13 +1223,13 @@ class ResourceManager:
|
|||
mode = os.stat(path).st_mode
|
||||
if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
|
||||
msg = (
|
||||
"Extraction path is writable by group/others "
|
||||
"and vulnerable to attack when "
|
||||
"used with get_resource_filename ({path}). "
|
||||
"Consider a more secure "
|
||||
"location (set with .set_extraction_path or the "
|
||||
"PYTHON_EGG_CACHE environment variable)."
|
||||
).format(**locals())
|
||||
f'Extraction path is writable by group/others '
|
||||
f'and vulnerable to attack when '
|
||||
f'used with get_resource_filename ({path}). '
|
||||
f'Consider a more secure '
|
||||
f'location (set with .set_extraction_path or the '
|
||||
f'PYTHON_EGG_CACHE environment variable).'
|
||||
)
|
||||
warnings.warn(msg, UserWarning)
|
||||
|
||||
def postprocess(self, tempname, filename):
|
||||
|
|
@ -1270,7 +1273,7 @@ class ResourceManager:
|
|||
"""
|
||||
if self.cached_files:
|
||||
raise ValueError(
|
||||
"Can't change extraction path, files already extracted"
|
||||
"Can't change extraction path, files already extracted",
|
||||
)
|
||||
|
||||
self.extraction_path = path
|
||||
|
|
@ -1296,8 +1299,8 @@ def get_default_cache():
|
|||
named "Python-Eggs".
|
||||
"""
|
||||
return (
|
||||
os.environ.get('PYTHON_EGG_CACHE')
|
||||
or appdirs.user_cache_dir(appname='Python-Eggs')
|
||||
os.environ.get('PYTHON_EGG_CACHE') or
|
||||
appdirs.user_cache_dir(appname='Python-Eggs')
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -1402,7 +1405,7 @@ class NullProvider:
|
|||
|
||||
def get_metadata(self, name):
|
||||
if not self.egg_info:
|
||||
return ""
|
||||
return ''
|
||||
path = self._get_metadata_path(name)
|
||||
value = self._get(path)
|
||||
try:
|
||||
|
|
@ -1410,7 +1413,7 @@ class NullProvider:
|
|||
except UnicodeDecodeError as exc:
|
||||
# Include the path in the error message to simplify
|
||||
# troubleshooting, and without changing the exception type.
|
||||
exc.reason += ' in {} file at path: {}'.format(name, path)
|
||||
exc.reason += f' in {name} file at path: {path}'
|
||||
raise
|
||||
|
||||
def get_metadata_lines(self, name):
|
||||
|
|
@ -1434,8 +1437,7 @@ class NullProvider:
|
|||
script = 'scripts/' + script_name
|
||||
if not self.has_metadata(script):
|
||||
raise ResolutionError(
|
||||
"Script {script!r} not found in metadata at {self.egg_info!r}"
|
||||
.format(**locals()),
|
||||
f'Script {script!r} not found in metadata at {self.egg_info!r}',
|
||||
)
|
||||
script_text = self.get_metadata(script).replace('\r\n', '\n')
|
||||
script_text = script_text.replace('\r', '\n')
|
||||
|
|
@ -1449,24 +1451,24 @@ class NullProvider:
|
|||
else:
|
||||
from linecache import cache
|
||||
cache[script_filename] = (
|
||||
len(script_text), 0, script_text.split('\n'), script_filename
|
||||
len(script_text), 0, script_text.split('\n'), script_filename,
|
||||
)
|
||||
script_code = compile(script_text, script_filename, 'exec')
|
||||
exec(script_code, namespace, namespace)
|
||||
|
||||
def _has(self, path):
|
||||
raise NotImplementedError(
|
||||
"Can't perform this operation for unregistered loader type"
|
||||
"Can't perform this operation for unregistered loader type",
|
||||
)
|
||||
|
||||
def _isdir(self, path):
|
||||
raise NotImplementedError(
|
||||
"Can't perform this operation for unregistered loader type"
|
||||
"Can't perform this operation for unregistered loader type",
|
||||
)
|
||||
|
||||
def _listdir(self, path):
|
||||
raise NotImplementedError(
|
||||
"Can't perform this operation for unregistered loader type"
|
||||
"Can't perform this operation for unregistered loader type",
|
||||
)
|
||||
|
||||
def _fn(self, base, resource_name):
|
||||
|
|
@ -1536,7 +1538,7 @@ is not allowed.
|
|||
if not invalid:
|
||||
return
|
||||
|
||||
msg = "Use of .. or absolute path in a resource path is not allowed."
|
||||
msg = 'Use of .. or absolute path in a resource path is not allowed.'
|
||||
|
||||
# Aggressively disallow Windows absolute paths
|
||||
if ntpath.isabs(path) and not posixpath.isabs(path):
|
||||
|
|
@ -1545,7 +1547,7 @@ is not allowed.
|
|||
# for compatibility, warn; in future
|
||||
# raise ValueError(msg)
|
||||
warnings.warn(
|
||||
msg[:-1] + " and will raise exceptions in a future release.",
|
||||
msg[:-1] + ' and will raise exceptions in a future release.',
|
||||
DeprecationWarning,
|
||||
stacklevel=4,
|
||||
)
|
||||
|
|
@ -1554,7 +1556,7 @@ is not allowed.
|
|||
if hasattr(self.loader, 'get_data'):
|
||||
return self.loader.get_data(path)
|
||||
raise NotImplementedError(
|
||||
"Can't perform this operation for loaders without 'get_data()'"
|
||||
"Can't perform this operation for loaders without 'get_data()'",
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -1708,7 +1710,7 @@ class ZipProvider(EggProvider):
|
|||
if fspath.startswith(self.zip_pre):
|
||||
return fspath[len(self.zip_pre):]
|
||||
raise AssertionError(
|
||||
"%s is not a subpath of %s" % (fspath, self.zip_pre)
|
||||
'{} is not a subpath of {}'.format(fspath, self.zip_pre),
|
||||
)
|
||||
|
||||
def _parts(self, zip_path):
|
||||
|
|
@ -1718,7 +1720,7 @@ class ZipProvider(EggProvider):
|
|||
if fspath.startswith(self.egg_root + os.sep):
|
||||
return fspath[len(self.egg_root) + 1:].split(os.sep)
|
||||
raise AssertionError(
|
||||
"%s is not a subpath of %s" % (fspath, self.egg_root)
|
||||
'{} is not a subpath of {}'.format(fspath, self.egg_root),
|
||||
)
|
||||
|
||||
@property
|
||||
|
|
@ -1728,7 +1730,7 @@ class ZipProvider(EggProvider):
|
|||
def get_resource_filename(self, manager, resource_name):
|
||||
if not self.egg_name:
|
||||
raise NotImplementedError(
|
||||
"resource_filename() only supported for .egg, not .zip"
|
||||
'resource_filename() only supported for .egg, not .zip',
|
||||
)
|
||||
# no need to lock for extraction, since we use temp names
|
||||
zip_path = self._resource_to_zip(resource_name)
|
||||
|
|
@ -1753,7 +1755,7 @@ class ZipProvider(EggProvider):
|
|||
if zip_path in self._index():
|
||||
for name in self._index()[zip_path]:
|
||||
last = self._extract_resource(
|
||||
manager, os.path.join(zip_path, name)
|
||||
manager, os.path.join(zip_path, name),
|
||||
)
|
||||
# return the extracted directory name
|
||||
return os.path.dirname(last)
|
||||
|
|
@ -1761,19 +1763,21 @@ class ZipProvider(EggProvider):
|
|||
timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
|
||||
|
||||
if not WRITE_SUPPORT:
|
||||
raise IOError('"os.rename" and "os.unlink" are not supported '
|
||||
'on this platform')
|
||||
raise OSError(
|
||||
'"os.rename" and "os.unlink" are not supported '
|
||||
'on this platform',
|
||||
)
|
||||
try:
|
||||
|
||||
real_path = manager.get_cache_path(
|
||||
self.egg_name, self._parts(zip_path)
|
||||
self.egg_name, self._parts(zip_path),
|
||||
)
|
||||
|
||||
if self._is_current(real_path, zip_path):
|
||||
return real_path
|
||||
|
||||
outf, tmpnam = _mkstemp(
|
||||
".$extract",
|
||||
'.$extract',
|
||||
dir=os.path.dirname(real_path),
|
||||
)
|
||||
os.write(outf, self.loader.get_data(zip_path))
|
||||
|
|
@ -1784,7 +1788,7 @@ class ZipProvider(EggProvider):
|
|||
try:
|
||||
rename(tmpnam, real_path)
|
||||
|
||||
except os.error:
|
||||
except OSError:
|
||||
if os.path.isfile(real_path):
|
||||
if self._is_current(real_path, zip_path):
|
||||
# the file became current since it was checked above,
|
||||
|
|
@ -1797,7 +1801,7 @@ class ZipProvider(EggProvider):
|
|||
return real_path
|
||||
raise
|
||||
|
||||
except os.error:
|
||||
except OSError:
|
||||
# report a user-friendly error
|
||||
manager.extraction_error()
|
||||
|
||||
|
|
@ -1888,9 +1892,9 @@ class FileMetadata(EmptyProvider):
|
|||
|
||||
def get_metadata(self, name):
|
||||
if name != 'PKG-INFO':
|
||||
raise KeyError("No metadata except PKG-INFO is available")
|
||||
raise KeyError('No metadata except PKG-INFO is available')
|
||||
|
||||
with io.open(self.path, encoding='utf-8', errors="replace") as f:
|
||||
with open(self.path, encoding='utf-8', errors='replace') as f:
|
||||
metadata = f.read()
|
||||
self._warn_on_replacement(metadata)
|
||||
return metadata
|
||||
|
|
@ -1898,7 +1902,7 @@ class FileMetadata(EmptyProvider):
|
|||
def _warn_on_replacement(self, metadata):
|
||||
replacement_char = '<EFBFBD>'
|
||||
if replacement_char in metadata:
|
||||
tmpl = "{self.path} could not be properly decoded in UTF-8"
|
||||
tmpl = '{self.path} could not be properly decoded in UTF-8'
|
||||
msg = tmpl.format(**locals())
|
||||
warnings.warn(msg)
|
||||
|
||||
|
|
@ -1984,8 +1988,7 @@ def find_eggs_in_zip(importer, path_item, only=False):
|
|||
if _is_egg_path(subitem):
|
||||
subpath = os.path.join(path_item, subitem)
|
||||
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
|
||||
for dist in dists:
|
||||
yield dist
|
||||
yield from dists
|
||||
elif subitem.lower().endswith(('.dist-info', '.egg-info')):
|
||||
subpath = os.path.join(path_item, subitem)
|
||||
submeta = EggMetadata(zipimport.zipimporter(subpath))
|
||||
|
|
@ -2036,8 +2039,8 @@ def find_on_path(importer, path_item, only=False):
|
|||
if _is_unpacked_egg(path_item):
|
||||
yield Distribution.from_filename(
|
||||
path_item, metadata=PathMetadata(
|
||||
path_item, os.path.join(path_item, 'EGG-INFO')
|
||||
)
|
||||
path_item, os.path.join(path_item, 'EGG-INFO'),
|
||||
),
|
||||
)
|
||||
return
|
||||
|
||||
|
|
@ -2060,8 +2063,7 @@ def find_on_path(importer, path_item, only=False):
|
|||
for entry in path_item_entries:
|
||||
fullpath = os.path.join(path_item, entry)
|
||||
factory = dist_factory(path_item, entry, only)
|
||||
for dist in factory(fullpath):
|
||||
yield dist
|
||||
yield from factory(fullpath)
|
||||
|
||||
|
||||
def dist_factory(path_item, entry, only):
|
||||
|
|
@ -2092,6 +2094,7 @@ class NoDists:
|
|||
>>> list(NoDists()('anything'))
|
||||
[]
|
||||
"""
|
||||
|
||||
def __bool__(self):
|
||||
return False
|
||||
|
||||
|
|
@ -2195,7 +2198,7 @@ def _handle_ns(packageName, path_item):
|
|||
except AttributeError:
|
||||
# capture warnings due to #1111
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
warnings.simplefilter('ignore')
|
||||
loader = importer.find_module(packageName)
|
||||
|
||||
if loader is None:
|
||||
|
|
@ -2206,7 +2209,7 @@ def _handle_ns(packageName, path_item):
|
|||
module.__path__ = []
|
||||
_set_parent_ns(packageName)
|
||||
elif not hasattr(module, '__path__'):
|
||||
raise TypeError("Not a package:", packageName)
|
||||
raise TypeError('Not a package:', packageName)
|
||||
handler = _find_adapter(_namespace_handlers, importer)
|
||||
subpath = handler(importer, path_item, packageName, module)
|
||||
if subpath is not None:
|
||||
|
|
@ -2269,7 +2272,7 @@ def declare_namespace(packageName):
|
|||
try:
|
||||
path = sys.modules[parent].__path__
|
||||
except AttributeError as e:
|
||||
raise TypeError("Not a package:", parent) from e
|
||||
raise TypeError('Not a package:', parent) from e
|
||||
|
||||
# Track what packages are namespaces, so when new path items are added,
|
||||
# they can be updated
|
||||
|
|
@ -2326,8 +2329,13 @@ register_namespace_handler(object, null_ns_handler)
|
|||
|
||||
def normalize_path(filename):
|
||||
"""Normalize a file/dir name for comparison purposes"""
|
||||
return os.path.normcase(os.path.realpath(os.path.normpath(
|
||||
_cygwin_patch(filename))))
|
||||
return os.path.normcase(
|
||||
os.path.realpath(
|
||||
os.path.normpath(
|
||||
_cygwin_patch(filename),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _cygwin_patch(filename): # pragma: nocover
|
||||
|
|
@ -2396,7 +2404,7 @@ def yield_lines(strs):
|
|||
yield s
|
||||
|
||||
|
||||
MODULE = re.compile(r"\w+(\.\w+)*$").match
|
||||
MODULE = re.compile(r'\w+(\.\w+)*$').match
|
||||
EGG_NAME = re.compile(
|
||||
r"""
|
||||
(?P<name>[^-]+) (
|
||||
|
|
@ -2416,7 +2424,7 @@ class EntryPoint:
|
|||
|
||||
def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
|
||||
if not MODULE(module_name):
|
||||
raise ValueError("Invalid module name", module_name)
|
||||
raise ValueError('Invalid module name', module_name)
|
||||
self.name = name
|
||||
self.module_name = module_name
|
||||
self.attrs = tuple(attrs)
|
||||
|
|
@ -2424,7 +2432,7 @@ class EntryPoint:
|
|||
self.dist = dist
|
||||
|
||||
def __str__(self):
|
||||
s = "%s = %s" % (self.name, self.module_name)
|
||||
s = '{} = {}'.format(self.name, self.module_name)
|
||||
if self.attrs:
|
||||
s += ':' + '.'.join(self.attrs)
|
||||
if self.extras:
|
||||
|
|
@ -2432,7 +2440,7 @@ class EntryPoint:
|
|||
return s
|
||||
|
||||
def __repr__(self):
|
||||
return "EntryPoint.parse(%r)" % str(self)
|
||||
return 'EntryPoint.parse(%r)' % str(self)
|
||||
|
||||
def load(self, require=True, *args, **kwargs):
|
||||
"""
|
||||
|
|
@ -2440,8 +2448,8 @@ class EntryPoint:
|
|||
"""
|
||||
if not require or args or kwargs:
|
||||
warnings.warn(
|
||||
"Parameters to load are deprecated. Call .resolve and "
|
||||
".require separately.",
|
||||
'Parameters to load are deprecated. Call .resolve and '
|
||||
'.require separately.',
|
||||
PkgResourcesDeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
|
@ -2478,7 +2486,7 @@ class EntryPoint:
|
|||
r'=\s*'
|
||||
r'(?P<module>[\w.]+)\s*'
|
||||
r'(:\s*(?P<attr>[\w.]+))?\s*'
|
||||
r'(?P<extras>\[.*\])?\s*$'
|
||||
r'(?P<extras>\[.*\])?\s*$',
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
|
@ -2514,12 +2522,12 @@ class EntryPoint:
|
|||
def parse_group(cls, group, lines, dist=None):
|
||||
"""Parse an entry point group"""
|
||||
if not MODULE(group):
|
||||
raise ValueError("Invalid group name", group)
|
||||
raise ValueError('Invalid group name', group)
|
||||
this = {}
|
||||
for line in yield_lines(lines):
|
||||
ep = cls.parse(line, dist)
|
||||
if ep.name in this:
|
||||
raise ValueError("Duplicate entry point", group, ep.name)
|
||||
raise ValueError('Duplicate entry point', group, ep.name)
|
||||
this[ep.name] = ep
|
||||
return this
|
||||
|
||||
|
|
@ -2535,10 +2543,10 @@ class EntryPoint:
|
|||
if group is None:
|
||||
if not lines:
|
||||
continue
|
||||
raise ValueError("Entry points must be listed in groups")
|
||||
raise ValueError('Entry points must be listed in groups')
|
||||
group = group.strip()
|
||||
if group in maps:
|
||||
raise ValueError("Duplicate group name", group)
|
||||
raise ValueError('Duplicate group name', group)
|
||||
maps[group] = cls.parse_group(group, lines, dist)
|
||||
return maps
|
||||
|
||||
|
|
@ -2563,7 +2571,8 @@ class Distribution:
|
|||
def __init__(
|
||||
self, location=None, metadata=None, project_name=None,
|
||||
version=None, py_version=PY_MAJOR, platform=None,
|
||||
precedence=EGG_DIST):
|
||||
precedence=EGG_DIST,
|
||||
):
|
||||
self.project_name = safe_name(project_name or 'Unknown')
|
||||
if version is not None:
|
||||
self._version = safe_version(version)
|
||||
|
|
@ -2583,11 +2592,11 @@ class Distribution:
|
|||
match = EGG_NAME(basename)
|
||||
if match:
|
||||
project_name, version, py_version, platform = match.group(
|
||||
'name', 'ver', 'pyver', 'plat'
|
||||
'name', 'ver', 'pyver', 'plat',
|
||||
)
|
||||
return cls(
|
||||
location, metadata, project_name=project_name, version=version,
|
||||
py_version=py_version, platform=platform, **kw
|
||||
py_version=py_version, platform=platform, **kw,
|
||||
)._reload_version()
|
||||
|
||||
def _reload_version(self):
|
||||
|
|
@ -2642,7 +2651,7 @@ class Distribution:
|
|||
|
||||
@property
|
||||
def parsed_version(self):
|
||||
if not hasattr(self, "_parsed_version"):
|
||||
if not hasattr(self, '_parsed_version'):
|
||||
self._parsed_version = parse_version(self.version)
|
||||
|
||||
return self._parsed_version
|
||||
|
|
@ -2712,8 +2721,8 @@ class Distribution:
|
|||
reqs = dm.pop(extra)
|
||||
new_extra, _, marker = extra.partition(':')
|
||||
fails_marker = marker and (
|
||||
invalid_marker(marker)
|
||||
or not evaluate_marker(marker)
|
||||
invalid_marker(marker) or
|
||||
not evaluate_marker(marker)
|
||||
)
|
||||
if fails_marker:
|
||||
reqs = []
|
||||
|
|
@ -2739,7 +2748,7 @@ class Distribution:
|
|||
deps.extend(dm[safe_extra(ext)])
|
||||
except KeyError as e:
|
||||
raise UnknownExtra(
|
||||
"%s has no such extra feature %r" % (self, ext)
|
||||
'{} has no such extra feature {!r}'.format(self, ext),
|
||||
) from e
|
||||
return deps
|
||||
|
||||
|
|
@ -2762,8 +2771,7 @@ class Distribution:
|
|||
|
||||
def _get_metadata(self, name):
|
||||
if self.has_metadata(name):
|
||||
for line in self.get_metadata_lines(name):
|
||||
yield line
|
||||
yield from self.get_metadata_lines(name)
|
||||
|
||||
def _get_version(self):
|
||||
lines = self._get_metadata(self.PKG_INFO)
|
||||
|
|
@ -2784,9 +2792,9 @@ class Distribution:
|
|||
|
||||
def egg_name(self):
|
||||
"""Return what this distribution's standard .egg filename should be"""
|
||||
filename = "%s-%s-py%s" % (
|
||||
filename = '{}-{}-py{}'.format(
|
||||
to_filename(self.project_name), to_filename(self.version),
|
||||
self.py_version or PY_MAJOR
|
||||
self.py_version or PY_MAJOR,
|
||||
)
|
||||
|
||||
if self.platform:
|
||||
|
|
@ -2795,7 +2803,7 @@ class Distribution:
|
|||
|
||||
def __repr__(self):
|
||||
if self.location:
|
||||
return "%s (%s)" % (self, self.location)
|
||||
return '{} ({})'.format(self, self.location)
|
||||
else:
|
||||
return str(self)
|
||||
|
||||
|
|
@ -2804,8 +2812,8 @@ class Distribution:
|
|||
version = getattr(self, 'version', None)
|
||||
except ValueError:
|
||||
version = None
|
||||
version = version or "[unknown version]"
|
||||
return "%s %s" % (self.project_name, version)
|
||||
version = version or '[unknown version]'
|
||||
return '{} {}'.format(self.project_name, version)
|
||||
|
||||
def __getattr__(self, attr):
|
||||
"""Delegate all unrecognized public attributes to .metadata provider"""
|
||||
|
|
@ -2815,26 +2823,26 @@ class Distribution:
|
|||
|
||||
def __dir__(self):
|
||||
return list(
|
||||
set(super(Distribution, self).__dir__())
|
||||
| set(
|
||||
set(super().__dir__()) |
|
||||
{
|
||||
attr for attr in self._provider.__dir__()
|
||||
if not attr.startswith('_')
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_filename(cls, filename, metadata=None, **kw):
|
||||
return cls.from_location(
|
||||
_normalize_cached(filename), os.path.basename(filename), metadata,
|
||||
**kw
|
||||
**kw,
|
||||
)
|
||||
|
||||
def as_requirement(self):
|
||||
"""Return a ``Requirement`` that matches this distribution exactly"""
|
||||
if isinstance(self.parsed_version, packaging.version.Version):
|
||||
spec = "%s==%s" % (self.project_name, self.parsed_version)
|
||||
spec = '{}=={}'.format(self.project_name, self.parsed_version)
|
||||
else:
|
||||
spec = "%s===%s" % (self.project_name, self.parsed_version)
|
||||
spec = '{}==={}'.format(self.project_name, self.parsed_version)
|
||||
|
||||
return Requirement.parse(spec)
|
||||
|
||||
|
|
@ -2842,7 +2850,7 @@ class Distribution:
|
|||
"""Return the `name` entry point of `group` or raise ImportError"""
|
||||
ep = self.get_entry_info(group, name)
|
||||
if ep is None:
|
||||
raise ImportError("Entry point %r not found" % ((group, name),))
|
||||
raise ImportError('Entry point {!r} not found'.format((group, name)))
|
||||
return ep.load()
|
||||
|
||||
def get_entry_map(self, group=None):
|
||||
|
|
@ -2851,7 +2859,7 @@ class Distribution:
|
|||
ep_map = self._ep_map
|
||||
except AttributeError:
|
||||
ep_map = self._ep_map = EntryPoint.parse_map(
|
||||
self._get_metadata('entry_points.txt'), self
|
||||
self._get_metadata('entry_points.txt'), self,
|
||||
)
|
||||
if group is not None:
|
||||
return ep_map.get(group, {})
|
||||
|
|
@ -2938,25 +2946,29 @@ class Distribution:
|
|||
nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
|
||||
loc = normalize_path(self.location)
|
||||
for modname in self._get_metadata('top_level.txt'):
|
||||
if (modname not in sys.modules or modname in nsp
|
||||
or modname in _namespace_packages):
|
||||
if (
|
||||
modname not in sys.modules or modname in nsp or
|
||||
modname in _namespace_packages
|
||||
):
|
||||
continue
|
||||
if modname in ('pkg_resources', 'setuptools', 'site'):
|
||||
continue
|
||||
fn = getattr(sys.modules[modname], '__file__', None)
|
||||
if fn and (normalize_path(fn).startswith(loc) or
|
||||
fn.startswith(self.location)):
|
||||
if fn and (
|
||||
normalize_path(fn).startswith(loc) or
|
||||
fn.startswith(self.location)
|
||||
):
|
||||
continue
|
||||
issue_warning(
|
||||
"Module %s was already imported from %s, but %s is being added"
|
||||
" to sys.path" % (modname, fn, self.location),
|
||||
'Module %s was already imported from %s, but %s is being added'
|
||||
' to sys.path' % (modname, fn, self.location),
|
||||
)
|
||||
|
||||
def has_version(self):
|
||||
try:
|
||||
self.version
|
||||
except ValueError:
|
||||
issue_warning("Unbuilt egg for " + repr(self))
|
||||
issue_warning('Unbuilt egg for ' + repr(self))
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
@ -2998,7 +3010,7 @@ class DistInfoDistribution(Distribution):
|
|||
w/metadata, .dist-info style.
|
||||
"""
|
||||
PKG_INFO = 'METADATA'
|
||||
EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
|
||||
EQEQ = re.compile(r'([\(,])\s*(\d.*?)\s*([,\)])')
|
||||
|
||||
@property
|
||||
def _parsed_pkg_info(self):
|
||||
|
|
@ -3085,18 +3097,19 @@ def parse_requirements(strs):
|
|||
|
||||
|
||||
class RequirementParseError(packaging.requirements.InvalidRequirement):
|
||||
"Compatibility wrapper for InvalidRequirement"
|
||||
'Compatibility wrapper for InvalidRequirement'
|
||||
|
||||
|
||||
class Requirement(packaging.requirements.Requirement):
|
||||
def __init__(self, requirement_string):
|
||||
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
|
||||
super(Requirement, self).__init__(requirement_string)
|
||||
super().__init__(requirement_string)
|
||||
self.unsafe_name = self.name
|
||||
project_name = safe_name(self.name)
|
||||
self.project_name, self.key = project_name, project_name.lower()
|
||||
self.specs = [
|
||||
(spec.operator, spec.version) for spec in self.specifier]
|
||||
(spec.operator, spec.version) for spec in self.specifier
|
||||
]
|
||||
self.extras = tuple(map(safe_extra, self.extras))
|
||||
self.hashCmp = (
|
||||
self.key,
|
||||
|
|
@ -3132,7 +3145,7 @@ class Requirement(packaging.requirements.Requirement):
|
|||
return self.__hash
|
||||
|
||||
def __repr__(self):
|
||||
return "Requirement.parse(%r)" % str(self)
|
||||
return 'Requirement.parse(%r)' % str(self)
|
||||
|
||||
@staticmethod
|
||||
def parse(s):
|
||||
|
|
@ -3167,7 +3180,7 @@ def ensure_directory(path):
|
|||
def _bypass_ensure_directory(path):
|
||||
"""Sandbox-bypassing version of ensure_directory()"""
|
||||
if not WRITE_SUPPORT:
|
||||
raise IOError('"os.mkdir" not supported on this platform.')
|
||||
raise OSError('"os.mkdir" not supported on this platform.')
|
||||
dirname, filename = split(path)
|
||||
if dirname and filename and not isdir(dirname):
|
||||
_bypass_ensure_directory(dirname)
|
||||
|
|
@ -3188,14 +3201,14 @@ def split_sections(s):
|
|||
section = None
|
||||
content = []
|
||||
for line in yield_lines(s):
|
||||
if line.startswith("["):
|
||||
if line.endswith("]"):
|
||||
if line.startswith('['):
|
||||
if line.endswith(']'):
|
||||
if section or content:
|
||||
yield section, content
|
||||
section = line[1:-1].strip()
|
||||
content = []
|
||||
else:
|
||||
raise ValueError("Invalid section heading", line)
|
||||
raise ValueError('Invalid section heading', line)
|
||||
else:
|
||||
content.append(line)
|
||||
|
||||
|
|
@ -3218,7 +3231,7 @@ def _mkstemp(*args, **kw):
|
|||
# randomly just because they use pkg_resources. We want to append the rule
|
||||
# because we want earlier uses of filterwarnings to take precedence over this
|
||||
# one.
|
||||
warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
|
||||
warnings.filterwarnings('ignore', category=PEP440Warning, append=True)
|
||||
|
||||
|
||||
# from jaraco.functools 1.3
|
||||
|
|
@ -3229,7 +3242,7 @@ def _call_aside(f, *args, **kwargs):
|
|||
|
||||
@_call_aside
|
||||
def _initialize(g=globals()):
|
||||
"Set up global resource manager (deliberately not state-saved)"
|
||||
'Set up global resource manager (deliberately not state-saved)'
|
||||
manager = ResourceManager()
|
||||
g['_manager'] = manager
|
||||
g.update(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue