desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Threads are created only when get_project is called, and terminate
before it returns. They are there primarily to parallelise I/O (i.e.
fetching web pages).'
| def _prepare_threads(self):
| self._threads = []
for i in range(self.num_workers):
t = threading.Thread(target=self._fetch)
t.setDaemon(True)
t.start()
self._threads.append(t)
|
'Tell all the threads to terminate (by sending a sentinel value) and
wait for them to do so.'
| def _wait_threads(self):
| for t in self._threads:
self._to_fetch.put(None)
for t in self._threads:
t.join()
self._threads = []
|
'Does an URL refer to a platform-specific download?'
| def _is_platform_dependent(self, url):
| return self.platform_dependent.search(url)
|
'See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it\'s for.
Note that the return value isn\'t actually used other than as a boolean
value.'
| def _process_download(self, url):
| if self._is_platform_dependent(url):
info = None
else:
info = self.convert_url_to_download_info(url, self.project_name)
logger.debug('process_download: %s -> %s', url, info)
if info:
with self._lock:
self._update_version_data(self.result, info)
return info
|
'Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.'
| def _should_queue(self, link, referrer, rel):
| (scheme, netloc, path, _, _, _) = urlparse(link)
if path.endswith(((self.source_extensions + self.binary_extensions) + self.excluded_extensions)):
result = False
elif (self.skip_externals and (not link.startswith(self.base_url))):
result = False
elif (not referrer.startswith(self.base_url)):
result = False
elif (rel not in ('homepage', 'download')):
result = False
elif (scheme not in ('http', 'https', 'ftp')):
result = False
elif self._is_platform_dependent(link):
result = False
else:
host = netloc.split(':', 1)[0]
if (host.lower() == 'localhost'):
result = False
else:
result = True
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel, referrer, result)
return result
|
'Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread.'
| def _fetch(self):
| while True:
url = self._to_fetch.get()
try:
if url:
page = self.get_page(url)
if (page is None):
continue
for (link, rel) in page.links:
if (link not in self._seen):
self._seen.add(link)
if ((not self._process_download(link)) and self._should_queue(link, url, rel)):
logger.debug('Queueing %s from %s', link, url)
self._to_fetch.put(link)
finally:
self._to_fetch.task_done()
if (not url):
break
|
'Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It\'s assumed that
the data won\'t get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).'
| def get_page(self, url):
| (scheme, netloc, path, _, _, _) = urlparse(url)
if ((scheme == 'file') and os.path.isdir(url2pathname(path))):
url = urljoin(ensure_slash(url), 'index.html')
if (url in self._page_cache):
result = self._page_cache[url]
logger.debug('Returning %s from cache: %s', url, result)
else:
host = netloc.split(':', 1)[0]
result = None
if (host in self._bad_hosts):
logger.debug('Skipping %s due to bad host %s', url, host)
else:
req = Request(url, headers={'Accept-encoding': 'identity'})
try:
logger.debug('Fetching %s', url)
resp = self.opener.open(req, timeout=self.timeout)
logger.debug('Fetched %s', url)
headers = resp.info()
content_type = headers.get('Content-Type', '')
if HTML_CONTENT_TYPE.match(content_type):
final_url = resp.geturl()
data = resp.read()
encoding = headers.get('Content-Encoding')
if encoding:
decoder = self.decoders[encoding]
data = decoder(data)
encoding = 'utf-8'
m = CHARSET.search(content_type)
if m:
encoding = m.group(1)
try:
data = data.decode(encoding)
except UnicodeError:
data = data.decode('latin-1')
result = Page(data, final_url)
self._page_cache[final_url] = result
except HTTPError as e:
if (e.code != 404):
logger.exception('Fetch failed: %s: %s', url, e)
except URLError as e:
logger.exception('Fetch failed: %s: %s', url, e)
with self._lock:
self._bad_hosts.add(host)
except Exception as e:
logger.exception('Fetch failed: %s: %s', url, e)
finally:
self._page_cache[url] = result
return result
|
'Return all the distribution names known to this locator.'
| def get_distribution_names(self):
| result = set()
page = self.get_page(self.base_url)
if (not page):
raise DistlibException(('Unable to get %s' % self.base_url))
for match in self._distname_re.finditer(page.data):
result.add(match.group(1))
return result
|
'Initialise an instance.
:param path: The root of the directory tree to search.
:param kwargs: Passed to the superclass constructor,
except for:
* recursive - if True (the default), subdirectories are
recursed into. If False, only the top-level directory
is searched,'
| def __init__(self, path, **kwargs):
| self.recursive = kwargs.pop('recursive', True)
super(DirectoryLocator, self).__init__(**kwargs)
path = os.path.abspath(path)
if (not os.path.isdir(path)):
raise DistlibException(('Not a directory: %r' % path))
self.base_dir = path
|
'Should a filename be considered as a candidate for a distribution
archive? As well as the filename, the directory which contains it
is provided, though not used by the current implementation.'
| def should_include(self, filename, parent):
| return filename.endswith(self.downloadable_extensions)
|
'Return all the distribution names known to this locator.'
| def get_distribution_names(self):
| result = set()
for (root, dirs, files) in os.walk(self.base_dir):
for fn in files:
if self.should_include(fn, root):
fn = os.path.join(root, fn)
url = urlunparse(('file', '', pathname2url(os.path.abspath(fn)), '', '', ''))
info = self.convert_url_to_download_info(url, None)
if info:
result.add(info['name'])
if (not self.recursive):
break
return result
|
'Return all the distribution names known to this locator.'
| def get_distribution_names(self):
| raise NotImplementedError('Not available from this locator')
|
'Initialise an instance.
:param distpath: A :class:`DistributionPath` instance to search.'
| def __init__(self, distpath, **kwargs):
| super(DistPathLocator, self).__init__(**kwargs)
assert isinstance(distpath, DistributionPath)
self.distpath = distpath
|
'Initialise an instance.
:param locators: The list of locators to search.
:param kwargs: Passed to the superclass constructor,
except for:
* merge - if False (the default), the first successful
search from any of the locators is returned. If True,
the results from all locators are merged (this can be
slow).'
| def __init__(self, *locators, **kwargs):
| self.merge = kwargs.pop('merge', False)
self.locators = locators
super(AggregatingLocator, self).__init__(**kwargs)
|
'Return all the distribution names known to this locator.'
| def get_distribution_names(self):
| result = set()
for locator in self.locators:
try:
result |= locator.get_distribution_names()
except NotImplementedError:
pass
return result
|
'Initialise an instance, using the specified locator
to locate distributions.'
| def __init__(self, locator=None):
| self.locator = (locator or default_locator)
self.scheme = get_scheme(self.locator.scheme)
|
'Add a distribution to the finder. This will update internal information
about who provides what.
:param dist: The distribution to add.'
| def add_distribution(self, dist):
| logger.debug('adding distribution %s', dist)
name = dist.key
self.dists_by_name[name] = dist
self.dists[(name, dist.version)] = dist
for p in dist.provides:
(name, version) = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
self.provided.setdefault(name, set()).add((version, dist))
|
'Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.'
| def remove_distribution(self, dist):
| logger.debug('removing distribution %s', dist)
name = dist.key
del self.dists_by_name[name]
del self.dists[(name, dist.version)]
for p in dist.provides:
(name, version) = parse_name_and_version(p)
logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
s = self.provided[name]
s.remove((version, dist))
if (not s):
del self.provided[name]
|
'Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).'
| def get_matcher(self, reqt):
| try:
matcher = self.scheme.matcher(reqt)
except UnsupportedVersionError:
name = reqt.split()[0]
matcher = self.scheme.matcher(name)
return matcher
|
'Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.'
| def find_providers(self, reqt):
| matcher = self.get_matcher(reqt)
name = matcher.key
result = set()
provided = self.provided
if (name in provided):
for (version, provider) in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
result.add(provider)
break
return result
|
'Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet all the requirements
which ``other`` fulfills.
:param provider: The provider we are trying to replace with.
:param other: The provider we\'re trying to replace.
:param problems: If False is returned, this will contain what
problems prevented replacement. This is currently
a tuple of the literal string \'cantreplace\',
``provider``, ``other`` and the set of requirements
that ``provider`` couldn\'t fulfill.
:return: True if we can replace ``other`` with ``provider``, else
False.'
| def try_to_replace(self, provider, other, problems):
| rlist = self.reqts[other]
unmatched = set()
for s in rlist:
matcher = self.get_matcher(s)
if (not matcher.match(provider.version)):
unmatched.add(s)
if unmatched:
problems.add(('cantreplace', provider, other, frozenset(unmatched)))
result = False
else:
self.remove_distribution(other)
del self.reqts[other]
for s in rlist:
self.reqts.setdefault(provider, set()).add(s)
self.add_distribution(provider)
result = True
return result
|
'Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:param prereleases: If ``True``, allow pre-release versions to be
returned - otherwise, don\'t return prereleases
unless they\'re all that\'s available.
Return a set of :class:`Distribution` instances and a set of
problems.
The distributions returned should be such that they have the
:attr:`required` attribute set to ``True`` if they were
from the ``requirement`` passed to ``find()``, and they have the
:attr:`build_time_dependency` attribute set to ``True`` unless they
are post-installation dependencies of the ``requirement``.
The problems should be a tuple consisting of the string
``\'unsatisfied\'`` and the requirement which couldn\'t be satisfied
by any distribution known to the locator.'
| def find(self, requirement, meta_extras=None, prereleases=False):
| self.provided = {}
self.dists = {}
self.dists_by_name = {}
self.reqts = {}
meta_extras = set((meta_extras or []))
if (':*:' in meta_extras):
meta_extras.remove(':*:')
meta_extras |= set([':test:', ':build:', ':dev:'])
if isinstance(requirement, Distribution):
dist = odist = requirement
logger.debug('passed %s as requirement', odist)
else:
dist = odist = self.locator.locate(requirement, prereleases=prereleases)
if (dist is None):
raise DistlibException(('Unable to locate %r' % requirement))
logger.debug('located %s', odist)
dist.requested = True
problems = set()
todo = set([dist])
install_dists = set([odist])
while todo:
dist = todo.pop()
name = dist.key
if (name not in self.dists_by_name):
self.add_distribution(dist)
else:
other = self.dists_by_name[name]
if (other != dist):
self.try_to_replace(dist, other, problems)
ireqts = (dist.run_requires | dist.meta_requires)
sreqts = dist.build_requires
ereqts = set()
if (dist in install_dists):
for key in ('test', 'build', 'dev'):
e = (':%s:' % key)
if (e in meta_extras):
ereqts |= getattr(dist, ('%s_requires' % key))
all_reqts = ((ireqts | sreqts) | ereqts)
for r in all_reqts:
providers = self.find_providers(r)
if (not providers):
logger.debug('No providers found for %r', r)
provider = self.locator.locate(r, prereleases=prereleases)
if ((provider is None) and (not prereleases)):
provider = self.locator.locate(r, prereleases=True)
if (provider is None):
logger.debug('Cannot satisfy %r', r)
problems.add(('unsatisfied', r))
else:
(n, v) = (provider.key, provider.version)
if ((n, v) not in self.dists):
todo.add(provider)
providers.add(provider)
if ((r in ireqts) and (dist in install_dists)):
install_dists.add(provider)
logger.debug('Adding %s to install_dists', provider.name_and_version)
for p in providers:
name = p.key
if (name not in self.dists_by_name):
self.reqts.setdefault(p, set()).add(r)
else:
other = self.dists_by_name[name]
if (other != p):
self.try_to_replace(p, other, problems)
dists = set(self.dists.values())
for dist in dists:
dist.build_time_dependency = (dist not in install_dists)
if dist.build_time_dependency:
logger.debug('%s is a build-time dependency only.', dist.name_and_version)
logger.debug('find done for %s', odist)
return (dists, problems)
|
'If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.'
| def with_context(self, required_by):
| if (not required_by):
return self
args = (self.args + (required_by,))
return ContextualVersionConflict(*args)
|
'Create working set from list of path entries (default=sys.path)'
| def __init__(self, entries=None):
| self.entries = []
self.entry_keys = {}
self.by_key = {}
self.callbacks = []
if (entries is None):
entries = sys.path
for entry in entries:
self.add_entry(entry)
|
'Prepare the master working set.'
| @classmethod
def _build_master(cls):
| ws = cls()
try:
from __main__ import __requires__
except ImportError:
return ws
try:
ws.require(__requires__)
except VersionConflict:
return cls._build_from_requirements(__requires__)
return ws
|
'Build a working set from a requirement spec. Rewrites sys.path.'
| @classmethod
def _build_from_requirements(cls, req_spec):
| ws = cls([])
reqs = parse_requirements(req_spec)
dists = ws.resolve(reqs, Environment())
for dist in dists:
ws.add(dist)
for entry in sys.path:
if (entry not in ws.entries):
ws.add_entry(entry)
sys.path[:] = ws.entries
return ws
|
'Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value more than
once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
equal ``sys.path``.)'
| def add_entry(self, entry):
| self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False)
|
'True if `dist` is the active distribution for its project'
| def __contains__(self, dist):
| return (self.by_key.get(dist.key) == dist)
|
'Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.'
| def find(self, req):
| dist = self.by_key.get(req.key)
if ((dist is not None) and (dist not in req)):
raise VersionConflict(dist, req)
return dist
|
'Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).'
| def iter_entry_points(self, group, name=None):
| for dist in self:
entries = dist.get_entry_map(group)
if (name is None):
for ep in entries.values():
(yield ep)
elif (name in entries):
(yield entries[name])
|
'Locate distribution for `requires` and run `script_name` script'
| def run_script(self, requires, script_name):
| ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns)
|
'Yield distributions for non-duplicate projects in the working set
The yield order is the order in which the items\' path entries were
added to the working set.'
| def __iter__(self):
| seen = {}
for item in self.entries:
if (item not in self.entry_keys):
continue
for key in self.entry_keys[item]:
if (key not in seen):
seen[key] = 1
(yield self.by_key[key])
|
'Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set\'s ``.entries`` (if it wasn\'t already present).
`dist` is only added to the working set if it\'s for a project that
doesn\'t already have a distribution in the set, unless `replace=True`.
If it\'s added, any callbacks registered with the ``subscribe()`` method
will be called.'
| def add(self, dist, entry=None, insert=True, replace=False):
| if insert:
dist.insert_on(self.entries, entry, replace=replace)
if (entry is None):
entry = 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)):
return
self.by_key[dist.key] = dist
if (dist.key not in keys):
keys.append(dist.key)
if (dist.key not in keys2):
keys2.append(dist.key)
self._added_new(dist)
|
'List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if supplied,
will be invoked with each requirement that cannot be met by an
already-installed distribution; it should return a ``Distribution`` or
``None``.
Unless `replace_conflicting=True`, raises a VersionConflict exception if
any requirements are found on the path that have the correct name but
the wrong version. Otherwise, if an `installer` is supplied it will be
invoked to obtain the correct version of the requirement and activate
it.'
| def resolve(self, requirements, env=None, installer=None, replace_conflicting=False):
| requirements = list(requirements)[::(-1)]
processed = {}
best = {}
to_activate = []
required_by = collections.defaultdict(set)
while requirements:
req = requirements.pop(0)
if (req in processed):
continue
dist = best.get(req.key)
if (dist is None):
dist = self.by_key.get(req.key)
if ((dist is None) or ((dist not in req) and replace_conflicting)):
ws = self
if (env is None):
if (dist is None):
env = Environment(self.entries)
else:
env = Environment([])
ws = WorkingSet([])
dist = best[req.key] = env.best_match(req, ws, installer)
if (dist is None):
requirers = required_by.get(req, None)
raise DistributionNotFound(req, requirers)
to_activate.append(dist)
if (dist not in req):
dependent_req = required_by[req]
raise VersionConflict(dist, req).with_context(dependent_req)
new_requirements = dist.requires(req.extras)[::(-1)]
requirements.extend(new_requirements)
for new_requirement in new_requirements:
required_by[new_requirement].add(req.project_name)
processed[req] = True
return to_activate
|
'Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
# add plugins+libs to sys.path
map(working_set.add, distributions)
# display errors
print(\'Could not load\', errors)
The `plugin_env` should be an ``Environment`` instance that contains
only distributions that are in the project\'s "plugin directory" or
directories. The `full_env`, if supplied, should be an ``Environment``
contains all currently-available distributions. If `full_env` is not
supplied, one is created automatically from the ``WorkingSet`` this
method is called on, which will typically mean that every directory on
``sys.path`` will be scanned for distributions.
`installer` is a standard installer callback as used by the
``resolve()`` method. The `fallback` flag indicates whether we should
attempt to resolve older versions of a plugin if the newest version
cannot be resolved.
This method returns a 2-tuple: (`distributions`, `error_info`), where
`distributions` is a list of the distributions found in `plugin_env`
that were loadable, along with any other distributions that are needed
to resolve their dependencies. `error_info` is a dictionary mapping
unloadable plugin distributions to an exception instance describing the
error that occurred. Usually this will be a ``DistributionNotFound`` or
``VersionConflict`` instance.'
| def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True):
| plugin_projects = list(plugin_env)
plugin_projects.sort()
error_info = {}
distributions = {}
if (full_env is None):
env = Environment(self.entries)
env += plugin_env
else:
env = (full_env + plugin_env)
shadow_set = self.__class__([])
list(map(shadow_set.add, self))
for project_name in plugin_projects:
for dist in plugin_env[project_name]:
req = [dist.as_requirement()]
try:
resolvees = shadow_set.resolve(req, env, installer)
except ResolutionError as v:
error_info[dist] = v
if fallback:
continue
else:
break
else:
list(map(shadow_set.add, resolvees))
distributions.update(dict.fromkeys(resolvees))
break
distributions = list(distributions)
distributions.sort()
return (distributions, error_info)
|
'Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distributions are
included, even if they were already activated in this working set.'
| def require(self, *requirements):
| needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed
|
'Invoke `callback` for all distributions (including existing ones)'
| def subscribe(self, callback):
| if (callback in self.callbacks):
return
self.callbacks.append(callback)
for dist in self:
callback(dist)
|
'Snapshot distributions available on a search path
Any distributions found on `search_path` are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used.
`platform` is an optional string specifying the name of the platform
that platform-specific distributions must be compatible with. If
unspecified, it defaults to the current platform. `python` is an
optional string naming the desired version of Python (e.g. ``\'3.3\'``);
it defaults to the current version.
You may explicitly set `platform` (and/or `python`) to ``None`` if you
wish to map *all* distributions, not just those compatible with the
running platform or Python version.'
| def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
| self._distmap = {}
self.platform = platform
self.python = python
self.scan(search_path)
|
'Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.'
| def can_add(self, dist):
| return (((self.python is None) or (dist.py_version is None) or (dist.py_version == self.python)) and compatible_platforms(dist.platform, self.platform))
|
'Remove `dist` from the environment'
| def remove(self, dist):
| self._distmap[dist.key].remove(dist)
|
'Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.'
| def scan(self, search_path=None):
| if (search_path is None):
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist)
|
'Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project\'s distributions use their project\'s name converted to all
lowercase as their key.'
| def __getitem__(self, project_name):
| distribution_key = project_name.lower()
return self._distmap.get(distribution_key, [])
|
'Add `dist` if we ``can_add()`` it and it has not already been added'
| def add(self, dist):
| if (self.can_add(dist) and dist.has_version()):
dists = self._distmap.setdefault(dist.key, [])
if (dist not in dists):
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
|
'Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn\'t active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment\'s ``obtain(req, installer)`` method will be
returned.'
| def best_match(self, req, working_set, installer=None):
| dist = working_set.find(req)
if (dist is not None):
return dist
for dist in self[req.key]:
if (dist in req):
return dist
return self.obtain(req, installer)
|
'Obtain a distribution matching `requirement` (e.g. via download)
Obtain a distro that matches requirement (e.g. via download). In the
base ``Environment`` class, this routine just returns
``installer(requirement)``, unless `installer` is None, in which case
None is returned instead. This method is a hook that allows subclasses
to attempt other ways of obtaining a distribution before falling back
to the `installer` argument.'
| def obtain(self, requirement, installer=None):
| if (installer is not None):
return installer(requirement)
|
'Yield the unique project names of the available distributions'
| def __iter__(self):
| for key in self._distmap.keys():
if self[key]:
(yield key)
|
'In-place addition of a distribution or environment'
| def __iadd__(self, other):
| if isinstance(other, Distribution):
self.add(other)
elif isinstance(other, Environment):
for project in other:
for dist in other[project]:
self.add(dist)
else:
raise TypeError(("Can't add %r to environment" % (other,)))
return self
|
'Add an environment or distribution to an environment'
| def __add__(self, other):
| new = self.__class__([], platform=None, python=None)
for env in (self, other):
new += env
return new
|
'Does the named resource exist?'
| def resource_exists(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).has_resource(resource_name)
|
'Is the named resource an existing directory?'
| def resource_isdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_isdir(resource_name)
|
'Return a true filesystem path for specified resource'
| def resource_filename(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
|
'Return a readable file-like object for specified resource'
| def resource_stream(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
|
'Return specified resource as a string'
| def resource_string(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_string(self, resource_name)
|
'List the contents of the named resource directory'
| def resource_listdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_listdir(resource_name)
|
'Give an error message for problems extracting file(s)'
| def extraction_error(self):
| old_exc = sys.exc_info()[1]
cache_path = (self.extraction_path or get_default_cache())
err = ExtractionError(("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n %s\n\nThe Python egg cache directory is currently set to:\n\n %s\n\nPerhaps your account does not have write access to this directory? You can\nchange the cache directory by setting the PYTHON_EGG_CACHE environment\nvariable to point to an accessible directory.\n" % (old_exc, cache_path)))
err.manager = self
err.cache_path = cache_path
err.original_error = old_exc
raise err
|
'Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not be the name of the enclosing zipfile!),
including its ".egg" extension. `names`, if provided, should be a
sequence of path name parts "under" the egg\'s extraction location.
This method should only be called by resource providers that need to
obtain an extraction location, and only for names they intend to
extract, as it tracks the generated names for possible cleanup later.'
| def get_cache_path(self, archive_name, names=()):
| extract_path = (self.extraction_path or get_default_cache())
target_path = os.path.join(extract_path, (archive_name + '-tmp'), *names)
try:
_bypass_ensure_directory(target_path)
except:
self.extraction_error()
self._warn_unsafe_extraction_path(extract_path)
self.cached_files[target_path] = 1
return target_path
|
'If the default extraction path is overridden and set to an insecure
location, such as /tmp, it opens up an opportunity for an attacker to
replace an extracted file with an unauthorized payload. Warn the user
if a known insecure location is used.
See Distribute #375 for more details.'
| @staticmethod
def _warn_unsafe_extraction_path(path):
| if ((os.name == 'nt') and (not path.startswith(os.environ['windir']))):
return
mode = os.stat(path).st_mode
if ((mode & stat.S_IWOTH) or (mode & stat.S_IWGRP)):
msg = ('%s is writable by group/others and vulnerable to attack when used with get_resource_filename. Consider a more secure location (set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable).' % path)
warnings.warn(msg, UserWarning)
|
'Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don\'t
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are already in the filesystem.
`tempname` is the current (temporary) name of the file, and `filename`
is the name it will be renamed to by the caller after this routine
returns.'
| def postprocess(self, tempname, filename):
| if (os.name == 'posix'):
mode = ((os.stat(tempname).st_mode | 365) & 4095)
os.chmod(tempname, mode)
|
'Set the base path where resources will be extracted to, if needed.
If you do not call this routine before any extractions take place, the
path defaults to the return value of ``get_default_cache()``. (Which
is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
platform-specific fallbacks. See that routine\'s documentation for more
details.)
Resources are extracted to subdirectories of this path based upon
information given by the ``IResourceProvider``. You may set this to a
temporary directory, but then you must call ``cleanup_resources()`` to
delete the extracted files when done. There is no guarantee that
``cleanup_resources()`` will be able to remove all extracted files.
(Note: you may not change the extraction path for a given resource
manager once resources have been extracted, unless you first call
``cleanup_resources()``.)'
| def set_extraction_path(self, path):
| if self.cached_files:
raise ValueError("Can't change extraction path, files already extracted")
self.extraction_path = path
|
'Validate text as a PEP 426 environment marker; return an exception
if invalid or False otherwise.'
| @classmethod
def is_invalid_marker(cls, text):
| try:
cls.evaluate_marker(text)
except SyntaxError as e:
return cls.normalize_exception(e)
return False
|
'Given a SyntaxError from a marker evaluation, normalize the error
message:
- Remove indications of filename and line number.
- Replace platform-specific error messages with standard error
messages.'
| @staticmethod
def normalize_exception(exc):
| subs = {'unexpected EOF while parsing': 'invalid syntax', 'parenthesis is never closed': 'invalid syntax'}
exc.filename = None
exc.lineno = None
exc.msg = subs.get(exc.msg, exc.msg)
return exc
|
'Evaluate a PEP 426 environment marker on CPython 2.4+.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the \'parser\' module, which is not implemented
on
Jython and has been superseded by the \'ast\' module in Python 2.6 and
later.'
| @classmethod
def evaluate_marker(cls, text, extra=None):
| return cls.interpret(parser.expr(text).totuple(1)[1])
|
'Markerlib implements Metadata 1.2 (PEP 345) environment markers.
Translate the variables to Metadata 2.0 (PEP 426).'
| @staticmethod
def _translate_metadata2(env):
| return dict(((key.replace('.', '_'), value) for (key, value) in env.items()))
|
'Evaluate a PEP 426 environment marker using markerlib.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.'
| @classmethod
def _markerlib_evaluate(cls, text):
| from pip._vendor import _markerlib
env = cls._translate_metadata2(_markerlib.default_environment())
try:
result = _markerlib.interpret(text, env)
except NameError as e:
raise SyntaxError(e.args[0])
return result
|
'Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows.'
| @classmethod
def build(cls, path):
| with ContextualZipFile(path) as zfile:
items = ((name.replace('/', os.sep), zfile.getinfo(name)) for name in zfile.namelist())
return dict(items)
|
'Load a manifest at path or return a suitable manifest already loaded.'
| def load(self, path):
| path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if ((path not in self) or (self[path].mtime != mtime)):
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest
|
'Construct a ZipFile or ContextualZipFile as appropriate'
| def __new__(cls, *args, **kwargs):
| if hasattr(zipfile.ZipFile, '__exit__'):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)
|
'Return True if the file_path is current for this zip_path'
| def _is_current(self, file_path, zip_path):
| (timestamp, size) = self._get_date_and_size(self.zipinfo[zip_path])
if (not os.path.isfile(file_path)):
return False
stat = os.stat(file_path)
if ((stat.st_size != size) or (stat.st_mtime != timestamp)):
return False
zip_contents = self.loader.get_data(zip_path)
with open(file_path, 'rb') as f:
file_contents = f.read()
return (zip_contents == file_contents)
|
'Create a metadata provider from a zipimporter'
| def __init__(self, importer):
| self.zip_pre = (importer.archive + os.sep)
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
|
'Require packages for this EntryPoint, then resolve it.'
| def load(self, require=True, *args, **kwargs):
| if ((not require) or args or kwargs):
warnings.warn('Parameters to load are deprecated. Call .resolve and .require separately.', DeprecationWarning, stacklevel=2)
if require:
self.require(*args, **kwargs)
return self.resolve()
|
'Resolve the entry point from its module and attrs.'
| def resolve(self):
| module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc))
|
'Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional'
| @classmethod
def parse(cls, src, dist=None):
| m = cls.pattern.match(src)
if (not m):
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(res['extras'])
attrs = (res['attr'].split('.') if res['attr'] else ())
return cls(res['name'], res['module'], attrs, extras, dist)
|
'Parse an entry point group'
| @classmethod
def parse_group(cls, group, lines, dist=None):
| if (not MODULE(group)):
raise ValueError('Invalid group name', group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if (ep.name in this):
raise ValueError('Duplicate entry point', group, ep.name)
this[ep.name] = ep
return this
|
'Parse a map of entry point groups'
| @classmethod
def parse_map(cls, data, dist=None):
| if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for (group, lines) in data:
if (group is None):
if (not lines):
continue
raise ValueError('Entry points must be listed in groups')
group = group.strip()
if (group in maps):
raise ValueError('Duplicate group name', group)
maps[group] = cls.parse_group(group, lines, dist)
return maps
|
'List of Requirements needed for this distro if `extras` are used'
| def requires(self, extras=()):
| dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(('%s has no such extra feature %r' % (self, ext)))
return deps
|
'Ensure distribution is importable on `path` (default=sys.path)'
| def activate(self, path=None):
| if (path is None):
path = sys.path
self.insert_on(path, replace=True)
if (path is sys.path):
fixup_namespace_packages(self.location)
for pkg in self._get_metadata('namespace_packages.txt'):
if (pkg in sys.modules):
declare_namespace(pkg)
|
'Return what this distribution\'s standard .egg filename should be'
| def egg_name(self):
| filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR)))
if self.platform:
filename += ('-' + self.platform)
return filename
|
'Delegate all unrecognized public attributes to .metadata provider'
| def __getattr__(self, attr):
| if attr.startswith('_'):
raise AttributeError(attr)
return getattr(self._provider, attr)
|
'Return a ``Requirement`` that matches this distribution exactly'
| def as_requirement(self):
| if isinstance(self.parsed_version, packaging.version.Version):
spec = ('%s==%s' % (self.project_name, self.parsed_version))
else:
spec = ('%s===%s' % (self.project_name, self.parsed_version))
return Requirement.parse(spec)
|
'Return the `name` entry point of `group` or raise ImportError'
| def load_entry_point(self, group, name):
| ep = self.get_entry_info(group, name)
if (ep is None):
raise ImportError(('Entry point %r not found' % ((group, name),)))
return ep.load()
|
'Return the entry point map for `group`, or the full entry map'
| def get_entry_map(self, group=None):
| try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
if (group is not None):
return ep_map.get(group, {})
return ep_map
|
'Return the EntryPoint object for `group`+`name`, or ``None``'
| def get_entry_info(self, group, name):
| return self.get_entry_map(group).get(name)
|
'Insert self.location in path before its nearest parent directory'
| def insert_on(self, path, loc=None, replace=False):
| 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]
for (p, item) in enumerate(npath):
if (item == nloc):
break
elif ((item == bdir) and (self.precedence == EGG_DIST)):
if (path is sys.path):
self.check_version_conflict()
path.insert(p, loc)
npath.insert(p, nloc)
break
else:
if (path is sys.path):
self.check_version_conflict()
if replace:
path.insert(0, loc)
else:
path.append(loc)
return
while True:
try:
np = npath.index(nloc, (p + 1))
except ValueError:
break
else:
del npath[np], path[np]
p = np
return
|
'Copy this distribution, substituting in any changed keyword args'
| def clone(self, **kw):
| names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw)
|
'Packages installed by distutils (e.g. numpy or scipy),
which uses an old safe_version, and so
their version numbers can get mangled when
converted to filenames (e.g., 1.11.0.dev0+2329eae to
1.11.0.dev0_2329eae). These distributions will not be
parsed properly
downstream by Distribution and safe_version, so
take an extra step and try to get the version number from
the metadata file itself instead of the filename.'
| def _reload_version(self):
| md_version = _version_from_file(self._get_metadata(self.PKG_INFO))
if md_version:
self._version = md_version
return self
|
'Parse and cache metadata'
| @property
def _parsed_pkg_info(self):
| try:
return self._pkg_info
except AttributeError:
metadata = self.get_metadata(self.PKG_INFO)
self._pkg_info = email.parser.Parser().parsestr(metadata)
return self._pkg_info
|
'Convert \'Foobar (1); baz\' to (\'Foobar ==1\', \'baz\')
Split environment marker, add == prefix to version specifiers as
necessary, and remove parenthesis.'
| def _preparse_requirement(self, requires_dist):
| parts = (requires_dist.split(';', 1) + [''])
distvers = parts[0].strip()
mark = parts[1].strip()
distvers = re.sub(self.EQEQ, '\\1==\\2\\3', distvers)
distvers = distvers.replace('(', '').replace(')', '')
return (distvers, mark)
|
'Recompute this distribution\'s dependencies.'
| def _compute_dependencies(self):
| from pip._vendor._markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
for req in (self._parsed_pkg_info.get_all('Requires-Dist') or []):
(distvers, mark) = self._preparse_requirement(req)
parsed = next(parse_requirements(distvers))
parsed.marker_fn = compile_marker(mark)
reqs.append(parsed)
def reqs_for_extra(extra):
for req in reqs:
if req.marker_fn(override={'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 []):
extra = safe_extra(extra.strip())
dm[extra] = list((frozenset(reqs_for_extra(extra)) - common))
return dm
|
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
| def __init__(self, project_name, specs, extras):
| (self.unsafe_name, project_name) = (project_name, safe_name(project_name))
(self.project_name, self.key) = (project_name, project_name.lower())
self.specifier = packaging.specifiers.SpecifierSet(','.join([''.join([x, y]) for (x, y) in specs]))
self.specs = specs
self.extras = tuple(map(safe_extra, extras))
self.hashCmp = (self.key, self.specifier, frozenset(self.extras))
self.__hash = hash(self.hashCmp)
|
'Ensure statement only contains allowed nodes.'
| def visit(self, node):
| if (not isinstance(node, self.ALLOWED)):
raise SyntaxError(('Not allowed in environment markers.\n%s\n%s' % (self.statement, ((' ' * node.col_offset) + '^'))))
return ast.NodeTransformer.visit(self, node)
|
'Flatten one level of attribute access.'
| def visit_Attribute(self, node):
| new_node = ast.Name(('%s.%s' % (node.value.id, node.attr)), node.ctx)
return ast.copy_location(new_node, node)
|
'Stop after the previous attempt >= stop_max_attempt_number.'
| def stop_after_attempt(self, previous_attempt_number, delay_since_first_attempt_ms):
| return (previous_attempt_number >= self._stop_max_attempt_number)
|
'Stop after the time from the first attempt >= stop_max_delay.'
| def stop_after_delay(self, previous_attempt_number, delay_since_first_attempt_ms):
| return (delay_since_first_attempt_ms >= self._stop_max_delay)
|
'Don\'t sleep at all before retrying.'
| def no_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
| return 0
|
'Sleep a fixed amount of time between each retry.'
| def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
| return self._wait_fixed
|
'Sleep a random amount of time between wait_random_min and wait_random_max'
| def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
| return random.randint(self._wait_random_min, self._wait_random_max)
|
'Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment'
| def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
| result = (self._wait_incrementing_start + (self._wait_incrementing_increment * (previous_attempt_number - 1)))
if (result < 0):
result = 0
return result
|
'Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.'
| def get(self, wrap_exception=False):
| if self.has_exception:
if wrap_exception:
raise RetryError(self)
else:
six.reraise(self.value[0], self.value[1], self.value[2])
else:
return self.value
|
'True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()'
| def should_wrap(self):
| return (self.convert or self.strip or self.autoreset)
|
'Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.'
| def write_and_convert(self, text):
| cursor = 0
text = self.convert_osc(text)
for match in self.ANSI_CSI_RE.finditer(text):
(start, end) = match.span()
self.write_plain_text(text, cursor, start)
self.convert_ansi(*match.groups())
cursor = end
self.write_plain_text(text, cursor, len(text))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.