Commit 2a0db96e authored by Jason R. Coombs's avatar Jason R. Coombs Committed by GitHub

Merge pull request #749 from stepshal/E3

Fix quantity of blank lines after code object, class of function definition.
parents c296634d 08511f5f
......@@ -209,10 +209,12 @@ 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()
......@@ -220,25 +222,31 @@ def __getstate__():
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)
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
......@@ -265,6 +273,7 @@ def get_supported_platform():
pass
return plat
__all__ = [
# Basic resource access and distribution/entry point discovery
'require', 'run_script', 'get_provider', 'get_distribution',
......@@ -311,8 +320,10 @@ __all__ = [
'run_main', 'AvailableDistributions',
]
class ResolutionError(Exception):
"""Abstract base for dependency resolution errors"""
def __repr__(self):
return self.__class__.__name__ + repr(self.args)
......@@ -391,6 +402,8 @@ class DistributionNotFound(ResolutionError):
class UnknownExtra(ResolutionError):
"""Distribution doesn't have an "extra feature" of the given name"""
_provider_factories = {}
PY_MAJOR = sys.version[:3]
......@@ -400,6 +413,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`
......@@ -409,6 +423,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):
......@@ -421,6 +436,7 @@ def get_provider(moduleOrReq):
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module)
def _macosx_vers(_cache=[]):
if not _cache:
version = platform.mac_ver()[0]
......@@ -436,9 +452,11 @@ def _macosx_vers(_cache=[]):
_cache.append(version.split('.'))
return _cache[0]
def _macosx_arch(machine):
return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
def get_build_platform():
"""Return this platform's string for platform-specific distributions
......@@ -464,6 +482,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
......@@ -524,9 +543,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, six.string_types):
......@@ -537,14 +558,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)
......@@ -1332,6 +1356,7 @@ class ResourceManager:
"""
# XXX
def get_default_cache():
"""Determine the default cache location
......@@ -1376,6 +1401,7 @@ def get_default_cache():
"Please set the PYTHON_EGG_CACHE environment variable"
)
def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
......@@ -1538,6 +1564,7 @@ class NullProvider:
"Can't perform this operation for loaders without 'get_data()'"
)
register_loader_type(object, NullProvider)
......@@ -1562,6 +1589,7 @@ class EggProvider(NullProvider):
old = path
path, base = os.path.split(path)
class DefaultProvider(EggProvider):
"""Provides access to package resources in the filesystem"""
......@@ -1587,6 +1615,7 @@ class DefaultProvider(EggProvider):
type(None))
register_loader_type(loader_cls, cls)
DefaultProvider._register()
......@@ -1601,6 +1630,7 @@ class EmptyProvider(NullProvider):
def __init__(self):
pass
empty_provider = EmptyProvider()
......@@ -1836,6 +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)
......@@ -1913,8 +1944,10 @@ class EggMetadata(ZipProvider):
self.module_path = importer.archive
self._setup_prefix()
_declare_state('dict', _distribution_finders={})
def register_finder(importer_type, distribution_finder):
"""Register `distribution_finder` to find distributions in sys.path items
......@@ -1931,6 +1964,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.
......@@ -1951,12 +1985,17 @@ def find_eggs_in_zip(importer, path_item, only=False):
for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath):
yield dist
register_finder(zipimport.zipimporter, find_eggs_in_zip)
def find_nothing(importer, path_item, only=False):
return ()
register_finder(object, find_nothing)
def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
......@@ -1997,6 +2036,8 @@ def find_on_path(importer, path_item, only=False):
for item in dists:
yield item
break
register_finder(pkgutil.ImpImporter, find_on_path)
if hasattr(importlib_machinery, 'FileFinder'):
......@@ -2023,6 +2064,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)"""
......@@ -2055,6 +2097,7 @@ 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 position_in_sys_path(path):
"""
Return the ordinal of the path based on its position in sys.path
......@@ -2100,6 +2143,7 @@ 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()
......@@ -2111,6 +2155,7 @@ def fixup_namespace_packages(path_item, parent=None):
finally:
_imp.release_lock()
def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
......@@ -2123,6 +2168,7 @@ def file_ns_handler(importer, path_item, packageName, module):
# 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)
......@@ -2133,6 +2179,7 @@ if hasattr(importlib_machinery, 'FileFinder'):
def null_ns_handler(importer, path_item, packageName, module):
return None
register_namespace_handler(object, null_ns_handler)
......@@ -2140,6 +2187,7 @@ def normalize_path(filename):
"""Normalize a file/dir name for comparison purposes"""
return os.path.normcase(os.path.realpath(filename))
def _normalize_cached(filename, _cache={}):
try:
return _cache[filename]
......@@ -2147,6 +2195,7 @@ def _normalize_cached(filename, _cache={}):
_cache[filename] = result = normalize_path(filename)
return result
def _is_unpacked_egg(path):
"""
Determine if given path appears to be an unpacked egg.
......@@ -2155,6 +2204,7 @@ def _is_unpacked_egg(path):
path.lower().endswith('.egg')
)
def _set_parent_ns(packageName):
parts = packageName.split('.')
name = parts.pop()
......@@ -2176,6 +2226,7 @@ def yield_lines(strs):
for s in yield_lines(ss):
yield s
MODULE = re.compile(r"\w+(\.\w+)*$").match
EGG_NAME = re.compile(
r"""
......@@ -2783,6 +2834,7 @@ def issue_warning(*args, **kw):
class RequirementParseError(ValueError):
def __str__(self):
return ' '.join(self.args)
......@@ -2807,6 +2859,7 @@ def parse_requirements(strs):
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
try:
......@@ -2867,6 +2920,7 @@ def _get_mro(cls):
return cls.__mro__[1:]
return cls.__mro__
def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
for t in _get_mro(getattr(ob, '__class__', type(ob))):
......@@ -2916,6 +2970,7 @@ def split_sections(s):
# wrap up last segment
yield section, content
def _mkstemp(*args, **kw):
old_open = os.open
try:
......
......@@ -6,6 +6,7 @@ class VendorImporter:
A PEP 302 meta path importer for finding optionally-vendored
or otherwise naturally-installed packages from root_name.
"""
def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
self.root_name = root_name
self.vendored_names = set(vendored_names)
......@@ -67,5 +68,6 @@ class VendorImporter:
if self not in sys.meta_path:
sys.meta_path.append(self)
names = 'packaging', 'pyparsing', 'six'
VendorImporter(__name__, names).install()
......@@ -5,6 +5,7 @@ except ImportError:
from pkg_resources import evaluate_marker
@mock.patch('platform.python_version', return_value='2.7.10')
def test_ordering(python_version_mock):
assert evaluate_marker("python_full_version > '2.7.3'") is True
......@@ -24,6 +24,7 @@ try:
except NameError:
unicode = str
def timestamp(dt):
"""
Return a timestamp for a local, naive datetime instance.
......@@ -34,13 +35,16 @@ def timestamp(dt):
# Python 3.2 and earlier
return time.mktime(dt.timetuple())
class EggRemover(unicode):
def __call__(self):
if self in sys.path:
sys.path.remove(self)
if os.path.exists(self):
os.remove(self)
class TestZipProvider(object):
finalizers = []
......@@ -94,7 +98,9 @@ class TestZipProvider(object):
assert f.read() == 'hello, world!'
manager.cleanup_resources()
class TestResourceManager(object):
def test_get_cache_path(self):
mgr = pkg_resources.ResourceManager()
path = mgr.get_cache_path('foo')
......@@ -107,6 +113,7 @@ class TestIndependence:
"""
Tests to ensure that pkg_resources runs independently from setuptools.
"""
def test_setuptools_not_imported(self):
"""
In a separate Python environment, import pkg_resources and assert
......@@ -122,7 +129,6 @@ class TestIndependence:
subprocess.check_call(cmd)
class TestDeepVersionLookupDistutils(object):
@pytest.fixture
......
......@@ -34,6 +34,7 @@ class Metadata(pkg_resources.EmptyProvider):
dist_from_fn = pkg_resources.Distribution.from_filename
class TestDistro:
def testCollection(self):
......@@ -294,6 +295,7 @@ class TestDistro:
class TestWorkingSet:
def test_find_conflicting(self):
ws = WorkingSet([])
Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg")
......@@ -380,6 +382,7 @@ class TestEntryPoints:
assert ep.name == 'html+mako'
reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2"
@pytest.mark.parametrize("reject_spec", reject_specs)
def test_reject_spec(self, reject_spec):
with pytest.raises(ValueError):
......@@ -434,6 +437,7 @@ class TestEntryPoints:
with pytest.raises(ValueError):
EntryPoint.parse_map(self.submap_str)
class TestRequirements:
def testBasics(self):
......
......@@ -59,6 +59,7 @@ elif os.name != 'nt':
if_dl = lambda s: s if have_rtld else ''
def get_abi3_suffix():
"""Return the file extension for an abi3-compliant Extension()"""
for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION):
......@@ -67,6 +68,7 @@ def get_abi3_suffix():
elif suffix == '.pyd': # Windows
return suffix
class build_ext(_build_ext):
def run(self):
......
......@@ -8,6 +8,7 @@ from setuptools.command.build_ext import build_ext, get_abi3_suffix
from setuptools.dist import Distribution
from setuptools.extension import Extension
class TestBuildExt:
def test_get_ext_filename(self):
......
......@@ -51,6 +51,7 @@ def quiet():
def touch(filename):
open(filename, 'w').close()
# The set of files always in the manifest, including all files in the
# .egg-info directory
default_files = frozenset(map(make_local_path, [
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment