aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/setuptools/py3
diff options
context:
space:
mode:
authororivej <orivej@yandex-team.ru>2022-02-10 16:44:49 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:44:49 +0300
commit718c552901d703c502ccbefdfc3c9028d608b947 (patch)
tree46534a98bbefcd7b1f3faa5b52c138ab27db75b7 /contrib/python/setuptools/py3
parente9656aae26e0358d5378e5b63dcac5c8dbe0e4d0 (diff)
downloadydb-718c552901d703c502ccbefdfc3c9028d608b947.tar.gz
Restoring authorship annotation for <orivej@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/setuptools/py3')
-rw-r--r--contrib/python/setuptools/py3/pkg_resources/__init__.py680
-rw-r--r--contrib/python/setuptools/py3/setuptools/__init__.py78
-rw-r--r--contrib/python/setuptools/py3/setuptools/archive_util.py20
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/bdist_egg.py18
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/build_clib.py138
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/build_ext.py76
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/build_py.py84
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/develop.py46
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/easy_install.py244
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/egg_info.py424
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install.py2
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_egg_info.py6
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_lib.py2
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/install_scripts.py10
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/py36compat.py266
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/rotate.py10
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/sdist.py106
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/test.py132
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/upload.py10
-rw-r--r--contrib/python/setuptools/py3/setuptools/command/upload_docs.py118
-rw-r--r--contrib/python/setuptools/py3/setuptools/config.py936
-rw-r--r--contrib/python/setuptools/py3/setuptools/dep_util.py44
-rw-r--r--contrib/python/setuptools/py3/setuptools/depends.py32
-rw-r--r--contrib/python/setuptools/py3/setuptools/dist.py212
-rw-r--r--contrib/python/setuptools/py3/setuptools/extension.py24
-rw-r--r--contrib/python/setuptools/py3/setuptools/glob.py314
-rw-r--r--contrib/python/setuptools/py3/setuptools/launch.py34
-rw-r--r--contrib/python/setuptools/py3/setuptools/monkey.py306
-rw-r--r--contrib/python/setuptools/py3/setuptools/msvc.py1642
-rw-r--r--contrib/python/setuptools/py3/setuptools/namespaces.py194
-rw-r--r--contrib/python/setuptools/py3/setuptools/package_index.py250
-rw-r--r--contrib/python/setuptools/py3/setuptools/sandbox.py106
-rw-r--r--contrib/python/setuptools/py3/setuptools/version.py12
-rw-r--r--contrib/python/setuptools/py3/ya.make36
34 files changed, 3306 insertions, 3306 deletions
diff --git a/contrib/python/setuptools/py3/pkg_resources/__init__.py b/contrib/python/setuptools/py3/pkg_resources/__init__.py
index 6b947a49a7..472ee767dd 100644
--- a/contrib/python/setuptools/py3/pkg_resources/__init__.py
+++ b/contrib/python/setuptools/py3/pkg_resources/__init__.py
@@ -34,7 +34,7 @@ import email.parser
import errno
import tempfile
import textwrap
-import itertools
+import itertools
import inspect
import ntpath
import posixpath
@@ -123,44 +123,44 @@ def parse_version(v):
_state_vars = {}
-
+
def _declare_state(vartype, **kw):
globals().update(kw)
_state_vars.update(dict.fromkeys(kw, vartype))
-
+
def __getstate__():
state = {}
g = globals()
for k, v in _state_vars.items():
- state[k] = g['_sget_' + v](g[k])
+ state[k] = g['_sget_' + v](g[k])
return state
-
+
def __setstate__(state):
g = globals()
for k, v in state.items():
- g['_sset_' + _state_vars[k]](k, g[k], v)
+ g['_sset_' + _state_vars[k]](k, g[k], v)
return state
-
+
def _sget_dict(val):
return val.copy()
-
+
def _sset_dict(key, ob, state):
ob.clear()
ob.update(state)
-
+
def _sget_object(val):
return val.__getstate__()
-
+
def _sset_object(key, ob, state):
ob.__setstate__(state)
-
+
_sget_none = _sset_none = lambda *args: None
@@ -187,10 +187,10 @@ def get_supported_platform():
pass
return plat
-
+
__all__ = [
# Basic resource access and distribution/entry point discovery
- 'require', 'run_script', 'get_provider', 'get_distribution',
+ 'require', 'run_script', 'get_provider', 'get_distribution',
'load_entry_point', 'get_entry_map', 'get_entry_info',
'iter_entry_points',
'resource_string', 'resource_stream', 'resource_filename',
@@ -237,12 +237,12 @@ __all__ = [
'run_main', 'AvailableDistributions',
]
-
+
class ResolutionError(Exception):
"""Abstract base for dependency resolution errors"""
-
+
def __repr__(self):
- return self.__class__.__name__ + repr(self.args)
+ return self.__class__.__name__ + repr(self.args)
class VersionConflict(ResolutionError):
@@ -319,8 +319,8 @@ class DistributionNotFound(ResolutionError):
class UnknownExtra(ResolutionError):
"""Distribution doesn't have an "extra feature" of the given name"""
-
-
+
+
_provider_factories = {}
PY_MAJOR = '{}.{}'.format(*sys.version_info)
@@ -330,7 +330,7 @@ SOURCE_DIST = 1
CHECKOUT_DIST = 0
DEVELOP_DIST = -1
-
+
def register_loader_type(loader_type, provider_factory):
"""Register `provider_factory` to make providers for `loader_type`
@@ -340,7 +340,7 @@ def register_loader_type(loader_type, provider_factory):
"""
_provider_factories[loader_type] = provider_factory
-
+
def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq, Requirement):
@@ -353,7 +353,7 @@ def get_provider(moduleOrReq):
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module)
-
+
def _macos_vers(_cache=[]):
if not _cache:
version = platform.mac_ver()[0]
@@ -369,11 +369,11 @@ def _macos_vers(_cache=[]):
_cache.append(version.split('.'))
return _cache[0]
-
+
def _macos_arch(machine):
return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
-
+
def get_build_platform():
"""Return this platform's string for platform-specific distributions
@@ -397,7 +397,7 @@ def get_build_platform():
pass
return plat
-
+
macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
# XXX backward compat
@@ -411,7 +411,7 @@ def compatible_platforms(provided, required):
XXX Needs compatibility checks for Linux and other unixy OSes.
"""
- if provided is None or required is None or provided == required:
+ if provided is None or required is None or provided == required:
# easy case
return True
@@ -458,11 +458,11 @@ def run_script(dist_spec, script_name):
ns['__name__'] = name
require(dist_spec)[0].run_script(script_name, ns)
-
+
# backward compatibility
run_main = run_script
-
+
def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist, str):
@@ -473,17 +473,17 @@ def get_distribution(dist):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist
-
+
def load_entry_point(dist, group, name):
"""Return `name` entry point of `group` for `dist` or raise ImportError"""
return get_distribution(dist).load_entry_point(group, name)
-
+
def get_entry_map(dist, group=None):
"""Return the entry point map for `group`, or the full entry map"""
return get_distribution(dist).get_entry_map(group)
-
+
def get_entry_info(dist, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return get_distribution(dist).get_entry_info(group, name)
@@ -669,7 +669,7 @@ class WorkingSet:
for key in self.entry_keys[item]:
if key not in seen:
- seen[key] = 1
+ seen[key] = 1
yield self.by_key[key]
def add(self, dist, entry=None, insert=True, replace=False):
@@ -689,8 +689,8 @@ class WorkingSet:
if entry is None:
entry = dist.location
- keys = self.entry_keys.setdefault(entry, [])
- keys2 = self.entry_keys.setdefault(dist.location, [])
+ keys = self.entry_keys.setdefault(entry, [])
+ keys2 = self.entry_keys.setdefault(dist.location, [])
if not replace and dist.key in self.by_key:
# ignore hidden distros
return
@@ -704,7 +704,7 @@ class WorkingSet:
# FIXME: 'WorkingSet.resolve' is too complex (11)
def resolve(self, requirements, env=None, installer=None, # noqa: C901
- replace_conflicting=False, extras=None):
+ replace_conflicting=False, extras=None):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
@@ -721,12 +721,12 @@ class WorkingSet:
the wrong version. Otherwise, if an `installer` is supplied it will be
invoked to obtain the correct version of the requirement and activate
it.
-
- `extras` is a list of the extras to be used with these requirements.
- This is important because extra requirements may look like `my_req;
- extra = "my_extra"`, which would otherwise be interpreted as a purely
- optional requirement. Instead, we want to be able to assert that these
- requirements are truly required.
+
+ `extras` is a list of the extras to be used with these requirements.
+ This is important because extra requirements may look like `my_req;
+ extra = "my_extra"`, which would otherwise be interpreted as a purely
+ optional requirement. Instead, we want to be able to assert that these
+ requirements are truly required.
"""
# set up the stack
@@ -737,8 +737,8 @@ class WorkingSet:
best = {}
to_activate = []
- req_extras = _ReqExtras()
-
+ req_extras = _ReqExtras()
+
# Mapping of requirement to set of distributions that required it;
# useful for reporting info about conflicts.
required_by = collections.defaultdict(set)
@@ -749,10 +749,10 @@ class WorkingSet:
if req in processed:
# Ignore cyclic or redundant dependencies
continue
-
- if not req_extras.markers_pass(req, extras):
- continue
-
+
+ if not req_extras.markers_pass(req, extras):
+ continue
+
dist = best.get(req.key)
if dist is None:
# Find the best distribution and add it to the map
@@ -788,7 +788,7 @@ class WorkingSet:
# Register the new requirements needed by req
for new_requirement in new_requirements:
required_by[new_requirement].add(req.project_name)
- req_extras[new_requirement] = req.extras
+ req_extras[new_requirement] = req.extras
processed[req] = True
@@ -895,17 +895,17 @@ class WorkingSet:
return needed
- def subscribe(self, callback, existing=True):
- """Invoke `callback` for all distributions
-
- If `existing=True` (default),
- call on all existing ones, as well.
- """
+ def subscribe(self, callback, existing=True):
+ """Invoke `callback` for all distributions
+
+ If `existing=True` (default),
+ call on all existing ones, as well.
+ """
if callback in self.callbacks:
return
self.callbacks.append(callback)
- if not existing:
- return
+ if not existing:
+ return
for dist in self:
callback(dist)
@@ -927,26 +927,26 @@ class WorkingSet:
self.callbacks = callbacks[:]
-class _ReqExtras(dict):
- """
- Map each requirement to the extras that demanded it.
- """
-
- def markers_pass(self, req, extras=None):
- """
- Evaluate markers for req against each extra that
- demanded it.
-
- Return False if the req has a marker and fails
- evaluation. Otherwise, return True.
- """
- extra_evals = (
- req.marker.evaluate({'extra': extra})
- for extra in self.get(req, ()) + (extras or (None,))
- )
- return not req.marker or any(extra_evals)
-
-
+class _ReqExtras(dict):
+ """
+ Map each requirement to the extras that demanded it.
+ """
+
+ def markers_pass(self, req, extras=None):
+ """
+ Evaluate markers for req against each extra that
+ demanded it.
+
+ Return False if the req has a marker and fails
+ evaluation. Otherwise, return True.
+ """
+ extra_evals = (
+ req.marker.evaluate({'extra': extra})
+ for extra in self.get(req, ()) + (extras or (None,))
+ )
+ return not req.marker or any(extra_evals)
+
+
class Environment:
"""Searchable snapshot of distributions on a search path"""
@@ -1196,7 +1196,7 @@ class ResourceManager:
extract, as it tracks the generated names for possible cleanup later.
"""
extract_path = self.extraction_path or get_default_cache()
- target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
+ target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
try:
_bypass_ensure_directory(target_path)
except Exception:
@@ -1293,17 +1293,17 @@ class ResourceManager:
"""
# XXX
-
+
def get_default_cache():
"""
- Return the ``PYTHON_EGG_CACHE`` environment variable
- or a platform-relevant user cache dir for an app
- named "Python-Eggs".
- """
- return (
- os.environ.get('PYTHON_EGG_CACHE')
- or appdirs.user_cache_dir(appname='Python-Eggs')
- )
+ Return the ``PYTHON_EGG_CACHE`` environment variable
+ or a platform-relevant user cache dir for an app
+ named "Python-Eggs".
+ """
+ return (
+ os.environ.get('PYTHON_EGG_CACHE')
+ or appdirs.user_cache_dir(appname='Python-Eggs')
+ )
def safe_name(name):
@@ -1322,7 +1322,7 @@ def safe_version(version):
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
- version = version.replace(' ', '.')
+ version = version.replace(' ', '.')
return re.sub('[^A-Za-z0-9.]+', '-', version)
@@ -1332,7 +1332,7 @@ def safe_extra(extra):
Any runs of non-alphanumeric characters are replaced with a single '_',
and the result is always lowercased.
"""
- return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
+ return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
def to_filename(name):
@@ -1340,35 +1340,35 @@ def to_filename(name):
Any '-' characters are currently replaced with '_'.
"""
- return name.replace('-', '_')
-
-
-def invalid_marker(text):
- """
- Validate text as a PEP 508 environment marker; return an exception
- if invalid or False otherwise.
- """
- try:
- evaluate_marker(text)
- except SyntaxError as e:
- e.filename = None
- e.lineno = None
- return e
- return False
-
-
-def evaluate_marker(text, extra=None):
- """
- Evaluate a PEP 508 environment marker.
- Return a boolean indicating the marker result in this environment.
- Raise SyntaxError if marker is invalid.
-
- This implementation uses the 'pyparsing' module.
- """
- try:
- marker = packaging.markers.Marker(text)
- return marker.evaluate()
- except packaging.markers.InvalidMarker as e:
+ return name.replace('-', '_')
+
+
+def invalid_marker(text):
+ """
+ Validate text as a PEP 508 environment marker; return an exception
+ if invalid or False otherwise.
+ """
+ try:
+ evaluate_marker(text)
+ except SyntaxError as e:
+ e.filename = None
+ e.lineno = None
+ return e
+ return False
+
+
+def evaluate_marker(text, extra=None):
+ """
+ Evaluate a PEP 508 environment marker.
+ Return a boolean indicating the marker result in this environment.
+ Raise SyntaxError if marker is invalid.
+
+ This implementation uses the 'pyparsing' module.
+ """
+ try:
+ marker = packaging.markers.Marker(text)
+ return marker.evaluate()
+ except packaging.markers.InvalidMarker as e:
raise SyntaxError(e) from e
@@ -1405,9 +1405,9 @@ class NullProvider:
path = self._get_metadata_path(name)
return self._has(path)
- def get_metadata(self, name):
- if not self.egg_info:
- return ""
+ def get_metadata(self, name):
+ if not self.egg_info:
+ return ""
path = self._get_metadata_path(name)
value = self._get(path)
try:
@@ -1436,7 +1436,7 @@ class NullProvider:
return []
def run_script(self, script_name, namespace):
- script = 'scripts/' + script_name
+ script = 'scripts/' + script_name
if not self.has_metadata(script):
raise ResolutionError(
"Script {script!r} not found in metadata at {self.egg_info!r}"
@@ -1456,7 +1456,7 @@ class NullProvider:
cache[script_filename] = (
len(script_text), 0, script_text.split('\n'), script_filename
)
- script_code = compile(script_text, script_filename, 'exec')
+ script_code = compile(script_text, script_filename, 'exec')
exec(script_code, namespace, namespace)
def _has(self, path):
@@ -1562,7 +1562,7 @@ is not allowed.
"Can't perform this operation for loaders without 'get_data()'"
)
-
+
register_loader_type(object, NullProvider)
@@ -1595,7 +1595,7 @@ class EggProvider(NullProvider):
self.egg_name = os.path.basename(path)
self.egg_info = os.path.join(path, 'EGG-INFO')
self.egg_root = path
-
+
class DefaultProvider(EggProvider):
"""Provides access to package resources in the filesystem"""
@@ -1623,7 +1623,7 @@ class DefaultProvider(EggProvider):
loader_cls = getattr(importlib_machinery, name, type(None))
register_loader_type(loader_cls, cls)
-
+
DefaultProvider._register()
@@ -1643,7 +1643,7 @@ class EmptyProvider(NullProvider):
def __init__(self):
pass
-
+
empty_provider = EmptyProvider()
@@ -1702,7 +1702,7 @@ class ZipProvider(EggProvider):
def __init__(self, module):
EggProvider.__init__(self, module)
- self.zip_pre = self.loader.archive + os.sep
+ self.zip_pre = self.loader.archive + os.sep
def _zipinfo_name(self, fspath):
# Convert a virtual filename (full path to file) into a zipfile subpath
@@ -1719,9 +1719,9 @@ class ZipProvider(EggProvider):
def _parts(self, zip_path):
# Convert a zipfile subpath into an egg-relative path part list.
# pseudo-fs path
- fspath = self.zip_pre + zip_path
- if fspath.startswith(self.egg_root + os.sep):
- return fspath[len(self.egg_root) + 1:].split(os.sep)
+ fspath = self.zip_pre + zip_path
+ 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)
)
@@ -1796,7 +1796,7 @@ class ZipProvider(EggProvider):
# so proceed.
return real_path
# Windows, del old file and retry
- elif os.name == 'nt':
+ elif os.name == 'nt':
unlink(real_path)
rename(tmpnam, real_path)
return real_path
@@ -1816,7 +1816,7 @@ class ZipProvider(EggProvider):
if not os.path.isfile(file_path):
return False
stat = os.stat(file_path)
- if stat.st_size != size or stat.st_mtime != timestamp:
+ if stat.st_size != size or stat.st_mtime != timestamp:
return False
# check that the contents match
zip_contents = self.loader.get_data(zip_path)
@@ -1866,7 +1866,7 @@ class ZipProvider(EggProvider):
def _resource_to_zip(self, resource_name):
return self._zipinfo_name(self._fn(self.module_path, resource_name))
-
+
register_loader_type(zipimport.zipimporter, ZipProvider)
@@ -1889,24 +1889,24 @@ class FileMetadata(EmptyProvider):
return self.path
def has_metadata(self, name):
- return name == 'PKG-INFO' and os.path.isfile(self.path)
+ return name == 'PKG-INFO' and os.path.isfile(self.path)
def get_metadata(self, name):
- if name != 'PKG-INFO':
- raise KeyError("No metadata except PKG-INFO is available")
-
- with io.open(self.path, encoding='utf-8', errors="replace") as f:
- metadata = f.read()
- self._warn_on_replacement(metadata)
- return metadata
-
- def _warn_on_replacement(self, metadata):
+ if name != 'PKG-INFO':
+ raise KeyError("No metadata except PKG-INFO is available")
+
+ with io.open(self.path, encoding='utf-8', errors="replace") as f:
+ metadata = f.read()
+ self._warn_on_replacement(metadata)
+ return metadata
+
+ def _warn_on_replacement(self, metadata):
replacement_char = '�'
- if replacement_char in metadata:
- tmpl = "{self.path} could not be properly decoded in UTF-8"
- msg = tmpl.format(**locals())
- warnings.warn(msg)
-
+ if replacement_char in metadata:
+ tmpl = "{self.path} could not be properly decoded in UTF-8"
+ msg = tmpl.format(**locals())
+ warnings.warn(msg)
+
def get_metadata_lines(self, name):
return yield_lines(self.get_metadata(name))
@@ -1942,7 +1942,7 @@ class EggMetadata(ZipProvider):
def __init__(self, importer):
"""Create a metadata provider from a zipimporter"""
- self.zip_pre = importer.archive + os.sep
+ self.zip_pre = importer.archive + os.sep
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
@@ -1951,9 +1951,9 @@ class EggMetadata(ZipProvider):
self._setup_prefix()
-_declare_state('dict', _distribution_finders={})
-
-
+_declare_state('dict', _distribution_finders={})
+
+
def register_finder(importer_type, distribution_finder):
"""Register `distribution_finder` to find distributions in sys.path items
@@ -1970,7 +1970,7 @@ def find_distributions(path_item, only=False):
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
-
+
def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
@@ -1992,37 +1992,37 @@ def find_eggs_in_zip(importer, path_item, only=False):
for dist in dists:
yield dist
elif subitem.lower().endswith(('.dist-info', '.egg-info')):
- subpath = os.path.join(path_item, subitem)
- submeta = EggMetadata(zipimport.zipimporter(subpath))
- submeta.egg_info = subpath
- yield Distribution.from_location(path_item, subitem, submeta)
-
+ subpath = os.path.join(path_item, subitem)
+ submeta = EggMetadata(zipimport.zipimporter(subpath))
+ submeta.egg_info = subpath
+ yield Distribution.from_location(path_item, subitem, submeta)
+
register_finder(zipimport.zipimporter, find_eggs_in_zip)
-
+
def find_nothing(importer, path_item, only=False):
return ()
-
-
+
+
register_finder(object, find_nothing)
-
-def _by_version_descending(names):
- """
- Given a list of filenames, return them in descending order
- by version number.
-
- >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
- >>> _by_version_descending(names)
+
+def _by_version_descending(names):
+ """
+ Given a list of filenames, return them in descending order
+ by version number.
+
+ >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
+ >>> _by_version_descending(names)
['Python-2.7.10.egg', 'Python-2.7.2.egg', 'bar', 'foo']
- >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
- >>> _by_version_descending(names)
- ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
- >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
- >>> _by_version_descending(names)
- ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
- """
+ >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
+ >>> _by_version_descending(names)
+ ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
+ >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
+ >>> _by_version_descending(names)
+ ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
+ """
def try_parse(name):
"""
Attempt to parse as a version or return a null version.
@@ -2032,17 +2032,17 @@ def _by_version_descending(names):
except Exception:
return packaging.version.Version('0')
- def _by_version(name):
- """
- Parse each component of the filename
- """
- name, ext = os.path.splitext(name)
- parts = itertools.chain(name.split('-'), [ext])
+ def _by_version(name):
+ """
+ Parse each component of the filename
+ """
+ name, ext = os.path.splitext(name)
+ parts = itertools.chain(name.split('-'), [ext])
return [try_parse(part) for part in parts]
-
- return sorted(names, key=_by_version, reverse=True)
-
-
+
+ return sorted(names, key=_by_version, reverse=True)
+
+
def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
@@ -2054,12 +2054,12 @@ def find_on_path(importer, path_item, only=False):
)
)
return
-
+
entries = (
os.path.join(path_item, child)
for child in safe_listdir(path_item)
)
-
+
# for performance, before sorting by version,
# screen entries for only those that will yield
# distributions
@@ -2195,7 +2195,7 @@ def register_namespace_handler(importer_type, namespace_handler):
"""
_namespace_handlers[importer_type] = namespace_handler
-
+
def _handle_ns(packageName, path_item):
"""Ensure that named package includes a subpath of path_item (if needed)"""
@@ -2219,7 +2219,7 @@ def _handle_ns(packageName, path_item):
module = sys.modules[packageName] = types.ModuleType(packageName)
module.__path__ = []
_set_parent_ns(packageName)
- elif not hasattr(module, '__path__'):
+ elif not hasattr(module, '__path__'):
raise TypeError("Not a package:", packageName)
handler = _find_adapter(_namespace_handlers, importer)
subpath = handler(importer, path_item, packageName, module)
@@ -2237,28 +2237,28 @@ def _rebuild_mod_path(orig_path, package_name, module):
corresponding to their sys.path order
"""
sys_path = [_normalize_cached(p) for p in sys.path]
-
- def safe_sys_path_index(entry):
- """
- Workaround for #520 and #513.
- """
- try:
- return sys_path.index(entry)
- except ValueError:
- return float('inf')
-
- def position_in_sys_path(path):
+
+ def safe_sys_path_index(entry):
"""
+ Workaround for #520 and #513.
+ """
+ try:
+ return sys_path.index(entry)
+ except ValueError:
+ return float('inf')
+
+ def position_in_sys_path(path):
+ """
Return the ordinal of the path based on its position in sys.path
"""
- path_parts = path.split(os.sep)
- module_parts = package_name.count('.') + 1
- parts = path_parts[:-module_parts]
- return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
+ path_parts = path.split(os.sep)
+ module_parts = package_name.count('.') + 1
+ parts = path_parts[:-module_parts]
+ return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
new_path = sorted(orig_path, key=position_in_sys_path)
new_path = [_normalize_cached(p) for p in new_path]
-
+
if isinstance(module.__path__, list):
module.__path__[:] = new_path
else:
@@ -2288,7 +2288,7 @@ def declare_namespace(packageName):
# Track what packages are namespaces, so when new path items are added,
# they can be updated
_namespace_packages.setdefault(parent or None, []).append(packageName)
- _namespace_packages.setdefault(packageName, [])
+ _namespace_packages.setdefault(packageName, [])
for path_item in path:
# Ensure all the parent's path items are reflected in the child,
@@ -2298,32 +2298,32 @@ def declare_namespace(packageName):
finally:
_imp.release_lock()
-
+
def fixup_namespace_packages(path_item, parent=None):
"""Ensure that previously-declared namespace packages include path_item"""
_imp.acquire_lock()
try:
- for package in _namespace_packages.get(parent, ()):
+ for package in _namespace_packages.get(parent, ()):
subpath = _handle_ns(package, path_item)
if subpath:
fixup_namespace_packages(subpath, package)
finally:
_imp.release_lock()
-
+
def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
- if _normalize_cached(item) == normalized:
+ if _normalize_cached(item) == normalized:
break
else:
# Only return the path if it's not already there
return subpath
-
+
register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
register_namespace_handler(zipimport.zipimporter, file_ns_handler)
@@ -2334,7 +2334,7 @@ if hasattr(importlib_machinery, 'FileFinder'):
def null_ns_handler(importer, path_item, packageName, module):
return None
-
+
register_namespace_handler(object, null_ns_handler)
@@ -2343,7 +2343,7 @@ def normalize_path(filename):
return os.path.normcase(os.path.realpath(os.path.normpath(
_cygwin_patch(filename))))
-
+
def _cygwin_patch(filename): # pragma: nocover
"""
Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
@@ -2362,7 +2362,7 @@ def _normalize_cached(filename, _cache={}):
_cache[filename] = result = normalize_path(filename)
return result
-
+
def _is_egg_path(path):
"""
Determine if given path appears to be an egg.
@@ -2387,7 +2387,7 @@ def _is_unpacked_egg(path):
os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))
)
-
+
def _set_parent_ns(packageName):
parts = packageName.split('.')
name = parts.pop()
@@ -2399,7 +2399,7 @@ def _set_parent_ns(packageName):
def _nonblank(str):
return str and not str.startswith('#')
-
+
@functools.singledispatch
def yield_lines(iterable):
"""Yield valid lines of a string or iterable"""
@@ -2477,14 +2477,14 @@ class EntryPoint:
def require(self, env=None, installer=None):
if self.extras and not self.dist:
raise UnknownExtra("Can't require() without a distribution", self)
-
- # Get the requirements for this entry point with all its extras and
- # then resolve them. We have to pass `extras` along when resolving so
- # that the working set knows what extras we want. Otherwise, for
- # dist-info distributions, the working set will assume that the
- # requirements for that extra are purely optional and skip over them.
+
+ # Get the requirements for this entry point with all its extras and
+ # then resolve them. We have to pass `extras` along when resolving so
+ # that the working set knows what extras we want. Otherwise, for
+ # dist-info distributions, the working set will assume that the
+ # requirements for that extra are purely optional and skip over them.
reqs = self.dist.requires(self.extras)
- items = working_set.resolve(reqs, env, installer, extras=self.extras)
+ items = working_set.resolve(reqs, env, installer, extras=self.extras)
list(map(working_set.add, items))
pattern = re.compile(
@@ -2535,7 +2535,7 @@ class EntryPoint:
ep = cls.parse(line, dist)
if ep.name in this:
raise ValueError("Duplicate entry point", group, ep.name)
- this[ep.name] = ep
+ this[ep.name] = ep
return this
@classmethod
@@ -2590,7 +2590,7 @@ class Distribution:
@classmethod
def from_location(cls, location, basename, metadata=None, **kw):
- project_name, version, py_version, platform = [None] * 4
+ project_name, version, py_version, platform = [None] * 4
basename, ext = os.path.splitext(basename)
if ext.lower() in _distributionImpl:
cls = _distributionImpl[ext.lower()]
@@ -2786,11 +2786,11 @@ class Distribution:
return version
- def activate(self, path=None, replace=False):
+ def activate(self, path=None, replace=False):
"""Ensure distribution is importable on `path` (default=sys.path)"""
if path is None:
path = sys.path
- self.insert_on(path, replace=replace)
+ self.insert_on(path, replace=replace)
if path is sys.path:
fixup_namespace_packages(self.location)
for pkg in self._get_metadata('namespace_packages.txt'):
@@ -2869,7 +2869,7 @@ class Distribution:
self._get_metadata('entry_points.txt'), self
)
if group is not None:
- return ep_map.get(group, {})
+ return ep_map.get(group, {})
return ep_map
def get_entry_info(self, group, name):
@@ -2878,46 +2878,46 @@ class Distribution:
# FIXME: 'Distribution.insert_on' is too complex (13)
def insert_on(self, path, loc=None, replace=False): # noqa: C901
- """Ensure self.location is on path
-
- If replace=False (default):
- - If location is already in path anywhere, do nothing.
- - Else:
- - If it's an egg and its parent directory is on path,
- insert just ahead of the parent.
- - Else: add to the end of path.
- If replace=True:
- - If location is already on path anywhere (not eggs)
- or higher priority than its parent (eggs)
- do nothing.
- - Else:
- - If it's an egg and its parent directory is on path,
- insert just ahead of the parent,
- removing any lower-priority entries.
- - Else: add it to the front of path.
- """
-
+ """Ensure self.location is on path
+
+ If replace=False (default):
+ - If location is already in path anywhere, do nothing.
+ - Else:
+ - If it's an egg and its parent directory is on path,
+ insert just ahead of the parent.
+ - Else: add to the end of path.
+ If replace=True:
+ - If location is already on path anywhere (not eggs)
+ or higher priority than its parent (eggs)
+ do nothing.
+ - Else:
+ - If it's an egg and its parent directory is on path,
+ insert just ahead of the parent,
+ removing any lower-priority entries.
+ - Else: add it to the front of path.
+ """
+
loc = loc or self.location
if not loc:
return
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
- npath = [(p and _normalize_cached(p) or p) for p in path]
+ npath = [(p and _normalize_cached(p) or p) for p in path]
for p, item in enumerate(npath):
if item == nloc:
- if replace:
- break
- else:
+ if replace:
+ break
+ else:
# don't modify path (even removing duplicates) if
# found and not replace
- return
+ return
elif item == bdir and self.precedence == EGG_DIST:
# if it's an .egg, give it precedence over its directory
- # UNLESS it's already been added to sys.path and replace=False
- if (not replace) and nloc in npath[p:]:
- return
+ # UNLESS it's already been added to sys.path and replace=False
+ if (not replace) and nloc in npath[p:]:
+ return
if path is sys.path:
self.check_version_conflict()
path.insert(p, loc)
@@ -2935,7 +2935,7 @@ class Distribution:
# p is the spot where we found or inserted loc; now remove duplicates
while True:
try:
- np = npath.index(nloc, p + 1)
+ np = npath.index(nloc, p + 1)
except ValueError:
break
else:
@@ -2975,7 +2975,7 @@ class Distribution:
return False
return True
- def clone(self, **kw):
+ def clone(self, **kw):
"""Copy this distribution, substituting in any changed keyword args"""
names = 'project_name version py_version platform location precedence'
for attr in names.split():
@@ -3040,19 +3040,19 @@ class DistInfoDistribution(Distribution):
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
- reqs.extend(parse_requirements(req))
+ reqs.extend(parse_requirements(req))
def reqs_for_extra(extra):
for req in reqs:
- if not req.marker or req.marker.evaluate({'extra': extra}):
+ if not req.marker or req.marker.evaluate({'extra': extra}):
yield req
common = frozenset(reqs_for_extra(None))
dm[None].extend(common)
for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
- s_extra = safe_extra(extra.strip())
- dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
+ s_extra = safe_extra(extra.strip())
+ dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)
return dm
@@ -3064,7 +3064,7 @@ _distributionImpl = {
}
-def issue_warning(*args, **kw):
+def issue_warning(*args, **kw):
level = 1
g = globals()
try:
@@ -3086,39 +3086,39 @@ def parse_requirements(strs):
lines = iter(yield_lines(strs))
for line in lines:
- # Drop comments -- a hash without a space may be in a URL.
- if ' #' in line:
- line = line[:line.find(' #')]
- # If there is a line continuation, drop it, and append the next line.
- if line.endswith('\\'):
- line = line[:-2].strip()
+ # Drop comments -- a hash without a space may be in a URL.
+ if ' #' in line:
+ line = line[:line.find(' #')]
+ # If there is a line continuation, drop it, and append the next line.
+ if line.endswith('\\'):
+ line = line[:-2].strip()
try:
line += next(lines)
except StopIteration:
return
- yield Requirement(line)
+ yield Requirement(line)
class RequirementParseError(packaging.requirements.InvalidRequirement):
"Compatibility wrapper for InvalidRequirement"
-class Requirement(packaging.requirements.Requirement):
- def __init__(self, requirement_string):
+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)
- self.unsafe_name = self.name
- project_name = safe_name(self.name)
+ 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]
- self.extras = tuple(map(safe_extra, self.extras))
+ self.specs = [
+ (spec.operator, spec.version) for spec in self.specifier]
+ self.extras = tuple(map(safe_extra, self.extras))
self.hashCmp = (
self.key,
self.url,
self.specifier,
frozenset(self.extras),
- str(self.marker) if self.marker else None,
+ str(self.marker) if self.marker else None,
)
self.__hash = hash(self.hashCmp)
@@ -3163,8 +3163,8 @@ def _always_object(classes):
if object not in classes:
return classes + (object,)
return classes
-
-
+
+
def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
@@ -3217,27 +3217,27 @@ def split_sections(s):
# wrap up last segment
yield section, content
-
-def _mkstemp(*args, **kw):
+
+def _mkstemp(*args, **kw):
old_open = os.open
try:
# temporarily bypass sandboxing
os.open = os_open
- return tempfile.mkstemp(*args, **kw)
+ return tempfile.mkstemp(*args, **kw)
finally:
# and then put it back
os.open = old_open
-# Yandex resource support
+# Yandex resource support
from __res import Y_PYTHON_SOURCE_ROOT, ResourceImporter, executable
-from library.python import resource
-
-
-class ResProvider(EmptyProvider):
+from library.python import resource
+
+
+class ResProvider(EmptyProvider):
_resource_fs = {}
- def __init__(self, prefix):
+ def __init__(self, prefix):
if hasattr(prefix, '__file__'):
key = prefix.__file__.rsplit('/', 1)[0]
self.module_path = 'resfs/file/{}/'.format(key)
@@ -3248,7 +3248,7 @@ class ResProvider(EmptyProvider):
# Сюда попадаем только из ResDistribution, который работает
# только метаданными, поэтому self.module_path не используется
self.egg_info = prefix
-
+
@staticmethod
def from_module(module):
if Y_PYTHON_SOURCE_ROOT:
@@ -3259,60 +3259,60 @@ class ResProvider(EmptyProvider):
def _fn(self, base, resource_name):
return base + resource_name
- def _has(self, path):
+ def _has(self, path):
return resource.find(path) is not None
-
- def _get(self, path):
+
+ def _get(self, path):
result = resource.find(path)
if result is None:
raise IOError(path)
return result
-
- @classmethod
- def _init_resource_fs(cls):
- for path in resource.iterkeys(b'resfs/file/'):
+
+ @classmethod
+ def _init_resource_fs(cls):
+ for path in resource.iterkeys(b'resfs/file/'):
path_str = path.decode('utf-8')
- components = path_str.split('/')
- for l in range(len(components)):
- subpath = os.path.normpath('/'.join(components[:l]))
- cls._resource_fs.setdefault(subpath, set()).add(components[l])
-
- def __lookup(self, path):
- if not self._resource_fs:
- self._init_resource_fs()
- path = os.path.normpath(path)
- return self._resource_fs.get(path)
-
+ components = path_str.split('/')
+ for l in range(len(components)):
+ subpath = os.path.normpath('/'.join(components[:l]))
+ cls._resource_fs.setdefault(subpath, set()).add(components[l])
+
+ def __lookup(self, path):
+ if not self._resource_fs:
+ self._init_resource_fs()
+ path = os.path.normpath(path)
+ return self._resource_fs.get(path)
+
def _listdir(self, path):
result = self.__lookup(path)
if result is None:
return []
return list(result)
-
+
def _isdir(self, path):
return bool(self.__lookup(path))
-class ResDistribution(DistInfoDistribution):
- def __init__(self, prefix):
- super(ResDistribution, self).__init__(
- location=executable,
- metadata=ResProvider(prefix),
- precedence=BINARY_DIST,
- )
+class ResDistribution(DistInfoDistribution):
+ def __init__(self, prefix):
+ super(ResDistribution, self).__init__(
+ location=executable,
+ metadata=ResProvider(prefix),
+ precedence=BINARY_DIST,
+ )
self.project_name = self._parsed_pkg_info.get('Name', self.project_name)
-
-
-def find_in_res(importer, path_item, only=False):
- for key in resource.iterkeys():
- if key.endswith('.dist-info/METADATA') and not key.startswith('resfs/src/'):
- yield ResDistribution(key[:-8])
-
-
-register_finder(ResourceImporter, find_in_res)
+
+
+def find_in_res(importer, path_item, only=False):
+ for key in resource.iterkeys():
+ if key.endswith('.dist-info/METADATA') and not key.startswith('resfs/src/'):
+ yield ResDistribution(key[:-8])
+
+
+register_finder(ResourceImporter, find_in_res)
register_loader_type(ResourceImporter, ResProvider.from_module)
-
-
+
+
# Silence the PEP440Warning by default, so that end users don't get hit by it
# 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
@@ -3331,11 +3331,11 @@ def _initialize(g=globals()):
"Set up global resource manager (deliberately not state-saved)"
manager = ResourceManager()
g['_manager'] = manager
- g.update(
- (name, getattr(manager, name))
- for name in dir(manager)
- if not name.startswith('_')
- )
+ g.update(
+ (name, getattr(manager, name))
+ for name in dir(manager)
+ if not name.startswith('_')
+ )
class PkgResourcesDeprecationWarning(Warning):
@@ -3369,19 +3369,19 @@ def _initialize_master_working_set():
run_script = working_set.run_script
# backward compatibility
run_main = run_script
- # Activate all distributions already on sys.path with replace=False and
- # ensure that all distributions added to the working set in the future
- # (e.g. by calling ``require()``) will get activated as well,
- # with higher priority (replace=True).
- tuple(
- dist.activate(replace=False)
- for dist in working_set
- )
+ # Activate all distributions already on sys.path with replace=False and
+ # ensure that all distributions added to the working set in the future
+ # (e.g. by calling ``require()``) will get activated as well,
+ # with higher priority (replace=True).
+ tuple(
+ dist.activate(replace=False)
+ for dist in working_set
+ )
add_activation_listener(
lambda dist: dist.activate(replace=True),
existing=False,
)
- working_set.entries = []
+ working_set.entries = []
# match order
list(map(working_set.add_entry, sys.path))
globals().update(locals())
diff --git a/contrib/python/setuptools/py3/setuptools/__init__.py b/contrib/python/setuptools/py3/setuptools/__init__.py
index 9d6f0bc0dd..d032ca17d3 100644
--- a/contrib/python/setuptools/py3/setuptools/__init__.py
+++ b/contrib/python/setuptools/py3/setuptools/__init__.py
@@ -17,7 +17,7 @@ import setuptools.version
from setuptools.extension import Extension
from setuptools.dist import Distribution
from setuptools.depends import Require
-from . import monkey
+from . import monkey
__all__ = [
@@ -37,18 +37,18 @@ bootstrap_install_from = None
class PackageFinder:
- """
- Generate a list of all Python packages found within a directory
- """
-
+ """
+ Generate a list of all Python packages found within a directory
+ """
+
@classmethod
def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
- 'where' is the root directory which will be searched for packages. It
- should be supplied as a "cross-platform" (i.e. URL-style) path; it will
- be converted to the appropriate local path syntax.
-
+ 'where' is the root directory which will be searched for packages. It
+ should be supplied as a "cross-platform" (i.e. URL-style) path; it will
+ be converted to the appropriate local path syntax.
+
'exclude' is a sequence of package names to exclude; '*' can be used
as a wildcard in the names, such that 'foo.*' will exclude all
subpackages of 'foo' (but not 'foo' itself).
@@ -67,54 +67,54 @@ class PackageFinder:
)
)
- @classmethod
- def _find_packages_iter(cls, where, exclude, include):
+ @classmethod
+ def _find_packages_iter(cls, where, exclude, include):
"""
- All the packages found in 'where' that pass the 'include' filter, but
- not the 'exclude' filter.
+ All the packages found in 'where' that pass the 'include' filter, but
+ not the 'exclude' filter.
"""
- for root, dirs, files in os.walk(where, followlinks=True):
- # Copy dirs to iterate over it, then empty dirs.
- all_dirs = dirs[:]
- dirs[:] = []
+ for root, dirs, files in os.walk(where, followlinks=True):
+ # Copy dirs to iterate over it, then empty dirs.
+ all_dirs = dirs[:]
+ dirs[:] = []
- for dir in all_dirs:
- full_path = os.path.join(root, dir)
- rel_path = os.path.relpath(full_path, where)
- package = rel_path.replace(os.path.sep, '.')
+ for dir in all_dirs:
+ full_path = os.path.join(root, dir)
+ rel_path = os.path.relpath(full_path, where)
+ package = rel_path.replace(os.path.sep, '.')
- # Skip directory trees that are not valid packages
+ # Skip directory trees that are not valid packages
if '.' in dir or not cls._looks_like_package(full_path):
- continue
-
- # Should this package be included?
- if include(package) and not exclude(package):
- yield package
-
- # Keep searching subdirectories, as there may be more packages
- # down there, even if the parent was excluded.
- dirs.append(dir)
-
+ continue
+
+ # Should this package be included?
+ if include(package) and not exclude(package):
+ yield package
+
+ # Keep searching subdirectories, as there may be more packages
+ # down there, even if the parent was excluded.
+ dirs.append(dir)
+
@staticmethod
def _looks_like_package(path):
- """Does a directory look like a package?"""
+ """Does a directory look like a package?"""
return os.path.isfile(os.path.join(path, '__init__.py'))
@staticmethod
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
- the input matches at least one of the patterns.
+ the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
-
+
class PEP420PackageFinder(PackageFinder):
@staticmethod
def _looks_like_package(path):
return True
-
+
find_packages = PackageFinder.find
find_namespace_packages = PEP420PackageFinder.find
@@ -156,9 +156,9 @@ def setup(**attrs):
setup.__doc__ = distutils.core.setup.__doc__
-_Command = monkey.get_unpatched(distutils.core.Command)
-
+_Command = monkey.get_unpatched(distutils.core.Command)
+
class Command(_Command):
__doc__ = _Command.__doc__
@@ -239,4 +239,4 @@ class sic(str):
# Apply monkey patches
-monkey.patch_all()
+monkey.patch_all()
diff --git a/contrib/python/setuptools/py3/setuptools/archive_util.py b/contrib/python/setuptools/py3/setuptools/archive_util.py
index 0f70284822..0a45b93f4f 100644
--- a/contrib/python/setuptools/py3/setuptools/archive_util.py
+++ b/contrib/python/setuptools/py3/setuptools/archive_util.py
@@ -9,18 +9,18 @@ import contextlib
from distutils.errors import DistutilsError
from pkg_resources import ensure_directory
-
-__all__ = [
- "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",
- "UnrecognizedFormat", "extraction_drivers", "unpack_directory",
-]
-
-
+
+__all__ = [
+ "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",
+ "UnrecognizedFormat", "extraction_drivers", "unpack_directory",
+]
+
+
class UnrecognizedFormat(DistutilsError):
"""Couldn't recognize the archive type"""
-
-def default_filter(src, dst):
+
+def default_filter(src, dst):
"""The default progress/filter callback; returns True for all files"""
return dst
@@ -201,5 +201,5 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
return True
-
+
extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
diff --git a/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py b/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
index e6b1609f7b..940d4b121e 100644
--- a/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
+++ b/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
@@ -8,7 +8,7 @@ from types import CodeType
import sys
import os
import re
-import textwrap
+import textwrap
import marshal
from pkg_resources import get_build_platform, Distribution, ensure_directory
@@ -132,7 +132,7 @@ class bdist_egg(Command):
self.distribution.data_files.append(item)
try:
- log.info("installing package data to %s", self.bdist_dir)
+ log.info("installing package data to %s", self.bdist_dir)
self.call_command('install_data', force=0, root=None)
finally:
self.distribution.data_files = old
@@ -155,7 +155,7 @@ class bdist_egg(Command):
self.run_command("egg_info")
# We run install_lib before install_data, because some data hacks
# pull their data path from the install_lib command.
- log.info("installing library code to %s", self.bdist_dir)
+ log.info("installing library code to %s", self.bdist_dir)
instcmd = self.get_finalized_command('install')
old_root = instcmd.root
instcmd.root = None
@@ -172,7 +172,7 @@ class bdist_egg(Command):
pyfile = os.path.join(self.bdist_dir, strip_module(filename) +
'.py')
self.stubs.append(pyfile)
- log.info("creating stub loader for %s", ext_name)
+ log.info("creating stub loader for %s", ext_name)
if not self.dry_run:
write_stub(os.path.basename(ext_name), pyfile)
to_compile.append(pyfile)
@@ -189,14 +189,14 @@ class bdist_egg(Command):
self.mkpath(egg_info)
if self.distribution.scripts:
script_dir = os.path.join(egg_info, 'scripts')
- log.info("installing scripts to %s", script_dir)
+ log.info("installing scripts to %s", script_dir)
self.call_command('install_scripts', install_dir=script_dir,
no_ep=1)
self.copy_metadata_to(egg_info)
native_libs = os.path.join(egg_info, "native_libs.txt")
if all_outputs:
- log.info("writing %s", native_libs)
+ log.info("writing %s", native_libs)
if not self.dry_run:
ensure_directory(native_libs)
libs_file = open(native_libs, 'wt')
@@ -204,7 +204,7 @@ class bdist_egg(Command):
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
- log.info("removing %s", native_libs)
+ log.info("removing %s", native_libs)
if not self.dry_run:
os.unlink(native_libs)
@@ -413,7 +413,7 @@ def can_scan():
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py")
-
+
# Attribute names of options for commands that might need to be convinced to
# install to the egg build directory
@@ -442,7 +442,7 @@ def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
p = path[len(base_dir) + 1:]
if not dry_run:
z.write(path, p)
- log.debug("adding '%s'", p)
+ log.debug("adding '%s'", p)
compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED
if not dry_run:
diff --git a/contrib/python/setuptools/py3/setuptools/command/build_clib.py b/contrib/python/setuptools/py3/setuptools/command/build_clib.py
index 67ce2444ea..ed7d2cfe09 100644
--- a/contrib/python/setuptools/py3/setuptools/command/build_clib.py
+++ b/contrib/python/setuptools/py3/setuptools/command/build_clib.py
@@ -1,86 +1,86 @@
-import distutils.command.build_clib as orig
-from distutils.errors import DistutilsSetupError
-from distutils import log
-from setuptools.dep_util import newer_pairwise_group
-
-
-class build_clib(orig.build_clib):
- """
- Override the default build_clib behaviour to do the following:
-
- 1. Implement a rudimentary timestamp-based dependency system
- so 'compile()' doesn't run every time.
- 2. Add more keys to the 'build_info' dictionary:
- * obj_deps - specify dependencies for each object compiled.
- this should be a dictionary mapping a key
- with the source filename to a list of
- dependencies. Use an empty string for global
- dependencies.
- * cflags - specify a list of additional flags to pass to
- the compiler.
- """
-
- def build_libraries(self, libraries):
- for (lib_name, build_info) in libraries:
- sources = build_info.get('sources')
- if sources is None or not isinstance(sources, (list, tuple)):
- raise DistutilsSetupError(
+import distutils.command.build_clib as orig
+from distutils.errors import DistutilsSetupError
+from distutils import log
+from setuptools.dep_util import newer_pairwise_group
+
+
+class build_clib(orig.build_clib):
+ """
+ Override the default build_clib behaviour to do the following:
+
+ 1. Implement a rudimentary timestamp-based dependency system
+ so 'compile()' doesn't run every time.
+ 2. Add more keys to the 'build_info' dictionary:
+ * obj_deps - specify dependencies for each object compiled.
+ this should be a dictionary mapping a key
+ with the source filename to a list of
+ dependencies. Use an empty string for global
+ dependencies.
+ * cflags - specify a list of additional flags to pass to
+ the compiler.
+ """
+
+ def build_libraries(self, libraries):
+ for (lib_name, build_info) in libraries:
+ sources = build_info.get('sources')
+ if sources is None or not isinstance(sources, (list, tuple)):
+ raise DistutilsSetupError(
"in 'libraries' option (library '%s'), "
"'sources' must be present and must be "
"a list of source filenames" % lib_name)
- sources = list(sources)
-
- log.info("building '%s' library", lib_name)
-
- # Make sure everything is the correct type.
- # obj_deps should be a dictionary of keys as sources
- # and a list/tuple of files that are its dependencies.
- obj_deps = build_info.get('obj_deps', dict())
- if not isinstance(obj_deps, dict):
- raise DistutilsSetupError(
+ sources = list(sources)
+
+ log.info("building '%s' library", lib_name)
+
+ # Make sure everything is the correct type.
+ # obj_deps should be a dictionary of keys as sources
+ # and a list/tuple of files that are its dependencies.
+ obj_deps = build_info.get('obj_deps', dict())
+ if not isinstance(obj_deps, dict):
+ raise DistutilsSetupError(
"in 'libraries' option (library '%s'), "
"'obj_deps' must be a dictionary of "
"type 'source: list'" % lib_name)
- dependencies = []
-
- # Get the global dependencies that are specified by the '' key.
- # These will go into every source's dependency list.
- global_deps = obj_deps.get('', list())
- if not isinstance(global_deps, (list, tuple)):
- raise DistutilsSetupError(
+ dependencies = []
+
+ # Get the global dependencies that are specified by the '' key.
+ # These will go into every source's dependency list.
+ global_deps = obj_deps.get('', list())
+ if not isinstance(global_deps, (list, tuple)):
+ raise DistutilsSetupError(
"in 'libraries' option (library '%s'), "
"'obj_deps' must be a dictionary of "
"type 'source: list'" % lib_name)
-
- # Build the list to be used by newer_pairwise_group
- # each source will be auto-added to its dependencies.
- for source in sources:
- src_deps = [source]
- src_deps.extend(global_deps)
- extra_deps = obj_deps.get(source, list())
- if not isinstance(extra_deps, (list, tuple)):
- raise DistutilsSetupError(
+
+ # Build the list to be used by newer_pairwise_group
+ # each source will be auto-added to its dependencies.
+ for source in sources:
+ src_deps = [source]
+ src_deps.extend(global_deps)
+ extra_deps = obj_deps.get(source, list())
+ if not isinstance(extra_deps, (list, tuple)):
+ raise DistutilsSetupError(
"in 'libraries' option (library '%s'), "
"'obj_deps' must be a dictionary of "
"type 'source: list'" % lib_name)
- src_deps.extend(extra_deps)
- dependencies.append(src_deps)
-
- expected_objects = self.compiler.object_filenames(
+ src_deps.extend(extra_deps)
+ dependencies.append(src_deps)
+
+ expected_objects = self.compiler.object_filenames(
sources,
output_dir=self.build_temp,
)
-
+
if (
newer_pairwise_group(dependencies, expected_objects)
!= ([], [])
):
- # First, compile the source code to object files in the library
- # directory. (This should probably change to putting object
- # files in a temporary build directory.)
- macros = build_info.get('macros')
- include_dirs = build_info.get('include_dirs')
- cflags = build_info.get('cflags')
+ # First, compile the source code to object files in the library
+ # directory. (This should probably change to putting object
+ # files in a temporary build directory.)
+ macros = build_info.get('macros')
+ include_dirs = build_info.get('include_dirs')
+ cflags = build_info.get('cflags')
self.compiler.compile(
sources,
output_dir=self.build_temp,
@@ -89,11 +89,11 @@ class build_clib(orig.build_clib):
extra_postargs=cflags,
debug=self.debug
)
-
- # Now "link" the object files together into a static library.
- # (On Unix at least, this isn't really linking -- it just
- # builds an archive. Whatever.)
- self.compiler.create_static_lib(
+
+ # Now "link" the object files together into a static library.
+ # (On Unix at least, this isn't really linking -- it just
+ # builds an archive. Whatever.)
+ self.compiler.create_static_lib(
expected_objects,
lib_name,
output_dir=self.build_clib,
diff --git a/contrib/python/setuptools/py3/setuptools/command/build_ext.py b/contrib/python/setuptools/py3/setuptools/command/build_ext.py
index c59eff8bbf..8fd22c2f0d 100644
--- a/contrib/python/setuptools/py3/setuptools/command/build_ext.py
+++ b/contrib/python/setuptools/py3/setuptools/command/build_ext.py
@@ -1,11 +1,11 @@
-import os
-import sys
-import itertools
+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.sysconfig import customize_compiler, get_config_var
+from distutils.sysconfig import customize_compiler, get_config_var
from distutils.errors import DistutilsError
from distutils import log
@@ -20,31 +20,31 @@ try:
except ImportError:
_build_ext = _du_build_ext
-# make sure _config_vars is initialized
-get_config_var("LDSHARED")
+# make sure _config_vars is initialized
+get_config_var("LDSHARED")
from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa
-def _customize_compiler_for_shlib(compiler):
- if sys.platform == "darwin":
- # building .dylib requires additional compiler flags on OSX; here we
- # temporarily substitute the pyconfig.h variables so that distutils'
- # 'customize_compiler' uses them before we build the shared libraries.
- tmp = _CONFIG_VARS.copy()
- try:
- # XXX Help! I don't have any idea whether these are right...
- _CONFIG_VARS['LDSHARED'] = (
- "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup")
- _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
- _CONFIG_VARS['SO'] = ".dylib"
- customize_compiler(compiler)
- finally:
- _CONFIG_VARS.clear()
- _CONFIG_VARS.update(tmp)
- else:
- customize_compiler(compiler)
-
-
+def _customize_compiler_for_shlib(compiler):
+ if sys.platform == "darwin":
+ # building .dylib requires additional compiler flags on OSX; here we
+ # temporarily substitute the pyconfig.h variables so that distutils'
+ # 'customize_compiler' uses them before we build the shared libraries.
+ tmp = _CONFIG_VARS.copy()
+ try:
+ # XXX Help! I don't have any idea whether these are right...
+ _CONFIG_VARS['LDSHARED'] = (
+ "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup")
+ _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
+ _CONFIG_VARS['SO'] = ".dylib"
+ customize_compiler(compiler)
+ finally:
+ _CONFIG_VARS.clear()
+ _CONFIG_VARS.update(tmp)
+ else:
+ customize_compiler(compiler)
+
+
have_rtld = False
use_stubs = False
libtype = 'shared'
@@ -61,17 +61,17 @@ elif os.name != 'nt':
def if_dl(s):
return s if have_rtld else ''
+
-
-def get_abi3_suffix():
- """Return the file extension for an abi3-compliant Extension()"""
+def get_abi3_suffix():
+ """Return the file extension for an abi3-compliant Extension()"""
for suffix in EXTENSION_SUFFIXES:
- if '.abi3' in suffix: # Unix
- return suffix
- elif suffix == '.pyd': # Windows
- return suffix
-
-
+ if '.abi3' in suffix: # Unix
+ return suffix
+ elif suffix == '.pyd': # Windows
+ return suffix
+
+
class build_ext(_build_ext):
def run(self):
"""Build extensions in build directory, then copy if --inplace"""
@@ -114,8 +114,8 @@ class build_ext(_build_ext):
if fullname in self.ext_map:
ext = self.ext_map[fullname]
use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()
- if use_abi3:
- filename = filename[:-len(so_ext)]
+ if use_abi3:
+ filename = filename[:-len(so_ext)]
so_ext = get_abi3_suffix()
filename = filename + so_ext
if isinstance(ext, Library):
@@ -165,7 +165,7 @@ class build_ext(_build_ext):
compiler = self.shlib_compiler = new_compiler(
compiler=self.compiler, dry_run=self.dry_run, force=self.force
)
- _customize_compiler_for_shlib(compiler)
+ _customize_compiler_for_shlib(compiler)
if self.include_dirs is not None:
compiler.set_include_dirs(self.include_dirs)
diff --git a/contrib/python/setuptools/py3/setuptools/command/build_py.py b/contrib/python/setuptools/py3/setuptools/command/build_py.py
index c3fdc0927c..fe3d663661 100644
--- a/contrib/python/setuptools/py3/setuptools/command/build_py.py
+++ b/contrib/python/setuptools/py3/setuptools/command/build_py.py
@@ -10,7 +10,7 @@ import itertools
import stat
from setuptools.extern.more_itertools import unique_everseen
-
+
def make_writable(target):
os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)
@@ -93,19 +93,19 @@ class build_py(orig.build_py):
def find_data_files(self, package, src_dir):
"""Return filenames for package's data files in 'src_dir'"""
- patterns = self._get_platform_patterns(
- self.package_data,
- package,
- src_dir,
- )
- globs_expanded = map(glob, patterns)
- # flatten the expanded globs into an iterable of matches
- globs_matches = itertools.chain.from_iterable(globs_expanded)
- glob_files = filter(os.path.isfile, globs_matches)
- files = itertools.chain(
- self.manifest_files.get(package, []),
- glob_files,
- )
+ patterns = self._get_platform_patterns(
+ self.package_data,
+ package,
+ src_dir,
+ )
+ globs_expanded = map(glob, patterns)
+ # flatten the expanded globs into an iterable of matches
+ globs_matches = itertools.chain.from_iterable(globs_expanded)
+ glob_files = filter(os.path.isfile, globs_matches)
+ files = itertools.chain(
+ self.manifest_files.get(package, []),
+ glob_files,
+ )
return self.exclude_data_files(package, src_dir, files)
def build_package_data(self):
@@ -188,39 +188,39 @@ class build_py(orig.build_py):
def exclude_data_files(self, package, src_dir, files):
"""Filter filenames for package's data files in 'src_dir'"""
- files = list(files)
- patterns = self._get_platform_patterns(
- self.exclude_package_data,
- package,
- src_dir,
+ files = list(files)
+ patterns = self._get_platform_patterns(
+ self.exclude_package_data,
+ package,
+ src_dir,
)
match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)
- # flatten the groups of matches into an iterable of matches
- matches = itertools.chain.from_iterable(match_groups)
- bad = set(matches)
+ # flatten the groups of matches into an iterable of matches
+ matches = itertools.chain.from_iterable(match_groups)
+ bad = set(matches)
keepers = (fn for fn in files if fn not in bad)
- # ditch dupes
+ # ditch dupes
return list(unique_everseen(keepers))
- @staticmethod
- def _get_platform_patterns(spec, package, src_dir):
- """
- yield platform-specific path patterns (suitable for glob
- or fn_match) from a glob-based spec (such as
- self.package_data or self.exclude_package_data)
- matching package in src_dir.
- """
- raw_patterns = itertools.chain(
- spec.get('', []),
- spec.get(package, []),
- )
- return (
- # Each pattern has to be converted to a platform-specific path
- os.path.join(src_dir, convert_path(pattern))
- for pattern in raw_patterns
- )
-
-
+ @staticmethod
+ def _get_platform_patterns(spec, package, src_dir):
+ """
+ yield platform-specific path patterns (suitable for glob
+ or fn_match) from a glob-based spec (such as
+ self.package_data or self.exclude_package_data)
+ matching package in src_dir.
+ """
+ raw_patterns = itertools.chain(
+ spec.get('', []),
+ spec.get(package, []),
+ )
+ return (
+ # Each pattern has to be converted to a platform-specific path
+ os.path.join(src_dir, convert_path(pattern))
+ for pattern in raw_patterns
+ )
+
+
def assert_relative(path):
if not os.path.isabs(path):
return path
diff --git a/contrib/python/setuptools/py3/setuptools/command/develop.py b/contrib/python/setuptools/py3/setuptools/command/develop.py
index 24fb0a7c81..249670c415 100644
--- a/contrib/python/setuptools/py3/setuptools/command/develop.py
+++ b/contrib/python/setuptools/py3/setuptools/command/develop.py
@@ -7,11 +7,11 @@ import io
import pkg_resources
from setuptools.command.easy_install import easy_install
-from setuptools import namespaces
+from setuptools import namespaces
import setuptools
-class develop(namespaces.DevelopInstaller, easy_install):
+class develop(namespaces.DevelopInstaller, easy_install):
"""Set up package for development"""
description = "install package in 'development mode'"
@@ -29,7 +29,7 @@ class develop(namespaces.DevelopInstaller, easy_install):
if self.uninstall:
self.multi_version = True
self.uninstall_link()
- self.uninstall_namespaces()
+ self.uninstall_namespaces()
else:
self.install_for_development()
self.warn_deprecated_options()
@@ -78,22 +78,22 @@ class develop(namespaces.DevelopInstaller, easy_install):
project_name=ei.egg_name,
)
- self.setup_path = self._resolve_setup_path(
- self.egg_base,
- self.install_dir,
- self.egg_path,
- )
-
- @staticmethod
- def _resolve_setup_path(egg_base, install_dir, egg_path):
- """
- Generate a path from egg_base back to '.' where the
- setup script resides and ensure that path points to the
- setup path from $install_dir/$egg_path.
- """
- path_to_setup = egg_base.replace(os.sep, '/').rstrip('/')
- if path_to_setup != os.curdir:
- path_to_setup = '../' * (path_to_setup.count('/') + 1)
+ self.setup_path = self._resolve_setup_path(
+ self.egg_base,
+ self.install_dir,
+ self.egg_path,
+ )
+
+ @staticmethod
+ def _resolve_setup_path(egg_base, install_dir, egg_path):
+ """
+ Generate a path from egg_base back to '.' where the
+ setup script resides and ensure that path points to the
+ setup path from $install_dir/$egg_path.
+ """
+ path_to_setup = egg_base.replace(os.sep, '/').rstrip('/')
+ if path_to_setup != os.curdir:
+ path_to_setup = '../' * (path_to_setup.count('/') + 1)
resolved = pkg_resources.normalize_path(
os.path.join(install_dir, egg_path, path_to_setup)
)
@@ -104,7 +104,7 @@ class develop(namespaces.DevelopInstaller, easy_install):
resolved,
pkg_resources.normalize_path(os.curdir),
)
- return path_to_setup
+ return path_to_setup
def install_for_development(self):
self.run_command('egg_info')
@@ -117,8 +117,8 @@ class develop(namespaces.DevelopInstaller, easy_install):
self.easy_install(setuptools.bootstrap_install_from)
setuptools.bootstrap_install_from = None
- self.install_namespaces()
-
+ self.install_namespaces()
+
# create an .egg-link in the installation dir, pointing to our egg
log.info("Creating %s (link to %s)", self.egg_link, self.egg_base)
if not self.dry_run:
@@ -182,7 +182,7 @@ class VersionlessRequirement:
>>> str(adapted_dist.as_requirement())
'foo'
"""
-
+
def __init__(self, dist):
self.__dist = dist
diff --git a/contrib/python/setuptools/py3/setuptools/command/easy_install.py b/contrib/python/setuptools/py3/setuptools/command/easy_install.py
index fc848d0d1c..15abe5d068 100644
--- a/contrib/python/setuptools/py3/setuptools/command/easy_install.py
+++ b/contrib/python/setuptools/py3/setuptools/command/easy_install.py
@@ -13,10 +13,10 @@ __ https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
from glob import glob
from distutils.util import get_platform
from distutils.util import convert_path, subst_vars
-from distutils.errors import (
- DistutilsArgError, DistutilsOptionError,
- DistutilsError, DistutilsPlatformError,
-)
+from distutils.errors import (
+ DistutilsArgError, DistutilsOptionError,
+ DistutilsError, DistutilsPlatformError,
+)
from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
from distutils import log, dir_util
from distutils.command.build_scripts import first_line_re
@@ -49,9 +49,9 @@ from setuptools import Command
from setuptools.sandbox import run_setup
from setuptools.command import setopt
from setuptools.archive_util import unpack_archive
-from setuptools.package_index import (
- PackageIndex, parse_requirement_arg, URL_SCHEME,
-)
+from setuptools.package_index import (
+ PackageIndex, parse_requirement_arg, URL_SCHEME,
+)
from setuptools.command import bdist_egg, egg_info
from setuptools.wheel import Wheel
from pkg_resources import (
@@ -76,12 +76,12 @@ def is_64bit():
def samefile(p1, p2):
- """
- Determine if two paths reference the same file.
-
- Augments os.path.samefile to work on Windows and
- suppresses errors if the path doesn't exist.
- """
+ """
+ Determine if two paths reference the same file.
+
+ Augments os.path.samefile to work on Windows and
+ suppresses errors if the path doesn't exist.
+ """
both_exist = os.path.exists(p1) and os.path.exists(p2)
use_samefile = hasattr(os.path, 'samefile') and both_exist
if use_samefile:
@@ -93,7 +93,7 @@ def samefile(p1, p2):
def _to_bytes(s):
return s.encode('utf8')
-
+
def isascii(s):
try:
@@ -101,7 +101,7 @@ def isascii(s):
return True
except UnicodeError:
return False
-
+
def _one_liner(text):
return textwrap.dedent(text).strip().replace('\n', '; ')
@@ -265,10 +265,10 @@ class easy_install(Command):
self.expand_basedirs()
self.expand_dirs()
- self._expand(
- 'install_dir', 'script_dir', 'build_directory',
- 'site_dirs',
- )
+ self._expand(
+ 'install_dir', 'script_dir', 'build_directory',
+ 'site_dirs',
+ )
# If a non-default installation directory was specified, default the
# script directory to match it.
if self.script_dir is None:
@@ -390,15 +390,15 @@ class easy_install(Command):
def expand_dirs(self):
"""Calls `os.path.expanduser` on install dirs."""
- dirs = [
- 'install_purelib',
- 'install_platlib',
- 'install_lib',
- 'install_headers',
- 'install_scripts',
- 'install_data',
- ]
- self._expand_attrs(dirs)
+ dirs = [
+ 'install_purelib',
+ 'install_platlib',
+ 'install_lib',
+ 'install_headers',
+ 'install_scripts',
+ 'install_data',
+ ]
+ self._expand_attrs(dirs)
def run(self, show_deprecation=True):
if show_deprecation:
@@ -436,7 +436,7 @@ class easy_install(Command):
"""
try:
pid = os.getpid()
- except Exception:
+ except Exception:
pid = random.randint(0, sys.maxsize)
return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
@@ -540,12 +540,12 @@ class easy_install(Command):
pth_file = self.pseudo_tempname() + ".pth"
ok_file = pth_file + '.ok'
ok_exists = os.path.exists(ok_file)
- tmpl = _one_liner("""
- import os
- f = open({ok_file!r}, 'w')
- f.write('OK')
- f.close()
- """) + '\n'
+ tmpl = _one_liner("""
+ import os
+ f = open({ok_file!r}, 'w')
+ f.write('OK')
+ f.close()
+ """) + '\n'
try:
if ok_exists:
os.unlink(ok_file)
@@ -556,18 +556,18 @@ class easy_install(Command):
self.cant_write_to_target()
else:
try:
- f.write(tmpl.format(**locals()))
+ f.write(tmpl.format(**locals()))
f.close()
f = None
executable = sys.executable
if os.name == 'nt':
dirname, basename = os.path.split(executable)
alt = os.path.join(dirname, 'pythonw.exe')
- use_alt = (
- basename.lower() == 'python.exe' and
- os.path.exists(alt)
- )
- if use_alt:
+ use_alt = (
+ basename.lower() == 'python.exe' and
+ os.path.exists(alt)
+ )
+ if use_alt:
# use pythonw.exe to avoid opening a console window
executable = alt
@@ -632,23 +632,23 @@ class easy_install(Command):
(spec.key, self.build_directory)
)
- @contextlib.contextmanager
- def _tmpdir(self):
+ @contextlib.contextmanager
+ def _tmpdir(self):
tmpdir = tempfile.mkdtemp(prefix=u"easy_install-")
- try:
- # cast to str as workaround for #709 and #710 and #712
- yield str(tmpdir)
- finally:
+ try:
+ # cast to str as workaround for #709 and #710 and #712
+ yield str(tmpdir)
+ finally:
os.path.exists(tmpdir) and rmtree(tmpdir)
-
+
def easy_install(self, spec, deps=False):
- with self._tmpdir() as tmpdir:
+ with self._tmpdir() as tmpdir:
if not isinstance(spec, Requirement):
if URL_SCHEME(spec):
# It's a url, download it to tmpdir and process
self.not_editable(spec)
- dl = self.package_index.download(spec, tmpdir)
- return self.install_item(None, dl, tmpdir, deps, True)
+ dl = self.package_index.download(spec, tmpdir)
+ return self.install_item(None, dl, tmpdir, deps, True)
elif os.path.exists(spec):
# Existing file or directory, just process it directly
@@ -744,7 +744,7 @@ class easy_install(Command):
elif requirement is None or dist not in requirement:
# if we wound up with a different version, resolve what we've got
distreq = dist.as_requirement()
- requirement = Requirement(str(distreq))
+ requirement = Requirement(str(distreq))
log.info("Processing dependencies for %s", requirement)
try:
distros = WorkingSet([]).resolve(
@@ -773,9 +773,9 @@ class easy_install(Command):
def maybe_move(self, spec, dist_filename, setup_base):
dst = os.path.join(self.build_directory, spec.key)
if os.path.exists(dst):
- msg = (
- "%r already exists in %s; build directory %s will not be kept"
- )
+ msg = (
+ "%r already exists in %s; build directory %s will not be kept"
+ )
log.warn(msg, spec.key, self.build_directory, setup_base)
return setup_base
if os.path.isdir(dist_filename):
@@ -815,7 +815,7 @@ class easy_install(Command):
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
"""
- # See https://github.com/pypa/setuptools/issues/134 for info
+ # See https://github.com/pypa/setuptools/issues/134 for info
# on script file naming and downstream issues with SVR4
name = 'script.tmpl'
if dev_path:
@@ -905,10 +905,10 @@ class easy_install(Command):
# FIXME: 'easy_install.install_egg' is too complex (11)
def install_egg(self, egg_path, tmpdir): # noqa: C901
- destination = os.path.join(
- self.install_dir,
- os.path.basename(egg_path),
- )
+ destination = os.path.join(
+ self.install_dir,
+ os.path.basename(egg_path),
+ )
destination = os.path.abspath(destination)
if not self.dry_run:
ensure_directory(destination)
@@ -918,11 +918,11 @@ class easy_install(Command):
if os.path.isdir(destination) and not os.path.islink(destination):
dir_util.remove_tree(destination, dry_run=self.dry_run)
elif os.path.exists(destination):
- self.execute(
- os.unlink,
- (destination,),
- "Removing " + destination,
- )
+ self.execute(
+ os.unlink,
+ (destination,),
+ "Removing " + destination,
+ )
try:
new_dist_is_zipped = False
if os.path.isdir(egg_path):
@@ -939,19 +939,19 @@ class easy_install(Command):
f, m = shutil.move, "Moving"
else:
f, m = shutil.copy2, "Copying"
- self.execute(
- f,
- (egg_path, destination),
- (m + " %s to %s") % (
- os.path.basename(egg_path),
- os.path.dirname(destination)
- ),
- )
- update_dist_caches(
- destination,
- fix_zipimporter_caches=new_dist_is_zipped,
- )
- except Exception:
+ self.execute(
+ f,
+ (egg_path, destination),
+ (m + " %s to %s") % (
+ os.path.basename(egg_path),
+ os.path.dirname(destination)
+ ),
+ )
+ update_dist_caches(
+ destination,
+ fix_zipimporter_caches=new_dist_is_zipped,
+ )
+ except Exception:
update_dist_caches(destination, fix_zipimporter_caches=False)
raise
@@ -973,8 +973,8 @@ class easy_install(Command):
)
# Convert the .exe to an unpacked egg
- egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
- dist.location = egg_path
+ egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
+ dist.location = egg_path
egg_tmp = egg_path + '.tmp'
_egg_info = os.path.join(egg_tmp, 'EGG-INFO')
pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
@@ -992,13 +992,13 @@ class easy_install(Command):
f.close()
script_dir = os.path.join(_egg_info, 'scripts')
# delete entry-point scripts to avoid duping
- self.delete_blockers([
- os.path.join(script_dir, args[0])
- for args in ScriptWriter.get_args(dist)
- ])
+ self.delete_blockers([
+ os.path.join(script_dir, args[0])
+ for args in ScriptWriter.get_args(dist)
+ ])
# Build .egg file from tmpdir
bdist_egg.make_zipfile(
- egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,
+ egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,
)
# install the .egg
return self.install_egg(egg_path, tmpdir)
@@ -1219,7 +1219,7 @@ class easy_install(Command):
if dist.location in self.pth_file.paths:
log.info(
"%s is already the active version in easy-install.pth",
- dist,
+ dist,
)
else:
log.info("Adding %s to easy-install.pth file", dist)
@@ -1281,7 +1281,7 @@ class easy_install(Command):
if self.optimize:
byte_compile(
to_compile, optimize=self.optimize, force=1,
- dry_run=self.dry_run,
+ dry_run=self.dry_run,
)
finally:
log.set_verbosity(self.verbose) # restore original verbosity
@@ -1314,7 +1314,7 @@ class easy_install(Command):
https://setuptools.pypa.io/en/latest/deprecated/easy_install.html#custom-installation-locations
-
+
Please make the appropriate changes for your system and try again.
""").strip()
@@ -1390,7 +1390,7 @@ def get_site_dirs():
elif os.sep == '/':
sitedirs.extend([
os.path.join(
- prefix,
+ prefix,
"lib",
"python{}.{}".format(*sys.version_info),
"site-packages",
@@ -1431,8 +1431,8 @@ def get_site_dirs():
sitedirs.append(site.USER_SITE)
with contextlib.suppress(AttributeError):
- sitedirs.extend(site.getsitepackages())
-
+ sitedirs.extend(site.getsitepackages())
+
sitedirs = list(map(normalize_path, sitedirs))
return sitedirs
@@ -1505,8 +1505,8 @@ def extract_wininst_cfg(dist_filename):
return None # not a valid tag
f.seek(prepended - (12 + cfglen))
- init = {'version': '', 'target_version': ''}
- cfg = configparser.RawConfigParser(init)
+ init = {'version': '', 'target_version': ''}
+ cfg = configparser.RawConfigParser(init)
try:
part = f.read(cfglen)
# Read up to the first null byte.
@@ -1529,8 +1529,8 @@ def get_exe_prefixes(exe_filename):
"""Get exe->egg path translations for a given .exe file"""
prefixes = [
- ('PURELIB/', ''),
- ('PLATLIB/pywin32_system32', ''),
+ ('PURELIB/', ''),
+ ('PLATLIB/pywin32_system32', ''),
('PLATLIB/', ''),
('SCRIPTS/', 'EGG-INFO/scripts/'),
('DATA/lib/site-packages', ''),
@@ -1678,11 +1678,11 @@ class RewritePthDistributions(PthDistributions):
yield line
yield cls.postlude
- prelude = _one_liner("""
+ prelude = _one_liner("""
import sys
sys.__plen = len(sys.path)
""")
- postlude = _one_liner("""
+ postlude = _one_liner("""
import sys
new = sys.path[sys.__plen:]
del sys.path[sys.__plen:]
@@ -1692,7 +1692,7 @@ class RewritePthDistributions(PthDistributions):
""")
-if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
+if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
PthDistributions = RewritePthDistributions
@@ -1709,7 +1709,7 @@ def _first_line_re():
def auto_chmod(func, arg, exc):
- if func in [os.unlink, os.remove] and os.name == 'nt':
+ if func in [os.unlink, os.remove] and os.name == 'nt':
chmod(arg, stat.S_IWRITE)
return func(arg)
et, ev, _ = sys.exc_info()
@@ -1842,7 +1842,7 @@ def _update_zipimporter_cache(normalized_path, cache, updater=None):
# * Does not support the dict.pop() method, forcing us to use the
# get/del patterns instead. For more detailed information see the
# following links:
- # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
+ # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
# http://bit.ly/2h9itJX
old_entry = cache[p]
del cache[p]
@@ -1863,7 +1863,7 @@ def _remove_and_clear_zip_directory_cache_data(normalized_path):
normalized_path, zipimport._zip_directory_cache,
updater=clear_and_remove_cached_zip_archive_directory_data)
-
+
# PyPy Python implementation does not allow directly writing to the
# zipimport._zip_directory_cache and so prevents us from attempting to correct
# its content. The best we can do there is clear the problematic cache content
@@ -1876,7 +1876,7 @@ if '__pypy__' in sys.builtin_module_names:
_replace_zip_directory_cache_data = \
_remove_and_clear_zip_directory_cache_data
else:
-
+
def _replace_zip_directory_cache_data(normalized_path):
def replace_cached_zip_archive_directory_data(path, old_entry):
# N.B. In theory, we could load the zip directory information just
@@ -2020,20 +2020,20 @@ class CommandSpec(list):
return self._render(self + list(self.options))
@staticmethod
- def _strip_quotes(item):
- _QUOTES = '"\''
- for q in _QUOTES:
- if item.startswith(q) and item.endswith(q):
- return item[1:-1]
- return item
-
- @staticmethod
+ def _strip_quotes(item):
+ _QUOTES = '"\''
+ for q in _QUOTES:
+ if item.startswith(q) and item.endswith(q):
+ return item[1:-1]
+ return item
+
+ @staticmethod
def _render(items):
- cmdline = subprocess.list2cmdline(
- CommandSpec._strip_quotes(item.strip()) for item in items)
+ cmdline = subprocess.list2cmdline(
+ CommandSpec._strip_quotes(item.strip()) for item in items)
return '#!' + cmdline + '\n'
-
+
# For pbr compat; will be removed in a future version.
sys_executable = CommandSpec._sys_executable()
@@ -2048,9 +2048,9 @@ class ScriptWriter:
gui apps.
"""
- template = textwrap.dedent(r"""
+ template = textwrap.dedent(r"""
# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
- import re
+ import re
import sys
# for compatibility with easy_install; see #2198
@@ -2079,7 +2079,7 @@ class ScriptWriter:
if __name__ == '__main__':
- sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
""").lstrip()
@@ -2185,11 +2185,11 @@ class WindowsScriptWriter(ScriptWriter):
"For Windows, add a .py extension"
ext = dict(console='.pya', gui='.pyw')[type_]
if ext not in os.environ['PATHEXT'].lower().split(';'):
- msg = (
- "{ext} not listed in PATHEXT; scripts will not be "
- "recognized as executables."
- ).format(**locals())
- warnings.warn(msg, UserWarning)
+ msg = (
+ "{ext} not listed in PATHEXT; scripts will not be "
+ "recognized as executables."
+ ).format(**locals())
+ warnings.warn(msg, UserWarning)
old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
old.remove(ext)
header = cls._adjust_header(type_, header)
@@ -2284,7 +2284,7 @@ def load_launcher_manifest(name):
def rmtree(path, ignore_errors=False, onerror=auto_chmod):
- return shutil.rmtree(path, ignore_errors, onerror)
+ return shutil.rmtree(path, ignore_errors, onerror)
def current_umask():
diff --git a/contrib/python/setuptools/py3/setuptools/command/egg_info.py b/contrib/python/setuptools/py3/setuptools/command/egg_info.py
index f2210292e3..77683cd840 100644
--- a/contrib/python/setuptools/py3/setuptools/command/egg_info.py
+++ b/contrib/python/setuptools/py3/setuptools/command/egg_info.py
@@ -3,7 +3,7 @@
Create a distribution's .egg-info directory and contents"""
from distutils.filelist import FileList as _FileList
-from distutils.errors import DistutilsInternalError
+from distutils.errors import DistutilsInternalError
from distutils.util import convert_path
from distutils import log
import distutils.errors
@@ -15,7 +15,7 @@ import sys
import io
import warnings
import time
-import collections
+import collections
from setuptools import Command
from setuptools.command.sdist import sdist
@@ -26,95 +26,95 @@ from pkg_resources import (
parse_requirements, safe_name, parse_version,
safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
import setuptools.unicode_utils as unicode_utils
-from setuptools.glob import glob
+from setuptools.glob import glob
from setuptools.extern import packaging
from setuptools import SetuptoolsDeprecationWarning
def translate_pattern(glob): # noqa: C901 # is too complex (14) # FIXME
- """
- Translate a file path glob like '*.txt' in to a regular expression.
- This differs from fnmatch.translate which allows wildcards to match
- directory separators. It also knows about '**/' which matches any number of
- directories.
- """
- pat = ''
-
- # This will split on '/' within [character classes]. This is deliberate.
- chunks = glob.split(os.path.sep)
-
- sep = re.escape(os.sep)
- valid_char = '[^%s]' % (sep,)
-
- for c, chunk in enumerate(chunks):
- last_chunk = c == len(chunks) - 1
-
- # Chunks that are a literal ** are globstars. They match anything.
- if chunk == '**':
- if last_chunk:
- # Match anything if this is the last component
- pat += '.*'
- else:
- # Match '(name/)*'
- pat += '(?:%s+%s)*' % (valid_char, sep)
- continue # Break here as the whole path component has been handled
-
- # Find any special characters in the remainder
- i = 0
- chunk_len = len(chunk)
- while i < chunk_len:
- char = chunk[i]
- if char == '*':
- # Match any number of name characters
- pat += valid_char + '*'
- elif char == '?':
- # Match a name character
- pat += valid_char
- elif char == '[':
- # Character class
- inner_i = i + 1
- # Skip initial !/] chars
- if inner_i < chunk_len and chunk[inner_i] == '!':
- inner_i = inner_i + 1
- if inner_i < chunk_len and chunk[inner_i] == ']':
- inner_i = inner_i + 1
-
- # Loop till the closing ] is found
- while inner_i < chunk_len and chunk[inner_i] != ']':
- inner_i = inner_i + 1
-
- if inner_i >= chunk_len:
- # Got to the end of the string without finding a closing ]
- # Do not treat this as a matching group, but as a literal [
- pat += re.escape(char)
- else:
- # Grab the insides of the [brackets]
- inner = chunk[i + 1:inner_i]
- char_class = ''
-
- # Class negation
- if inner[0] == '!':
- char_class = '^'
- inner = inner[1:]
-
- char_class += re.escape(inner)
- pat += '[%s]' % (char_class,)
-
- # Skip to the end ]
- i = inner_i
- else:
- pat += re.escape(char)
- i += 1
-
- # Join each chunk with the dir separator
- if not last_chunk:
- pat += sep
-
+ """
+ Translate a file path glob like '*.txt' in to a regular expression.
+ This differs from fnmatch.translate which allows wildcards to match
+ directory separators. It also knows about '**/' which matches any number of
+ directories.
+ """
+ pat = ''
+
+ # This will split on '/' within [character classes]. This is deliberate.
+ chunks = glob.split(os.path.sep)
+
+ sep = re.escape(os.sep)
+ valid_char = '[^%s]' % (sep,)
+
+ for c, chunk in enumerate(chunks):
+ last_chunk = c == len(chunks) - 1
+
+ # Chunks that are a literal ** are globstars. They match anything.
+ if chunk == '**':
+ if last_chunk:
+ # Match anything if this is the last component
+ pat += '.*'
+ else:
+ # Match '(name/)*'
+ pat += '(?:%s+%s)*' % (valid_char, sep)
+ continue # Break here as the whole path component has been handled
+
+ # Find any special characters in the remainder
+ i = 0
+ chunk_len = len(chunk)
+ while i < chunk_len:
+ char = chunk[i]
+ if char == '*':
+ # Match any number of name characters
+ pat += valid_char + '*'
+ elif char == '?':
+ # Match a name character
+ pat += valid_char
+ elif char == '[':
+ # Character class
+ inner_i = i + 1
+ # Skip initial !/] chars
+ if inner_i < chunk_len and chunk[inner_i] == '!':
+ inner_i = inner_i + 1
+ if inner_i < chunk_len and chunk[inner_i] == ']':
+ inner_i = inner_i + 1
+
+ # Loop till the closing ] is found
+ while inner_i < chunk_len and chunk[inner_i] != ']':
+ inner_i = inner_i + 1
+
+ if inner_i >= chunk_len:
+ # Got to the end of the string without finding a closing ]
+ # Do not treat this as a matching group, but as a literal [
+ pat += re.escape(char)
+ else:
+ # Grab the insides of the [brackets]
+ inner = chunk[i + 1:inner_i]
+ char_class = ''
+
+ # Class negation
+ if inner[0] == '!':
+ char_class = '^'
+ inner = inner[1:]
+
+ char_class += re.escape(inner)
+ pat += '[%s]' % (char_class,)
+
+ # Skip to the end ]
+ i = inner_i
+ else:
+ pat += re.escape(char)
+ i += 1
+
+ # Join each chunk with the dir separator
+ if not last_chunk:
+ pat += sep
+
pat += r'\Z'
return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
-
-
+
+
class InfoCommon:
tag_build = None
tag_date = None
@@ -157,10 +157,10 @@ class egg_info(InfoCommon, Command):
('no-date', 'D', "Don't include date stamp [default]"),
]
- boolean_options = ['tag-date']
- negative_opt = {
- 'no-date': 'tag-date',
- }
+ boolean_options = ['tag-date']
+ negative_opt = {
+ 'no-date': 'tag-date',
+ }
def initialize_options(self):
self.egg_base = None
@@ -169,30 +169,30 @@ class egg_info(InfoCommon, Command):
self.egg_version = None
self.broken_egg_info = False
- ####################################
- # allow the 'tag_svn_revision' to be detected and
- # set, supporting sdists built on older Setuptools.
- @property
- def tag_svn_revision(self):
- pass
-
- @tag_svn_revision.setter
- def tag_svn_revision(self, value):
- pass
- ####################################
-
+ ####################################
+ # allow the 'tag_svn_revision' to be detected and
+ # set, supporting sdists built on older Setuptools.
+ @property
+ def tag_svn_revision(self):
+ pass
+
+ @tag_svn_revision.setter
+ def tag_svn_revision(self, value):
+ pass
+ ####################################
+
def save_version_info(self, filename):
- """
- Materialize the value of date into the
- build tag. Install build keys in a deterministic order
- to avoid arbitrary reordering on subsequent builds.
- """
+ """
+ Materialize the value of date into the
+ build tag. Install build keys in a deterministic order
+ to avoid arbitrary reordering on subsequent builds.
+ """
egg_info = collections.OrderedDict()
- # follow the order these keys would have been added
- # when PYTHONHASHSEED=0
- egg_info['tag_build'] = self.tags()
- egg_info['tag_date'] = 0
- edit_config(filename, dict(egg_info=egg_info))
+ # follow the order these keys would have been added
+ # when PYTHONHASHSEED=0
+ egg_info['tag_build'] = self.tags()
+ egg_info['tag_date'] = 0
+ edit_config(filename, dict(egg_info=egg_info))
def finalize_options(self):
# Note: we need to capture the current value returned
@@ -323,16 +323,16 @@ class egg_info(InfoCommon, Command):
class FileList(_FileList):
- # Implementations of the various MANIFEST.in commands
-
- def process_template_line(self, line):
- # Parse the line: split it up, make sure the right number of words
- # is there, and return the relevant words. 'action' is always
- # defined: it's the first word of the line. Which of the other
- # three are defined depends on the action; it'll be either
- # patterns, (dir and patterns), or (dir_pattern).
- (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
-
+ # Implementations of the various MANIFEST.in commands
+
+ def process_template_line(self, line):
+ # Parse the line: split it up, make sure the right number of words
+ # is there, and return the relevant words. 'action' is always
+ # defined: it's the first word of the line. Which of the other
+ # three are defined depends on the action; it'll be either
+ # patterns, (dir and patterns), or (dir_pattern).
+ (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
+
action_map = {
'include': self.include,
'exclude': self.exclude,
@@ -381,16 +381,16 @@ class FileList(_FileList):
format(action=action),
)
- # OK, now we know that the action is valid and we have the
- # right number of words on the line for that action -- so we
- # can proceed with minimal error-checking.
-
+ # OK, now we know that the action is valid and we have the
+ # right number of words on the line for that action -- so we
+ # can proceed with minimal error-checking.
+
action_is_recursive = action.startswith('recursive-')
if action in {'graft', 'prune'}:
patterns = [dir_pattern]
extra_log_args = (dir, ) if action_is_recursive else ()
log_tmpl = log_map[action]
-
+
self.debug_print(
' '.join(
[action] +
@@ -401,82 +401,82 @@ class FileList(_FileList):
for pattern in patterns:
if not process_action(pattern):
log.warn(log_tmpl, pattern, *extra_log_args)
-
- def _remove_files(self, predicate):
- """
- Remove all files from the file list that match the predicate.
- Return True if any matching files were removed
- """
- found = False
- for i in range(len(self.files) - 1, -1, -1):
- if predicate(self.files[i]):
- self.debug_print(" removing " + self.files[i])
- del self.files[i]
- found = True
- return found
-
- def include(self, pattern):
- """Include files that match 'pattern'."""
- found = [f for f in glob(pattern) if not os.path.isdir(f)]
- self.extend(found)
- return bool(found)
-
- def exclude(self, pattern):
- """Exclude files that match 'pattern'."""
- match = translate_pattern(pattern)
- return self._remove_files(match.match)
-
- def recursive_include(self, dir, pattern):
- """
- Include all files anywhere in 'dir/' that match the pattern.
- """
- full_pattern = os.path.join(dir, '**', pattern)
- found = [f for f in glob(full_pattern, recursive=True)
- if not os.path.isdir(f)]
- self.extend(found)
- return bool(found)
-
- def recursive_exclude(self, dir, pattern):
- """
- Exclude any file anywhere in 'dir/' that match the pattern.
- """
- match = translate_pattern(os.path.join(dir, '**', pattern))
- return self._remove_files(match.match)
-
- def graft(self, dir):
- """Include all files from 'dir/'."""
- found = [
- item
- for match_dir in glob(dir)
- for item in distutils.filelist.findall(match_dir)
- ]
- self.extend(found)
- return bool(found)
-
- def prune(self, dir):
- """Filter out files from 'dir/'."""
- match = translate_pattern(os.path.join(dir, '**'))
- return self._remove_files(match.match)
-
- def global_include(self, pattern):
- """
- Include all files anywhere in the current directory that match the
- pattern. This is very inefficient on large file trees.
- """
- if self.allfiles is None:
- self.findall()
- match = translate_pattern(os.path.join('**', pattern))
- found = [f for f in self.allfiles if match.match(f)]
- self.extend(found)
- return bool(found)
-
- def global_exclude(self, pattern):
- """
- Exclude all files anywhere that match the pattern.
- """
- match = translate_pattern(os.path.join('**', pattern))
- return self._remove_files(match.match)
-
+
+ def _remove_files(self, predicate):
+ """
+ Remove all files from the file list that match the predicate.
+ Return True if any matching files were removed
+ """
+ found = False
+ for i in range(len(self.files) - 1, -1, -1):
+ if predicate(self.files[i]):
+ self.debug_print(" removing " + self.files[i])
+ del self.files[i]
+ found = True
+ return found
+
+ def include(self, pattern):
+ """Include files that match 'pattern'."""
+ found = [f for f in glob(pattern) if not os.path.isdir(f)]
+ self.extend(found)
+ return bool(found)
+
+ def exclude(self, pattern):
+ """Exclude files that match 'pattern'."""
+ match = translate_pattern(pattern)
+ return self._remove_files(match.match)
+
+ def recursive_include(self, dir, pattern):
+ """
+ Include all files anywhere in 'dir/' that match the pattern.
+ """
+ full_pattern = os.path.join(dir, '**', pattern)
+ found = [f for f in glob(full_pattern, recursive=True)
+ if not os.path.isdir(f)]
+ self.extend(found)
+ return bool(found)
+
+ def recursive_exclude(self, dir, pattern):
+ """
+ Exclude any file anywhere in 'dir/' that match the pattern.
+ """
+ match = translate_pattern(os.path.join(dir, '**', pattern))
+ return self._remove_files(match.match)
+
+ def graft(self, dir):
+ """Include all files from 'dir/'."""
+ found = [
+ item
+ for match_dir in glob(dir)
+ for item in distutils.filelist.findall(match_dir)
+ ]
+ self.extend(found)
+ return bool(found)
+
+ def prune(self, dir):
+ """Filter out files from 'dir/'."""
+ match = translate_pattern(os.path.join(dir, '**'))
+ return self._remove_files(match.match)
+
+ def global_include(self, pattern):
+ """
+ Include all files anywhere in the current directory that match the
+ pattern. This is very inefficient on large file trees.
+ """
+ if self.allfiles is None:
+ self.findall()
+ match = translate_pattern(os.path.join('**', pattern))
+ found = [f for f in self.allfiles if match.match(f)]
+ self.extend(found)
+ return bool(found)
+
+ def global_exclude(self, pattern):
+ """
+ Exclude all files anywhere that match the pattern.
+ """
+ match = translate_pattern(os.path.join('**', pattern))
+ return self._remove_files(match.match)
+
def append(self, item):
if item.endswith('\r'): # Fix older sdists built on Windows
item = item[:-1]
@@ -563,17 +563,17 @@ class manifest_maker(sdist):
msg = "writing manifest file '%s'" % self.manifest
self.execute(write_file, (self.manifest, files), msg)
- def warn(self, msg):
- if not self._should_suppress_warning(msg):
+ def warn(self, msg):
+ if not self._should_suppress_warning(msg):
sdist.warn(self, msg)
- @staticmethod
- def _should_suppress_warning(msg):
- """
- suppress missing-file warnings from sdist
- """
- return re.match(r"standard file .*not found", msg)
-
+ @staticmethod
+ def _should_suppress_warning(msg):
+ """
+ suppress missing-file warnings from sdist
+ """
+ return re.match(r"standard file .*not found", msg)
+
def add_defaults(self):
sdist.add_defaults(self)
self.filelist.append(self.template)
@@ -590,7 +590,7 @@ class manifest_maker(sdist):
self.filelist.append("setup.py")
ei_cmd = self.get_finalized_command('egg_info')
- self.filelist.graft(ei_cmd.egg_info)
+ self.filelist.graft(ei_cmd.egg_info)
def add_license_files(self):
license_files = self.distribution.metadata.license_files or []
@@ -602,8 +602,8 @@ class manifest_maker(sdist):
def prune_file_list(self):
build = self.get_finalized_command('build')
base_dir = self.distribution.get_fullname()
- self.filelist.prune(build.build_base)
- self.filelist.prune(base_dir)
+ self.filelist.prune(build.build_base)
+ self.filelist.prune(base_dir)
sep = re.escape(os.sep)
self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
is_regex=1)
diff --git a/contrib/python/setuptools/py3/setuptools/command/install.py b/contrib/python/setuptools/py3/setuptools/command/install.py
index 35e54d2043..cf77ae5625 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install.py
@@ -8,7 +8,7 @@ import distutils.command.install as orig
import setuptools
# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for
-# now. See https://github.com/pypa/setuptools/issues/199/
+# now. See https://github.com/pypa/setuptools/issues/199/
_install = orig.install
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py b/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
index edc4718b68..b5b4c6fc60 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_egg_info.py
@@ -2,12 +2,12 @@ from distutils import log, dir_util
import os
from setuptools import Command
-from setuptools import namespaces
+from setuptools import namespaces
from setuptools.archive_util import unpack_archive
import pkg_resources
-class install_egg_info(namespaces.Installer, Command):
+class install_egg_info(namespaces.Installer, Command):
"""Install an .egg-info directory for the package"""
description = "Install an .egg-info directory for the package"
@@ -28,7 +28,7 @@ class install_egg_info(namespaces.Installer, Command):
).egg_name() + '.egg-info'
self.source = ei_cmd.egg_info
self.target = os.path.join(self.install_dir, basename)
- self.outputs = []
+ self.outputs = []
def run(self):
self.run_command('egg_info')
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_lib.py b/contrib/python/setuptools/py3/setuptools/command/install_lib.py
index 2e9d8757a5..95df1797a2 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_lib.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_lib.py
@@ -3,7 +3,7 @@ import sys
from itertools import product, starmap
import distutils.command.install_lib as orig
-
+
class install_lib(orig.install_lib):
"""Don't add compiled flags to filenames of non-Python files"""
diff --git a/contrib/python/setuptools/py3/setuptools/command/install_scripts.py b/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
index 9cd8eb0627..ec0cbd5a57 100644
--- a/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
+++ b/contrib/python/setuptools/py3/setuptools/command/install_scripts.py
@@ -2,7 +2,7 @@ from distutils import log
import distutils.command.install_scripts as orig
from distutils.errors import DistutilsModuleError
import os
-import sys
+import sys
from pkg_resources import Distribution, PathMetadata, ensure_directory
@@ -42,10 +42,10 @@ class install_scripts(orig.install_scripts):
if is_wininst:
exec_param = "python.exe"
writer = ei.WindowsScriptWriter
- if exec_param == sys.executable:
- # In case the path to the Python executable contains a space, wrap
- # it so it's not split up.
- exec_param = [exec_param]
+ if exec_param == sys.executable:
+ # In case the path to the Python executable contains a space, wrap
+ # it so it's not split up.
+ exec_param = [exec_param]
# resolve the writer to the environment
writer = writer.best()
cmd = writer.command_spec_class.best().from_param(exec_param)
diff --git a/contrib/python/setuptools/py3/setuptools/command/py36compat.py b/contrib/python/setuptools/py3/setuptools/command/py36compat.py
index 343547a4d3..d677698cac 100644
--- a/contrib/python/setuptools/py3/setuptools/command/py36compat.py
+++ b/contrib/python/setuptools/py3/setuptools/command/py36compat.py
@@ -1,134 +1,134 @@
-import os
-from glob import glob
-from distutils.util import convert_path
-from distutils.command import sdist
-
-
-class sdist_add_defaults:
- """
- Mix-in providing forward-compatibility for functionality as found in
- distutils on Python 3.7.
-
- Do not edit the code in this class except to update functionality
- as implemented in distutils. Instead, override in the subclass.
- """
-
- def add_defaults(self):
- """Add all the default files to self.filelist:
- - README or README.txt
- - setup.py
- - test/test*.py
- - all pure Python modules mentioned in setup script
- - all files pointed by package_data (build_py)
- - all files defined in data_files.
- - all files defined as scripts.
- - all C sources listed as part of extensions or C libraries
- in the setup script (doesn't catch C headers!)
- Warns if (README or README.txt) or setup.py are missing; everything
- else is optional.
- """
- self._add_defaults_standards()
- self._add_defaults_optional()
- self._add_defaults_python()
- self._add_defaults_data_files()
- self._add_defaults_ext()
- self._add_defaults_c_libs()
- self._add_defaults_scripts()
-
- @staticmethod
- def _cs_path_exists(fspath):
- """
- Case-sensitive path existence check
-
- >>> sdist_add_defaults._cs_path_exists(__file__)
- True
- >>> sdist_add_defaults._cs_path_exists(__file__.upper())
- False
- """
- if not os.path.exists(fspath):
- return False
- # make absolute so we always have a directory
- abspath = os.path.abspath(fspath)
- directory, filename = os.path.split(abspath)
- return filename in os.listdir(directory)
-
- def _add_defaults_standards(self):
- standards = [self.READMES, self.distribution.script_name]
- for fn in standards:
- if isinstance(fn, tuple):
- alts = fn
- got_it = False
- for fn in alts:
- if self._cs_path_exists(fn):
- got_it = True
- self.filelist.append(fn)
- break
-
- if not got_it:
- self.warn("standard file not found: should have one of " +
- ', '.join(alts))
- else:
- if self._cs_path_exists(fn):
- self.filelist.append(fn)
- else:
- self.warn("standard file '%s' not found" % fn)
-
- def _add_defaults_optional(self):
- optional = ['test/test*.py', 'setup.cfg']
- for pattern in optional:
- files = filter(os.path.isfile, glob(pattern))
- self.filelist.extend(files)
-
- def _add_defaults_python(self):
- # build_py is used to get:
- # - python modules
- # - files defined in package_data
- build_py = self.get_finalized_command('build_py')
-
- # getting python files
- if self.distribution.has_pure_modules():
- self.filelist.extend(build_py.get_source_files())
-
- # getting package_data files
- # (computed in build_py.data_files by build_py.finalize_options)
- for pkg, src_dir, build_dir, filenames in build_py.data_files:
- for filename in filenames:
- self.filelist.append(os.path.join(src_dir, filename))
-
- def _add_defaults_data_files(self):
- # getting distribution.data_files
- if self.distribution.has_data_files():
- for item in self.distribution.data_files:
- if isinstance(item, str):
- # plain file
- item = convert_path(item)
- if os.path.isfile(item):
- self.filelist.append(item)
- else:
- # a (dirname, filenames) tuple
- dirname, filenames = item
- for f in filenames:
- f = convert_path(f)
- if os.path.isfile(f):
- self.filelist.append(f)
-
- def _add_defaults_ext(self):
- if self.distribution.has_ext_modules():
- build_ext = self.get_finalized_command('build_ext')
- self.filelist.extend(build_ext.get_source_files())
-
- def _add_defaults_c_libs(self):
- if self.distribution.has_c_libraries():
- build_clib = self.get_finalized_command('build_clib')
- self.filelist.extend(build_clib.get_source_files())
-
- def _add_defaults_scripts(self):
- if self.distribution.has_scripts():
- build_scripts = self.get_finalized_command('build_scripts')
- self.filelist.extend(build_scripts.get_source_files())
-
-
-if hasattr(sdist.sdist, '_add_defaults_standards'):
- # disable the functionality already available upstream
+import os
+from glob import glob
+from distutils.util import convert_path
+from distutils.command import sdist
+
+
+class sdist_add_defaults:
+ """
+ Mix-in providing forward-compatibility for functionality as found in
+ distutils on Python 3.7.
+
+ Do not edit the code in this class except to update functionality
+ as implemented in distutils. Instead, override in the subclass.
+ """
+
+ def add_defaults(self):
+ """Add all the default files to self.filelist:
+ - README or README.txt
+ - setup.py
+ - test/test*.py
+ - all pure Python modules mentioned in setup script
+ - all files pointed by package_data (build_py)
+ - all files defined in data_files.
+ - all files defined as scripts.
+ - all C sources listed as part of extensions or C libraries
+ in the setup script (doesn't catch C headers!)
+ Warns if (README or README.txt) or setup.py are missing; everything
+ else is optional.
+ """
+ self._add_defaults_standards()
+ self._add_defaults_optional()
+ self._add_defaults_python()
+ self._add_defaults_data_files()
+ self._add_defaults_ext()
+ self._add_defaults_c_libs()
+ self._add_defaults_scripts()
+
+ @staticmethod
+ def _cs_path_exists(fspath):
+ """
+ Case-sensitive path existence check
+
+ >>> sdist_add_defaults._cs_path_exists(__file__)
+ True
+ >>> sdist_add_defaults._cs_path_exists(__file__.upper())
+ False
+ """
+ if not os.path.exists(fspath):
+ return False
+ # make absolute so we always have a directory
+ abspath = os.path.abspath(fspath)
+ directory, filename = os.path.split(abspath)
+ return filename in os.listdir(directory)
+
+ def _add_defaults_standards(self):
+ standards = [self.READMES, self.distribution.script_name]
+ for fn in standards:
+ if isinstance(fn, tuple):
+ alts = fn
+ got_it = False
+ for fn in alts:
+ if self._cs_path_exists(fn):
+ got_it = True
+ self.filelist.append(fn)
+ break
+
+ if not got_it:
+ self.warn("standard file not found: should have one of " +
+ ', '.join(alts))
+ else:
+ if self._cs_path_exists(fn):
+ self.filelist.append(fn)
+ else:
+ self.warn("standard file '%s' not found" % fn)
+
+ def _add_defaults_optional(self):
+ optional = ['test/test*.py', 'setup.cfg']
+ for pattern in optional:
+ files = filter(os.path.isfile, glob(pattern))
+ self.filelist.extend(files)
+
+ def _add_defaults_python(self):
+ # build_py is used to get:
+ # - python modules
+ # - files defined in package_data
+ build_py = self.get_finalized_command('build_py')
+
+ # getting python files
+ if self.distribution.has_pure_modules():
+ self.filelist.extend(build_py.get_source_files())
+
+ # getting package_data files
+ # (computed in build_py.data_files by build_py.finalize_options)
+ for pkg, src_dir, build_dir, filenames in build_py.data_files:
+ for filename in filenames:
+ self.filelist.append(os.path.join(src_dir, filename))
+
+ def _add_defaults_data_files(self):
+ # getting distribution.data_files
+ if self.distribution.has_data_files():
+ for item in self.distribution.data_files:
+ if isinstance(item, str):
+ # plain file
+ item = convert_path(item)
+ if os.path.isfile(item):
+ self.filelist.append(item)
+ else:
+ # a (dirname, filenames) tuple
+ dirname, filenames = item
+ for f in filenames:
+ f = convert_path(f)
+ if os.path.isfile(f):
+ self.filelist.append(f)
+
+ def _add_defaults_ext(self):
+ if self.distribution.has_ext_modules():
+ build_ext = self.get_finalized_command('build_ext')
+ self.filelist.extend(build_ext.get_source_files())
+
+ def _add_defaults_c_libs(self):
+ if self.distribution.has_c_libraries():
+ build_clib = self.get_finalized_command('build_clib')
+ self.filelist.extend(build_clib.get_source_files())
+
+ def _add_defaults_scripts(self):
+ if self.distribution.has_scripts():
+ build_scripts = self.get_finalized_command('build_scripts')
+ self.filelist.extend(build_scripts.get_source_files())
+
+
+if hasattr(sdist.sdist, '_add_defaults_standards'):
+ # disable the functionality already available upstream
class sdist_add_defaults: # noqa
- pass
+ pass
diff --git a/contrib/python/setuptools/py3/setuptools/command/rotate.py b/contrib/python/setuptools/py3/setuptools/command/rotate.py
index 74795ba922..ec2046cfac 100644
--- a/contrib/python/setuptools/py3/setuptools/command/rotate.py
+++ b/contrib/python/setuptools/py3/setuptools/command/rotate.py
@@ -2,7 +2,7 @@ from distutils.util import convert_path
from distutils import log
from distutils.errors import DistutilsOptionError
import os
-import shutil
+import shutil
from setuptools import Command
@@ -58,7 +58,7 @@ class rotate(Command):
for (t, f) in files:
log.info("Deleting %s", f)
if not self.dry_run:
- if os.path.isdir(f):
- shutil.rmtree(f)
- else:
- os.unlink(f)
+ if os.path.isdir(f):
+ shutil.rmtree(f)
+ else:
+ os.unlink(f)
diff --git a/contrib/python/setuptools/py3/setuptools/command/sdist.py b/contrib/python/setuptools/py3/setuptools/command/sdist.py
index 0285b690fc..7d79fbf873 100644
--- a/contrib/python/setuptools/py3/setuptools/command/sdist.py
+++ b/contrib/python/setuptools/py3/setuptools/command/sdist.py
@@ -3,15 +3,15 @@ import distutils.command.sdist as orig
import os
import sys
import io
-import contextlib
+import contextlib
-from .py36compat import sdist_add_defaults
+from .py36compat import sdist_add_defaults
import pkg_resources
_default_revctrl = list
-
+
def walk_revctrl(dirname=''):
"""Find all files under revision control"""
for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
@@ -19,7 +19,7 @@ def walk_revctrl(dirname=''):
yield item
-class sdist(sdist_add_defaults, orig.sdist):
+class sdist(sdist_add_defaults, orig.sdist):
"""Smart sdist that finds anything supported by revision control"""
user_options = [
@@ -41,7 +41,7 @@ class sdist(sdist_add_defaults, orig.sdist):
README_EXTENSIONS = ['', '.rst', '.txt', '.md']
READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
-
+
def run(self):
self.run_command('egg_info')
ei_cmd = self.get_finalized_command('egg_info')
@@ -61,52 +61,52 @@ class sdist(sdist_add_defaults, orig.sdist):
if data not in dist_files:
dist_files.append(data)
- def initialize_options(self):
- orig.sdist.initialize_options(self)
-
- self._default_to_gztar()
-
- def _default_to_gztar(self):
- # only needed on Python prior to 3.6.
- if sys.version_info >= (3, 6, 0, 'beta', 1):
- return
- self.formats = ['gztar']
-
- def make_distribution(self):
- """
- Workaround for #516
- """
- with self._remove_os_link():
- orig.sdist.make_distribution(self)
-
- @staticmethod
- @contextlib.contextmanager
- def _remove_os_link():
- """
- In a context, remove and restore os.link if it exists
- """
-
- class NoValue:
- pass
-
- orig_val = getattr(os, 'link', NoValue)
- try:
- del os.link
- except Exception:
- pass
- try:
- yield
- finally:
- if orig_val is not NoValue:
- setattr(os, 'link', orig_val)
-
+ def initialize_options(self):
+ orig.sdist.initialize_options(self)
+
+ self._default_to_gztar()
+
+ def _default_to_gztar(self):
+ # only needed on Python prior to 3.6.
+ if sys.version_info >= (3, 6, 0, 'beta', 1):
+ return
+ self.formats = ['gztar']
+
+ def make_distribution(self):
+ """
+ Workaround for #516
+ """
+ with self._remove_os_link():
+ orig.sdist.make_distribution(self)
+
+ @staticmethod
+ @contextlib.contextmanager
+ def _remove_os_link():
+ """
+ In a context, remove and restore os.link if it exists
+ """
+
+ class NoValue:
+ pass
+
+ orig_val = getattr(os, 'link', NoValue)
+ try:
+ del os.link
+ except Exception:
+ pass
+ try:
+ yield
+ finally:
+ if orig_val is not NoValue:
+ setattr(os, 'link', orig_val)
+
def _add_defaults_optional(self):
super()._add_defaults_optional()
if os.path.isfile('pyproject.toml'):
self.filelist.append('pyproject.toml')
- def _add_defaults_python(self):
- """getting python files"""
+ def _add_defaults_python(self):
+ """getting python files"""
if self.distribution.has_pure_modules():
build_py = self.get_finalized_command('build_py')
self.filelist.extend(build_py.get_source_files())
@@ -135,20 +135,20 @@ class sdist(sdist_add_defaults, orig.sdist):
for name in filenames
)
- def _add_defaults_data_files(self):
- try:
+ def _add_defaults_data_files(self):
+ try:
super()._add_defaults_data_files()
- except TypeError:
- log.warn("data_files contains unexpected objects")
+ except TypeError:
+ log.warn("data_files contains unexpected objects")
def check_readme(self):
- for f in self.READMES:
+ for f in self.READMES:
if os.path.exists(f):
return
else:
self.warn(
"standard file not found: should have one of " +
- ', '.join(self.READMES)
+ ', '.join(self.READMES)
)
def make_release_tree(self, base_dir, files):
@@ -180,7 +180,7 @@ class sdist(sdist_add_defaults, orig.sdist):
distribution.
"""
log.info("reading manifest file '%s'", self.manifest)
- manifest = open(self.manifest, 'rb')
+ manifest = open(self.manifest, 'rb')
for line in manifest:
# The manifest must contain UTF-8. See #303.
try:
diff --git a/contrib/python/setuptools/py3/setuptools/command/test.py b/contrib/python/setuptools/py3/setuptools/command/test.py
index 4a389e4d07..96ea68c089 100644
--- a/contrib/python/setuptools/py3/setuptools/command/test.py
+++ b/contrib/python/setuptools/py3/setuptools/command/test.py
@@ -1,11 +1,11 @@
-import os
-import operator
-import sys
-import contextlib
-import itertools
+import os
+import operator
+import sys
+import contextlib
+import itertools
import unittest
-from distutils.errors import DistutilsError, DistutilsOptionError
-from distutils import log
+from distutils.errors import DistutilsError, DistutilsOptionError
+from distutils import log
from unittest import TestLoader
from pkg_resources import (
@@ -125,14 +125,14 @@ class test(Command):
yield self.test_suite
def with_project_on_sys_path(self, func):
- """
- Backward compatibility for project_on_sys_path context.
- """
- with self.project_on_sys_path():
- func()
-
- @contextlib.contextmanager
- def project_on_sys_path(self, include_dists=[]):
+ """
+ Backward compatibility for project_on_sys_path context.
+ """
+ with self.project_on_sys_path():
+ func()
+
+ @contextlib.contextmanager
+ def project_on_sys_path(self, include_dists=[]):
self.run_command('egg_info')
# Build extensions in-place
@@ -145,60 +145,60 @@ class test(Command):
old_modules = sys.modules.copy()
try:
- project_path = normalize_path(ei_cmd.egg_base)
- sys.path.insert(0, project_path)
+ project_path = normalize_path(ei_cmd.egg_base)
+ sys.path.insert(0, project_path)
working_set.__init__()
add_activation_listener(lambda dist: dist.activate())
require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))
- with self.paths_on_pythonpath([project_path]):
- yield
+ with self.paths_on_pythonpath([project_path]):
+ yield
finally:
sys.path[:] = old_path
sys.modules.clear()
sys.modules.update(old_modules)
working_set.__init__()
- @staticmethod
- @contextlib.contextmanager
- def paths_on_pythonpath(paths):
- """
- Add the indicated paths to the head of the PYTHONPATH environment
- variable so that subprocesses will also see the packages at
- these paths.
-
- Do this in a context that restores the value on exit.
- """
- nothing = object()
- orig_pythonpath = os.environ.get('PYTHONPATH', nothing)
- current_pythonpath = os.environ.get('PYTHONPATH', '')
- try:
+ @staticmethod
+ @contextlib.contextmanager
+ def paths_on_pythonpath(paths):
+ """
+ Add the indicated paths to the head of the PYTHONPATH environment
+ variable so that subprocesses will also see the packages at
+ these paths.
+
+ Do this in a context that restores the value on exit.
+ """
+ nothing = object()
+ orig_pythonpath = os.environ.get('PYTHONPATH', nothing)
+ current_pythonpath = os.environ.get('PYTHONPATH', '')
+ try:
prefix = os.pathsep.join(unique_everseen(paths))
- to_join = filter(None, [prefix, current_pythonpath])
- new_path = os.pathsep.join(to_join)
- if new_path:
- os.environ['PYTHONPATH'] = new_path
- yield
- finally:
- if orig_pythonpath is nothing:
- os.environ.pop('PYTHONPATH', None)
- else:
- os.environ['PYTHONPATH'] = orig_pythonpath
-
- @staticmethod
- def install_dists(dist):
- """
- Install the requirements indicated by self.distribution and
- return an iterable of the dists that were built.
- """
+ to_join = filter(None, [prefix, current_pythonpath])
+ new_path = os.pathsep.join(to_join)
+ if new_path:
+ os.environ['PYTHONPATH'] = new_path
+ yield
+ finally:
+ if orig_pythonpath is nothing:
+ os.environ.pop('PYTHONPATH', None)
+ else:
+ os.environ['PYTHONPATH'] = orig_pythonpath
+
+ @staticmethod
+ def install_dists(dist):
+ """
+ Install the requirements indicated by self.distribution and
+ return an iterable of the dists that were built.
+ """
ir_d = dist.fetch_build_eggs(dist.install_requires)
- tr_d = dist.fetch_build_eggs(dist.tests_require or [])
+ tr_d = dist.fetch_build_eggs(dist.tests_require or [])
er_d = dist.fetch_build_eggs(
v
for k, v in dist.extras_require.items()
if k.startswith(':') and evaluate_marker(k[1:])
)
return itertools.chain(ir_d, tr_d, er_d)
-
+
def run(self):
self.announce(
"WARNING: Testing via this command is deprecated and will be "
@@ -208,20 +208,20 @@ class test(Command):
log.WARN,
)
- installed_dists = self.install_dists(self.distribution)
+ installed_dists = self.install_dists(self.distribution)
cmd = ' '.join(self._argv)
if self.dry_run:
self.announce('skipping "%s" (dry run)' % cmd)
- return
-
- self.announce('running "%s"' % cmd)
-
- paths = map(operator.attrgetter('location'), installed_dists)
- with self.paths_on_pythonpath(paths):
- with self.project_on_sys_path():
- self.run_tests()
-
+ return
+
+ self.announce('running "%s"' % cmd)
+
+ paths = map(operator.attrgetter('location'), installed_dists)
+ with self.paths_on_pythonpath(paths):
+ with self.project_on_sys_path():
+ self.run_tests()
+
def run_tests(self):
test = unittest.main(
None,
@@ -231,10 +231,10 @@ class test(Command):
testRunner=self._resolve_as_ep(self.test_runner),
exit=False,
)
- if not test.result.wasSuccessful():
- msg = 'Test failed: %s' % test.result
- self.announce(msg, log.ERROR)
- raise DistutilsError(msg)
+ if not test.result.wasSuccessful():
+ msg = 'Test failed: %s' % test.result
+ self.announce(msg, log.ERROR)
+ raise DistutilsError(msg)
@property
def _argv(self):
diff --git a/contrib/python/setuptools/py3/setuptools/command/upload.py b/contrib/python/setuptools/py3/setuptools/command/upload.py
index ec7f81e227..11baab4990 100644
--- a/contrib/python/setuptools/py3/setuptools/command/upload.py
+++ b/contrib/python/setuptools/py3/setuptools/command/upload.py
@@ -1,8 +1,8 @@
from distutils import log
-from distutils.command import upload as orig
-
+from distutils.command import upload as orig
+
from setuptools.errors import RemovedCommandError
-
+
class upload(orig.upload):
"""Formerly used to upload packages to PyPI."""
@@ -11,7 +11,7 @@ class upload(orig.upload):
msg = (
"The upload command has been removed, use twine to upload "
+ "instead (https://pypi.org/p/twine)"
- )
-
+ )
+
self.announce("ERROR: " + msg, log.ERROR)
raise RemovedCommandError(msg)
diff --git a/contrib/python/setuptools/py3/setuptools/command/upload_docs.py b/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
index 845bff4421..09bf8b82f3 100644
--- a/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
+++ b/contrib/python/setuptools/py3/setuptools/command/upload_docs.py
@@ -13,23 +13,23 @@ import socket
import zipfile
import tempfile
import shutil
-import itertools
-import functools
+import itertools
+import functools
import http.client
import urllib.parse
from pkg_resources import iter_entry_points
-from .upload import upload
+from .upload import upload
-def _encode(s):
+def _encode(s):
return s.encode('utf-8', 'surrogateescape')
-class upload_docs(upload):
- # override the default repository as upload_docs isn't
- # supported by Warehouse (and won't be).
- DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
+class upload_docs(upload):
+ # override the default repository as upload_docs isn't
+ # supported by Warehouse (and won't be).
+ DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'
description = 'Upload documentation to sites other than PyPi such as devpi'
@@ -76,8 +76,8 @@ class upload_docs(upload):
self.mkpath(self.target_dir) # just in case
for root, dirs, files in os.walk(self.target_dir):
if root == self.target_dir and not files:
- tmpl = "no files found in upload directory '%s'"
- raise DistutilsOptionError(tmpl % self.target_dir)
+ tmpl = "no files found in upload directory '%s'"
+ raise DistutilsOptionError(tmpl % self.target_dir)
for name in files:
full = os.path.join(root, name)
relative = root[len(self.target_dir):].lstrip(os.path.sep)
@@ -100,48 +100,48 @@ class upload_docs(upload):
finally:
shutil.rmtree(tmp_dir)
- @staticmethod
- def _build_part(item, sep_boundary):
- key, values = item
- title = '\nContent-Disposition: form-data; name="%s"' % key
- # handle multiple entries for the same name
- if not isinstance(values, list):
- values = [values]
- for value in values:
- if isinstance(value, tuple):
- title += '; filename="%s"' % value[0]
- value = value[1]
- else:
- value = _encode(value)
- yield sep_boundary
- yield _encode(title)
- yield b"\n\n"
- yield value
- if value and value[-1:] == b'\r':
- yield b'\n' # write an extra newline (lurve Macs)
-
- @classmethod
- def _build_multipart(cls, data):
- """
- Build up the MIME payload for the POST data
- """
+ @staticmethod
+ def _build_part(item, sep_boundary):
+ key, values = item
+ title = '\nContent-Disposition: form-data; name="%s"' % key
+ # handle multiple entries for the same name
+ if not isinstance(values, list):
+ values = [values]
+ for value in values:
+ if isinstance(value, tuple):
+ title += '; filename="%s"' % value[0]
+ value = value[1]
+ else:
+ value = _encode(value)
+ yield sep_boundary
+ yield _encode(title)
+ yield b"\n\n"
+ yield value
+ if value and value[-1:] == b'\r':
+ yield b'\n' # write an extra newline (lurve Macs)
+
+ @classmethod
+ def _build_multipart(cls, data):
+ """
+ Build up the MIME payload for the POST data
+ """
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = b'\n--' + boundary.encode('ascii')
- end_boundary = sep_boundary + b'--'
- end_items = end_boundary, b"\n",
- builder = functools.partial(
- cls._build_part,
- sep_boundary=sep_boundary,
- )
- part_groups = map(builder, data.items())
- parts = itertools.chain.from_iterable(part_groups)
- body_items = itertools.chain(parts, end_items)
+ end_boundary = sep_boundary + b'--'
+ end_items = end_boundary, b"\n",
+ builder = functools.partial(
+ cls._build_part,
+ sep_boundary=sep_boundary,
+ )
+ part_groups = map(builder, data.items())
+ parts = itertools.chain.from_iterable(part_groups)
+ body_items = itertools.chain(parts, end_items)
content_type = 'multipart/form-data; boundary=%s' % boundary
- return b''.join(body_items), content_type
-
+ return b''.join(body_items), content_type
+
def upload_file(self, filename):
- with open(filename, 'rb') as f:
- content = f.read()
+ with open(filename, 'rb') as f:
+ content = f.read()
meta = self.distribution.metadata
data = {
':action': 'doc_upload',
@@ -149,14 +149,14 @@ class upload_docs(upload):
'content': (os.path.basename(filename), content),
}
# set up the authentication
- credentials = _encode(self.username + ':' + self.password)
+ credentials = _encode(self.username + ':' + self.password)
credentials = standard_b64encode(credentials).decode('ascii')
auth = "Basic " + credentials
- body, ct = self._build_multipart(data)
+ body, ct = self._build_multipart(data)
- msg = "Submitting documentation to %s" % (self.repository)
- self.announce(msg, log.INFO)
+ msg = "Submitting documentation to %s" % (self.repository)
+ self.announce(msg, log.INFO)
# build the Request
# We can't use urllib2 since we need to send the Basic
@@ -175,7 +175,7 @@ class upload_docs(upload):
try:
conn.connect()
conn.putrequest("POST", url)
- content_type = ct
+ content_type = ct
conn.putheader('Content-type', content_type)
conn.putheader('Content-length', str(len(body)))
conn.putheader('Authorization', auth)
@@ -187,16 +187,16 @@ class upload_docs(upload):
r = conn.getresponse()
if r.status == 200:
- msg = 'Server response (%s): %s' % (r.status, r.reason)
- self.announce(msg, log.INFO)
+ msg = 'Server response (%s): %s' % (r.status, r.reason)
+ self.announce(msg, log.INFO)
elif r.status == 301:
location = r.getheader('Location')
if location is None:
location = 'https://pythonhosted.org/%s/' % meta.get_name()
- msg = 'Upload successful. Visit %s' % location
- self.announce(msg, log.INFO)
+ msg = 'Upload successful. Visit %s' % location
+ self.announce(msg, log.INFO)
else:
- msg = 'Upload failed (%s): %s' % (r.status, r.reason)
- self.announce(msg, log.ERROR)
+ msg = 'Upload failed (%s): %s' % (r.status, r.reason)
+ self.announce(msg, log.ERROR)
if self.show_response:
print('-' * 75, r.read(), '-' * 75)
diff --git a/contrib/python/setuptools/py3/setuptools/config.py b/contrib/python/setuptools/py3/setuptools/config.py
index b4e968e5ca..4724ee7d54 100644
--- a/contrib/python/setuptools/py3/setuptools/config.py
+++ b/contrib/python/setuptools/py3/setuptools/config.py
@@ -1,22 +1,22 @@
import ast
-import io
-import os
-import sys
+import io
+import os
+import sys
import warnings
import functools
import importlib
-from collections import defaultdict
-from functools import partial
+from collections import defaultdict
+from functools import partial
from functools import wraps
from glob import iglob
import contextlib
-
-from distutils.errors import DistutilsOptionError, DistutilsFileError
+
+from distutils.errors import DistutilsOptionError, DistutilsFileError
from setuptools.extern.packaging.version import Version, InvalidVersion
from setuptools.extern.packaging.specifiers import SpecifierSet
-
-
+
+
class StaticModule:
"""
Attempt to load the module by the name
@@ -58,50 +58,50 @@ def patch_path(path):
def read_configuration(filepath, find_others=False, ignore_option_errors=False):
- """Read given configuration file and returns options from it as a dict.
-
- :param str|unicode filepath: Path to configuration file
- to get options from.
-
- :param bool find_others: Whether to search for other configuration files
- which could be on in various places.
-
- :param bool ignore_option_errors: Whether to silently ignore
- options, values of which could not be resolved (e.g. due to exceptions
- in directives such as file:, attr:, etc.).
- If False exceptions are propagated as expected.
-
- :rtype: dict
- """
- from setuptools.dist import Distribution, _Distribution
-
- filepath = os.path.abspath(filepath)
-
- if not os.path.isfile(filepath):
+ """Read given configuration file and returns options from it as a dict.
+
+ :param str|unicode filepath: Path to configuration file
+ to get options from.
+
+ :param bool find_others: Whether to search for other configuration files
+ which could be on in various places.
+
+ :param bool ignore_option_errors: Whether to silently ignore
+ options, values of which could not be resolved (e.g. due to exceptions
+ in directives such as file:, attr:, etc.).
+ If False exceptions are propagated as expected.
+
+ :rtype: dict
+ """
+ from setuptools.dist import Distribution, _Distribution
+
+ filepath = os.path.abspath(filepath)
+
+ if not os.path.isfile(filepath):
raise DistutilsFileError('Configuration file %s does not exist.' % filepath)
-
- current_directory = os.getcwd()
- os.chdir(os.path.dirname(filepath))
-
- try:
- dist = Distribution()
-
- filenames = dist.find_config_files() if find_others else []
- if filepath not in filenames:
- filenames.append(filepath)
-
- _Distribution.parse_config_files(dist, filenames=filenames)
-
- handlers = parse_configuration(
+
+ current_directory = os.getcwd()
+ os.chdir(os.path.dirname(filepath))
+
+ try:
+ dist = Distribution()
+
+ filenames = dist.find_config_files() if find_others else []
+ if filepath not in filenames:
+ filenames.append(filepath)
+
+ _Distribution.parse_config_files(dist, filenames=filenames)
+
+ handlers = parse_configuration(
dist, dist.command_options, ignore_option_errors=ignore_option_errors
)
-
- finally:
- os.chdir(current_directory)
-
- return configuration_to_dict(handlers)
-
-
+
+ finally:
+ os.chdir(current_directory)
+
+ return configuration_to_dict(handlers)
+
+
def _get_option(target_obj, key):
"""
Given a target object and option key, get that option from
@@ -114,41 +114,41 @@ def _get_option(target_obj, key):
return getter()
-def configuration_to_dict(handlers):
- """Returns configuration data gathered by given handlers as a dict.
-
- :param list[ConfigHandler] handlers: Handlers list,
- usually from parse_configuration()
-
- :rtype: dict
- """
- config_dict = defaultdict(dict)
-
- for handler in handlers:
- for option in handler.set_options:
+def configuration_to_dict(handlers):
+ """Returns configuration data gathered by given handlers as a dict.
+
+ :param list[ConfigHandler] handlers: Handlers list,
+ usually from parse_configuration()
+
+ :rtype: dict
+ """
+ config_dict = defaultdict(dict)
+
+ for handler in handlers:
+ for option in handler.set_options:
value = _get_option(handler.target_obj, option)
config_dict[handler.section_prefix][option] = value
-
- return config_dict
-
-
+
+ return config_dict
+
+
def parse_configuration(distribution, command_options, ignore_option_errors=False):
- """Performs additional parsing of configuration options
- for a distribution.
-
- Returns a list of used option handlers.
-
- :param Distribution distribution:
- :param dict command_options:
- :param bool ignore_option_errors: Whether to silently ignore
- options, values of which could not be resolved (e.g. due to exceptions
- in directives such as file:, attr:, etc.).
- If False exceptions are propagated as expected.
- :rtype: list
- """
+ """Performs additional parsing of configuration options
+ for a distribution.
+
+ Returns a list of used option handlers.
+
+ :param Distribution distribution:
+ :param dict command_options:
+ :param bool ignore_option_errors: Whether to silently ignore
+ options, values of which could not be resolved (e.g. due to exceptions
+ in directives such as file:, attr:, etc.).
+ If False exceptions are propagated as expected.
+ :rtype: list
+ """
options = ConfigOptionsHandler(distribution, command_options, ignore_option_errors)
- options.parse()
-
+ options.parse()
+
meta = ConfigMetadataHandler(
distribution.metadata,
command_options,
@@ -156,108 +156,108 @@ def parse_configuration(distribution, command_options, ignore_option_errors=Fals
distribution.package_dir,
)
meta.parse()
-
+
return meta, options
-
+
class ConfigHandler:
- """Handles metadata supplied in configuration files."""
-
- section_prefix = None
- """Prefix for config sections handled by this handler.
- Must be provided by class heirs.
-
- """
-
- aliases = {}
- """Options aliases.
- For compatibility with various packages. E.g.: d2to1 and pbr.
- Note: `-` in keys is replaced with `_` by config parser.
-
- """
-
- def __init__(self, target_obj, options, ignore_option_errors=False):
- sections = {}
-
- section_prefix = self.section_prefix
- for section_name, section_options in options.items():
- if not section_name.startswith(section_prefix):
- continue
-
- section_name = section_name.replace(section_prefix, '').strip('.')
- sections[section_name] = section_options
-
- self.ignore_option_errors = ignore_option_errors
- self.target_obj = target_obj
- self.sections = sections
- self.set_options = []
-
- @property
- def parsers(self):
- """Metadata item name to parser function mapping."""
- raise NotImplementedError(
+ """Handles metadata supplied in configuration files."""
+
+ section_prefix = None
+ """Prefix for config sections handled by this handler.
+ Must be provided by class heirs.
+
+ """
+
+ aliases = {}
+ """Options aliases.
+ For compatibility with various packages. E.g.: d2to1 and pbr.
+ Note: `-` in keys is replaced with `_` by config parser.
+
+ """
+
+ def __init__(self, target_obj, options, ignore_option_errors=False):
+ sections = {}
+
+ section_prefix = self.section_prefix
+ for section_name, section_options in options.items():
+ if not section_name.startswith(section_prefix):
+ continue
+
+ section_name = section_name.replace(section_prefix, '').strip('.')
+ sections[section_name] = section_options
+
+ self.ignore_option_errors = ignore_option_errors
+ self.target_obj = target_obj
+ self.sections = sections
+ self.set_options = []
+
+ @property
+ def parsers(self):
+ """Metadata item name to parser function mapping."""
+ raise NotImplementedError(
'%s must provide .parsers property' % self.__class__.__name__
)
-
- def __setitem__(self, option_name, value):
- unknown = tuple()
- target_obj = self.target_obj
-
- # Translate alias into real name.
- option_name = self.aliases.get(option_name, option_name)
-
- current_value = getattr(target_obj, option_name, unknown)
-
- if current_value is unknown:
- raise KeyError(option_name)
-
- if current_value:
- # Already inhabited. Skipping.
- return
-
- skip_option = False
- parser = self.parsers.get(option_name)
- if parser:
- try:
- value = parser(value)
-
- except Exception:
- skip_option = True
- if not self.ignore_option_errors:
- raise
-
- if skip_option:
- return
-
- setter = getattr(target_obj, 'set_%s' % option_name, None)
- if setter is None:
- setattr(target_obj, option_name, value)
- else:
- setter(value)
-
- self.set_options.append(option_name)
-
- @classmethod
- def _parse_list(cls, value, separator=','):
- """Represents value as a list.
-
- Value is split either by separator (defaults to comma) or by lines.
-
- :param value:
- :param separator: List items separator character.
- :rtype: list
- """
- if isinstance(value, list): # _get_parser_compound case
- return value
-
- if '\n' in value:
- value = value.splitlines()
- else:
- value = value.split(separator)
-
- return [chunk.strip() for chunk in value if chunk.strip()]
-
- @classmethod
+
+ def __setitem__(self, option_name, value):
+ unknown = tuple()
+ target_obj = self.target_obj
+
+ # Translate alias into real name.
+ option_name = self.aliases.get(option_name, option_name)
+
+ current_value = getattr(target_obj, option_name, unknown)
+
+ if current_value is unknown:
+ raise KeyError(option_name)
+
+ if current_value:
+ # Already inhabited. Skipping.
+ return
+
+ skip_option = False
+ parser = self.parsers.get(option_name)
+ if parser:
+ try:
+ value = parser(value)
+
+ except Exception:
+ skip_option = True
+ if not self.ignore_option_errors:
+ raise
+
+ if skip_option:
+ return
+
+ setter = getattr(target_obj, 'set_%s' % option_name, None)
+ if setter is None:
+ setattr(target_obj, option_name, value)
+ else:
+ setter(value)
+
+ self.set_options.append(option_name)
+
+ @classmethod
+ def _parse_list(cls, value, separator=','):
+ """Represents value as a list.
+
+ Value is split either by separator (defaults to comma) or by lines.
+
+ :param value:
+ :param separator: List items separator character.
+ :rtype: list
+ """
+ if isinstance(value, list): # _get_parser_compound case
+ return value
+
+ if '\n' in value:
+ value = value.splitlines()
+ else:
+ value = value.split(separator)
+
+ return [chunk.strip() for chunk in value if chunk.strip()]
+
+ @classmethod
def _parse_list_glob(cls, value, separator=','):
"""Equivalent to _parse_list() but expands any glob patterns using glob().
@@ -286,35 +286,35 @@ class ConfigHandler:
return expanded_values
@classmethod
- def _parse_dict(cls, value):
- """Represents value as a dict.
-
- :param value:
- :rtype: dict
- """
- separator = '='
- result = {}
- for line in cls._parse_list(value):
- key, sep, val = line.partition(separator)
- if sep != separator:
- raise DistutilsOptionError(
+ def _parse_dict(cls, value):
+ """Represents value as a dict.
+
+ :param value:
+ :rtype: dict
+ """
+ separator = '='
+ result = {}
+ for line in cls._parse_list(value):
+ key, sep, val = line.partition(separator)
+ if sep != separator:
+ raise DistutilsOptionError(
'Unable to parse option value to dict: %s' % value
)
- result[key.strip()] = val.strip()
-
- return result
-
- @classmethod
- def _parse_bool(cls, value):
- """Represents value as boolean.
-
- :param value:
- :rtype: bool
- """
- value = value.lower()
- return value in ('1', 'true', 'yes')
-
- @classmethod
+ result[key.strip()] = val.strip()
+
+ return result
+
+ @classmethod
+ def _parse_bool(cls, value):
+ """Represents value as boolean.
+
+ :param value:
+ :rtype: bool
+ """
+ value = value.lower()
+ return value in ('1', 'true', 'yes')
+
+ @classmethod
def _exclude_files_parser(cls, key):
"""Returns a parser function to make sure field inputs
are not files.
@@ -338,27 +338,27 @@ class ConfigHandler:
return parser
@classmethod
- def _parse_file(cls, value):
- """Represents value as a string, allowing including text
- from nearest files using `file:` directive.
-
- Directive is sandboxed and won't reach anything outside
- directory with setup.py.
-
- Examples:
+ def _parse_file(cls, value):
+ """Represents value as a string, allowing including text
+ from nearest files using `file:` directive.
+
+ Directive is sandboxed and won't reach anything outside
+ directory with setup.py.
+
+ Examples:
file: README.rst, CHANGELOG.md, src/file.txt
-
- :param str value:
- :rtype: str
- """
+
+ :param str value:
+ :rtype: str
+ """
include_directive = 'file:'
if not isinstance(value, str):
- return value
-
- if not value.startswith(include_directive):
- return value
-
+ return value
+
+ if not value.startswith(include_directive):
+ return value
+
spec = value[len(include_directive) :]
filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))
return '\n'.join(
@@ -366,38 +366,38 @@ class ConfigHandler:
for path in filepaths
if (cls._assert_local(path) or True) and os.path.isfile(path)
)
-
+
@staticmethod
def _assert_local(filepath):
if not filepath.startswith(os.getcwd()):
raise DistutilsOptionError('`file:` directive can not access %s' % filepath)
-
+
@staticmethod
def _read_file(filepath):
with io.open(filepath, encoding='utf-8') as f:
return f.read()
-
- @classmethod
+
+ @classmethod
def _parse_attr(cls, value, package_dir=None):
- """Represents value as a module attribute.
-
- Examples:
- attr: package.attr
- attr: package.module.attr
-
- :param str value:
- :rtype: str
- """
- attr_directive = 'attr:'
- if not value.startswith(attr_directive):
- return value
-
- attrs_path = value.replace(attr_directive, '').strip().split('.')
- attr_name = attrs_path.pop()
-
- module_name = '.'.join(attrs_path)
- module_name = module_name or '__init__'
-
+ """Represents value as a module attribute.
+
+ Examples:
+ attr: package.attr
+ attr: package.module.attr
+
+ :param str value:
+ :rtype: str
+ """
+ attr_directive = 'attr:'
+ if not value.startswith(attr_directive):
+ return value
+
+ attrs_path = value.replace(attr_directive, '').strip().split('.')
+ attr_name = attrs_path.pop()
+
+ module_name = '.'.join(attrs_path)
+ module_name = module_name or '__init__'
+
parent_path = os.getcwd()
if package_dir:
if attrs_path[0] in package_dir:
@@ -412,7 +412,7 @@ class ConfigHandler:
elif '' in package_dir:
# A custom parent directory was specified for all root modules
parent_path = os.path.join(os.getcwd(), package_dir[''])
-
+
with patch_path(parent_path):
try:
# attempt to load value statically
@@ -420,86 +420,86 @@ class ConfigHandler:
except Exception:
# fallback to simple import
module = importlib.import_module(module_name)
-
+
return getattr(module, attr_name)
-
- @classmethod
- def _get_parser_compound(cls, *parse_methods):
- """Returns parser function to represents value as a list.
-
- Parses a value applying given methods one after another.
-
- :param parse_methods:
- :rtype: callable
- """
-
- def parse(value):
- parsed = value
-
- for method in parse_methods:
- parsed = method(parsed)
-
- return parsed
-
- return parse
-
- @classmethod
- def _parse_section_to_dict(cls, section_options, values_parser=None):
- """Parses section options into a dictionary.
-
- Optionally applies a given parser to values.
-
- :param dict section_options:
- :param callable values_parser:
- :rtype: dict
- """
- value = {}
- values_parser = values_parser or (lambda val: val)
- for key, (_, val) in section_options.items():
- value[key] = values_parser(val)
- return value
-
- def parse_section(self, section_options):
- """Parses configuration file section.
-
- :param dict section_options:
- """
- for (name, (_, value)) in section_options.items():
- try:
- self[name] = value
-
- except KeyError:
- pass # Keep silent for a new option may appear anytime.
-
- def parse(self):
- """Parses configuration file items from one
- or more related sections.
-
- """
- for section_name, section_options in self.sections.items():
-
- method_postfix = ''
- if section_name: # [section.option] variant
- method_postfix = '_%s' % section_name
-
- section_parser_method = getattr(
- self,
+
+ @classmethod
+ def _get_parser_compound(cls, *parse_methods):
+ """Returns parser function to represents value as a list.
+
+ Parses a value applying given methods one after another.
+
+ :param parse_methods:
+ :rtype: callable
+ """
+
+ def parse(value):
+ parsed = value
+
+ for method in parse_methods:
+ parsed = method(parsed)
+
+ return parsed
+
+ return parse
+
+ @classmethod
+ def _parse_section_to_dict(cls, section_options, values_parser=None):
+ """Parses section options into a dictionary.
+
+ Optionally applies a given parser to values.
+
+ :param dict section_options:
+ :param callable values_parser:
+ :rtype: dict
+ """
+ value = {}
+ values_parser = values_parser or (lambda val: val)
+ for key, (_, val) in section_options.items():
+ value[key] = values_parser(val)
+ return value
+
+ def parse_section(self, section_options):
+ """Parses configuration file section.
+
+ :param dict section_options:
+ """
+ for (name, (_, value)) in section_options.items():
+ try:
+ self[name] = value
+
+ except KeyError:
+ pass # Keep silent for a new option may appear anytime.
+
+ def parse(self):
+ """Parses configuration file items from one
+ or more related sections.
+
+ """
+ for section_name, section_options in self.sections.items():
+
+ method_postfix = ''
+ if section_name: # [section.option] variant
+ method_postfix = '_%s' % section_name
+
+ section_parser_method = getattr(
+ self,
# Dots in section names are translated into dunderscores.
- ('parse_section%s' % method_postfix).replace('.', '__'),
+ ('parse_section%s' % method_postfix).replace('.', '__'),
None,
)
-
- if section_parser_method is None:
- raise DistutilsOptionError(
+
+ if section_parser_method is None:
+ raise DistutilsOptionError(
'Unsupported distribution option section: [%s.%s]'
% (self.section_prefix, section_name)
)
-
- section_parser_method(section_options)
-
+
+ section_parser_method(section_options)
+
def _deprecated_config_handler(self, func, msg, warning_class):
"""this function will wrap around parameters that are deprecated
-
+
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around
@@ -513,23 +513,23 @@ class ConfigHandler:
return config_handler
-class ConfigMetadataHandler(ConfigHandler):
-
- section_prefix = 'metadata'
-
- aliases = {
- 'home_page': 'url',
- 'summary': 'description',
- 'classifier': 'classifiers',
- 'platform': 'platforms',
- }
-
- strict_mode = False
- """We need to keep it loose, to be partially compatible with
- `pbr` and `d2to1` packages which also uses `metadata` section.
-
- """
-
+class ConfigMetadataHandler(ConfigHandler):
+
+ section_prefix = 'metadata'
+
+ aliases = {
+ 'home_page': 'url',
+ 'summary': 'description',
+ 'classifier': 'classifiers',
+ 'platform': 'platforms',
+ }
+
+ strict_mode = False
+ """We need to keep it loose, to be partially compatible with
+ `pbr` and `d2to1` packages which also uses `metadata` section.
+
+ """
+
def __init__(
self, target_obj, options, ignore_option_errors=False, package_dir=None
):
@@ -538,26 +538,26 @@ class ConfigMetadataHandler(ConfigHandler):
)
self.package_dir = package_dir
- @property
- def parsers(self):
- """Metadata item name to parser function mapping."""
- parse_list = self._parse_list
- parse_file = self._parse_file
+ @property
+ def parsers(self):
+ """Metadata item name to parser function mapping."""
+ parse_list = self._parse_list
+ parse_file = self._parse_file
parse_dict = self._parse_dict
exclude_files_parser = self._exclude_files_parser
-
- return {
- 'platforms': parse_list,
- 'keywords': parse_list,
- 'provides': parse_list,
+
+ return {
+ 'platforms': parse_list,
+ 'keywords': parse_list,
+ 'provides': parse_list,
'requires': self._deprecated_config_handler(
parse_list,
"The requires parameter is deprecated, please use "
"install_requires for runtime dependencies.",
DeprecationWarning,
),
- 'obsoletes': parse_list,
- 'classifiers': self._get_parser_compound(parse_file, parse_list),
+ 'obsoletes': parse_list,
+ 'classifiers': self._get_parser_compound(parse_file, parse_list),
'license': exclude_files_parser('license'),
'license_file': self._deprecated_config_handler(
exclude_files_parser('license_file'),
@@ -566,21 +566,21 @@ class ConfigMetadataHandler(ConfigHandler):
DeprecationWarning,
),
'license_files': parse_list,
- 'description': parse_file,
- 'long_description': parse_file,
- 'version': self._parse_version,
+ 'description': parse_file,
+ 'long_description': parse_file,
+ 'version': self._parse_version,
'project_urls': parse_dict,
- }
-
- def _parse_version(self, value):
- """Parses `version` option value.
-
- :param value:
- :rtype: str
-
- """
+ }
+
+ def _parse_version(self, value):
+ """Parses `version` option value.
+
+ :param value:
+ :rtype: str
+
+ """
version = self._parse_file(value)
-
+
if version != value:
version = version.strip()
# Be strict about versions loaded from file because it's easy to
@@ -598,49 +598,49 @@ class ConfigMetadataHandler(ConfigHandler):
version = self._parse_attr(value, self.package_dir)
- if callable(version):
- version = version()
-
+ if callable(version):
+ version = version()
+
if not isinstance(version, str):
- if hasattr(version, '__iter__'):
- version = '.'.join(map(str, version))
- else:
- version = '%s' % version
-
- return version
-
-
-class ConfigOptionsHandler(ConfigHandler):
-
- section_prefix = 'options'
-
- @property
- def parsers(self):
- """Metadata item name to parser function mapping."""
- parse_list = self._parse_list
- parse_list_semicolon = partial(self._parse_list, separator=';')
- parse_bool = self._parse_bool
- parse_dict = self._parse_dict
+ if hasattr(version, '__iter__'):
+ version = '.'.join(map(str, version))
+ else:
+ version = '%s' % version
+
+ return version
+
+
+class ConfigOptionsHandler(ConfigHandler):
+
+ section_prefix = 'options'
+
+ @property
+ def parsers(self):
+ """Metadata item name to parser function mapping."""
+ parse_list = self._parse_list
+ parse_list_semicolon = partial(self._parse_list, separator=';')
+ parse_bool = self._parse_bool
+ parse_dict = self._parse_dict
parse_cmdclass = self._parse_cmdclass
-
- return {
- 'zip_safe': parse_bool,
- 'include_package_data': parse_bool,
- 'package_dir': parse_dict,
- 'scripts': parse_list,
- 'eager_resources': parse_list,
- 'dependency_links': parse_list,
- 'namespace_packages': parse_list,
- 'install_requires': parse_list_semicolon,
- 'setup_requires': parse_list_semicolon,
- 'tests_require': parse_list_semicolon,
- 'packages': self._parse_packages,
- 'entry_points': self._parse_file,
+
+ return {
+ 'zip_safe': parse_bool,
+ 'include_package_data': parse_bool,
+ 'package_dir': parse_dict,
+ 'scripts': parse_list,
+ 'eager_resources': parse_list,
+ 'dependency_links': parse_list,
+ 'namespace_packages': parse_list,
+ 'install_requires': parse_list_semicolon,
+ 'setup_requires': parse_list_semicolon,
+ 'tests_require': parse_list_semicolon,
+ 'packages': self._parse_packages,
+ 'entry_points': self._parse_file,
'py_modules': parse_list,
'python_requires': SpecifierSet,
'cmdclass': parse_cmdclass,
- }
-
+ }
+
def _parse_cmdclass(self, value):
def resolve_class(qualified_class_name):
idx = qualified_class_name.rfind('.')
@@ -653,92 +653,92 @@ class ConfigOptionsHandler(ConfigHandler):
return {k: resolve_class(v) for k, v in self._parse_dict(value).items()}
- def _parse_packages(self, value):
- """Parses `packages` option value.
-
- :param value:
- :rtype: list
- """
+ def _parse_packages(self, value):
+ """Parses `packages` option value.
+
+ :param value:
+ :rtype: list
+ """
find_directives = ['find:', 'find_namespace:']
trimmed_value = value.strip()
-
+
if trimmed_value not in find_directives:
- return self._parse_list(value)
-
+ return self._parse_list(value)
+
findns = trimmed_value == find_directives[1]
- # Read function arguments from a dedicated section.
- find_kwargs = self.parse_section_packages__find(
+ # Read function arguments from a dedicated section.
+ find_kwargs = self.parse_section_packages__find(
self.sections.get('packages.find', {})
)
-
+
if findns:
from setuptools import find_namespace_packages as find_packages
else:
from setuptools import find_packages
-
- return find_packages(**find_kwargs)
-
- def parse_section_packages__find(self, section_options):
- """Parses `packages.find` configuration file section.
-
- To be used in conjunction with _parse_packages().
-
- :param dict section_options:
- """
+
+ return find_packages(**find_kwargs)
+
+ def parse_section_packages__find(self, section_options):
+ """Parses `packages.find` configuration file section.
+
+ To be used in conjunction with _parse_packages().
+
+ :param dict section_options:
+ """
section_data = self._parse_section_to_dict(section_options, self._parse_list)
-
- valid_keys = ['where', 'include', 'exclude']
-
- find_kwargs = dict(
+
+ valid_keys = ['where', 'include', 'exclude']
+
+ find_kwargs = dict(
[(k, v) for k, v in section_data.items() if k in valid_keys and v]
)
-
- where = find_kwargs.get('where')
- if where is not None:
- find_kwargs['where'] = where[0] # cast list to single val
-
- return find_kwargs
-
- def parse_section_entry_points(self, section_options):
- """Parses `entry_points` configuration file section.
-
- :param dict section_options:
- """
- parsed = self._parse_section_to_dict(section_options, self._parse_list)
- self['entry_points'] = parsed
-
- def _parse_package_data(self, section_options):
- parsed = self._parse_section_to_dict(section_options, self._parse_list)
-
- root = parsed.get('*')
- if root:
- parsed[''] = root
- del parsed['*']
-
- return parsed
-
- def parse_section_package_data(self, section_options):
- """Parses `package_data` configuration file section.
-
- :param dict section_options:
- """
- self['package_data'] = self._parse_package_data(section_options)
-
- def parse_section_exclude_package_data(self, section_options):
- """Parses `exclude_package_data` configuration file section.
-
- :param dict section_options:
- """
+
+ where = find_kwargs.get('where')
+ if where is not None:
+ find_kwargs['where'] = where[0] # cast list to single val
+
+ return find_kwargs
+
+ def parse_section_entry_points(self, section_options):
+ """Parses `entry_points` configuration file section.
+
+ :param dict section_options:
+ """
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
+ self['entry_points'] = parsed
+
+ def _parse_package_data(self, section_options):
+ parsed = self._parse_section_to_dict(section_options, self._parse_list)
+
+ root = parsed.get('*')
+ if root:
+ parsed[''] = root
+ del parsed['*']
+
+ return parsed
+
+ def parse_section_package_data(self, section_options):
+ """Parses `package_data` configuration file section.
+
+ :param dict section_options:
+ """
+ self['package_data'] = self._parse_package_data(section_options)
+
+ def parse_section_exclude_package_data(self, section_options):
+ """Parses `exclude_package_data` configuration file section.
+
+ :param dict section_options:
+ """
self['exclude_package_data'] = self._parse_package_data(section_options)
-
- def parse_section_extras_require(self, section_options):
- """Parses `extras_require` configuration file section.
-
- :param dict section_options:
- """
- parse_list = partial(self._parse_list, separator=';')
- self['extras_require'] = self._parse_section_to_dict(
+
+ def parse_section_extras_require(self, section_options):
+ """Parses `extras_require` configuration file section.
+
+ :param dict section_options:
+ """
+ parse_list = partial(self._parse_list, separator=';')
+ self['extras_require'] = self._parse_section_to_dict(
section_options, parse_list
)
diff --git a/contrib/python/setuptools/py3/setuptools/dep_util.py b/contrib/python/setuptools/py3/setuptools/dep_util.py
index 521eb716a5..ff830fe6ec 100644
--- a/contrib/python/setuptools/py3/setuptools/dep_util.py
+++ b/contrib/python/setuptools/py3/setuptools/dep_util.py
@@ -1,25 +1,25 @@
-from distutils.dep_util import newer_group
+from distutils.dep_util import newer_group
+
-
-# yes, this is was almost entirely copy-pasted from
-# 'newer_pairwise()', this is just another convenience
-# function.
-def newer_pairwise_group(sources_groups, targets):
- """Walk both arguments in parallel, testing if each source group is newer
- than its corresponding target. Returns a pair of lists (sources_groups,
- targets) where sources is newer than target, according to the semantics
- of 'newer_group()'.
- """
- if len(sources_groups) != len(targets):
+# yes, this is was almost entirely copy-pasted from
+# 'newer_pairwise()', this is just another convenience
+# function.
+def newer_pairwise_group(sources_groups, targets):
+ """Walk both arguments in parallel, testing if each source group is newer
+ than its corresponding target. Returns a pair of lists (sources_groups,
+ targets) where sources is newer than target, according to the semantics
+ of 'newer_group()'.
+ """
+ if len(sources_groups) != len(targets):
raise ValueError(
"'sources_group' and 'targets' must be the same length")
-
- # build a pair of lists (sources_groups, targets) where source is newer
- n_sources = []
- n_targets = []
- for i in range(len(sources_groups)):
- if newer_group(sources_groups[i], targets[i]):
- n_sources.append(sources_groups[i])
- n_targets.append(targets[i])
-
- return n_sources, n_targets
+
+ # build a pair of lists (sources_groups, targets) where source is newer
+ n_sources = []
+ n_targets = []
+ for i in range(len(sources_groups)):
+ if newer_group(sources_groups[i], targets[i]):
+ n_sources.append(sources_groups[i])
+ n_targets.append(targets[i])
+
+ return n_sources, n_targets
diff --git a/contrib/python/setuptools/py3/setuptools/depends.py b/contrib/python/setuptools/py3/setuptools/depends.py
index adffd12db8..39152f89d8 100644
--- a/contrib/python/setuptools/py3/setuptools/depends.py
+++ b/contrib/python/setuptools/py3/setuptools/depends.py
@@ -8,12 +8,12 @@ from setuptools.extern.packaging import version
from ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE
from . import _imp
-
+
__all__ = [
'Require', 'find_module', 'get_module_constant', 'extract_constant'
]
-
+
class Require:
"""A prerequisite to building or installing a distribution"""
@@ -35,7 +35,7 @@ class Require:
def full_name(self):
"""Return full package/distribution name, w/version"""
if self.requested_version is not None:
- return '%s-%s' % (self.name, self.requested_version)
+ return '%s-%s' % (self.name, self.requested_version)
return self.name
def version_ok(self, version):
@@ -56,9 +56,9 @@ class Require:
if self.attribute is None:
try:
- f, p, i = find_module(self.module, paths)
- if f:
- f.close()
+ f, p, i = find_module(self.module, paths)
+ if f:
+ f.close()
return default
except ImportError:
return None
@@ -107,12 +107,12 @@ def get_module_constant(module, symbol, default=-1, paths=None):
return None
with maybe_close(f):
- if kind == PY_COMPILED:
- f.read(8) # skip magic & date
+ if kind == PY_COMPILED:
+ f.read(8) # skip magic & date
code = marshal.load(f)
- elif kind == PY_FROZEN:
+ elif kind == PY_FROZEN:
code = _imp.get_frozen_object(module, paths)
- elif kind == PY_SOURCE:
+ elif kind == PY_SOURCE:
code = compile(f.read(), path, 'exec')
else:
# Not something we can parse; we'll have to import it. :(
@@ -135,7 +135,7 @@ def extract_constant(code, symbol, default=-1):
must be present in 'code.co_names'.
"""
if symbol not in code.co_names:
- # name's not there, can't possibly be an assignment
+ # name's not there, can't possibly be an assignment
return None
name_idx = list(code.co_names).index(symbol)
@@ -147,12 +147,12 @@ def extract_constant(code, symbol, default=-1):
const = default
for byte_code in dis.Bytecode(code):
- op = byte_code.opcode
- arg = byte_code.arg
+ op = byte_code.opcode
+ arg = byte_code.arg
- if op == LOAD_CONST:
+ if op == LOAD_CONST:
const = code.co_consts[arg]
- elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
+ elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
return const
else:
const = default
@@ -172,5 +172,5 @@ def _update_globals():
del globals()[name]
__all__.remove(name)
-
+
_update_globals()
diff --git a/contrib/python/setuptools/py3/setuptools/dist.py b/contrib/python/setuptools/py3/setuptools/dist.py
index 37a10d1dcd..cce0ae9ccf 100644
--- a/contrib/python/setuptools/py3/setuptools/dist.py
+++ b/contrib/python/setuptools/py3/setuptools/dist.py
@@ -24,7 +24,7 @@ from collections import defaultdict
from email import message_from_file
from distutils.errors import DistutilsOptionError, DistutilsSetupError
-from distutils.util import rfc822_escape
+from distutils.util import rfc822_escape
from setuptools.extern import packaging
from setuptools.extern import ordered_set
@@ -35,8 +35,8 @@ from . import SetuptoolsDeprecationWarning
import setuptools
import setuptools.command
from setuptools import windows_support
-from setuptools.monkey import get_unpatched
-from setuptools.config import parse_configuration
+from setuptools.monkey import get_unpatched
+from setuptools.config import parse_configuration
import pkg_resources
from setuptools.extern.packaging import version
@@ -49,9 +49,9 @@ __import__('setuptools.extern.packaging.version')
def _get_unpatched(cls):
warnings.warn("Do not call this function", DistDeprecationWarning)
- return get_unpatched(cls)
-
+ return get_unpatched(cls)
+
def get_metadata_version(self):
mv = getattr(self, 'metadata_version', None)
if mv is None:
@@ -159,7 +159,7 @@ def single_line(val):
return val
-# Based on Python 3.5 version
+# Based on Python 3.5 version
def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
"""Write the PKG-INFO format data to a file object."""
version = self.get_metadata_version()
@@ -187,36 +187,36 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
license = rfc822_escape(self.get_license())
write_field('License', license)
- if self.download_url:
+ if self.download_url:
write_field('Download-URL', self.download_url)
for project_url in self.project_urls.items():
write_field('Project-URL', '%s, %s' % project_url)
- keywords = ','.join(self.get_keywords())
- if keywords:
+ keywords = ','.join(self.get_keywords())
+ if keywords:
write_field('Keywords', keywords)
-
+
for platform in self.get_platforms():
write_field('Platform', platform)
- self._write_list(file, 'Classifier', self.get_classifiers())
-
- # PEP 314
- self._write_list(file, 'Requires', self.get_requires())
- self._write_list(file, 'Provides', self.get_provides())
- self._write_list(file, 'Obsoletes', self.get_obsoletes())
-
- # Setuptools specific for PEP 345
- if hasattr(self, 'python_requires'):
+ self._write_list(file, 'Classifier', self.get_classifiers())
+
+ # PEP 314
+ self._write_list(file, 'Requires', self.get_requires())
+ self._write_list(file, 'Provides', self.get_provides())
+ self._write_list(file, 'Obsoletes', self.get_obsoletes())
+
+ # Setuptools specific for PEP 345
+ if hasattr(self, 'python_requires'):
write_field('Requires-Python', self.python_requires)
-
+
# PEP 566
if self.long_description_content_type:
write_field('Description-Content-Type', self.long_description_content_type)
if self.provides_extras:
for extra in self.provides_extras:
write_field('Provides-Extra', extra)
-
+
self._write_list(file, 'License-File', self.license_files or [])
file.write("\n%s\n\n" % self.get_long_description())
@@ -224,10 +224,10 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
sequence = tuple, list
-
+
def check_importable(dist, attr, value):
try:
- ep = pkg_resources.EntryPoint.parse('x=' + value)
+ ep = pkg_resources.EntryPoint.parse('x=' + value)
assert not ep.extras
except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
@@ -242,33 +242,33 @@ def assert_string_list(dist, attr, value):
# or single-use iterables
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
- assert ''.join(value) != value
+ assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
- "%r must be a list of strings (got %r)" % (attr, value)
+ "%r must be a list of strings (got %r)" % (attr, value)
) from e
-
-
+
+
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
- ns_packages = value
- assert_string_list(dist, attr, ns_packages)
- for nsp in ns_packages:
+ ns_packages = value
+ assert_string_list(dist, attr, ns_packages)
+ for nsp in ns_packages:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for "
+ "namespace package %r" % nsp
)
- parent, sep, child = nsp.rpartition('.')
- if parent and parent not in ns_packages:
- distutils.log.warn(
- "WARNING: %r is declared as a package namespace, but %r"
+ parent, sep, child = nsp.rpartition('.')
+ if parent and parent not in ns_packages:
+ distutils.log.warn(
+ "WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py",
nsp,
parent,
- )
-
+ )
+
def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
@@ -280,7 +280,7 @@ def check_extras(dist, attr, value):
"requirement specifiers."
) from e
-
+
def _check_extra(extra, reqs):
name, sep, marker = extra.partition(':')
if marker and pkg_resources.invalid_marker(marker):
@@ -315,18 +315,18 @@ def check_requirements(dist, attr, value):
)
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
-
-def check_specifier(dist, attr, value):
- """Verify that value is a valid version specifier"""
- try:
- packaging.specifiers.SpecifierSet(value)
+
+def check_specifier(dist, attr, value):
+ """Verify that value is a valid version specifier"""
+ try:
+ packaging.specifiers.SpecifierSet(value)
except (packaging.specifiers.InvalidSpecifier, AttributeError) as error:
- tmpl = (
+ tmpl = (
"{attr!r} must be a string " "containing valid version specifiers; {error}"
- )
+ )
raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
-
-
+
+
def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
@@ -334,12 +334,12 @@ def check_entry_points(dist, attr, value):
except ValueError as e:
raise DistutilsSetupError(e) from e
-
+
def check_test_suite(dist, attr, value):
if not isinstance(value, str):
raise DistutilsSetupError("test_suite must be a string")
-
+
def check_package_data(dist, attr, value):
"""Verify that value is a dictionary of package names to glob lists"""
if not isinstance(value, dict):
@@ -354,7 +354,7 @@ def check_package_data(dist, attr, value):
)
assert_string_list(dist, 'values of {!r} dict'.format(attr), v)
-
+
def check_packages(dist, attr, value):
for pkgname in value:
if not re.match(r'\w+(\.\w+)*', pkgname):
@@ -365,9 +365,9 @@ def check_packages(dist, attr, value):
)
-_Distribution = get_unpatched(distutils.core.Distribution)
-
-
+_Distribution = get_unpatched(distutils.core.Distribution)
+
+
class Distribution(_Distribution):
"""Distribution with support for tests and package data
@@ -518,8 +518,8 @@ class Distribution(_Distribution):
Set `metadata.python_requires` and fix environment markers
in `install_requires` and `extras_require`.
"""
- if getattr(self, 'python_requires', None):
- self.metadata.python_requires = self.python_requires
+ if getattr(self, 'python_requires', None):
+ self.metadata.python_requires = self.python_requires
if getattr(self, 'extras_require', None):
for extra in self.extras_require.keys():
@@ -795,18 +795,18 @@ class Distribution(_Distribution):
raise DistutilsOptionError(e) from e
def parse_config_files(self, filenames=None, ignore_option_errors=False):
- """Parses configuration files from various levels
- and loads configuration.
-
- """
+ """Parses configuration files from various levels
+ and loads configuration.
+
+ """
self._parse_config_files(filenames=filenames)
-
+
parse_configuration(
self, self.command_options, ignore_option_errors=ignore_option_errors
)
self._finalize_requires()
self._finalize_license_files()
-
+
def fetch_build_eggs(self, requires):
"""Resolve pre-setup requirements"""
resolved_dists = pkg_resources.working_set.resolve(
@@ -816,7 +816,7 @@ class Distribution(_Distribution):
)
for dist in resolved_dists:
pkg_resources.working_set.add(dist, replace=True)
- return resolved_dists
+ return resolved_dists
def finalize_options(self):
"""
@@ -852,7 +852,7 @@ class Distribution(_Distribution):
def _finalize_setup_keywords(self):
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
- value = getattr(self, ep.name, None)
+ value = getattr(self, ep.name, None)
if value is not None:
ep.require(installer=self.fetch_build_egg)
ep.load()(self, ep.name, value)
@@ -911,7 +911,7 @@ class Distribution(_Distribution):
self.cmdclass[ep.name] = cmdclass
return _Distribution.get_command_list(self)
- def include(self, **attrs):
+ def include(self, **attrs):
"""Add items to distribution that are named in keyword arguments
For example, 'dist.include(py_modules=["x"])' would add 'x' to
@@ -926,17 +926,17 @@ class Distribution(_Distribution):
will try to call 'dist._include_foo({"bar":"baz"})', which can then
handle whatever special inclusion logic is needed.
"""
- for k, v in attrs.items():
- include = getattr(self, '_include_' + k, None)
+ for k, v in attrs.items():
+ include = getattr(self, '_include_' + k, None)
if include:
include(v)
else:
- self._include_misc(k, v)
+ self._include_misc(k, v)
- def exclude_package(self, package):
+ def exclude_package(self, package):
"""Remove packages, modules, and extensions in named package"""
- pfx = package + '.'
+ pfx = package + '.'
if self.packages:
self.packages = [
p for p in self.packages if p != package and not p.startswith(pfx)
@@ -951,55 +951,55 @@ class Distribution(_Distribution):
self.ext_modules = [
p
for p in self.ext_modules
- if p.name != package and not p.name.startswith(pfx)
+ if p.name != package and not p.name.startswith(pfx)
]
- def has_contents_for(self, package):
+ def has_contents_for(self, package):
"""Return true if 'exclude_package(package)' would do something"""
- pfx = package + '.'
+ pfx = package + '.'
for p in self.iter_distribution_names():
- if p == package or p.startswith(pfx):
+ if p == package or p.startswith(pfx):
return True
- def _exclude_misc(self, name, value):
+ def _exclude_misc(self, name, value):
"""Handle 'exclude()' for list/tuple attrs without a special handler"""
- if not isinstance(value, sequence):
+ if not isinstance(value, sequence):
raise DistutilsSetupError(
"%s: setting must be a list or tuple (%r)" % (name, value)
)
try:
- old = getattr(self, name)
+ old = getattr(self, name)
except AttributeError as e:
raise DistutilsSetupError("%s: No such distribution setting" % name) from e
- if old is not None and not isinstance(old, sequence):
+ if old is not None and not isinstance(old, sequence):
raise DistutilsSetupError(
- name + ": this setting cannot be changed via include/exclude"
+ name + ": this setting cannot be changed via include/exclude"
)
elif old:
- setattr(self, name, [item for item in old if item not in value])
+ setattr(self, name, [item for item in old if item not in value])
- def _include_misc(self, name, value):
+ def _include_misc(self, name, value):
"""Handle 'include()' for list/tuple attrs without a special handler"""
- if not isinstance(value, sequence):
+ if not isinstance(value, sequence):
raise DistutilsSetupError("%s: setting must be a list (%r)" % (name, value))
try:
- old = getattr(self, name)
+ old = getattr(self, name)
except AttributeError as e:
raise DistutilsSetupError("%s: No such distribution setting" % name) from e
if old is None:
- setattr(self, name, value)
- elif not isinstance(old, sequence):
+ setattr(self, name, value)
+ elif not isinstance(old, sequence):
raise DistutilsSetupError(
- name + ": this setting cannot be changed via include/exclude"
+ name + ": this setting cannot be changed via include/exclude"
)
else:
new = [item for item in value if item not in old]
setattr(self, name, old + new)
- def exclude(self, **attrs):
+ def exclude(self, **attrs):
"""Remove items from distribution that are named in keyword arguments
For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
@@ -1015,15 +1015,15 @@ class Distribution(_Distribution):
will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
handle whatever special exclusion logic is needed.
"""
- for k, v in attrs.items():
- exclude = getattr(self, '_exclude_' + k, None)
+ for k, v in attrs.items():
+ exclude = getattr(self, '_exclude_' + k, None)
if exclude:
exclude(v)
else:
- self._exclude_misc(k, v)
+ self._exclude_misc(k, v)
- def _exclude_packages(self, packages):
- if not isinstance(packages, sequence):
+ def _exclude_packages(self, packages):
+ if not isinstance(packages, sequence):
raise DistutilsSetupError(
"packages: setting must be a list or tuple (%r)" % (packages,)
)
@@ -1038,18 +1038,18 @@ class Distribution(_Distribution):
command = args[0]
aliases = self.get_option_dict('aliases')
while command in aliases:
- src, alias = aliases[command]
- del aliases[command] # ensure each alias can expand only once!
+ src, alias = aliases[command]
+ del aliases[command] # ensure each alias can expand only once!
import shlex
- args[:1] = shlex.split(alias, True)
+ args[:1] = shlex.split(alias, True)
command = args[0]
nargs = _Distribution._parse_command_opts(self, parser, args)
# Handle commands that want to consume all remaining arguments
cmd_class = self.get_command_class(command)
- if getattr(cmd_class, 'command_consumes_arguments', None):
+ if getattr(cmd_class, 'command_consumes_arguments', None):
self.get_option_dict(command)['args'] = ("command line", nargs)
if nargs is not None:
return []
@@ -1068,31 +1068,31 @@ class Distribution(_Distribution):
d = {}
- for cmd, opts in self.command_options.items():
+ for cmd, opts in self.command_options.items():
- for opt, (src, val) in opts.items():
+ for opt, (src, val) in opts.items():
if src != "command line":
continue
- opt = opt.replace('_', '-')
+ opt = opt.replace('_', '-')
- if val == 0:
+ if val == 0:
cmdobj = self.get_command_obj(cmd)
neg_opt = self.negative_opt.copy()
- neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
- for neg, pos in neg_opt.items():
- if pos == opt:
- opt = neg
- val = None
+ neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
+ for neg, pos in neg_opt.items():
+ if pos == opt:
+ opt = neg
+ val = None
break
else:
raise AssertionError("Shouldn't be able to get here")
- elif val == 1:
+ elif val == 1:
val = None
- d.setdefault(cmd, {})[opt] = val
+ d.setdefault(cmd, {})[opt] = val
return d
@@ -1106,7 +1106,7 @@ class Distribution(_Distribution):
yield module
for ext in self.ext_modules or ():
- if isinstance(ext, tuple):
+ if isinstance(ext, tuple):
name, buildinfo = ext
else:
name = ext.name
diff --git a/contrib/python/setuptools/py3/setuptools/extension.py b/contrib/python/setuptools/py3/setuptools/extension.py
index 1820722a49..d4ea86a6e6 100644
--- a/contrib/python/setuptools/py3/setuptools/extension.py
+++ b/contrib/python/setuptools/py3/setuptools/extension.py
@@ -4,14 +4,14 @@ import distutils.core
import distutils.errors
import distutils.extension
-from .monkey import get_unpatched
+from .monkey import get_unpatched
def _have_cython():
"""
Return True if Cython can be imported.
"""
- cython_impl = 'Cython.Distutils.build_ext'
+ cython_impl = 'Cython.Distutils.build_ext'
try:
# from (cython_impl) import build_ext
__import__(cython_impl, fromlist=['build_ext']).build_ext
@@ -20,22 +20,22 @@ def _have_cython():
pass
return False
-
+
# for compatibility
have_pyrex = _have_cython
-_Extension = get_unpatched(distutils.core.Extension)
-
+_Extension = get_unpatched(distutils.core.Extension)
+
class Extension(_Extension):
"""Extension that uses '.c' files in place of '.pyx' files"""
- def __init__(self, name, sources, *args, **kw):
- # The *args is needed for compatibility as calls may use positional
- # arguments. py_limited_api may be set only via keyword.
- self.py_limited_api = kw.pop("py_limited_api", False)
- _Extension.__init__(self, name, sources, *args, **kw)
-
+ def __init__(self, name, sources, *args, **kw):
+ # The *args is needed for compatibility as calls may use positional
+ # arguments. py_limited_api may be set only via keyword.
+ self.py_limited_api = kw.pop("py_limited_api", False)
+ _Extension.__init__(self, name, sources, *args, **kw)
+
def _convert_pyx_sources_to_lang(self):
"""
Replace sources with .pyx extensions to sources with the target
@@ -50,6 +50,6 @@ class Extension(_Extension):
sub = functools.partial(re.sub, '.pyx$', target_ext)
self.sources = list(map(sub, self.sources))
-
+
class Library(Extension):
"""Just like a regular Extension, but built as a library instead"""
diff --git a/contrib/python/setuptools/py3/setuptools/glob.py b/contrib/python/setuptools/py3/setuptools/glob.py
index 87062b8187..212260e3e4 100644
--- a/contrib/python/setuptools/py3/setuptools/glob.py
+++ b/contrib/python/setuptools/py3/setuptools/glob.py
@@ -1,167 +1,167 @@
-"""
-Filename globbing utility. Mostly a copy of `glob` from Python 3.5.
-
-Changes include:
- * `yield from` and PEP3102 `*` removed.
- * Hidden files are not ignored.
-"""
-
-import os
-import re
-import fnmatch
-
-__all__ = ["glob", "iglob", "escape"]
-
-
-def glob(pathname, recursive=False):
- """Return a list of paths matching a pathname pattern.
-
- The pattern may contain simple shell-style wildcards a la
- fnmatch. However, unlike fnmatch, filenames starting with a
- dot are special cases that are not matched by '*' and '?'
- patterns.
-
- If recursive is true, the pattern '**' will match any files and
- zero or more directories and subdirectories.
- """
- return list(iglob(pathname, recursive=recursive))
-
-
-def iglob(pathname, recursive=False):
- """Return an iterator which yields the paths matching a pathname pattern.
-
- The pattern may contain simple shell-style wildcards a la
- fnmatch. However, unlike fnmatch, filenames starting with a
- dot are special cases that are not matched by '*' and '?'
- patterns.
-
- If recursive is true, the pattern '**' will match any files and
- zero or more directories and subdirectories.
- """
- it = _iglob(pathname, recursive)
- if recursive and _isrecursive(pathname):
- s = next(it) # skip empty string
- assert not s
- return it
-
-
-def _iglob(pathname, recursive):
- dirname, basename = os.path.split(pathname)
+"""
+Filename globbing utility. Mostly a copy of `glob` from Python 3.5.
+
+Changes include:
+ * `yield from` and PEP3102 `*` removed.
+ * Hidden files are not ignored.
+"""
+
+import os
+import re
+import fnmatch
+
+__all__ = ["glob", "iglob", "escape"]
+
+
+def glob(pathname, recursive=False):
+ """Return a list of paths matching a pathname pattern.
+
+ The pattern may contain simple shell-style wildcards a la
+ fnmatch. However, unlike fnmatch, filenames starting with a
+ dot are special cases that are not matched by '*' and '?'
+ patterns.
+
+ If recursive is true, the pattern '**' will match any files and
+ zero or more directories and subdirectories.
+ """
+ return list(iglob(pathname, recursive=recursive))
+
+
+def iglob(pathname, recursive=False):
+ """Return an iterator which yields the paths matching a pathname pattern.
+
+ The pattern may contain simple shell-style wildcards a la
+ fnmatch. However, unlike fnmatch, filenames starting with a
+ dot are special cases that are not matched by '*' and '?'
+ patterns.
+
+ If recursive is true, the pattern '**' will match any files and
+ zero or more directories and subdirectories.
+ """
+ it = _iglob(pathname, recursive)
+ if recursive and _isrecursive(pathname):
+ s = next(it) # skip empty string
+ assert not s
+ return it
+
+
+def _iglob(pathname, recursive):
+ dirname, basename = os.path.split(pathname)
glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1
- if not has_magic(pathname):
- if basename:
- if os.path.lexists(pathname):
- yield pathname
- else:
- # Patterns ending with a slash should match only directories
- if os.path.isdir(dirname):
- yield pathname
- return
-
- if not dirname:
+ if not has_magic(pathname):
+ if basename:
+ if os.path.lexists(pathname):
+ yield pathname
+ else:
+ # Patterns ending with a slash should match only directories
+ if os.path.isdir(dirname):
+ yield pathname
+ return
+
+ if not dirname:
yield from glob_in_dir(dirname, basename)
- return
- # `os.path.split()` returns the argument itself as a dirname if it is a
- # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
- # contains magic characters (i.e. r'\\?\C:').
- if dirname != pathname and has_magic(dirname):
- dirs = _iglob(dirname, recursive)
- else:
- dirs = [dirname]
+ return
+ # `os.path.split()` returns the argument itself as a dirname if it is a
+ # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
+ # contains magic characters (i.e. r'\\?\C:').
+ if dirname != pathname and has_magic(dirname):
+ dirs = _iglob(dirname, recursive)
+ else:
+ dirs = [dirname]
if not has_magic(basename):
- glob_in_dir = glob0
- for dirname in dirs:
- for name in glob_in_dir(dirname, basename):
- yield os.path.join(dirname, name)
-
-
-# These 2 helper functions non-recursively glob inside a literal directory.
-# They return a list of basenames. `glob1` accepts a pattern while `glob0`
-# takes a literal basename (so it only has to check for its existence).
-
-
-def glob1(dirname, pattern):
- if not dirname:
+ glob_in_dir = glob0
+ for dirname in dirs:
+ for name in glob_in_dir(dirname, basename):
+ yield os.path.join(dirname, name)
+
+
+# These 2 helper functions non-recursively glob inside a literal directory.
+# They return a list of basenames. `glob1` accepts a pattern while `glob0`
+# takes a literal basename (so it only has to check for its existence).
+
+
+def glob1(dirname, pattern):
+ if not dirname:
if isinstance(pattern, bytes):
- dirname = os.curdir.encode('ASCII')
- else:
- dirname = os.curdir
- try:
- names = os.listdir(dirname)
- except OSError:
- return []
- return fnmatch.filter(names, pattern)
-
-
-def glob0(dirname, basename):
- if not basename:
- # `os.path.split()` returns an empty basename for paths ending with a
- # directory separator. 'q*x/' should match only directories.
- if os.path.isdir(dirname):
- return [basename]
- else:
- if os.path.lexists(os.path.join(dirname, basename)):
- return [basename]
- return []
-
-
-# This helper function recursively yields relative pathnames inside a literal
-# directory.
-
-
-def glob2(dirname, pattern):
- assert _isrecursive(pattern)
- yield pattern[:0]
- for x in _rlistdir(dirname):
- yield x
-
-
-# Recursively yields relative pathnames inside a literal directory.
-def _rlistdir(dirname):
- if not dirname:
+ dirname = os.curdir.encode('ASCII')
+ else:
+ dirname = os.curdir
+ try:
+ names = os.listdir(dirname)
+ except OSError:
+ return []
+ return fnmatch.filter(names, pattern)
+
+
+def glob0(dirname, basename):
+ if not basename:
+ # `os.path.split()` returns an empty basename for paths ending with a
+ # directory separator. 'q*x/' should match only directories.
+ if os.path.isdir(dirname):
+ return [basename]
+ else:
+ if os.path.lexists(os.path.join(dirname, basename)):
+ return [basename]
+ return []
+
+
+# This helper function recursively yields relative pathnames inside a literal
+# directory.
+
+
+def glob2(dirname, pattern):
+ assert _isrecursive(pattern)
+ yield pattern[:0]
+ for x in _rlistdir(dirname):
+ yield x
+
+
+# Recursively yields relative pathnames inside a literal directory.
+def _rlistdir(dirname):
+ if not dirname:
if isinstance(dirname, bytes):
dirname = os.curdir.encode('ASCII')
- else:
- dirname = os.curdir
- try:
- names = os.listdir(dirname)
- except os.error:
- return
- for x in names:
- yield x
- path = os.path.join(dirname, x) if dirname else x
- for y in _rlistdir(path):
- yield os.path.join(x, y)
-
-
-magic_check = re.compile('([*?[])')
-magic_check_bytes = re.compile(b'([*?[])')
-
-
-def has_magic(s):
+ else:
+ dirname = os.curdir
+ try:
+ names = os.listdir(dirname)
+ except os.error:
+ return
+ for x in names:
+ yield x
+ path = os.path.join(dirname, x) if dirname else x
+ for y in _rlistdir(path):
+ yield os.path.join(x, y)
+
+
+magic_check = re.compile('([*?[])')
+magic_check_bytes = re.compile(b'([*?[])')
+
+
+def has_magic(s):
if isinstance(s, bytes):
- match = magic_check_bytes.search(s)
- else:
- match = magic_check.search(s)
- return match is not None
-
-
-def _isrecursive(pattern):
+ match = magic_check_bytes.search(s)
+ else:
+ match = magic_check.search(s)
+ return match is not None
+
+
+def _isrecursive(pattern):
if isinstance(pattern, bytes):
- return pattern == b'**'
- else:
- return pattern == '**'
-
-
-def escape(pathname):
- """Escape all special characters.
- """
- # Escaping is done by wrapping any of "*?[" between square brackets.
- # Metacharacters do not work in the drive part and shouldn't be escaped.
- drive, pathname = os.path.splitdrive(pathname)
+ return pattern == b'**'
+ else:
+ return pattern == '**'
+
+
+def escape(pathname):
+ """Escape all special characters.
+ """
+ # Escaping is done by wrapping any of "*?[" between square brackets.
+ # Metacharacters do not work in the drive part and shouldn't be escaped.
+ drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
- pathname = magic_check_bytes.sub(br'[\1]', pathname)
- else:
- pathname = magic_check.sub(r'[\1]', pathname)
- return drive + pathname
+ pathname = magic_check_bytes.sub(br'[\1]', pathname)
+ else:
+ pathname = magic_check.sub(r'[\1]', pathname)
+ return drive + pathname
diff --git a/contrib/python/setuptools/py3/setuptools/launch.py b/contrib/python/setuptools/py3/setuptools/launch.py
index 0208fdf33b..5ec4acfc20 100644
--- a/contrib/python/setuptools/py3/setuptools/launch.py
+++ b/contrib/python/setuptools/py3/setuptools/launch.py
@@ -11,26 +11,26 @@ import sys
def run():
- """
- Run the script in sys.argv[1] as if it had
- been invoked naturally.
- """
- __builtins__
- script_name = sys.argv[1]
- namespace = dict(
- __file__=script_name,
- __name__='__main__',
- __doc__=None,
- )
- sys.argv[:] = sys.argv[1:]
+ """
+ Run the script in sys.argv[1] as if it had
+ been invoked naturally.
+ """
+ __builtins__
+ script_name = sys.argv[1]
+ namespace = dict(
+ __file__=script_name,
+ __name__='__main__',
+ __doc__=None,
+ )
+ sys.argv[:] = sys.argv[1:]
- open_ = getattr(tokenize, 'open', open)
+ open_ = getattr(tokenize, 'open', open)
with open_(script_name) as fid:
script = fid.read()
- norm_script = script.replace('\\r\\n', '\\n')
- code = compile(norm_script, script_name, 'exec')
- exec(code, namespace)
+ norm_script = script.replace('\\r\\n', '\\n')
+ code = compile(norm_script, script_name, 'exec')
+ exec(code, namespace)
if __name__ == '__main__':
- run()
+ run()
diff --git a/contrib/python/setuptools/py3/setuptools/monkey.py b/contrib/python/setuptools/py3/setuptools/monkey.py
index fb36dc1a97..701ca62c25 100644
--- a/contrib/python/setuptools/py3/setuptools/monkey.py
+++ b/contrib/python/setuptools/py3/setuptools/monkey.py
@@ -1,24 +1,24 @@
-"""
-Monkey patching of distutils.
-"""
-
-import sys
-import distutils.filelist
-import platform
-import types
-import functools
+"""
+Monkey patching of distutils.
+"""
+
+import sys
+import distutils.filelist
+import platform
+import types
+import functools
from importlib import import_module
-import inspect
-
-import setuptools
-
-__all__ = []
-"""
-Everything is private. Contact the project team
-if you think you need this functionality.
-"""
-
-
+import inspect
+
+import setuptools
+
+__all__ = []
+"""
+Everything is private. Contact the project team
+if you think you need this functionality.
+"""
+
+
def _get_mro(cls):
"""
Returns the bases classes for cls sorted by the MRO.
@@ -33,145 +33,145 @@ def _get_mro(cls):
return inspect.getmro(cls)
-def get_unpatched(item):
- lookup = (
+def get_unpatched(item):
+ lookup = (
get_unpatched_class if isinstance(item, type) else
- get_unpatched_function if isinstance(item, types.FunctionType) else
- lambda item: None
- )
- return lookup(item)
-
-
-def get_unpatched_class(cls):
- """Protect against re-patching the distutils if reloaded
-
- Also ensures that no other distutils extension monkeypatched the distutils
- first.
- """
- external_bases = (
- cls
+ get_unpatched_function if isinstance(item, types.FunctionType) else
+ lambda item: None
+ )
+ return lookup(item)
+
+
+def get_unpatched_class(cls):
+ """Protect against re-patching the distutils if reloaded
+
+ Also ensures that no other distutils extension monkeypatched the distutils
+ first.
+ """
+ external_bases = (
+ cls
for cls in _get_mro(cls)
- if not cls.__module__.startswith('setuptools')
- )
- base = next(external_bases)
- if not base.__module__.startswith('distutils'):
- msg = "distutils has already been patched by %r" % cls
- raise AssertionError(msg)
- return base
-
-
-def patch_all():
- # we can't patch distutils.cmd, alas
- distutils.core.Command = setuptools.Command
-
- has_issue_12885 = sys.version_info <= (3, 5, 3)
-
- if has_issue_12885:
- # fix findall bug in distutils (http://bugs.python.org/issue12885)
- distutils.filelist.findall = setuptools.findall
-
- needs_warehouse = (
- sys.version_info < (2, 7, 13)
- or
- (3, 4) < sys.version_info < (3, 4, 6)
- or
- (3, 5) < sys.version_info <= (3, 5, 3)
- )
-
- if needs_warehouse:
- warehouse = 'https://upload.pypi.org/legacy/'
- distutils.config.PyPIRCCommand.DEFAULT_REPOSITORY = warehouse
-
+ if not cls.__module__.startswith('setuptools')
+ )
+ base = next(external_bases)
+ if not base.__module__.startswith('distutils'):
+ msg = "distutils has already been patched by %r" % cls
+ raise AssertionError(msg)
+ return base
+
+
+def patch_all():
+ # we can't patch distutils.cmd, alas
+ distutils.core.Command = setuptools.Command
+
+ has_issue_12885 = sys.version_info <= (3, 5, 3)
+
+ if has_issue_12885:
+ # fix findall bug in distutils (http://bugs.python.org/issue12885)
+ distutils.filelist.findall = setuptools.findall
+
+ needs_warehouse = (
+ sys.version_info < (2, 7, 13)
+ or
+ (3, 4) < sys.version_info < (3, 4, 6)
+ or
+ (3, 5) < sys.version_info <= (3, 5, 3)
+ )
+
+ if needs_warehouse:
+ warehouse = 'https://upload.pypi.org/legacy/'
+ distutils.config.PyPIRCCommand.DEFAULT_REPOSITORY = warehouse
+
_patch_distribution_metadata()
-
- # Install Distribution throughout the distutils
- for module in distutils.dist, distutils.core, distutils.cmd:
- module.Distribution = setuptools.dist.Distribution
-
- # Install the patched Extension
- distutils.core.Extension = setuptools.extension.Extension
- distutils.extension.Extension = setuptools.extension.Extension
- if 'distutils.command.build_ext' in sys.modules:
- sys.modules['distutils.command.build_ext'].Extension = (
- setuptools.extension.Extension
- )
-
- patch_for_msvc_specialized_compiler()
-
-
+
+ # Install Distribution throughout the distutils
+ for module in distutils.dist, distutils.core, distutils.cmd:
+ module.Distribution = setuptools.dist.Distribution
+
+ # Install the patched Extension
+ distutils.core.Extension = setuptools.extension.Extension
+ distutils.extension.Extension = setuptools.extension.Extension
+ if 'distutils.command.build_ext' in sys.modules:
+ sys.modules['distutils.command.build_ext'].Extension = (
+ setuptools.extension.Extension
+ )
+
+ patch_for_msvc_specialized_compiler()
+
+
def _patch_distribution_metadata():
"""Patch write_pkg_file and read_pkg_file for higher metadata standards"""
for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'):
new_val = getattr(setuptools.dist, attr)
setattr(distutils.dist.DistributionMetadata, attr, new_val)
-
-
-def patch_func(replacement, target_mod, func_name):
- """
- Patch func_name in target_mod with replacement
-
- Important - original must be resolved by name to avoid
- patching an already patched function.
- """
- original = getattr(target_mod, func_name)
-
- # set the 'unpatched' attribute on the replacement to
- # point to the original.
- vars(replacement).setdefault('unpatched', original)
-
- # replace the function in the original module
- setattr(target_mod, func_name, replacement)
-
-
-def get_unpatched_function(candidate):
- return getattr(candidate, 'unpatched')
-
-
-def patch_for_msvc_specialized_compiler():
- """
- Patch functions in distutils to use standalone Microsoft Visual C++
- compilers.
- """
- # import late to avoid circular imports on Python < 3.5
- msvc = import_module('setuptools.msvc')
-
- if platform.system() != 'Windows':
+
+
+def patch_func(replacement, target_mod, func_name):
+ """
+ Patch func_name in target_mod with replacement
+
+ Important - original must be resolved by name to avoid
+ patching an already patched function.
+ """
+ original = getattr(target_mod, func_name)
+
+ # set the 'unpatched' attribute on the replacement to
+ # point to the original.
+ vars(replacement).setdefault('unpatched', original)
+
+ # replace the function in the original module
+ setattr(target_mod, func_name, replacement)
+
+
+def get_unpatched_function(candidate):
+ return getattr(candidate, 'unpatched')
+
+
+def patch_for_msvc_specialized_compiler():
+ """
+ Patch functions in distutils to use standalone Microsoft Visual C++
+ compilers.
+ """
+ # import late to avoid circular imports on Python < 3.5
+ msvc = import_module('setuptools.msvc')
+
+ if platform.system() != 'Windows':
# Compilers only available on Microsoft Windows
- return
-
- def patch_params(mod_name, func_name):
- """
- Prepare the parameters for patch_func to patch indicated function.
- """
- repl_prefix = 'msvc9_' if 'msvc9' in mod_name else 'msvc14_'
- repl_name = repl_prefix + func_name.lstrip('_')
- repl = getattr(msvc, repl_name)
- mod = import_module(mod_name)
- if not hasattr(mod, func_name):
- raise ImportError(func_name)
- return repl, mod, func_name
-
- # Python 2.7 to 3.4
- msvc9 = functools.partial(patch_params, 'distutils.msvc9compiler')
-
- # Python 3.5+
- msvc14 = functools.partial(patch_params, 'distutils._msvccompiler')
-
- try:
- # Patch distutils.msvc9compiler
- patch_func(*msvc9('find_vcvarsall'))
- patch_func(*msvc9('query_vcvarsall'))
- except ImportError:
- pass
-
- try:
- # Patch distutils._msvccompiler._get_vc_env
- patch_func(*msvc14('_get_vc_env'))
- except ImportError:
- pass
-
- try:
- # Patch distutils._msvccompiler.gen_lib_options for Numpy
- patch_func(*msvc14('gen_lib_options'))
- except ImportError:
- pass
+ return
+
+ def patch_params(mod_name, func_name):
+ """
+ Prepare the parameters for patch_func to patch indicated function.
+ """
+ repl_prefix = 'msvc9_' if 'msvc9' in mod_name else 'msvc14_'
+ repl_name = repl_prefix + func_name.lstrip('_')
+ repl = getattr(msvc, repl_name)
+ mod = import_module(mod_name)
+ if not hasattr(mod, func_name):
+ raise ImportError(func_name)
+ return repl, mod, func_name
+
+ # Python 2.7 to 3.4
+ msvc9 = functools.partial(patch_params, 'distutils.msvc9compiler')
+
+ # Python 3.5+
+ msvc14 = functools.partial(patch_params, 'distutils._msvccompiler')
+
+ try:
+ # Patch distutils.msvc9compiler
+ patch_func(*msvc9('find_vcvarsall'))
+ patch_func(*msvc9('query_vcvarsall'))
+ except ImportError:
+ pass
+
+ try:
+ # Patch distutils._msvccompiler._get_vc_env
+ patch_func(*msvc14('_get_vc_env'))
+ except ImportError:
+ pass
+
+ try:
+ # Patch distutils._msvccompiler.gen_lib_options for Numpy
+ patch_func(*msvc14('gen_lib_options'))
+ except ImportError:
+ pass
diff --git a/contrib/python/setuptools/py3/setuptools/msvc.py b/contrib/python/setuptools/py3/setuptools/msvc.py
index 281ea1c2af..f7320f790d 100644
--- a/contrib/python/setuptools/py3/setuptools/msvc.py
+++ b/contrib/python/setuptools/py3/setuptools/msvc.py
@@ -1,53 +1,53 @@
-"""
-Improved support for Microsoft Visual C++ compilers.
-
-Known supported compilers:
---------------------------
-Microsoft Visual C++ 9.0:
+"""
+Improved support for Microsoft Visual C++ compilers.
+
+Known supported compilers:
+--------------------------
+Microsoft Visual C++ 9.0:
Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64)
- Microsoft Windows SDK 6.1 (x86, x64, ia64)
+ Microsoft Windows SDK 6.1 (x86, x64, ia64)
Microsoft Windows SDK 7.0 (x86, x64, ia64)
-
-Microsoft Visual C++ 10.0:
- Microsoft Windows SDK 7.1 (x86, x64, ia64)
-
+
+Microsoft Visual C++ 10.0:
+ Microsoft Windows SDK 7.1 (x86, x64, ia64)
+
Microsoft Visual C++ 14.X:
- Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)
+ Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)
Microsoft Visual Studio Build Tools 2017 (x86, x64, arm, arm64)
Microsoft Visual Studio Build Tools 2019 (x86, x64, arm, arm64)
This may also support compilers shipped with compatible Visual Studio versions.
-"""
-
+"""
+
import json
from io import open
from os import listdir, pathsep
from os.path import join, isfile, isdir, dirname
-import sys
+import sys
import contextlib
-import platform
-import itertools
+import platform
+import itertools
import subprocess
-import distutils.errors
+import distutils.errors
from setuptools.extern.packaging.version import LegacyVersion
from setuptools.extern.more_itertools import unique_everseen
-
-from .monkey import get_unpatched
-
-if platform.system() == 'Windows':
+
+from .monkey import get_unpatched
+
+if platform.system() == 'Windows':
import winreg
from os import environ
-else:
+else:
# Mock winreg and environ so the module can be imported on this platform.
-
- class winreg:
- HKEY_USERS = None
- HKEY_CURRENT_USER = None
- HKEY_LOCAL_MACHINE = None
- HKEY_CLASSES_ROOT = None
-
+
+ class winreg:
+ HKEY_USERS = None
+ HKEY_CURRENT_USER = None
+ HKEY_LOCAL_MACHINE = None
+ HKEY_CLASSES_ROOT = None
+
environ = dict()
-
+
_msvc9_suppress_errors = (
# msvc9compiler isn't available on some platforms
ImportError,
@@ -57,92 +57,92 @@ _msvc9_suppress_errors = (
distutils.errors.DistutilsPlatformError,
)
-try:
- from distutils.msvc9compiler import Reg
+try:
+ from distutils.msvc9compiler import Reg
except _msvc9_suppress_errors:
- pass
-
-
-def msvc9_find_vcvarsall(version):
- """
- Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
+ pass
+
+
+def msvc9_find_vcvarsall(version):
+ """
+ Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
compiler build for Python
(VCForPython / Microsoft Visual C++ Compiler for Python 2.7).
-
+
Fall back to original behavior when the standalone compiler is not
available.
- Redirect the path of "vcvarsall.bat".
-
- Parameters
- ----------
- version: float
- Required Microsoft Visual C++ version.
-
- Return
- ------
+ Redirect the path of "vcvarsall.bat".
+
+ Parameters
+ ----------
+ version: float
+ Required Microsoft Visual C++ version.
+
+ Return
+ ------
str
vcvarsall.bat path
- """
+ """
vc_base = r'Software\%sMicrosoft\DevDiv\VCForPython\%0.1f'
key = vc_base % ('', version)
- try:
- # Per-user installs register the compiler path here
- productdir = Reg.get_value(key, "installdir")
- except KeyError:
- try:
- # All-user installs on a 64-bit system register here
+ try:
+ # Per-user installs register the compiler path here
+ productdir = Reg.get_value(key, "installdir")
+ except KeyError:
+ try:
+ # All-user installs on a 64-bit system register here
key = vc_base % ('Wow6432Node\\', version)
- productdir = Reg.get_value(key, "installdir")
- except KeyError:
- productdir = None
-
- if productdir:
+ productdir = Reg.get_value(key, "installdir")
+ except KeyError:
+ productdir = None
+
+ if productdir:
vcvarsall = join(productdir, "vcvarsall.bat")
if isfile(vcvarsall):
- return vcvarsall
-
- return get_unpatched(msvc9_find_vcvarsall)(version)
-
-
-def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs):
- """
+ return vcvarsall
+
+ return get_unpatched(msvc9_find_vcvarsall)(version)
+
+
+def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs):
+ """
Patched "distutils.msvc9compiler.query_vcvarsall" for support extra
Microsoft Visual C++ 9.0 and 10.0 compilers.
-
- Set environment without use of "vcvarsall.bat".
-
- Parameters
- ----------
- ver: float
- Required Microsoft Visual C++ version.
- arch: str
- Target architecture.
-
- Return
- ------
+
+ Set environment without use of "vcvarsall.bat".
+
+ Parameters
+ ----------
+ ver: float
+ Required Microsoft Visual C++ version.
+ arch: str
+ Target architecture.
+
+ Return
+ ------
dict
environment
- """
+ """
# Try to get environment from vcvarsall.bat (Classical way)
- try:
- orig = get_unpatched(msvc9_query_vcvarsall)
- return orig(ver, arch, *args, **kwargs)
- except distutils.errors.DistutilsPlatformError:
- # Pass error if Vcvarsall.bat is missing
- pass
- except ValueError:
- # Pass error if environment not set after executing vcvarsall.bat
- pass
-
- # If error, try to set environment directly
- try:
- return EnvironmentInfo(arch, ver).return_env()
- except distutils.errors.DistutilsPlatformError as exc:
- _augment_exception(exc, ver, arch)
- raise
-
-
+ try:
+ orig = get_unpatched(msvc9_query_vcvarsall)
+ return orig(ver, arch, *args, **kwargs)
+ except distutils.errors.DistutilsPlatformError:
+ # Pass error if Vcvarsall.bat is missing
+ pass
+ except ValueError:
+ # Pass error if environment not set after executing vcvarsall.bat
+ pass
+
+ # If error, try to set environment directly
+ try:
+ return EnvironmentInfo(arch, ver).return_env()
+ except distutils.errors.DistutilsPlatformError as exc:
+ _augment_exception(exc, ver, arch)
+ raise
+
+
def _msvc14_find_vc2015():
"""Python 3.8 "distutils/_msvccompiler.py" backport"""
try:
@@ -293,98 +293,98 @@ def _msvc14_get_vc_env(plat_spec):
return env
-def msvc14_get_vc_env(plat_spec):
- """
+def msvc14_get_vc_env(plat_spec):
+ """
Patched "distutils._msvccompiler._get_vc_env" for support extra
Microsoft Visual C++ 14.X compilers.
-
- Set environment without use of "vcvarsall.bat".
-
- Parameters
- ----------
- plat_spec: str
- Target architecture.
-
- Return
- ------
+
+ Set environment without use of "vcvarsall.bat".
+
+ Parameters
+ ----------
+ plat_spec: str
+ Target architecture.
+
+ Return
+ ------
dict
environment
- """
-
+ """
+
# Always use backport from CPython 3.8
- try:
+ try:
return _msvc14_get_vc_env(plat_spec)
- except distutils.errors.DistutilsPlatformError as exc:
- _augment_exception(exc, 14.0)
- raise
-
-
-def msvc14_gen_lib_options(*args, **kwargs):
- """
- Patched "distutils._msvccompiler.gen_lib_options" for fix
- compatibility between "numpy.distutils" and "distutils._msvccompiler"
- (for Numpy < 1.11.2)
- """
- if "numpy.distutils" in sys.modules:
- import numpy as np
- if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
- return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
- return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)
-
-
-def _augment_exception(exc, version, arch=''):
- """
- Add details to the exception message to help guide the user
- as to what action will resolve it.
- """
- # Error if MSVC++ directory not found or environment not set
- message = exc.args[0]
-
- if "vcvarsall" in message.lower() or "visual c" in message.lower():
- # Special error message if MSVC++ not installed
+ except distutils.errors.DistutilsPlatformError as exc:
+ _augment_exception(exc, 14.0)
+ raise
+
+
+def msvc14_gen_lib_options(*args, **kwargs):
+ """
+ Patched "distutils._msvccompiler.gen_lib_options" for fix
+ compatibility between "numpy.distutils" and "distutils._msvccompiler"
+ (for Numpy < 1.11.2)
+ """
+ if "numpy.distutils" in sys.modules:
+ import numpy as np
+ if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
+ return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
+ return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)
+
+
+def _augment_exception(exc, version, arch=''):
+ """
+ Add details to the exception message to help guide the user
+ as to what action will resolve it.
+ """
+ # Error if MSVC++ directory not found or environment not set
+ message = exc.args[0]
+
+ 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} or greater is required.'
- message = tmpl.format(**locals())
- msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
- if version == 9.0:
- if arch.lower().find('ia64') > -1:
- # For VC++ 9.0, if IA64 support is needed, redirect user
+ message = tmpl.format(**locals())
+ msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
+ if version == 9.0:
+ if arch.lower().find('ia64') > -1:
+ # For VC++ 9.0, if IA64 support is needed, redirect user
# to Windows SDK 7.0.
# Note: No download link available from Microsoft.
message += ' Get it with "Microsoft Windows SDK 7.0"'
- else:
- # For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
- # This redirection link is maintained by Microsoft.
- # Contact vspython@microsoft.com if it needs updating.
- message += ' Get it from http://aka.ms/vcpython27'
- elif version == 10.0:
- # For VC++ 10.0 Redirect user to Windows SDK 7.1
- message += ' Get it with "Microsoft Windows SDK 7.1": '
- message += msdownload % 8279
- elif version >= 14.0:
+ else:
+ # For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
+ # This redirection link is maintained by Microsoft.
+ # Contact vspython@microsoft.com if it needs updating.
+ message += ' Get it from http://aka.ms/vcpython27'
+ elif version == 10.0:
+ # For VC++ 10.0 Redirect user to Windows SDK 7.1
+ message += ' Get it with "Microsoft Windows SDK 7.1": '
+ message += msdownload % 8279
+ elif version >= 14.0:
# For VC++ 14.X Redirect user to latest Visual C++ Build Tools
message += (' Get it with "Microsoft C++ Build Tools": '
r'https://visualstudio.microsoft.com'
r'/visual-cpp-build-tools/')
-
- exc.args = (message, )
-
-
-class PlatformInfo:
- """
+
+ exc.args = (message, )
+
+
+class PlatformInfo:
+ """
Current and Target Architectures information.
-
- Parameters
- ----------
- arch: str
- Target architecture.
- """
+
+ Parameters
+ ----------
+ arch: str
+ Target architecture.
+ """
current_cpu = environ.get('processor_architecture', '').lower()
-
- def __init__(self, arch):
- self.arch = arch.lower().replace('x64', 'amd64')
-
- @property
- def target_cpu(self):
+
+ def __init__(self, arch):
+ self.arch = arch.lower().replace('x64', 'amd64')
+
+ @property
+ def target_cpu(self):
"""
Return Target CPU architecture.
@@ -393,9 +393,9 @@ class PlatformInfo:
str
Target CPU
"""
- return self.arch[self.arch.find('_') + 1:]
-
- def target_is_x86(self):
+ return self.arch[self.arch.find('_') + 1:]
+
+ def target_is_x86(self):
"""
Return True if target CPU is x86 32 bits..
@@ -404,9 +404,9 @@ class PlatformInfo:
bool
CPU is x86 32 bits
"""
- return self.target_cpu == 'x86'
-
- def current_is_x86(self):
+ return self.target_cpu == 'x86'
+
+ def current_is_x86(self):
"""
Return True if current CPU is x86 32 bits..
@@ -415,282 +415,282 @@ class PlatformInfo:
bool
CPU is x86 32 bits
"""
- return self.current_cpu == 'x86'
-
- def current_dir(self, hidex86=False, x64=False):
- """
- Current platform specific subfolder.
-
- Parameters
- ----------
- hidex86: bool
- return '' and not '\x86' if architecture is x86.
- x64: bool
- return '\x64' and not '\amd64' if architecture is amd64.
-
- Return
- ------
+ return self.current_cpu == 'x86'
+
+ def current_dir(self, hidex86=False, x64=False):
+ """
+ Current platform specific subfolder.
+
+ Parameters
+ ----------
+ hidex86: bool
+ return '' and not '\x86' if architecture is x86.
+ x64: bool
+ return '\x64' and not '\amd64' if architecture is amd64.
+
+ Return
+ ------
str
subfolder: '\target', or '' (see hidex86 parameter)
- """
- return (
- '' if (self.current_cpu == 'x86' and hidex86) else
- r'\x64' if (self.current_cpu == 'amd64' and x64) else
- r'\%s' % self.current_cpu
- )
-
- def target_dir(self, hidex86=False, x64=False):
- r"""
- Target platform specific subfolder.
-
- Parameters
- ----------
- hidex86: bool
- return '' and not '\x86' if architecture is x86.
- x64: bool
- return '\x64' and not '\amd64' if architecture is amd64.
-
- Return
- ------
+ """
+ return (
+ '' if (self.current_cpu == 'x86' and hidex86) else
+ r'\x64' if (self.current_cpu == 'amd64' and x64) else
+ r'\%s' % self.current_cpu
+ )
+
+ def target_dir(self, hidex86=False, x64=False):
+ r"""
+ Target platform specific subfolder.
+
+ Parameters
+ ----------
+ hidex86: bool
+ return '' and not '\x86' if architecture is x86.
+ x64: bool
+ return '\x64' and not '\amd64' if architecture is amd64.
+
+ Return
+ ------
str
subfolder: '\current', or '' (see hidex86 parameter)
- """
- return (
- '' if (self.target_cpu == 'x86' and hidex86) else
- r'\x64' if (self.target_cpu == 'amd64' and x64) else
- r'\%s' % self.target_cpu
- )
-
- def cross_dir(self, forcex86=False):
- r"""
- Cross platform specific subfolder.
-
- Parameters
- ----------
- forcex86: bool
+ """
+ return (
+ '' if (self.target_cpu == 'x86' and hidex86) else
+ r'\x64' if (self.target_cpu == 'amd64' and x64) else
+ r'\%s' % self.target_cpu
+ )
+
+ def cross_dir(self, forcex86=False):
+ r"""
+ Cross platform specific subfolder.
+
+ Parameters
+ ----------
+ forcex86: bool
Use 'x86' as current architecture even if current architecture is
- not x86.
-
- Return
- ------
+ not x86.
+
+ Return
+ ------
str
subfolder: '' if target architecture is current architecture,
- '\current_target' if not.
- """
- current = 'x86' if forcex86 else self.current_cpu
- return (
- '' if self.target_cpu == current else
- self.target_dir().replace('\\', '\\%s_' % current)
- )
-
-
-class RegistryInfo:
- """
+ '\current_target' if not.
+ """
+ current = 'x86' if forcex86 else self.current_cpu
+ return (
+ '' if self.target_cpu == current else
+ self.target_dir().replace('\\', '\\%s_' % current)
+ )
+
+
+class RegistryInfo:
+ """
Microsoft Visual Studio related registry information.
-
- Parameters
- ----------
- platform_info: PlatformInfo
- "PlatformInfo" instance.
- """
- HKEYS = (winreg.HKEY_USERS,
- winreg.HKEY_CURRENT_USER,
- winreg.HKEY_LOCAL_MACHINE,
- winreg.HKEY_CLASSES_ROOT)
-
- def __init__(self, platform_info):
- self.pi = platform_info
-
- @property
- def visualstudio(self):
- """
- Microsoft Visual Studio root registry key.
+
+ Parameters
+ ----------
+ platform_info: PlatformInfo
+ "PlatformInfo" instance.
+ """
+ HKEYS = (winreg.HKEY_USERS,
+ winreg.HKEY_CURRENT_USER,
+ winreg.HKEY_LOCAL_MACHINE,
+ winreg.HKEY_CLASSES_ROOT)
+
+ def __init__(self, platform_info):
+ self.pi = platform_info
+
+ @property
+ def visualstudio(self):
+ """
+ Microsoft Visual Studio root registry key.
Return
------
str
Registry key
- """
- return 'VisualStudio'
-
- @property
- def sxs(self):
- """
- Microsoft Visual Studio SxS registry key.
+ """
+ return 'VisualStudio'
+
+ @property
+ def sxs(self):
+ """
+ Microsoft Visual Studio SxS registry key.
Return
------
str
Registry key
- """
+ """
return join(self.visualstudio, 'SxS')
-
- @property
- def vc(self):
- """
- Microsoft Visual C++ VC7 registry key.
+
+ @property
+ def vc(self):
+ """
+ Microsoft Visual C++ VC7 registry key.
Return
------
str
Registry key
- """
+ """
return join(self.sxs, 'VC7')
-
- @property
- def vs(self):
- """
- Microsoft Visual Studio VS7 registry key.
+
+ @property
+ def vs(self):
+ """
+ Microsoft Visual Studio VS7 registry key.
Return
------
str
Registry key
- """
+ """
return join(self.sxs, 'VS7')
-
- @property
- def vc_for_python(self):
- """
- Microsoft Visual C++ for Python registry key.
+
+ @property
+ def vc_for_python(self):
+ """
+ Microsoft Visual C++ for Python registry key.
Return
------
str
Registry key
- """
- return r'DevDiv\VCForPython'
-
- @property
- def microsoft_sdk(self):
- """
- Microsoft SDK registry key.
+ """
+ return r'DevDiv\VCForPython'
+
+ @property
+ def microsoft_sdk(self):
+ """
+ Microsoft SDK registry key.
Return
------
str
Registry key
- """
- return 'Microsoft SDKs'
-
- @property
- def windows_sdk(self):
- """
- Microsoft Windows/Platform SDK registry key.
+ """
+ return 'Microsoft SDKs'
+
+ @property
+ def windows_sdk(self):
+ """
+ Microsoft Windows/Platform SDK registry key.
Return
------
str
Registry key
- """
+ """
return join(self.microsoft_sdk, 'Windows')
-
- @property
- def netfx_sdk(self):
- """
- Microsoft .NET Framework SDK registry key.
+
+ @property
+ def netfx_sdk(self):
+ """
+ Microsoft .NET Framework SDK registry key.
Return
------
str
Registry key
- """
+ """
return join(self.microsoft_sdk, 'NETFXSDK')
-
- @property
- def windows_kits_roots(self):
- """
- Microsoft Windows Kits Roots registry key.
+
+ @property
+ def windows_kits_roots(self):
+ """
+ Microsoft Windows Kits Roots registry key.
Return
------
str
Registry key
- """
- return r'Windows Kits\Installed Roots'
-
- def microsoft(self, key, x86=False):
- """
- Return key in Microsoft software registry.
-
- Parameters
- ----------
- key: str
- Registry key path where look.
- x86: str
- Force x86 software registry.
-
- Return
- ------
+ """
+ return r'Windows Kits\Installed Roots'
+
+ def microsoft(self, key, x86=False):
+ """
+ Return key in Microsoft software registry.
+
+ Parameters
+ ----------
+ key: str
+ Registry key path where look.
+ x86: str
+ Force x86 software registry.
+
+ Return
+ ------
str
Registry key
- """
+ """
node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node'
return join('Software', node64, 'Microsoft', key)
-
- def lookup(self, key, name):
- """
- Look for values in registry in Microsoft software registry.
-
- Parameters
- ----------
- key: str
- Registry key path where look.
- name: str
- Value name to find.
-
- Return
- ------
+
+ def lookup(self, key, name):
+ """
+ Look for values in registry in Microsoft software registry.
+
+ Parameters
+ ----------
+ key: str
+ Registry key path where look.
+ name: str
+ Value name to find.
+
+ Return
+ ------
str
value
- """
+ """
key_read = winreg.KEY_READ
- openkey = winreg.OpenKey
+ openkey = winreg.OpenKey
closekey = winreg.CloseKey
- ms = self.microsoft
- for hkey in self.HKEYS:
+ ms = self.microsoft
+ for hkey in self.HKEYS:
bkey = None
- try:
+ try:
bkey = openkey(hkey, ms(key), 0, key_read)
- except (OSError, IOError):
- if not self.pi.current_is_x86():
- try:
+ except (OSError, IOError):
+ if not self.pi.current_is_x86():
+ try:
bkey = openkey(hkey, ms(key, True), 0, key_read)
- except (OSError, IOError):
- continue
- else:
- continue
- try:
- return winreg.QueryValueEx(bkey, name)[0]
- except (OSError, IOError):
- pass
+ except (OSError, IOError):
+ continue
+ else:
+ continue
+ try:
+ return winreg.QueryValueEx(bkey, name)[0]
+ except (OSError, IOError):
+ pass
finally:
if bkey:
closekey(bkey)
-
-
-class SystemInfo:
- """
+
+
+class SystemInfo:
+ """
Microsoft Windows and Visual Studio related system information.
-
- Parameters
- ----------
- registry_info: RegistryInfo
- "RegistryInfo" instance.
- vc_ver: float
- Required Microsoft Visual C++ version.
- """
-
- # Variables and properties in this class use originals CamelCase variables
+
+ Parameters
+ ----------
+ registry_info: RegistryInfo
+ "RegistryInfo" instance.
+ vc_ver: float
+ Required Microsoft Visual C++ version.
+ """
+
+ # Variables and properties in this class use originals CamelCase variables
# names from Microsoft source files for more easy comparison.
WinDir = environ.get('WinDir', '')
ProgramFiles = environ.get('ProgramFiles', '')
ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles)
-
- def __init__(self, registry_info, vc_ver=None):
- self.ri = registry_info
- self.pi = self.ri.pi
-
+
+ def __init__(self, registry_info, vc_ver=None):
+ self.ri = registry_info
+ self.pi = self.ri.pi
+
self.known_vs_paths = self.find_programdata_vs_vers()
# Except for VS15+, VC version is aligned with VS version
@@ -698,14 +698,14 @@ class SystemInfo:
vc_ver or self._find_latest_available_vs_ver())
def _find_latest_available_vs_ver(self):
- """
+ """
Find the latest VC version
Return
------
float
version
- """
+ """
reg_vc_vers = self.find_reg_vs_vers()
if not (reg_vc_vers or self.known_vs_paths):
@@ -734,19 +734,19 @@ class SystemInfo:
except (OSError, IOError):
continue
with bkey:
- subkeys, values, _ = winreg.QueryInfoKey(bkey)
- for i in range(values):
+ subkeys, values, _ = winreg.QueryInfoKey(bkey)
+ for i in range(values):
with contextlib.suppress(ValueError):
- ver = float(winreg.EnumValue(bkey, i)[0])
+ ver = float(winreg.EnumValue(bkey, i)[0])
if ver not in vs_vers:
vs_vers.append(ver)
- for i in range(subkeys):
+ for i in range(subkeys):
with contextlib.suppress(ValueError):
- ver = float(winreg.EnumKey(bkey, i))
+ ver = float(winreg.EnumKey(bkey, i))
if ver not in vs_vers:
vs_vers.append(ver)
return sorted(vs_vers)
-
+
def find_programdata_vs_vers(self):
r"""
Find Visual studio 2017+ versions from information in
@@ -806,41 +806,41 @@ class SystemInfo:
"""
return float('.'.join(version.split('.')[:2]))
- @property
- def VSInstallDir(self):
- """
- Microsoft Visual Studio directory.
+ @property
+ def VSInstallDir(self):
+ """
+ Microsoft Visual Studio directory.
Return
------
str
path
- """
- # Default path
+ """
+ # Default path
default = join(self.ProgramFilesx86,
'Microsoft Visual Studio %0.1f' % self.vs_ver)
-
- # Try to get path from registry, if fail use default path
+
+ # Try to get path from registry, if fail use default path
return self.ri.lookup(self.ri.vs, '%0.1f' % self.vs_ver) or default
-
- @property
- def VCInstallDir(self):
- """
- Microsoft Visual C++ directory.
+
+ @property
+ def VCInstallDir(self):
+ """
+ Microsoft Visual C++ directory.
Return
------
str
path
- """
+ """
path = self._guess_vc() or self._guess_vc_legacy()
-
+
if not isdir(path):
- msg = 'Microsoft Visual C++ directory not found'
- raise distutils.errors.DistutilsPlatformError(msg)
-
- return path
-
+ msg = 'Microsoft Visual C++ directory not found'
+ raise distutils.errors.DistutilsPlatformError(msg)
+
+ return path
+
def _guess_vc(self):
"""
Locate Visual C++ for VS2017+.
@@ -891,16 +891,16 @@ class SystemInfo:
# Try to get path from registry, if fail use default path
return self.ri.lookup(self.ri.vc, '%0.1f' % self.vs_ver) or default_vc
- @property
- def WindowsSdkVersion(self):
- """
+ @property
+ def WindowsSdkVersion(self):
+ """
Microsoft Windows SDK versions for specified MSVC++ version.
Return
------
tuple of str
versions
- """
+ """
if self.vs_ver <= 9.0:
return '7.0', '6.1', '6.0a'
elif self.vs_ver == 10.0:
@@ -911,8 +911,8 @@ class SystemInfo:
return '8.1', '8.1a'
elif self.vs_ver >= 14.0:
return '10.0', '8.1'
-
- @property
+
+ @property
def WindowsSdkLastVersion(self):
"""
Microsoft Windows SDK last version.
@@ -926,116 +926,116 @@ class SystemInfo:
@property # noqa: C901
def WindowsSdkDir(self): # noqa: C901 # is too complex (12) # FIXME
- """
- Microsoft Windows SDK directory.
+ """
+ Microsoft Windows SDK directory.
Return
------
str
path
- """
- sdkdir = ''
- for ver in self.WindowsSdkVersion:
- # Try to get it from registry
+ """
+ sdkdir = ''
+ for ver in self.WindowsSdkVersion:
+ # Try to get it from registry
loc = join(self.ri.windows_sdk, 'v%s' % ver)
- sdkdir = self.ri.lookup(loc, 'installationfolder')
- if sdkdir:
- break
+ sdkdir = self.ri.lookup(loc, 'installationfolder')
+ if sdkdir:
+ break
if not sdkdir or not isdir(sdkdir):
- # Try to get "VC++ for Python" version from registry
+ # Try to get "VC++ for Python" version from registry
path = join(self.ri.vc_for_python, '%0.1f' % self.vc_ver)
- install_base = self.ri.lookup(path, 'installdir')
- if install_base:
+ install_base = self.ri.lookup(path, 'installdir')
+ if install_base:
sdkdir = join(install_base, 'WinSDK')
if not sdkdir or not isdir(sdkdir):
- # If fail, use default new path
- for ver in self.WindowsSdkVersion:
- intver = ver[:ver.rfind('.')]
+ # If fail, use default new path
+ for ver in self.WindowsSdkVersion:
+ intver = ver[:ver.rfind('.')]
path = r'Microsoft SDKs\Windows Kits\%s' % intver
d = join(self.ProgramFiles, path)
if isdir(d):
- sdkdir = d
+ sdkdir = d
if not sdkdir or not isdir(sdkdir):
- # If fail, use default old path
- for ver in self.WindowsSdkVersion:
- path = r'Microsoft SDKs\Windows\v%s' % ver
+ # If fail, use default old path
+ for ver in self.WindowsSdkVersion:
+ path = r'Microsoft SDKs\Windows\v%s' % ver
d = join(self.ProgramFiles, path)
if isdir(d):
- sdkdir = d
- if not sdkdir:
- # If fail, use Platform SDK
+ sdkdir = d
+ if not sdkdir:
+ # If fail, use Platform SDK
sdkdir = join(self.VCInstallDir, 'PlatformSDK')
- return sdkdir
-
- @property
- def WindowsSDKExecutablePath(self):
- """
- Microsoft Windows SDK executable directory.
+ return sdkdir
+
+ @property
+ def WindowsSDKExecutablePath(self):
+ """
+ Microsoft Windows SDK executable directory.
Return
------
str
path
- """
- # Find WinSDK NetFx Tools registry dir name
+ """
+ # Find WinSDK NetFx Tools registry dir name
if self.vs_ver <= 11.0:
- netfxver = 35
- arch = ''
- else:
- netfxver = 40
+ netfxver = 35
+ arch = ''
+ else:
+ netfxver = 40
hidex86 = True if self.vs_ver <= 12.0 else False
- arch = self.pi.current_dir(x64=True, hidex86=hidex86)
- fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\', '-'))
-
+ arch = self.pi.current_dir(x64=True, hidex86=hidex86)
+ fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\', '-'))
+
# list all possibles registry paths
- regpaths = []
+ regpaths = []
if self.vs_ver >= 14.0:
- for ver in self.NetFxSdkVersion:
+ for ver in self.NetFxSdkVersion:
regpaths += [join(self.ri.netfx_sdk, ver, fx)]
-
- for ver in self.WindowsSdkVersion:
+
+ for ver in self.WindowsSdkVersion:
regpaths += [join(self.ri.windows_sdk, 'v%sA' % ver, fx)]
-
- # Return installation folder from the more recent path
- for path in regpaths:
- execpath = self.ri.lookup(path, 'installationfolder')
- if execpath:
+
+ # Return installation folder from the more recent path
+ for path in regpaths:
+ execpath = self.ri.lookup(path, 'installationfolder')
+ if execpath:
return execpath
-
- @property
- def FSharpInstallDir(self):
- """
- Microsoft Visual F# directory.
+
+ @property
+ def FSharpInstallDir(self):
+ """
+ Microsoft Visual F# directory.
Return
------
str
path
- """
+ """
path = join(self.ri.visualstudio, r'%0.1f\Setup\F#' % self.vs_ver)
- return self.ri.lookup(path, 'productdir') or ''
-
- @property
- def UniversalCRTSdkDir(self):
- """
- Microsoft Universal CRT SDK directory.
+ return self.ri.lookup(path, 'productdir') or ''
+
+ @property
+ def UniversalCRTSdkDir(self):
+ """
+ Microsoft Universal CRT SDK directory.
Return
------
str
path
- """
- # Set Kit Roots versions for specified MSVC++ version
+ """
+ # Set Kit Roots versions for specified MSVC++ version
vers = ('10', '81') if self.vs_ver >= 14.0 else ()
-
- # Find path of the more recent Kit
- for ver in vers:
- sdkdir = self.ri.lookup(self.ri.windows_kits_roots,
- 'kitsroot%s' % ver)
- if sdkdir:
+
+ # Find path of the more recent Kit
+ for ver in vers:
+ sdkdir = self.ri.lookup(self.ri.windows_kits_roots,
+ 'kitsroot%s' % ver)
+ if sdkdir:
return sdkdir or ''
-
- @property
+
+ @property
def UniversalCRTSdkLastVersion(self):
"""
Microsoft Universal C Runtime SDK last version.
@@ -1048,115 +1048,115 @@ class SystemInfo:
return self._use_last_dir_name(join(self.UniversalCRTSdkDir, 'lib'))
@property
- def NetFxSdkVersion(self):
- """
- Microsoft .NET Framework SDK versions.
+ def NetFxSdkVersion(self):
+ """
+ Microsoft .NET Framework SDK versions.
Return
------
tuple of str
versions
- """
+ """
# Set FxSdk versions for specified VS version
return (('4.7.2', '4.7.1', '4.7',
'4.6.2', '4.6.1', '4.6',
'4.5.2', '4.5.1', '4.5')
if self.vs_ver >= 14.0 else ())
-
- @property
- def NetFxSdkDir(self):
- """
- Microsoft .NET Framework SDK directory.
+
+ @property
+ def NetFxSdkDir(self):
+ """
+ Microsoft .NET Framework SDK directory.
Return
------
str
path
- """
+ """
sdkdir = ''
- for ver in self.NetFxSdkVersion:
+ for ver in self.NetFxSdkVersion:
loc = join(self.ri.netfx_sdk, ver)
- sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
- if sdkdir:
- break
+ sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
+ if sdkdir:
+ break
return sdkdir
-
- @property
- def FrameworkDir32(self):
- """
- Microsoft .NET Framework 32bit directory.
+
+ @property
+ def FrameworkDir32(self):
+ """
+ Microsoft .NET Framework 32bit directory.
Return
------
str
path
- """
- # Default path
+ """
+ # Default path
guess_fw = join(self.WinDir, r'Microsoft.NET\Framework')
-
- # Try to get path from registry, if fail use default path
- return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw
-
- @property
- def FrameworkDir64(self):
- """
- Microsoft .NET Framework 64bit directory.
+
+ # Try to get path from registry, if fail use default path
+ return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw
+
+ @property
+ def FrameworkDir64(self):
+ """
+ Microsoft .NET Framework 64bit directory.
Return
------
str
path
- """
- # Default path
+ """
+ # Default path
guess_fw = join(self.WinDir, r'Microsoft.NET\Framework64')
-
- # Try to get path from registry, if fail use default path
- return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw
-
- @property
- def FrameworkVersion32(self):
- """
- Microsoft .NET Framework 32bit versions.
+
+ # Try to get path from registry, if fail use default path
+ return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw
+
+ @property
+ def FrameworkVersion32(self):
+ """
+ Microsoft .NET Framework 32bit versions.
Return
------
tuple of str
versions
- """
- return self._find_dot_net_versions(32)
-
- @property
- def FrameworkVersion64(self):
- """
- Microsoft .NET Framework 64bit versions.
+ """
+ return self._find_dot_net_versions(32)
+
+ @property
+ def FrameworkVersion64(self):
+ """
+ Microsoft .NET Framework 64bit versions.
Return
------
tuple of str
versions
- """
- return self._find_dot_net_versions(64)
-
+ """
+ return self._find_dot_net_versions(64)
+
def _find_dot_net_versions(self, bits):
- """
- Find Microsoft .NET Framework versions.
-
- Parameters
- ----------
- bits: int
- Platform number of bits: 32 or 64.
+ """
+ Find Microsoft .NET Framework versions.
+
+ Parameters
+ ----------
+ bits: int
+ Platform number of bits: 32 or 64.
Return
------
tuple of str
versions
- """
+ """
# Find actual .NET version in registry
reg_ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits)
dot_net_dir = getattr(self, 'FrameworkDir%d' % bits)
ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or ''
-
- # Set .NET versions for specified MSVC++ version
+
+ # Set .NET versions for specified MSVC++ version
if self.vs_ver >= 12.0:
return ver, 'v4.0'
elif self.vs_ver >= 10.0:
@@ -1165,12 +1165,12 @@ class SystemInfo:
return 'v3.5', 'v2.0.50727'
elif self.vs_ver == 8.0:
return 'v3.0', 'v2.0.50727'
-
+
@staticmethod
def _use_last_dir_name(path, prefix=''):
"""
Return name of the last dir in path or '' if no dir found.
-
+
Parameters
----------
path: str
@@ -1192,40 +1192,40 @@ class SystemInfo:
return next(matching_dirs, None) or ''
-class EnvironmentInfo:
- """
- Return environment variables for specified Microsoft Visual C++ version
- and platform : Lib, Include, Path and libpath.
-
+class EnvironmentInfo:
+ """
+ Return environment variables for specified Microsoft Visual C++ version
+ and platform : Lib, Include, Path and libpath.
+
This function is compatible with Microsoft Visual C++ 9.0 to 14.X.
-
- Script created by analysing Microsoft environment configuration files like
- "vcvars[...].bat", "SetEnv.Cmd", "vcbuildtools.bat", ...
-
- Parameters
- ----------
- arch: str
- Target architecture.
- vc_ver: float
- Required Microsoft Visual C++ version. If not set, autodetect the last
- version.
- vc_min_ver: float
- Minimum Microsoft Visual C++ version.
- """
-
- # Variables and properties in this class use originals CamelCase variables
+
+ Script created by analysing Microsoft environment configuration files like
+ "vcvars[...].bat", "SetEnv.Cmd", "vcbuildtools.bat", ...
+
+ Parameters
+ ----------
+ arch: str
+ Target architecture.
+ vc_ver: float
+ Required Microsoft Visual C++ version. If not set, autodetect the last
+ version.
+ vc_min_ver: float
+ Minimum Microsoft Visual C++ version.
+ """
+
+ # Variables and properties in this class use originals CamelCase variables
# names from Microsoft source files for more easy comparison.
-
+
def __init__(self, arch, vc_ver=None, vc_min_ver=0):
- self.pi = PlatformInfo(arch)
- self.ri = RegistryInfo(self.pi)
- self.si = SystemInfo(self.ri, vc_ver)
-
+ self.pi = PlatformInfo(arch)
+ self.ri = RegistryInfo(self.pi)
+ self.si = SystemInfo(self.ri, vc_ver)
+
if self.vc_ver < vc_min_ver:
err = 'No suitable Microsoft Visual C++ version found'
raise distutils.errors.DistutilsPlatformError(err)
-
- @property
+
+ @property
def vs_ver(self):
"""
Microsoft Visual Studio.
@@ -1238,107 +1238,107 @@ class EnvironmentInfo:
return self.si.vs_ver
@property
- def vc_ver(self):
- """
- Microsoft Visual C++ version.
+ def vc_ver(self):
+ """
+ Microsoft Visual C++ version.
Return
------
float
version
- """
- return self.si.vc_ver
-
- @property
- def VSTools(self):
- """
+ """
+ return self.si.vc_ver
+
+ @property
+ def VSTools(self):
+ """
Microsoft Visual Studio Tools.
Return
------
list of str
paths
- """
- paths = [r'Common7\IDE', r'Common7\Tools']
-
+ """
+ paths = [r'Common7\IDE', r'Common7\Tools']
+
if self.vs_ver >= 14.0:
- arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
- paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
- paths += [r'Team Tools\Performance Tools']
- paths += [r'Team Tools\Performance Tools%s' % arch_subdir]
-
+ arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
+ paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
+ paths += [r'Team Tools\Performance Tools']
+ paths += [r'Team Tools\Performance Tools%s' % arch_subdir]
+
return [join(self.si.VSInstallDir, path) for path in paths]
-
- @property
- def VCIncludes(self):
- """
+
+ @property
+ def VCIncludes(self):
+ """
Microsoft Visual C++ & Microsoft Foundation Class Includes.
Return
------
list of str
paths
- """
+ """
return [join(self.si.VCInstallDir, 'Include'),
join(self.si.VCInstallDir, r'ATLMFC\Include')]
-
- @property
- def VCLibraries(self):
- """
+
+ @property
+ def VCLibraries(self):
+ """
Microsoft Visual C++ & Microsoft Foundation Class Libraries.
Return
------
list of str
paths
- """
+ """
if self.vs_ver >= 15.0:
arch_subdir = self.pi.target_dir(x64=True)
else:
arch_subdir = self.pi.target_dir(hidex86=True)
- paths = ['Lib%s' % arch_subdir, r'ATLMFC\Lib%s' % arch_subdir]
-
+ paths = ['Lib%s' % arch_subdir, r'ATLMFC\Lib%s' % arch_subdir]
+
if self.vs_ver >= 14.0:
- paths += [r'Lib\store%s' % arch_subdir]
-
+ paths += [r'Lib\store%s' % arch_subdir]
+
return [join(self.si.VCInstallDir, path) for path in paths]
-
- @property
- def VCStoreRefs(self):
- """
+
+ @property
+ def VCStoreRefs(self):
+ """
Microsoft Visual C++ store references Libraries.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 14.0:
- return []
+ return []
return [join(self.si.VCInstallDir, r'Lib\store\references')]
-
- @property
- def VCTools(self):
- """
+
+ @property
+ def VCTools(self):
+ """
Microsoft Visual C++ Tools.
Return
------
list of str
paths
- """
- si = self.si
+ """
+ si = self.si
tools = [join(si.VCInstallDir, 'VCPackages')]
-
+
forcex86 = True if self.vs_ver <= 10.0 else False
- arch_subdir = self.pi.cross_dir(forcex86)
- if arch_subdir:
+ arch_subdir = self.pi.cross_dir(forcex86)
+ if arch_subdir:
tools += [join(si.VCInstallDir, 'Bin%s' % arch_subdir)]
-
+
if self.vs_ver == 14.0:
- path = 'Bin%s' % self.pi.current_dir(hidex86=True)
+ path = 'Bin%s' % self.pi.current_dir(hidex86=True)
tools += [join(si.VCInstallDir, path)]
-
+
elif self.vs_ver >= 15.0:
host_dir = (r'bin\HostX86%s' if self.pi.current_is_x86() else
r'bin\HostX64%s')
@@ -1349,77 +1349,77 @@ class EnvironmentInfo:
tools += [join(
si.VCInstallDir, host_dir % self.pi.current_dir(x64=True))]
- else:
+ else:
tools += [join(si.VCInstallDir, 'Bin')]
-
- return tools
-
- @property
- def OSLibraries(self):
- """
+
+ return tools
+
+ @property
+ def OSLibraries(self):
+ """
Microsoft Windows SDK Libraries.
Return
------
list of str
paths
- """
+ """
if self.vs_ver <= 10.0:
- arch_subdir = self.pi.target_dir(hidex86=True, x64=True)
+ arch_subdir = self.pi.target_dir(hidex86=True, x64=True)
return [join(self.si.WindowsSdkDir, 'Lib%s' % arch_subdir)]
-
- else:
- arch_subdir = self.pi.target_dir(x64=True)
+
+ else:
+ arch_subdir = self.pi.target_dir(x64=True)
lib = join(self.si.WindowsSdkDir, 'lib')
libver = self._sdk_subdir
return [join(lib, '%sum%s' % (libver, arch_subdir))]
-
- @property
- def OSIncludes(self):
- """
+
+ @property
+ def OSIncludes(self):
+ """
Microsoft Windows SDK Include.
Return
------
list of str
paths
- """
+ """
include = join(self.si.WindowsSdkDir, 'include')
-
+
if self.vs_ver <= 10.0:
return [include, join(include, 'gl')]
-
- else:
+
+ else:
if self.vs_ver >= 14.0:
sdkver = self._sdk_subdir
- else:
- sdkver = ''
+ else:
+ sdkver = ''
return [join(include, '%sshared' % sdkver),
join(include, '%sum' % sdkver),
join(include, '%swinrt' % sdkver)]
-
- @property
- def OSLibpath(self):
- """
+
+ @property
+ def OSLibpath(self):
+ """
Microsoft Windows SDK Libraries Paths.
Return
------
list of str
paths
- """
+ """
ref = join(self.si.WindowsSdkDir, 'References')
- libpath = []
-
+ libpath = []
+
if self.vs_ver <= 9.0:
- libpath += self.OSLibraries
-
+ libpath += self.OSLibraries
+
if self.vs_ver >= 11.0:
libpath += [join(ref, r'CommonConfiguration\Neutral')]
-
+
if self.vs_ver >= 14.0:
- libpath += [
- ref,
+ libpath += [
+ ref,
join(self.si.WindowsSdkDir, 'UnionMetadata'),
join(
ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),
@@ -1431,21 +1431,21 @@ class EnvironmentInfo:
self.si.WindowsSdkDir, 'ExtensionSDKs', 'Microsoft.VCLibs',
'%0.1f' % self.vs_ver, 'References', 'CommonConfiguration',
'neutral'),
- ]
- return libpath
-
- @property
- def SdkTools(self):
- """
+ ]
+ return libpath
+
+ @property
+ def SdkTools(self):
+ """
Microsoft Windows SDK Tools.
Return
------
list of str
paths
- """
+ """
return list(self._sdk_tools())
-
+
def _sdk_tools(self):
"""
Microsoft Windows SDK Tools paths generator.
@@ -1459,28 +1459,28 @@ class EnvironmentInfo:
bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\x86'
yield join(self.si.WindowsSdkDir, bin_dir)
- if not self.pi.current_is_x86():
- arch_subdir = self.pi.current_dir(x64=True)
- path = 'Bin%s' % arch_subdir
+ if not self.pi.current_is_x86():
+ arch_subdir = self.pi.current_dir(x64=True)
+ path = 'Bin%s' % arch_subdir
yield join(self.si.WindowsSdkDir, path)
-
+
if self.vs_ver in (10.0, 11.0):
- if self.pi.target_is_x86():
- arch_subdir = ''
- else:
- arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
- path = r'Bin\NETFX 4.0 Tools%s' % arch_subdir
+ if self.pi.target_is_x86():
+ arch_subdir = ''
+ else:
+ arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
+ path = r'Bin\NETFX 4.0 Tools%s' % arch_subdir
yield join(self.si.WindowsSdkDir, path)
-
+
elif self.vs_ver >= 15.0:
path = join(self.si.WindowsSdkDir, 'Bin')
arch_subdir = self.pi.current_dir(x64=True)
sdkver = self.si.WindowsSdkLastVersion
yield join(path, '%s%s' % (sdkver, arch_subdir))
- if self.si.WindowsSDKExecutablePath:
+ if self.si.WindowsSDKExecutablePath:
yield self.si.WindowsSDKExecutablePath
-
+
@property
def _sdk_subdir(self):
"""
@@ -1493,172 +1493,172 @@ class EnvironmentInfo:
"""
ucrtver = self.si.WindowsSdkLastVersion
return ('%s\\' % ucrtver) if ucrtver else ''
-
- @property
- def SdkSetup(self):
- """
+
+ @property
+ def SdkSetup(self):
+ """
Microsoft Windows SDK Setup.
Return
------
list of str
paths
- """
+ """
if self.vs_ver > 9.0:
- return []
-
+ return []
+
return [join(self.si.WindowsSdkDir, 'Setup')]
-
- @property
- def FxTools(self):
- """
+
+ @property
+ def FxTools(self):
+ """
Microsoft .NET Framework Tools.
Return
------
list of str
paths
- """
- pi = self.pi
- si = self.si
-
+ """
+ pi = self.pi
+ si = self.si
+
if self.vs_ver <= 10.0:
- include32 = True
- include64 = not pi.target_is_x86() and not pi.current_is_x86()
- else:
- include32 = pi.target_is_x86() or pi.current_is_x86()
- include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'
-
- tools = []
- if include32:
+ include32 = True
+ include64 = not pi.target_is_x86() and not pi.current_is_x86()
+ else:
+ include32 = pi.target_is_x86() or pi.current_is_x86()
+ include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'
+
+ tools = []
+ if include32:
tools += [join(si.FrameworkDir32, ver)
- for ver in si.FrameworkVersion32]
- if include64:
+ for ver in si.FrameworkVersion32]
+ if include64:
tools += [join(si.FrameworkDir64, ver)
- for ver in si.FrameworkVersion64]
- return tools
-
- @property
- def NetFxSDKLibraries(self):
- """
+ for ver in si.FrameworkVersion64]
+ return tools
+
+ @property
+ def NetFxSDKLibraries(self):
+ """
Microsoft .Net Framework SDK Libraries.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
- return []
-
- arch_subdir = self.pi.target_dir(x64=True)
+ return []
+
+ arch_subdir = self.pi.target_dir(x64=True)
return [join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
-
- @property
- def NetFxSDKIncludes(self):
- """
+
+ @property
+ def NetFxSDKIncludes(self):
+ """
Microsoft .Net Framework SDK Includes.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
- return []
-
+ return []
+
return [join(self.si.NetFxSdkDir, r'include\um')]
-
- @property
- def VsTDb(self):
- """
+
+ @property
+ def VsTDb(self):
+ """
Microsoft Visual Studio Team System Database.
Return
------
list of str
paths
- """
+ """
return [join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
-
- @property
- def MSBuild(self):
- """
+
+ @property
+ def MSBuild(self):
+ """
Microsoft Build Engine.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 12.0:
- return []
+ return []
elif self.vs_ver < 15.0:
base_path = self.si.ProgramFilesx86
arch_subdir = self.pi.current_dir(hidex86=True)
else:
base_path = self.si.VSInstallDir
arch_subdir = ''
-
+
path = r'MSBuild\%0.1f\bin%s' % (self.vs_ver, arch_subdir)
build = [join(base_path, path)]
-
+
if self.vs_ver >= 15.0:
# Add Roslyn C# & Visual Basic Compiler
build += [join(base_path, path, 'Roslyn')]
return build
- @property
- def HTMLHelpWorkshop(self):
- """
+ @property
+ def HTMLHelpWorkshop(self):
+ """
Microsoft HTML Help Workshop.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 11.0:
- return []
-
+ return []
+
return [join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
-
- @property
- def UCRTLibraries(self):
- """
+
+ @property
+ def UCRTLibraries(self):
+ """
Microsoft Universal C Runtime SDK Libraries.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 14.0:
- return []
-
- arch_subdir = self.pi.target_dir(x64=True)
+ return []
+
+ arch_subdir = self.pi.target_dir(x64=True)
lib = join(self.si.UniversalCRTSdkDir, 'lib')
ucrtver = self._ucrt_subdir
return [join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]
-
- @property
- def UCRTIncludes(self):
- """
+
+ @property
+ def UCRTIncludes(self):
+ """
Microsoft Universal C Runtime SDK Include.
Return
------
list of str
paths
- """
+ """
if self.vs_ver < 14.0:
- return []
-
+ return []
+
include = join(self.si.UniversalCRTSdkDir, 'include')
return [join(include, '%sucrt' % self._ucrt_subdir)]
-
- @property
+
+ @property
def _ucrt_subdir(self):
"""
Microsoft Universal C Runtime SDK version subdir.
@@ -1672,33 +1672,33 @@ class EnvironmentInfo:
return ('%s\\' % ucrtver) if ucrtver else ''
@property
- def FSharp(self):
- """
+ def FSharp(self):
+ """
Microsoft Visual F#.
Return
------
list of str
paths
- """
+ """
if 11.0 > self.vs_ver > 12.0:
- return []
-
+ return []
+
return [self.si.FSharpInstallDir]
-
- @property
- def VCRuntimeRedist(self):
- """
+
+ @property
+ def VCRuntimeRedist(self):
+ """
Microsoft Visual C++ runtime redistributable dll.
Return
------
str
path
- """
+ """
vcruntime = 'vcruntime%d0.dll' % self.vc_ver
arch_subdir = self.pi.target_dir(x64=True).strip('\\')
-
+
# Installation prefixes candidates
prefixes = []
tools_path = self.si.VCInstallDir
@@ -1721,63 +1721,63 @@ class EnvironmentInfo:
if isfile(path):
return path
- def return_env(self, exists=True):
- """
- Return environment dict.
-
- Parameters
- ----------
- exists: bool
- It True, only return existing paths.
+ def return_env(self, exists=True):
+ """
+ Return environment dict.
+
+ Parameters
+ ----------
+ exists: bool
+ It True, only return existing paths.
Return
------
dict
environment
- """
- env = dict(
- include=self._build_paths('include',
- [self.VCIncludes,
- self.OSIncludes,
- self.UCRTIncludes,
- self.NetFxSDKIncludes],
- exists),
- lib=self._build_paths('lib',
- [self.VCLibraries,
- self.OSLibraries,
- self.FxTools,
- self.UCRTLibraries,
- self.NetFxSDKLibraries],
- exists),
- libpath=self._build_paths('libpath',
- [self.VCLibraries,
- self.FxTools,
- self.VCStoreRefs,
- self.OSLibpath],
- exists),
- path=self._build_paths('path',
- [self.VCTools,
- self.VSTools,
- self.VsTDb,
- self.SdkTools,
- self.SdkSetup,
- self.FxTools,
- self.MSBuild,
- self.HTMLHelpWorkshop,
- self.FSharp],
- exists),
- )
+ """
+ env = dict(
+ include=self._build_paths('include',
+ [self.VCIncludes,
+ self.OSIncludes,
+ self.UCRTIncludes,
+ self.NetFxSDKIncludes],
+ exists),
+ lib=self._build_paths('lib',
+ [self.VCLibraries,
+ self.OSLibraries,
+ self.FxTools,
+ self.UCRTLibraries,
+ self.NetFxSDKLibraries],
+ exists),
+ libpath=self._build_paths('libpath',
+ [self.VCLibraries,
+ self.FxTools,
+ self.VCStoreRefs,
+ self.OSLibpath],
+ exists),
+ path=self._build_paths('path',
+ [self.VCTools,
+ self.VSTools,
+ self.VsTDb,
+ self.SdkTools,
+ self.SdkSetup,
+ self.FxTools,
+ self.MSBuild,
+ self.HTMLHelpWorkshop,
+ self.FSharp],
+ exists),
+ )
if self.vs_ver >= 14 and isfile(self.VCRuntimeRedist):
- env['py_vcruntime_redist'] = self.VCRuntimeRedist
- return env
-
- def _build_paths(self, name, spec_path_lists, exists):
- """
- Given an environment variable name and specified paths,
- return a pathsep-separated string of paths containing
- unique, extant, directories from those paths and from
- the environment variable. Raise an error if no paths
- are resolved.
+ env['py_vcruntime_redist'] = self.VCRuntimeRedist
+ return env
+
+ def _build_paths(self, name, spec_path_lists, exists):
+ """
+ Given an environment variable name and specified paths,
+ return a pathsep-separated string of paths containing
+ unique, extant, directories from those paths and from
+ the environment variable. Raise an error if no paths
+ are resolved.
Parameters
----------
@@ -1792,14 +1792,14 @@ class EnvironmentInfo:
------
str
Pathsep-separated paths
- """
- # flatten spec_path_lists
- spec_paths = itertools.chain.from_iterable(spec_path_lists)
+ """
+ # flatten spec_path_lists
+ spec_paths = itertools.chain.from_iterable(spec_path_lists)
env_paths = environ.get(name, '').split(pathsep)
- paths = itertools.chain(spec_paths, env_paths)
+ paths = itertools.chain(spec_paths, env_paths)
extant_paths = list(filter(isdir, paths)) if exists else paths
- if not extant_paths:
- msg = "%s environment variable is empty" % name.upper()
- raise distutils.errors.DistutilsPlatformError(msg)
+ if not extant_paths:
+ msg = "%s environment variable is empty" % name.upper()
+ raise distutils.errors.DistutilsPlatformError(msg)
unique_paths = unique_everseen(extant_paths)
return pathsep.join(unique_paths)
diff --git a/contrib/python/setuptools/py3/setuptools/namespaces.py b/contrib/python/setuptools/py3/setuptools/namespaces.py
index 44939e1c6d..c6acde49c6 100644
--- a/contrib/python/setuptools/py3/setuptools/namespaces.py
+++ b/contrib/python/setuptools/py3/setuptools/namespaces.py
@@ -1,53 +1,53 @@
-import os
-from distutils import log
-import itertools
-
-
-flatten = itertools.chain.from_iterable
-
-
-class Installer:
-
- nspkg_ext = '-nspkg.pth'
-
- def install_namespaces(self):
- nsp = self._get_all_ns_packages()
- if not nsp:
- return
- filename, ext = os.path.splitext(self._get_target())
- filename += self.nspkg_ext
- self.outputs.append(filename)
- log.info("Installing %s", filename)
- lines = map(self._gen_nspkg_line, nsp)
-
- if self.dry_run:
- # always generate the lines, even in dry run
- list(lines)
- return
-
- with open(filename, 'wt') as f:
- f.writelines(lines)
-
- def uninstall_namespaces(self):
- filename, ext = os.path.splitext(self._get_target())
- filename += self.nspkg_ext
- if not os.path.exists(filename):
- return
- log.info("Removing %s", filename)
- os.remove(filename)
-
- def _get_target(self):
- return self.target
-
- _nspkg_tmpl = (
- "import sys, types, os",
- "has_mfs = sys.version_info > (3, 5)",
- "p = os.path.join(%(root)s, *%(pth)r)",
- "importlib = has_mfs and __import__('importlib.util')",
- "has_mfs and __import__('importlib.machinery')",
+import os
+from distutils import log
+import itertools
+
+
+flatten = itertools.chain.from_iterable
+
+
+class Installer:
+
+ nspkg_ext = '-nspkg.pth'
+
+ def install_namespaces(self):
+ nsp = self._get_all_ns_packages()
+ if not nsp:
+ return
+ filename, ext = os.path.splitext(self._get_target())
+ filename += self.nspkg_ext
+ self.outputs.append(filename)
+ log.info("Installing %s", filename)
+ lines = map(self._gen_nspkg_line, nsp)
+
+ if self.dry_run:
+ # always generate the lines, even in dry run
+ list(lines)
+ return
+
+ with open(filename, 'wt') as f:
+ f.writelines(lines)
+
+ def uninstall_namespaces(self):
+ filename, ext = os.path.splitext(self._get_target())
+ filename += self.nspkg_ext
+ if not os.path.exists(filename):
+ return
+ log.info("Removing %s", filename)
+ os.remove(filename)
+
+ def _get_target(self):
+ return self.target
+
+ _nspkg_tmpl = (
+ "import sys, types, os",
+ "has_mfs = sys.version_info > (3, 5)",
+ "p = os.path.join(%(root)s, *%(pth)r)",
+ "importlib = has_mfs and __import__('importlib.util')",
+ "has_mfs and __import__('importlib.machinery')",
(
"m = has_mfs and "
- "sys.modules.setdefault(%(pkg)r, "
+ "sys.modules.setdefault(%(pkg)r, "
"importlib.util.module_from_spec("
"importlib.machinery.PathFinder.find_spec(%(pkg)r, "
"[os.path.dirname(p)])))"
@@ -56,52 +56,52 @@ class Installer:
"m = m or "
"sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"
),
- "mp = (m or []) and m.__dict__.setdefault('__path__',[])",
- "(p not in mp) and mp.append(p)",
- )
- "lines for the namespace installer"
-
- _nspkg_tmpl_multi = (
- 'm and setattr(sys.modules[%(parent)r], %(child)r, m)',
- )
- "additional line(s) when a parent package is indicated"
-
- def _get_root(self):
- return "sys._getframe(1).f_locals['sitedir']"
-
- def _gen_nspkg_line(self, pkg):
- pth = tuple(pkg.split('.'))
- root = self._get_root()
- tmpl_lines = self._nspkg_tmpl
- parent, sep, child = pkg.rpartition('.')
- if parent:
- tmpl_lines += self._nspkg_tmpl_multi
- return ';'.join(tmpl_lines) % locals() + '\n'
-
- def _get_all_ns_packages(self):
- """Return sorted list of all package namespaces"""
- pkgs = self.distribution.namespace_packages or []
- return sorted(flatten(map(self._pkg_names, pkgs)))
-
- @staticmethod
- def _pkg_names(pkg):
- """
- Given a namespace package, yield the components of that
- package.
-
- >>> names = Installer._pkg_names('a.b.c')
- >>> set(names) == set(['a', 'a.b', 'a.b.c'])
- True
- """
- parts = pkg.split('.')
- while parts:
- yield '.'.join(parts)
- parts.pop()
-
-
-class DevelopInstaller(Installer):
- def _get_root(self):
- return repr(str(self.egg_path))
-
- def _get_target(self):
- return self.egg_link
+ "mp = (m or []) and m.__dict__.setdefault('__path__',[])",
+ "(p not in mp) and mp.append(p)",
+ )
+ "lines for the namespace installer"
+
+ _nspkg_tmpl_multi = (
+ 'm and setattr(sys.modules[%(parent)r], %(child)r, m)',
+ )
+ "additional line(s) when a parent package is indicated"
+
+ def _get_root(self):
+ return "sys._getframe(1).f_locals['sitedir']"
+
+ def _gen_nspkg_line(self, pkg):
+ pth = tuple(pkg.split('.'))
+ root = self._get_root()
+ tmpl_lines = self._nspkg_tmpl
+ parent, sep, child = pkg.rpartition('.')
+ if parent:
+ tmpl_lines += self._nspkg_tmpl_multi
+ return ';'.join(tmpl_lines) % locals() + '\n'
+
+ def _get_all_ns_packages(self):
+ """Return sorted list of all package namespaces"""
+ pkgs = self.distribution.namespace_packages or []
+ return sorted(flatten(map(self._pkg_names, pkgs)))
+
+ @staticmethod
+ def _pkg_names(pkg):
+ """
+ Given a namespace package, yield the components of that
+ package.
+
+ >>> names = Installer._pkg_names('a.b.c')
+ >>> set(names) == set(['a', 'a.b', 'a.b.c'])
+ True
+ """
+ parts = pkg.split('.')
+ while parts:
+ yield '.'.join(parts)
+ parts.pop()
+
+
+class DevelopInstaller(Installer):
+ def _get_root(self):
+ return repr(str(self.egg_path))
+
+ def _get_target(self):
+ return self.egg_link
diff --git a/contrib/python/setuptools/py3/setuptools/package_index.py b/contrib/python/setuptools/py3/setuptools/package_index.py
index 270e7f3c91..f2a4c435aa 100644
--- a/contrib/python/setuptools/py3/setuptools/package_index.py
+++ b/contrib/python/setuptools/py3/setuptools/package_index.py
@@ -17,10 +17,10 @@ import urllib.request
import urllib.error
from functools import wraps
-import setuptools
+import setuptools
from pkg_resources import (
CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
- Environment, find_distributions, safe_name, safe_version,
+ Environment, find_distributions, safe_name, safe_version,
to_filename, Requirement, DEVELOP_DIST, EGG_DIST, parse_version,
)
from distutils import log
@@ -30,13 +30,13 @@ from setuptools.wheel import Wheel
from setuptools.extern.more_itertools import unique_everseen
-EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
+EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
PYPI_MD5 = re.compile(
r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
)
-URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
+URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
__all__ = [
@@ -46,20 +46,20 @@ __all__ = [
_SOCKET_TIMEOUT = 15
-_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
+_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
user_agent = _tmpl.format(
py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
-
-
-def parse_requirement_arg(spec):
- try:
- return Requirement.parse(spec)
+
+
+def parse_requirement_arg(spec):
+ try:
+ return Requirement.parse(spec)
except ValueError as e:
- raise DistutilsError(
- "Not a URL, existing file, or requirement spec: %r" % (spec,)
+ raise DistutilsError(
+ "Not a URL, existing file, or requirement spec: %r" % (spec,)
) from e
-
-
+
+
def parse_bdist_wininst(name):
"""Return (base,pyversion) or (None,None) for possible .exe name"""
@@ -70,49 +70,49 @@ def parse_bdist_wininst(name):
if lower.endswith('.win32.exe'):
base = name[:-10]
plat = 'win32'
- elif lower.startswith('.win32-py', -16):
+ elif lower.startswith('.win32-py', -16):
py_ver = name[-7:-4]
base = name[:-16]
plat = 'win32'
elif lower.endswith('.win-amd64.exe'):
base = name[:-14]
plat = 'win-amd64'
- elif lower.startswith('.win-amd64-py', -20):
+ elif lower.startswith('.win-amd64-py', -20):
py_ver = name[-7:-4]
base = name[:-20]
plat = 'win-amd64'
- return base, py_ver, plat
+ return base, py_ver, plat
def egg_info_for_url(url):
parts = urllib.parse.urlparse(url)
scheme, server, path, parameters, query, fragment = parts
base = urllib.parse.unquote(path.split('/')[-1])
- if server == 'sourceforge.net' and base == 'download': # XXX Yuck
+ if server == 'sourceforge.net' and base == 'download': # XXX Yuck
base = urllib.parse.unquote(path.split('/')[-2])
- if '#' in base:
- base, fragment = base.split('#', 1)
- return base, fragment
-
+ if '#' in base:
+ base, fragment = base.split('#', 1)
+ return base, fragment
+
def distros_for_url(url, metadata=None):
"""Yield egg or source distribution objects that might be found at a URL"""
base, fragment = egg_info_for_url(url)
- for dist in distros_for_location(url, base, metadata):
- yield dist
+ for dist in distros_for_location(url, base, metadata):
+ yield dist
if fragment:
match = EGG_FRAGMENT.match(fragment)
if match:
for dist in interpret_distro_name(
- url, match.group(1), metadata, precedence=CHECKOUT_DIST
+ url, match.group(1), metadata, precedence=CHECKOUT_DIST
):
yield dist
-
+
def distros_for_location(location, basename, metadata=None):
"""Yield egg or source distribution objects based on basename"""
if basename.endswith('.egg.zip'):
- basename = basename[:-4] # strip the .zip
+ basename = basename[:-4] # strip the .zip
if basename.endswith('.egg') and '-' in basename:
# only one, unambiguous interpretation
return [Distribution.from_location(location, basename, metadata)]
@@ -141,7 +141,7 @@ def distros_for_location(location, basename, metadata=None):
return interpret_distro_name(location, basename, metadata)
return [] # no extension matched
-
+
def distros_for_filename(filename, metadata=None):
"""Yield possible egg or source distribution objects based on a filename"""
return distros_for_location(
@@ -172,35 +172,35 @@ def interpret_distro_name(
# versions in distribution archive names (sdist and bdist).
parts = basename.split('-')
- if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
+ if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
# it is a bdist_dumb, not an sdist -- bail out
return
- for p in range(1, len(parts) + 1):
+ for p in range(1, len(parts) + 1):
yield Distribution(
location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
- py_version=py_version, precedence=precedence,
- platform=platform
+ py_version=py_version, precedence=precedence,
+ platform=platform
)
-
+
def unique_values(func):
"""
Wrap a function returning an iterable such that the resulting iterable
only ever yields unique items.
"""
-
+
@wraps(func)
def wrapper(*args, **kwargs):
return unique_everseen(func(*args, **kwargs))
-
+
return wrapper
-
-REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
+
+REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
# this line is here to fix emacs' cruddy broken syntax highlighting
-
+
@unique_values
def find_external_links(url, page):
"""Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
@@ -214,8 +214,8 @@ def find_external_links(url, page):
for tag in ("<th>Home Page", "<th>Download URL"):
pos = page.find(tag)
- if pos != -1:
- match = HREF.search(page, pos)
+ if pos != -1:
+ match = HREF.search(page, pos)
if match:
yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
@@ -224,7 +224,7 @@ class ContentChecker:
"""
A null content checker that defines the interface for checking content
"""
-
+
def feed(self, block):
"""
Feed a block of data to the hash.
@@ -244,7 +244,7 @@ class ContentChecker:
"""
return
-
+
class HashChecker(ContentChecker):
pattern = re.compile(
r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
@@ -285,12 +285,12 @@ class PackageIndex(Environment):
self, index_url="https://pypi.org/simple/", hosts=('*',),
ca_bundle=None, verify_ssl=True, *args, **kw
):
- Environment.__init__(self, *args, **kw)
- self.index_url = index_url + "/" [:not index_url.endswith('/')]
+ Environment.__init__(self, *args, **kw)
+ self.index_url = index_url + "/" [:not index_url.endswith('/')]
self.scanned_urls = {}
self.fetched_urls = {}
self.package_pages = {}
- self.allows = re.compile('|'.join(map(translate, hosts))).match
+ self.allows = re.compile('|'.join(map(translate, hosts))).match
self.to_scan = []
self.opener = urllib.request.urlopen
@@ -327,19 +327,19 @@ class PackageIndex(Environment):
return
self.info("Reading %s", url)
- self.fetched_urls[url] = True # prevent multiple fetch attempts
- tmpl = "Download error on %s: %%s -- Some packages may not be found!"
- f = self.open_url(url, tmpl % url)
- if f is None:
- return
+ self.fetched_urls[url] = True # prevent multiple fetch attempts
+ tmpl = "Download error on %s: %%s -- Some packages may not be found!"
+ f = self.open_url(url, tmpl % url)
+ if f is None:
+ return
if isinstance(f, urllib.error.HTTPError) and f.code == 401:
self.info("Authentication error: %s" % f.msg)
self.fetched_urls[f.url] = True
if 'html' not in f.headers.get('content-type', '').lower():
- f.close() # not html, we can't process it
+ f.close() # not html, we can't process it
return
- base = f.url # handle redirects
+ base = f.url # handle redirects
page = f.read()
if not isinstance(page, str):
# In Python 3 and got bytes but want str.
@@ -353,7 +353,7 @@ class PackageIndex(Environment):
for match in HREF.finditer(page):
link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
self.process_url(link)
- if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
+ if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
page = self.process_index(url, page)
def process_filename(self, fn, nested=False):
@@ -365,7 +365,7 @@ class PackageIndex(Environment):
if os.path.isdir(fn) and not nested:
path = os.path.realpath(fn)
for item in os.listdir(path):
- self.process_filename(os.path.join(path, item), True)
+ self.process_filename(os.path.join(path, item), True)
dists = distros_for_filename(fn)
if dists:
@@ -374,8 +374,8 @@ class PackageIndex(Environment):
def url_ok(self, url, fatal=False):
s = URL_SCHEME(url)
- is_file = s and s.group(1).lower() == 'file'
- if is_file or self.allows(urllib.parse.urlparse(url)[1]):
+ is_file = s and s.group(1).lower() == 'file'
+ if is_file or self.allows(urllib.parse.urlparse(url)[1]):
return True
msg = (
"\nNote: Bypassing %s (disallowed host; see "
@@ -429,9 +429,9 @@ class PackageIndex(Environment):
self.package_pages.setdefault(pkg.lower(), {})[link] = True
return to_filename(pkg), to_filename(ver)
- def process_index(self, url, page):
+ def process_index(self, url, page):
"""Process the contents of a PyPI page"""
-
+
# process an index page into the package-page index
for match in HREF.finditer(page):
try:
@@ -441,7 +441,7 @@ class PackageIndex(Environment):
pkg, ver = self._scan(url) # ensure this page is in the page index
if not pkg:
- return "" # no sense double-scanning non-package pages
+ return "" # no sense double-scanning non-package pages
# process individual package page
for new_url in find_external_links(url, page):
@@ -466,25 +466,25 @@ class PackageIndex(Environment):
def scan_all(self, msg=None, *args):
if self.index_url not in self.fetched_urls:
- if msg:
- self.warn(msg, *args)
+ if msg:
+ self.warn(msg, *args)
self.info(
"Scanning index of all packages (this may take a while)"
)
self.scan_url(self.index_url)
def find_packages(self, requirement):
- self.scan_url(self.index_url + requirement.unsafe_name + '/')
+ self.scan_url(self.index_url + requirement.unsafe_name + '/')
if not self.package_pages.get(requirement.key):
# Fall back to safe version of the name
- self.scan_url(self.index_url + requirement.project_name + '/')
+ self.scan_url(self.index_url + requirement.project_name + '/')
if not self.package_pages.get(requirement.key):
# We couldn't find the target package, so search the index page too
self.not_found_in_index(requirement)
- for url in list(self.package_pages.get(requirement.key, ())):
+ for url in list(self.package_pages.get(requirement.key, ())):
# scan each page that might be related to the desired package
self.scan_url(url)
@@ -495,7 +495,7 @@ class PackageIndex(Environment):
if dist in requirement:
return dist
self.debug("%s does not match %s", requirement, dist)
- return super(PackageIndex, self).obtain(requirement, installer)
+ return super(PackageIndex, self).obtain(requirement, installer)
def check_hash(self, checker, filename, tfp):
"""
@@ -517,10 +517,10 @@ class PackageIndex(Environment):
"""Add `urls` to the list that will be prescanned for searches"""
for url in urls:
if (
- self.to_scan is None # if we have already "gone online"
- or not URL_SCHEME(url) # or it's a local file/directory
+ self.to_scan is None # if we have already "gone online"
+ or not URL_SCHEME(url) # or it's a local file/directory
or url.startswith('file:')
- or list(distros_for_url(url)) # or a direct package link
+ or list(distros_for_url(url)) # or a direct package link
):
# then go ahead and process it now
self.scan_url(url)
@@ -532,12 +532,12 @@ class PackageIndex(Environment):
"""Scan urls scheduled for prescanning (e.g. --find-links)"""
if self.to_scan:
list(map(self.scan_url, self.to_scan))
- self.to_scan = None # from now on, go ahead and process immediately
+ self.to_scan = None # from now on, go ahead and process immediately
def not_found_in_index(self, requirement):
- if self[requirement.key]: # we've seen at least one distro
+ if self[requirement.key]: # we've seen at least one distro
meth, msg = self.info, "Couldn't retrieve index page for %r"
- else: # no distros seen for this name, might be misspelled
+ else: # no distros seen for this name, might be misspelled
meth, msg = (
self.warn,
"Couldn't find index page for %r (maybe misspelled?)")
@@ -562,21 +562,21 @@ class PackageIndex(Environment):
of `tmpdir`, and the local filename is returned. Various errors may be
raised if a problem occurs during downloading.
"""
- if not isinstance(spec, Requirement):
+ if not isinstance(spec, Requirement):
scheme = URL_SCHEME(spec)
if scheme:
# It's a url, download it to tmpdir
found = self._download_url(scheme.group(1), spec, tmpdir)
base, fragment = egg_info_for_url(spec)
if base.endswith('.py'):
- found = self.gen_setup(found, fragment, tmpdir)
+ found = self.gen_setup(found, fragment, tmpdir)
return found
elif os.path.exists(spec):
# Existing file or directory, just return it
return spec
else:
- spec = parse_requirement_arg(spec)
- return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
+ spec = parse_requirement_arg(spec)
+ return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME
self, requirement, tmpdir, force_scan=False, source=False,
@@ -609,7 +609,7 @@ class PackageIndex(Environment):
for dist in env[req.key]:
- if dist.precedence == DEVELOP_DIST and not develop_ok:
+ if dist.precedence == DEVELOP_DIST and not develop_ok:
if dist not in skipped:
self.warn(
"Skipping development or system egg: %s", dist,
@@ -624,16 +624,16 @@ class PackageIndex(Environment):
if test:
loc = self.download(dist.location, tmpdir)
dist.download_location = loc
- if os.path.exists(dist.download_location):
- return dist
+ if os.path.exists(dist.download_location):
+ return dist
if force_scan:
self.prescan()
self.find_packages(requirement)
dist = find(requirement)
- if not dist and local_index is not None:
- dist = find(requirement, local_index)
+ if not dist and local_index is not None:
+ dist = find(requirement, local_index)
if dist is None:
if self.to_scan is not None:
@@ -646,13 +646,13 @@ class PackageIndex(Environment):
if dist is None:
self.warn(
- "No local packages or working download links found for %s%s",
+ "No local packages or working download links found for %s%s",
(source and "a source distribution of " or ""),
requirement,
)
else:
self.info("Best match: %s", dist)
- return dist.clone(location=dist.download_location)
+ return dist.clone(location=dist.download_location)
def fetch(self, requirement, tmpdir, force_scan=False, source=False):
"""Obtain a file suitable for fulfilling `requirement`
@@ -662,7 +662,7 @@ class PackageIndex(Environment):
``location`` of the downloaded distribution instead of a distribution
object.
"""
- dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
+ dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
if dist is not None:
return dist.location
return None
@@ -674,7 +674,7 @@ class PackageIndex(Environment):
interpret_distro_name(filename, match.group(1), None) if d.version
] or []
- if len(dists) == 1: # unambiguous ``#egg`` fragment
+ if len(dists) == 1: # unambiguous ``#egg`` fragment
basename = os.path.basename(filename)
# Make sure the file has been downloaded to the temp dir.
@@ -683,7 +683,7 @@ class PackageIndex(Environment):
from setuptools.command.easy_install import samefile
if not samefile(filename, dst):
shutil.copy2(filename, dst)
- filename = dst
+ filename = dst
with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
file.write(
@@ -700,7 +700,7 @@ class PackageIndex(Environment):
raise DistutilsError(
"Can't unambiguously interpret project/version identifier %r; "
"any dashes in the name or version should be escaped using "
- "underscores. %r" % (fragment, dists)
+ "underscores. %r" % (fragment, dists)
)
else:
raise DistutilsError(
@@ -709,7 +709,7 @@ class PackageIndex(Environment):
)
dl_blocksize = 8192
-
+
def _download_to(self, url, filename):
self.info("Downloading %s", url)
# Download the file
@@ -719,7 +719,7 @@ class PackageIndex(Environment):
fp = self.open_url(url)
if isinstance(fp, urllib.error.HTTPError):
raise DistutilsError(
- "Can't download %s: %s %s" % (url, fp.code, fp.msg)
+ "Can't download %s: %s %s" % (url, fp.code, fp.msg)
)
headers = fp.info()
blocknum = 0
@@ -730,7 +730,7 @@ class PackageIndex(Environment):
sizes = headers.get_all('Content-Length')
size = max(map(int, sizes))
self.reporthook(url, filename, blocknum, bs, size)
- with open(filename, 'wb') as tfp:
+ with open(filename, 'wb') as tfp:
while True:
block = fp.read(bs)
if block:
@@ -743,11 +743,11 @@ class PackageIndex(Environment):
self.check_hash(checker, filename, tfp)
return headers
finally:
- if fp:
- fp.close()
+ if fp:
+ fp.close()
def reporthook(self, url, filename, blocknum, blksize, size):
- pass # no-op
+ pass # no-op
# FIXME:
def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
@@ -791,27 +791,27 @@ class PackageIndex(Environment):
name, fragment = egg_info_for_url(url)
if name:
while '..' in name:
- name = name.replace('..', '.').replace('\\', '_')
+ name = name.replace('..', '.').replace('\\', '_')
else:
- name = "__downloaded__" # default if URL has no path contents
+ name = "__downloaded__" # default if URL has no path contents
if name.endswith('.egg.zip'):
- name = name[:-4] # strip the extra .zip before download
+ name = name[:-4] # strip the extra .zip before download
- filename = os.path.join(tmpdir, name)
+ filename = os.path.join(tmpdir, name)
# Download the file
#
- if scheme == 'svn' or scheme.startswith('svn+'):
+ if scheme == 'svn' or scheme.startswith('svn+'):
return self._download_svn(url, filename)
- elif scheme == 'git' or scheme.startswith('git+'):
+ elif scheme == 'git' or scheme.startswith('git+'):
return self._download_git(url, filename)
elif scheme.startswith('hg+'):
return self._download_hg(url, filename)
- elif scheme == 'file':
+ elif scheme == 'file':
return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
else:
- self.url_ok(url, True) # raises error if not allowed
+ self.url_ok(url, True) # raises error if not allowed
return self._attempt_download(url, filename)
def scan_url(self, url):
@@ -819,7 +819,7 @@ class PackageIndex(Environment):
def _attempt_download(self, url, filename):
headers = self._download_to(url, filename)
- if 'html' in headers.get('content-type', '').lower():
+ if 'html' in headers.get('content-type', '').lower():
return self._download_html(url, headers, filename)
else:
return filename
@@ -834,26 +834,26 @@ class PackageIndex(Environment):
file.close()
os.unlink(filename)
return self._download_svn(url, filename)
- break # not an index page
+ break # not an index page
file.close()
os.unlink(filename)
- raise DistutilsError("Unexpected HTML page found at " + url)
+ raise DistutilsError("Unexpected HTML page found at " + url)
def _download_svn(self, url, filename):
warnings.warn("SVN download support is deprecated", UserWarning)
- url = url.split('#', 1)[0] # remove any fragment for svn's sake
+ url = url.split('#', 1)[0] # remove any fragment for svn's sake
creds = ''
if url.lower().startswith('svn:') and '@' in url:
scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
if not netloc and path.startswith('//') and '/' in path[2:]:
- netloc, path = path[2:].split('/', 1)
+ netloc, path = path[2:].split('/', 1)
auth, host = _splituser(netloc)
if auth:
if ':' in auth:
- user, pw = auth.split(':', 1)
+ user, pw = auth.split(':', 1)
creds = " --username=%s --password=%s" % (user, pw)
else:
- creds = " --username=" + auth
+ creds = " --username=" + auth
netloc = host
parts = scheme, netloc, url, p, q, f
url = urllib.parse.urlunparse(parts)
@@ -868,7 +868,7 @@ class PackageIndex(Environment):
scheme = scheme.split('+', 1)[-1]
# Some fragment identification fails
- path = path.split('#', 1)[0]
+ path = path.split('#', 1)[0]
rev = None
if '@' in path:
@@ -880,7 +880,7 @@ class PackageIndex(Environment):
return url, rev
def _download_git(self, url, filename):
- filename = filename.split('#', 1)[0]
+ filename = filename.split('#', 1)[0]
url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
self.info("Doing git clone from %s to %s", url, filename)
@@ -896,7 +896,7 @@ class PackageIndex(Environment):
return filename
def _download_hg(self, url, filename):
- filename = filename.split('#', 1)[0]
+ filename = filename.split('#', 1)[0]
url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
self.info("Doing hg clone from %s to %s", url, filename)
@@ -920,17 +920,17 @@ class PackageIndex(Environment):
def warn(self, msg, *args):
log.warn(msg, *args)
-
+
# This pattern matches a character entity reference (a decimal numeric
# references, a hexadecimal numeric reference, or a named reference).
entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
-
+
def decode_entity(match):
what = match.group(0)
return html.unescape(what)
-
+
def htmldecode(text):
"""
Decode HTML entities in the given text.
@@ -942,7 +942,7 @@ def htmldecode(text):
"""
return entity_sub(decode_entity, text)
-
+
def socket_timeout(timeout=15):
def _socket_timeout(func):
def _socket_timeout(*args, **kwargs):
@@ -952,12 +952,12 @@ def socket_timeout(timeout=15):
return func(*args, **kwargs)
finally:
socket.setdefaulttimeout(old_timeout)
-
+
return _socket_timeout
-
+
return _socket_timeout
-
+
def _encode_auth(auth):
"""
Encode auth from a URL suitable for an HTTP header.
@@ -976,14 +976,14 @@ def _encode_auth(auth):
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
- return encoded.replace('\n', '')
-
+ return encoded.replace('\n', '')
+
class Credential:
"""
A username/password pair. Use like a namedtuple.
"""
-
+
def __init__(self, username, password):
self.username = username
self.password = password
@@ -995,7 +995,7 @@ class Credential:
def __str__(self):
return '%(username)s:%(password)s' % vars(self)
-
+
class PyPIConfig(configparser.RawConfigParser):
def __init__(self):
"""
@@ -1055,7 +1055,7 @@ def open_with_auth(url, opener=urllib.request.urlopen):
if cred:
auth = str(cred)
info = cred.username, url
- log.info('Authenticating as %s for %s (from .pypirc)', *info)
+ log.info('Authenticating as %s for %s (from .pypirc)', *info)
if auth:
auth = "Basic " + _encode_auth(auth)
@@ -1079,7 +1079,7 @@ def open_with_auth(url, opener=urllib.request.urlopen):
return fp
-
+
# copy of urllib.parse._splituser from Python 3.8
def _splituser(host):
"""splituser('user[:passwd]@host[:port]')
@@ -1093,9 +1093,9 @@ open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
def fix_sf_url(url):
- return url # backward compatibility
-
+ return url # backward compatibility
+
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
diff --git a/contrib/python/setuptools/py3/setuptools/sandbox.py b/contrib/python/setuptools/py3/setuptools/sandbox.py
index 034fc80d20..a1f43f783c 100644
--- a/contrib/python/setuptools/py3/setuptools/sandbox.py
+++ b/contrib/python/setuptools/py3/setuptools/sandbox.py
@@ -32,7 +32,7 @@ __all__ = [
"run_setup",
]
-
+
def _execfile(filename, globals, locals=None):
"""
Python 3 implementation of execfile.
@@ -97,7 +97,7 @@ class UnpickleableException(Exception):
"""
An exception representing another Exception that could not be pickled.
"""
-
+
@staticmethod
def dump(type, exc):
"""
@@ -118,7 +118,7 @@ class ExceptionSaver:
A Context Manager that will save an exception, serialized, and restore it
later.
"""
-
+
def __enter__(self):
return self
@@ -248,12 +248,12 @@ def run_setup(setup_script, args):
setup_dir = os.path.abspath(os.path.dirname(setup_script))
with setup_context(setup_dir):
try:
- sys.argv[:] = [setup_script] + list(args)
+ sys.argv[:] = [setup_script] + list(args)
sys.path.insert(0, setup_dir)
# reset to include setup dir, w/clean callback list
working_set.__init__()
- working_set.callbacks.append(lambda dist: dist.activate())
-
+ working_set.callbacks.append(lambda dist: dist.activate())
+
with DirectorySandbox(setup_dir):
ns = dict(__file__=setup_script, __name__='__main__')
_execfile(setup_script, ns)
@@ -272,12 +272,12 @@ class AbstractSandbox:
self._attrs = [
name
for name in dir(_os)
- if not name.startswith('_') and hasattr(self, name)
+ if not name.startswith('_') and hasattr(self, name)
]
def _copy(self, source):
for name in self._attrs:
- setattr(os, name, getattr(source, name))
+ setattr(os, name, getattr(source, name))
def __enter__(self):
self._copy(self)
@@ -299,27 +299,27 @@ class AbstractSandbox:
return func()
def _mk_dual_path_wrapper(name):
- original = getattr(_os, name)
-
- def wrap(self, src, dst, *args, **kw):
+ original = getattr(_os, name)
+
+ def wrap(self, src, dst, *args, **kw):
if self._active:
- src, dst = self._remap_pair(name, src, dst, *args, **kw)
- return original(src, dst, *args, **kw)
-
+ src, dst = self._remap_pair(name, src, dst, *args, **kw)
+ return original(src, dst, *args, **kw)
+
return wrap
for name in ["rename", "link", "symlink"]:
- if hasattr(_os, name):
- locals()[name] = _mk_dual_path_wrapper(name)
+ if hasattr(_os, name):
+ locals()[name] = _mk_dual_path_wrapper(name)
def _mk_single_path_wrapper(name, original=None):
- original = original or getattr(_os, name)
-
- def wrap(self, path, *args, **kw):
+ original = original or getattr(_os, name)
+
+ def wrap(self, path, *args, **kw):
if self._active:
- path = self._remap_input(name, path, *args, **kw)
- return original(path, *args, **kw)
-
+ path = self._remap_input(name, path, *args, **kw)
+ return original(path, *args, **kw)
+
return wrap
if _file:
@@ -346,55 +346,55 @@ class AbstractSandbox:
"pathconf",
"access",
]:
- if hasattr(_os, name):
- locals()[name] = _mk_single_path_wrapper(name)
+ if hasattr(_os, name):
+ locals()[name] = _mk_single_path_wrapper(name)
def _mk_single_with_return(name):
- original = getattr(_os, name)
-
- def wrap(self, path, *args, **kw):
+ original = getattr(_os, name)
+
+ def wrap(self, path, *args, **kw):
if self._active:
- path = self._remap_input(name, path, *args, **kw)
- return self._remap_output(name, original(path, *args, **kw))
- return original(path, *args, **kw)
-
+ path = self._remap_input(name, path, *args, **kw)
+ return self._remap_output(name, original(path, *args, **kw))
+ return original(path, *args, **kw)
+
return wrap
for name in ['readlink', 'tempnam']:
- if hasattr(_os, name):
- locals()[name] = _mk_single_with_return(name)
+ if hasattr(_os, name):
+ locals()[name] = _mk_single_with_return(name)
def _mk_query(name):
- original = getattr(_os, name)
-
- def wrap(self, *args, **kw):
- retval = original(*args, **kw)
+ original = getattr(_os, name)
+
+ def wrap(self, *args, **kw):
+ retval = original(*args, **kw)
if self._active:
return self._remap_output(name, retval)
return retval
-
+
return wrap
for name in ['getcwd', 'tmpnam']:
- if hasattr(_os, name):
- locals()[name] = _mk_query(name)
+ if hasattr(_os, name):
+ locals()[name] = _mk_query(name)
- def _validate_path(self, path):
+ def _validate_path(self, path):
"""Called to remap or validate any path, whether input or output"""
return path
- def _remap_input(self, operation, path, *args, **kw):
+ def _remap_input(self, operation, path, *args, **kw):
"""Called for path inputs"""
return self._validate_path(path)
- def _remap_output(self, operation, path):
+ def _remap_output(self, operation, path):
"""Called for path outputs"""
return self._validate_path(path)
- def _remap_pair(self, operation, src, dst, *args, **kw):
+ def _remap_pair(self, operation, src, dst, *args, **kw):
"""Called for path pairs like rename, link, and symlink operations"""
return (
- self._remap_input(operation + '-from', src, *args, **kw),
+ self._remap_input(operation + '-from', src, *args, **kw),
self._remap_input(operation + '-to', dst, *args, **kw),
)
@@ -431,7 +431,7 @@ class DirectorySandbox(AbstractSandbox):
def __init__(self, sandbox, exceptions=_EXCEPTIONS):
self._sandbox = os.path.normcase(os.path.realpath(sandbox))
- self._prefix = os.path.join(self._sandbox, '')
+ self._prefix = os.path.join(self._sandbox, '')
self._exceptions = [
os.path.normcase(os.path.realpath(path)) for path in exceptions
]
@@ -443,16 +443,16 @@ class DirectorySandbox(AbstractSandbox):
raise SandboxViolation(operation, args, kw)
if _file:
-
+
def _file(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("file", path, mode, *args, **kw)
- return _file(path, mode, *args, **kw)
+ return _file(path, mode, *args, **kw)
def _open(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
self._violation("open", path, mode, *args, **kw)
- return _open(path, mode, *args, **kw)
+ return _open(path, mode, *args, **kw)
def tmpnam(self):
self._violation("tmpnam")
@@ -490,15 +490,15 @@ class DirectorySandbox(AbstractSandbox):
"""Called for path pairs like rename, link, and symlink operations"""
if not self._ok(src) or not self._ok(dst):
self._violation(operation, src, dst, *args, **kw)
- return (src, dst)
+ return (src, dst)
def open(self, file, flags, mode=0o777, *args, **kw):
"""Called for low-level os.open()"""
if flags & WRITE_FLAGS and not self._ok(file):
self._violation("os.open", file, flags, mode, *args, **kw)
- return _os.open(file, flags, mode, *args, **kw)
-
+ return _os.open(file, flags, mode, *args, **kw)
+
WRITE_FLAGS = functools.reduce(
operator.or_,
[
@@ -507,7 +507,7 @@ WRITE_FLAGS = functools.reduce(
],
)
-
+
class SandboxViolation(DistutilsError):
"""A setup script attempted to modify the filesystem outside the sandbox"""
diff --git a/contrib/python/setuptools/py3/setuptools/version.py b/contrib/python/setuptools/py3/setuptools/version.py
index 95e1869658..1385d5af6d 100644
--- a/contrib/python/setuptools/py3/setuptools/version.py
+++ b/contrib/python/setuptools/py3/setuptools/version.py
@@ -1,6 +1,6 @@
-import pkg_resources
-
-try:
- __version__ = pkg_resources.get_distribution('setuptools').version
-except Exception:
- __version__ = 'unknown'
+import pkg_resources
+
+try:
+ __version__ = pkg_resources.get_distribution('setuptools').version
+except Exception:
+ __version__ = 'unknown'
diff --git a/contrib/python/setuptools/py3/ya.make b/contrib/python/setuptools/py3/ya.make
index 5682b6f782..76f191c556 100644
--- a/contrib/python/setuptools/py3/ya.make
+++ b/contrib/python/setuptools/py3/ya.make
@@ -5,17 +5,17 @@ OWNER(borman orivej g:python-contrib)
VERSION(59.7.0)
LICENSE(MIT)
-
-PEERDIR(
- library/python/resource
-)
-
+
+PEERDIR(
+ library/python/resource
+)
+
NO_LINT()
-NO_CHECK_IMPORTS(
- setuptools.*
-)
-
+NO_CHECK_IMPORTS(
+ setuptools.*
+)
+
PY_SRCS(
TOP_LEVEL
_distutils_hack/__init__.py
@@ -116,7 +116,7 @@ PY_SRCS(
setuptools/command/alias.py
setuptools/command/bdist_egg.py
setuptools/command/bdist_rpm.py
- setuptools/command/build_clib.py
+ setuptools/command/build_clib.py
setuptools/command/build_ext.py
setuptools/command/build_py.py
setuptools/command/develop.py
@@ -127,28 +127,28 @@ PY_SRCS(
setuptools/command/install_egg_info.py
setuptools/command/install_lib.py
setuptools/command/install_scripts.py
- setuptools/command/py36compat.py
+ setuptools/command/py36compat.py
setuptools/command/register.py
setuptools/command/rotate.py
setuptools/command/saveopts.py
setuptools/command/sdist.py
setuptools/command/setopt.py
setuptools/command/test.py
- setuptools/command/upload.py
+ setuptools/command/upload.py
setuptools/command/upload_docs.py
- setuptools/config.py
- setuptools/dep_util.py
+ setuptools/config.py
+ setuptools/dep_util.py
setuptools/depends.py
setuptools/dist.py
setuptools/errors.py
setuptools/extension.py
setuptools/extern/__init__.py
- setuptools/glob.py
+ setuptools/glob.py
setuptools/installer.py
setuptools/launch.py
- setuptools/monkey.py
- setuptools/msvc.py
- setuptools/namespaces.py
+ setuptools/monkey.py
+ setuptools/msvc.py
+ setuptools/namespaces.py
setuptools/package_index.py
setuptools/py34compat.py
setuptools/sandbox.py