desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initialise an instance. :param url: The URL to use for XML-RPC. :param kwargs: Passed to the superclass constructor.'
def __init__(self, url, **kwargs):
super(PyPIRPCLocator, self).__init__(**kwargs) self.base_url = url self.client = ServerProxy(url, timeout=3.0)
'Return all the distribution names known to this locator.'
def get_distribution_names(self):
return set(self.client.list_packages())
'Return all the distribution names known to this locator.'
def get_distribution_names(self):
raise NotImplementedError('Not available from this locator')
'Initialise an instance with the Unicode page contents and the URL they came from.'
def __init__(self, data, url):
self.data = data self.base_url = self.url = url m = self._base.search(self.data) if m: self.base_url = m.group(1)
'Return the URLs of all the links on a page together with information about their "rel" attribute, for determining which ones to treat as downloads and which ones to queue for further scraping.'
@cached_property def links(self):
def clean(url): 'Tidy up an URL.' (scheme, netloc, path, params, query, frag) = urlparse(url) return urlunparse((scheme, netloc, quote(path), params, query, frag)) result = set() for match in self._href.finditer(self.data): d = match.groupdict('') rel = (d['r...
'Initialise an instance. :param url: The root URL to use for scraping. :param timeout: The timeout, in seconds, to be applied to requests. This defaults to ``None`` (no timeout specified). :param num_workers: The number of worker threads you want to do I/O, This defaults to 10. :param kwargs: Passed to the superclass.'...
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
super(SimpleScrapingLocator, self).__init__(**kwargs) self.base_url = ensure_slash(url) self.timeout = timeout self._page_cache = {} self._seen = set() self._to_fetch = queue.Queue() self._bad_hosts = set() self.skip_externals = False self.num_workers = num_workers self._lock = t...
'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 inf...
'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_ur...
'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...
'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, resu...
'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_u...
'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, dis...
'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, di...
'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 = Fa...
'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 t...
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, unmatched)) result = False else: self.r...
'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 - otherwi...
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 = o...
'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)
'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 for match in self.ANSI_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))
':raises InvalidWheelFilename: when the filename is invalid for a wheel'
def __init__(self, filename):
wheel_info = self.wheel_file_re.match(filename) if (not wheel_info): raise InvalidWheelFilename(('%s is not a valid wheel filename.' % filename)) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') self.version = wheel_info.group('ver').replace('...
'Return the lowest index that one of the wheel\'s file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported.'
def support_index_min(self, tags=None):
if (tags is None): tags = pep425tags.supported_tags indexes = [tags.index(c) for c in self.file_tags if (c in tags)] return (min(indexes) if indexes else None)
'Is this wheel supported on this system?'
def supported(self, tags=None):
if (tags is None): tags = pep425tags.supported_tags return bool(set(tags).intersection(self.file_tags))
'Build one wheel.'
def _build_one(self, req):
base_args = ([sys.executable, '-c', ("import setuptools;__file__=%r;exec(compile(open(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))" % req.setup_py)] + list(self.global_options)) logger.notify(('Running setup.py bdist_wheel for %s' % req.name)) logger.notify(('Destina...
'Build wheels.'
def build(self):
self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [req for req in reqset if (not req.is_wheel)] if (not buildset): return logger.notify(('Building wheels for collected packages: %s' % ','.join([req.name for req in bu...
'Return a comma-separated list of option strings and metavars. :param option: tuple of (short opt, long opt), e.g: (\'-f\', \'--format\') :param mvarfmt: metavar format string - evaluated as mvarfmt % metavar :param optsep: separator'
def _format_option_strings(self, option, mvarfmt=' <%s>', optsep=', '):
opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if (len(opts) > 1): opts.insert(1, optsep) if option.takes_value(): metavar = (option.metavar or option.dest.lower()) opts.append((mvarf...
'Ensure there is only one newline between usage and the first heading if there is no description.'
def format_usage(self, usage):
msg = ('\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), ' ')) return msg
'Insert an OptionGroup at a given position.'
def insert_option_group(self, idx, *args, **kwargs):
group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group
'Get a list of all options, including those in option groups.'
@property def option_list_all(self):
res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res
'Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).'
def update_defaults(self, defaults):
config = {} for section in ('global', self.name): config.update(self.normalize_keys(self.get_config_section(section))) config.update(self.normalize_keys(self.get_environ_vars())) for (key, val) in config.items(): option = self.get_option(key) if (option is not None): ...
'Return a config dictionary with normalized keys regardless of whether the keys were specified in environment variables or in config files'
def normalize_keys(self, items):
normalized = {} for (key, val) in items: key = key.replace('_', '-') if (not key.startswith('--')): key = ('--%s' % key) normalized[key] = val return normalized
'Get a section of a configuration'
def get_config_section(self, name):
if self.config.has_section(name): return self.config.items(name) return []
'Returns a generator with all environmental vars with prefix PIP_'
def get_environ_vars(self, prefix='PIP_'):
for (key, val) in os.environ.items(): if key.startswith(prefix): (yield (key.replace(prefix, '').lower(), val))
'Overridding to make updating the defaults after instantiation of the option parser possible, update_defaults() does the dirty work.'
def get_default_values(self):
if (not self.process_default_values): return optparse.Values(self.defaults) defaults = self.update_defaults(self.defaults.copy()) for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): opt_str = option.get_opt_stri...
'Creates an InstallRequirement from a name, which might be a requirement, directory containing \'setup.py\', filename, or URL.'
@classmethod def from_line(cls, name, comes_from=None, prereleases=None):
url = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif (os.path.isdir(path) and ((os.path.sep in name) or name.startswith('.'))): if (not is_installable_dir(path)): raise Install...
'If the build location was a temporary directory, this will move it to a new more permanent location'
def correct_build_location(self):
if (self.source_dir is not None): return assert (self.req is not None) assert self._temp_build_dir old_location = self._temp_build_dir new_build_dir = self._ideal_build_dir del self._ideal_build_dir if self.editable: name = self.name.lower() else: name = self.name...
'Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv i...
def uninstall(self, auto_confirm=False):
if (not self.check_if_exists()): raise UninstallationError(('Cannot uninstall requirement %s, not installed' % (self.name,))) dist = (self.satisfied_by or self.conflicts_with) paths_to_remove = UninstallPathSet(dist) pip_egg_info_path = (os.path.join(dist.location, dist.egg_name()...
'Remove the source files from this requirement, if they are marked for deletion'
def remove_temporary_source(self):
if (self.is_bundle or os.path.exists(self.delete_marker_filename)): logger.info(('Removing source in %s' % self.source_dir)) if self.source_dir: rmtree(self.source_dir) self.source_dir = None if (self._temp_build_dir and os.path.exists(self._temp_build_dir)): ...
'Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.'
def check_if_exists(self):
if (self.req is None): return False try: if ((self.req.project_name == 'setuptools') and self.conflicts_with and (self.conflicts_with.project_name == 'distribute')): return True else: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_reso...
'Prepare process. Create temp directories, download and/or unpack files.'
def prepare_files(self, finder, force_root_egg_info=False, bundle=False):
unnamed = list(self.unnamed_requirements) reqs = list(self.requirements.values()) while (reqs or unnamed): if unnamed: req_to_install = unnamed.pop(0) else: req_to_install = reqs.pop(0) install = True best_installed = False not_found = None ...
'Clean up files, remove builds.'
def cleanup_files(self, bundle=False):
logger.notify('Cleaning up...') logger.indent += 2 for req in self.reqs_to_cleanup: req.remove_temporary_source() remove_dir = [] if self._pip_has_created_build_dir(): remove_dir.append(self.build_dir) if bundle: remove_dir.append(self.src_dir) for dir in remove_di...
'Install everything in this set (after having downloaded and unpacked the packages)'
def install(self, install_options, global_options=(), *args, **kwargs):
to_install = [r for r in self.requirements.values() if (not r.satisfied_by)] distribute_req = pkg_resources.Requirement.parse('distribute>=0.7') for req in to_install: if ((req.name == 'distribute') and (req.installed_version in distribute_req)): to_install.remove(req) to_ins...
'Return True if the given path is one we are permitted to remove/modify, False otherwise.'
def _permitted(self, path):
return is_local(path)
'Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path.'
def compact(self, paths):
short_paths = set() for path in sorted(paths, key=len): if (not any([(path.startswith(shortpath) and (path[len(shortpath.rstrip(os.path.sep))] == os.path.sep)) for shortpath in short_paths])): short_paths.add(path) return short_paths
'Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).'
def remove(self, auto_confirm=False):
if (not self._can_uninstall()): return if (not self.paths): logger.notify(("Can't uninstall '%s'. No files were found to uninstall." % self.dist.project_name)) return logger.notify(('Uninstalling %s:' % self.dist.project_name)) logger.indent += 2 pa...
'Rollback the changes previously made by remove().'
def rollback(self):
if (self.save_dir is None): logger.error(("Can't roll back %s; was not uninstalled" % self.dist.project_name)) return False logger.notify(('Rolling back uninstall of %s' % self.dist.project_name)) for path in self._moved_paths: tmp_path = self._stash(pat...
'Remove temporary save dir: rollback will no longer be possible.'
def commit(self):
if (self.save_dir is not None): rmtree(self.save_dir) self.save_dir = None self._moved_paths = []
'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)
'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 mo...
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 rais...
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) else: 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\...
def add(self, dist, entry=None, insert=True):
if insert: dist.insert_on(self.entries, entry) if (entry is None): entry = dist.location keys = self.entry_keys.setdefault(entry, []) keys2 = self.entry_keys.setdefault(dist.location, []) if (dist.key in self.by_key): return self.by_key[dist.key] = dist if (dist.key n...
'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...
def resolve(self, requirements, env=None, installer=None):
requirements = list(requirements)[::(-1)] processed = {} best = {} to_activate = [] 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) ...
'Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) map(working_set.add, distributions) # add plugins+libs to sys.path print \'Could not load\', errors # display errors The `plugin_env` should be an ``Environment`` ins...
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)...
'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 distrib...
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 distribu...
def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
self._distmap = {} self._cache = {} 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`'
def __getitem__(self, project_name):
try: return self._cache[project_name] except KeyError: project_name = project_name.lower() if (project_name not in self._distmap): return [] if (project_name not in self._cache): dists = self._cache[project_name] = self._distmap[project_name] _sort_dists(d...
'Add `dist` if we ``can_add()`` it and it isn\'t already 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) if (dist.key in self._cache): _sort_dists(self._cache[dist.key])
'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 ...
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...
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 ...
'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 ...
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[targ...
'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_fil...
'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 alr...
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 ...
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: return cls.normalize_exception(sys.exc_info()[1]) 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])
'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):
import _markerlib env = _markerlib.default_environment() for key in env.keys(): new_key = key.replace('.', '_') env[new_key] = env.pop(key) try: result = _markerlib.interpret(text, env) except NameError: e = sys.exc_info()[1] raise SyntaxError(e.args[0]) r...
'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) f = open(file_pat...
'Create a metadata provider from a zipimporter'
def __init__(self, importer):
self.zipinfo = build_zipmanifest(importer.archive) 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()
'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):
try: attrs = extras = () (name, value) = src.split('=', 1) if ('[' in value): (value, extras) = value.split('[', 1) req = Requirement.parse(('x[' + extras)) if req.specs: raise ValueError extras = req.extras if (':' in v...