ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- index.py000064400000110027152347654140006241 0ustar00"""Routines related to PyPI, indexes""" # The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import re from pip._vendor.packaging import specifiers from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import parse as parse_version from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.models.candidate import InstallationCandidate from pip._internal.models.format_control import FormatControl from pip._internal.models.link import Link from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.models.target_python import TargetPython from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import build_netloc from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS from pip._internal.utils.urls import url_to_path from pip._internal.wheel import Wheel if MYPY_CHECK_RUNNING: from typing import ( FrozenSet, Iterable, List, Optional, Set, Text, Tuple, Union, ) from pip._vendor.packaging.version import _BaseVersion from pip._internal.collector import LinkCollector from pip._internal.models.search_scope import SearchScope from pip._internal.req import InstallRequirement from pip._internal.pep425tags import Pep425Tag from pip._internal.utils.hashes import Hashes BuildTag = Union[Tuple[()], Tuple[int, str]] CandidateSortingKey = ( Tuple[int, int, int, _BaseVersion, BuildTag, Optional[int]] ) __all__ = ['FormatControl', 'BestCandidateResult', 'PackageFinder'] logger = logging.getLogger(__name__) def _check_link_requires_python( link, # type: Link version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> bool """ Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. """ try: is_compatible = check_requires_python( link.requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier: logger.debug( "Ignoring invalid Requires-Python (%r) for link: %s", link.requires_python, link, ) else: if not is_compatible: version = '.'.join(map(str, version_info)) if not ignore_requires_python: logger.debug( 'Link requires a different Python (%s not in: %r): %s', version, link.requires_python, link, ) return False logger.debug( 'Ignoring failed Requires-Python check (%s not in: %r) ' 'for link: %s', version, link.requires_python, link, ) return True class LinkEvaluator(object): """ Responsible for evaluating links for a particular project. """ _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$') # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def __init__( self, project_name, # type: str canonical_name, # type: str formats, # type: FrozenSet target_python, # type: TargetPython allow_yanked, # type: bool ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. """ if ignore_requires_python is None: ignore_requires_python = False self._allow_yanked = allow_yanked self._canonical_name = canonical_name self._ignore_requires_python = ignore_requires_python self._formats = formats self._target_python = target_python self.project_name = project_name def evaluate_link(self, link): # type: (Link) -> Tuple[bool, Optional[Text]] """ Determine whether a link is a candidate for installation. :return: A tuple (is_candidate, result), where `result` is (1) a version string if `is_candidate` is True, and (2) if `is_candidate` is False, an optional string to log the reason the link fails to qualify. """ version = None if link.is_yanked and not self._allow_yanked: reason = link.yanked_reason or '' # Mark this as a unicode string to prevent "UnicodeEncodeError: # 'ascii' codec can't encode character" in Python 2 when # the reason contains non-ascii characters. return (False, u'yanked for reason: {}'.format(reason)) if link.egg_fragment: egg_info = link.egg_fragment ext = link.ext else: egg_info, ext = link.splitext() if not ext: return (False, 'not a file') if ext not in SUPPORTED_EXTENSIONS: return (False, 'unsupported archive format: %s' % ext) if "binary" not in self._formats and ext == WHEEL_EXTENSION: reason = 'No binaries permitted for %s' % self.project_name return (False, reason) if "macosx10" in link.path and ext == '.zip': return (False, 'macosx10 one') if ext == WHEEL_EXTENSION: try: wheel = Wheel(link.filename) except InvalidWheelFilename: return (False, 'invalid wheel filename') if canonicalize_name(wheel.name) != self._canonical_name: reason = 'wrong project name (not %s)' % self.project_name return (False, reason) supported_tags = self._target_python.get_tags() if not wheel.supported(supported_tags): # Include the wheel's tags in the reason string to # simplify troubleshooting compatibility issues. file_tags = wheel.get_formatted_file_tags() reason = ( "none of the wheel's tags match: {}".format( ', '.join(file_tags) ) ) return (False, reason) version = wheel.version # This should be up by the self.ok_binary check, but see issue 2700. if "source" not in self._formats and ext != WHEEL_EXTENSION: return (False, 'No sources permitted for %s' % self.project_name) if not version: version = _extract_version_from_fragment( egg_info, self._canonical_name, ) if not version: return ( False, 'Missing project version for %s' % self.project_name, ) match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != self._target_python.py_version: return (False, 'Python version is incorrect') supports_python = _check_link_requires_python( link, version_info=self._target_python.py_version_info, ignore_requires_python=self._ignore_requires_python, ) if not supports_python: # Return None for the reason text to suppress calling # _log_skipped_link(). return (False, None) logger.debug('Found link %s, version: %s', link, version) return (True, version) def filter_unallowed_hashes( candidates, # type: List[InstallationCandidate] hashes, # type: Hashes project_name, # type: str ): # type: (...) -> List[InstallationCandidate] """ Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). """ if not hashes: logger.debug( 'Given no hashes to check %s links for project %r: ' 'discarding no candidates', len(candidates), project_name, ) # Make sure we're not returning back the given value. return list(candidates) matches_or_no_digest = [] # Collect the non-matches for logging purposes. non_matches = [] match_count = 0 for candidate in candidates: link = candidate.link if not link.has_hash: pass elif link.is_hash_allowed(hashes=hashes): match_count += 1 else: non_matches.append(candidate) continue matches_or_no_digest.append(candidate) if match_count: filtered = matches_or_no_digest else: # Make sure we're not returning back the given value. filtered = list(candidates) if len(filtered) == len(candidates): discard_message = 'discarding no candidates' else: discard_message = 'discarding {} non-matches:\n {}'.format( len(non_matches), '\n '.join(str(candidate.link) for candidate in non_matches) ) logger.debug( 'Checked %s links for project %r against %s hashes ' '(%s matches, %s no digest): %s', len(candidates), project_name, hashes.digest_count, match_count, len(matches_or_no_digest) - match_count, discard_message ) return filtered class CandidatePreferences(object): """ Encapsulates some of the preferences for filtering and sorting InstallationCandidate objects. """ def __init__( self, prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool ): # type: (...) -> None """ :param allow_all_prereleases: Whether to allow all pre-releases. """ self.allow_all_prereleases = allow_all_prereleases self.prefer_binary = prefer_binary class BestCandidateResult(object): """A collection of candidates, returned by `PackageFinder.find_best_candidate`. This class is only intended to be instantiated by CandidateEvaluator's `compute_best_candidate()` method. """ def __init__( self, candidates, # type: List[InstallationCandidate] applicable_candidates, # type: List[InstallationCandidate] best_candidate, # type: Optional[InstallationCandidate] ): # type: (...) -> None """ :param candidates: A sequence of all available candidates found. :param applicable_candidates: The applicable candidates. :param best_candidate: The most preferred candidate found, or None if no applicable candidates were found. """ assert set(applicable_candidates) <= set(candidates) if best_candidate is None: assert not applicable_candidates else: assert best_candidate in applicable_candidates self._applicable_candidates = applicable_candidates self._candidates = candidates self.best_candidate = best_candidate def iter_all(self): # type: () -> Iterable[InstallationCandidate] """Iterate through all candidates. """ return iter(self._candidates) def iter_applicable(self): # type: () -> Iterable[InstallationCandidate] """Iterate through the applicable candidates. """ return iter(self._applicable_candidates) class CandidateEvaluator(object): """ Responsible for filtering and sorting candidates for installation based on what tags are valid. """ @classmethod def create( cls, project_name, # type: str target_python=None, # type: Optional[TargetPython] prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> CandidateEvaluator """Create a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :param hashes: An optional collection of allowed hashes. """ if target_python is None: target_python = TargetPython() if specifier is None: specifier = specifiers.SpecifierSet() supported_tags = target_python.get_tags() return cls( project_name=project_name, supported_tags=supported_tags, specifier=specifier, prefer_binary=prefer_binary, allow_all_prereleases=allow_all_prereleases, hashes=hashes, ) def __init__( self, project_name, # type: str supported_tags, # type: List[Pep425Tag] specifier, # type: specifiers.BaseSpecifier prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool hashes=None, # type: Optional[Hashes] ): # type: (...) -> None """ :param supported_tags: The PEP 425 tags supported by the target Python in order of preference (most preferred first). """ self._allow_all_prereleases = allow_all_prereleases self._hashes = hashes self._prefer_binary = prefer_binary self._project_name = project_name self._specifier = specifier self._supported_tags = supported_tags def get_applicable_candidates( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> List[InstallationCandidate] """ Return the applicable candidates from a list of candidates. """ # Using None infers from the specifier instead. allow_prereleases = self._allow_all_prereleases or None specifier = self._specifier versions = { str(v) for v in specifier.filter( # We turn the version object into a str here because otherwise # when we're debundled but setuptools isn't, Python will see # packaging.version.Version and # pkg_resources._vendor.packaging.version.Version as different # types. This way we'll use a str as a common data interchange # format. If we stop using the pkg_resources provided specifier # and start using our own, we can drop the cast to str(). (str(c.version) for c in candidates), prereleases=allow_prereleases, ) } # Again, converting version to str to deal with debundling. applicable_candidates = [ c for c in candidates if str(c.version) in versions ] return filter_unallowed_hashes( candidates=applicable_candidates, hashes=self._hashes, project_name=self._project_name, ) def _sort_key(self, candidate): # type: (InstallationCandidate) -> CandidateSortingKey """ Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal """ valid_tags = self._supported_tags support_num = len(valid_tags) build_tag = () # type: BuildTag binary_preference = 0 link = candidate.link if link.is_wheel: # can raise InvalidWheelFilename wheel = Wheel(link.filename) if not wheel.supported(valid_tags): raise UnsupportedWheel( "%s is not a supported wheel for this platform. It " "can't be sorted." % wheel.filename ) if self._prefer_binary: binary_preference = 1 pri = -(wheel.support_index_min(valid_tags)) if wheel.build_tag is not None: match = re.match(r'^(\d+)(.*)$', wheel.build_tag) build_tag_groups = match.groups() build_tag = (int(build_tag_groups[0]), build_tag_groups[1]) else: # sdist pri = -(support_num) has_allowed_hash = int(link.is_hash_allowed(self._hashes)) yank_value = -1 * int(link.is_yanked) # -1 for yanked. return ( has_allowed_hash, yank_value, binary_preference, candidate.version, build_tag, pri, ) def sort_best_candidate( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> Optional[InstallationCandidate] """ Return the best candidate per the instance's sort order, or None if no candidate is acceptable. """ if not candidates: return None best_candidate = max(candidates, key=self._sort_key) # Log a warning per PEP 592 if necessary before returning. link = best_candidate.link if link.is_yanked: reason = link.yanked_reason or '' msg = ( # Mark this as a unicode string to prevent # "UnicodeEncodeError: 'ascii' codec can't encode character" # in Python 2 when the reason contains non-ascii characters. u'The candidate selected for download or install is a ' 'yanked version: {candidate}\n' 'Reason for being yanked: {reason}' ).format(candidate=best_candidate, reason=reason) logger.warning(msg) return best_candidate def compute_best_candidate( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> BestCandidateResult """ Compute and return a `BestCandidateResult` instance. """ applicable_candidates = self.get_applicable_candidates(candidates) best_candidate = self.sort_best_candidate(applicable_candidates) return BestCandidateResult( candidates, applicable_candidates=applicable_candidates, best_candidate=best_candidate, ) class PackageFinder(object): """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector, # type: LinkCollector target_python, # type: TargetPython allow_yanked, # type: bool format_control=None, # type: Optional[FormatControl] candidate_prefs=None, # type: CandidatePreferences ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. """ if candidate_prefs is None: candidate_prefs = CandidatePreferences() format_control = format_control or FormatControl(set(), set()) self._allow_yanked = allow_yanked self._candidate_prefs = candidate_prefs self._ignore_requires_python = ignore_requires_python self._link_collector = link_collector self._target_python = target_python self.format_control = format_control # These are boring links that have already been logged somehow. self._logged_links = set() # type: Set[Link] # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. @classmethod def create( cls, link_collector, # type: LinkCollector selection_prefs, # type: SelectionPreferences target_python=None, # type: Optional[TargetPython] ): # type: (...) -> PackageFinder """Create a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. """ if target_python is None: target_python = TargetPython() candidate_prefs = CandidatePreferences( prefer_binary=selection_prefs.prefer_binary, allow_all_prereleases=selection_prefs.allow_all_prereleases, ) return cls( candidate_prefs=candidate_prefs, link_collector=link_collector, target_python=target_python, allow_yanked=selection_prefs.allow_yanked, format_control=selection_prefs.format_control, ignore_requires_python=selection_prefs.ignore_requires_python, ) @property def search_scope(self): # type: () -> SearchScope return self._link_collector.search_scope @search_scope.setter def search_scope(self, search_scope): # type: (SearchScope) -> None self._link_collector.search_scope = search_scope @property def find_links(self): # type: () -> List[str] return self._link_collector.find_links @property def index_urls(self): # type: () -> List[str] return self.search_scope.index_urls @property def trusted_hosts(self): # type: () -> Iterable[str] for host_port in self._link_collector.session.pip_trusted_origins: yield build_netloc(*host_port) @property def allow_all_prereleases(self): # type: () -> bool return self._candidate_prefs.allow_all_prereleases def set_allow_all_prereleases(self): # type: () -> None self._candidate_prefs.allow_all_prereleases = True def make_link_evaluator(self, project_name): # type: (str) -> LinkEvaluator canonical_name = canonicalize_name(project_name) formats = self.format_control.get_allowed_formats(canonical_name) return LinkEvaluator( project_name=project_name, canonical_name=canonical_name, formats=formats, target_python=self._target_python, allow_yanked=self._allow_yanked, ignore_requires_python=self._ignore_requires_python, ) def _sort_links(self, links): # type: (Iterable[Link]) -> List[Link] """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() # type: Set[Link] for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs def _log_skipped_link(self, link, reason): # type: (Link, Text) -> None if link not in self._logged_links: # Mark this as a unicode string to prevent "UnicodeEncodeError: # 'ascii' codec can't encode character" in Python 2 when # the reason contains non-ascii characters. # Also, put the link at the end so the reason is more visible # and because the link string is usually very long. logger.debug(u'Skipping link: %s: %s', reason, link) self._logged_links.add(link) def get_install_candidate(self, link_evaluator, link): # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate] """ If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. """ is_candidate, result = link_evaluator.evaluate_link(link) if not is_candidate: if result: self._log_skipped_link(link, reason=result) return None return InstallationCandidate( project=link_evaluator.project_name, link=link, # Convert the Text result to str since InstallationCandidate # accepts str. version=str(result), ) def evaluate_links(self, link_evaluator, links): # type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate] """ Convert links that are candidates to InstallationCandidate objects. """ candidates = [] for link in self._sort_links(links): candidate = self.get_install_candidate(link_evaluator, link) if candidate is not None: candidates.append(candidate) return candidates def find_all_candidates(self, project_name): # type: (str) -> List[InstallationCandidate] """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. """ collected_links = self._link_collector.collect_links(project_name) link_evaluator = self.make_link_evaluator(project_name) find_links_versions = self.evaluate_links( link_evaluator, links=collected_links.find_links, ) page_versions = [] for page_url, page_links in collected_links.pages.items(): logger.debug('Analyzing links from page %s', page_url) with indent_log(): new_versions = self.evaluate_links( link_evaluator, links=page_links, ) page_versions.extend(new_versions) file_versions = self.evaluate_links( link_evaluator, links=collected_links.files, ) if file_versions: file_versions.sort(reverse=True) logger.debug( 'Local files found: %s', ', '.join([ url_to_path(candidate.link.url) for candidate in file_versions ]) ) # This is an intentional priority ordering return file_versions + find_links_versions + page_versions def make_candidate_evaluator( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> CandidateEvaluator """Create a CandidateEvaluator object to use. """ candidate_prefs = self._candidate_prefs return CandidateEvaluator.create( project_name=project_name, target_python=self._target_python, prefer_binary=candidate_prefs.prefer_binary, allow_all_prereleases=candidate_prefs.allow_all_prereleases, specifier=specifier, hashes=hashes, ) def find_best_candidate( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> BestCandidateResult """Find matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. """ candidates = self.find_all_candidates(project_name) candidate_evaluator = self.make_candidate_evaluator( project_name=project_name, specifier=specifier, hashes=hashes, ) return candidate_evaluator.compute_best_candidate(candidates) def find_requirement(self, req, upgrade): # type: (InstallRequirement, bool) -> Optional[Link] """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise """ hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( req.name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version = None # type: Optional[_BaseVersion] if req.satisfied_by is not None: installed_version = parse_version(req.satisfied_by.version) def _format_versions(cand_iter): # This repeated parse_version and str() conversion is needed to # handle different vendoring sources from pip and pkg_resources. # If we stop using the pkg_resources provided specifier and start # using our own, we can drop the cast to str(). return ", ".join(sorted( {str(c.version) for c in cand_iter}, key=parse_version, )) or "none" if installed_version is None and best_candidate is None: logger.critical( 'Could not find a version that satisfies the requirement %s ' '(from versions: %s)', req, _format_versions(best_candidate_result.iter_all()), ) raise DistributionNotFound( 'No matching distribution found for %s' % req ) best_installed = False if installed_version and ( best_candidate is None or best_candidate.version <= installed_version): best_installed = True if not upgrade and installed_version is not None: if best_installed: logger.debug( 'Existing installed version (%s) is most up-to-date and ' 'satisfies requirement', installed_version, ) else: logger.debug( 'Existing installed version (%s) satisfies requirement ' '(most up-to-date version is %s)', installed_version, best_candidate.version, ) return None if best_installed: # We have an existing version, and its the best version logger.debug( 'Installed version (%s) is most up-to-date (past versions: ' '%s)', installed_version, _format_versions(best_candidate_result.iter_applicable()), ) raise BestVersionAlreadyInstalled logger.debug( 'Using version %s (newest of versions: %s)', best_candidate.version, _format_versions(best_candidate_result.iter_applicable()), ) return best_candidate.link def _find_name_version_sep(fragment, canonical_name): # type: (str, str) -> int """Find the separator's index based on the package's canonical name. :param fragment: A + filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 """ # Project name and version must be separated by one single dash. Find all # occurrences of dashes; if the string in front of it matches the canonical # name, this is the one separating the name and version parts. for i, c in enumerate(fragment): if c != "-": continue if canonicalize_name(fragment[:i]) == canonical_name: return i raise ValueError("{} does not match {}".format(fragment, canonical_name)) def _extract_version_from_fragment(fragment, canonical_name): # type: (str, str) -> Optional[str] """Parse the version string from a + filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. """ try: version_start = _find_name_version_sep(fragment, canonical_name) + 1 except ValueError: return None version = fragment[version_start:] if not version: return None return version collector.py000064400000043127152347654140007126 0ustar00""" The main purpose of this module is to expose LinkCollector.collect_links(). """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False import cgi import itertools import logging import mimetypes import os from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import HTTPError, RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.models.link import Link from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs if MYPY_CHECK_RUNNING: from typing import ( Callable, Dict, Iterable, List, MutableMapping, Optional, Sequence, Tuple, Union, ) import xml.etree.ElementTree from pip._vendor.requests import Response from pip._internal.models.search_scope import SearchScope from pip._internal.network.session import PipSession HTMLElement = xml.etree.ElementTree.Element ResponseHeaders = MutableMapping[str, str] logger = logging.getLogger(__name__) def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return None def _is_url_like_archive(url): # type: (str) -> bool """Return whether the URL looks like an archive. """ filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False class _NotHTML(Exception): def __init__(self, content_type, request_desc): # type: (str, str) -> None super(_NotHTML, self).__init__(content_type, request_desc) self.content_type = content_type self.request_desc = request_desc def _ensure_html_header(response): # type: (Response) -> None """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/html"): raise _NotHTML(content_type, response.request.method) class _NotHTTP(Exception): pass def _ensure_html_response(url, session): # type: (str, PipSession) -> None """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) resp.raise_for_status() _ensure_html_header(resp) def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if _is_url_like_archive(url): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) resp.raise_for_status() # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp def _get_encoding_from_headers(headers): # type: (ResponseHeaders) -> Optional[str] """Determine if we have any encoding information in our headers. """ if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: return params['charset'] return None def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str """Determine the HTML document's base URL. This looks for a ```` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. """ for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url def _clean_link(url): # type: (str) -> str """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).""" # Split the URL into parts according to the general structure # `scheme://netloc/path;parameters?query#fragment`. Note that the # `netloc` can be empty and the URI will then refer to a local # filesystem path. result = urllib_parse.urlparse(url) # In both cases below we unquote prior to quoting to make sure # nothing is double quoted. if result.netloc == "": # On Windows the path part might contain a drive letter which # should not be quoted. On Linux where drive letters do not # exist, the colon should be quoted. We rely on urllib.request # to do the right thing here. path = urllib_request.pathname2url( urllib_request.url2pathname(result.path)) else: # In addition to the `/` character we protect `@` so that # revision strings in VCS URLs are properly parsed. path = urllib_parse.quote(urllib_parse.unquote(result.path), safe="/@") return urllib_parse.urlunparse(result._replace(path=path)) def _create_link_from_element( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str ): # type: (...) -> Optional[Link] """ Convert an anchor element in a simple repository page to a Link. """ href = anchor.get("href") if not href: return None url = _clean_link(urllib_parse.urljoin(base_url, href)) pyrequire = anchor.get('data-requires-python') pyrequire = unescape(pyrequire) if pyrequire else None yanked_reason = anchor.get('data-yanked') if yanked_reason: # This is a unicode string in Python 2 (and 3). yanked_reason = unescape(yanked_reason) link = Link( url, comes_from=page_url, requires_python=pyrequire, yanked_reason=yanked_reason, ) return link def parse_links(page): # type: (HTMLPage) -> Iterable[Link] """ Parse an HTML document, and yield its anchor elements as Link objects. """ document = html5lib.parse( page.content, transport_encoding=page.encoding, namespaceHTMLElements=False, ) url = page.url base_url = _determine_base_url(document, url) for anchor in document.findall(".//a"): link = _create_link_from_element( anchor, page_url=url, base_url=base_url, ) if link is None: continue yield link class HTMLPage(object): """Represents one page, along with its URL""" def __init__( self, content, # type: bytes encoding, # type: Optional[str] url, # type: str ): # type: (...) -> None """ :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. """ self.content = content self.encoding = encoding self.url = url def __str__(self): return redact_auth_from_url(self.url) def _handle_get_page_fail( link, # type: Link reason, # type: Union[str, Exception] meth=None # type: Optional[Callable[..., None]] ): # type: (...) -> None if meth is None: meth = logger.debug meth("Could not fetch URL %s: %s - skipping", link, reason) def _make_html_page(response): # type: (Response) -> HTMLPage encoding = _get_encoding_from_headers(response.headers) return HTMLPage(response.content, encoding=encoding, url=response.url) def _get_html_page(link, session=None): # type: (Link, Optional[PipSession]) -> Optional[HTMLPage] if session is None: raise TypeError( "_get_html_page() missing 1 required keyword argument: 'session'" ) url = link.url.split('#', 1)[0] # Check for VCS schemes that do not support lookup as web pages. vcs_scheme = _match_vcs_scheme(url) if vcs_scheme: logger.debug('Cannot look at %s URL %s', vcs_scheme, link) return None # Tack index.html onto file:// URLs that point to directories scheme, _, path, _, _, _ = urllib_parse.urlparse(url) if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))): # add trailing slash if not present so urljoin doesn't trim # final segment if not url.endswith('/'): url += '/' url = urllib_parse.urljoin(url, 'index.html') logger.debug(' file: URL is directory, getting %s', url) try: resp = _get_html_response(url, session=session) except _NotHTTP: logger.debug( 'Skipping page %s because it looks like an archive, and cannot ' 'be checked by HEAD.', link, ) except _NotHTML as exc: logger.debug( 'Skipping page %s because the %s request got Content-Type: %s', link, exc.request_desc, exc.content_type, ) except HTTPError as exc: _handle_get_page_fail(link, exc) except RetryError as exc: _handle_get_page_fail(link, exc) except SSLError as exc: reason = "There was a problem confirming the ssl certificate: " reason += str(exc) _handle_get_page_fail(link, reason, meth=logger.info) except requests.ConnectionError as exc: _handle_get_page_fail(link, "connection error: %s" % exc) except requests.Timeout: _handle_get_page_fail(link, "timed out") else: return _make_html_page(resp) return None def _remove_duplicate_links(links): # type: (Iterable[Link]) -> List[Link] """ Return a list of links, with duplicates removed and ordering preserved. """ # We preserve the ordering when removing duplicates because we can. return list(OrderedDict.fromkeys(links)) def group_locations(locations, expand_dir=False): # type: (Sequence[str], bool) -> Tuple[List[str], List[str]] """ Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) else: logger.warning( "Path '{0}' is ignored: " "it is a directory.".format(path), ) elif os.path.isfile(path): sort_path(path) else: logger.warning( "Url '%s' is ignored: it is neither a file " "nor a directory.", url, ) elif is_url(url): # Only add url with clear scheme urls.append(url) else: logger.warning( "Url '%s' is ignored. It is either a non-existing " "path or lacks a specific scheme.", url, ) return files, urls class CollectedLinks(object): """ Encapsulates all the Link objects collected by a call to LinkCollector.collect_links(), stored separately as-- (1) links from the configured file locations, (2) links from the configured find_links, and (3) a dict mapping HTML page url to links from that page. """ def __init__( self, files, # type: List[Link] find_links, # type: List[Link] pages, # type: Dict[str, List[Link]] ): # type: (...) -> None """ :param files: Links from file locations. :param find_links: Links from find_links. :param pages: A dict mapping HTML page url to links from that page. """ self.files = files self.find_links = find_links self.pages = pages class LinkCollector(object): """ Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. """ def __init__( self, session, # type: PipSession search_scope, # type: SearchScope ): # type: (...) -> None self.search_scope = search_scope self.session = session @property def find_links(self): # type: () -> List[str] return self.search_scope.find_links def _get_pages(self, locations): # type: (Iterable[Link]) -> Iterable[HTMLPage] """ Yields (page, page_url) from the given locations, skipping locations that have errors. """ for location in locations: page = _get_html_page(location, session=self.session) if page is None: continue yield page def collect_links(self, project_name): # type: (str) -> CollectedLinks """Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. """ search_scope = self.search_scope index_locations = search_scope.get_index_urls_locations(project_name) index_file_loc, index_url_loc = group_locations(index_locations) fl_file_loc, fl_url_loc = group_locations( self.find_links, expand_dir=True, ) file_links = [ Link(url) for url in itertools.chain(index_file_loc, fl_file_loc) ] # We trust every directly linked archive in find_links find_link_links = [Link(url, '-f') for url in self.find_links] # We trust every url that the user has given us whether it was given # via --index-url or --find-links. # We want to filter out anything that does not have a secure origin. url_locations = [ link for link in itertools.chain( (Link(url) for url in index_url_loc), (Link(url) for url in fl_url_loc), ) if self.session.is_secure_origin(link) ] url_locations = _remove_duplicate_links(url_locations) lines = [ '{} location(s) to search for versions of {}:'.format( len(url_locations), project_name, ), ] for link in url_locations: lines.append('* {}'.format(link)) logger.debug('\n'.join(lines)) pages_links = {} for page in self._get_pages(url_locations): pages_links[page.url] = list(parse_links(page)) return CollectedLinks( files=file_links, find_links=find_link_links, pages=pages_links, ) __pycache__/legacy_resolve.cpython-38.pyc000064400000024404152347654150014427 0ustar00U .eRC@sFdZddlZddlZddlmZddlmZddlmZddl m Z m Z m Z m Z mZddlmZddlmZmZmZmZdd lmZmZdd lmZerdd lmZmZmZmZm Z m!Z!dd l"m#Z#dd l$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ee0e-ge-fZ1e2e3Z4dddZ5Gddde6Z7dS)ayDependency Resolution The dependency resolution in pip is performed as follows: for top-level requirements: a. only one spec allowed per project, regardless of conflicts or not. otherwise a "double requirement" exception is raised b. they override sub-dependency requirements. for sub-dependencies a. "first found, wins" (where the order is breadth first) N) defaultdict)chain) specifiers)BestVersionAlreadyInstalledDistributionNotFound HashError HashErrorsUnsupportedPythonVersion) indent_log)dist_in_install_pathdist_in_usersite ensure_dirnormalize_version_info)check_requires_pythonget_requires_python)MYPY_CHECK_RUNNING)Callable DefaultDictListOptionalSetTuple) pkg_resources)AbstractDistribution) PipSession) PackageFinder)RequirementPreparer)InstallRequirement)RequirementSetFc Cst|}zt||d}Wn:tjk rR}ztd|j|WYdSd}~XYnX|r\dSdtt |}|rt d|j||dSt d |j||dS)a Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. ) version_infoz-Package %r has an invalid Requires-Python: %sN.zBIgnoring failed Requires-Python check for package %r: %s not in %rz8Package {!r} requires a different Python: {} not in {!r}) rrrZInvalidSpecifierloggerwarningZ project_namejoinmapstrdebugr format)distrignore_requires_pythonZrequires_pythonZ is_compatibleexcversionr,@/usr/lib/python3.8/site-packages/pip/_internal/legacy_resolve.py_check_dist_requires_python>s> r.csdeZdZdZdddhZdfdd Zdd Zd d Zd d ZddZ ddZ ddZ ddZ Z S)ResolverzResolves which packages need to be installed/uninstalled to perform the requested operation without breaking the requirements of any package. eageronly-if-neededto-satisfy-onlyNc stt|| |jkst| dkr4tjdd} nt| } | |_||_ ||_ ||_ d|_ | |_ | |_||_||_||_||_||_tt|_dS)N)superr/__init___allowed_strategiesAssertionErrorsysrr_py_version_infopreparerfindersessionrequire_hashesupgrade_strategyforce_reinstallignore_dependenciesignore_installedr) use_user_site_make_install_reqrlist_discovered_dependencies) selfr:r<r;Zmake_install_reqrBr@rAr)r?r>Zpy_version_info __class__r,r-r5us&zResolver.__init__c Cs|jjrt|jj|jt|j}|jp>tdd|D|_|j j }| }|r`t |g}t}t||D]N}z||||Wqttk r}z||_||W5d}~XYqtXqt|r|dS)aResolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be possible to move the preparation to become a step separated from dependency resolution. css|] }|jVqdSN)Zhas_hash_options).0reqr,r,r- sz#Resolver.resolve..N)r:Zwheel_download_dirr Zunnamed_requirementsrD requirementsvaluesr=anyr; search_scopeZget_formatted_locationsr!inforrextend _resolve_onerrKappend) rFrequirement_setZ root_reqsrPZ locationsZdiscovered_reqsZ hash_errorsrKr*r,r,r-resolves2     zResolver.resolvecCs4|jdkrdS|jdkrdS|jdks*t|jSdS)Nr2Fr0Tr1)r>r7 is_directrFrKr,r,r-_is_upgrade_alloweds   zResolver._is_upgrade_allowedcCs,|jrt|jr"t|jr"|j|_d|_dS)z4 Set a requirement to be installed. N)rBr satisfied_byr Zconflicts_withrXr,r,r-_set_req_to_reinstallszResolver._set_req_to_reinstallcCs|jr dS||j|js dS|jr4||dS||sP|jdkrLdSdS|jsz|j j |ddWn(t k rYdSt k rYnX||dS)aCheck if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. Nr1z#already satisfied, skipping upgradezalready satisfiedT)Zupgradezalready up-to-date) rAcheck_if_existsrBrZr?r[rYr>linkr;Zfind_requirementrr)rFreq_to_installr,r,r-_check_skip_installeds*     zResolver._check_skip_installedcCs|jdk std|jr0|j||j|j|jS|jdks>t||}|jr`|j ||j|S| |}| |j||j|j ||j |j|j}|js||j|jr|jdkp|jp|jp|jjdk}|r||n td||S)zzTakes a InstallRequirement and returns a single AbstractDist representing a prepared variant of the same. Nz9require_hashes should have been set in Resolver.resolve()r2filezr?r]Zschemer[r!rQ)rFrKZ skip_reasonZupgrade_allowed abstract_distZ should_modifyr,r,r-_get_abstract_dist_forsV        zResolver._get_abstract_dist_forc s4js jrgSd_j}|}t|jjdgfdd}t  j sd_ j ddjs jrtddjttjt|j}|D]}td ||qtt|jtj@}||D]} || |d qjs&js&jW5QRXS) zxPrepare a single requirements file. :return: A list of additional InstallRequirements to also install. T)rr)csPt|}j}j|||d\}}|rB|rBj|||dS)N)parent_req_nameextras_requested)rCr%nameadd_requirementrErTrR)subreqreZsub_install_reqrdZ to_scan_againZ add_to_parentZ more_reqsr^rUrFr,r-add_req}s  z&Resolver._resolve_one..add_reqN)rdz!Installing extra requirements: %r,z"%s does not provide the extra '%s')re) constraintZpreparedZreqs_to_cleanuprTrcZget_pkg_resources_distributionr.r9r)r Zhas_requirementrfrWrgr@Zextrasr!r&r#sortedsetr"ZrequiresrarZZsuccessfully_downloaded) rFrUr^rbr(rjZmissing_requestedZmissingZavailable_requestedrhr,rir-rS[sV     zResolver._resolve_onecs8gtfdd|jD] }|q&S)zCreate the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. csN|js|krdS|jrdS|j|jD] }|q2|dSrI)rZrladdrErfrT)rKZdeporderZ ordered_reqsschedulerFr,r-rrs  z1Resolver.get_installation_order..schedule)rnrMrN)rFZreq_setZ install_reqr,rpr-get_installation_orders   zResolver.get_installation_order)N)__name__ __module__ __qualname____doc__r6r5rVrYr[r_rcrSrs __classcell__r,r,rGr-r/ns +3  5<Zr/)F)8rwZloggingr8 collectionsr itertoolsrZpip._vendor.packagingrZpip._internal.exceptionsrrrrr Zpip._internal.utils.loggingr Zpip._internal.utils.miscr r r rZpip._internal.utils.packagingrrZpip._internal.utils.typingrtypingrrrrrrZ pip._vendorrZpip._internal.distributionsrZpip._internal.network.sessionrZpip._internal.indexrZ pip._internal.operations.preparerZpip._internal.req.req_installrZpip._internal.req.req_setrr%ZInstallRequirementProviderZ getLoggerrtr!r.objectr/r,r,r,r-s4                0__pycache__/index.cpython-38.pyc000064400000061347152347654150012542 0ustar00U .e@s(dZddlmZddlZddlZddlmZddlmZddl m Z ddl m Z mZmZmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*e$rddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3ddl m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>e3e2de2e?e@ffZAe2e?e?e?e4eAe/e?fZBdddgZCeDeEZFd1d!d"ZGGd#d$d$eHZId%d&ZJGd'd(d(eHZKGd)ddeHZLGd*d+d+eHZMGd,ddeHZNd-d.ZOd/d0ZPdS)2z!Routines related to PyPI, indexes)absolute_importN) specifiers)canonicalize_name)parse)BestVersionAlreadyInstalledDistributionNotFoundInvalidWheelFilenameUnsupportedWheel)InstallationCandidate) FormatControl)Link)SelectionPreferences) TargetPython)WHEEL_EXTENSION) indent_log) build_netloc)check_requires_python)MYPY_CHECK_RUNNING)SUPPORTED_EXTENSIONS) url_to_path)Wheel) FrozenSetIterableListOptionalSetTextTupleUnion) _BaseVersion) LinkCollector) SearchScope)InstallRequirement) Pep425Tag)Hashesr BestCandidateResult PackageFinderFcCs~zt|j|d}Wn&tjk r8td|j|YnBX|szdtt|}|shtd||j|dStd||j|dS)aa Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. ) version_infoz2Ignoring invalid Requires-Python (%r) for link: %s.z4Link requires a different Python (%s not in: %r): %sFzBIgnoring failed Requires-Python check (%s not in: %r) for link: %sT) rZrequires_pythonrZInvalidSpecifierloggerdebugjoinmapstr)linkr(ignore_requires_pythonZ is_compatibleversionr%r%7/usr/lib/python3.8/site-packages/pip/_internal/index.py_check_link_requires_python;s8  r3c@s,eZdZdZedZdddZddZdS) LinkEvaluatorzD Responsible for evaluating links for a particular project. z-py([123]\.?[0-9]?)$NcCs4|dkr d}||_||_||_||_||_||_dS)a :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. NF) _allow_yanked_canonical_name_ignore_requires_python_formats_target_python project_name)selfr:canonical_nameformats target_python allow_yankedr0r%r%r2__init__rszLinkEvaluator.__init__c Csd}|jr(|js(|jpd}dd|fS|jr<|j}|j}n|\}}|sPdS|tkrddd|fSd|jkr|t krd|j }d|fSd |j kr|d krd S|t kr,zt |j }Wntk rYd SXt|j|jkrd |j }d|fS|j}||s&|}dd|}d|fS|j}d|jkrP|t krPdd|j fS|sbt||j}|svdd|j fS|j|} | r|d| }| d} | |jjkrdSt||jj|j d} | sdSt!"d||d|fS)aG Determine whether a link is a candidate for installation. :return: A tuple (is_candidate, result), where `result` is (1) a version string if `is_candidate` is True, and (2) if `is_candidate` is False, an optional string to log the reason the link fails to qualify. N Fzyanked for reason: {})Fz not a filezunsupported archive format: %sZbinaryzNo binaries permitted for %sZmacosx10z.zip)Fz macosx10 one)Fzinvalid wheel filenamezwrong project name (not %s)z"none of the wheel's tags match: {}, sourcezNo sources permitted for %szMissing project version for %s)FzPython version is incorrect)r(r0)FNzFound link %s, version: %sT)# is_yankedr5 yanked_reasonformat egg_fragmentextsplitextrr8rr:pathrfilenamerrnamer6r9get_tags supportedZget_formatted_file_tagsr,r1_extract_version_from_fragment_py_version_researchstartgroup py_versionr3Zpy_version_infor7r*r+) r;r/r1reasonZegg_inforIwheelsupported_tagsZ file_tagsmatchrUZsupports_pythonr%r%r2 evaluate_linksx            zLinkEvaluator.evaluate_link)N) __name__ __module__ __qualname____doc__recompilerQr@rZr%r%r%r2r4fs  &r4c Cs|stdt||t|Sg}g}d}|D]>}|j}|js@n"|j|drV|d7}n ||q.||q.|rx|}nt|}t|t|krd} n dt|d dd |D} td t|||j |t||| |S) a Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). zJGiven no hashes to check %s links for project %r: discarding no candidatesr)hashesrDzdiscarding no candidateszdiscarding {} non-matches: {}z css|]}t|jVqdSN)r.r/.0 candidater%r%r2 +sz*filter_unallowed_hashes..zPChecked %s links for project %r against %s hashes (%s matches, %s no digest): %s) r*r+lenlistr/Zhas_hashis_hash_allowedappendrGr,Z digest_count) candidatesrar:Zmatches_or_no_digestZ non_matchesZ match_countrer/ZfilteredZdiscard_messager%r%r2filter_unallowed_hashessL      rlc@seZdZdZdddZdS)CandidatePreferenceszk Encapsulates some of the preferences for filtering and sorting InstallationCandidate objects. FcCs||_||_dS)zR :param allow_all_prereleases: Whether to allow all pre-releases. N)allow_all_prereleases prefer_binary)r;rornr%r%r2r@Cs zCandidatePreferences.__init__N)FF)r[r\r]r^r@r%r%r%r2rm<srmc@s(eZdZdZddZddZddZdS) r&zA collection of candidates, returned by `PackageFinder.find_best_candidate`. This class is only intended to be instantiated by CandidateEvaluator's `compute_best_candidate()` method. cCsHt|t|kst|dkr&|r2tn ||ks2t||_||_||_dS)a :param candidates: A sequence of all available candidates found. :param applicable_candidates: The applicable candidates. :param best_candidate: The most preferred candidate found, or None if no applicable candidates were found. N)setAssertionError_applicable_candidates _candidatesbest_candidater;rkapplicable_candidatesrtr%r%r2r@Ws   zBestCandidateResult.__init__cCs t|jS)z(Iterate through all candidates. )iterrsr;r%r%r2iter_allpszBestCandidateResult.iter_allcCs t|jS)z3Iterate through the applicable candidates. )rwrrrxr%r%r2iter_applicablevsz#BestCandidateResult.iter_applicableN)r[r\r]r^r@ryrzr%r%r%r2r&Psc@sHeZdZdZedddZdddZdd Zd d Zd d Z ddZ dS)CandidateEvaluatorzm Responsible for filtering and sorting candidates for installation based on what tags are valid. NFcCs:|dkrt}|dkrt}|}|||||||dS)aCreate a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :param hashes: An optional collection of allowed hashes. N)r:rX specifierrornra)rrZ SpecifierSetrN)clsr:r>rornr|rarXr%r%r2createszCandidateEvaluator.createcCs(||_||_||_||_||_||_dS)z :param supported_tags: The PEP 425 tags supported by the target Python in order of preference (most preferred first). N)_allow_all_prereleases_hashes_prefer_binary _project_name _specifier_supported_tags)r;r:rXr|rornrar%r%r2r@s zCandidateEvaluator.__init__csV|jpd}|j}dd|jdd|D|dDfdd|D}t||j|jd S) zM Return the applicable candidates from a list of candidates. NcSsh|] }t|qSr%)r.)rdvr%r%r2 sz?CandidateEvaluator.get_applicable_candidates..css|]}t|jVqdSrbr.r1rdcr%r%r2rfsz?CandidateEvaluator.get_applicable_candidates..)Z prereleasescsg|]}t|jkr|qSr%rrZversionsr%r2 sz@CandidateEvaluator.get_applicable_candidates..)rkrar:)rrfilterrlrr)r;rkZallow_prereleasesr|rvr%rr2get_applicable_candidatess   z,CandidateEvaluator.get_applicable_candidatesc Cs|j}t|}d}d}|j}|jrt|j}||sDtd|j|jrNd}| | }|j dk rt d|j } | } t| d| df}n| }t||j} dt|j} | | ||j||fS)a) Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal r%rzB%s is not a supported wheel for this platform. It can't be sorted.rDNz ^(\d+)(.*)$)rrgr/Zis_wheelrrLrOr rZsupport_index_min build_tagr_rYgroupsintrirrEr1) r;reZ valid_tagsZ support_numrZbinary_preferencer/rWZprirYZbuild_tag_groupsZhas_allowed_hashZ yank_valuer%r%r2 _sort_keys<    zCandidateEvaluator._sort_keycCsH|sdSt||jd}|j}|jrD|jp*d}dj||d}t||S)zy Return the best candidate per the instance's sort order, or None if no candidate is acceptable. NkeyrAzqThe candidate selected for download or install is a yanked version: {candidate} Reason for being yanked: {reason})rerV)maxrr/rErFrGr*Zwarning)r;rkrtr/rVmsgr%r%r2sort_best_candidates   z&CandidateEvaluator.sort_best_candidatecCs"||}||}t|||dS)zF Compute and return a `BestCandidateResult` instance. )rvrt)rrr&rur%r%r2compute_best_candidate<s  z)CandidateEvaluator.compute_best_candidate)NFFNN)FFN) r[r\r]r^ classmethodr~r@rrrrr%r%r%r2r{}s  ) $<r{c@seZdZdZd&ddZed'ddZeddZej d dZed d Z ed d Z eddZ eddZ ddZddZddZddZddZddZddZd(d d!Zd)d"d#Zd$d%ZdS)*r'zThis finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. NcCsP|dkrt}|pttt}||_||_||_||_||_||_t|_ dS)a This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. N) rmr rpr5_candidate_prefsr7_link_collectorr9format_control _logged_links)r;link_collectorr>r?rcandidate_prefsr0r%r%r2r@VszPackageFinder.__init__cCs8|dkrt}t|j|jd}|||||j|j|jdS)afCreate a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. N)rorn)rrr>r?rr0)rrmrornr?rr0)r}rZselection_prefsr>rr%r%r2r~~szPackageFinder.createcCs|jjSrbr search_scoperxr%r%r2rszPackageFinder.search_scopecCs ||j_dSrbr)r;rr%r%r2rscCs|jjSrb)r find_linksrxr%r%r2rszPackageFinder.find_linkscCs|jjSrb)r index_urlsrxr%r%r2rszPackageFinder.index_urlsccs|jjjD]}t|Vq dSrb)rZsessionZpip_trusted_originsr)r;Z host_portr%r%r2 trusted_hostsszPackageFinder.trusted_hostscCs|jjSrbrrnrxr%r%r2rnsz#PackageFinder.allow_all_prereleasescCs d|j_dS)NTrrxr%r%r2set_allow_all_prereleasessz'PackageFinder.set_allow_all_prereleasescCs.t|}|j|}t||||j|j|jdS)N)r:r<r=r>r?r0)rrZget_allowed_formatsr4r9r5r7)r;r:r<r=r%r%r2make_link_evaluators z!PackageFinder.make_link_evaluatorcCsPgg}}t}|D]2}||kr|||jr<||q||q||S)z Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates )rpaddrHrj)r;linksZeggsZno_eggsseenr/r%r%r2 _sort_linkss    zPackageFinder._sort_linkscCs(||jkr$td|||j|dS)NzSkipping link: %s: %s)rr*r+r)r;r/rVr%r%r2_log_skipped_links zPackageFinder._log_skipped_linkcCs<||\}}|s(|r$|j||ddSt|j|t|dS)z If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. )rVN)Zprojectr/r1)rZrr r:r.)r;link_evaluatorr/Z is_candidateresultr%r%r2get_install_candidatesz#PackageFinder.get_install_candidatecCs6g}||D]"}|||}|dk r||q|S)zU Convert links that are candidates to InstallationCandidate objects. N)rrrj)r;rrrkr/rer%r%r2evaluate_linkss   zPackageFinder.evaluate_linksc Cs|j|}||}|j||jd}g}|jD]>\}}td|t |j||d}| |W5QRXq4|j||j d} | r| j ddtdd dd| D| ||S) aFind all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. )rzAnalyzing links from page %sT)reversezLocal files found: %srBcSsg|]}t|jjqSr%)rr/Zurlrcr%r%r2r2sz5PackageFinder.find_all_candidates..)rZ collect_linksrrrZpagesitemsr*r+rextendfilessortr,) r;r:Zcollected_linksrZfind_links_versionsZ page_versionsZpage_urlZ page_linksZ new_versionsZ file_versionsr%r%r2find_all_candidates s8      z!PackageFinder.find_all_candidatescCs"|j}tj||j|j|j||dS)z3Create a CandidateEvaluator object to use. )r:r>rornr|ra)rr{r~r9rorn)r;r:r|rarr%r%r2make_candidate_evaluator;s z&PackageFinder.make_candidate_evaluatorcCs$||}|j|||d}||S)aFind matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. )r:r|ra)rrr)r;r:r|rarkZcandidate_evaluatorr%r%r2find_best_candidateNs z!PackageFinder.find_best_candidatec Cs|jdd}|j|j|j|d}|j}d}|jdk r@t|jj}dd}|dkrz|dkrzt d||| t d|d}|r|dks|j|krd }|s|dk r|rt d |nt d ||jdS|rt d ||| tt d |j|| |jS)zTry to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise F)Ztrust_internet)r|raNcSs dtdd|DtdpdS)NrBcSsh|]}t|jqSr%rrr%r%r2r}szKPackageFinder.find_requirement.._format_versions..rZnone)r,sorted parse_version)Z cand_iterr%r%r2_format_versionsws  z8PackageFinder.find_requirement.._format_versionszNCould not find a version that satisfies the requirement %s (from versions: %s)z%No matching distribution found for %sTzLExisting installed version (%s) is most up-to-date and satisfies requirementzUExisting installed version (%s) satisfies requirement (most up-to-date version is %s)z=Installed version (%s) is most up-to-date (past versions: %s)z)Using version %s (newest of versions: %s))rarrMr|rtZ satisfied_byrr1r*Zcriticalryrr+rzrr/) r;ZreqZupgraderaZbest_candidate_resultrtZinstalled_versionrZbest_installedr%r%r2find_requirementesh        zPackageFinder.find_requirement)NNN)N)NN)NN)r[r\r]r^r@rr~propertyrsetterrrrrnrrrrrrrrrrr%r%r%r2r'OsD  (         1  cCsLt|D].\}}|dkrqt|d||kr|Sqtd||dS)aFind the separator's index based on the package's canonical name. :param fragment: A + filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 -Nz{} does not match {}) enumerater ValueErrorrG)fragmentr<irr%r%r2_find_name_version_seps  rcCsBzt||d}Wntk r(YdSX||d}|s>dS|S)zParse the version string from a + filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. rDN)rr)rr<Z version_startr1r%r%r2rPs  rP)F)Qr^Z __future__rZloggingr_Zpip._vendor.packagingrZpip._vendor.packaging.utilsrZpip._vendor.packaging.versionrrZpip._internal.exceptionsrrrr Zpip._internal.models.candidater Z#pip._internal.models.format_controlr Zpip._internal.models.linkr Z$pip._internal.models.selection_prefsr Z"pip._internal.models.target_pythonrZpip._internal.utils.filetypesrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.packagingrZpip._internal.utils.typingrZpip._internal.utils.unpackingrZpip._internal.utils.urlsrZpip._internal.wheelrtypingrrrrrrrrrZpip._internal.collectorr Z!pip._internal.models.search_scoper!Zpip._internal.reqr"Zpip._internal.pep425tagsr#Zpip._internal.utils.hashesr$rr.ZBuildTagZCandidateSortingKey__all__Z getLoggerr[r*r3objectr4rlrmr&r{r'rrPr%r%r%r2s^                 (         + K-Sh__pycache__/locations.cpython-38.opt-1.pyc000064400000005766152347654150014370 0ustar00U .e&@sdZddlmZddlZddlZddlZddlZddlZddlZddl mZ ddl m Z ddl mZddlmZddlmZdd lmZerdd lmZmZmZmZmZed Zd d ZddZedZ e!"dkre #Z z e$Z%Wne&k r ej'Z%YnXer`ej()ej*dZ+ej()e%dZ,ej(-e+sej()ej*dZ+ej()e%dZ,nJej()ej*dZ+ej()e%dZ,ejdddkrej*dddkrdZ+dddZ.dS)z7Locations where we look for configs, install stuff, etc)absolute_importN) sysconfig) SCHEME_KEYS)appdirs)WINDOWS)MYPY_CHECK_RUNNING)running_under_virtualenv)AnyUnionDictListOptionalZpipcCs djtjS)ze Return the major-minor version of the current Python as a string, e.g. "3.7" or "3.10". z{}.{})formatsys version_inforr;/usr/lib/python3.8/site-packages/pip/_internal/locations.pyget_major_minor_versionsrcCsZtrtjtjd}n6ztjtd}Wntk rLtdYnXtj |S)Nsrcz=The folder you are executing pip from can no longer be found.) rospathjoinrprefixgetcwdOSErrorexitabspath)Z src_prefixrrrget_src_prefix(s rpurelibZpypyZScriptsbindarwinz/System/Library/z/usr/local/binFcCsHddlm}i}|r ddgi}ni}d|i} | ||| } | | jddd} |p\| j| _|sh|rnd | _|pv| j| _|p| j| _|p| j| _| t D]} t | d | || <qd | dkr|t | j| jd trDtjtjd ddt||d<|dk rDtjtj|dd} tj|| dd|d<|S)z+ Return a distutils install scheme r) DistributionZ script_argsz --no-user-cfgnameZinstallT)ZcreateZinstall_ install_lib)rZplatlibZincludesitezpython{}ZheadersN)Zdistutils.distr#updateZparse_config_filesZget_command_objuserrhomerootZfinalize_optionsrgetattrZget_option_dictdictr&rrrrrrr splitdriver)Z dist_namer*r+r,isolatedrr#ZschemeZextra_dist_argsZ dist_argsdikeyZ path_no_driverrrdistutils_scheme[sP           r4)FNNFN)/__doc__Z __future__rrZos.pathplatformr'rrZ distutilsZdistutils_sysconfigZdistutils.command.installrZpip._internal.utilsrZpip._internal.utils.compatrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrtypingr r r r r Zuser_cache_dirZUSER_CACHE_DIRrrZget_pathZ site_packagesZpython_implementationlowerZget_python_libgetusersitepackages user_siteAttributeError USER_SITErrrZbin_pyZbin_userexistsr4rrrrsN            (__pycache__/wheel.cpython-38.pyc000064400000066650152347654150012541 0ustar00U .eH@s4dZddlmZddlZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lm Z m!Z!m"Z"dd l#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>ddl?m@Z@e:rddlAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMddlNmOZOddlPmQZQddlRmSZSddlTmUZUddlVmWZWeGeXdfZYeLeQgeZfZ[d Z\e]e^Z_d!d"Z`dXd$d%ZadYd&d'Zbd(d)Zcd*d+Zdd,d-Zee fd.e jgZhd/d0Zid1d2Zjd3d4Zkd5d6Zld7d8ZmGd9d:d:enZod;d<ZpGd=d>d>eZqdZdAdBZrdCdDZsdEdFZtdGdHZuGdIdJdJevZwe fdKe jxfdLdMZydNdOZzdPdQZ{dRdSZ|dTdUZ}GdVdWdWevZ~dS)[zH Support for installing and building the "wheel" binary package format. )absolute_importN)urlsafe_b64encode)Parser) pkg_resources) ScriptMaker)get_export_entry)canonicalize_name)StringIO) pep425tags)InstallationErrorInvalidWheelFilenameUnsupportedWheel)distutils_schemeget_major_minor_version)Link) indent_log)has_delete_marker_file)captured_stdout ensure_dir read_chunks)make_setuptools_shim_args) LOG_DIVIDERcall_subprocessformat_command_argsrunner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING) open_spinner) unpack_file) path_to_url) DictListOptionalSequenceMappingTupleIOTextAnyIterableCallableSet) Requirement)InstallRequirement)RequirementPreparer) WheelCache) Pep425Tag.)rcCstj||tjjdS)N/)ospathrelpathreplacesep)srcpr:7/usr/lib/python3.8/site-packages/pip/_internal/wheel.pynormpathOsr<c CsRt}d}t|d.}t||dD]}|t|7}||q$W5QRX||fS)z5Return (hash, length) for path using hashlib.sha256()rrb)size)hashlibZsha256openrlenupdate)r4 blocksizehlengthfblockr:r:r; hash_fileSs  rIcCs6t||\}}dt|dd}|t|fS)z?Return (encoded_digest, length) for path using hashlib.sha256()zsha256=latin1=)rIrdigestdecoderstripstr)r4rDrErFrLr:r:r;rehash_srPcCs6tjddkri}d}n ddi}d}t|||f|S)Nrbnewline)sys version_inforA)namemodenlbinr:r:r; open_for_csvjs r[cCs|d}||d<d|S)zBReplace the Python tag in a wheel file name with a new value. -)splitjoin)Z wheelnameZnew_tagpartsr:r:r;replace_python_tagus rac Cstj|rt|dR}|}|ds8W5QRdStjt }d|tj d}| }W5QRXt|d}| || |W5QRXdSdS) zLReplace #!python with #!/path/to/python Return True if file was changed.r>s#!pythonFs#!asciiwbTN) r3r4isfilerAreadline startswithrU executableencodegetfilesystemencodinglinesepreadwrite)r4Zscript firstlineZexenamerestr:r:r; fix_script~s     rozX^(?P(?P.+?)(-(?P.+?))?) \.dist-info$c Cs|dd}t|D]p}t|}|r|d|krttj||d6}|D]*}| }|dkrPW5QRdSqPW5QRXqdS)zP Return True if the extracted wheel in wheeldir should go into purelib. r\_rWWHEELzroot-is-purelib: trueTF) r6r3listdir dist_info_rematchgrouprAr4r_lowerrN)rWwheeldirZ name_foldeditemrtwheelliner:r:r;root_is_purelibs    r{c stj|siifSt|8}t}|D]}|||dq(|dW5QRXtj |}| di}| di}ddt fdd| D}t fd d| D}||fS) N rZconsole_scriptsZ gui_scriptscSst|dddS)zRget the string representation of EntryPoint, remove space and split on '=' rTrK)rOr6r^)sr:r:r; _split_epsz"get_entrypoints.._split_epc3s|]}|VqdSNr:.0vrr:r; sz"get_entrypoints..c3s|]}|VqdSrr:rrr:r;rs)r3r4existsrAr rlstripseekrZ EntryPointZ parse_mapgetdictvalues)filenamefpdatarzZ entry_pointsconsoleguir:rr;get_entrypointss      rc sJ|sdStt}|D]*}tj|}tj|}|||qddtj dd tj D tj tjtjfdd|D}|sdSg}|D]b\}}t|}t|dkrd |d } n$d d |dd d|d } | d| |qd} t|dkr0| | dn| | dd|S)zDetermine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. NcSs g|]}tj|tjqSr:)r3r4normcaserNr7)rir:r:r; sz5message_about_scripts_not_on_PATH..PATHrTcs&i|]\}}tj|kr||qSr:)r3r4r)r parent_dirscriptsZ not_warn_dirsr:r; sz5message_about_scripts_not_on_PATH..r1z script {} isrzscripts {} are, z and z.The {} installed in '{}' which is not on PATH.zeConsider adding {} to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.zthis directoryzthese directoriesr|) collections defaultdictsetr3r4dirnamebasenameaddenvironrr^pathsepappendrrUrgitemssortedrBformatr_) rZgrouped_by_dirdestfilerZ script_nameZwarn_for msg_linesZ dir_scriptsZsorted_scriptsZ start_textZ last_line_fmtr:rr;!message_about_scripts_not_on_PATHsH     rcCst|dddS)a; Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. cSstdd|DS)Ncss|]}t|VqdSr)rO)rxr:r:r;rsz3sorted_outrows....)tuple)rowr:r:r;z sorted_outrows..)key)r)outrowsr:r:r;sorted_outrowssrc Csg}|D]v}t|dkr(td|t|}|d}|||}||d<||krpt|\} } | |d<| |d<|t|q|D]*} t| \} } |t | || t | fq|D]} ||| ddfq|S)z_ :param installed: A map from archive RECORD path to installation RECORD path. rQz,RECORD line has more than three elements: {}rr1rT) rBloggerwarningrlistpoprPrrr<rO) Z old_csv_rows installedchanged generatedlib_dirZinstalled_rowsrZold_pathnew_pathrLrFrGr:r:r;get_csv_rows_for_installeds*     rc@s eZdZdS)MissingCallableSuffixN)__name__ __module__ __qualname__r:r:r:r;r=srcCs*t|}|dk r&|jdkr&tt|dSr)rsuffixrrO) specificationentryr:r:r;_raise_for_invalid_entrypointAsrcseZdZdfdd ZZS)PipScriptMakerNcst|tt|||Sr)rsuperrmake)selfrZoptions __class__r:r;rHszPipScriptMaker.make)N)rrrr __classcell__r:r:rr;rGsrFTc - s\|st|||||| d}t| r,|dn|dgg tjjtjj} itg} |rt4} t t dt j | dddW5QRXW5QRXt | d. fdd d/fd d }|| dstd tjdd}t|\fdd}D]j}d }d }ttj |D]F}d }|dkr`t}|}tj ||} ||}|| |d||dqFq&td |d}d|_dh|_d|_g}dd }|rDdtjkr|d|tjdddkr|dtjd|f|dt|fddD}|D] }|=q6dd }|rdtjkrp|d||dt|fddD}|D] }|=q| d d!!Dd"d!D}g}z.|"|}| || |"|d#diWn>t#k r>}z|j$d} t%d$&| W5d }~XYnX| rbt'|}!|!d k rbt (|!tjdd%}"tjdd&}#t)|#d'}$|$*d(W5QRXt+,|#|"| |"tjdd)}%tjdd*}&t-|%d+\}'t-|&d,F}(t./|'})t0|)| d-}*t.1|(}+t2|*D]},|+3|,q&W5QRXW5QRXt+,|&|%d S)0zInstall a wheel)userhomerootisolatedprefixZpurelibZplatlibignoreT)forcequietFcs.t|}t|}||<|r*|dS)z6Map archive RECORD paths to installation RECORD paths.N)r<r)srcfilerZmodifiedZoldpathnewpath)rrrrwr:r;record_installeds   z*move_wheel_files..record_installedNcst|t|D]\}}}|t|dtjj}tj||} |rf|tjjdd drfq|D]} tj||| } |r|dkr| dr | qjqj|rj| drjt |  t j rjrtd| dd | qj|D]} |r|| rqtj|| } tj||| }t| tj|rFt|t| |t| }ttdr|t||j|jft| tjrt| }|jtjBtjBtjB}t||d }|r||}| ||qqdS) Nr1rz.datarTz .dist-infoz!Multiple .dist-info directories: rutimeF)rr3walkrBlstripr4r7r_r^endswithrrrfrWAssertionErrorrunlinkshutilZcopyfilestathasattrrst_atimest_mtimeaccessX_OKst_modeS_IXUSRS_IXGRPS_IXOTHchmod)sourcedestZis_basefixerfilterdirZsubdirsfilesZbasedirZdestdirr~Z destsubdirrGrrstZ permissionsr) data_dirsinfo_dirrreqr:r;clobbers^         z!move_wheel_files..clobberz!%s .dist-info directory not foundrzentry_points.txtcsh|dr|dd}n<|dr8|dd}n |drT|dd}n|}|kpf|kS)Nz.exez -script.pyiz.pya)rvr)rWZ matchname)rrr:r;is_entrypoint_wrappersz/move_wheel_files..is_entrypoint_wrapperr)rrrTZpipZENSUREPIP_OPTIONSzpip = Z altinstallz pip%s = %scSsg|]}td|r|qS)zpip(\d(\.\d)?)?$rertrkr:r:r;r0s z$move_wheel_files..Z easy_installzeasy_install = zeasy_install-%s = %scSsg|]}td|r|qS)zeasy_install(-\d\.\d)?$rrr:r:r;r@s css|]}d|VqdS)%s = %sNr:rZkvr:r:r;rGsz#move_wheel_files..cSsg|] }d|qS)rr:rr:r:r;rKsrzInvalid script entry point: {} for req: {} - A callable suffix is required. Cf https://packaging.python.org/en/latest/distributing.html#console-scripts for more information.Z INSTALLERz INSTALLER.piprcspip ZRECORDz RECORD.piprzw+)rrrr)F)NN)4rr{rNr3r4r7rrwarningscatch_warningsfilterwarnings compileall compile_dirrdebuggetvaluerr_rrrrorrZvariantsZset_moderrrrrUrVrextendrZ make_multiplerargsr rrrrArlrmover[csvreaderrwriterrZwriterow)-rWrrwrrrZ pycompileZschemerrZwarn_script_locationrrstdoutrZep_filerZdatadirrrZsubdirrZmakerZscripts_to_generateZ pip_scriptZpip_eprZeasy_install_scriptZeasy_install_epZgui_scripts_to_generateZgenerated_console_scriptsermsgZ installerZtemp_installerZinstaller_filerecordZ temp_recordZ record_inZ record_outr rr rr:) rrrrrrrrrrwr;move_wheel_filesMs    $F   #                     "rcCsrzVddtd|Dd}|d}t|}|d}ttt| d}|WSt k rlYdSXdS)z Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. cSsg|]}|qSr:r:)rdr:r:r;rsz!wheel_version..Nrrqz Wheel-Version.) rZ find_on_pathZ get_metadatarZparsestrrrmapintr^ Exception) source_dirZdistZ wheel_dataversionr:r:r; wheel_versions   rcCsb|std||dtdkr>td|dtt|fn |tkr^tddtt|dS)a Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given z(%s is in an unsupported or invalid wheelrzB%s's Wheel-Version (%s) is not compatible with this version of piprz*Installing from a newer Wheel-Version (%s)N)r VERSION_COMPATIBLEr_rrOrr)rrWr:r:r;check_compatibilitysrcCs d|S)z Format three tags in the form "--". :param file_tag: A 3-tuple of tags (python_tag, abi_tag, platform_tag). r\)r_)Zfile_tagr:r:r; format_tagsrc@s>eZdZdZedejZddZddZ ddZ d d Z d S) Wheelz A wheel filez^(?P(?P.+?)-(?P.*?)) ((-(?P\d[^-]*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$csj|}|std||_|ddd_|ddd_|d_|d d_ |d  d_ |d  d_ fd d j D_ d S)zX :raises InvalidWheelFilename: when the filename is invalid for a wheel z!%s is not a valid wheel filename.rWrpr\ZverbuildZpyverrZabiZplatcs.h|]&}jD]}jD]}|||fqqqSr:)abisplats)rryzrr:r; s z!Wheel.__init__..N) wheel_file_rertr rrur6rWrZ build_tagr^Z pyversionsrr file_tags)rrZ wheel_infor:r!r;__init__s   zWheel.__init__cCstdd|jDS)zF Return the wheel's tags as a sorted list of strings. css|]}t|VqdSr)rrtagr:r:r;rsz0Wheel.get_formatted_file_tags..)rr$r!r:r:r;get_formatted_file_tagsszWheel.get_formatted_file_tagscstfdd|jDS)a Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. c3s |]}|kr|VqdSr)indexr&tagsr:r;rsz*Wheel.support_index_min..)minr$rr+r:r*r;support_index_minszWheel.support_index_mincCs|j| S)z Return whether the wheel is compatible with one of the given tags. :param tags: the PEP 425 tags to check the wheel against. )r$ isdisjointr-r:r:r; supportedszWheel.supportedN) rrr__doc__rcompileVERBOSEr#r%r(r.r0r:r:r:r;rsrz([a-z0-9_.]+)-([a-z0-9_.!+-]+)cCst||S)zjDetermine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 )boolsearch)r~Z _egg_info_rer:r:r;_contains_egg_infosr6cCs|jr dS|jr&|s"td|jdS|s.dS|js:|js>dS||sXtd|jdS|jrj|jjrjdS|j}| \}}|rt |rdSdS)a[ Return whether to build an InstallRequirement object using the ephemeral cache. :param cache_available: whether a cache directory is available for the should_unpack=True case. :return: True or False to build the requirement with ephem_cache=True or False, respectively; or None not to build the requirement. Nz(Skipping %s, due to already being wheel.FzCSkipping wheel build for %s, due to binaries being disabled for it.T) Z constraintis_wheelrinforWZeditablerlinkZis_vcssplitextr6)r should_unpackcache_availablecheck_binary_allowedr9baseZextr:r:r;should_use_ephemeral_cache s4   r?cCs^t|}d|}|s |d7}n:ttjkr8|d7}n"|dsJ|d7}|d|t7}|S)z1 Format command information for logging. zCommand arguments: {} zCommand output: Nonez'Command output: [use --verbose to show]r|zCommand output: {}{})rrrZgetEffectiveLevelloggingDEBUGrr) command_argscommand_outputZ command_desctextr:r:r;format_command_resultGs    rEcCsxt|}|s4d|j}|t||7}t|dSt|dkrfd|j|}|t||7}t|tj ||dS)zH Return the path to the wheel in the temporary build directory. z1Legacy build of wheel for {!r} created no files. Nr1zZLegacy build of wheel for {!r} created more than one file. Filenames (choosing first): {} r) rrrWrErrrBr3r4r_)namestemp_dirrrBrCr r:r:r;get_legacy_build_wheel_path^s$    rHcCsdS)NTr:)rpr:r:r; _always_true~srIc@s\eZdZdZdddZdddZddd Zd d Zdd d ZdddZ ddZ dddZ dS) WheelBuilderz#Build wheels from a RequirementSet.NFcCsD|dkr t}||_||_|j|_|p&g|_|p0g|_||_||_dSr) rIpreparer wheel_cacheZwheel_download_dir _wheel_dir build_optionsglobal_optionsr=no_clean)rrKrLrNrOr=rPr:r:r;r%s   zWheelBuilder.__init__c Cs.|j|j|||dW5QRSQRXdS)ziBuild one wheel. :return: The filename of the built wheel, or None if the build failed.  python_tagN)Z build_env_build_one_inside_env)rr output_dirrRr:r:r; _build_oneszWheelBuilder._build_onec Cstdd}|jr|j}n|j}|||j|d}|dk rtj|}tj||}zNt|\} } t ||t d|j || | t d||WW5QRStk rYnX||W5QRdSQRXdS)Nry)ZkindrQz3Created wheel for %s: filename=%s size=%d sha256=%szStored in directory: %s)rZ use_pep517_build_one_pep517_build_one_legacyr4r3rr_rIrrrr8rWZ hexdigestr _clean_one) rrrTrRrGZbuilder wheel_path wheel_nameZ dest_pathZ wheel_hashrFr:r:r;rSs.      z"WheelBuilder._build_one_inside_envcCst|j|jddS)NT)rOZunbuffered_output)rZ setup_py_pathrO)rrr:r:r;_base_setup_argss zWheelBuilder._base_setup_argsc Cs|jdk st|jr*td|jfdSz~td|td|j}|j }| ||j ||jd}W5QRX|rt ||}t t j||t j|||}Wn$tk rtd|jYdSXt j||S)zBuild one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. NzGCannot build wheel for %s using PEP 517 when --build-options is presentDestination directory: %szBuilding wheel for {} (PEP 517))metadata_directoryFailed building wheel for %s)r]rrNrerrorrWrrrZpep517_backendZsubprocess_runnerZ build_wheelrar3renamer4r_r)rrtempdrRZrunnerZbackendrZnew_namer:r:r;rVs8      zWheelBuilder._build_one_pep517c Cs||}d|jf}t|}td||dd|g|j}|dk rT|d|g7}zt||j|d}Wn8tk r| dt d |jYW5QRdSXt |} t | ||||d } | W5QRSQRXdS) zBuild one InstallRequirement using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. z Building wheel for %s (setup.py)r\Z bdist_wheelz-dNz --python-tag)cwdspinnerr_r^)rFrGrrBrC)r[rWrrrrNrZunpacked_source_directoryrZfinishr_r3rrrH) rrrarR base_argsZ spin_messagerdZ wheel_argsoutputrFrYr:r:r;rWs8         zWheelBuilder._build_one_legacycCsb||}td|j|ddg}zt||jdWdStk r\td|jYdSXdS)NzRunning setup.py clean for %sZcleanz--all)rcTz Failed cleaning build dir for %sF)r[rr8rWrrrr_)rrreZ clean_argsr:r:r;rXs  zWheelBuilder._clean_onec Cs|r |jr|s|jstg}t|jj}|D]\}t||||jd}|dkrLq,|rt|rd|j|j}qz|j |j}n|j}| ||fq,|sgSt dd dd|Dd}|rtj}tgg} } |D]\}}z t|WnFtk r.} z&t d|j| | |WYqW5d} ~ XYnX|j|||d} | r| ||r|jrrt|jsrtd |||jj|_tt| |_|jjstt|jj |jq| |qW5QRX| rt d d d d| D| rt d d dd| D| S)aBuild wheels. :param should_unpack: If True, after building the wheel, unpack it and replace the sdist with the unpacked version in preparation for installation. :return: True if all the wheels built correctly. )r;r<r=Nz*Building wheels for collected packages: %srcSsg|]\}}|jqSr:rW)rrrpr:r:r;r\sz&WheelBuilder.build..z Building wheel for %s failed: %srQzbad source dir - missing markerzSuccessfully built %sr}cSsg|] }|jqSr:rgrrr:r:r;rszFailed to build %scSsg|] }|jqSr:rgrhr:r:r;rs)!rMrr4rL cache_dirr?r=Zget_ephem_path_for_linkr9Zget_path_for_linkrrr8r_r Zimplementation_tagrrOSErrorrrWrUrrZremove_temporary_sourceZensure_build_locationrKZ build_dirrrr7rZ file_path) rZ requirementsr;Zbuildsetr<rZ ephem_cacherTrRZ build_successZ build_failurer Z wheel_filer:r:r;r#s       zWheelBuilder.build)NNNF)N)N)N)N)F) rrrr1r%rUrSr[rVrWrXrr:r:r:r;rJs   ' %rJ)r=)r=)FNNTNFNT)r1Z __future__rrrrr@r@Zos.pathr3rrrrUrbase64rZ email.parserrZ pip._vendorrZpip._vendor.distlib.scriptsrZpip._vendor.distlib.utilrZpip._vendor.packaging.utilsrZpip._vendor.sixr Z pip._internalr Zpip._internal.exceptionsr r r Zpip._internal.locationsrrZpip._internal.models.linkrZpip._internal.utils.loggingrZ pip._internal.utils.marker_filesrZpip._internal.utils.miscrrrZ$pip._internal.utils.setuptools_buildrZpip._internal.utils.subprocessrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.uirZpip._internal.utils.unpackingrZpip._internal.utils.urlsrtypingr r!r"r#r$r%r&r'r(r)r*r+Z"pip._vendor.packaging.requirementsr,Zpip._internal.req.req_installr-Z pip._internal.operations.preparer.Zpip._internal.cacher/Zpip._internal.pep425tagsr0rOZInstalledCSVRowr4ZBinaryAllowedPredicaterZ getLoggerrrr<rIrPr[raror2r3rsr{rrrrrrrrrrrrobjectrIr6r?rErHrIrJr:r:r:r;s                  8           =$  4 J : __pycache__/legacy_resolve.cpython-38.opt-1.pyc000064400000024134152347654150015366 0ustar00U .eRC@sFdZddlZddlZddlmZddlmZddlmZddl m Z m Z m Z m Z mZddlmZddlmZmZmZmZdd lmZmZdd lmZerdd lmZmZmZmZm Z m!Z!dd l"m#Z#dd l$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ee0e-ge-fZ1e2e3Z4dddZ5Gddde6Z7dS)ayDependency Resolution The dependency resolution in pip is performed as follows: for top-level requirements: a. only one spec allowed per project, regardless of conflicts or not. otherwise a "double requirement" exception is raised b. they override sub-dependency requirements. for sub-dependencies a. "first found, wins" (where the order is breadth first) N) defaultdict)chain) specifiers)BestVersionAlreadyInstalledDistributionNotFound HashError HashErrorsUnsupportedPythonVersion) indent_log)dist_in_install_pathdist_in_usersite ensure_dirnormalize_version_info)check_requires_pythonget_requires_python)MYPY_CHECK_RUNNING)Callable DefaultDictListOptionalSetTuple) pkg_resources)AbstractDistribution) PipSession) PackageFinder)RequirementPreparer)InstallRequirement)RequirementSetFc Cst|}zt||d}Wn:tjk rR}ztd|j|WYdSd}~XYnX|r\dSdtt |}|rt d|j||dSt d |j||dS)a Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. ) version_infoz-Package %r has an invalid Requires-Python: %sN.zBIgnoring failed Requires-Python check for package %r: %s not in %rz8Package {!r} requires a different Python: {} not in {!r}) rrrZInvalidSpecifierloggerwarningZ project_namejoinmapstrdebugr format)distrignore_requires_pythonZrequires_pythonZ is_compatibleexcversionr,@/usr/lib/python3.8/site-packages/pip/_internal/legacy_resolve.py_check_dist_requires_python>s> r.csdeZdZdZdddhZdfdd Zdd Zd d Zd d ZddZ ddZ ddZ ddZ Z S)ResolverzResolves which packages need to be installed/uninstalled to perform the requested operation without breaking the requirements of any package. eageronly-if-neededto-satisfy-onlyNc stt|| dkr&tjdd} nt| } | |_||_||_||_ d|_ | |_ | |_ ||_ ||_||_||_||_tt|_dS)N)superr/__init__sysrr_py_version_infopreparerfindersessionrequire_hashesupgrade_strategyforce_reinstallignore_dependenciesignore_installedr) use_user_site_make_install_reqrlist_discovered_dependencies) selfr8r:r9Zmake_install_reqr@r>r?r)r=r<Zpy_version_info __class__r,r-r5us$zResolver.__init__c Cs|jjrt|jj|jt|j}|jp>tdd|D|_|j j }| }|r`t |g}t}t||D]N}z||||Wqttk r}z||_||W5d}~XYqtXqt|r|dS)aResolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be possible to move the preparation to become a step separated from dependency resolution. css|] }|jVqdSN)Zhas_hash_options).0reqr,r,r- sz#Resolver.resolve..N)r8Zwheel_download_dirr Zunnamed_requirementsrB requirementsvaluesr;anyr9 search_scopeZget_formatted_locationsr!inforrextend _resolve_onerrIappend) rDrequirement_setZ root_reqsrNZ locationsZdiscovered_reqsZ hash_errorsrIr*r,r,r-resolves2     zResolver.resolvecCs&|jdkrdS|jdkrdS|jSdS)Nr2Fr0T)r< is_directrDrIr,r,r-_is_upgrade_alloweds   zResolver._is_upgrade_allowedcCs,|jrt|jr"t|jr"|j|_d|_dS)z4 Set a requirement to be installed. N)r@r satisfied_byr Zconflicts_withrVr,r,r-_set_req_to_reinstallszResolver._set_req_to_reinstallcCs|jr dS||j|js dS|jr4||dS||sP|jdkrLdSdS|jsz|j j |ddWn(t k rYdSt k rYnX||dS)aCheck if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. Nr1z#already satisfied, skipping upgradezalready satisfiedT)Zupgradezalready up-to-date) r?check_if_existsr@rXr=rYrWr<linkr9Zfind_requirementrr)rDreq_to_installr,r,r-_check_skip_installeds*     zResolver._check_skip_installedcCs|jr|j||j|j|jS||}|jr@|j||j|S| |}| |j||j|j ||j |j|j}|j s||j|jr|jdkp|jp|j p|jjdk}|r||n td||S)zzTakes a InstallRequirement and returns a single AbstractDist representing a prepared variant of the same. r2filez.add_reqN)rbz!Installing extra requirements: %r,z"%s does not provide the extra '%s')rc) constraintZpreparedZreqs_to_cleanuprRraZget_pkg_resources_distributionr.r7r)r Zhas_requirementrdrUrer>Zextrasr!r&r#sortedsetr"Zrequiresr_rXZsuccessfully_downloaded) rDrSr\r`r(rhZmissing_requestedZmissingZavailable_requestedrfr,rgr-rQ[sV     zResolver._resolve_onecs8gtfdd|jD] }|q&S)zCreate the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. csN|js|krdS|jrdS|j|jD] }|q2|dSrG)rXrjaddrCrdrR)rIZdeporderZ ordered_reqsschedulerDr,r-rps  z1Resolver.get_installation_order..schedule)rlrKrL)rDZreq_setZ install_reqr,rnr-get_installation_orders   zResolver.get_installation_order)N)__name__ __module__ __qualname____doc__Z_allowed_strategiesr5rTrWrYr]rarQrq __classcell__r,r,rEr-r/ns +3  5<Zr/)F)8ruZloggingr6 collectionsr itertoolsrZpip._vendor.packagingrZpip._internal.exceptionsrrrrr Zpip._internal.utils.loggingr Zpip._internal.utils.miscr r r rZpip._internal.utils.packagingrrZpip._internal.utils.typingrtypingrrrrrrZ pip._vendorrZpip._internal.distributionsrZpip._internal.network.sessionrZpip._internal.indexrZ pip._internal.operations.preparerZpip._internal.req.req_installrZpip._internal.req.req_setrr%ZInstallRequirementProviderZ getLoggerrrr!r.objectr/r,r,r,r-s4                0__pycache__/wheel.cpython-38.opt-1.pyc000064400000066275152347654150013503 0ustar00U .eH@s4dZddlmZddlZddlZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lm Z m!Z!m"Z"dd l#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>ddl?m@Z@e:rddlAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMddlNmOZOddlPmQZQddlRmSZSddlTmUZUddlVmWZWeGeXdfZYeLeQgeZfZ[d Z\e]e^Z_d!d"Z`dXd$d%ZadYd&d'Zbd(d)Zcd*d+Zdd,d-Zee fd.e jgZhd/d0Zid1d2Zjd3d4Zkd5d6Zld7d8ZmGd9d:d:enZod;d<ZpGd=d>d>eZqdZdAdBZrdCdDZsdEdFZtdGdHZuGdIdJdJevZwe fdKe jxfdLdMZydNdOZzdPdQZ{dRdSZ|dTdUZ}GdVdWdWevZ~dS)[zH Support for installing and building the "wheel" binary package format. )absolute_importN)urlsafe_b64encode)Parser) pkg_resources) ScriptMaker)get_export_entry)canonicalize_name)StringIO) pep425tags)InstallationErrorInvalidWheelFilenameUnsupportedWheel)distutils_schemeget_major_minor_version)Link) indent_log)has_delete_marker_file)captured_stdout ensure_dir read_chunks)make_setuptools_shim_args) LOG_DIVIDERcall_subprocessformat_command_argsrunner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING) open_spinner) unpack_file) path_to_url) DictListOptionalSequenceMappingTupleIOTextAnyIterableCallableSet) Requirement)InstallRequirement)RequirementPreparer) WheelCache) Pep425Tag.)rcCstj||tjjdS)N/)ospathrelpathreplacesep)srcpr:7/usr/lib/python3.8/site-packages/pip/_internal/wheel.pynormpathOsr<c CsRt}d}t|d.}t||dD]}|t|7}||q$W5QRX||fS)z5Return (hash, length) for path using hashlib.sha256()rrb)size)hashlibZsha256openrlenupdate)r4 blocksizehlengthfblockr:r:r; hash_fileSs  rIcCs6t||\}}dt|dd}|t|fS)z?Return (encoded_digest, length) for path using hashlib.sha256()zsha256=latin1=)rIrdigestdecoderstripstr)r4rDrErFrLr:r:r;rehash_srPcCs6tjddkri}d}n ddi}d}t|||f|S)Nrbnewline)sys version_inforA)namemodenlbinr:r:r; open_for_csvjs r[cCs|d}||d<d|S)zBReplace the Python tag in a wheel file name with a new value. -)splitjoin)Z wheelnameZnew_tagpartsr:r:r;replace_python_tagus rac Cstj|rt|dR}|}|ds8W5QRdStjt }d|tj d}| }W5QRXt|d}| || |W5QRXdSdS) zLReplace #!python with #!/path/to/python Return True if file was changed.r>s#!pythonFs#!asciiwbTN) r3r4isfilerAreadline startswithrU executableencodegetfilesystemencodinglinesepreadwrite)r4Zscript firstlineZexenamerestr:r:r; fix_script~s     rozX^(?P(?P.+?)(-(?P.+?))?) \.dist-info$c Cs|dd}t|D]p}t|}|r|d|krttj||d6}|D]*}| }|dkrPW5QRdSqPW5QRXqdS)zP Return True if the extracted wheel in wheeldir should go into purelib. r\_rWWHEELzroot-is-purelib: trueTF) r6r3listdir dist_info_rematchgrouprAr4r_lowerrN)rWwheeldirZ name_foldeditemrtwheelliner:r:r;root_is_purelibs    r{c stj|siifSt|8}t}|D]}|||dq(|dW5QRXtj |}| di}| di}ddt fdd| D}t fd d| D}||fS) N rZconsole_scriptsZ gui_scriptscSst|dddS)zRget the string representation of EntryPoint, remove space and split on '=' rTrK)rOr6r^)sr:r:r; _split_epsz"get_entrypoints.._split_epc3s|]}|VqdSNr:.0vrr:r; sz"get_entrypoints..c3s|]}|VqdSrr:rrr:r;rs)r3r4existsrAr rlstripseekrZ EntryPointZ parse_mapgetdictvalues)filenamefpdatarzZ entry_pointsconsoleguir:rr;get_entrypointss      rc sJ|sdStt}|D]*}tj|}tj|}|||qddtj dd tj D tj tjtjfdd|D}|sdSg}|D]b\}}t|}t|dkrd |d } n$d d |dd d|d } | d| |qd} t|dkr0| | dn| | dd|S)zDetermine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. NcSs g|]}tj|tjqSr:)r3r4normcaserNr7)rir:r:r; sz5message_about_scripts_not_on_PATH..PATHrTcs&i|]\}}tj|kr||qSr:)r3r4r)r parent_dirscriptsZ not_warn_dirsr:r; sz5message_about_scripts_not_on_PATH..r1z script {} isrzscripts {} are, z and z.The {} installed in '{}' which is not on PATH.zeConsider adding {} to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.zthis directoryzthese directoriesr|) collections defaultdictsetr3r4dirnamebasenameaddenvironrr^pathsepappendrrUrgitemssortedrBformatr_) rZgrouped_by_dirdestfilerZ script_nameZwarn_for msg_linesZ dir_scriptsZsorted_scriptsZ start_textZ last_line_fmtr:rr;!message_about_scripts_not_on_PATHsH     rcCst|dddS)a; Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. cSstdd|DS)Ncss|]}t|VqdSr)rO)rxr:r:r;rsz3sorted_outrows....)tuple)rowr:r:r;z sorted_outrows..)key)r)outrowsr:r:r;sorted_outrowssrc Csg}|D]v}t|dkr(td|t|}|d}|||}||d<||krpt|\} } | |d<| |d<|t|q|D]*} t| \} } |t | || t | fq|D]} ||| ddfq|S)z_ :param installed: A map from archive RECORD path to installation RECORD path. rQz,RECORD line has more than three elements: {}rr1rT) rBloggerwarningrlistpoprPrrr<rO) Z old_csv_rows installedchanged generatedlib_dirZinstalled_rowsrZold_pathnew_pathrLrFrGr:r:r;get_csv_rows_for_installeds*     rc@s eZdZdS)MissingCallableSuffixN)__name__ __module__ __qualname__r:r:r:r;r=srcCs*t|}|dk r&|jdkr&tt|dSr)rsuffixrrO) specificationentryr:r:r;_raise_for_invalid_entrypointAsrcseZdZdfdd ZZS)PipScriptMakerNcst|tt|||Sr)rsuperrmake)selfrZoptions __class__r:r;rHszPipScriptMaker.make)N)rrrr __classcell__r:r:rr;rGsrFTc - sL|st|||||| d}t| r,|dn|dgg tjjtjj} itg} |rt4} t t dt j | dddW5QRXW5QRXt | d- fdd d.fd d }|| dtjd d}t|\fdd}D]j}d }d }ttj |D]F}d }|dkrPt}|}tj ||} ||}|| |d||dq6qtd |d}d|_dh|_d|_g}dd }|r4dtjkr|d|tjdddkr|dtjd |f|dt|fddD}|D] }|=q&dd }|rdtjkr`|d||dt|fddD}|D] }|=q|dd  Dd!d D}g}z.|!|}| || |!|d"diWn>t"k r.}z|j#d } t$d#%| W5d }~XYnX| rRt&|}!|!d k rRt '|!tjd d$}"tjd d%}#t(|#d&}$|$)d'W5QRXt*+|#|"| |"tjd d(}%tjd d)}&t,|%d*\}'t,|&d+F}(t-.|'})t/|)| d,}*t-0|(}+t1|*D]},|+2|,qW5QRXW5QRXt*+|&|%d S)/zInstall a wheel)userhomerootisolatedprefixZpurelibZplatlibignoreT)forcequietFcs.t|}t|}||<|r*|dS)z6Map archive RECORD paths to installation RECORD paths.N)r<r)srcfilerZmodifiedZoldpathnewpath)rrrrwr:r;record_installeds   z*move_wheel_files..record_installedNcst|t|D]\}}}|t|dtjj}tj||} |rf|tjjdd drfq|D]d} tj||| } |r|dkr| dr | qjqj|rj| drjt |  t j rj | qj|D]} |r|| rqtj|| } tj||| }t| tj|r$t|t| |t| }ttdrZt||j|jft| tjrt| }|jtjBtjBtjB}t||d}|r||}| ||qqdS)Nr1rz.datarTz .dist-infoutimeF)rr3walkrBlstripr4r7r_r^endswithrrrfrWrunlinkshutilZcopyfilestathasattrrst_atimest_mtimeaccessX_OKst_modeS_IXUSRS_IXGRPS_IXOTHchmod)sourcedestZis_basefixerfilterdirZsubdirsfilesZbasedirZdestdirr~Z destsubdirrGrrstZ permissionsr) data_dirsinfo_dirrreqr:r;clobbersP          z!move_wheel_files..clobberrzentry_points.txtcsh|dr|dd}n<|dr8|dd}n |drT|dd}n|}|kpf|kS)Nz.exez -script.pyiz.pya)rvr)rWZ matchname)rrr:r;is_entrypoint_wrappersz/move_wheel_files..is_entrypoint_wrapperr)rrrTZpipZENSUREPIP_OPTIONSzpip = Z altinstallz pip%s = %scSsg|]}td|r|qS)zpip(\d(\.\d)?)?$rertrkr:r:r;r0s z$move_wheel_files..Z easy_installzeasy_install = zeasy_install-%s = %scSsg|]}td|r|qS)zeasy_install(-\d\.\d)?$rrr:r:r;r@s css|]}d|VqdS)%s = %sNr:rZkvr:r:r;rGsz#move_wheel_files..cSsg|] }d|qS)rr:rr:r:r;rKsrzInvalid script entry point: {} for req: {} - A callable suffix is required. Cf https://packaging.python.org/en/latest/distributing.html#console-scripts for more information.Z INSTALLERz INSTALLER.piprcspip ZRECORDz RECORD.piprzw+)rrrr)F)NN)3rr{rNr3r4r7rrwarningscatch_warningsfilterwarnings compileall compile_dirrdebuggetvaluer_rrrrorrZvariantsZset_moderrrrrUrVrextendrZ make_multiplerargsr rrrrArlrmover[csvreaderrwriterrZwriterow)-rWrrwrrrZ pycompileZschemerrZwarn_script_locationrrstdoutrZep_filerZdatadirrrZsubdirrZmakerZscripts_to_generateZ pip_scriptZpip_eprZeasy_install_scriptZeasy_install_epZgui_scripts_to_generateZgenerated_console_scriptsermsgZ installerZtemp_installerZinstaller_filerecordZ temp_recordZ record_inZ record_outrrr rr:) rrrrrrrrrrwr;move_wheel_filesMs    $F   #                     "rcCsrzVddtd|Dd}|d}t|}|d}ttt| d}|WSt k rlYdSXdS)z Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. cSsg|]}|qSr:r:)rdr:r:r;rsz!wheel_version..Nrrqz Wheel-Version.) rZ find_on_pathZ get_metadatarZparsestrrrmapintr^ Exception) source_dirZdistZ wheel_dataversionr:r:r; wheel_versions   rcCsb|std||dtdkr>td|dtt|fn |tkr^tddtt|dS)a Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given z(%s is in an unsupported or invalid wheelrzB%s's Wheel-Version (%s) is not compatible with this version of piprz*Installing from a newer Wheel-Version (%s)N)r VERSION_COMPATIBLEr_rrOrr)rrWr:r:r;check_compatibilitysrcCs d|S)z Format three tags in the form "--". :param file_tag: A 3-tuple of tags (python_tag, abi_tag, platform_tag). r\)r_)Zfile_tagr:r:r; format_tagsrc@s>eZdZdZedejZddZddZ ddZ d d Z d S) Wheelz A wheel filez^(?P(?P.+?)-(?P.*?)) ((-(?P\d[^-]*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$csj|}|std||_|ddd_|ddd_|d_|d d_ |d  d_ |d  d_ fd d j D_ d S)zX :raises InvalidWheelFilename: when the filename is invalid for a wheel z!%s is not a valid wheel filename.rWrpr\ZverbuildZpyverrZabiZplatcs.h|]&}jD]}jD]}|||fqqqSr:)abisplats)rryzrr:r; s z!Wheel.__init__..N) wheel_file_rertr rrur6rWrZ build_tagr^Z pyversionsrr file_tags)rrZ wheel_infor:r r;__init__s   zWheel.__init__cCstdd|jDS)zF Return the wheel's tags as a sorted list of strings. css|]}t|VqdSr)rrtagr:r:r;rsz0Wheel.get_formatted_file_tags..)rr#r r:r:r;get_formatted_file_tagsszWheel.get_formatted_file_tagscstfdd|jDS)a Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. c3s |]}|kr|VqdSr)indexr%tagsr:r;rsz*Wheel.support_index_min..)minr#rr*r:r)r;support_index_minszWheel.support_index_mincCs|j| S)z Return whether the wheel is compatible with one of the given tags. :param tags: the PEP 425 tags to check the wheel against. )r# isdisjointr,r:r:r; supportedszWheel.supportedN) rrr__doc__rcompileVERBOSEr"r$r'r-r/r:r:r:r;rsrz([a-z0-9_.]+)-([a-z0-9_.!+-]+)cCst||S)zjDetermine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 )boolsearch)r~Z _egg_info_rer:r:r;_contains_egg_infosr5cCs|jr dS|jr&|s"td|jdS|s.dS|js:|js>dS||sXtd|jdS|jrj|jjrjdS|j}| \}}|rt |rdSdS)a[ Return whether to build an InstallRequirement object using the ephemeral cache. :param cache_available: whether a cache directory is available for the should_unpack=True case. :return: True or False to build the requirement with ephem_cache=True or False, respectively; or None not to build the requirement. Nz(Skipping %s, due to already being wheel.FzCSkipping wheel build for %s, due to binaries being disabled for it.T) Z constraintZis_wheelrinforWZeditablerlinkZis_vcssplitextr5)r should_unpackcache_availablecheck_binary_allowedr7baseZextr:r:r;should_use_ephemeral_cache s4   r=cCs^t|}d|}|s |d7}n:ttjkr8|d7}n"|dsJ|d7}|d|t7}|S)z1 Format command information for logging. zCommand arguments: {} zCommand output: Nonez'Command output: [use --verbose to show]r|zCommand output: {}{})rrrZgetEffectiveLevelloggingDEBUGrr) command_argscommand_outputZ command_desctextr:r:r;format_command_resultGs    rCcCsxt|}|s4d|j}|t||7}t|dSt|dkrfd|j|}|t||7}t|tj ||dS)zH Return the path to the wheel in the temporary build directory. z1Legacy build of wheel for {!r} created no files. Nr1zZLegacy build of wheel for {!r} created more than one file. Filenames (choosing first): {} r) rrrWrCrrrBr3r4r_)namestemp_dirrr@rAr r:r:r;get_legacy_build_wheel_path^s$    rFcCsdS)NTr:)rpr:r:r; _always_true~srGc@s\eZdZdZdddZdddZddd Zd d Zdd d ZdddZ ddZ dddZ dS) WheelBuilderz#Build wheels from a RequirementSet.NFcCsD|dkr t}||_||_|j|_|p&g|_|p0g|_||_||_dSr) rGpreparer wheel_cacheZwheel_download_dir _wheel_dir build_optionsglobal_optionsr;no_clean)rrIrJrLrMr;rNr:r:r;r$s   zWheelBuilder.__init__c Cs.|j|j|||dW5QRSQRXdS)ziBuild one wheel. :return: The filename of the built wheel, or None if the build failed.  python_tagN)Z build_env_build_one_inside_env)rr output_dirrPr:r:r; _build_oneszWheelBuilder._build_onec Cstdd}|jr|j}n|j}|||j|d}|dk rtj|}tj||}zNt|\} } t ||t d|j || | t d||WW5QRStk rYnX||W5QRdSQRXdS)Nry)ZkindrOz3Created wheel for %s: filename=%s size=%d sha256=%szStored in directory: %s)rZ use_pep517_build_one_pep517_build_one_legacyr4r3rr_rIrrrr6rWZ hexdigestr _clean_one) rrrRrPrEZbuilder wheel_path wheel_nameZ dest_pathZ wheel_hashrFr:r:r;rQs.      z"WheelBuilder._build_one_inside_envcCst|j|jddS)NT)rMZunbuffered_output)rZ setup_py_pathrM)rrr:r:r;_base_setup_argss zWheelBuilder._base_setup_argsc Cs|jrtd|jfdSz~td|td|j}|j}|||j ||j d}W5QRX|rt ||}t t j||t j|||}Wn$tk rtd|jYdSXt j||S)zBuild one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. zGCannot build wheel for %s using PEP 517 when --build-options is presentNDestination directory: %szBuilding wheel for {} (PEP 517))metadata_directoryFailed building wheel for %s)rLrerrorrWrrrZpep517_backendZsubprocess_runnerZ build_wheelr[rar3renamer4r_r)rrtempdrPZrunnerZbackendrXnew_namer:r:r;rTs6      zWheelBuilder._build_one_pep517c Cs||}d|jf}t|}td||dd|g|j}|dk rT|d|g7}zt||j|d}Wn8tk r| dt d |jYW5QRdSXt |} t | ||||d } | W5QRSQRXdS) zBuild one InstallRequirement using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. z Building wheel for %s (setup.py)rZZ bdist_wheelz-dNz --python-tag)cwdspinnerr]r\)rDrErr@rA)rYrWrrrrLrZunpacked_source_directoryrZfinishr]r3rrrF) rrr_rP base_argsZ spin_messagerbZ wheel_argsoutputrDrWr:r:r;rUs8         zWheelBuilder._build_one_legacycCsb||}td|j|ddg}zt||jdWdStk r\td|jYdSXdS)NzRunning setup.py clean for %sZcleanz--all)raTz Failed cleaning build dir for %sF)rYrr6rWrrrr])rrrcZ clean_argsr:r:r;rVs  zWheelBuilder._clean_onec Csg}t|jj}|D]\}t||||jd}|dkr4q|r\|rL|j|j}qb|j|j}n|j}| ||fq|szgSt dd dd|Dd}|rt j}tgg} } |D]\}}z t|WnFtk r} z&t d|j| | |WYqW5d} ~ XYnX|j|||d} | r| ||r|jrXt|jsXtd |||jj|_tt| |_t|jj|jq| |qW5QRX| rt d d d d| D| rt d d dd| D| S)aBuild wheels. :param should_unpack: If True, after building the wheel, unpack it and replace the sdist with the unpacked version in preparation for installation. :return: True if all the wheels built correctly. )r9r:r;Nz*Building wheels for collected packages: %srcSsg|]\}}|jqSr:rW)rrrpr:r:r;r\sz&WheelBuilder.build..z Building wheel for %s failed: %srOzbad source dir - missing markerzSuccessfully built %sr}cSsg|] }|jqSr:rerrr:r:r;rszFailed to build %scSsg|] }|jqSr:rerfr:r:r;rs) r3rJ cache_dirr=r;Zget_ephem_path_for_linkr7Zget_path_for_linkrKrrr6r_r Zimplementation_tagrrOSErrorrrWrSrrAssertionErrorZremove_temporary_sourceZensure_build_locationrIZ build_dirrrrZ file_path) rZ requirementsr9Zbuildsetr:rZ ephem_cacherRrPZ build_successZ build_failurer Z wheel_filer:r:r;r#s      zWheelBuilder.build)NNNF)N)N)N)N)F) rrrr0r$rSrQrYrTrUrVrr:r:r:r;rHs   ' %rH)r=)r=)FNNTNFNT)r0Z __future__rrrrr@r>Zos.pathr3rrrrUrbase64rZ email.parserrZ pip._vendorrZpip._vendor.distlib.scriptsrZpip._vendor.distlib.utilrZpip._vendor.packaging.utilsrZpip._vendor.sixr Z pip._internalr Zpip._internal.exceptionsr r r Zpip._internal.locationsrrZpip._internal.models.linkrZpip._internal.utils.loggingrZ pip._internal.utils.marker_filesrZpip._internal.utils.miscrrrZ$pip._internal.utils.setuptools_buildrZpip._internal.utils.subprocessrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.uirZpip._internal.utils.unpackingrZpip._internal.utils.urlsrtypingr r!r"r#r$r%r&r'r(r)r*r+Z"pip._vendor.packaging.requirementsr,Zpip._internal.req.req_installr-Z pip._internal.operations.preparer.Zpip._internal.cacher/Zpip._internal.pep425tagsr0rOZInstalledCSVRowr3ZBinaryAllowedPredicaterZ getLoggerrrr<rIrPr[raror1r2rsr{rrrrrrrrrrrrobjectrIr5r=rCrFrGrHr:r:r:r;s                  8           =$  4 J : __pycache__/cache.cpython-38.pyc000064400000016045152347654150012471 0ustar00U .e @sdZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZmZerdd lmZmZmZmZdd lmZdd lmZeeZGd dde Z!Gddde!Z"Gddde"Z#Gddde!Z$dS)zCache Management N)canonicalize_name)Link) expanduser) TempDirectory)MYPY_CHECK_RUNNING) path_to_url)InvalidWheelFilenameWheel)OptionalSetListAny) FormatControl) Pep425TagcsPeZdZdZfddZddZddZdd Zd d Zd d Z ddZ Z S)CacheaAn abstract class - provides cache directories for data from links :param cache_dir: The root of the cache. :param format_control: An object of FormatControl class to limit binaries being read from the cache. :param allowed_formats: which formats of files the cache should store. ('binary' and 'source' are the only allowed values) csLtt||rt|nd|_||_||_ddh}|j||ksHtdS)Nsourcebinary) superr__init__r cache_dirformat_controlallowed_formatsunionAssertionError)selfrrrZ_valid_formats __class__7/usr/lib/python3.8/site-packages/pip/_internal/cache.pyr(s zCache.__init__cCs|jg}|jdk r4|jdk r4|d|j|jgd|}t|}|dd|dd|dd|ddg}|S)zEGet parts of part that must be os.path.joined with cache_dir N=#) Zurl_without_fragmentZ hash_namehashappendjoinhashlibZsha224encodeZ hexdigest)rlinkZ key_partsZkey_urlZhashedpartsrrr_get_cache_path_parts2s ,zCache._get_cache_path_partsc Cs|j p| p| }|rgSt|}|j|}|j|s@gS||}z t|WSt k r}z$|j t j t j hkrgWYSW5d}~XYnXdSN) rrrZget_allowed_formatsr intersectionget_path_for_linkoslistdirOSErrorerrnoZENOENTZENOTDIR)rr) package_nameZ can_not_cacheZcanonical_nameZformatsrooterrrrr_get_candidatesLs(    zCache._get_candidatescCs tdS)z>Return a directory to store cached items in for link. NNotImplementedErrorrr)rrrr.eszCache.get_path_for_linkcCs tdS)zaReturns a link to a cached item if it exists, otherwise returns the passed link. Nr7)rr)r3supported_tagsrrrgetks z Cache.getcCs$||}tj||}tt|Sr,)r.r/pathr&rr)rr) candidater4r<rrr_link_for_candidatews zCache._link_for_candidatecCsdSr,rrrrrcleanup~sz Cache.cleanup) __name__ __module__ __qualname____doc__rr+r6r.r;r>r@ __classcell__rrrrrs  rcs0eZdZdZfddZddZddZZS)SimpleWheelCachez+A cache of wheels for future installs. cstt|||dhdSNr)rrFrrrrrrrrs  zSimpleWheelCache.__init__cCs ||}tjj|jdf|S)aReturn a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. Zwheels)r+r/r<r&r)rr)r*rrrr.s z"SimpleWheelCache.get_path_for_linkc Csxg}|||D]J}z t|}Wntk r8YqYnX||sFq||||fq|sd|S||t|dS)N)r6r rZ supportedr%Zsupport_index_minr>min)rr)r3r:Z candidatesZ wheel_nameZwheelrrrr;s    zSimpleWheelCache.get)rArBrCrDrr.r;rErrrrrFs rFcs(eZdZdZfddZddZZS)EphemWheelCachezGA SimpleWheelCache that creates it's own temporary cache directory cs&tdd|_tt||jj|dS)Nzephem-wheel-cache)Zkind)r _temp_dirrrKrr<)rrrrrrs   zEphemWheelCache.__init__cCs|jdSr,)rLr@r?rrrr@szEphemWheelCache.cleanup)rArBrCrDrr@rErrrrrKs rKcs@eZdZdZfddZddZddZdd Zd d ZZ S) WheelCachezWraps EphemWheelCache and SimpleWheelCache into a single Cache This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. cs0tt|||dht|||_t||_dSrG)rrMrrF _wheel_cacherK _ephem_cacherHrrrrs  zWheelCache.__init__cCs |j|Sr,)rNr.r9rrrr.szWheelCache.get_path_for_linkcCs |j|Sr,)rOr.r9rrrget_ephem_path_for_linksz"WheelCache.get_ephem_path_for_linkcCs0|jj|||d}||k r|S|jj|||dS)N)r)r3r:)rNr;rO)rr)r3r:Zretvalrrrr;szWheelCache.getcCs|j|jdSr,)rNr@rOr?rrrr@s zWheelCache.cleanup) rArBrCrDrr.rPr;r@rErrrrrMs  rM)%rDr2r'Zloggingr/Zpip._vendor.packaging.utilsrZpip._internal.models.linkrZpip._internal.utils.compatrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.urlsrZpip._internal.wheelrr typingr r r r Zpip._internal.indexrZpip._internal.pep425tagsrZ getLoggerrAZloggerobjectrrFrKrMrrrrs(         f:__pycache__/download.cpython-38.opt-1.pyc000064400000026231152347654150014172 0ustar00U .eEQ@sddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z ddlmZddlmZddlmZmZddlmZdd lmZdd lmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3e+rddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;mZ>ddl?m@Z@ddlAmBZBered0d ZSd1d2ZTd3d4ZUd?d5dZVd@d6d!ZWd7d#ZXd8d"ZYd9d:ZZd;d<Z[dS)A)absolute_importN)requests)CONTENT_CHUNK_SIZEResponse)PY2)parse) HashMismatchInstallationError)PyPI) PipSession) auto_decode) copy2_fixed) ask_path_exists backup_dirconsume display_path format_sizehide_urlpath_to_displayrmtreesplitext) TempDirectory)MYPY_CHECK_RUNNING)DownloadProgressProvider) unpack_file)get_url_scheme)vcs)IOCallableListOptionalTextTuple) TypedDict)Link)Hashes)VersionControlCopytreeKwargsignoresymlinksF)Ztotal) copy_functionr)Zignore_dangling_symlinksr*get_file_contentunpack_vcs_linkunpack_file_urlunpack_http_url unpack_urlparse_content_dispositionsanitize_content_filenamec Cs6|dkrtdt|}|dkr>||}||j|jfS|dkr|rd|drdtd||f|ddd}| d d }t |}|r| dd|d dd}t |}|d rd |d }|}z&t|d }t|}W5QRXWn4tk r,} ztd t| W5d} ~ XYnX||fS)a*Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. :param url: File path or url. :param comes_from: Origin description of requirements. :param session: Instance of pip.download.PipSession. NzAget_file_content() missing 1 required keyword argument: 'session')httpZhttpsfiler3z6Requirements file %s references URL %s, which is local:\/|rbz$Could not open requirements file: %s) TypeErrorrgetraise_for_statusurltext startswithr splitreplace_url_slash_drive_rematchgroup urllib_parseZunquotelstripopenr readIOErrorstr) r>Z comes_fromsessionschemeresppathrDfZcontentexcrR:/usr/lib/python3.8/site-packages/pip/_internal/download.pyr,UsB         z /*([a-z])\|cCs t|}|j|t|jddS)N)r>)_get_used_vcs_backendunpackrr>)linklocation vcs_backendrRrRrSr-scCs$tjD]}|j|jkr|SqdS)z1 Return a VersionControl object or None. N)rZbackendsrMZschemes)rVrXrRrRrSrTs   rTcOs|SNrR)iterableargskwargsrRrRrS_progress_indicatorsr]c s6ztjd}Wntttfk r0d}YnXtdd}ttj krRd}n&|r\d}n|dkrjd}n|std}nd}|j }fdd} fd d } t } |j t j kr|} n|j} |rt||d } |rtd | t|n td | n|rtd| n td | | | | tt} |r*|| nt| dS)Nzcontent-lengthrZ from_cacheFi@Tc3sTz jj|ddD] }|VqWn.tk rNj|}|sBqJ|Vq0YnXdS)NF)Zdecode_content)rawstreamAttributeErrorrI)Z chunk_sizechunk)rNrRrS resp_reads   z _download_url..resp_readc3s|D]}||VqdSrY)write)Zchunksra) content_filerRrSwritten_chunkss z%_download_url..written_chunks)maxzDownloading %s (%s)zDownloading %szUsing cached %s)intheaders ValueErrorKeyErrorr;getattrloggerZgetEffectiveLevelloggingINFOshow_urlr]Znetlocr Zurl_without_fragmentrinforrZcheck_against_chunksr)rNrVrdhashes progress_barZ total_lengthZ cached_respZ show_progressrorbreZprogress_indicatorr>Zdownloaded_chunksrR)rdrNrS _download_urlsP   %    rscCsd}tj||j}tj|rtdt|d}|dkr@d}nj|dkrdtdt|t |nF|dkrt |}td t|t|t ||n|d krt d |rt ||td t|dS) NTz8The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort)iwbartFruz Deleting %srvzBacking up %s to %srwzSaved %s)osrOjoinfilenameexistsrrrlwarningremovershutilZmovesysexitcopyrp)r{rWrVrZdownload_locationresponseZ dest_filerRrRrS _copy_files6    ronc Cs|dkrtdtddv}d}|r0t|||}|rH|}t|d} nt|||j||\}} t||| |r~|s~t||||st |W5QRXdS)Nz@unpack_http_url() missing 1 required keyword argument: 'session'rU)Zkindr) r;r_check_download_dir mimetypes guess_type_download_http_urlrOrrryunlink) rVrW download_dirrLrqrrtemp_diralready_downloaded_path from_path content_typerRrRrSr/s2    c CsTzt||Wn@tjk rN}z tdt|t|t|W5d}~XYnXdS)zCopying special files is not supported, but as a convenience to users we skip errors copying them. This supports tools that may create e.g. socket files in the project source directory. z>Ignoring special file error '%s' encountered copying %s to %s.N)r rZSpecialFileErrorrlr}rKr)srcdesterRrRrS_copy2_ignoring_special_filesJsrcs`tj|}tj|tj|fdd}t|dd}tsLt|d<tj |f|dS)Ncs6g}|kr|ddg7}tj|kr2|g7}|S)Nz.toxz.nox)ryrOabspath)dnamesZskippedsourceZtarget_basenameZtarget_dirnamerRrSr)es   z!_copy_source_tree..ignoreTr(r+) ryrOrbasenamedirnamedictrrrZcopytree)rtargetZtarget_abspathr)r\rRrrS_copy_source_tree_s    rcCs|j}|r>tj|r"t|t|||r:tddS|rL| |d}|r`t |||}|rj|}n|}t |d}t ||||r|st|||dS)zUnpack link into location. If download_dir is provided and link points to a file, make a copy of the link file inside download_dir. z*Link is a directory, ignoring download_dirNr) file_pathZis_existing_dirryrOisdirrrrlrpcheck_against_pathrrrrr)rVrWrrqZ link_pathrrrrRrRrSr.~s.      cCsP|jrt||n:|jr*t||||dn"|dkr8t}t||||||ddS)avUnpack link. If link is a VCS link: if only_download, export into download_dir and ignore location else unpack into location for other types of link: - unpack into location - if download_dir, copy the file into download_dir - if only_download, mark location for deletion :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. )rqN)rqrr)Zis_vcsr-is_filer.r r/)rVrWrrLrqrrrRrRrSr0s cCs tj|S)zJ Sanitize the "filename" value from a Content-Disposition header. )ryrOr)r{rRrRrSr2scCs,t|\}}|d}|r$t|}|p*|S)z Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. r{)cgiZ parse_headerr<r2)content_dispositionZdefault_filenameZ_typeZparamsr{rRrRrSr1s  c Cs*|jddd}z |j|ddidd}|Wn8tjk rj}ztd|jj |W5d }~XYnX|j d d }|j } |j d } | rt | | } t | d} | st|} | r| | 7} | s|j|jkrtj |jd} | r| | 7} tj|| } t| d } t||| ||W5QRX| |fS)z6Download link url into temp_dir using provided session#r6rzAccept-EncodingZidentityT)rhr_zHTTP error %s while getting %sNz content-typezcontent-dispositionwb)r>rAr<r=rZ HTTPErrorrlZcriticalrZ status_coderhr{r1rrZguess_extensionryrOrzrHrs)rVrLrrqrrZ target_urlrNrQrr{rZextrrdrRrRrSrsB       rcCsptj||j}tj|s dStd||rlz||Wn,tk rjt d|t |YdSX|S)z Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None NzFile was already downloaded %sz;Previously-downloaded file %s has bad hash. Re-downloading.) ryrOrzr{r|rlrprrr}r)rVrrqZ download_pathrRrRrSr7s   r)NN)NNNr)NN)NNNr)\Z __future__rrrmrryrerrZ pip._vendorrZpip._vendor.requests.modelsrrZpip._vendor.sixrZpip._vendor.six.moves.urllibrrFZpip._internal.exceptionsrr Zpip._internal.models.indexr Zpip._internal.network.sessionr Zpip._internal.utils.encodingr Zpip._internal.utils.filesystemr Zpip._internal.utils.miscrrrrrrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.uirZpip._internal.utils.unpackingrZpip._internal.utils.urlsrZpip._internal.vcsrtypingrrrr r!r"Zmypy_extensionsr#Zpip._internal.models.linkr$Zpip._internal.utils.hashesr%Z pip._internal.vcs.versioncontrolr&rKboolr'__all__Z getLogger__name__rlr,compileIrCr-rTr]rsrr/rrr.r0r2r1rrrRrRrRrSs        ,               0 d -" 8 .?__pycache__/locations.cpython-38.pyc000064400000006160152347654150013416 0ustar00U .e&@sdZddlmZddlZddlZddlZddlZddlZddlZddl mZ ddl m Z ddl mZddlmZddlmZdd lmZerdd lmZmZmZmZmZed Zd d ZddZedZ e!"dkre #Z z e$Z%Wne&k r ej'Z%YnXer`ej()ej*dZ+ej()e%dZ,ej(-e+sej()ej*dZ+ej()e%dZ,nJej()ej*dZ+ej()e%dZ,ejdddkrej*dddkrdZ+dddZ.dS)z7Locations where we look for configs, install stuff, etc)absolute_importN) sysconfig) SCHEME_KEYS)appdirs)WINDOWS)MYPY_CHECK_RUNNING)running_under_virtualenv)AnyUnionDictListOptionalZpipcCs djtjS)ze Return the major-minor version of the current Python as a string, e.g. "3.7" or "3.10". z{}.{})formatsys version_inforr;/usr/lib/python3.8/site-packages/pip/_internal/locations.pyget_major_minor_versionsrcCsZtrtjtjd}n6ztjtd}Wntk rLtdYnXtj |S)Nsrcz=The folder you are executing pip from can no longer be found.) rospathjoinrprefixgetcwdOSErrorexitabspath)Z src_prefixrrrget_src_prefix(s rpurelibZpypyZScriptsbindarwinz/System/Library/z/usr/local/binFcCsddlm}i}|r ddgi}ni}d|i} | ||| } | | jddd} | d k s`t|rx|rxtd |||r|rtd |||p| j| _|s|rd | _|p| j| _|p| j | _ |p| j | _ | t D]} t | d | || <qd| dkr|t| j| jdtrtjtjdddt||d<|d k rtjtj|dd} tj|| dd |d<|S)z+ Return a distutils install scheme r) DistributionZ script_argsz --no-user-cfgnameZinstallT)ZcreateNzuser={} prefix={}zhome={} prefix={}Zinstall_ install_lib)rZplatlibZincludesitezpython{}Zheaders)Zdistutils.distr#updateZparse_config_filesZget_command_objAssertionErrorruserrhomerootZfinalize_optionsrgetattrZget_option_dictdictr&rrrrrr splitdriver)Z dist_namer+r,r-isolatedrr#ZschemeZextra_dist_argsZ dist_argsdikeyZ path_no_driverrrdistutils_scheme[sV            r5)FNNFN)/__doc__Z __future__rrZos.pathplatformr'rrZ distutilsZdistutils_sysconfigZdistutils.command.installrZpip._internal.utilsrZpip._internal.utils.compatrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrtypingr r r r r Zuser_cache_dirZUSER_CACHE_DIRrrZget_pathZ site_packagesZpython_implementationlowerZget_python_libgetusersitepackages user_siteAttributeError USER_SITErrrZbin_pyZbin_userexistsr5rrrrsN            (__pycache__/cache.cpython-38.opt-1.pyc000064400000015772152347654150013436 0ustar00U .e @sdZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZmZerdd lmZmZmZmZdd lmZdd lmZeeZGd dde Z!Gddde!Z"Gddde"Z#Gddde!Z$dS)zCache Management N)canonicalize_name)Link) expanduser) TempDirectory)MYPY_CHECK_RUNNING) path_to_url)InvalidWheelFilenameWheel)OptionalSetListAny) FormatControl) Pep425TagcsPeZdZdZfddZddZddZdd Zd d Zd d Z ddZ Z S)CacheaAn abstract class - provides cache directories for data from links :param cache_dir: The root of the cache. :param format_control: An object of FormatControl class to limit binaries being read from the cache. :param allowed_formats: which formats of files the cache should store. ('binary' and 'source' are the only allowed values) cs8tt||rt|nd|_||_||_ddh}dS)Nsourcebinary)superr__init__r cache_dirformat_controlallowed_formats)selfrrrZ_valid_formats __class__7/usr/lib/python3.8/site-packages/pip/_internal/cache.pyr(s zCache.__init__cCs|jg}|jdk r4|jdk r4|d|j|jgd|}t|}|dd|dd|dd|ddg}|S)zEGet parts of part that must be os.path.joined with cache_dir N=#) Zurl_without_fragmentZ hash_namehashappendjoinhashlibZsha224encodeZ hexdigest)rlinkZ key_partsZkey_urlZhashedpartsrrr_get_cache_path_parts2s ,zCache._get_cache_path_partsc Cs|j p| p| }|rgSt|}|j|}|j|s@gS||}z t|WSt k r}z$|j t j t j hkrgWYSW5d}~XYnXdSN) rrrZget_allowed_formatsr intersectionget_path_for_linkoslistdirOSErrorerrnoZENOENTZENOTDIR)rr' package_nameZ can_not_cacheZcanonical_nameZformatsrooterrrrr_get_candidatesLs(    zCache._get_candidatescCs tdS)z>Return a directory to store cached items in for link. NNotImplementedErrorrr'rrrr,eszCache.get_path_for_linkcCs tdS)zaReturns a link to a cached item if it exists, otherwise returns the passed link. Nr5)rr'r1supported_tagsrrrgetks z Cache.getcCs$||}tj||}tt|Sr*)r,r-pathr$rr)rr' candidater2r:rrr_link_for_candidatews zCache._link_for_candidatecCsdSr*rrrrrcleanup~sz Cache.cleanup) __name__ __module__ __qualname____doc__rr)r4r,r9r<r> __classcell__rrrrrs  rcs0eZdZdZfddZddZddZZS)SimpleWheelCachez+A cache of wheels for future installs. cstt|||dhdSNr)rrDrrrrrrrrs  zSimpleWheelCache.__init__cCs ||}tjj|jdf|S)aReturn a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. Zwheels)r)r-r:r$r)rr'r(rrrr,s z"SimpleWheelCache.get_path_for_linkc Csxg}|||D]J}z t|}Wntk r8YqYnX||sFq||||fq|sd|S||t|dS)N)r4r rZ supportedr#Zsupport_index_minr<min)rr'r1r8Z candidatesZ wheel_nameZwheelrrrr9s    zSimpleWheelCache.get)r?r@rArBrr,r9rCrrrrrDs rDcs(eZdZdZfddZddZZS)EphemWheelCachezGA SimpleWheelCache that creates it's own temporary cache directory cs&tdd|_tt||jj|dS)Nzephem-wheel-cache)Zkind)r _temp_dirrrIrr:)rrrrrrs   zEphemWheelCache.__init__cCs|jdSr*)rJr>r=rrrr>szEphemWheelCache.cleanup)r?r@rArBrr>rCrrrrrIs rIcs@eZdZdZfddZddZddZdd Zd d ZZ S) WheelCachezWraps EphemWheelCache and SimpleWheelCache into a single Cache This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. cs0tt|||dht|||_t||_dSrE)rrKrrD _wheel_cacherI _ephem_cacherFrrrrs  zWheelCache.__init__cCs |j|Sr*)rLr,r7rrrr,szWheelCache.get_path_for_linkcCs |j|Sr*)rMr,r7rrrget_ephem_path_for_linksz"WheelCache.get_ephem_path_for_linkcCs0|jj|||d}||k r|S|jj|||dS)N)r'r1r8)rLr9rM)rr'r1r8Zretvalrrrr9szWheelCache.getcCs|j|jdSr*)rLr>rMr=rrrr>s zWheelCache.cleanup) r?r@rArBrr,rNr9r>rCrrrrrKs  rK)%rBr0r%Zloggingr-Zpip._vendor.packaging.utilsrZpip._internal.models.linkrZpip._internal.utils.compatrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.urlsrZpip._internal.wheelrr typingr r r r Zpip._internal.indexrZpip._internal.pep425tagsrZ getLoggerr?ZloggerobjectrrDrIrKrrrrs(         f:__pycache__/collector.cpython-38.pyc000064400000033422152347654150013412 0ustar00U .eWF@s dZddlZddlZddlZddlZddlZddlmZddlm Z m Z ddl m Z ddl mZmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZm Z ddl!m"Z"m#Z#erDddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5e/j6j7j8Z9e)e:e:fZ;eddZ?ddZ@GdddeAZBddZCGdddeAZDddZEdd ZFd!d"ZGd#d$ZHd%d&ZId'd(ZJd)d*ZKGd+d,d,eLZMdd6d7ZRGd8d9d9eLZSGd:d;d;eLZTdS)?zM The main purpose of this module is to expose LinkCollector.collect_links(). N) OrderedDict)html5librequests)unescape) HTTPError RetryErrorSSLError)parse)requestLink)ARCHIVE_EXTENSIONS)redact_auth_from_url)MYPY_CHECK_RUNNING) path_to_url url_to_path)is_urlvcs) CallableDictIterableListMutableMappingOptionalSequenceTupleUnion)Response) SearchScope) PipSessioncCs6tjD]*}||r|t|dkr|SqdS)zgLook for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. z+:N)rZschemeslower startswithlen)urlschemer%;/usr/lib/python3.8/site-packages/pip/_internal/collector.py_match_vcs_scheme/s  r'cCs(t|j}tD]}||rdSqdS)z2Return whether the URL looks like an archive. TF)r filenamer endswith)r#r(Zbad_extr%r%r&_is_url_like_archive;s   r*cseZdZfddZZS)_NotHTMLcs"tt|||||_||_dSN)superr+__init__ content_type request_desc)selfr/r0 __class__r%r&r.Gsz_NotHTML.__init__)__name__ __module__ __qualname__r. __classcell__r%r%r2r&r+Fsr+cCs.|jdd}|ds*t||jjdS)zCheck the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. Content-Type text/htmlN)headersgetr r!r+r method)responser/r%r%r&_ensure_html_headerNsr?c@s eZdZdS)_NotHTTPN)r4r5r6r%r%r%r&r@Ysr@cCsDt|\}}}}}|dkr"t|j|dd}|t|dS)zSend a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. >httphttpsT)Zallow_redirectsN) urllib_parseZurlsplitr@headraise_for_statusr?)r#sessionr$netlocpathZqueryZfragmentrespr%r%r&_ensure_html_response]s rJcCsLt|rt||dtdt||j|dddd}|t||S)aAccess an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. rFzGetting page %sr:z max-age=0)ZAcceptz Cache-Control)r;)r*rJloggerdebugrr<rEr?)r#rFrIr%r%r&_get_html_responsens rNcCs2|r.d|kr.t|d\}}d|kr.|dSdS)zBDetermine if we have any encoding information in our headers. r8charsetN)cgiZ parse_header)r;r/Zparamsr%r%r&_get_encoding_from_headerss  rQcCs.|dD]}|d}|dk r |Sq |S)aDetermine the HTML document's base URL. This looks for a ```` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. z.//basehrefN)findallr<)documentpage_urlbaserRr%r%r&_determine_base_urls   rWcCsPt|}|jdkr(tt|j}ntjt|jdd}t |j |dS)zMakes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).r9z/@)Zsafe)rH) rCurlparserGurllib_requestZ pathname2url url2pathnamerHZquoteZunquoteZ urlunparse_replace)r#resultrHr%r%r& _clean_links   r]cCsf|d}|sdStt||}|d}|r8t|nd}|d}|rRt|}t||||d}|S)zJ Convert an anchor element in a simple repository page to a Link. rRNzdata-requires-pythonz data-yanked)Z comes_fromZrequires_python yanked_reason)r<r]rCurljoinrr )anchorrUbase_urlrRr#Z pyrequirer^linkr%r%r&_create_link_from_elements   rcccsVtj|j|jdd}|j}t||}|dD]"}t|||d}|dkrJq.|Vq.dS)zP Parse an HTML document, and yield its anchor elements as Link objects. F)Ztransport_encodingZnamespaceHTMLElementsz.//a)rUraN)rr contentencodingr#rWrSrc)pagerTr#rar`rbr%r%r& parse_linkss  rgc@s eZdZdZddZddZdS)HTMLPagez'Represents one page, along with its URLcCs||_||_||_dS)z :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. N)rdrer#)r1rdrer#r%r%r&r.s zHTMLPage.__init__cCs t|jSr,)rr#r1r%r%r&__str__$szHTMLPage.__str__N)r4r5r6__doc__r.rjr%r%r%r&rhsrhcCs|dkrtj}|d||dS)Nz%Could not fetch URL %s: %s - skipping)rLrM)rbreasonmethr%r%r&_handle_get_page_fail(srncCst|j}t|j||jdS)N)rer#)rQr;rhrdr#)r>rer%r%r&_make_html_page3s roc Cs|dkrtd|jddd}t|}|r@td||dSt|\}}}}}}|dkrtj t |r| ds|d7}t|d}td |zt||d }WnDtk rtd |Yn,tk r}ztd ||j|jW5d}~XYntk r0}zt||W5d}~XYntk r\}zt||W5d}~XYntk r}z$d } | t|7} t|| tjdW5d}~XYn\tjk r}zt|d|W5d}~XYn*tjk rt|dYn Xt|SdS)Nz?_get_html_page() missing 1 required keyword argument: 'session'#rzCannot look at %s URL %sfile/z index.htmlz# file: URL is directory, getting %srKzQSkipping page %s because it looks like an archive, and cannot be checked by HEAD.z.sort_pathzfile:z)Path '{0}' is ignored: it is a directory.z:Url '%s' is ignored: it is neither a file nor a directory.zQUrl '%s' is ignored. It is either a non-existing path or lacks a specific scheme.)rvrHexistsr!rrwrealpathlistdirjoinrrLZwarningformatisfiler) locations expand_dirrr#Z is_local_pathZ is_file_urlrHitemr%rr&group_locationsxsF        rc@seZdZdZddZdS)CollectedLinksa Encapsulates all the Link objects collected by a call to LinkCollector.collect_links(), stored separately as-- (1) links from the configured file locations, (2) links from the configured find_links, and (3) a dict mapping HTML page url to links from that page. cCs||_||_||_dS)z :param files: Links from file locations. :param find_links: Links from find_links. :param pages: A dict mapping HTML page url to links from that page. Nr find_linkspages)r1rrrr%r%r&r.s zCollectedLinks.__init__N)r4r5r6rkr.r%r%r%r&rs rc@s4eZdZdZddZeddZddZdd Zd S) LinkCollectorz Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. cCs||_||_dSr,) search_scoperF)r1rFrr%r%r&r.szLinkCollector.__init__cCs|jjSr,)rrrir%r%r&rszLinkCollector.find_linksccs,|D]"}t||jd}|dkr q|VqdS)zp Yields (page, page_url) from the given locations, skipping locations that have errors. rKN)r}rF)r1rlocationrfr%r%r& _get_pagess zLinkCollector._get_pagescsj}||}t|\}}tjdd\}}ddt||D}ddjD} fddtdd|Dd d|DD} t| } d t| |g} | D]} | d | qt d | i} | D]}tt|| |j<qt|| | d S)zFind all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. T)rcSsg|] }t|qSr%r .0r#r%r%r& sz/LinkCollector.collect_links..cSsg|]}t|dqS)z-fr rr%r%r&rscsg|]}j|r|qSr%)rFZis_secure_origin)rrbrir%r&r s css|]}t|VqdSr,r rr%r%r& sz.LinkCollector.collect_links..css|]}t|VqdSr,r rr%r%r&r sz,{} location(s) to search for versions of {}:z* {} r)rZget_index_urls_locationsrr itertoolschainrrr"rrLrMrrr~rgr#r)r1Z project_namerZindex_locationsZindex_file_locZ index_url_locZ fl_file_locZ fl_url_locZ file_linksZfind_link_linksZ url_locationslinesrbZ pages_linksrfr%rir& collect_linkssD       zLinkCollector.collect_linksN) r4r5r6rkr.propertyrrrr%r%r%r&rs    r)N)N)F)UrkrPrZloggingrrv collectionsrZ pip._vendorrrZpip._vendor.distlib.compatrZpip._vendor.requests.exceptionsrrrZpip._vendor.six.moves.urllibr rCr rYZpip._internal.models.linkr Zpip._internal.utils.filetypesr Zpip._internal.utils.miscrZpip._internal.utils.typingrZpip._internal.utils.urlsrrZpip._internal.vcsrrtypingrrrrrrrrrZxml.etree.ElementTreeZxmlZpip._vendor.requestsrZ!pip._internal.models.search_scoperZpip._internal.network.sessionrZetreeZ ElementTreeZElementZ HTMLElementrxZResponseHeadersZ getLoggerr4rLr'r* Exceptionr+r?r@rJrNrQrWr]rcrgobjectrhrnror}rrrrr%r%r%r&s^        ,         3    6 ;__pycache__/pep425tags.cpython-38.pyc000064400000023072152347654150013322 0ustar00U .eE>@sTdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl ZddlmZddlmZerddlmZmZmZmZmZmZmZeeeefZeeZe dZ!d d Z"d d Z#d dZ$ddZ%ddZ&ddZ'd-ddZ(ddZ)ddZ*ddZ+ddZ,d d!Z-d"d#Z.d$d%Z/d&d'Z0d(d)Z1d.d+d,Z2e'Z3dS)/z2Generate and work with PEP 425 Compatibility Tags.)absolute_importN) OrderedDict)get_extension_suffixes)MYPY_CHECK_RUNNING)TupleCallableListOptionalUnionDictSetz(.+)_(\d+)_(\d+)_(.+)c CsLz t|WStk rF}ztd|tWYdSd}~XYnXdS)Nz{}) sysconfigget_config_varIOErrorwarningswarnformatRuntimeWarning)varerConfig variable '%s' is unset, Python ABI tag may be incorrect)rloggerdebug)rZfallbackexpectedrvalrrrget_flagYsr2cstd}t}d}|s|dkrttdrd}d}d}|dktddd d rRd }tjd krvtd fdd d rvd}tjdkrtddd ddrd}d|t|||f}n:|r|drd|dd}n|r| dd dd}|S)zXReturn the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).ZSOABIN>rr maxunicoder!rZPy_DEBUGcSs ttdS)NZgettotalrefcount)rrrrrrtzget_abi_tag..)rd)Z WITH_PYMALLOCcsS)NrrZ is_cpythonrrr4xr5m)r7r7ZPy_UNICODE_SIZEcSs tjdkS)Ni)rr3rrrrr4{r5)r0ruz %s%s%s%s%szcpython--r*._) rr rrr2r&r)rsplitreplace)Zsoabiimplabir6r:r<rr9r get_abi_tagfsB   rDcCs tjdkS)Ni)rmaxsizerrrr_is_running_32bitsrFcCstjdkr^t\}}}|d}|dkr6tr6d}n|dkrHtrHd}d|d|d |Stj dd  d d }|d krtrd }|S)z0Return our platform name 'win32', 'linux_x86_64'darwinr>x86_64i386ppc64ppczmacosx_{}_{}_{}rr*r?r= linux_x86_64 linux_i686) rrZmac_verr@rFr distutilsutil get_platformrA)releaser?machineZ split_verresultrrrrPs  rPc Cs$tdkrdSz&ttjd}|d}W5QRXWntttfk rPYdSX|dksft|dkrjdSt |t rdd|D}ndd|D}|dd d d d d gk}||d ddgkM}||dddgkM}||ddddgkM}||dddgkM}||dddd @d kM}|S)N linux_armv7lFrb(cSsg|] }t|qSr)ord).0crrr sz"is_linux_armhf..cSsg|]}|qSrr)rXbrrrrZsrr;ELFr*'%&) rPopenr executablereadrOSError TypeErrorlen isinstancer%)fZelf_header_rawZ elf_headerrSrrris_linux_armhfs&  roc CsNtdkrdSzddl}t|jWSttfk r:YnXtjjj ddS)NrMrLFrr"r`) rP _manylinuxboolZmanylinux1_compatible ImportErrorAttributeErrorpip _internalutilsglibchave_compatible_glibcrqrrris_manylinux1_compatibles  r{c CsNtdkrdSzddl}t|jWSttfk r:YnXtjjj ddS)NrpFrr" ) rPrqrrZmanylinux2010_compatiblersrtrurvrwrxryrzrrris_manylinux2010_compatibles  r}c Csdt}|dkrdS|dkr$ts$dSzddl}t|jWSttfk rPYnXtjj j ddS)N>rM linux_s390x linux_ppc64lerLrT linux_aarch64 linux_ppc64FrTrr") rProrqrrZmanylinux2014_compatiblersrtrurvrwrxry)rrqrrris_manylinux2014_compatibles rcsrg}fddtddddg|||r8||D]&}||kr<|||r<||q<|d|S)zReturn a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. cs||dkr||fdkS|dkr(||fdkS|dkr<||fdkS|dkrP||fdkS|krx|D]}|||r`dSq`dS) NrK) r`rJrI)rr;rHTFr)r+r,archgarch_supports_archgroupsrrrs      z)get_darwin_arches.._supports_arch)Zfat)rIrK)Zintel)rHrI)Zfat64)rHrJ)Zfat32)rHrIrKZ universal)rappend)r+r,rRarchesrrrrget_darwin_archess%    rc CsFg}|dd}t|dddD] }|dtt||fq |S)Nr!)rangerr#r$r%)r&versionsr+r,rrr!get_all_minor_versions_as_strings>s  rFcCsDg}|dkrt}t|}|p"t}g}|p0t}|rD|g|dd<t}tD]$} | drP|| dddqP| t t || d|s|pt } | d\} } } | d r>t| }|r6|\}}}}d ||}g}ttt|dD]0}tt|||D]}| |||fqqn| g}n| d kr~| g}| d kr| d | | | d| | n| d kr| d| | g}nn|dkrg}tr| d | | tr| d | | tr| d| | | | n| g}|D].}|D]"} | d||df|| fqq |ddD]F}|dkr\q|D]*}|D]} | d||f|| fqhq`qH|D]"} | d|ddd| fq| d||dfddf| d||ddfddft|D]B\}}| d|fddf|dkr| d|dddfq|S)acReturn a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. Nrz.abir>r"r*Znoner?Zmacosxz {}_{}_%i_%sZ manylinux2014>rHi686Z manylinux2010Z manylinux1z%s%s>3130zpy%sany)r(rr rDsetrraddr@extendsortedlistrrP partition _osx_arch_patmatchrrreversedrintrrr}r{ enumerate)rZnoarchrrBrCZ supportedr&ZabisZabi3ssuffixrZ arch_prefixZarch_sepZ arch_suffixrnamer+r,Z actual_archZtplrr:aversionirrr get_supportedHs~              $ $   r)TT)NFNNN)4__doc__Z __future__rZdistutils.utilrNZloggingrrerr r collectionsrZpip._internal.utils.glibcruZpip._internal.utils.compatrZpip._internal.utils.typingrtypingrrrr r r r r%Z Pep425TagZ getLogger__name__r.compilerrr r'r)r(r-r2rDrFrPror{r}rrrrZimplementation_tagrrrrsP    $     !?  y__pycache__/build_env.cpython-38.opt-1.pyc000064400000016416152347654150014336 0ustar00U .e]@sdZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZerdd lmZmZmZmZmZdd l m!Z!e"e#Z$GdddZ%Gddde&Z'Gddde'Z(dS)z;Build Environment used for isolation during sdist building N) OrderedDict)get_python_lib) get_paths) RequirementVersionConflict WorkingSet)__file__)call_subprocess) TempDirectory)MYPY_CHECK_RUNNING) open_spinner)TupleSetIterableOptionalList) PackageFinderc@seZdZddZdS)_PrefixcCsj||_d|_ttjdkrdnd||ddd|_td|d}td|d}||kr\|g|_n ||g|_dS) NFntZ posix_prefix)baseZplatbase)varsZscripts) plat_specificprefixT)pathsetuprosnamebin_dirrlib_dirs)selfrZpurelibZplatlibr ;/usr/lib/python3.8/site-packages/pip/_internal/build_env.py__init__!s   z_Prefix.__init__N)__name__ __module__ __qualname__r"r r r r!rsrc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)BuildEnvironmentzFCreates and manages an isolated environment to install build deps c stdd_tfdddD_g_g_ttjD] }j |j j |j qBddt dd t d d fD}tjjjd _tjjstjttjjd d "}|tdj|jdW5QRXdS)Nz build-env)Zkindc3s(|] }|ttjjj|fVqdSN)rrrjoin _temp_dir.0rrr r! ;sz,BuildEnvironment.__init__..)ZnormalZoverlaycSsh|]}tj|qSr )rrnormcase)r+siter r r! Isz,BuildEnvironment.__init__..F)rTr/zsitecustomize.pywa import os, site, sys # First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path # Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) ) system_sitesr)r r)r _prefixes _bin_dirs _lib_dirsreversedlistvaluesappendrextendrrrrr( _site_direxistsmkdiropenwritetextwrapdedentformat)rrr2fpr r,r!r"7s0    zBuildEnvironment.__init__cCsndddD|_|jdd}|jd}|r>||tj|jg}tjtj |dtj |ddS)NcSsi|]}|tj|dqSr')renvirongetr*r r r! osz.BuildEnvironment.__enter__..)PATHZPYTHONNOUSERSITEZ PYTHONPATHrG1) _save_envr4r:splitrpathsepr;rDupdater()rrZold_pathZ pythonpathr r r! __enter__ns   zBuildEnvironment.__enter__cCs:|jD]*\}}|dkr*tj|dq |tj|<q dSr')rIitemsrrDpop)rexc_typeexc_valexc_tbZvarname old_valuer r r!__exit__szBuildEnvironment.__exit__cCs|jdSr')r)cleanupr,r r r!rUszBuildEnvironment.cleanupc Cst}t}|rt|j}|D]p}z"|t|dkrB||Wqtk r}z*|t|j d t|j dfW5d}~XYqXq||fS)zReturn 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs Nr) setrr5findrparseaddrstrargsZas_requirement)rZreqsZmissingZ conflictingZwsZreqer r r!check_requirementss  z#BuildEnvironment.check_requirementsc CsV|j|}d|_|sdStjtjtdddd|jdg}t t j krP| ddD]:}t |j|}|d |d d d t|pd hfqT|j} | r|d| dg| ddD]} |d| gqn | d|jD]} |d| gq|jD]} |d| gq|jr| d| d ||t|} t|| dW5QRXdS)NTZinstallz--ignore-installedz --no-userz--prefixz--no-warn-script-locationz-v)Z no_binaryZ only_binaryz--_-,z:none:z-irrVz--extra-index-urlz --no-indexz --find-linksz--trusted-hostz--pre)spinner)r3rsys executablerrdirname pip_locationloggerZgetEffectiveLevelloggingDEBUGr9getattrformat_controlr:replacer(sorted index_urlsZ find_linksZ trusted_hostsZallow_all_prereleasesr r )rfinder requirementsZprefix_as_stringmessagerr\rkZformatsrnZ extra_indexlinkZhostrbr r r!install_requirementssH           z%BuildEnvironment.install_requirementsN) r#r$r%__doc__r"rMrTrUr^rsr r r r!r&3s7r&c@s8eZdZdZddZddZddZdd Zd d Zd S) NoOpBuildEnvironmentz5A no-op drop-in replacement for BuildEnvironment cCsdSr'r r,r r r!r"szNoOpBuildEnvironment.__init__cCsdSr'r r,r r r!rMszNoOpBuildEnvironment.__enter__cCsdSr'r )rrPrQrRr r r!rTszNoOpBuildEnvironment.__exit__cCsdSr'r r,r r r!rUszNoOpBuildEnvironment.cleanupcCs tdSr')NotImplementedError)rrorprrqr r r!rssz)NoOpBuildEnvironment.install_requirementsN) r#r$r%rtr"rMrTrUrsr r r r!rus ru))rtrhrrcr@ collectionsrZdistutils.sysconfigrZ sysconfigrZpip._vendor.pkg_resourcesrrrZpiprrfZpip._internal.utils.subprocessr Zpip._internal.utils.temp_dirr Zpip._internal.utils.typingr Zpip._internal.utils.uir typingr rrrrZpip._internal.indexrZ getLoggerr#rgrobjectr&rur r r r!s*          __pycache__/main.cpython-38.pyc000064400000002371152347654150012347 0ustar00U .eO@sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZeeZd d d ZdS) z Primary application entrypoint. )absolute_importN) autocomplete) parse_command)create_command)PipError) deprecationc Cs|dkrtjdd}ttzt|\}}WnJtk r~}z,tjd|tjt j t dW5d}~XYnXzt t jdWn0t jk r}ztd|W5d}~XYnXt|d|kd}||S)Nz ERROR: %sz%Ignoring error %s when setting localez --isolated)isolated)sysargvrZinstall_warning_loggerrrrstderrwriteoslinesepexitlocale setlocaleLC_ALLErrorloggerdebugrmain)argsZcmd_nameZcmd_argsexceZcommandr6/usr/lib/python3.8/site-packages/pip/_internal/main.pyrs r)N)__doc__Z __future__rrZloggingrr Z pip._internal.cli.autocompletionrZpip._internal.cli.main_parserrZpip._internal.commandsrZpip._internal.exceptionsrZpip._internal.utilsrZ getLogger__name__rrrrrrs       __pycache__/__init__.cpython-38.pyc000064400000000320152347654150013152 0ustar00U .eP@s ddlZdS)N)Z*pip._internal.utils.inject_securetransportZpiprr:/usr/lib/python3.8/site-packages/pip/_internal/__init__.py__pycache__/build_env.cpython-38.pyc000064400000016454152347654150013401 0ustar00U .e]@sdZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZerdd lmZmZmZmZmZdd l m!Z!e"e#Z$GdddZ%Gddde&Z'Gddde'Z(dS)z;Build Environment used for isolation during sdist building N) OrderedDict)get_python_lib) get_paths) RequirementVersionConflict WorkingSet)__file__)call_subprocess) TempDirectory)MYPY_CHECK_RUNNING) open_spinner)TupleSetIterableOptionalList) PackageFinderc@seZdZddZdS)_PrefixcCsj||_d|_ttjdkrdnd||ddd|_td|d}td|d}||kr\|g|_n ||g|_dS) NFntZ posix_prefix)baseZplatbase)varsZscripts) plat_specificprefixT)pathsetuprosnamebin_dirrlib_dirs)selfrZpurelibZplatlibr ;/usr/lib/python3.8/site-packages/pip/_internal/build_env.py__init__!s   z_Prefix.__init__N)__name__ __module__ __qualname__r"r r r r!rsrc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)BuildEnvironmentzFCreates and manages an isolated environment to install build deps c stdd_tfdddD_g_g_ttjD] }j |j j |j qBddt dd t d d fD}tjjjd _tjjstjttjjd d "}|tdj|jdW5QRXdS)Nz build-env)Zkindc3s(|] }|ttjjj|fVqdSN)rrrjoin _temp_dir.0rrr r! ;sz,BuildEnvironment.__init__..)ZnormalZoverlaycSsh|]}tj|qSr )rrnormcase)r+siter r r! Isz,BuildEnvironment.__init__..F)rTr/zsitecustomize.pywa import os, site, sys # First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path # Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) ) system_sitesr)r r)r _prefixes _bin_dirs _lib_dirsreversedlistvaluesappendrextendrrrrr( _site_direxistsmkdiropenwritetextwrapdedentformat)rrr2fpr r,r!r"7s0    zBuildEnvironment.__init__cCsndddD|_|jdd}|jd}|r>||tj|jg}tjtj |dtj |ddS)NcSsi|]}|tj|dqSr')renvirongetr*r r r! osz.BuildEnvironment.__enter__..)PATHZPYTHONNOUSERSITEZ PYTHONPATHrG1) _save_envr4r:splitrpathsepr;rDupdater()rrZold_pathZ pythonpathr r r! __enter__ns   zBuildEnvironment.__enter__cCs:|jD]*\}}|dkr*tj|dq |tj|<q dSr')rIitemsrrDpop)rexc_typeexc_valexc_tbZvarname old_valuer r r!__exit__szBuildEnvironment.__exit__cCs|jdSr')r)cleanupr,r r r!rUszBuildEnvironment.cleanupc Cst}t}|rt|j}|D]p}z"|t|dkrB||Wqtk r}z*|t|j d t|j dfW5d}~XYqXq||fS)zReturn 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs Nr) setrr5findrparseaddrstrargsZas_requirement)rZreqsZmissingZ conflictingZwsZreqer r r!check_requirementss  z#BuildEnvironment.check_requirementsc Csb|j|}|jrtd|_|s"dStjtjtdddd|jdg}t t j krZ| ddD]:}t|j|}|d |d d d t|pd hfq^|j} | r|d| dg| ddD]} |d| gqn | d|jD]} |d| gq|jD]} |d| gq|jr*| d| d ||t|} t|| dW5QRXdS)NTZinstallz--ignore-installedz --no-userz--prefixz--no-warn-script-locationz-v)Z no_binaryZ only_binaryz--_-,z:none:z-irrVz--extra-index-urlz --no-indexz --find-linksz--trusted-hostz--pre)spinner)r3rAssertionErrorsys executablerrdirname pip_locationloggerZgetEffectiveLevelloggingDEBUGr9getattrformat_controlr:replacer(sorted index_urlsZ find_linksZ trusted_hostsZallow_all_prereleasesr r )rfinder requirementsZprefix_as_stringmessagerr\rlZformatsroZ extra_indexlinkZhostrbr r r!install_requirementssJ            z%BuildEnvironment.install_requirementsN) r#r$r%__doc__r"rMrTrUr^rtr r r r!r&3s7r&c@s8eZdZdZddZddZddZdd Zd d Zd S) NoOpBuildEnvironmentz5A no-op drop-in replacement for BuildEnvironment cCsdSr'r r,r r r!r"szNoOpBuildEnvironment.__init__cCsdSr'r r,r r r!rMszNoOpBuildEnvironment.__enter__cCsdSr'r )rrPrQrRr r r!rTszNoOpBuildEnvironment.__exit__cCsdSr'r r,r r r!rUszNoOpBuildEnvironment.cleanupcCs tdSr')NotImplementedError)rrprqrrrr r r!rtsz)NoOpBuildEnvironment.install_requirementsN) r#r$r%rur"rMrTrUrtr r r r!rvs rv))rurirrdr@ collectionsrZdistutils.sysconfigrZ sysconfigrZpip._vendor.pkg_resourcesrrrZpiprrgZpip._internal.utils.subprocessr Zpip._internal.utils.temp_dirr Zpip._internal.utils.typingr Zpip._internal.utils.uir typingr rrrrZpip._internal.indexrZ getLoggerr#rhrobjectr&rvr r r r!s*          __pycache__/configuration.cpython-38.pyc000064400000024625152347654150014300 0ustar00U .e7@sdZddlZddlZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z mZddlmZmZddlmZerdd lmZmZmZmZmZmZmZejZed eZee Z!d d Z"d dZ#eddddddZ$e rdndZ%ddZ&Gddde'Z(dS)a Configuration management setup Some terminology: - name As written in config files. - value Value associated with a name - key Name combined with it's section (section.name) - variant A single word describing where the configuration key-value pair came from N) configparser)ConfigurationError!ConfigurationFileCouldNotBeLoaded)appdirs)WINDOWS expanduser) ensure_direnum)MYPY_CHECK_RUNNING)AnyDictIterableListNewTypeOptionalTupleKindcCs*|dd}|dr&|dd}|S)zFMake a name consistent regardless of source (environment or file) _-z--N)lowerreplace startswith)namer?/usr/lib/python3.8/site-packages/pip/_internal/configuration.py_normalize_name.s  rcCs&d|krd|}t||ddS)N.zbKey does not contain dot separated section and key. Perhaps you wanted to use 'global.{}' instead?)formatrsplit)rZ error_messagerrr_disassemble_key8sr!userglobalZsiteenvzenv-var)USERGLOBALSITEENVENV_VARzpip.inizpip.confcCspddtdD}tjtjt}tjtdt r8dndt}tjt dt}t j |t j |gt j||giS)NcSsg|]}tj|tqSr)ospathjoinCONFIG_BASENAME).0r+rrr Qsz+get_configuration_files..Zpip~z.pip)rZsite_config_dirsr*r+r,sysprefixr-rrZuser_config_dirkindsr&r'r%)Zglobal_config_filesZsite_config_fileZlegacy_config_fileZnew_config_filerrrget_configuration_filesPs( r4cseZdZdZd)fdd ZddZddZd d Zd d Zd dZ ddZ ddZ ddZ e ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(ZZS)* ConfigurationaHandles management of configuration. Provides an interface to accessing and managing configuration files. This class converts provides an API that takes "section.key-name" style keys and stores the value associated with it as "key-name" under the section "section". This allows for a clean interface wherein the both the section and the key-name are preserved in an easy to manage form in the configuration files and the data stored is also nice. Nc stt|tjtjtjdg}||krJtdd t t |dd||_ ||_ tjtjtjtjtjg|_ddg|_dd|jD|_dd|jD|_g|_dS) Nz5Got invalid value for load_only - should be one of {}z, versionhelpcSsi|] }|gqSrrr.variantrrr sz*Configuration.__init__..cSsi|] }|iqSrrr9rrrr;s)superr5__init__r3r%r&r'rrr,mapreprisolated load_onlyr(r)_override_order_ignore_env_names_parsers_config_modified_parsers)selfr@rAZ_valid_load_only __class__rrr=ts0 zConfiguration.__init__cCs||js|dS)zELoads configuration from configuration files and environment N)_load_config_filesr@_load_environment_varsrGrrrloadszConfiguration.loadcCs<|jdk stdz|dWStk r6YdSXdS)z@Returns the file with highest priority in configuration Nz)Need to be specified a file to be editingr)rAAssertionError_get_parser_to_modify IndexErrorrLrrrget_file_to_edits zConfiguration.get_file_to_editcCs |jS)z`Returns key-value pairs like dict.items() representing the loaded configuration ) _dictionaryitemsrLrrrrSszConfiguration.itemscCs4z |j|WStk r.td|YnXdS)z,Get a value from the configuration. No such key - {}N)rRKeyErrorrr)rGkeyrrr get_values zConfiguration.get_valuecCsj||\}}|dk rJt|\}}||s<||||||||j|j|<|||dS)z-Modify a value in the configuration. N) _ensure_have_load_onlyrOr! has_sectionZ add_sectionsetrErA_mark_as_modified)rGrVvaluefnameparsersectionrrrr set_values    zConfiguration.set_valuec Cs|||j|jkr&td||\}}|dk rt|\}}d}||r`|||}|rt | |}z t |}Wnt k rd}YnX|dkr| ||||ntd|j|j|=dS)z,Unset a value in the configuration. rTNFz4Fatal Internal error [id=1]. Please report as a bug.)rXrErArrrOr!rYZ remove_optioniterrSnext StopIterationZremove_sectionr[) rGrVr]r^r_rZmodified_somethingZ section_itervalrrr unset_values,       zConfiguration.unset_valuec CsX||jD]D\}}td|ttj|t|d}| |W5QRXqdS)z*Save the current in-memory state. z Writing to %swN) rXrFloggerinforr*r+dirnameopenwrite)rGr]r^frrrsaves   zConfiguration.savecCs$|jdkrtdtd|jdS)Nz'Needed a specific file to be modifying.z$Will be working with %s variant only)rArrgdebugrLrrrrXs z$Configuration._ensure_have_load_onlycCs$i}|jD]}||j|q |S)zs6   $     __pycache__/self_outdated_check.cpython-38.opt-1.pyc000064400000012622152347654150016341 0ustar00U .e@s^ddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZmZmZdd lmZm Z m!Z!dd l"m#Z#ddl$m%Z%e%rddl&Z&ddl&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,ddl-m.Z.dZ/e0e1Z2dddZ3ddZ4Gddde5Z6ddZ7ddZ8dS))absolute_importN) pkg_resources)version) ensure_binary) LinkCollector) PackageFinder) SearchScope)SelectionPreferences)WINDOWS)adjacent_tmp_filecheck_path_ownerreplace) ensure_dirget_installed_versionredact_auth_from_url) get_installer)MYPY_CHECK_RUNNING)Values)AnyDictTextUnion) PipSessionz%Y-%m-%dT%H:%M:%SZFcCs`|jg|j}|jr8|s8tdddd|Dg}|jp@g}tj||d}t ||d}|S)z :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. zIgnoring indexes: %s,css|]}t|VqdSN)r).0ZurlrE/usr/lib/python3.8/site-packages/pip/_internal/self_outdated_check.py @sz&make_link_collector..) find_links index_urls)session search_scope) Z index_urlZextra_index_urlsZno_indexloggerdebugjoinrrcreater)r!optionssuppress_no_indexr rr"link_collectorrrrmake_link_collector1s    r*cCst|}t|}|Sr)rhashlibZsha224Z hexdigest)keyZ key_bytesnamerrr_get_statefile_namePsr.c@s(eZdZddZeddZddZdS)SelfCheckStatec Csni|_d|_|rjtj|dt|j|_z&t|j}t ||_W5QRXWnt t t fk rhYnXdS)NZ selfcheck) statestatefile_pathospathr%r.r,openjsonloadIOError ValueErrorKeyError)self cache_dirZ statefilerrr__init__Xs zSelfCheckState.__init__cCstjSr)sysprefix)r:rrrr,jszSelfCheckState.keyc Cs|js dSttj|js dSttj|j|j|t|d}t j |ddd}t |j}| t |W5QRXzt|j|jWntk rYnXdS)N)r, last_check pypi_versionT)r:)Z sort_keysZ separators)r1r r2r3dirnamerr,strftimeSELFCHECK_DATE_FMTr5dumpsr writerr r-OSError)r:r@ current_timer0textfrrrsavens  zSelfCheckState.saveN)__name__ __module__ __qualname__r<propertyr,rKrrrrr/Ws r/cCs6zt|}dt|kWStjk r0YdSXdS)zChecks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. pipFN)rZget_distributionrZDistributionNotFound)ZpkgZdistrrrwas_installed_by_pips  rQcCsXtd}|sdSt|}d}zt|jd}tj}d|jkrzd|jkrztj|jdt }|| dkrz|jd}|dkrt ||dd}t d d d } t j|| d } | dj} | dkrWdSt| j}|||t|} || ko|j| jkotd} | s WdStrd }nd}td |||Wn$tk rRtjdddYnXdS)zCheck for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. rPN)r;r?r@i: T)r'r(F)Z allow_yankedZallow_all_prereleases)r)selection_prefsz python -m pipzYou are using pip version %s; however, version %s is available. You should consider upgrading via the '%s install --upgrade pip' command.z5There was an error checking the latest version of pip)exc_info)rpackaging_versionparser/r;datetimeZutcnowr0strptimerDZ total_secondsr*r rr&Zfind_best_candidatebest_candidatestrrrKZ base_versionrQr r#Zwarning Exceptionr$)r!r'Zinstalled_versionZ pip_versionr@r0rHr?r)rRfinderrXZremote_versionZlocal_version_is_olderZpip_cmdrrrpip_self_version_checksp         r\)F)9Z __future__rrVr+r5ZloggingZos.pathr2r=Z pip._vendorrZpip._vendor.packagingrrTZpip._vendor.sixrZpip._internal.collectorrZpip._internal.indexrZ!pip._internal.models.search_scoperZ$pip._internal.models.selection_prefsr Zpip._internal.utils.compatr Zpip._internal.utils.filesystemr r r Zpip._internal.utils.miscrrrZpip._internal.utils.packagingrZpip._internal.utils.typingrZoptparsertypingrrrrZpip._internal.network.sessionrrDZ getLoggerrLr#r*r.objectr/rQr\rrrrs>               ;__pycache__/download.cpython-38.pyc000064400000026267152347654150013244 0ustar00U .eEQ@sddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z ddlmZddlmZddlmZmZddlmZdd lmZdd lmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3e+rddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;mZ>ddl?m@Z@ddlAmBZBered0d ZSd1d2ZTd3d4ZUd?d5dZVd@d6d!ZWd7d#ZXd8d"ZYd9d:ZZd;d<Z[dS)A)absolute_importN)requests)CONTENT_CHUNK_SIZEResponse)PY2)parse) HashMismatchInstallationError)PyPI) PipSession) auto_decode) copy2_fixed) ask_path_exists backup_dirconsume display_path format_sizehide_urlpath_to_displayrmtreesplitext) TempDirectory)MYPY_CHECK_RUNNING)DownloadProgressProvider) unpack_file)get_url_scheme)vcs)IOCallableListOptionalTextTuple) TypedDict)Link)Hashes)VersionControlCopytreeKwargsignoresymlinksF)Ztotal) copy_functionr)Zignore_dangling_symlinksr*get_file_contentunpack_vcs_linkunpack_file_urlunpack_http_url unpack_urlparse_content_dispositionsanitize_content_filenamec Cs6|dkrtdt|}|dkr>||}||j|jfS|dkr|rd|drdtd||f|ddd}| d d }t |}|r| dd|d dd}t |}|d rd |d }|}z&t|d }t|}W5QRXWn4tk r,} ztd t| W5d} ~ XYnX||fS)a*Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. :param url: File path or url. :param comes_from: Origin description of requirements. :param session: Instance of pip.download.PipSession. NzAget_file_content() missing 1 required keyword argument: 'session')httpZhttpsfiler3z6Requirements file %s references URL %s, which is local:\/|rbz$Could not open requirements file: %s) TypeErrorrgetraise_for_statusurltext startswithr splitreplace_url_slash_drive_rematchgroup urllib_parseZunquotelstripopenr readIOErrorstr) r>Z comes_fromsessionschemeresppathrDfZcontentexcrR:/usr/lib/python3.8/site-packages/pip/_internal/download.pyr,UsB         z /*([a-z])\|cCs,t|}|dk st|j|t|jddS)N)r>)_get_used_vcs_backendAssertionErrorunpackrr>)linklocation vcs_backendrRrRrSr-s cCs$tjD]}|j|jkr|SqdS)z1 Return a VersionControl object or None. N)rZbackendsrMZschemes)rWrYrRrRrSrTs   rTcOs|SNrR)iterableargskwargsrRrRrS_progress_indicatorsr^c s6ztjd}Wntttfk r0d}YnXtdd}ttj krRd}n&|r\d}n|dkrjd}n|std}nd}|j }fdd} fd d } t } |j t j kr|} n|j} |rt||d } |rtd | t|n td | n|rtd| n td | | | | tt} |r*|| nt| dS)Nzcontent-lengthrZ from_cacheFi@Tc3sTz jj|ddD] }|VqWn.tk rNj|}|sBqJ|Vq0YnXdS)NF)Zdecode_content)rawstreamAttributeErrorrI)Z chunk_sizechunk)rNrRrS resp_reads   z _download_url..resp_readc3s|D]}||VqdSrZ)write)Zchunksrb) content_filerRrSwritten_chunkss z%_download_url..written_chunks)maxzDownloading %s (%s)zDownloading %szUsing cached %s)intheaders ValueErrorKeyErrorr;getattrloggerZgetEffectiveLevelloggingINFOshow_urlr^Znetlocr Zurl_without_fragmentrinforrZcheck_against_chunksr)rNrWrehashes progress_barZ total_lengthZ cached_respZ show_progressrprcrfZprogress_indicatorr>Zdownloaded_chunksrR)rerNrS _download_urlsP   %    rtcCsd}tj||j}tj|rtdt|d}|dkr@d}nj|dkrdtdt|t |nF|dkrt |}td t|t|t ||n|d krt d |rt ||td t|dS) NTz8The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort)iwbaruFrvz Deleting %srwzBacking up %s to %srxzSaved %s)osrOjoinfilenameexistsrrrmwarningremovershutilZmovesysexitcopyrq)r|rXrWrZdownload_locationresponseZ dest_filerRrRrS _copy_files6    ronc Cs|dkrtdtddv}d}|r0t|||}|rH|}t|d} nt|||j||\}} t||| |r~|s~t||||st |W5QRXdS)Nz@unpack_http_url() missing 1 required keyword argument: 'session'rV)Zkindr) r;r_check_download_dir mimetypes guess_type_download_http_urlrOrrrzunlink) rWrX download_dirrLrrrstemp_diralready_downloaded_path from_path content_typerRrRrSr/s2    c CsTzt||Wn@tjk rN}z tdt|t|t|W5d}~XYnXdS)zCopying special files is not supported, but as a convenience to users we skip errors copying them. This supports tools that may create e.g. socket files in the project source directory. z>Ignoring special file error '%s' encountered copying %s to %s.N)r rZSpecialFileErrorrmr~rKr)srcdesterRrRrS_copy2_ignoring_special_filesJsrcs`tj|}tj|tj|fdd}t|dd}tsLt|d<tj |f|dS)Ncs6g}|kr|ddg7}tj|kr2|g7}|S)Nz.toxz.nox)rzrOabspath)dnamesZskippedsourceZtarget_basenameZtarget_dirnamerRrSr)es   z!_copy_source_tree..ignoreTr(r+) rzrOrbasenamedirnamedictrrrZcopytree)rtargetZtarget_abspathr)r]rRrrS_copy_source_tree_s    rcCs|j}|r>tj|r"t|t|||r:tddS|rL| |d}|r`t |||}|rj|}n|}t |d}t ||||r|st|||dS)zUnpack link into location. If download_dir is provided and link points to a file, make a copy of the link file inside download_dir. z*Link is a directory, ignoring download_dirNr) file_pathZis_existing_dirrzrOisdirrrrmrqcheck_against_pathrrrrr)rWrXrrrZ link_pathrrrrRrRrSr.~s.      cCsP|jrt||n:|jr*t||||dn"|dkr8t}t||||||ddS)avUnpack link. If link is a VCS link: if only_download, export into download_dir and ignore location else unpack into location for other types of link: - unpack into location - if download_dir, copy the file into download_dir - if only_download, mark location for deletion :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. )rrN)rrrs)Zis_vcsr-is_filer.r r/)rWrXrrLrrrsrRrRrSr0s cCs tj|S)zJ Sanitize the "filename" value from a Content-Disposition header. )rzrOr)r|rRrRrSr2scCs,t|\}}|d}|r$t|}|p*|S)z Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. r|)cgiZ parse_headerr<r2)content_dispositionZdefault_filenameZ_typeZparamsr|rRrRrSr1s  c Cs*|jddd}z |j|ddidd}|Wn8tjk rj}ztd|jj |W5d }~XYnX|j d d }|j } |j d } | rt | | } t | d} | st|} | r| | 7} | s|j|jkrtj |jd} | r| | 7} tj|| } t| d } t||| ||W5QRX| |fS)z6Download link url into temp_dir using provided session#r6rzAccept-EncodingZidentityT)rir`zHTTP error %s while getting %sNz content-typezcontent-dispositionwb)r>rAr<r=rZ HTTPErrorrmZcriticalrZ status_coderir|r1rrZguess_extensionrzrOr{rHrt)rWrLrrrrsZ target_urlrNrQrr|rZextrrerRrRrSrsB       rcCsptj||j}tj|s dStd||rlz||Wn,tk rjt d|t |YdSX|S)z Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None NzFile was already downloaded %sz;Previously-downloaded file %s has bad hash. Re-downloading.) rzrOr{r|r}rmrqrrr~r)rWrrrZ download_pathrRrRrSr7s   r)NN)NNNr)NN)NNNr)\Z __future__rrrnrrzrerrZ pip._vendorrZpip._vendor.requests.modelsrrZpip._vendor.sixrZpip._vendor.six.moves.urllibrrFZpip._internal.exceptionsrr Zpip._internal.models.indexr Zpip._internal.network.sessionr Zpip._internal.utils.encodingr Zpip._internal.utils.filesystemr Zpip._internal.utils.miscrrrrrrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.uirZpip._internal.utils.unpackingrZpip._internal.utils.urlsrZpip._internal.vcsrtypingrrrr r!r"Zmypy_extensionsr#Zpip._internal.models.linkr$Zpip._internal.utils.hashesr%Z pip._internal.vcs.versioncontrolr&rKboolr'__all__Z getLogger__name__rmr,compileIrCr-rTr^rtrr/rrr.r0r2r1rrrRrRrRrSs        ,               0 d -" 8 .?__pycache__/configuration.cpython-38.opt-1.pyc000064400000024475152347654150015242 0ustar00U .e7@sdZddlZddlZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z mZddlmZmZddlmZerdd lmZmZmZmZmZmZmZejZed eZee Z!d d Z"d dZ#eddddddZ$e rdndZ%ddZ&Gddde'Z(dS)a Configuration management setup Some terminology: - name As written in config files. - value Value associated with a name - key Name combined with it's section (section.name) - variant A single word describing where the configuration key-value pair came from N) configparser)ConfigurationError!ConfigurationFileCouldNotBeLoaded)appdirs)WINDOWS expanduser) ensure_direnum)MYPY_CHECK_RUNNING)AnyDictIterableListNewTypeOptionalTupleKindcCs*|dd}|dr&|dd}|S)zFMake a name consistent regardless of source (environment or file) _-z--N)lowerreplace startswith)namer?/usr/lib/python3.8/site-packages/pip/_internal/configuration.py_normalize_name.s  rcCs&d|krd|}t||ddS)N.zbKey does not contain dot separated section and key. Perhaps you wanted to use 'global.{}' instead?)formatrsplit)rZ error_messagerrr_disassemble_key8sr!userglobalZsiteenvzenv-var)USERGLOBALSITEENVENV_VARzpip.inizpip.confcCspddtdD}tjtjt}tjtdt r8dndt}tjt dt}t j |t j |gt j||giS)NcSsg|]}tj|tqSr)ospathjoinCONFIG_BASENAME).0r+rrr Qsz+get_configuration_files..Zpip~z.pip)rZsite_config_dirsr*r+r,sysprefixr-rrZuser_config_dirkindsr&r'r%)Zglobal_config_filesZsite_config_fileZlegacy_config_fileZnew_config_filerrrget_configuration_filesPs( r4cseZdZdZd)fdd ZddZddZd d Zd d Zd dZ ddZ ddZ ddZ e ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(ZZS)* ConfigurationaHandles management of configuration. Provides an interface to accessing and managing configuration files. This class converts provides an API that takes "section.key-name" style keys and stores the value associated with it as "key-name" under the section "section". This allows for a clean interface wherein the both the section and the key-name are preserved in an easy to manage form in the configuration files and the data stored is also nice. Nc stt|tjtjtjdg}||krJtdd t t |dd||_ ||_ tjtjtjtjtjg|_ddg|_dd|jD|_dd|jD|_g|_dS) Nz5Got invalid value for load_only - should be one of {}z, versionhelpcSsi|] }|gqSrrr.variantrrr sz*Configuration.__init__..cSsi|] }|iqSrrr9rrrr;s)superr5__init__r3r%r&r'rrr,mapreprisolated load_onlyr(r)_override_order_ignore_env_names_parsers_config_modified_parsers)selfr@rAZ_valid_load_only __class__rrr=ts0 zConfiguration.__init__cCs||js|dS)zELoads configuration from configuration files and environment N)_load_config_filesr@_load_environment_varsrGrrrloadszConfiguration.loadcCs*z|dWStk r$YdSXdS)z@Returns the file with highest priority in configuration rN)_get_parser_to_modify IndexErrorrLrrrget_file_to_editszConfiguration.get_file_to_editcCs |jS)z`Returns key-value pairs like dict.items() representing the loaded configuration ) _dictionaryitemsrLrrrrRszConfiguration.itemscCs4z |j|WStk r.td|YnXdS)z,Get a value from the configuration. No such key - {}N)rQKeyErrorrr)rGkeyrrr get_values zConfiguration.get_valuecCsj||\}}|dk rJt|\}}||s<||||||||j|j|<|||dS)z-Modify a value in the configuration. N) _ensure_have_load_onlyrNr! has_sectionZ add_sectionsetrErA_mark_as_modified)rGrUvaluefnameparsersectionrrrr set_values    zConfiguration.set_valuec Cs|||j|jkr&td||\}}|dk rt|\}}d}||r`|||}|rt | |}z t |}Wnt k rd}YnX|dkr| ||||ntd|j|j|=dS)z,Unset a value in the configuration. rSNFz4Fatal Internal error [id=1]. Please report as a bug.)rWrErArrrNr!rXZ remove_optioniterrRnext StopIterationZremove_sectionrZ) rGrUr\r]r^rZmodified_somethingZ section_itervalrrr unset_values,       zConfiguration.unset_valuec CsX||jD]D\}}td|ttj|t|d}| |W5QRXqdS)z*Save the current in-memory state. z Writing to %swN) rWrFloggerinforr*r+dirnameopenwrite)rGr\r]frrrsaves   zConfiguration.savecCs$|jdkrtdtd|jdS)Nz'Needed a specific file to be modifying.z$Will be working with %s variant only)rArrfdebugrLrrrrWs z$Configuration._ensure_have_load_onlycCs$i}|jD]}||j|q |S)zs6   $     __pycache__/pep425tags.cpython-38.opt-1.pyc000064400000023072152347654150014261 0ustar00U .eE>@sTdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl ZddlmZddlmZerddlmZmZmZmZmZmZmZeeeefZeeZe dZ!d d Z"d d Z#d dZ$ddZ%ddZ&ddZ'd-ddZ(ddZ)ddZ*ddZ+ddZ,d d!Z-d"d#Z.d$d%Z/d&d'Z0d(d)Z1d.d+d,Z2e'Z3dS)/z2Generate and work with PEP 425 Compatibility Tags.)absolute_importN) OrderedDict)get_extension_suffixes)MYPY_CHECK_RUNNING)TupleCallableListOptionalUnionDictSetz(.+)_(\d+)_(\d+)_(.+)c CsLz t|WStk rF}ztd|tWYdSd}~XYnXdS)Nz{}) sysconfigget_config_varIOErrorwarningswarnformatRuntimeWarning)varerConfig variable '%s' is unset, Python ABI tag may be incorrect)rloggerdebug)rZfallbackexpectedrvalrrrget_flagYsr2cstd}t}d}|s|dkrttdrd}d}d}|dktddd d rRd }tjd krvtd fdd d rvd}tjdkrtddd ddrd}d|t|||f}n:|r|drd|dd}n|r| dd dd}|S)zXReturn the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).ZSOABIN>rr maxunicoder!rZPy_DEBUGcSs ttdS)NZgettotalrefcount)rrrrrrtzget_abi_tag..)rd)Z WITH_PYMALLOCcsS)NrrZ is_cpythonrrr4xr5m)r7r7ZPy_UNICODE_SIZEcSs tjdkS)Ni)rr3rrrrr4{r5)r0ruz %s%s%s%s%szcpython--r*._) rr rrr2r&r)rsplitreplace)Zsoabiimplabir6r:r<rr9r get_abi_tagfsB   rDcCs tjdkS)Ni)rmaxsizerrrr_is_running_32bitsrFcCstjdkr^t\}}}|d}|dkr6tr6d}n|dkrHtrHd}d|d|d |Stj dd  d d }|d krtrd }|S)z0Return our platform name 'win32', 'linux_x86_64'darwinr>x86_64i386ppc64ppczmacosx_{}_{}_{}rr*r?r= linux_x86_64 linux_i686) rrZmac_verr@rFr distutilsutil get_platformrA)releaser?machineZ split_verresultrrrrPs  rPc Cs$tdkrdSz&ttjd}|d}W5QRXWntttfk rPYdSX|dksft|dkrjdSt |t rdd|D}ndd|D}|dd d d d d gk}||d ddgkM}||dddgkM}||ddddgkM}||dddgkM}||dddd @d kM}|S)N linux_armv7lFrb(cSsg|] }t|qSr)ord).0crrr sz"is_linux_armhf..cSsg|]}|qSrr)rXbrrrrZsrr;ELFr*'%&) rPopenr executablereadrOSError TypeErrorlen isinstancer%)fZelf_header_rawZ elf_headerrSrrris_linux_armhfs&  roc CsNtdkrdSzddl}t|jWSttfk r:YnXtjjj ddS)NrLrMFrr"r`) rP _manylinuxboolZmanylinux1_compatible ImportErrorAttributeErrorpip _internalutilsglibchave_compatible_glibcrqrrris_manylinux1_compatibles  r{c CsNtdkrdSzddl}t|jWSttfk r:YnXtjjj ddS)NrpFrr" ) rPrqrrZmanylinux2010_compatiblersrtrurvrwrxryrzrrris_manylinux2010_compatibles  r}c Csdt}|dkrdS|dkr$ts$dSzddl}t|jWSttfk rPYnXtjj j ddS)N> linux_s390xrMrL linux_ppc64lerT linux_aarch64 linux_ppc64FrTrr") rProrqrrZmanylinux2014_compatiblersrtrurvrwrxry)rrqrrris_manylinux2014_compatibles rcsrg}fddtddddg|||r8||D]&}||kr<|||r<||q<|d|S)zReturn a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. cs||dkr||fdkS|dkr(||fdkS|dkr<||fdkS|dkrP||fdkS|krx|D]}|||r`dSq`dS) NrK) r`rJrI)rr;rHTFr)r+r,archgarch_supports_archgroupsrrrs      z)get_darwin_arches.._supports_arch)Zfat)rIrK)Zintel)rHrI)Zfat64)rHrJ)Zfat32)rHrIrKZ universal)rappend)r+r,rRarchesrrrrget_darwin_archess%    rc CsFg}|dd}t|dddD] }|dtt||fq |S)Nr!)rangerr#r$r%)r&versionsr+r,rrr!get_all_minor_versions_as_strings>s  rFcCsDg}|dkrt}t|}|p"t}g}|p0t}|rD|g|dd<t}tD]$} | drP|| dddqP| t t || d|s|pt } | d\} } } | d r>t| }|r6|\}}}}d ||}g}ttt|dD]0}tt|||D]}| |||fqqn| g}n| d kr~| g}| d kr| d | | | d| | n| d kr| d| | g}nn|dkrg}tr| d | | tr| d | | tr| d| | | | n| g}|D].}|D]"} | d||df|| fqq |ddD]F}|dkr\q|D]*}|D]} | d||f|| fqhq`qH|D]"} | d|ddd| fq| d||dfddf| d||ddfddft|D]B\}}| d|fddf|dkr| d|dddfq|S)acReturn a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. Nrz.abir>r"r*Znoner?Zmacosxz {}_{}_%i_%sZ manylinux2014>i686rHZ manylinux2010Z manylinux1z%s%s>3130zpy%sany)r(rr rDsetrraddr@extendsortedlistrrP partition _osx_arch_patmatchrrreversedrintrrr}r{ enumerate)rZnoarchrrBrCZ supportedr&ZabisZabi3ssuffixrZ arch_prefixZarch_sepZ arch_suffixrnamer+r,Z actual_archZtplrr:aversionirrr get_supportedHs~              $ $   r)TT)NFNNN)4__doc__Z __future__rZdistutils.utilrNZloggingrrerr r collectionsrZpip._internal.utils.glibcruZpip._internal.utils.compatrZpip._internal.utils.typingrtypingrrrr r r r r%Z Pep425TagZ getLogger__name__r.compilerrr r'r)r(r-r2rDrFrPror{r}rrrrZimplementation_tagrrrrsP    $     !?  y__pycache__/index.cpython-38.opt-1.pyc000064400000061246152347654150013477 0ustar00U .e@s(dZddlmZddlZddlZddlmZddlmZddl m Z ddl m Z mZmZmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*e$rddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3ddl m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>e3e2de2e?e@ffZAe2e?e?e?e4eAe/e?fZBdddgZCeDeEZFd1d!d"ZGGd#d$d$eHZId%d&ZJGd'd(d(eHZKGd)ddeHZLGd*d+d+eHZMGd,ddeHZNd-d.ZOd/d0ZPdS)2z!Routines related to PyPI, indexes)absolute_importN) specifiers)canonicalize_name)parse)BestVersionAlreadyInstalledDistributionNotFoundInvalidWheelFilenameUnsupportedWheel)InstallationCandidate) FormatControl)Link)SelectionPreferences) TargetPython)WHEEL_EXTENSION) indent_log) build_netloc)check_requires_python)MYPY_CHECK_RUNNING)SUPPORTED_EXTENSIONS) url_to_path)Wheel) FrozenSetIterableListOptionalSetTextTupleUnion) _BaseVersion) LinkCollector) SearchScope)InstallRequirement) Pep425Tag)Hashesr BestCandidateResult PackageFinderFcCs~zt|j|d}Wn&tjk r8td|j|YnBX|szdtt|}|shtd||j|dStd||j|dS)aa Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. ) version_infoz2Ignoring invalid Requires-Python (%r) for link: %s.z4Link requires a different Python (%s not in: %r): %sFzBIgnoring failed Requires-Python check (%s not in: %r) for link: %sT) rZrequires_pythonrZInvalidSpecifierloggerdebugjoinmapstr)linkr(ignore_requires_pythonZ is_compatibleversionr%r%7/usr/lib/python3.8/site-packages/pip/_internal/index.py_check_link_requires_python;s8  r3c@s,eZdZdZedZdddZddZdS) LinkEvaluatorzD Responsible for evaluating links for a particular project. z-py([123]\.?[0-9]?)$NcCs4|dkr d}||_||_||_||_||_||_dS)a :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. NF) _allow_yanked_canonical_name_ignore_requires_python_formats_target_python project_name)selfr:canonical_nameformats target_python allow_yankedr0r%r%r2__init__rszLinkEvaluator.__init__c Csd}|jr(|js(|jpd}dd|fS|jr<|j}|j}n|\}}|sPdS|tkrddd|fSd|jkr|t krd|j }d|fSd |j kr|d krd S|t kr,zt |j }Wntk rYd SXt|j|jkrd |j }d|fS|j}||s&|}dd|}d|fS|j}d|jkrP|t krPdd|j fS|sbt||j}|svdd|j fS|j|} | r|d| }| d} | |jjkrdSt||jj|j d} | sdSt!"d||d|fS)aG Determine whether a link is a candidate for installation. :return: A tuple (is_candidate, result), where `result` is (1) a version string if `is_candidate` is True, and (2) if `is_candidate` is False, an optional string to log the reason the link fails to qualify. N Fzyanked for reason: {})Fz not a filezunsupported archive format: %sZbinaryzNo binaries permitted for %sZmacosx10z.zip)Fz macosx10 one)Fzinvalid wheel filenamezwrong project name (not %s)z"none of the wheel's tags match: {}, sourcezNo sources permitted for %szMissing project version for %s)FzPython version is incorrect)r(r0)FNzFound link %s, version: %sT)# is_yankedr5 yanked_reasonformat egg_fragmentextsplitextrr8rr:pathrfilenamerrnamer6r9get_tags supportedZget_formatted_file_tagsr,r1_extract_version_from_fragment_py_version_researchstartgroup py_versionr3Zpy_version_infor7r*r+) r;r/r1reasonZegg_inforIwheelsupported_tagsZ file_tagsmatchrUZsupports_pythonr%r%r2 evaluate_linksx            zLinkEvaluator.evaluate_link)N) __name__ __module__ __qualname____doc__recompilerQr@rZr%r%r%r2r4fs  &r4c Cs|stdt||t|Sg}g}d}|D]>}|j}|js@n"|j|drV|d7}n ||q.||q.|rx|}nt|}t|t|krd} n dt|d dd |D} td t|||j |t||| |S) a Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). zJGiven no hashes to check %s links for project %r: discarding no candidatesr)hashesrDzdiscarding no candidateszdiscarding {} non-matches: {}z css|]}t|jVqdSN)r.r/.0 candidater%r%r2 +sz*filter_unallowed_hashes..zPChecked %s links for project %r against %s hashes (%s matches, %s no digest): %s) r*r+lenlistr/Zhas_hashis_hash_allowedappendrGr,Z digest_count) candidatesrar:Zmatches_or_no_digestZ non_matchesZ match_countrer/ZfilteredZdiscard_messager%r%r2filter_unallowed_hashessL      rlc@seZdZdZdddZdS)CandidatePreferenceszk Encapsulates some of the preferences for filtering and sorting InstallationCandidate objects. FcCs||_||_dS)zR :param allow_all_prereleases: Whether to allow all pre-releases. N)allow_all_prereleases prefer_binary)r;rornr%r%r2r@Cs zCandidatePreferences.__init__N)FF)r[r\r]r^r@r%r%r%r2rm<srmc@s(eZdZdZddZddZddZdS) r&zA collection of candidates, returned by `PackageFinder.find_best_candidate`. This class is only intended to be instantiated by CandidateEvaluator's `compute_best_candidate()` method. cCs |dkr n||_||_||_dS)a :param candidates: A sequence of all available candidates found. :param applicable_candidates: The applicable candidates. :param best_candidate: The most preferred candidate found, or None if no applicable candidates were found. N)_applicable_candidates _candidatesbest_candidater;rkapplicable_candidatesrrr%r%r2r@Ws zBestCandidateResult.__init__cCs t|jS)z(Iterate through all candidates. )iterrqr;r%r%r2iter_allpszBestCandidateResult.iter_allcCs t|jS)z3Iterate through the applicable candidates. )rurprvr%r%r2iter_applicablevsz#BestCandidateResult.iter_applicableN)r[r\r]r^r@rwrxr%r%r%r2r&Psc@sHeZdZdZedddZdddZdd Zd d Zd d Z ddZ dS)CandidateEvaluatorzm Responsible for filtering and sorting candidates for installation based on what tags are valid. NFcCs:|dkrt}|dkrt}|}|||||||dS)aCreate a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :param hashes: An optional collection of allowed hashes. N)r:rX specifierrornra)rrZ SpecifierSetrN)clsr:r>rornrzrarXr%r%r2createszCandidateEvaluator.createcCs(||_||_||_||_||_||_dS)z :param supported_tags: The PEP 425 tags supported by the target Python in order of preference (most preferred first). N)_allow_all_prereleases_hashes_prefer_binary _project_name _specifier_supported_tags)r;r:rXrzrornrar%r%r2r@s zCandidateEvaluator.__init__csV|jpd}|j}dd|jdd|D|dDfdd|D}t||j|jd S) zM Return the applicable candidates from a list of candidates. NcSsh|] }t|qSr%)r.)rdvr%r%r2 sz?CandidateEvaluator.get_applicable_candidates..css|]}t|jVqdSrbr.r1rdcr%r%r2rfsz?CandidateEvaluator.get_applicable_candidates..)Z prereleasescsg|]}t|jkr|qSr%rrZversionsr%r2 sz@CandidateEvaluator.get_applicable_candidates..)rkrar:)r}rfilterrlr~r)r;rkZallow_prereleasesrzrtr%rr2get_applicable_candidatess   z,CandidateEvaluator.get_applicable_candidatesc Cs|j}t|}d}d}|j}|jrt|j}||sDtd|j|jrNd}| | }|j dk rt d|j } | } t| d| df}n| }t||j} dt|j} | | ||j||fS)a) Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal r%rzB%s is not a supported wheel for this platform. It can't be sorted.rDNz ^(\d+)(.*)$)rrgr/Zis_wheelrrLrOr rZsupport_index_min build_tagr_rYgroupsintrir~rEr1) r;reZ valid_tagsZ support_numrZbinary_preferencer/rWZprirYZbuild_tag_groupsZhas_allowed_hashZ yank_valuer%r%r2 _sort_keys<    zCandidateEvaluator._sort_keycCsH|sdSt||jd}|j}|jrD|jp*d}dj||d}t||S)zy Return the best candidate per the instance's sort order, or None if no candidate is acceptable. NkeyrAzqThe candidate selected for download or install is a yanked version: {candidate} Reason for being yanked: {reason})rerV)maxrr/rErFrGr*Zwarning)r;rkrrr/rVmsgr%r%r2sort_best_candidates   z&CandidateEvaluator.sort_best_candidatecCs"||}||}t|||dS)zF Compute and return a `BestCandidateResult` instance. )rtrr)rrr&rsr%r%r2compute_best_candidate<s  z)CandidateEvaluator.compute_best_candidate)NFFNN)FFN) r[r\r]r^ classmethodr|r@rrrrr%r%r%r2ry}s  ) $<ryc@seZdZdZd&ddZed'ddZeddZej d dZed d Z ed d Z eddZ eddZ ddZddZddZddZddZddZddZd(d d!Zd)d"d#Zd$d%ZdS)*r'zThis finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. NcCsP|dkrt}|pttt}||_||_||_||_||_||_t|_ dS)a This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. N) rmr setr5_candidate_prefsr7_link_collectorr9format_control _logged_links)r;link_collectorr>r?rcandidate_prefsr0r%r%r2r@VszPackageFinder.__init__cCs8|dkrt}t|j|jd}|||||j|j|jdS)afCreate a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. N)rorn)rrr>r?rr0)rrmrornr?rr0)r{rZselection_prefsr>rr%r%r2r|~szPackageFinder.createcCs|jjSrbr search_scopervr%r%r2rszPackageFinder.search_scopecCs ||j_dSrbr)r;rr%r%r2rscCs|jjSrb)r find_linksrvr%r%r2rszPackageFinder.find_linkscCs|jjSrb)r index_urlsrvr%r%r2rszPackageFinder.index_urlsccs|jjjD]}t|Vq dSrb)rZsessionZpip_trusted_originsr)r;Z host_portr%r%r2 trusted_hostsszPackageFinder.trusted_hostscCs|jjSrbrrnrvr%r%r2rnsz#PackageFinder.allow_all_prereleasescCs d|j_dS)NTrrvr%r%r2set_allow_all_prereleasessz'PackageFinder.set_allow_all_prereleasescCs.t|}|j|}t||||j|j|jdS)N)r:r<r=r>r?r0)rrZget_allowed_formatsr4r9r5r7)r;r:r<r=r%r%r2make_link_evaluators z!PackageFinder.make_link_evaluatorcCsPgg}}t}|D]2}||kr|||jr<||q||q||S)z Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates )raddrHrj)r;linksZeggsZno_eggsseenr/r%r%r2 _sort_linkss    zPackageFinder._sort_linkscCs(||jkr$td|||j|dS)NzSkipping link: %s: %s)rr*r+r)r;r/rVr%r%r2_log_skipped_links zPackageFinder._log_skipped_linkcCs<||\}}|s(|r$|j||ddSt|j|t|dS)z If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. )rVN)Zprojectr/r1)rZrr r:r.)r;link_evaluatorr/Z is_candidateresultr%r%r2get_install_candidatesz#PackageFinder.get_install_candidatecCs6g}||D]"}|||}|dk r||q|S)zU Convert links that are candidates to InstallationCandidate objects. N)rrrj)r;rrrkr/rer%r%r2evaluate_linkss   zPackageFinder.evaluate_linksc Cs|j|}||}|j||jd}g}|jD]>\}}td|t |j||d}| |W5QRXq4|j||j d} | r| j ddtdd dd| D| ||S) aFind all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. )rzAnalyzing links from page %sT)reversezLocal files found: %srBcSsg|]}t|jjqSr%)rr/Zurlrcr%r%r2r2sz5PackageFinder.find_all_candidates..)rZ collect_linksrrrZpagesitemsr*r+rextendfilessortr,) r;r:Zcollected_linksrZfind_links_versionsZ page_versionsZpage_urlZ page_linksZ new_versionsZ file_versionsr%r%r2find_all_candidates s8      z!PackageFinder.find_all_candidatescCs"|j}tj||j|j|j||dS)z3Create a CandidateEvaluator object to use. )r:r>rornrzra)rryr|r9rorn)r;r:rzrarr%r%r2make_candidate_evaluator;s z&PackageFinder.make_candidate_evaluatorcCs$||}|j|||d}||S)aFind matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. )r:rzra)rrr)r;r:rzrarkZcandidate_evaluatorr%r%r2find_best_candidateNs z!PackageFinder.find_best_candidatec Cs|jdd}|j|j|j|d}|j}d}|jdk r@t|jj}dd}|dkrz|dkrzt d||| t d|d}|r|dks|j|krd }|s|dk r|rt d |nt d ||jdS|rt d ||| tt d |j|| |jS)zTry to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise F)Ztrust_internet)rzraNcSs dtdd|DtdpdS)NrBcSsh|]}t|jqSr%rrr%r%r2r}szKPackageFinder.find_requirement.._format_versions..rZnone)r,sorted parse_version)Z cand_iterr%r%r2_format_versionsws  z8PackageFinder.find_requirement.._format_versionszNCould not find a version that satisfies the requirement %s (from versions: %s)z%No matching distribution found for %sTzLExisting installed version (%s) is most up-to-date and satisfies requirementzUExisting installed version (%s) satisfies requirement (most up-to-date version is %s)z=Installed version (%s) is most up-to-date (past versions: %s)z)Using version %s (newest of versions: %s))rarrMrzrrZ satisfied_byrr1r*Zcriticalrwrr+rxrr/) r;ZreqZupgraderaZbest_candidate_resultrrZinstalled_versionrZbest_installedr%r%r2find_requirementesh        zPackageFinder.find_requirement)NNN)N)NN)NN)r[r\r]r^r@rr|propertyrsetterrrrrnrrrrrrrrrrr%r%r%r2r'OsD  (         1  cCsLt|D].\}}|dkrqt|d||kr|Sqtd||dS)aFind the separator's index based on the package's canonical name. :param fragment: A + filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 -Nz{} does not match {}) enumerater ValueErrorrG)fragmentr<irr%r%r2_find_name_version_seps  rcCsBzt||d}Wntk r(YdSX||d}|s>dS|S)zParse the version string from a + filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. rDN)rr)rr<Z version_startr1r%r%r2rPs  rP)F)Qr^Z __future__rZloggingr_Zpip._vendor.packagingrZpip._vendor.packaging.utilsrZpip._vendor.packaging.versionrrZpip._internal.exceptionsrrrr Zpip._internal.models.candidater Z#pip._internal.models.format_controlr Zpip._internal.models.linkr Z$pip._internal.models.selection_prefsr Z"pip._internal.models.target_pythonrZpip._internal.utils.filetypesrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.packagingrZpip._internal.utils.typingrZpip._internal.utils.unpackingrZpip._internal.utils.urlsrZpip._internal.wheelrtypingrrrrrrrrrZpip._internal.collectorr Z!pip._internal.models.search_scoper!Zpip._internal.reqr"Zpip._internal.pep425tagsr#Zpip._internal.utils.hashesr$rr.ZBuildTagZCandidateSortingKey__all__Z getLoggerr[r*r3objectr4rlrmr&ryr'rrPr%r%r%r2s^                 (         + K-Sh__pycache__/pyproject.cpython-38.opt-1.pyc000064400000006076152347654150014407 0ustar00U .eZ@sddlmZddlZddlZddlZddlmZmZddlm Z ddl m Z e rhddl m Z mZmZmZddZd d Zd d ZdS) )absolute_importN)pytomlsix)InstallationError)MYPY_CHECK_RUNNING)AnyTupleOptionalListcCst|totdd|DS)Ncss|]}t|tjVqdS)N) isinstancerZ string_types).0itemr;/usr/lib/python3.8/site-packages/pip/_internal/pyproject.py sz"_is_list_of_str..)r listall)objrrr_is_list_of_strs rcCs2tj|d}tjr.t|tjr.|t }|S)Nzpyproject.toml) ospathjoinrZPY2r Z text_typeencodesysgetfilesystemencoding)Zunpacked_source_directoryrrrrmake_pyproject_pathsrc Cs<tj|}tj|}|rLtj|dd}t|}W5QRX|d}nd}|rr|sr|dk rl|sltdd}n<|rd|kr|dk r|std |dd}n |dkr|}|sdS|dkrd d gd d }d } d|krt| j |dd|d} t | st| j |dd|d} g} | dkr2d } d d g} | | | fS)aLoad the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment ) zutf-8)encodingz build-systemNzIDisabling PEP 517 processing is invalid: project does not have a setup.pyT build-backendzbDisabling PEP 517 processing is invalid: project specifies a build backend of {} in pyproject.tomlzsetuptools>=40.8.0Zwheelz setuptools.build_meta:__legacy__)requiresrzO{package} has a pyproject.toml file that does not comply with PEP 518: {reason}rz]it has a 'build-system' table but not 'build-system.requires' which is mandatory in the table)packagereasonz1'build-system.requires' is not a list of strings.) rrisfileioopenrloadgetrformatr) Z use_pep517Zpyproject_tomlZsetup_pyZreq_nameZ has_pyprojectZ has_setupfZpp_tomlZ build_systemZerror_templaterZbackendZcheckrrrload_pyproject_toml#sb          r()Z __future__rr"rrZ pip._vendorrrZpip._internal.exceptionsrZpip._internal.utils.typingrtypingrrr r rrr(rrrrs    __pycache__/exceptions.cpython-38.opt-1.pyc000064400000030242152347654150014541 0ustar00U .e(@sdZddlmZddlmZmZmZddlmZddl m Z e rdddl m Z ddl mZddlmZGd d d eZGd d d eZGd ddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdd d eZGd!d"d"eZGd#d$d$eZGd%d&d&eZ Gd'd(d(e Z!Gd)d*d*e Z"Gd+d,d,e Z#Gd-d.d.e Z$Gd/d0d0e Z%Gd1d2d2eZ&Gd3d4d4eZ'd5S)6z"Exceptions used throughout package)absolute_import)chaingroupbyrepeat) iteritems)MYPY_CHECK_RUNNING)Optional) Distribution)InstallRequirementc@seZdZdZdS)PipErrorzBase pip exceptionN__name__ __module__ __qualname____doc__rrnz$HashErrors.__str__..)keycSs|jSr' __class__r,rrrr.or/css|]}|VqdSr')body.0r-rrr qsz%HashErrors.__str__.. )r(sortrr)headextendjoin)rlinesclsZ errors_of_clsrrrrls zHashErrors.__str__cCs t|jSr')boolr(rrrr __nonzero__uszHashErrors.__nonzero__cCs|Sr')r?rrrr__bool__xszHashErrors.__bool__N) r rrrrr)rr?r@rrrrr&cs  r&c@s0eZdZdZdZdZddZddZdd ZdS) HashErrora A failure to verify a package against known-good hashes :cvar order: An int sorting hash exception classes by difficulty of recovery (lower being harder), so the user doesn't bother fretting about unpinned packages when he has deeper issues, like VCS dependencies, to deal with. Also keeps error reports in a deterministic order. :cvar head: A section heading for display above potentially many exceptions of this kind :ivar req: The InstallRequirement that triggered this error. This is pasted on after the exception is instantiated, because it's not typically available earlier. NcCs d|S)a)Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with populate_link() having already been called z %s)_requirement_namerrrrr3s zHashError.bodycCsd|j|fS)Nz%s %s)r9r3rrrrrszHashError.__str__cCs|jrt|jSdS)zReturn a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers unknown package)reqstrrrrrrCszHashError._requirement_name) r rrrrEr9r3rrCrrrrrA|s  rAc@seZdZdZdZdZdS)VcsHashUnsupporteduA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.rzlCan't verify hashes for these requirements because we don't have a way to hash version control repositories:Nr rrrr+r9rrrrrGsrGc@seZdZdZdZdZdS)DirectoryUrlHashUnsupportedrHzUCan't verify hashes for these file:// requirements because they point to directories:NrIrrrrrJsrJc@s(eZdZdZdZdZddZddZdS) HashMissingz2A hash was needed for a requirement but is absent.awHashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If you did not enable --require-hashes manually, note that it turns on automatically when any package has a hash.)cCs ||_dS)zq :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded N) gotten_hash)rrNrrrrszHashMissing.__init__cCsHddlm}d}|jr4|jjr&|jjn t|jdd}d|p.hash_then_orc3s|]}dt|fVqdS)z Expected %s %sN)nextr4prefixrrr6sz0HashMismatch._hash_comparison..z Got %s r7)rrVr:r)rWZ hexdigestr;)rrZr<rYZ expectedsrr\rrXs  zHashMismatch._hash_comparisonN) r rrrr+r9rr3rXrrrrrTs  rTc@seZdZdZdS)UnsupportedPythonVersionzMUnsupported python version according to Requires-Python package metadata.Nr rrrrr^sr^cs*eZdZdZdfdd ZddZZS) !ConfigurationFileCouldNotBeLoadedz=When there are errors while loading a configuration file could not be loadedNcs&tt||||_||_||_dSr')superr_rreasonfnamer*)rrbrcr*r1rrr(sz*ConfigurationFileCouldNotBeLoaded.__init__cCs4|jdk rd|j}nd|jj}d|j|S)Nz in {}.z. {} zConfiguration file {}{})rcrr*messagerb)rZ message_partrrrr.s z)ConfigurationFileCouldNotBeLoaded.__str__)r`NN)r rrrrr __classcell__rrr1rr_$sr_N)(rZ __future__r itertoolsrrrZpip._vendor.sixrZpip._internal.utils.typingrtypingrZpip._vendor.pkg_resourcesr Zpip._internal.req.req_installr Exceptionr rrrrrrr r!r"r#r$r%r&rArGrJrLrRrTr^r_rrrrs<      ,  % 7__pycache__/pyproject.cpython-38.pyc000064400000006154152347654150013445 0ustar00U .eZ@sddlmZddlZddlZddlZddlmZmZddlm Z ddl m Z e rhddl m Z mZmZmZddZd d Zd d ZdS) )absolute_importN)pytomlsix)InstallationError)MYPY_CHECK_RUNNING)AnyTupleOptionalListcCst|totdd|DS)Ncss|]}t|tjVqdS)N) isinstancerZ string_types).0itemr;/usr/lib/python3.8/site-packages/pip/_internal/pyproject.py sz"_is_list_of_str..)r listall)objrrr_is_list_of_strs rcCs2tj|d}tjr.t|tjr.|t }|S)Nzpyproject.toml) ospathjoinrZPY2r Z text_typeencodesysgetfilesystemencoding)Zunpacked_source_directoryrrrrmake_pyproject_pathsrc CsVtj|}tj|}|rLtj|dd}t|}W5QRX|d}nd}|rr|sr|dk rl|sltdd}n<|rd|kr|dk r|std |dd}n |dkr|}|dk st |sdS|dkrd d gd d }|dk st d } d|krt| j |dd|d} t | s(t| j |dd|d} g} | dkrLd } d d g} | | | fS)aLoad the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment ) zutf-8)encodingz build-systemNzIDisabling PEP 517 processing is invalid: project does not have a setup.pyT build-backendzbDisabling PEP 517 processing is invalid: project specifies a build backend of {} in pyproject.tomlzsetuptools>=40.8.0Zwheelz setuptools.build_meta:__legacy__)requiresrzO{package} has a pyproject.toml file that does not comply with PEP 518: {reason}rz]it has a 'build-system' table but not 'build-system.requires' which is mandatory in the table)packagereasonz1'build-system.requires' is not a list of strings.) rrisfileioopenrloadgetrformatAssertionErrorr) Z use_pep517Zpyproject_tomlZsetup_pyZreq_nameZ has_pyprojectZ has_setupfZpp_tomlZ build_systemZerror_templaterZbackendZcheckrrrload_pyproject_toml#sf             r))Z __future__rr"rrZ pip._vendorrrZpip._internal.exceptionsrZpip._internal.utils.typingrtypingrrr r rrr)rrrrs    __pycache__/collector.cpython-38.opt-1.pyc000064400000033422152347654150014351 0ustar00U .eWF@s dZddlZddlZddlZddlZddlZddlmZddlm Z m Z ddl m Z ddl mZmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZm Z ddl!m"Z"m#Z#erDddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5e/j6j7j8Z9e)e:e:fZ;eddZ?ddZ@GdddeAZBddZCGdddeAZDddZEdd ZFd!d"ZGd#d$ZHd%d&ZId'd(ZJd)d*ZKGd+d,d,eLZMdd6d7ZRGd8d9d9eLZSGd:d;d;eLZTdS)?zM The main purpose of this module is to expose LinkCollector.collect_links(). N) OrderedDict)html5librequests)unescape) HTTPError RetryErrorSSLError)parse)requestLink)ARCHIVE_EXTENSIONS)redact_auth_from_url)MYPY_CHECK_RUNNING) path_to_url url_to_path)is_urlvcs) CallableDictIterableListMutableMappingOptionalSequenceTupleUnion)Response) SearchScope) PipSessioncCs6tjD]*}||r|t|dkr|SqdS)zgLook for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. z+:N)rZschemeslower startswithlen)urlschemer%;/usr/lib/python3.8/site-packages/pip/_internal/collector.py_match_vcs_scheme/s  r'cCs(t|j}tD]}||rdSqdS)z2Return whether the URL looks like an archive. TF)r filenamer endswith)r#r(Zbad_extr%r%r&_is_url_like_archive;s   r*cseZdZfddZZS)_NotHTMLcs"tt|||||_||_dSN)superr+__init__ content_type request_desc)selfr/r0 __class__r%r&r.Gsz_NotHTML.__init__)__name__ __module__ __qualname__r. __classcell__r%r%r2r&r+Fsr+cCs.|jdd}|ds*t||jjdS)zCheck the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. Content-Type text/htmlN)headersgetr r!r+r method)responser/r%r%r&_ensure_html_headerNsr?c@s eZdZdS)_NotHTTPN)r4r5r6r%r%r%r&r@Ysr@cCsDt|\}}}}}|dkr"t|j|dd}|t|dS)zSend a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. >httphttpsT)Zallow_redirectsN) urllib_parseZurlsplitr@headraise_for_statusr?)r#sessionr$netlocpathZqueryZfragmentrespr%r%r&_ensure_html_response]s rJcCsLt|rt||dtdt||j|dddd}|t||S)aAccess an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. rFzGetting page %sr:z max-age=0)ZAcceptz Cache-Control)r;)r*rJloggerdebugrr<rEr?)r#rFrIr%r%r&_get_html_responsens rNcCs2|r.d|kr.t|d\}}d|kr.|dSdS)zBDetermine if we have any encoding information in our headers. r8charsetN)cgiZ parse_header)r;r/Zparamsr%r%r&_get_encoding_from_headerss  rQcCs.|dD]}|d}|dk r |Sq |S)aDetermine the HTML document's base URL. This looks for a ```` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. z.//basehrefN)findallr<)documentpage_urlbaserRr%r%r&_determine_base_urls   rWcCsPt|}|jdkr(tt|j}ntjt|jdd}t |j |dS)zMakes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).r9z/@)Zsafe)rH) rCurlparserGurllib_requestZ pathname2url url2pathnamerHZquoteZunquoteZ urlunparse_replace)r#resultrHr%r%r& _clean_links   r]cCsf|d}|sdStt||}|d}|r8t|nd}|d}|rRt|}t||||d}|S)zJ Convert an anchor element in a simple repository page to a Link. rRNzdata-requires-pythonz data-yanked)Z comes_fromZrequires_python yanked_reason)r<r]rCurljoinrr )anchorrUbase_urlrRr#Z pyrequirer^linkr%r%r&_create_link_from_elements   rcccsVtj|j|jdd}|j}t||}|dD]"}t|||d}|dkrJq.|Vq.dS)zP Parse an HTML document, and yield its anchor elements as Link objects. F)Ztransport_encodingZnamespaceHTMLElementsz.//a)rUraN)rr contentencodingr#rWrSrc)pagerTr#rar`rbr%r%r& parse_linkss  rgc@s eZdZdZddZddZdS)HTMLPagez'Represents one page, along with its URLcCs||_||_||_dS)z :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. N)rdrer#)r1rdrer#r%r%r&r.s zHTMLPage.__init__cCs t|jSr,)rr#r1r%r%r&__str__$szHTMLPage.__str__N)r4r5r6__doc__r.rjr%r%r%r&rhsrhcCs|dkrtj}|d||dS)Nz%Could not fetch URL %s: %s - skipping)rLrM)rbreasonmethr%r%r&_handle_get_page_fail(srncCst|j}t|j||jdS)N)rer#)rQr;rhrdr#)r>rer%r%r&_make_html_page3s roc Cs|dkrtd|jddd}t|}|r@td||dSt|\}}}}}}|dkrtj t |r| ds|d7}t|d}td |zt||d }WnDtk rtd |Yn,tk r}ztd ||j|jW5d}~XYntk r0}zt||W5d}~XYntk r\}zt||W5d}~XYntk r}z$d } | t|7} t|| tjdW5d}~XYn\tjk r}zt|d|W5d}~XYn*tjk rt|dYn Xt|SdS)Nz?_get_html_page() missing 1 required keyword argument: 'session'#rzCannot look at %s URL %sfile/z index.htmlz# file: URL is directory, getting %srKzQSkipping page %s because it looks like an archive, and cannot be checked by HEAD.z.sort_pathzfile:z)Path '{0}' is ignored: it is a directory.z:Url '%s' is ignored: it is neither a file nor a directory.zQUrl '%s' is ignored. It is either a non-existing path or lacks a specific scheme.)rvrHexistsr!rrwrealpathlistdirjoinrrLZwarningformatisfiler) locations expand_dirrr#Z is_local_pathZ is_file_urlrHitemr%rr&group_locationsxsF        rc@seZdZdZddZdS)CollectedLinksa Encapsulates all the Link objects collected by a call to LinkCollector.collect_links(), stored separately as-- (1) links from the configured file locations, (2) links from the configured find_links, and (3) a dict mapping HTML page url to links from that page. cCs||_||_||_dS)z :param files: Links from file locations. :param find_links: Links from find_links. :param pages: A dict mapping HTML page url to links from that page. Nr find_linkspages)r1rrrr%r%r&r.s zCollectedLinks.__init__N)r4r5r6rkr.r%r%r%r&rs rc@s4eZdZdZddZeddZddZdd Zd S) LinkCollectorz Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. cCs||_||_dSr,) search_scoperF)r1rFrr%r%r&r.szLinkCollector.__init__cCs|jjSr,)rrrir%r%r&rszLinkCollector.find_linksccs,|D]"}t||jd}|dkr q|VqdS)zp Yields (page, page_url) from the given locations, skipping locations that have errors. rKN)r}rF)r1rlocationrfr%r%r& _get_pagess zLinkCollector._get_pagescsj}||}t|\}}tjdd\}}ddt||D}ddjD} fddtdd|Dd d|DD} t| } d t| |g} | D]} | d | qt d | i} | D]}tt|| |j<qt|| | d S)zFind all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. T)rcSsg|] }t|qSr%r .0r#r%r%r& sz/LinkCollector.collect_links..cSsg|]}t|dqS)z-fr rr%r%r&rscsg|]}j|r|qSr%)rFZis_secure_origin)rrbrir%r&r s css|]}t|VqdSr,r rr%r%r& sz.LinkCollector.collect_links..css|]}t|VqdSr,r rr%r%r&r sz,{} location(s) to search for versions of {}:z* {} r)rZget_index_urls_locationsrr itertoolschainrrr"rrLrMrrr~rgr#r)r1Z project_namerZindex_locationsZindex_file_locZ index_url_locZ fl_file_locZ fl_url_locZ file_linksZfind_link_linksZ url_locationslinesrbZ pages_linksrfr%rir& collect_linkssD       zLinkCollector.collect_linksN) r4r5r6rkr.propertyrrrr%r%r%r&rs    r)N)N)F)UrkrPrZloggingrrv collectionsrZ pip._vendorrrZpip._vendor.distlib.compatrZpip._vendor.requests.exceptionsrrrZpip._vendor.six.moves.urllibr rCr rYZpip._internal.models.linkr Zpip._internal.utils.filetypesr Zpip._internal.utils.miscrZpip._internal.utils.typingrZpip._internal.utils.urlsrrZpip._internal.vcsrrtypingrrrrrrrrrZxml.etree.ElementTreeZxmlZpip._vendor.requestsrZ!pip._internal.models.search_scoperZpip._internal.network.sessionrZetreeZ ElementTreeZElementZ HTMLElementrxZResponseHeadersZ getLoggerr4rLr'r* Exceptionr+r?r@rJrNrQrWr]rcrgobjectrhrnror}rrrrr%r%r%r&s^        ,         3    6 ;__pycache__/main.cpython-38.opt-1.pyc000064400000002371152347654150013306 0ustar00U .eO@sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZeeZd d d ZdS) z Primary application entrypoint. )absolute_importN) autocomplete) parse_command)create_command)PipError) deprecationc Cs|dkrtjdd}ttzt|\}}WnJtk r~}z,tjd|tjt j t dW5d}~XYnXzt t jdWn0t jk r}ztd|W5d}~XYnXt|d|kd}||S)Nz ERROR: %sz%Ignoring error %s when setting localez --isolated)isolated)sysargvrZinstall_warning_loggerrrrstderrwriteoslinesepexitlocale setlocaleLC_ALLErrorloggerdebugrmain)argsZcmd_nameZcmd_argsexceZcommandr6/usr/lib/python3.8/site-packages/pip/_internal/main.pyrs r)N)__doc__Z __future__rrZloggingrr Z pip._internal.cli.autocompletionrZpip._internal.cli.main_parserrZpip._internal.commandsrZpip._internal.exceptionsrZpip._internal.utilsrZ getLogger__name__rrrrrrs       __pycache__/self_outdated_check.cpython-38.pyc000064400000012622152347654150015402 0ustar00U .e@s^ddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZmZmZdd lmZm Z m!Z!dd l"m#Z#ddl$m%Z%e%rddl&Z&ddl&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,ddl-m.Z.dZ/e0e1Z2dddZ3ddZ4Gddde5Z6ddZ7ddZ8dS))absolute_importN) pkg_resources)version) ensure_binary) LinkCollector) PackageFinder) SearchScope)SelectionPreferences)WINDOWS)adjacent_tmp_filecheck_path_ownerreplace) ensure_dirget_installed_versionredact_auth_from_url) get_installer)MYPY_CHECK_RUNNING)Values)AnyDictTextUnion) PipSessionz%Y-%m-%dT%H:%M:%SZFcCs`|jg|j}|jr8|s8tdddd|Dg}|jp@g}tj||d}t ||d}|S)z :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. zIgnoring indexes: %s,css|]}t|VqdSN)r).0ZurlrE/usr/lib/python3.8/site-packages/pip/_internal/self_outdated_check.py @sz&make_link_collector..) find_links index_urls)session search_scope) Z index_urlZextra_index_urlsZno_indexloggerdebugjoinrrcreater)r!optionssuppress_no_indexr rr"link_collectorrrrmake_link_collector1s    r*cCst|}t|}|Sr)rhashlibZsha224Z hexdigest)keyZ key_bytesnamerrr_get_statefile_namePsr.c@s(eZdZddZeddZddZdS)SelfCheckStatec Csni|_d|_|rjtj|dt|j|_z&t|j}t ||_W5QRXWnt t t fk rhYnXdS)NZ selfcheck) statestatefile_pathospathr%r.r,openjsonloadIOError ValueErrorKeyError)self cache_dirZ statefilerrr__init__Xs zSelfCheckState.__init__cCstjSr)sysprefix)r:rrrr,jszSelfCheckState.keyc Cs|js dSttj|js dSttj|j|j|t|d}t j |ddd}t |j}| t |W5QRXzt|j|jWntk rYnXdS)N)r, last_check pypi_versionT)r:)Z sort_keysZ separators)r1r r2r3dirnamerr,strftimeSELFCHECK_DATE_FMTr5dumpsr writerr r-OSError)r:r@ current_timer0textfrrrsavens  zSelfCheckState.saveN)__name__ __module__ __qualname__r<propertyr,rKrrrrr/Ws r/cCs6zt|}dt|kWStjk r0YdSXdS)zChecks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. pipFN)rZget_distributionrZDistributionNotFound)ZpkgZdistrrrwas_installed_by_pips  rQcCsXtd}|sdSt|}d}zt|jd}tj}d|jkrzd|jkrztj|jdt }|| dkrz|jd}|dkrt ||dd}t d d d } t j|| d } | dj} | dkrWdSt| j}|||t|} || ko|j| jkotd} | s WdStrd }nd}td |||Wn$tk rRtjdddYnXdS)zCheck for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. rPN)r;r?r@i: T)r'r(F)Z allow_yankedZallow_all_prereleases)r)selection_prefsz python -m pipzYou are using pip version %s; however, version %s is available. You should consider upgrading via the '%s install --upgrade pip' command.z5There was an error checking the latest version of pip)exc_info)rpackaging_versionparser/r;datetimeZutcnowr0strptimerDZ total_secondsr*r rr&Zfind_best_candidatebest_candidatestrrrKZ base_versionrQr r#Zwarning Exceptionr$)r!r'Zinstalled_versionZ pip_versionr@r0rHr?r)rRfinderrXZremote_versionZlocal_version_is_olderZpip_cmdrrrpip_self_version_checksp         r\)F)9Z __future__rrVr+r5ZloggingZos.pathr2r=Z pip._vendorrZpip._vendor.packagingrrTZpip._vendor.sixrZpip._internal.collectorrZpip._internal.indexrZ!pip._internal.models.search_scoperZ$pip._internal.models.selection_prefsr Zpip._internal.utils.compatr Zpip._internal.utils.filesystemr r r Zpip._internal.utils.miscrrrZpip._internal.utils.packagingrZpip._internal.utils.typingrZoptparsertypingrrrrZpip._internal.network.sessionrrDZ getLoggerrLr#r*r.objectr/rQr\rrrrs>               ;__pycache__/exceptions.cpython-38.pyc000064400000030302152347654150013577 0ustar00U .e(@sdZddlmZddlmZmZmZddlmZddl m Z e rdddl m Z ddl mZddlmZGd d d eZGd d d eZGd ddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdd d eZGd!d"d"eZGd#d$d$eZGd%d&d&eZ Gd'd(d(e Z!Gd)d*d*e Z"Gd+d,d,e Z#Gd-d.d.e Z$Gd/d0d0e Z%Gd1d2d2eZ&Gd3d4d4eZ'd5S)6z"Exceptions used throughout package)absolute_import)chaingroupbyrepeat) iteritems)MYPY_CHECK_RUNNING)Optional) Distribution)InstallRequirementc@seZdZdZdS)PipErrorzBase pip exceptionN__name__ __module__ __qualname____doc__rrnz$HashErrors.__str__..)keycSs|jSr' __class__r,rrrr.or/css|]}|VqdSr')body.0r-rrr qsz%HashErrors.__str__.. )r(sortrr)headextendjoin)rlinesclsZ errors_of_clsrrrrls zHashErrors.__str__cCs t|jSr')boolr(rrrr __nonzero__uszHashErrors.__nonzero__cCs|Sr')r?rrrr__bool__xszHashErrors.__bool__N) r rrrrr)rr?r@rrrrr&cs  r&c@s0eZdZdZdZdZddZddZdd ZdS) HashErrora A failure to verify a package against known-good hashes :cvar order: An int sorting hash exception classes by difficulty of recovery (lower being harder), so the user doesn't bother fretting about unpinned packages when he has deeper issues, like VCS dependencies, to deal with. Also keeps error reports in a deterministic order. :cvar head: A section heading for display above potentially many exceptions of this kind :ivar req: The InstallRequirement that triggered this error. This is pasted on after the exception is instantiated, because it's not typically available earlier. NcCs d|S)a)Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with populate_link() having already been called z %s)_requirement_namerrrrr3s zHashError.bodycCsd|j|fS)Nz%s %s)r9r3rrrrrszHashError.__str__cCs|jrt|jSdS)zReturn a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers unknown package)reqstrrrrrrCszHashError._requirement_name) r rrrrEr9r3rrCrrrrrA|s  rAc@seZdZdZdZdZdS)VcsHashUnsupporteduA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.rzlCan't verify hashes for these requirements because we don't have a way to hash version control repositories:Nr rrrr+r9rrrrrGsrGc@seZdZdZdZdZdS)DirectoryUrlHashUnsupportedrHzUCan't verify hashes for these file:// requirements because they point to directories:NrIrrrrrJsrJc@s(eZdZdZdZdZddZddZdS) HashMissingz2A hash was needed for a requirement but is absent.awHashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If you did not enable --require-hashes manually, note that it turns on automatically when any package has a hash.)cCs ||_dS)zq :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded N) gotten_hash)rrNrrrrszHashMissing.__init__cCsHddlm}d}|jr4|jjr&|jjn t|jdd}d|p.hash_then_orc3s|]}dt|fVqdS)z Expected %s %sN)nextr4prefixrrr6sz0HashMismatch._hash_comparison..z Got %s r7)rrVr:r)rWZ hexdigestr;)rrZr<rYZ expectedsrr\rrXs  zHashMismatch._hash_comparisonN) r rrrr+r9rr3rXrrrrrTs  rTc@seZdZdZdS)UnsupportedPythonVersionzMUnsupported python version according to Requires-Python package metadata.Nr rrrrr^sr^cs*eZdZdZdfdd ZddZZS) !ConfigurationFileCouldNotBeLoadedz=When there are errors while loading a configuration file could not be loadedNcs&tt||||_||_||_dSr')superr_rreasonfnamer*)rrbrcr*r1rrr(sz*ConfigurationFileCouldNotBeLoaded.__init__cCsB|jdk rd|j}n|jdk s&td|jj}d|j|S)Nz in {}.z. {} zConfiguration file {}{})rcrr*AssertionErrormessagerb)rZ message_partrrrr.s  z)ConfigurationFileCouldNotBeLoaded.__str__)r`NN)r rrrrr __classcell__rrr1rr_$sr_N)(rZ __future__r itertoolsrrrZpip._vendor.sixrZpip._internal.utils.typingrtypingrZpip._vendor.pkg_resourcesr Zpip._internal.req.req_installr Exceptionr rrrrrrr r!r"r#r$r%r&rArGrJrLrRrTr^r_rrrrs<      ,  % 7__pycache__/__init__.cpython-38.opt-1.pyc000064400000000320152347654150014111 0ustar00U .eP@s ddlZdS)N)Z*pip._internal.utils.inject_securetransportZpiprr:/usr/lib/python3.8/site-packages/pip/_internal/__init__.pycache.py000064400000027731152347654150006207 0ustar00"""Cache Management """ import hashlib import json import logging import os from pip._vendor.packaging.tags import interpreter_name, interpreter_version from pip._vendor.packaging.utils import canonicalize_name from pip._internal.exceptions import InvalidWheelFilename from pip._internal.models.link import Link from pip._internal.models.wheel import Wheel from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url if MYPY_CHECK_RUNNING: from typing import Optional, Set, List, Any, Dict from pip._vendor.packaging.tags import Tag from pip._internal.models.format_control import FormatControl logger = logging.getLogger(__name__) def _hash_dict(d): # type: (Dict[str, str]) -> str """Return a stable sha224 of a dictionary.""" s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha224(s.encode("ascii")).hexdigest() class Cache(object): """An abstract class - provides cache directories for data from links :param cache_dir: The root of the cache. :param format_control: An object of FormatControl class to limit binaries being read from the cache. :param allowed_formats: which formats of files the cache should store. ('binary' and 'source' are the only allowed values) """ def __init__(self, cache_dir, format_control, allowed_formats): # type: (str, FormatControl, Set[str]) -> None super(Cache, self).__init__() assert not cache_dir or os.path.isabs(cache_dir) self.cache_dir = cache_dir or None self.format_control = format_control self.allowed_formats = allowed_formats _valid_formats = {"source", "binary"} assert self.allowed_formats.union(_valid_formats) == _valid_formats def _get_cache_path_parts_legacy(self, link): # type: (Link) -> List[str] """Get parts of part that must be os.path.joined with cache_dir Legacy cache key (pip < 20) for compatibility with older caches. """ # We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts def _get_cache_path_parts(self, link): # type: (Link) -> List[str] """Get parts of part that must be os.path.joined with cache_dir """ # We want to generate an url to use as our cache key, we don't want to # just re-use the URL because it might have other items in the fragment # and we don't care about those. key_parts = {"url": link.url_without_fragment} if link.hash_name is not None and link.hash is not None: key_parts[link.hash_name] = link.hash if link.subdirectory_fragment: key_parts["subdirectory"] = link.subdirectory_fragment # Include interpreter name, major and minor version in cache key # to cope with ill-behaved sdists that build a different wheel # depending on the python version their setup.py is being run on, # and don't encode the difference in compatibility tags. # https://github.com/pypa/pip/issues/7296 key_parts["interpreter_name"] = interpreter_name() key_parts["interpreter_version"] = interpreter_version() # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = _hash_dict(key_parts) # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts def _get_candidates(self, link, canonical_package_name): # type: (Link, str) -> List[Any] can_not_cache = ( not self.cache_dir or not canonical_package_name or not link ) if can_not_cache: return [] formats = self.format_control.get_allowed_formats( canonical_package_name ) if not self.allowed_formats.intersection(formats): return [] candidates = [] path = self.get_path_for_link(link) if os.path.isdir(path): for candidate in os.listdir(path): candidates.append((candidate, path)) # TODO remove legacy path lookup in pip>=21 legacy_path = self.get_path_for_link_legacy(link) if os.path.isdir(legacy_path): for candidate in os.listdir(legacy_path): candidates.append((candidate, legacy_path)) return candidates def get_path_for_link_legacy(self, link): # type: (Link) -> str raise NotImplementedError() def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached items in for link. """ raise NotImplementedError() def get( self, link, # type: Link package_name, # type: Optional[str] supported_tags, # type: List[Tag] ): # type: (...) -> Link """Returns a link to a cached item if it exists, otherwise returns the passed link. """ raise NotImplementedError() class SimpleWheelCache(Cache): """A cache of wheels for future installs. """ def __init__(self, cache_dir, format_control): # type: (str, FormatControl) -> None super(SimpleWheelCache, self).__init__( cache_dir, format_control, {"binary"} ) def get_path_for_link_legacy(self, link): # type: (Link) -> str parts = self._get_cache_path_parts_legacy(link) assert self.cache_dir return os.path.join(self.cache_dir, "wheels", *parts) def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) assert self.cache_dir # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts) def get( self, link, # type: Link package_name, # type: Optional[str] supported_tags, # type: List[Tag] ): # type: (...) -> Link candidates = [] if not package_name: return link canonical_package_name = canonicalize_name(package_name) for wheel_name, wheel_dir in self._get_candidates( link, canonical_package_name ): try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if canonicalize_name(wheel.name) != canonical_package_name: logger.debug( "Ignoring cached wheel %s for %s as it " "does not match the expected distribution name %s.", wheel_name, link, package_name, ) continue if not wheel.supported(supported_tags): # Built for a different python/arch/etc continue candidates.append( ( wheel.support_index_min(supported_tags), wheel_name, wheel_dir, ) ) if not candidates: return link _, wheel_name, wheel_dir = min(candidates) return Link(path_to_url(os.path.join(wheel_dir, wheel_name))) class EphemWheelCache(SimpleWheelCache): """A SimpleWheelCache that creates it's own temporary cache directory """ def __init__(self, format_control): # type: (FormatControl) -> None self._temp_dir = TempDirectory( kind=tempdir_kinds.EPHEM_WHEEL_CACHE, globally_managed=True, ) super(EphemWheelCache, self).__init__( self._temp_dir.path, format_control ) class CacheEntry(object): def __init__( self, link, # type: Link persistent, # type: bool ): self.link = link self.persistent = persistent class WheelCache(Cache): """Wraps EphemWheelCache and SimpleWheelCache into a single Cache This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. """ def __init__(self, cache_dir, format_control): # type: (str, FormatControl) -> None super(WheelCache, self).__init__( cache_dir, format_control, {'binary'} ) self._wheel_cache = SimpleWheelCache(cache_dir, format_control) self._ephem_cache = EphemWheelCache(format_control) def get_path_for_link_legacy(self, link): # type: (Link) -> str return self._wheel_cache.get_path_for_link_legacy(link) def get_path_for_link(self, link): # type: (Link) -> str return self._wheel_cache.get_path_for_link(link) def get_ephem_path_for_link(self, link): # type: (Link) -> str return self._ephem_cache.get_path_for_link(link) def get( self, link, # type: Link package_name, # type: Optional[str] supported_tags, # type: List[Tag] ): # type: (...) -> Link cache_entry = self.get_cache_entry(link, package_name, supported_tags) if cache_entry is None: return link return cache_entry.link def get_cache_entry( self, link, # type: Link package_name, # type: Optional[str] supported_tags, # type: List[Tag] ): # type: (...) -> Optional[CacheEntry] """Returns a CacheEntry with a link to a cached item if it exists or None. The cache entry indicates if the item was found in the persistent or ephemeral cache. """ retval = self._wheel_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=True) retval = self._ephem_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=False) return None pep425tags.py000064400000037105152347654150007036 0ustar00"""Generate and work with PEP 425 Compatibility Tags.""" from __future__ import absolute_import import distutils.util import logging import platform import re import sys import sysconfig import warnings from collections import OrderedDict import pip._internal.utils.glibc from pip._internal.utils.compat import get_extension_suffixes from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Tuple, Callable, List, Optional, Union, Dict, Set ) Pep425Tag = Tuple[str, str, str] logger = logging.getLogger(__name__) _osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)') def get_config_var(var): # type: (str) -> Optional[str] try: return sysconfig.get_config_var(var) except IOError as e: # Issue #1074 warnings.warn("{}".format(e), RuntimeWarning) return None def get_abbr_impl(): # type: () -> str """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl def version_info_to_nodot(version_info): # type: (Tuple[int, ...]) -> str # Only use up to the first two numbers. return ''.join(map(str, version_info[:2])) def get_impl_ver(): # type: () -> str """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1] def get_impl_tag(): # type: () -> str """ Returns the Tag for this specific implementation. """ return "{}{}".format(get_abbr_impl(), get_impl_ver()) def get_flag(var, fallback, expected=True, warn=True): # type: (str, Callable[..., bool], Union[bool, int], bool) -> bool """Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.""" val = get_config_var(var) if val is None: if warn: logger.debug("Config variable '%s' is unset, Python ABI tag may " "be incorrect", var) return fallback() return val == expected def get_abi_tag(): # type: () -> Optional[str] """Return the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).""" soabi = get_config_var('SOABI') impl = get_abbr_impl() abi = None # type: Optional[str] if not soabi and impl in {'cp', 'pp'} and hasattr(sys, 'maxunicode'): d = '' m = '' u = '' is_cpython = (impl == 'cp') if get_flag( 'Py_DEBUG', lambda: hasattr(sys, 'gettotalrefcount'), warn=is_cpython): d = 'd' if sys.version_info < (3, 8) and get_flag( 'WITH_PYMALLOC', lambda: is_cpython, warn=is_cpython): m = 'm' if sys.version_info < (3, 3) and get_flag( 'Py_UNICODE_SIZE', lambda: sys.maxunicode == 0x10ffff, expected=4, warn=is_cpython): u = 'u' abi = '%s%s%s%s%s' % (impl, get_impl_ver(), d, m, u) elif soabi and soabi.startswith('cpython-'): abi = 'cp' + soabi.split('-')[1] elif soabi: abi = soabi.replace('.', '_').replace('-', '_') return abi def _is_running_32bit(): # type: () -> bool return sys.maxsize == 2147483647 def get_platform(): # type: () -> str """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') if machine == "x86_64" and _is_running_32bit(): machine = "i386" elif machine == "ppc64" and _is_running_32bit(): machine = "ppc" return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency result = distutils.util.get_platform().replace('.', '_').replace('-', '_') if result == "linux_x86_64" and _is_running_32bit(): # 32 bit Python program (running on a 64 bit Linux): pip should only # install and run 32 bit compiled extensions in that case. result = "linux_i686" return result def is_linux_armhf(): # type: () -> bool if get_platform() != "linux_armv7l": return False # hard-float ABI can be detected from the ELF header of the running # process try: with open(sys.executable, 'rb') as f: elf_header_raw = f.read(40) # read 40 first bytes of ELF header except (IOError, OSError, TypeError): return False if elf_header_raw is None or len(elf_header_raw) < 40: return False if isinstance(elf_header_raw, str): elf_header = [ord(c) for c in elf_header_raw] else: elf_header = [b for b in elf_header_raw] result = elf_header[0:4] == [0x7f, 0x45, 0x4c, 0x46] # ELF magic number result &= elf_header[4:5] == [1] # 32-bit ELF result &= elf_header[5:6] == [1] # little-endian result &= elf_header[18:20] == [0x28, 0] # ARM machine result &= elf_header[39:40] == [5] # ARM EABIv5 result &= (elf_header[37:38][0] & 4) == 4 # EF_ARM_ABI_FLOAT_HARD return result def is_manylinux1_compatible(): # type: () -> bool # Only Linux, and only x86-64 / i686 if get_platform() not in {"linux_x86_64", "linux_i686"}: return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux1_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 5 uses glibc 2.5. return pip._internal.utils.glibc.have_compatible_glibc(2, 5) def is_manylinux2010_compatible(): # type: () -> bool # Only Linux, and only x86-64 / i686 if get_platform() not in {"linux_x86_64", "linux_i686"}: return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux2010_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 6 uses glibc 2.12. return pip._internal.utils.glibc.have_compatible_glibc(2, 12) def is_manylinux2014_compatible(): # type: () -> bool # Only Linux, and only supported architectures platform = get_platform() if platform not in {"linux_x86_64", "linux_i686", "linux_aarch64", "linux_armv7l", "linux_ppc64", "linux_ppc64le", "linux_s390x"}: return False # check for hard-float ABI in case we're running linux_armv7l not to # install hard-float ABI wheel in a soft-float ABI environment if platform == "linux_armv7l" and not is_linux_armhf(): return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux2014_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 7 uses glibc 2.17. return pip._internal.utils.glibc.have_compatible_glibc(2, 17) def get_darwin_arches(major, minor, machine): # type: (int, int, str) -> List[str] """Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. """ arches = [] def _supports_arch(major, minor, arch): # type: (int, int, str) -> bool # Looking at the application support for macOS versions in the chart # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears # our timeline looks roughly like: # # 10.0 - Introduces ppc support. # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64 # and x86_64 support is CLI only, and cannot be used for GUI # applications. # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications. # 10.6 - Drops support for ppc64 # 10.7 - Drops support for ppc # # Given that we do not know if we're installing a CLI or a GUI # application, we must be conservative and assume it might be a GUI # application and behave as if ppc64 and x86_64 support did not occur # until 10.5. # # Note: The above information is taken from the "Application support" # column in the chart not the "Processor support" since I believe # that we care about what instruction sets an application can use # not which processors the OS supports. if arch == 'ppc': return (major, minor) <= (10, 5) if arch == 'ppc64': return (major, minor) == (10, 5) if arch == 'i386': return (major, minor) >= (10, 4) if arch == 'x86_64': return (major, minor) >= (10, 5) if arch in groups: for garch in groups[arch]: if _supports_arch(major, minor, garch): return True return False groups = OrderedDict([ ("fat", ("i386", "ppc")), ("intel", ("x86_64", "i386")), ("fat64", ("x86_64", "ppc64")), ("fat32", ("x86_64", "i386", "ppc")), ]) # type: Dict[str, Tuple[str, ...]] if _supports_arch(major, minor, machine): arches.append(machine) for garch in groups: if machine in groups[garch] and _supports_arch(major, minor, garch): arches.append(garch) arches.append('universal') return arches def get_all_minor_versions_as_strings(version_info): # type: (Tuple[int, ...]) -> List[str] versions = [] major = version_info[:-1] # Support all previous minor Python versions. for minor in range(version_info[-1], -1, -1): versions.append(''.join(map(str, major + (minor,)))) return versions def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # Versions must be given with respect to the preference if versions is None: version_info = get_impl_version_info() versions = get_all_minor_versions_as_strings(version_info) impl = impl or get_abbr_impl() abis = [] # type: List[str] abi = abi or get_abi_tag() if abi: abis[0:0] = [abi] abi3s = set() # type: Set[str] for suffix in get_extension_suffixes(): if suffix.startswith('.abi'): abi3s.add(suffix.split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = platform or get_platform() arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch.startswith('macosx'): # support macosx-10.6-intel on macosx-10.9-x86_64 match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() tpl = '{}_{}_%i_%s'.format(name, major) arches = [] for m in reversed(range(int(minor) + 1)): for a in get_darwin_arches(int(major), m, actual_arch): arches.append(tpl % (m, a)) else: # arch pattern didn't match (?!) arches = [arch] elif arch_prefix == 'manylinux2014': arches = [arch] # manylinux1/manylinux2010 wheels run on most manylinux2014 systems # with the exception of wheels depending on ncurses. PEP 599 states # manylinux1/manylinux2010 wheels should be considered # manylinux2014 wheels: # https://www.python.org/dev/peps/pep-0599/#backwards-compatibility-with-manylinux2010-wheels if arch_suffix in {'i686', 'x86_64'}: arches.append('manylinux2010' + arch_sep + arch_suffix) arches.append('manylinux1' + arch_sep + arch_suffix) elif arch_prefix == 'manylinux2010': # manylinux1 wheels run on most manylinux2010 systems with the # exception of wheels depending on ncurses. PEP 571 states # manylinux1 wheels should be considered manylinux2010 wheels: # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels arches = [arch, 'manylinux1' + arch_sep + arch_suffix] elif platform is None: arches = [] if is_manylinux2014_compatible(): arches.append('manylinux2014' + arch_sep + arch_suffix) if is_manylinux2010_compatible(): arches.append('manylinux2010' + arch_sep + arch_suffix) if is_manylinux1_compatible(): arches.append('manylinux1' + arch_sep + arch_suffix) arches.append(arch) else: arches = [arch] # Current version, current API (built specifically for our Python): for abi in abis: for arch in arches: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # abi3 modules compatible with older version of Python for version in versions[1:]: # abi3 was introduced in Python 3.2 if version in {'31', '30'}: break for abi in abi3s: # empty set if not Python 3 for arch in arches: supported.append(("%s%s" % (impl, version), abi, arch)) # Has binaries, does not use the Python API: for arch in arches: supported.append(('py%s' % (versions[0][0]), 'none', arch)) # No abi / arch, but requires our implementation: supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported implementation_tag = get_impl_tag() legacy_resolve.py000064400000041522152347654150010141 0ustar00"""Dependency Resolution The dependency resolution in pip is performed as follows: for top-level requirements: a. only one spec allowed per project, regardless of conflicts or not. otherwise a "double requirement" exception is raised b. they override sub-dependency requirements. for sub-dependencies a. "first found, wins" (where the order is breadth first) """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False import logging import sys from collections import defaultdict from itertools import chain from pip._vendor.packaging import specifiers from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, HashError, HashErrors, UnsupportedPythonVersion, ) from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( dist_in_install_path, dist_in_usersite, ensure_dir, normalize_version_info, ) from pip._internal.utils.packaging import ( check_requires_python, get_requires_python, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Callable, DefaultDict, List, Optional, Set, Tuple from pip._vendor import pkg_resources from pip._internal.distributions import AbstractDistribution from pip._internal.network.session import PipSession from pip._internal.index import PackageFinder from pip._internal.operations.prepare import RequirementPreparer from pip._internal.req.req_install import InstallRequirement from pip._internal.req.req_set import RequirementSet InstallRequirementProvider = Callable[ [str, InstallRequirement], InstallRequirement ] logger = logging.getLogger(__name__) def _check_dist_requires_python( dist, # type: pkg_resources.Distribution version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> None """ Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. """ requires_python = get_requires_python(dist) try: is_compatible = check_requires_python( requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier as exc: logger.warning( "Package %r has an invalid Requires-Python: %s", dist.project_name, exc, ) return if is_compatible: return version = '.'.join(map(str, version_info)) if ignore_requires_python: logger.debug( 'Ignoring failed Requires-Python check for package %r: ' '%s not in %r', dist.project_name, version, requires_python, ) return raise UnsupportedPythonVersion( 'Package {!r} requires a different Python: {} not in {!r}'.format( dist.project_name, version, requires_python, )) class Resolver(object): """Resolves which packages need to be installed/uninstalled to perform \ the requested operation without breaking the requirements of any package. """ _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} def __init__( self, preparer, # type: RequirementPreparer session, # type: PipSession finder, # type: PackageFinder make_install_req, # type: InstallRequirementProvider use_user_site, # type: bool ignore_dependencies, # type: bool ignore_installed, # type: bool ignore_requires_python, # type: bool force_reinstall, # type: bool upgrade_strategy, # type: str py_version_info=None, # type: Optional[Tuple[int, ...]] ): # type: (...) -> None super(Resolver, self).__init__() assert upgrade_strategy in self._allowed_strategies if py_version_info is None: py_version_info = sys.version_info[:3] else: py_version_info = normalize_version_info(py_version_info) self._py_version_info = py_version_info self.preparer = preparer self.finder = finder self.session = session # This is set in resolve self.require_hashes = None # type: Optional[bool] self.upgrade_strategy = upgrade_strategy self.force_reinstall = force_reinstall self.ignore_dependencies = ignore_dependencies self.ignore_installed = ignore_installed self.ignore_requires_python = ignore_requires_python self.use_user_site = use_user_site self._make_install_req = make_install_req self._discovered_dependencies = \ defaultdict(list) # type: DefaultDict[str, List] def resolve(self, requirement_set): # type: (RequirementSet) -> None """Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be possible to move the preparation to become a step separated from dependency resolution. """ # make the wheelhouse if self.preparer.wheel_download_dir: ensure_dir(self.preparer.wheel_download_dir) # If any top-level requirement has a hash specified, enter # hash-checking mode, which requires hashes from all. root_reqs = ( requirement_set.unnamed_requirements + list(requirement_set.requirements.values()) ) self.require_hashes = ( requirement_set.require_hashes or any(req.has_hash_options for req in root_reqs) ) # Display where finder is looking for packages search_scope = self.finder.search_scope locations = search_scope.get_formatted_locations() if locations: logger.info(locations) # Actually prepare the files, and collect any exceptions. Most hash # exceptions cannot be checked ahead of time, because # req.populate_link() needs to be called before we can make decisions # based on link type. discovered_reqs = [] # type: List[InstallRequirement] hash_errors = HashErrors() for req in chain(root_reqs, discovered_reqs): try: discovered_reqs.extend( self._resolve_one(requirement_set, req) ) except HashError as exc: exc.req = req hash_errors.append(exc) if hash_errors: raise hash_errors def _is_upgrade_allowed(self, req): # type: (InstallRequirement) -> bool if self.upgrade_strategy == "to-satisfy-only": return False elif self.upgrade_strategy == "eager": return True else: assert self.upgrade_strategy == "only-if-needed" return req.is_direct def _set_req_to_reinstall(self, req): # type: (InstallRequirement) -> None """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if ((not self.use_user_site or dist_in_usersite(req.satisfied_by)) and dist_in_install_path(req.satisfied_by)): req.conflicts_with = req.satisfied_by req.satisfied_by = None def _check_skip_installed(self, req_to_install): # type: (InstallRequirement) -> Optional[str] """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. """ if self.ignore_installed: return None req_to_install.check_if_exists(self.use_user_site) if not req_to_install.satisfied_by: return None if self.force_reinstall: self._set_req_to_reinstall(req_to_install) return None if not self._is_upgrade_allowed(req_to_install): if self.upgrade_strategy == "only-if-needed": return 'already satisfied, skipping upgrade' return 'already satisfied' # Check for the possibility of an upgrade. For link-based # requirements we have to pull the tree down and inspect to assess # the version #, so it's handled way down. if not req_to_install.link: try: self.finder.find_requirement(req_to_install, upgrade=True) except BestVersionAlreadyInstalled: # Then the best version is installed. return 'already up-to-date' except DistributionNotFound: # No distribution found, so we squash the error. It will # be raised later when we re-try later to do the install. # Why don't we just raise here? pass self._set_req_to_reinstall(req_to_install) return None def _get_abstract_dist_for(self, req): # type: (InstallRequirement) -> AbstractDistribution """Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same. """ assert self.require_hashes is not None, ( "require_hashes should have been set in Resolver.resolve()" ) if req.editable: return self.preparer.prepare_editable_requirement( req, self.require_hashes, self.use_user_site, self.finder, ) # satisfied_by is only evaluated by calling _check_skip_installed, # so it must be None here. assert req.satisfied_by is None skip_reason = self._check_skip_installed(req) if req.satisfied_by: return self.preparer.prepare_installed_requirement( req, self.require_hashes, skip_reason ) upgrade_allowed = self._is_upgrade_allowed(req) # We eagerly populate the link, since that's our "legacy" behavior. req.populate_link(self.finder, upgrade_allowed, self.require_hashes) abstract_dist = self.preparer.prepare_linked_requirement( req, self.session, self.finder, self.require_hashes ) # NOTE # The following portion is for determining if a certain package is # going to be re-installed/upgraded or not and reporting to the user. # This should probably get cleaned up in a future refactor. # req.req is only avail after unpack for URL # pkgs repeat check_if_exists to uninstall-on-upgrade # (#14) if not self.ignore_installed: req.check_if_exists(self.use_user_site) if req.satisfied_by: should_modify = ( self.upgrade_strategy != "to-satisfy-only" or self.force_reinstall or self.ignore_installed or req.link.scheme == 'file' ) if should_modify: self._set_req_to_reinstall(req) else: logger.info( 'Requirement already satisfied (use --upgrade to upgrade):' ' %s', req, ) return abstract_dist def _resolve_one( self, requirement_set, # type: RequirementSet req_to_install # type: InstallRequirement ): # type: (...) -> List[InstallRequirement] """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting # (remote url or package name) if req_to_install.constraint or req_to_install.prepared: return [] req_to_install.prepared = True # register tmp src for cleanup in case something goes wrong requirement_set.reqs_to_cleanup.append(req_to_install) abstract_dist = self._get_abstract_dist_for(req_to_install) # Parse and return dependencies dist = abstract_dist.get_pkg_resources_distribution() # This will raise UnsupportedPythonVersion if the given Python # version isn't compatible with the distribution's Requires-Python. _check_dist_requires_python( dist, version_info=self._py_version_info, ignore_requires_python=self.ignore_requires_python, ) more_reqs = [] # type: List[InstallRequirement] def add_req(subreq, extras_requested): sub_install_req = self._make_install_req( str(subreq), req_to_install, ) parent_req_name = req_to_install.name to_scan_again, add_to_parent = requirement_set.add_requirement( sub_install_req, parent_req_name=parent_req_name, extras_requested=extras_requested, ) if parent_req_name and add_to_parent: self._discovered_dependencies[parent_req_name].append( add_to_parent ) more_reqs.extend(to_scan_again) with indent_log(): # We add req_to_install before its dependencies, so that we # can refer to it when adding dependencies. if not requirement_set.has_requirement(req_to_install.name): # 'unnamed' requirements will get added here req_to_install.is_direct = True requirement_set.add_requirement( req_to_install, parent_req_name=None, ) if not self.ignore_dependencies: if req_to_install.extras: logger.debug( "Installing extra requirements: %r", ','.join(req_to_install.extras), ) missing_requested = sorted( set(req_to_install.extras) - set(dist.extras) ) for missing in missing_requested: logger.warning( '%s does not provide the extra \'%s\'', dist, missing ) available_requested = sorted( set(dist.extras) & set(req_to_install.extras) ) for subreq in dist.requires(available_requested): add_req(subreq, extras_requested=available_requested) if not req_to_install.editable and not req_to_install.satisfied_by: # XXX: --no-install leads this to report 'Successfully # downloaded' for only non-editable reqs, even though we took # action on them. requirement_set.successfully_downloaded.append(req_to_install) return more_reqs def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # dependencies must come earlier to achieve topological order. order = [] ordered_reqs = set() # type: Set[InstallRequirement] def schedule(req): if req.satisfied_by or req in ordered_reqs: return if req.constraint: return ordered_reqs.add(req) for dep in self._discovered_dependencies[req.name]: schedule(dep) order.append(req) for install_req in req_set.requirements.values(): schedule(install_req) return order commands/debug.py000064400000016222152347654150010024 0ustar00from __future__ import absolute_import import locale import logging import os import sys import pip._vendor from pip._vendor import pkg_resources from pip._vendor.certifi import where from pip import __file__ as pip_location from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_pip_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from types import ModuleType from typing import List, Optional, Dict from optparse import Values from pip._internal.configuration import Configuration logger = logging.getLogger(__name__) def show_value(name, value): # type: (str, Optional[str]) -> None logger.info('%s: %s', name, value) def show_sys_implementation(): # type: () -> None logger.info('sys.implementation:') if hasattr(sys, 'implementation'): implementation = sys.implementation # type: ignore implementation_name = implementation.name else: implementation_name = '' with indent_log(): show_value('name', implementation_name) def create_vendor_txt_map(): # type: () -> Dict[str, str] vendor_txt_path = os.path.join( os.path.dirname(pip_location), '_vendor', 'vendor.txt' ) with open(vendor_txt_path) as f: # Purge non version specifying lines. # Also, remove any space prefix or suffixes (including comments). lines = [line.strip().split(' ', 1)[0] for line in f.readlines() if '==' in line] # Transform into "module" -> version dict. return dict(line.split('==', 1) for line in lines) # type: ignore def get_module_from_module_name(module_name): # type: (str) -> ModuleType # Module name can be uppercase in vendor.txt for some reason... module_name = module_name.lower() # PATCH: setuptools is actually only pkg_resources. if module_name == 'setuptools': module_name = 'pkg_resources' __import__( 'pip._vendor.{}'.format(module_name), globals(), locals(), level=0 ) return getattr(pip._vendor, module_name) def get_vendor_version_from_module(module_name): # type: (str) -> Optional[str] module = get_module_from_module_name(module_name) version = getattr(module, '__version__', None) if not version: # Try to find version in debundled module info # The type for module.__file__ is Optional[str] in # Python 2, and str in Python 3. The type: ignore is # added to account for Python 2, instead of a cast # and should be removed once we drop Python 2 support pkg_set = pkg_resources.WorkingSet( [os.path.dirname(module.__file__)] # type: ignore ) package = pkg_set.find(pkg_resources.Requirement.parse(module_name)) version = getattr(package, 'version', None) return version def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None """Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. """ for module_name, expected_version in vendor_txt_versions.items(): extra_message = '' actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message = ' (Unable to locate actual module version, using'\ ' vendor.txt specified version)' actual_version = expected_version elif actual_version != expected_version: extra_message = ' (CONFLICT: vendor.txt suggests version should'\ ' be {})'.format(expected_version) logger.info('%s==%s%s', module_name, actual_version, extra_message) def show_vendor_versions(): # type: () -> None logger.info('vendored library versions:') vendor_txt_versions = create_vendor_txt_map() with indent_log(): show_actual_vendor_versions(vendor_txt_versions) def show_tags(options): # type: (Values) -> None tag_limit = 10 target_python = make_target_python(options) tags = target_python.get_tags() # Display the target options that were explicitly provided. formatted_target = target_python.format_given() suffix = '' if formatted_target: suffix = ' (target: {})'.format(formatted_target) msg = 'Compatible tags: {}{}'.format(len(tags), suffix) logger.info(msg) if options.verbose < 1 and len(tags) > tag_limit: tags_limited = True tags = tags[:tag_limit] else: tags_limited = False with indent_log(): for tag in tags: logger.info(str(tag)) if tags_limited: msg = ( '...\n' '[First {tag_limit} tags shown. Pass --verbose to show all.]' ).format(tag_limit=tag_limit) logger.info(msg) def ca_bundle_info(config): # type: (Configuration) -> str levels = set() for key, _ in config.items(): levels.add(key.split('.')[0]) if not levels: return "Not specified" levels_that_override_global = ['install', 'wheel', 'download'] global_overriding_level = [ level for level in levels if level in levels_that_override_global ] if not global_overriding_level: return 'global' if 'global' in levels: levels.remove('global') return ", ".join(levels) class DebugCommand(Command): """ Display debug information. """ usage = """ %prog """ ignore_require_venv = True def add_options(self): # type: () -> None cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.config.load() def run(self, options, args): # type: (Values, List[str]) -> int logger.warning( "This command is only meant for debugging. " "Do not use this with automation for parsing and getting these " "details, since the output and options of this command may " "change without notice." ) show_value('pip version', get_pip_version()) show_value('sys.version', sys.version) show_value('sys.executable', sys.executable) show_value('sys.getdefaultencoding', sys.getdefaultencoding()) show_value('sys.getfilesystemencoding', sys.getfilesystemencoding()) show_value( 'locale.getpreferredencoding', locale.getpreferredencoding(), ) show_value('sys.platform', sys.platform) show_sys_implementation() show_value("'cert' config value", ca_bundle_info(self.parser.config)) show_value("REQUESTS_CA_BUNDLE", os.environ.get('REQUESTS_CA_BUNDLE')) show_value("CURL_CA_BUNDLE", os.environ.get('CURL_CA_BUNDLE')) show_value("pip._vendor.certifi.where()", where()) show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) show_vendor_versions() show_tags(options) return SUCCESS commands/__pycache__/hash.cpython-38.opt-1.pyc000064400000003706152347654150015111 0ustar00U .e@sddlmZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z mZeeZGdddeZd d ZdS) )absolute_importN)Command)ERROR) FAVORITE_HASH STRONG_HASHES) read_chunks write_outputcs0eZdZdZdZdZfddZddZZS) HashCommandz Compute a hash of a local package archive. These can be used with --hash in a requirements file to do repeatable installs. z%prog [options] ...Tc sJtt|j|||jjdddtdtddtd|j d|jdS) Nz-az --algorithm algorithmZstorez$The hash algorithm to use: one of %sz, )destchoicesactiondefaulthelpr) superr __init__Zcmd_optsZ add_optionrrjoinparserZinsert_option_group)selfargskw __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/hash.pyrszHashCommand.__init__cCs>|s|jtjtS|j}|D]}td||t||q dS)Nz%s: --hash=%s:%s)rZ print_usagesysstderrrr r _hash_of_file)rZoptionsrr pathrrrrun)szHashCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvrr __classcell__rrrrr s  r c Cs@t|d(}t|}t|D]}||qW5QRX|S)z!Return the hash digest of a file.rb)openhashlibnewrupdateZ hexdigest)rr archivehashchunkrrrr4s    r)Z __future__rr'ZloggingrZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrZpip._internal.utils.hashesrrZpip._internal.utils.miscrrZ getLoggerr Zloggerr rrrrrs    "commands/__pycache__/list.cpython-38.opt-1.pyc000064400000021267152347654150015143 0ustar00U .e4)@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZdd lmZmZmZdd lmZeeZGd dde ZddZddZddZ dS))absolute_importN)six) zip_longest) cmdoptions)IndexGroupCommand) CommandError) PackageFinder)SelectionPreferences)make_link_collector)dist_is_editableget_installed_distributions write_output) get_installercsdeZdZdZdZfddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ZS) ListCommandzt List installed packages, including editables. Packages are listed in a case-insensitive sorted order. z %prog [options]cstt|j|||j}|jdddddd|jddddd d|jd d ddd d|jd ddddd|jjdddddd|t|jddddd|jddddddd|jddddd |jd!d"d#d$d |jd%dd#d&d'd(ttj|j }|j d)||j d)|dS)*Nz-oz --outdated store_trueFzList outdated packages)actiondefaulthelpz-uz --uptodatezList uptodate packagesz-ez --editablezList editable projects.z-lz--localzSIf in a virtualenv that has global access, do not list globally-installed packages.z--useruserz,Only output packages installed in user-site.)destrrrz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--formatZstore list_formatcolumns)rfreezejsonzBSelect the output format among: columns (default), freeze, or json)rrrchoicesrz--not-required not_requiredz>List packages that are not dependencies of installed packages.)rrrz--exclude-editableZ store_falseinclude_editablez%Exclude editable package from output.z--include-editablez%Include editable package from output.T)rrrrr) superr__init__cmd_optsZ add_optionrZ list_pathZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/list.pyr&s zListCommand.__init__cCs(t||d}td|jd}tj||dS)zK Create a package finder appropriate to this list command. )optionsF)Z allow_yankedZallow_all_prereleases)link_collectorselection_prefs)r r prerZcreate)r!r(sessionr)r*r&r&r'_build_package_findervs z!ListCommand._build_package_findercCs|jr|jrtdt|t|j|j|j|j |j d}|j rL| ||}|jr`| ||}n|jrr|||}|||dS)Nz5Options --outdated and --uptodate cannot be combined.)Z local_onlyZ user_onlyZeditables_onlyZinclude_editablespaths)outdatedZuptodaterrZcheck_list_path_optionr ZlocalrZeditablerpathrget_not_required get_outdated get_uptodateoutput_package_listing)r!r(r"packagesr&r&r'runs&     zListCommand.runcCsdd|||DS)NcSsg|]}|j|jkr|qSr&latest_versionZparsed_version.0distr&r&r' s z,ListCommand.get_outdated..iter_packages_latest_infosr!r5r(r&r&r'r2s zListCommand.get_outdatedcCsdd|||DS)NcSsg|]}|j|jkr|qSr&r7r9r&r&r'r<s z,ListCommand.get_uptodate..r=r?r&r&r'r3s zListCommand.get_uptodatecs:t|D]}dd|Dq fdd|DS)Ncss|] }|jVqdSNkey)r:Z requirementr&r&r' sz/ListCommand.get_not_required..csh|]}|jkr|qSr&rA)r:ZpkgZdep_keysr&r' s z/ListCommand.get_not_required..)setupdateZrequires)r!r5r(r;r&rDr'r1szListCommand.get_not_requiredc cs||}|||}|D]t}d}||j}|jsDdd|D}|j|jd}||} | dkrfq| j} | j j rzd}nd}| |_ ||_ |VqW5QRXdS)NunknowncSsg|]}|jjs|qSr&)versionZ is_prerelease)r: candidater&r&r'r<sz:ListCommand.iter_packages_latest_infos..) project_nameZwheelZsdist) Z_build_sessionr-Zfind_all_candidatesrBr+Zmake_candidate_evaluatorrKZsort_best_candidaterIlinkZis_wheelr8latest_filetype) r!r5r(r,finderr;typZall_candidatesZ evaluatorZbest_candidateZremote_versionr&r&r'r>s(    z&ListCommand.iter_packages_latest_infoscCst|ddd}|jdkr:|r:t||\}}|||n^|jdkr|D]4}|jdkrltd|j|j|jqHtd|j|jqHn|jd krtt ||dS) NcSs |jSr@)rKlower)r;r&r&r'z4ListCommand.output_package_listing..rArrz %s==%s (%s)z%s==%sr) sortedrformat_for_columnsoutput_package_listing_columnsverboser rKrIlocationformat_for_json)r!r5r(dataheaderr;r&r&r'r4s"   z"ListCommand.output_package_listingcCsbt|dkr|d|t|\}}t|dkrL|ddtdd||D] }t|qPdS)NrrS cSsd|S)N-r&)xr&r&r'rQrRz.)leninserttabulatejoinmapr )r!rZr[Z pkg_stringssizesvalr&r&r'rVs    z*ListCommand.output_package_listing_columns)__name__ __module__ __qualname____doc__Zusagerr-r6r2r3r1r>r4rV __classcell__r&r&r$r'rs PrcCspdgtdd|D}|D]}ddt||D}qg}|D](}dddt||D}||q>||fS)Nrcss|]}t|VqdSr@)r_r:r^r&r&r'rCsztabulate..cSs"g|]\}}t|tt|qSr&)maxr_strr:scr&r&r'r<sztabulate..r\cSs*g|]"\}}|dk r"t||ndqS)N)rmljustrnr&r&r'r<s)rlrrbappend)ZvalsrdrowresultZdisplayr&r&r'ras  racCs|j}|rddddg}nddg}g}|jdks@tdd|DrJ|d|jdkr^|d |D]l}|j|jg}|r||j||j|jdkst|r||j |jdkr|t |||qb||fS) z_ Convert the package data into something usable by output_package_listing_columns. ZPackageZVersionZLatestZTyperScss|]}t|VqdSr@)r rkr&r&r'rCsz%format_for_columns..ZLocationZ Installer) r/rWanyrsrKrIr8rMr rXr)Zpkgsr(Zrunning_outdatedr[rZZprojrtr&r&r'rUs(         rUcCsvg}|D]b}|jt|jd}|jdkr@|j|d<t||d<|jr`t|j|d<|j |d<| |qt |S)N)namerIrSrXZ installerr8rM) rKrZ text_typerIrWrXrr/r8rMrsrdumps)r5r(rZr;infor&r&r'rY+s      rY)!Z __future__rrZloggingZ pip._vendorrZpip._vendor.six.movesrZpip._internal.clirZpip._internal.cli.req_commandrZpip._internal.exceptionsrZpip._internal.indexrZ$pip._internal.models.selection_prefsr Z!pip._internal.self_outdated_checkr Zpip._internal.utils.miscr r r Zpip._internal.utils.packagingrZ getLoggerrfZloggerrrarUrYr&r&r&r's$           Y%commands/__pycache__/wheel.cpython-38.pyc000064400000011015152347654150014323 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z m Z ddl mZddlmZdd lmZdd lmZdd lmZerdd lmZdd lmZmZeeZGddde ZdS))absolute_importN) WheelCache) cmdoptions)RequirementCommand) CommandErrorPreviousBuildDirError)RequirementSet)RequirementTracker) TempDirectory)MYPY_CHECK_RUNNING) WheelBuilder)Values)AnyListcs,eZdZdZdZfddZddZZS) WheelCommanda Build Wheel archives for your requirements and dependencies. Wheel is a built-package format, and offers the advantage of not recompiling your software during every install. For more details, see the wheel docs: https://wheel.readthedocs.io/en/latest/ Requirements: setuptools>=0.8, and wheel. 'pip wheel' uses the bdist_wheel setuptools extension from the wheel package to build individual wheels. z %prog [options] ... %prog [options] -r ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...csztt|j|||j}|jddddtjdd|t|t |t |jddd d d d |t |t |t |t|t|t|t|t|t|t|t|jd dd d dd|jddddd|t|tttj|j}|jd||jd|dS)Nz-wz --wheel-dir wheel_dirdirzLBuild wheels into , where the default is the current working directory.)destmetavardefaulthelpz--build-option build_optionsoptionsappendz9Extra arguments to be supplied to 'setup.py bdist_wheel'.)rractionrz--global-optionglobal_optionszZExtra global options to be supplied to the setup.py call before the 'bdist_wheel' command.)rrrrz--pre store_trueFzYInclude pre-release and development versions. By default, pip only finds stable versions.)rrrr)superr__init__cmd_optsZ add_optionoscurdirrZ no_binaryZ only_binaryZ prefer_binaryZno_build_isolation use_pep517Z no_use_pep517Z constraintsZeditable requirementssrcignore_requires_pythonZno_deps build_dirZ progress_barno_cleanrequire_hashesZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__@/usr/lib/python3.8/site-packages/pip/_internal/commands/wheel.pyr3shzWheelCommand.__init__c Cszt||jr tj|j|_tj|j|_||}|||}|j pP|j }t |j |j }t }t|j|dd}t|jd} zz|| ||||||j||||jd} |j| |||||j|jd} | | t| ||jpg|jpg|j d} | | j} t | dkr"t!dWnt"k rBd |_ YnXW5|j s`| |XW5QRXW5QRXdS) NZwheel)deleteZkind)r()Ztemp_build_dirr req_trackerZwheel_download_dir)preparerfindersessionr wheel_cacher%r")rrr'rz"Failed to build one or more wheelsT)#rZcheck_install_build_globalr&r pathabspathZsrc_dirZget_default_sessionZ_build_package_finderr'r cache_dirZformat_controlr r rr(Z cleanup_filesZcleanupZpopulate_requirement_setZmake_requirement_preparerrZ make_resolverr%r"Zresolver rrZbuildr#valueslenrr)r*rr+r5r4Z build_deleter6r2Z directoryZrequirement_setr3ZresolverwbZbuild_failuresr/r/r0runqs|      zWheelCommand.run)__name__ __module__ __qualname____doc__Zusagerr= __classcell__r/r/r-r0rs >r) Z __future__rZloggingr Zpip._internal.cacherZpip._internal.clirZpip._internal.cli.req_commandrZpip._internal.exceptionsrrZpip._internal.reqrZpip._internal.req.req_trackerr Zpip._internal.utils.temp_dirr Zpip._internal.utils.typingr Zpip._internal.wheelr Zoptparser typingrrZ getLoggerr>Zloggerrr/r/r/r0s           commands/__pycache__/wheel.cpython-38.opt-1.pyc000064400000011015152347654150015262 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z m Z ddl mZddlmZdd lmZdd lmZdd lmZerdd lmZdd lmZmZeeZGddde ZdS))absolute_importN) WheelCache) cmdoptions)RequirementCommand) CommandErrorPreviousBuildDirError)RequirementSet)RequirementTracker) TempDirectory)MYPY_CHECK_RUNNING) WheelBuilder)Values)AnyListcs,eZdZdZdZfddZddZZS) WheelCommanda Build Wheel archives for your requirements and dependencies. Wheel is a built-package format, and offers the advantage of not recompiling your software during every install. For more details, see the wheel docs: https://wheel.readthedocs.io/en/latest/ Requirements: setuptools>=0.8, and wheel. 'pip wheel' uses the bdist_wheel setuptools extension from the wheel package to build individual wheels. z %prog [options] ... %prog [options] -r ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...csztt|j|||j}|jddddtjdd|t|t |t |jddd d d d |t |t |t |t|t|t|t|t|t|t|t|jd dd d dd|jddddd|t|tttj|j}|jd||jd|dS)Nz-wz --wheel-dir wheel_dirdirzLBuild wheels into , where the default is the current working directory.)destmetavardefaulthelpz--build-option build_optionsoptionsappendz9Extra arguments to be supplied to 'setup.py bdist_wheel'.)rractionrz--global-optionglobal_optionszZExtra global options to be supplied to the setup.py call before the 'bdist_wheel' command.)rrrrz--pre store_trueFzYInclude pre-release and development versions. By default, pip only finds stable versions.)rrrr)superr__init__cmd_optsZ add_optionoscurdirrZ no_binaryZ only_binaryZ prefer_binaryZno_build_isolation use_pep517Z no_use_pep517Z constraintsZeditable requirementssrcignore_requires_pythonZno_deps build_dirZ progress_barno_cleanrequire_hashesZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__@/usr/lib/python3.8/site-packages/pip/_internal/commands/wheel.pyr3shzWheelCommand.__init__c Cszt||jr tj|j|_tj|j|_||}|||}|j pP|j }t |j |j }t }t|j|dd}t|jd} zz|| ||||||j||||jd} |j| |||||j|jd} | | t| ||jpg|jpg|j d} | | j} t | dkr"t!dWnt"k rBd |_ YnXW5|j s`| |XW5QRXW5QRXdS) NZwheel)deleteZkind)r()Ztemp_build_dirr req_trackerZwheel_download_dir)preparerfindersessionr wheel_cacher%r")rrr'rz"Failed to build one or more wheelsT)#rZcheck_install_build_globalr&r pathabspathZsrc_dirZget_default_sessionZ_build_package_finderr'r cache_dirZformat_controlr r rr(Z cleanup_filesZcleanupZpopulate_requirement_setZmake_requirement_preparerrZ make_resolverr%r"Zresolver rrZbuildr#valueslenrr)r*rr+r5r4Z build_deleter6r2Z directoryZrequirement_setr3ZresolverwbZbuild_failuresr/r/r0runqs|      zWheelCommand.run)__name__ __module__ __qualname____doc__Zusagerr= __classcell__r/r/r-r0rs >r) Z __future__rZloggingr Zpip._internal.cacherZpip._internal.clirZpip._internal.cli.req_commandrZpip._internal.exceptionsrrZpip._internal.reqrZpip._internal.req.req_trackerr Zpip._internal.utils.temp_dirr Zpip._internal.utils.typingr Zpip._internal.wheelr Zoptparser typingrrZ getLoggerr>Zloggerrr/r/r/r0s           commands/__pycache__/download.cpython-38.opt-1.pyc000064400000010314152347654150015766 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZmZmZdd lmZeeZGd d d e ZdS) )absolute_importN) cmdoptions)make_target_python)RequirementCommand)RequirementSet)RequirementTracker)check_path_owner) ensure_dirnormalize_path write_output) TempDirectorycs,eZdZdZdZfddZddZZS)DownloadCommandaL Download packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports downloading from "requirements files", which provide an easy way to specify a whole environment to be downloaded. a %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] ... %prog [options] ... %prog [options] ...c sNtt|j|||j}|t|t|t|t |t |t |t |t |t|t|t|t|t|t|t|t|jddddddtjddt|ttj|j}|jd ||jd |dS) Nz-dz--destz--destination-dirz--destination-directory download_dirdirzDownload packages into .)destmetavardefaulthelpr)superr __init__cmd_optsZ add_optionrZ constraintsZ requirements build_dirZno_depsZglobal_optionsZ no_binaryZ only_binaryZ prefer_binarysrcZpreno_cleanrequire_hashesZ progress_barZno_build_isolationZ use_pep517Z no_use_pep517oscurdirZadd_target_python_optionsZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__C/usr/lib/python3.8/site-packages/pip/_internal/commands/download.pyr)sF zDownloadCommand.__init__c CsLd|_g|_t|tj|j|_t|j |_ t |j | |}t |}|j |||d}|jph|j }|jrt|jstd|jd|_t}t|j|dd}t|jd} || ||||d|j||||j d} |j| ||||jd} | | d d d | jD} | r$td | |js4| W5QRXW5QRX| S) NT)optionssession target_pythonzThe directory '%s' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.Zdownload)deleteZkind)r)Ztemp_build_dirr% req_trackerr)preparerfinderr&r%Zpy_version_info cSsg|] }|jqSr#)name).0Zreqr#r#r$ sz'DownloadCommand.run..zSuccessfully downloaded %s)!Zignore_installedZ editablesrZcheck_dist_restrictionrpathabspathZsrc_dirr rr Zget_default_sessionrZ_build_package_finderrr cache_dirrloggerZwarningrr rrZpopulate_requirement_setZmake_requirement_preparerZ make_resolverZpython_versionZresolvejoinZsuccessfully_downloadedr Z cleanup_files) rr%rr&r'r+Z build_deleter)Z directoryZrequirement_setr*ZresolverZ downloadedr#r#r$runQsv         zDownloadCommand.run)__name__ __module__ __qualname____doc__Zusagerr5 __classcell__r#r#r!r$r s  (r )Z __future__rZloggingrZpip._internal.clirZpip._internal.cli.cmdoptionsrZpip._internal.cli.req_commandrZpip._internal.reqrZpip._internal.req.req_trackerrZpip._internal.utils.filesystemrZpip._internal.utils.miscr r r Zpip._internal.utils.temp_dirr Z getLoggerr6r3r r#r#r#r$s         commands/__pycache__/install.cpython-38.opt-1.pyc000064400000034172152347654150015635 0ustar00U .e_@sddlmZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZmZdd lmZmZmZdd lmZddl m!Z!ddl"m#Z#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5e1rddl m6Z6ddl7m8Z8m9Z9m:Z:ddl;mZ>ddl4m?Z?e@eAZBddZCddZDd d!ZEGd"d#d#eZFd$d%ZGd&d'ZHdS)()absolute_importN)path) SUPPRESS_HELP) pkg_resources)canonicalize_name) WheelCache) cmdoptions)make_target_python)RequirementCommand)ERRORSUCCESS) CommandErrorInstallationErrorPreviousBuildDirErrordistutils_scheme)check_install_conflicts)RequirementSetinstall_given_reqs)RequirementTracker)check_path_owner) ensure_dirget_installed_version(protect_pip_from_modification_on_windows write_output) TempDirectory)MYPY_CHECK_RUNNING)virtualenv_no_global) WheelBuilder)Values)AnyListOptional) FormatControl)InstallRequirement)BinaryAllowedPredicatecCs(z ddl}Wntk r"YdSXdS)z8 Return whether the wheel package is installed. rNFT)wheel ImportError)r&r(B/usr/lib/python3.8/site-packages/pip/_internal/commands/install.pyis_wheel_installed<s  r*cCs*t}|j|dd}|r&|j|dd|S)zQ Build wheels for requirements, depending on whether wheel is installed. T)Z should_unpack)r*Zbuild)builderpep517_requirementslegacy_requirementsZshould_build_legacybuild_failuresr(r(r) build_wheelsHs r/csfdd}|S)Ncs&|jr dSt|j}|}d|kS)NTZbinary) use_pep517rnameZget_allowed_formats)reqZcanonical_nameZallowed_formatsformat_controlr(r)check_binary_allowedhs   z6get_check_binary_allowed..check_binary_allowedr()r4r5r(r3r)get_check_binary_allowedfs r6cs<eZdZdZdZfddZddZddZd d ZZ S) InstallCommandaI Install packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports installing from "requirements files", which provide an easy way to specify a whole environment to be installed. a% %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...cs^tt|j|||j}|t|t|t|t |t |jdddddddt ||jddd d d |jd dd t d |jdddddd|jdddddd|t |t|jdddd dd |jdddddgdd|jddd d d |jd!d"d#d d$d |t|t|t|t|t|t|jd%d d&d'd(d)|jd*d d&d+d,|jd-d d.d'd/d)|jd0d d1d'd2d)|t|t|t|t|t|tttj|j}|jd3||jd3|dS)4Nz-tz--target target_dirdirzInstall packages into . By default this will not replace existing files/folders in . Use --upgrade to replace existing packages in with new versions.)destmetavardefaulthelp--user use_user_site store_truezInstall to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.))r:actionr=z --no-userZ store_falsez--root root_pathz=Install everything relative to this alternate root directory.z--prefix prefix_pathzIInstallation prefix where lib, bin and other top-level folders are placedz-Uz --upgradeupgradezUpgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.z--upgrade-strategyupgrade_strategyzonly-if-neededZeageraGDetermines how dependency upgrading should be handled [default: %default]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not satisfy the requirements of the upgraded package(s).)r:r<choicesr=z--force-reinstallforce_reinstallz;Reinstall all packages even if they are already up-to-date.z-Iz--ignore-installedignore_installedzIgnore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!z --compilecompileTz'Compile Python source files to bytecode)rAr:r<r=z --no-compilez.Do not compile Python source files to bytecode)rAr:r=z--no-warn-script-locationwarn_script_locationz0Do not warn when installing scripts outside PATHz--no-warn-conflictswarn_about_conflictsz%Do not warn about broken dependenciesr)superr7__init__cmd_optsZ add_optionr requirementsZ constraintsZno_depsZpreZeditableZadd_target_python_optionsr build_dirsrcignore_requires_pythonZno_build_isolationr0Z no_use_pep517install_optionsglobal_optionsZ no_binaryZ only_binaryZ prefer_binaryno_cleanrequire_hashesZ progress_barZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrNZ index_opts __class__r(r)rMs   zInstallCommand.__init__c*Cst|dd}tdkrZ|sZttjd}|dkrLttjd}t d|d}|j rj|j }|j rtj|j |_ tj|dd tj|j|_|jpg}|jr|jrtd trtd |d |d d}d}|jrJd|_tj|j|_tj|jr,tj|js,tdtdd}|j}|d||jpTg} ||} t|} |j || | |j!d} |j"p|j } t#|j$|j%}|j$rt&|j$st d|j$d|_$t'}t|j | dd}t(|j)|j d}zz*|,|||| | ||j-|||d}|j.|| | |||j|j|j!|j/||j0d }|1|z|2d}Wnt3k rzd}Yn X|j4dk}t5|dt6| j%}g}g}|j78D]$}|j0r||n ||qt9||gg|d}t:|||d}|rtd;d o.|j?}|r@|@||jA}|jrRd!}tB||| |jC||j|jD||jd" }tE|j||jC|j|jFd#} tGH| }!tI|tJKd$d%}"g}#|"D]R}|jL}$z$tM|jL|!d&}%|%r|$d'|%7}$WntNk rYnX|#|$qd(<|#}&|&r tOd)|&WntPk r}'zN|jQd*k}(tR|'|(|j})t jS|)|(d+tTWYWHW5QRW5QRSd}'~'XYntUk rd|_"YnXW5|j"s|*|+XW5QRXW5QRX|jr|V|j||j tWS),NcSs ttdpttdotjtjkS)NZ real_prefix base_prefix)hasattrsysr]prefixr(r(r(r)is_venvs   z#InstallCommand.run..is_venvrz __main__.pyz -m pipzgRunning pip install with root privileges is generally not a good idea. Try `%s install --user` instead.zto-satisfy-onlyT)Z check_targetzVCan not combine '--user' and '--prefix' as they imply different installation locationszZCan not perform a '--user' install. User site-packages are not visible in this virtualenv.r>z --prefix=z=Target path exists but is not a directory, will not continue.target)kindz--home=)optionssession target_pythonrRzThe directory '%s' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.Zinstall)deleterc)rVZcheck_supported_wheels)Ztemp_build_dirrd req_tracker) preparerfinderrerd wheel_cacher?rHrRrGrEr0Zpip) modifying_pip)Z build_optionsrTr5)r+r,r-zPCould not build wheels for {} which use PEP 517 and cannot be installed directlyz, css|] }|jVqdSN)r1).0rr(r(r) sz%InstallCommand.run..F)roothomer`Z pycompilerJr?)userrrrqr`isolatedr1)key) working_set- zSuccessfully installed %sexc_info)XrZcheck_install_build_globalosgetuidrbasenamer_argv executableloggerwarningrDrErPabspathZcheck_dist_restrictionZsrc_dirrSr?rCr rrappendr8rHexistsisdirrrTZget_default_sessionr Z_build_package_finderrRrUr cache_dirr4rrrrVZ cleanup_filesZcleanupZpopulate_requirement_setZmake_requirement_preparerZ make_resolverrGr0ZresolveZget_requirementKeyErrorZ satisfied_byrr6rOvaluesrr/formatjoinZget_installation_orderZignore_dependenciesrK_warn_about_conflictsrJrrBrIget_lib_location_guessesZ isolated_moderZ WorkingSetsortedoperator attrgetterr1r ExceptionrEnvironmentError verbositycreate_env_error_messageerrorr r_handle_target_dirr )*rXrdrYraZcommandrErStarget_temp_dirZtarget_temp_dir_pathrTrerfrjZ build_deleterkrhZ directoryZrequirement_setriZresolverZpip_reqrlr5r-r,r2Z wheel_builderr. to_installZshould_warn_about_conflictsrJZ installedZ lib_locationsrvZreqsitemsitemZinstalled_versionZinstalled_descrshow_tracebackmessager(r(r)runs                   4 zInstallCommand.runc sft|g}|Jtd|jd}|d}|d}|d}tj|rP||tj|rn||krn||tj|r|||D]} t| D]} | |krtj|| tfdd|ddDrqtj|| } tj| r>|st d | qtj | rt d | qtj | r4t | n t| t tj| | | qqW5QRXdS) N)rrpurelibplatlibdatac3s|]}|VqdSrm) startswith)rnsddirr(r)rp+sz4InstallCommand._handle_target_dir..zKTarget directory %s already exists. Specify --upgrade to force replacement.zTarget directory %s already exists and is a link. Pip will not automatically replace links, please remove if replacement is desired.)rrrr|rrlistdirranyrrislinkrshutilZrmtreeremoveZmove) rXr8rrDZ lib_dir_listschemeZ purelib_dirZ platlib_dirZdata_dirZlib_dirrZtarget_item_dirr(rr)rsP        z!InstallCommand._handle_target_dirc Cszt|\}}Wn$tk r4tjdddYdSX|\}}|D]2}||d}||D]}td|||dqZqB|D]8}||d}||D]\} } } td||| | | qqzdS)NzError checking for conflicts.Trzrz*%s %s requires %s, which is not installed.ryzF%s %s has requirement %s, but you'll have %s %s which is incompatible.)rrrrZcritical) rXrZ package_setZ _dep_infoZmissingZ conflictingZ project_nameversionZ dependencyZdep_nameZ dep_versionr2r(r(r)rIs4   z$InstallCommand._warn_about_conflicts) __name__ __module__ __qualname____doc__ZusagerMrrr __classcell__r(r(r[r)r7ss  w8r7cOstd||}|d|dgS)Nrrr)rr)rYkwargsrr(r(r)rdsrcCsg}|d|s,|d|t|n |d|dd7<|jtjkrd}d}|st||d|gn |||d d |dS) z{Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. z5Could not install packages due to an EnvironmentErrorz: .r z"Consider using the `--user` optionzCheck the permissionsz or z. r)rstrerrnoZEACCESextendlowerrstrip)rrZusing_user_sitepartsZuser_option_partZpermissions_partr(r(r)ris&      r)IZ __future__rrZloggingrr|rr_rZoptparserZ pip._vendorrZpip._vendor.packaging.utilsrZpip._internal.cacherZpip._internal.clirZpip._internal.cli.cmdoptionsr Zpip._internal.cli.req_commandr Zpip._internal.cli.status_codesr r Zpip._internal.exceptionsr rrZpip._internal.locationsrZpip._internal.operations.checkrZpip._internal.reqrrZpip._internal.req.req_trackerrZpip._internal.utils.filesystemrZpip._internal.utils.miscrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrZpip._internal.wheelrrtypingr r!r"Z#pip._internal.models.format_controlr#Zpip._internal.req.req_installr$r%Z getLoggerrrr*r/r6r7rrr(r(r(r)sT                        tcommands/__pycache__/debug.cpython-38.pyc000064400000006313152347654150014312 0ustar00U .eB @sddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZdd lmZerdd lmZmZdd lmZeeZd dZddZddZGdddeZ dS))absolute_importN) cmdoptions)Command)make_target_python)SUCCESS) indent_log)get_pip_version)MYPY_CHECK_RUNNING) format_tag)AnyList)ValuescCstd||dS)Nz{}: {})loggerinfoformat)namevaluer@/usr/lib/python3.8/site-packages/pip/_internal/commands/debug.py show_valuesrc CsFtdttdr"tj}|j}nd}ttd|W5QRXdS)Nzsys.implementation:implementationr)rrhasattrsysrrrr)rZimplementation_namerrrshow_sys_implementations  rc Csd}t|}|}|}d}|r.d|}dt||}t||jdkrpt||krpd}|d|}nd}t8|D]}tt |q|rdj|d }t|W5QRXdS) N rz (target: {})zCompatible tags: {}{}TFz?... [First {tag_limit} tags shown. Pass --verbose to show all.]) tag_limit) rZget_tagsZ format_givenrlenrrverboserr ) optionsrZ target_pythonZtagsZformatted_targetsuffixmsgZ tags_limitedtagrrr show_tags,s,  r$cs0eZdZdZdZdZfddZddZZS) DebugCommandz$ Display debug information. z %prog Tcs4tt|j|||j}t||jd|dS)Nr)superr%__init__cmd_optsrZadd_target_python_optionsparserZinsert_option_group)selfargskwr( __class__rrr'Ws zDebugCommand.__init__cCsvtdtdttdtjtdtjtdttdttdt tdtj t t |tS) NzThis command is only meant for debugging. Do not use this with automation for parsing and getting these details, since the output and options of this command may change without notice.z pip versionz sys.versionzsys.executablezsys.getdefaultencodingzsys.getfilesystemencodingzlocale.getpreferredencodingz sys.platform)rZwarningrrrversion executablegetdefaultencodinggetfilesystemencodinglocaleZgetpreferredencodingplatformrr$r)r*r r+rrrrun^s     zDebugCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvr'r5 __classcell__rrr-rr%Ns  r%)!Z __future__rr3ZloggingrZpip._internal.clirZpip._internal.cli.base_commandrZpip._internal.cli.cmdoptionsrZpip._internal.cli.status_codesrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.typingr Zpip._internal.wheelr typingr r Zoptparser Z getLoggerr6rrrr$r%rrrrs&            "commands/__pycache__/check.cpython-38.pyc000064400000002440152347654150014276 0ustar00U .e@sNddlZddlmZddlmZmZddlmZee Z GdddeZ dS)N)Command)check_package_set!create_package_set_from_installed) write_outputc@seZdZdZdZddZdS) CheckCommandz7Verify installed packages have compatible dependencies.z %prog [options]c Cst\}}t|\}}|D].}||j}||D]} td||| dq0q|D]4}||j}||D]\} } } td||| | | qdqN|s|s|rdStddS)Nz*%s %s requires %s, which is not installed.rz-%s %s has requirement %s, but you have %s %s.zNo broken requirements found.)rrversionr) selfZoptionsargsZ package_setZ parsing_probsZmissingZ conflictingZ project_namerZ dependencyZdep_nameZ dep_versionZreqr @/usr/lib/python3.8/site-packages/pip/_internal/commands/check.pyruns2      zCheckCommand.runN)__name__ __module__ __qualname____doc__Zusager r r r r rsr) ZloggingZpip._internal.cli.base_commandrZpip._internal.operations.checkrrZpip._internal.utils.miscrZ getLoggerrZloggerrr r r r s    commands/__pycache__/show.cpython-38.pyc000064400000014265152347654150014211 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z mZddlmZeeZGd d d e Zd d ZdddZdS))absolute_importN) FeedParser) pkg_resourcescanonicalize_name)Command)ERRORSUCCESS) write_outputcs0eZdZdZdZdZfddZddZZS) ShowCommandzx Show information about one or more installed packages. The output is in RFC-compliant mail header format. z$ %prog [options] ...Tcs>tt|j|||jjddddddd|jd|jdS) Nz-fz--filesfiles store_trueFz7Show the full list of installed files for each package.)destactiondefaulthelpr)superr __init__Zcmd_optsZ add_optionparserZinsert_option_group)selfargskw __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/show.pyrszShowCommand.__init__cCs8|stdtS|}t|}t||j|jds4tStS)Nz.ERROR: Please provide a package name or names.) list_filesverbose)loggerwarningrsearch_packages_info print_resultsr rr )rZoptionsrqueryresultsrrrrun*s zShowCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvrr$ __classcell__rrrrr s  r c#sTitjD]}|t|j<q dd|D}tfddt||D}|r^tdd|dd}fdd|DD]ԉjj j d d D|jd }d }d }t tj rd rd }d d|D} fdd| D} fdd| D}drnd}nPdrXd} fdd| D} fdd| D}drnd}drd} | |d<drƈdD]"} | r| |d<qƐqt} | || } dD]}| |||<qg}|D](} | dr|| tdd q||d<|rHt||d<|Vqxd S)z Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. cSsg|] }t|qSrr).0namerrr Bsz(search_packages_info..csg|]\}}|kr|qSrr)r*r+pkg installedrrr,DszPackage(s) not found: %s, cst|fddtjDS)Ncs(g|] }dd|Dkr|jqS)cSsg|]}t|jqSr)rr+)r*Zrequiredrrrr,NszSsearch_packages_info..get_requiring_packages...)requires project_namer*r-Zcanonical_namerrr,KszHsearch_packages_info..get_requiring_packages..)rr working_set)Z package_namerr4rget_requiring_packagesIs z4search_packages_info..get_requiring_packagescsg|]}|kr|qSrrr3r.rrr,RscSsg|] }|jqSr)r2)r*Zdeprrrr,Ws)r+versionlocationr1 required_byNZRECORDcSsg|]}|ddqS),r)split)r*lrrrr,`scsg|]}tjj|qSr)ospathjoinr8r*pdistrrr,ascsg|]}tj|jqSrr=r>relpathr8r@rBrrr,bsZMETADATAzinstalled-files.txtcsg|]}tjj|qSr)r=r>r?Zegg_infor@rBrrr,jscsg|]}tj|jqSrrDr@rBrrr,kszPKG-INFOzentry_points.txt entry_pointsZ INSTALLER installer)metadata-versionsummary home-pageauthor author-emaillicensez Classifier: classifiersr )rr5rr2sortedziprrr?r7r8r1 isinstanceZDistInfoDistributionZ has_metadataZget_metadata_linesZ get_metadatastriprZfeedcloseget splitlines startswithappendlen)r"rAZ query_namesZmissingr6packageZ file_listZmetadatalinespathsrFlineZ feed_parserZ pkg_info_dictkeyrNr)rCr/rr 7sl                    r Fc Csd}t|D]\}}d}|dkr*tdtd|ddtd|d dtd |d dtd |d dtd|ddtd|ddtd|ddtd|ddtdd|dgtdd|dg|rdtd|ddtd|ddtd|d gD]}td!|q(td"|d#gD]}td!|qN|r td$|d%gD]}td!|q|d%|kr td&q |S)'zD Print the informations from installed distributions found. FTrz---zName: %sr+z Version: %sr7z Summary: %srIz Home-page: %srJz Author: %srKzAuthor-email: %srLz License: %srMz Location: %sr8z Requires: %sr0r1zRequired-by: %sr9zMetadata-Version: %srHz Installer: %srGz Classifiers:rNz %sz Entry-points:rFzFiles:r z!Cannot locate installed-files.txt) enumerater rTr?rR) Z distributionsrrZresults_printedirCZ classifierentryr\rrrr!sB  r!)FF)Z __future__rZloggingr=Z email.parserrZ pip._vendorrZpip._vendor.packaging.utilsrZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrr Zpip._internal.utils.miscr Z getLoggerr%rr r r!rrrrs       #Xcommands/__pycache__/check.cpython-38.opt-1.pyc000064400000002440152347654150015235 0ustar00U .e@sNddlZddlmZddlmZmZddlmZee Z GdddeZ dS)N)Command)check_package_set!create_package_set_from_installed) write_outputc@seZdZdZdZddZdS) CheckCommandz7Verify installed packages have compatible dependencies.z %prog [options]c Cst\}}t|\}}|D].}||j}||D]} td||| dq0q|D]4}||j}||D]\} } } td||| | | qdqN|s|s|rdStddS)Nz*%s %s requires %s, which is not installed.rz-%s %s has requirement %s, but you have %s %s.zNo broken requirements found.)rrversionr) selfZoptionsargsZ package_setZ parsing_probsZmissingZ conflictingZ project_namerZ dependencyZdep_nameZ dep_versionZreqr @/usr/lib/python3.8/site-packages/pip/_internal/commands/check.pyruns2      zCheckCommand.runN)__name__ __module__ __qualname____doc__Zusager r r r r rsr) ZloggingZpip._internal.cli.base_commandrZpip._internal.operations.checkrrZpip._internal.utils.miscrZ getLoggerrZloggerrr r r r s    commands/__pycache__/search.cpython-38.opt-1.pyc000064400000010604152347654150015426 0ustar00U .e@sddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z e!e"Z#GdddeeZ$ddZ%dddZ&ddZ'dS))absolute_importN) OrderedDict) pkg_resources)parse) xmlrpc_client)Command)SessionCommandMixin)NO_MATCHES_FOUNDSUCCESS) CommandError)PyPI)PipXmlrpcTransport)get_terminal_size) indent_log) write_outputcs8eZdZdZdZdZfddZddZdd ZZ S) SearchCommandz@Search for PyPI packages whose name or summary contains .z %prog [options] Tcs@tt|j|||jjddddtjdd|jd|jdS)Nz-iz--indexindexZURLz3Base URL of Python Package Index (default %default))destmetavardefaulthelpr) superr__init__Zcmd_optsZ add_optionr Zpypi_urlparserZinsert_option_group)selfargskw __class__A/usr/lib/python3.8/site-packages/pip/_internal/commands/search.pyr%szSearchCommand.__init__cCsT|s td|}|||}t|}d}tjrksz!print_results..cSsg|] }|jqSr)Z project_name)r?prrr r@psr,r-r5r<   z %-*s - %sz%s (%s)zINSTALLED: %s (latest)z INSTALLED: %sz=LATEST: %s (pre-release; install with "pip install --pre")z LATEST: %s)maxrZ working_setr8r>textwrapZwrapjoinrZget_distributionrr4 parse_versionZpreUnicodeEncodeError) r*Zname_column_widthr!Zinstalled_packagesr;r,r-ZlatestZ target_widthlineZdistrrr r'gsJ          r'cCs t|tdS)N)key)rIrL)r5rrr r8sr8)NN)(Z __future__rZloggingr$rJ collectionsrZ pip._vendorrZpip._vendor.packaging.versionrrLZpip._vendor.six.movesrZpip._internal.cli.base_commandrZpip._internal.cli.req_commandrZpip._internal.cli.status_codesr r Zpip._internal.exceptionsr Zpip._internal.models.indexr Zpip._internal.network.xmlrpcr Zpip._internal.utils.compatrZpip._internal.utils.loggingrZpip._internal.utils.miscrZ getLoggerr/Zloggerrr#r'r8rrrr s*              - )commands/__pycache__/uninstall.cpython-38.opt-1.pyc000064400000005206152347654150016174 0ustar00U .e @svddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZGd d d eeZd S) )absolute_import)canonicalize_name)Command)SessionCommandMixin)InstallationError)parse_requirements)install_req_from_line)(protect_pip_from_modification_on_windowscs,eZdZdZdZfddZddZZS)UninstallCommandaB Uninstall packages. pip is able to uninstall most installed packages. Known exceptions are: - Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. zU %prog [options] ... %prog [options] -r ...c sVtt|j|||jjddddgddd|jjdd d d d d |jd|jdS)Nz-rz --requirement requirementsappendfilezjUninstall all the packages listed in the given requirements file. This option can be used multiple times.)destactiondefaultmetavarhelpz-yz--yesyes store_truez2Don't ask for confirmation of uninstall deletions.)rrrr)superr __init__Zcmd_optsZ add_optionparserZinsert_option_group)selfargskw __class__D/usr/lib/python3.8/site-packages/pip/_internal/commands/uninstall.pyrs$ zUninstallCommand.__init__c Cs||}i}|D]&}t||jd}|jr||t|j<q|jD],}t|||dD]}|jrR||t|j<qRq@|stdt|jdt d|kd| D]&}|j |j |j dkd}|r|qdS) N)isolated)optionssessionzLYou must give at least one requirement to %(name)s (see "pip help %(name)s"))nameZpip)Z modifying_pipr)Z auto_confirmverbose)Zget_default_sessionrZ isolated_moder"rr rrdictr valuesZ uninstallr verbosityZcommit) rr rr!Zreqs_to_uninstallr"ZreqfilenameZuninstall_pathsetrrrrun2sB     zUninstallCommand.run)__name__ __module__ __qualname____doc__Zusagerr( __classcell__rrrrr s  r N)Z __future__rZpip._vendor.packaging.utilsrZpip._internal.cli.base_commandrZpip._internal.cli.req_commandrZpip._internal.exceptionsrZpip._internal.reqrZpip._internal.req.constructorsrZpip._internal.utils.miscr r rrrrs        commands/__pycache__/freeze.cpython-38.opt-1.pyc000064400000005540152347654150015444 0ustar00U .e @s|ddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZd d d d hZGd ddeZdS))absolute_importN) WheelCache) cmdoptions)Command) FormatControl)freeze) stdlib_pkgsZpipZ setuptoolsZ distributeZwheelcs0eZdZdZdZdZfddZddZZS) FreezeCommandzx Output installed packages in requirements format. packages are listed in a case-insensitive sorted order. z %prog [options])ext://sys.stderrr c stt|j|||jjddddgddd|jjdd d dgd d d|jjd dddddd|jjdddddd|jt|jjdddddtd|jjddddd|j d|jdS) Nz-rz --requirement requirementsappendfilez}Use the order in the given requirements file and its comments when generating output. This option can be used multiple times.)destactiondefaultmetavarhelpz-fz --find-links find_linksZURLzs        commands/__pycache__/uninstall.cpython-38.pyc000064400000005206152347654150015235 0ustar00U .e @svddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZGd d d eeZd S) )absolute_import)canonicalize_name)Command)SessionCommandMixin)InstallationError)parse_requirements)install_req_from_line)(protect_pip_from_modification_on_windowscs,eZdZdZdZfddZddZZS)UninstallCommandaB Uninstall packages. pip is able to uninstall most installed packages. Known exceptions are: - Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. zU %prog [options] ... %prog [options] -r ...c sVtt|j|||jjddddgddd|jjdd d d d d |jd|jdS)Nz-rz --requirement requirementsappendfilezjUninstall all the packages listed in the given requirements file. This option can be used multiple times.)destactiondefaultmetavarhelpz-yz--yesyes store_truez2Don't ask for confirmation of uninstall deletions.)rrrr)superr __init__Zcmd_optsZ add_optionparserZinsert_option_group)selfargskw __class__D/usr/lib/python3.8/site-packages/pip/_internal/commands/uninstall.pyrs$ zUninstallCommand.__init__c Cs||}i}|D]&}t||jd}|jr||t|j<q|jD],}t|||dD]}|jrR||t|j<qRq@|stdt|jdt d|kd| D]&}|j |j |j dkd}|r|qdS) N)isolated)optionssessionzLYou must give at least one requirement to %(name)s (see "pip help %(name)s"))nameZpip)Z modifying_pipr)Z auto_confirmverbose)Zget_default_sessionrZ isolated_moder"rr rrdictr valuesZ uninstallr verbosityZcommit) rr rr!Zreqs_to_uninstallr"ZreqfilenameZuninstall_pathsetrrrrun2sB     zUninstallCommand.run)__name__ __module__ __qualname____doc__Zusagerr( __classcell__rrrrr s  r N)Z __future__rZpip._vendor.packaging.utilsrZpip._internal.cli.base_commandrZpip._internal.cli.req_commandrZpip._internal.exceptionsrZpip._internal.reqrZpip._internal.req.constructorsrZpip._internal.utils.miscr r rrrrs        commands/__pycache__/list.cpython-38.pyc000064400000021336152347654150014201 0ustar00U .e4)@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZdd lmZmZmZdd lmZeeZGd dde ZddZddZddZ dS))absolute_importN)six) zip_longest) cmdoptions)IndexGroupCommand) CommandError) PackageFinder)SelectionPreferences)make_link_collector)dist_is_editableget_installed_distributions write_output) get_installercsdeZdZdZdZfddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ZS) ListCommandzt List installed packages, including editables. Packages are listed in a case-insensitive sorted order. z %prog [options]cstt|j|||j}|jdddddd|jddddd d|jd d ddd d|jd ddddd|jjdddddd|t|jddddd|jddddddd|jddddd |jd!d"d#d$d |jd%dd#d&d'd(ttj|j }|j d)||j d)|dS)*Nz-oz --outdated store_trueFzList outdated packages)actiondefaulthelpz-uz --uptodatezList uptodate packagesz-ez --editablezList editable projects.z-lz--localzSIf in a virtualenv that has global access, do not list globally-installed packages.z--useruserz,Only output packages installed in user-site.)destrrrz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--formatZstore list_formatcolumns)rfreezejsonzBSelect the output format among: columns (default), freeze, or json)rrrchoicesrz--not-required not_requiredz>List packages that are not dependencies of installed packages.)rrrz--exclude-editableZ store_falseinclude_editablez%Exclude editable package from output.z--include-editablez%Include editable package from output.T)rrrrr) superr__init__cmd_optsZ add_optionrZ list_pathZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/list.pyr&s zListCommand.__init__cCs(t||d}td|jd}tj||dS)zK Create a package finder appropriate to this list command. )optionsF)Z allow_yankedZallow_all_prereleases)link_collectorselection_prefs)r r prerZcreate)r!r(sessionr)r*r&r&r'_build_package_findervs z!ListCommand._build_package_findercCs|jr|jrtdt|t|j|j|j|j |j d}|j rL| ||}|jr`| ||}n|jrr|||}|||dS)Nz5Options --outdated and --uptodate cannot be combined.)Z local_onlyZ user_onlyZeditables_onlyZinclude_editablespaths)outdatedZuptodaterrZcheck_list_path_optionr ZlocalrZeditablerpathrget_not_required get_outdated get_uptodateoutput_package_listing)r!r(r"packagesr&r&r'runs&     zListCommand.runcCsdd|||DS)NcSsg|]}|j|jkr|qSr&latest_versionZparsed_version.0distr&r&r' s z,ListCommand.get_outdated..iter_packages_latest_infosr!r5r(r&r&r'r2s zListCommand.get_outdatedcCsdd|||DS)NcSsg|]}|j|jkr|qSr&r7r9r&r&r'r<s z,ListCommand.get_uptodate..r=r?r&r&r'r3s zListCommand.get_uptodatecs:t|D]}dd|Dq fdd|DS)Ncss|] }|jVqdSNkey)r:Z requirementr&r&r' sz/ListCommand.get_not_required..csh|]}|jkr|qSr&rA)r:ZpkgZdep_keysr&r' s z/ListCommand.get_not_required..)setupdateZrequires)r!r5r(r;r&rDr'r1szListCommand.get_not_requiredc cs||}|||}|D]t}d}||j}|jsDdd|D}|j|jd}||} | dkrfq| j} | j j rzd}nd}| |_ ||_ |VqW5QRXdS)NunknowncSsg|]}|jjs|qSr&)versionZ is_prerelease)r: candidater&r&r'r<sz:ListCommand.iter_packages_latest_infos..) project_nameZwheelZsdist) Z_build_sessionr-Zfind_all_candidatesrBr+Zmake_candidate_evaluatorrKZsort_best_candidaterIlinkZis_wheelr8latest_filetype) r!r5r(r,finderr;typZall_candidatesZ evaluatorZbest_candidateZremote_versionr&r&r'r>s(    z&ListCommand.iter_packages_latest_infoscCst|ddd}|jdkr:|r:t||\}}|||n^|jdkr|D]4}|jdkrltd|j|j|jqHtd|j|jqHn|jd krtt ||dS) NcSs |jSr@)rKlower)r;r&r&r'z4ListCommand.output_package_listing..rArrz %s==%s (%s)z%s==%sr) sortedrformat_for_columnsoutput_package_listing_columnsverboser rKrIlocationformat_for_json)r!r5r(dataheaderr;r&r&r'r4s"   z"ListCommand.output_package_listingcCsbt|dkr|d|t|\}}t|dkrL|ddtdd||D] }t|qPdS)NrrS cSsd|S)N-r&)xr&r&r'rQrRz.)leninserttabulatejoinmapr )r!rZr[Z pkg_stringssizesvalr&r&r'rVs    z*ListCommand.output_package_listing_columns)__name__ __module__ __qualname____doc__Zusagerr-r6r2r3r1r>r4rV __classcell__r&r&r$r'rs PrcCst|dkstdgtdd|D}|D]}ddt||D}q,g}|D](}dddt||D}||qN||fS)Nrcss|]}t|VqdSr@)r_r:r^r&r&r'rCsztabulate..cSs"g|]\}}t|tt|qSr&)maxr_strr:scr&r&r'r<sztabulate..r\cSs*g|]"\}}|dk r"t||ndqS)N)rmljustrnr&r&r'r<s)r_AssertionErrorrlrrbappend)ZvalsrdrowresultZdisplayr&r&r'ras  racCs|j}|rddddg}nddg}g}|jdks@tdd|DrJ|d|jdkr^|d |D]l}|j|jg}|r||j||j|jdkst|r||j |jdkr|t |||qb||fS) z_ Convert the package data into something usable by output_package_listing_columns. ZPackageZVersionZLatestZTyperScss|]}t|VqdSr@)r rkr&r&r'rCsz%format_for_columns..ZLocationZ Installer) r/rWanyrtrKrIr8rMr rXr)Zpkgsr(Zrunning_outdatedr[rZZprojrur&r&r'rUs(         rUcCsvg}|D]b}|jt|jd}|jdkr@|j|d<t||d<|jr`t|j|d<|j |d<| |qt |S)N)namerIrSrXZ installerr8rM) rKrZ text_typerIrWrXrr/r8rMrtrdumps)r5r(rZr;infor&r&r'rY+s      rY)!Z __future__rrZloggingZ pip._vendorrZpip._vendor.six.movesrZpip._internal.clirZpip._internal.cli.req_commandrZpip._internal.exceptionsrZpip._internal.indexrZ$pip._internal.models.selection_prefsr Z!pip._internal.self_outdated_checkr Zpip._internal.utils.miscr r r Zpip._internal.utils.packagingrZ getLoggerrfZloggerrrarUrYr&r&r&r's$           Y%commands/__pycache__/__init__.cpython-38.pyc000064400000005444152347654150014767 0ustar00U .e@s:dZddlmZddlZddlmZmZddlmZerPddl m Z ddl m Z edd Z ed e d d d fde dddfde dddfde dddfde dddfde dd d!fd"e d#d$d%fd&e d'd(d)fd*e d+d,d-fd.e d/d0d1fd2e d3d4d5fd6e d7d8d9fd:e d;de d?d@dAfgZdBdCZdDdEZdS)Fz% Package containing all pip commands )absolute_importN) OrderedDict namedtuple)MYPY_CHECK_RUNNING)Any)Command CommandInfoz module_path, class_name, summaryZinstallzpip._internal.commands.installZInstallCommandzInstall packages.Zdownloadzpip._internal.commands.downloadZDownloadCommandzDownload packages.Z uninstallz pip._internal.commands.uninstallZUninstallCommandzUninstall packages.Zfreezezpip._internal.commands.freezeZ FreezeCommandz1Output installed packages in requirements format.listzpip._internal.commands.listZ ListCommandzList installed packages.Zshowzpip._internal.commands.showZ ShowCommandz*Show information about installed packages.Zcheckzpip._internal.commands.checkZ CheckCommandz7Verify installed packages have compatible dependencies.Zconfigz$pip._internal.commands.configurationZConfigurationCommandz&Manage local and global configuration.searchzpip._internal.commands.searchZ SearchCommandzSearch PyPI for packages.Zwheelzpip._internal.commands.wheelZ WheelCommandz$Build wheels from your requirements.hashzpip._internal.commands.hashZ HashCommandz#Compute hashes of package archives.Z completionz!pip._internal.commands.completionZCompletionCommandz-A helper command used for command completion.debugzpip._internal.commands.debugZ DebugCommandz&Show information useful for debugging.helpzpip._internal.commands.helpZ HelpCommandzShow help for commands.cKs:t|\}}}t|}t||}|f||d|}|S)zF Create an instance of the Command class with the given name. )namesummary) commands_dict importlib import_modulegetattr)rkwargsZ module_path class_namermoduleZ command_classZcommandrC/usr/lib/python3.8/site-packages/pip/_internal/commands/__init__.pycreate_commandZs   rcCs6ddlm}|}||t}|r.|dSdSdS)zCommand name auto-correct.r)get_close_matchesFN)Zdifflibrlowerrkeys)rrZclose_commandsrrrget_similar_commandsgs  r)__doc__Z __future__rr collectionsrrZpip._internal.utils.typingrtypingrZpip._internal.cli.base_commandrrrrrrrrrs     < commands/__pycache__/show.cpython-38.opt-1.pyc000064400000014265152347654150015150 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z mZddlmZeeZGd d d e Zd d ZdddZdS))absolute_importN) FeedParser) pkg_resourcescanonicalize_name)Command)ERRORSUCCESS) write_outputcs0eZdZdZdZdZfddZddZZS) ShowCommandzx Show information about one or more installed packages. The output is in RFC-compliant mail header format. z$ %prog [options] ...Tcs>tt|j|||jjddddddd|jd|jdS) Nz-fz--filesfiles store_trueFz7Show the full list of installed files for each package.)destactiondefaulthelpr)superr __init__Zcmd_optsZ add_optionparserZinsert_option_group)selfargskw __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/show.pyrszShowCommand.__init__cCs8|stdtS|}t|}t||j|jds4tStS)Nz.ERROR: Please provide a package name or names.) list_filesverbose)loggerwarningrsearch_packages_info print_resultsr rr )rZoptionsrqueryresultsrrrrun*s zShowCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvrr$ __classcell__rrrrr s  r c#sTitjD]}|t|j<q dd|D}tfddt||D}|r^tdd|dd}fdd|DD]ԉjj j d d D|jd }d }d }t tj rd rd }d d|D} fdd| D} fdd| D}drnd}nPdrXd} fdd| D} fdd| D}drnd}drd} | |d<drƈdD]"} | r| |d<qƐqt} | || } dD]}| |||<qg}|D](} | dr|| tdd q||d<|rHt||d<|Vqxd S)z Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. cSsg|] }t|qSrr).0namerrr Bsz(search_packages_info..csg|]\}}|kr|qSrr)r*r+pkg installedrrr,DszPackage(s) not found: %s, cst|fddtjDS)Ncs(g|] }dd|Dkr|jqS)cSsg|]}t|jqSr)rr+)r*Zrequiredrrrr,NszSsearch_packages_info..get_requiring_packages...)requires project_namer*r-Zcanonical_namerrr,KszHsearch_packages_info..get_requiring_packages..)rr working_set)Z package_namerr4rget_requiring_packagesIs z4search_packages_info..get_requiring_packagescsg|]}|kr|qSrrr3r.rrr,RscSsg|] }|jqSr)r2)r*Zdeprrrr,Ws)r+versionlocationr1 required_byNZRECORDcSsg|]}|ddqS),r)split)r*lrrrr,`scsg|]}tjj|qSr)ospathjoinr8r*pdistrrr,ascsg|]}tj|jqSrr=r>relpathr8r@rBrrr,bsZMETADATAzinstalled-files.txtcsg|]}tjj|qSr)r=r>r?Zegg_infor@rBrrr,jscsg|]}tj|jqSrrDr@rBrrr,kszPKG-INFOzentry_points.txt entry_pointsZ INSTALLER installer)metadata-versionsummary home-pageauthor author-emaillicensez Classifier: classifiersr )rr5rr2sortedziprrr?r7r8r1 isinstanceZDistInfoDistributionZ has_metadataZget_metadata_linesZ get_metadatastriprZfeedcloseget splitlines startswithappendlen)r"rAZ query_namesZmissingr6packageZ file_listZmetadatalinespathsrFlineZ feed_parserZ pkg_info_dictkeyrNr)rCr/rr 7sl                    r Fc Csd}t|D]\}}d}|dkr*tdtd|ddtd|d dtd |d dtd |d dtd|ddtd|ddtd|ddtd|ddtdd|dgtdd|dg|rdtd|ddtd|ddtd|d gD]}td!|q(td"|d#gD]}td!|qN|r td$|d%gD]}td!|q|d%|kr td&q |S)'zD Print the informations from installed distributions found. FTrz---zName: %sr+z Version: %sr7z Summary: %srIz Home-page: %srJz Author: %srKzAuthor-email: %srLz License: %srMz Location: %sr8z Requires: %sr0r1zRequired-by: %sr9zMetadata-Version: %srHz Installer: %srGz Classifiers:rNz %sz Entry-points:rFzFiles:r z!Cannot locate installed-files.txt) enumerater rTr?rR) Z distributionsrrZresults_printedirCZ classifierentryr\rrrr!sB  r!)FF)Z __future__rZloggingr=Z email.parserrZ pip._vendorrZpip._vendor.packaging.utilsrZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrr Zpip._internal.utils.miscr Z getLoggerr%rr r r!rrrrs       #Xcommands/__pycache__/configuration.cpython-38.pyc000064400000014657152347654150016105 0ustar00U .e:@sddlZddlZddlZddlmZddlmZmZddlm Z m Z m Z ddl m Z ddlmZmZeeZGdddeZdS) N)Command)ERRORSUCCESS) Configurationget_configuration_fileskinds)PipError)get_prog write_outputcsxeZdZdZdZdZfddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZZS)ConfigurationCommanda9Manage local and global configuration. Subcommands: list: List the active configuration (or from the file specified) edit: Edit the configuration file in an editor get: Get the value associated with name set: Set the name=value unset: Unset the value associated with name If none of --user, --global and --site are passed, a virtual environment configuration file is used if one is active and the file exists. Otherwise, all modifications happen on the to the user file by default. Tz %prog [] list %prog [] [--editor ] edit %prog [] get name %prog [] set name value %prog [] unset name cstt|j||d|_|jjdddddd|jjdddd d d|jjd d dd d d|jjdddd dd|jd|jdS)Nz--editoreditorZstorez\Editor to use to edit the file. Uses VISUAL or EDITOR environment variables if not provided.)destactiondefaulthelpz--global global_file store_trueFz+Use the system-wide configuration file onlyz--user user_filez$Use the user configuration file onlyz--site site_filez3Use the current environment configuration file onlyr)superr __init__ configurationZcmd_optsZ add_optionparserZinsert_option_group)selfargskwargs __class__H/usr/lib/python3.8/site-packages/pip/_internal/commands/configuration.pyr0s> zConfigurationCommand.__init__c Cs|j|j|j|j|jd}|r*|d|krHtddt |t S|d}z|j ||dkd}Wn:t k r}zt|j dt WYSd}~XYnXt|j|d|_|jz||||ddWn<t k r}zt|j dt WYSd}~XYnXtS) N)listeditgetsetunsetrzNeed an action ({}) to perform.z, )r"r#r$r!) need_value)isolated load_only) list_valuesopen_in_editorget_nameset_name_value unset_nameloggererrorformatjoinsortedr_determine_filerrrZ isolated_moderloadr)roptionsrZhandlersrr'errrrunZs>    zConfigurationCommand.runcCsddtj|jftj|jftj|jffD}|s`|s8dStddttjDrXtjStjSnt |dkrt|dSt ddS)NcSsg|]\}}|r|qSrr).0keyvaluerrr sz8ConfigurationCommand._determine_file..css|]}tj|VqdS)N)ospathexists)r8Zsite_config_filerrr sz7ConfigurationCommand._determine_file..r(rzLNeed exactly one file to operate upon (--user, --site, --global) to perform.) rZUSERrZGLOBALrZSITEranyrlenr)rr5r%Z file_optionsrrrr3s$     z$ConfigurationCommand._determine_filecCs8|j|dddt|jD]\}}td||qdS)Nr rnz%s=%r) _get_n_argsr2ritemsr rr5rr9r:rrrr)sz ConfigurationCommand.list_valuescCs*|j|ddd}|j|}td|dS)Nz get [name]r(rBz%s)rDrZ get_valuer rFrrrr+s zConfigurationCommand.get_namecCs.|j|ddd\}}|j|||dS)Nzset [name] [value]rB)rDrZ set_value_save_configurationrFrrrr,sz#ConfigurationCommand.set_name_valuecCs(|j|ddd}|j||dS)Nz unset [name]r(rB)rDrZ unset_valuerH)rr5rr9rrrr-s zConfigurationCommand.unset_namec Csp||}|j}|dkr$tdzt||gWn4tjk rj}ztd|jW5d}~XYnXdS)Nz%Could not determine appropriate file.z*Editor Subprocess exited with exit code {}) _determine_editorrZget_file_to_editr subprocessZ check_callZCalledProcessErrorr0 returncode)rr5rr Zfnamer6rrrr*s  z#ConfigurationCommand.open_in_editorcCs<t||kr$d|t|}t||dkr4|dS|SdS)zJHelper to make sure the command got the right number of arguments zJGot unexpected number of arguments, expected {}. (example: "{} config {}")r(rN)rAr0r r)rrZexamplerCmsgrrrrDs z ConfigurationCommand._get_n_argscCs>z|jWn*tk r8tjdddtdYnXdS)Nz:Unable to save configuration. Please report this as a bug.r()exc_infozInternal Error.)rZsave Exceptionr.r/r)rrrrrHsz(ConfigurationCommand._save_configurationcCsD|jdk r|jSdtjkr$tjdSdtjkr8tjdStddS)NZVISUALZEDITORz"Could not determine editor to use.)r r<environr)rr5rrrrIs     z&ConfigurationCommand._determine_editor)__name__ __module__ __qualname____doc__Zignore_require_venvZusagerr7r3r)r+r,r-r*rDrHrI __classcell__rrrrr s *+ r )Zloggingr<rJZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrrZpip._internal.configurationrrrZpip._internal.exceptionsrZpip._internal.utils.miscr r Z getLoggerrPr.r rrrrs   commands/__pycache__/completion.cpython-38.pyc000064400000005705152347654150015401 0ustar00U .e @sXddlmZddlZddlZddlmZddlmZdZdddd Z Gd d d eZ dS) )absolute_importN)Command)get_progzJ # pip %(shell)s completion start%(script)s# pip %(shell)s completion end a _pip_completion() { COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \ COMP_CWORD=$COMP_CWORD \ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) } complete -o default -F _pip_completion %(prog)s aM function _pip_completion { local words cword read -Ac words read -cn cword reply=( $( COMP_WORDS="$words[*]" \ COMP_CWORD=$(( cword-1 )) \ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) } compctl -K _pip_completion %(prog)s aw function __fish_complete_pip set -lx COMP_WORDS (commandline -o) "" set -lx COMP_CWORD ( \ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \ ) set -lx PIP_AUTO_COMPLETE 1 string split \ -- (eval $COMP_WORDS[1]) end complete -fa "(__fish_complete_pip)" -c %(prog)s )bashzshfishcs,eZdZdZdZfddZddZZS)CompletionCommandz3A helper command to be used for command completion.Tcsltt|j|||j}|jddddddd|jdd dd dd d|jd d ddddd|jd|dS)Nz--bashz-b store_constrshellzEmit completion code for bash)actionconstdesthelpz--zshz-zrzEmit completion code for zshz--fishz-frzEmit completion code for fishr)superr__init__cmd_optsZ add_optionparserZinsert_option_group)selfargskwr __class__E/usr/lib/python3.8/site-packages/pip/_internal/commands/completion.pyr8s6zCompletionCommand.__init__cCsrt}ddt|D}|j|krXtt|jddti}tt ||jdnt j dd |dS) z-Prints the completion code of the given shellcSsg|] }d|qS)z--r).0r rrr Usz)CompletionCommand.run..prog)scriptr zERROR: You must pass %s z or N)COMPLETION_SCRIPTSkeyssortedr textwrapdedentgetrprintBASE_COMPLETIONsysstderrwritejoin)rZoptionsrZshellsZ shell_optionsrrrrrunRs   zCompletionCommand.run)__name__ __module__ __qualname____doc__Zignore_require_venvrr+ __classcell__rrrrr3s r) Z __future__rr'r"Zpip._internal.cli.base_commandrZpip._internal.utils.miscrr&rrrrrrs     #commands/__pycache__/completion.cpython-38.opt-1.pyc000064400000005705152347654150016340 0ustar00U .e @sXddlmZddlZddlZddlmZddlmZdZdddd Z Gd d d eZ dS) )absolute_importN)Command)get_progzJ # pip %(shell)s completion start%(script)s# pip %(shell)s completion end a _pip_completion() { COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \ COMP_CWORD=$COMP_CWORD \ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) } complete -o default -F _pip_completion %(prog)s aM function _pip_completion { local words cword read -Ac words read -cn cword reply=( $( COMP_WORDS="$words[*]" \ COMP_CWORD=$(( cword-1 )) \ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) } compctl -K _pip_completion %(prog)s aw function __fish_complete_pip set -lx COMP_WORDS (commandline -o) "" set -lx COMP_CWORD ( \ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \ ) set -lx PIP_AUTO_COMPLETE 1 string split \ -- (eval $COMP_WORDS[1]) end complete -fa "(__fish_complete_pip)" -c %(prog)s )bashzshfishcs,eZdZdZdZfddZddZZS)CompletionCommandz3A helper command to be used for command completion.Tcsltt|j|||j}|jddddddd|jdd dd dd d|jd d ddddd|jd|dS)Nz--bashz-b store_constrshellzEmit completion code for bash)actionconstdesthelpz--zshz-zrzEmit completion code for zshz--fishz-frzEmit completion code for fishr)superr__init__cmd_optsZ add_optionparserZinsert_option_group)selfargskwr __class__E/usr/lib/python3.8/site-packages/pip/_internal/commands/completion.pyr8s6zCompletionCommand.__init__cCsrt}ddt|D}|j|krXtt|jddti}tt ||jdnt j dd |dS) z-Prints the completion code of the given shellcSsg|] }d|qS)z--r).0r rrr Usz)CompletionCommand.run..prog)scriptr zERROR: You must pass %s z or N)COMPLETION_SCRIPTSkeyssortedr textwrapdedentgetrprintBASE_COMPLETIONsysstderrwritejoin)rZoptionsrZshellsZ shell_optionsrrrrrunRs   zCompletionCommand.run)__name__ __module__ __qualname____doc__Zignore_require_venvrr+ __classcell__rrrrr3s r) Z __future__rr'r"Zpip._internal.cli.base_commandrZpip._internal.utils.miscrr&rrrrrrs     #commands/__pycache__/download.cpython-38.pyc000064400000010314152347654150015027 0ustar00U .e@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZmZmZdd lmZeeZGd d d e ZdS) )absolute_importN) cmdoptions)make_target_python)RequirementCommand)RequirementSet)RequirementTracker)check_path_owner) ensure_dirnormalize_path write_output) TempDirectorycs,eZdZdZdZfddZddZZS)DownloadCommandaL Download packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports downloading from "requirements files", which provide an easy way to specify a whole environment to be downloaded. a %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] ... %prog [options] ... %prog [options] ...c sNtt|j|||j}|t|t|t|t |t |t |t |t |t|t|t|t|t|t|t|t|jddddddtjddt|ttj|j}|jd ||jd |dS) Nz-dz--destz--destination-dirz--destination-directory download_dirdirzDownload packages into .)destmetavardefaulthelpr)superr __init__cmd_optsZ add_optionrZ constraintsZ requirements build_dirZno_depsZglobal_optionsZ no_binaryZ only_binaryZ prefer_binarysrcZpreno_cleanrequire_hashesZ progress_barZno_build_isolationZ use_pep517Z no_use_pep517oscurdirZadd_target_python_optionsZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrZ index_opts __class__C/usr/lib/python3.8/site-packages/pip/_internal/commands/download.pyr)sF zDownloadCommand.__init__c CsLd|_g|_t|tj|j|_t|j |_ t |j | |}t |}|j |||d}|jph|j }|jrt|jstd|jd|_t}t|j|dd}t|jd} || ||||d|j||||j d} |j| ||||jd} | | d d d | jD} | r$td | |js4| W5QRXW5QRX| S) NT)optionssession target_pythonzThe directory '%s' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.Zdownload)deleteZkind)r)Ztemp_build_dirr% req_trackerr)preparerfinderr&r%Zpy_version_info cSsg|] }|jqSr#)name).0Zreqr#r#r$ sz'DownloadCommand.run..zSuccessfully downloaded %s)!Zignore_installedZ editablesrZcheck_dist_restrictionrpathabspathZsrc_dirr rr Zget_default_sessionrZ_build_package_finderrr cache_dirrloggerZwarningrr rrZpopulate_requirement_setZmake_requirement_preparerZ make_resolverZpython_versionZresolvejoinZsuccessfully_downloadedr Z cleanup_files) rr%rr&r'r+Z build_deleter)Z directoryZrequirement_setr*ZresolverZ downloadedr#r#r$runQsv         zDownloadCommand.run)__name__ __module__ __qualname____doc__Zusagerr5 __classcell__r#r#r!r$r s  (r )Z __future__rZloggingrZpip._internal.clirZpip._internal.cli.cmdoptionsrZpip._internal.cli.req_commandrZpip._internal.reqrZpip._internal.req.req_trackerrZpip._internal.utils.filesystemrZpip._internal.utils.miscr r r Zpip._internal.utils.temp_dirr Z getLoggerr6r3r r#r#r#r$s         commands/__pycache__/configuration.cpython-38.opt-1.pyc000064400000014657152347654150017044 0ustar00U .e:@sddlZddlZddlZddlmZddlmZmZddlm Z m Z m Z ddl m Z ddlmZmZeeZGdddeZdS) N)Command)ERRORSUCCESS) Configurationget_configuration_fileskinds)PipError)get_prog write_outputcsxeZdZdZdZdZfddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZZS)ConfigurationCommanda9Manage local and global configuration. Subcommands: list: List the active configuration (or from the file specified) edit: Edit the configuration file in an editor get: Get the value associated with name set: Set the name=value unset: Unset the value associated with name If none of --user, --global and --site are passed, a virtual environment configuration file is used if one is active and the file exists. Otherwise, all modifications happen on the to the user file by default. Tz %prog [] list %prog [] [--editor ] edit %prog [] get name %prog [] set name value %prog [] unset name cstt|j||d|_|jjdddddd|jjdddd d d|jjd d dd d d|jjdddd dd|jd|jdS)Nz--editoreditorZstorez\Editor to use to edit the file. Uses VISUAL or EDITOR environment variables if not provided.)destactiondefaulthelpz--global global_file store_trueFz+Use the system-wide configuration file onlyz--user user_filez$Use the user configuration file onlyz--site site_filez3Use the current environment configuration file onlyr)superr __init__ configurationZcmd_optsZ add_optionparserZinsert_option_group)selfargskwargs __class__H/usr/lib/python3.8/site-packages/pip/_internal/commands/configuration.pyr0s> zConfigurationCommand.__init__c Cs|j|j|j|j|jd}|r*|d|krHtddt |t S|d}z|j ||dkd}Wn:t k r}zt|j dt WYSd}~XYnXt|j|d|_|jz||||ddWn<t k r}zt|j dt WYSd}~XYnXtS) N)listeditgetsetunsetrzNeed an action ({}) to perform.z, )r"r#r$r!) need_value)isolated load_only) list_valuesopen_in_editorget_nameset_name_value unset_nameloggererrorformatjoinsortedr_determine_filerrrZ isolated_moderloadr)roptionsrZhandlersrr'errrrunZs>    zConfigurationCommand.runcCsddtj|jftj|jftj|jffD}|s`|s8dStddttjDrXtjStjSnt |dkrt|dSt ddS)NcSsg|]\}}|r|qSrr).0keyvaluerrr sz8ConfigurationCommand._determine_file..css|]}tj|VqdS)N)ospathexists)r8Zsite_config_filerrr sz7ConfigurationCommand._determine_file..r(rzLNeed exactly one file to operate upon (--user, --site, --global) to perform.) rZUSERrZGLOBALrZSITEranyrlenr)rr5r%Z file_optionsrrrr3s$     z$ConfigurationCommand._determine_filecCs8|j|dddt|jD]\}}td||qdS)Nr rnz%s=%r) _get_n_argsr2ritemsr rr5rr9r:rrrr)sz ConfigurationCommand.list_valuescCs*|j|ddd}|j|}td|dS)Nz get [name]r(rBz%s)rDrZ get_valuer rFrrrr+s zConfigurationCommand.get_namecCs.|j|ddd\}}|j|||dS)Nzset [name] [value]rB)rDrZ set_value_save_configurationrFrrrr,sz#ConfigurationCommand.set_name_valuecCs(|j|ddd}|j||dS)Nz unset [name]r(rB)rDrZ unset_valuerH)rr5rr9rrrr-s zConfigurationCommand.unset_namec Csp||}|j}|dkr$tdzt||gWn4tjk rj}ztd|jW5d}~XYnXdS)Nz%Could not determine appropriate file.z*Editor Subprocess exited with exit code {}) _determine_editorrZget_file_to_editr subprocessZ check_callZCalledProcessErrorr0 returncode)rr5rr Zfnamer6rrrr*s  z#ConfigurationCommand.open_in_editorcCs<t||kr$d|t|}t||dkr4|dS|SdS)zJHelper to make sure the command got the right number of arguments zJGot unexpected number of arguments, expected {}. (example: "{} config {}")r(rN)rAr0r r)rrZexamplerCmsgrrrrDs z ConfigurationCommand._get_n_argscCs>z|jWn*tk r8tjdddtdYnXdS)Nz:Unable to save configuration. Please report this as a bug.r()exc_infozInternal Error.)rZsave Exceptionr.r/r)rrrrrHsz(ConfigurationCommand._save_configurationcCsD|jdk r|jSdtjkr$tjdSdtjkr8tjdStddS)NZVISUALZEDITORz"Could not determine editor to use.)r r<environr)rr5rrrrIs     z&ConfigurationCommand._determine_editor)__name__ __module__ __qualname____doc__Zignore_require_venvZusagerr7r3r)r+r,r-r*rDrHrI __classcell__rrrrr s *+ r )Zloggingr<rJZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrrZpip._internal.configurationrrrZpip._internal.exceptionsrZpip._internal.utils.miscr r Z getLoggerrPr.r rrrrs   commands/__pycache__/debug.cpython-38.opt-1.pyc000064400000006313152347654150015251 0ustar00U .eB @sddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZdd lmZerdd lmZmZdd lmZeeZd dZddZddZGdddeZ dS))absolute_importN) cmdoptions)Command)make_target_python)SUCCESS) indent_log)get_pip_version)MYPY_CHECK_RUNNING) format_tag)AnyList)ValuescCstd||dS)Nz{}: {})loggerinfoformat)namevaluer@/usr/lib/python3.8/site-packages/pip/_internal/commands/debug.py show_valuesrc CsFtdttdr"tj}|j}nd}ttd|W5QRXdS)Nzsys.implementation:implementationr)rrhasattrsysrrrr)rZimplementation_namerrrshow_sys_implementations  rc Csd}t|}|}|}d}|r.d|}dt||}t||jdkrpt||krpd}|d|}nd}t8|D]}tt |q|rdj|d }t|W5QRXdS) N rz (target: {})zCompatible tags: {}{}TFz?... [First {tag_limit} tags shown. Pass --verbose to show all.]) tag_limit) rZget_tagsZ format_givenrlenrrverboserr ) optionsrZ target_pythonZtagsZformatted_targetsuffixmsgZ tags_limitedtagrrr show_tags,s,  r$cs0eZdZdZdZdZfddZddZZS) DebugCommandz$ Display debug information. z %prog Tcs4tt|j|||j}t||jd|dS)Nr)superr%__init__cmd_optsrZadd_target_python_optionsparserZinsert_option_group)selfargskwr( __class__rrr'Ws zDebugCommand.__init__cCsvtdtdttdtjtdtjtdttdttdt tdtj t t |tS) NzThis command is only meant for debugging. Do not use this with automation for parsing and getting these details, since the output and options of this command may change without notice.z pip versionz sys.versionzsys.executablezsys.getdefaultencodingzsys.getfilesystemencodingzlocale.getpreferredencodingz sys.platform)rZwarningrrrversion executablegetdefaultencodinggetfilesystemencodinglocaleZgetpreferredencodingplatformrr$r)r*r r+rrrrun^s     zDebugCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvr'r5 __classcell__rrr-rr%Ns  r%)!Z __future__rr3ZloggingrZpip._internal.clirZpip._internal.cli.base_commandrZpip._internal.cli.cmdoptionsrZpip._internal.cli.status_codesrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.typingr Zpip._internal.wheelr typingr r Zoptparser Z getLoggerr6rrrr$r%rrrrs&            "commands/__pycache__/freeze.cpython-38.pyc000064400000005540152347654150014505 0ustar00U .e @s|ddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZd d d d hZGd ddeZdS))absolute_importN) WheelCache) cmdoptions)Command) FormatControl)freeze) stdlib_pkgsZpipZ setuptoolsZ distributeZwheelcs0eZdZdZdZdZfddZddZZS) FreezeCommandzx Output installed packages in requirements format. packages are listed in a case-insensitive sorted order. z %prog [options])ext://sys.stderrr c stt|j|||jjddddgddd|jjdd d dgd d d|jjd dddddd|jjdddddd|jt|jjdddddtd|jjddddd|j d|jdS) Nz-rz --requirement requirementsappendfilez}Use the order in the given requirements file and its comments when generating output. This option can be used multiple times.)destactiondefaultmetavarhelpz-fz --find-links find_linksZURLzs        commands/__pycache__/help.cpython-38.pyc000064400000002242152347654150014151 0ustar00U .e@sDddlmZddlmZddlmZddlmZGdddeZdS))absolute_import)Command)SUCCESS) CommandErrorc@s eZdZdZdZdZddZdS) HelpCommandzShow help for commandsz %prog Tc Csddlm}m}m}z |d}Wntk r8tYSX||krt||}d|g}|rf|d|td|||} | j tS)Nr) commands_dictcreate_commandget_similar_commandszunknown command "%s"zmaybe you meant "%s"z - ) Zpip._internal.commandsrrr IndexErrorrappendrjoinparserZ print_help) selfZoptionsargsrrr Zcmd_nameZguessmsgZcommandr?/usr/lib/python3.8/site-packages/pip/_internal/commands/help.pyruns    zHelpCommand.runN)__name__ __module__ __qualname____doc__ZusageZignore_require_venvrrrrrr srN) Z __future__rZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrZpip._internal.exceptionsrrrrrrs    commands/__pycache__/hash.cpython-38.pyc000064400000003706152347654150014152 0ustar00U .e@sddlmZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z mZeeZGdddeZd d ZdS) )absolute_importN)Command)ERROR) FAVORITE_HASH STRONG_HASHES) read_chunks write_outputcs0eZdZdZdZdZfddZddZZS) HashCommandz Compute a hash of a local package archive. These can be used with --hash in a requirements file to do repeatable installs. z%prog [options] ...Tc sJtt|j|||jjdddtdtddtd|j d|jdS) Nz-az --algorithm algorithmZstorez$The hash algorithm to use: one of %sz, )destchoicesactiondefaulthelpr) superr __init__Zcmd_optsZ add_optionrrjoinparserZinsert_option_group)selfargskw __class__?/usr/lib/python3.8/site-packages/pip/_internal/commands/hash.pyrszHashCommand.__init__cCs>|s|jtjtS|j}|D]}td||t||q dS)Nz%s: --hash=%s:%s)rZ print_usagesysstderrrr r _hash_of_file)rZoptionsrr pathrrrrun)szHashCommand.run) __name__ __module__ __qualname____doc__ZusageZignore_require_venvrr __classcell__rrrrr s  r c Cs@t|d(}t|}t|D]}||qW5QRX|S)z!Return the hash digest of a file.rb)openhashlibnewrupdateZ hexdigest)rr archivehashchunkrrrr4s    r)Z __future__rr'ZloggingrZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrZpip._internal.utils.hashesrrZpip._internal.utils.miscrrZ getLoggerr Zloggerr rrrrrs    "commands/__pycache__/install.cpython-38.pyc000064400000034172152347654150014676 0ustar00U .e_@sddlmZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZmZdd lmZmZmZdd lmZddl m!Z!ddl"m#Z#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5e1rddl m6Z6ddl7m8Z8m9Z9m:Z:ddl;mZ>ddl4m?Z?e@eAZBddZCddZDd d!ZEGd"d#d#eZFd$d%ZGd&d'ZHdS)()absolute_importN)path) SUPPRESS_HELP) pkg_resources)canonicalize_name) WheelCache) cmdoptions)make_target_python)RequirementCommand)ERRORSUCCESS) CommandErrorInstallationErrorPreviousBuildDirErrordistutils_scheme)check_install_conflicts)RequirementSetinstall_given_reqs)RequirementTracker)check_path_owner) ensure_dirget_installed_version(protect_pip_from_modification_on_windows write_output) TempDirectory)MYPY_CHECK_RUNNING)virtualenv_no_global) WheelBuilder)Values)AnyListOptional) FormatControl)InstallRequirement)BinaryAllowedPredicatecCs(z ddl}Wntk r"YdSXdS)z8 Return whether the wheel package is installed. rNFT)wheel ImportError)r&r(B/usr/lib/python3.8/site-packages/pip/_internal/commands/install.pyis_wheel_installed<s  r*cCs*t}|j|dd}|r&|j|dd|S)zQ Build wheels for requirements, depending on whether wheel is installed. T)Z should_unpack)r*Zbuild)builderpep517_requirementslegacy_requirementsZshould_build_legacybuild_failuresr(r(r) build_wheelsHs r/csfdd}|S)Ncs&|jr dSt|j}|}d|kS)NTZbinary) use_pep517rnameZget_allowed_formats)reqZcanonical_nameZallowed_formatsformat_controlr(r)check_binary_allowedhs   z6get_check_binary_allowed..check_binary_allowedr()r4r5r(r3r)get_check_binary_allowedfs r6cs<eZdZdZdZfddZddZddZd d ZZ S) InstallCommandaI Install packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports installing from "requirements files", which provide an easy way to specify a whole environment to be installed. a% %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...cs^tt|j|||j}|t|t|t|t |t |jdddddddt ||jddd d d |jd dd t d |jdddddd|jdddddd|t |t|jdddd dd |jdddddgdd|jddd d d |jd!d"d#d d$d |t|t|t|t|t|t|jd%d d&d'd(d)|jd*d d&d+d,|jd-d d.d'd/d)|jd0d d1d'd2d)|t|t|t|t|t|tttj|j}|jd3||jd3|dS)4Nz-tz--target target_dirdirzInstall packages into . By default this will not replace existing files/folders in . Use --upgrade to replace existing packages in with new versions.)destmetavardefaulthelp--user use_user_site store_truezInstall to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.))r:actionr=z --no-userZ store_falsez--root root_pathz=Install everything relative to this alternate root directory.z--prefix prefix_pathzIInstallation prefix where lib, bin and other top-level folders are placedz-Uz --upgradeupgradezUpgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.z--upgrade-strategyupgrade_strategyzonly-if-neededZeageraGDetermines how dependency upgrading should be handled [default: %default]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not satisfy the requirements of the upgraded package(s).)r:r<choicesr=z--force-reinstallforce_reinstallz;Reinstall all packages even if they are already up-to-date.z-Iz--ignore-installedignore_installedzIgnore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!z --compilecompileTz'Compile Python source files to bytecode)rAr:r<r=z --no-compilez.Do not compile Python source files to bytecode)rAr:r=z--no-warn-script-locationwarn_script_locationz0Do not warn when installing scripts outside PATHz--no-warn-conflictswarn_about_conflictsz%Do not warn about broken dependenciesr)superr7__init__cmd_optsZ add_optionr requirementsZ constraintsZno_depsZpreZeditableZadd_target_python_optionsr build_dirsrcignore_requires_pythonZno_build_isolationr0Z no_use_pep517install_optionsglobal_optionsZ no_binaryZ only_binaryZ prefer_binaryno_cleanrequire_hashesZ progress_barZmake_option_groupZ index_groupparserZinsert_option_group)selfargskwrNZ index_opts __class__r(r)rMs   zInstallCommand.__init__c*Cst|dd}tdkrZ|sZttjd}|dkrLttjd}t d|d}|j rj|j }|j rtj|j |_ tj|dd tj|j|_|jpg}|jr|jrtd trtd |d |d d}d}|jrJd|_tj|j|_tj|jr,tj|js,tdtdd}|j}|d||jpTg} ||} t|} |j || | |j!d} |j"p|j } t#|j$|j%}|j$rt&|j$st d|j$d|_$t'}t|j | dd}t(|j)|j d}zz*|,|||| | ||j-|||d}|j.|| | |||j|j|j!|j/||j0d }|1|z|2d}Wnt3k rzd}Yn X|j4dk}t5|dt6| j%}g}g}|j78D]$}|j0r||n ||qt9||gg|d}t:|||d}|rtd;d o.|j?}|r@|@||jA}|jrRd!}tB||| |jC||j|jD||jd" }tE|j||jC|j|jFd#} tGH| }!tI|tJKd$d%}"g}#|"D]R}|jL}$z$tM|jL|!d&}%|%r|$d'|%7}$WntNk rYnX|#|$qd(<|#}&|&r tOd)|&WntPk r}'zN|jQd*k}(tR|'|(|j})t jS|)|(d+tTWYWHW5QRW5QRSd}'~'XYntUk rd|_"YnXW5|j"s|*|+XW5QRXW5QRX|jr|V|j||j tWS),NcSs ttdpttdotjtjkS)NZ real_prefix base_prefix)hasattrsysr]prefixr(r(r(r)is_venvs   z#InstallCommand.run..is_venvrz __main__.pyz -m pipzgRunning pip install with root privileges is generally not a good idea. Try `%s install --user` instead.zto-satisfy-onlyT)Z check_targetzVCan not combine '--user' and '--prefix' as they imply different installation locationszZCan not perform a '--user' install. User site-packages are not visible in this virtualenv.r>z --prefix=z=Target path exists but is not a directory, will not continue.target)kindz--home=)optionssession target_pythonrRzThe directory '%s' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.Zinstall)deleterc)rVZcheck_supported_wheels)Ztemp_build_dirrd req_tracker) preparerfinderrerd wheel_cacher?rHrRrGrEr0Zpip) modifying_pip)Z build_optionsrTr5)r+r,r-zPCould not build wheels for {} which use PEP 517 and cannot be installed directlyz, css|] }|jVqdSN)r1).0rr(r(r) sz%InstallCommand.run..F)roothomer`Z pycompilerJr?)userrrrqr`isolatedr1)key) working_set- zSuccessfully installed %sexc_info)XrZcheck_install_build_globalosgetuidrbasenamer_argv executableloggerwarningrDrErPabspathZcheck_dist_restrictionZsrc_dirrSr?rCr rrappendr8rHexistsisdirrrTZget_default_sessionr Z_build_package_finderrRrUr cache_dirr4rrrrVZ cleanup_filesZcleanupZpopulate_requirement_setZmake_requirement_preparerZ make_resolverrGr0ZresolveZget_requirementKeyErrorZ satisfied_byrr6rOvaluesrr/formatjoinZget_installation_orderZignore_dependenciesrK_warn_about_conflictsrJrrBrIget_lib_location_guessesZ isolated_moderZ WorkingSetsortedoperator attrgetterr1r ExceptionrEnvironmentError verbositycreate_env_error_messageerrorr r_handle_target_dirr )*rXrdrYraZcommandrErStarget_temp_dirZtarget_temp_dir_pathrTrerfrjZ build_deleterkrhZ directoryZrequirement_setriZresolverZpip_reqrlr5r-r,r2Z wheel_builderr. to_installZshould_warn_about_conflictsrJZ installedZ lib_locationsrvZreqsitemsitemZinstalled_versionZinstalled_descrshow_tracebackmessager(r(r)runs                   4 zInstallCommand.runc sft|g}|Jtd|jd}|d}|d}|d}tj|rP||tj|rn||krn||tj|r|||D]} t| D]} | |krtj|| tfdd|ddDrqtj|| } tj| r>|st d | qtj | rt d | qtj | r4t | n t| t tj| | | qqW5QRXdS) N)rrpurelibplatlibdatac3s|]}|VqdSrm) startswith)rnsddirr(r)rp+sz4InstallCommand._handle_target_dir..zKTarget directory %s already exists. Specify --upgrade to force replacement.zTarget directory %s already exists and is a link. Pip will not automatically replace links, please remove if replacement is desired.)rrrr|rrlistdirranyrrislinkrshutilZrmtreeremoveZmove) rXr8rrDZ lib_dir_listschemeZ purelib_dirZ platlib_dirZdata_dirZlib_dirrZtarget_item_dirr(rr)rsP        z!InstallCommand._handle_target_dirc Cszt|\}}Wn$tk r4tjdddYdSX|\}}|D]2}||d}||D]}td|||dqZqB|D]8}||d}||D]\} } } td||| | | qqzdS)NzError checking for conflicts.Trzrz*%s %s requires %s, which is not installed.ryzF%s %s has requirement %s, but you'll have %s %s which is incompatible.)rrrrZcritical) rXrZ package_setZ _dep_infoZmissingZ conflictingZ project_nameversionZ dependencyZdep_nameZ dep_versionr2r(r(r)rIs4   z$InstallCommand._warn_about_conflicts) __name__ __module__ __qualname____doc__ZusagerMrrr __classcell__r(r(r[r)r7ss  w8r7cOstd||}|d|dgS)Nrrr)rr)rYkwargsrr(r(r)rdsrcCsg}|d|s,|d|t|n |d|dd7<|jtjkrd}d}|st||d|gn |||d d |dS) z{Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. z5Could not install packages due to an EnvironmentErrorz: .r z"Consider using the `--user` optionzCheck the permissionsz or z. r)rstrerrnoZEACCESextendlowerrstrip)rrZusing_user_sitepartsZuser_option_partZpermissions_partr(r(r)ris&      r)IZ __future__rrZloggingrr|rr_rZoptparserZ pip._vendorrZpip._vendor.packaging.utilsrZpip._internal.cacherZpip._internal.clirZpip._internal.cli.cmdoptionsr Zpip._internal.cli.req_commandr Zpip._internal.cli.status_codesr r Zpip._internal.exceptionsr rrZpip._internal.locationsrZpip._internal.operations.checkrZpip._internal.reqrrZpip._internal.req.req_trackerrZpip._internal.utils.filesystemrZpip._internal.utils.miscrrrrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrZpip._internal.wheelrrtypingr r!r"Z#pip._internal.models.format_controlr#Zpip._internal.req.req_installr$r%Z getLoggerrrr*r/r6r7rrr(r(r(r)sT                        tcommands/__pycache__/help.cpython-38.opt-1.pyc000064400000002242152347654150015110 0ustar00U .e@sDddlmZddlmZddlmZddlmZGdddeZdS))absolute_import)Command)SUCCESS) CommandErrorc@s eZdZdZdZdZddZdS) HelpCommandzShow help for commandsz %prog Tc Csddlm}m}m}z |d}Wntk r8tYSX||krt||}d|g}|rf|d|td|||} | j tS)Nr) commands_dictcreate_commandget_similar_commandszunknown command "%s"zmaybe you meant "%s"z - ) Zpip._internal.commandsrrr IndexErrorrappendrjoinparserZ print_help) selfZoptionsargsrrr Zcmd_nameZguessmsgZcommandr?/usr/lib/python3.8/site-packages/pip/_internal/commands/help.pyruns    zHelpCommand.runN)__name__ __module__ __qualname____doc__ZusageZignore_require_venvrrrrrr srN) Z __future__rZpip._internal.cli.base_commandrZpip._internal.cli.status_codesrZpip._internal.exceptionsrrrrrrs    commands/__pycache__/__init__.cpython-38.opt-1.pyc000064400000005444152347654150015726 0ustar00U .e@s:dZddlmZddlZddlmZmZddlmZerPddl m Z ddl m Z edd Z ed e d d d fde dddfde dddfde dddfde dddfde dd d!fd"e d#d$d%fd&e d'd(d)fd*e d+d,d-fd.e d/d0d1fd2e d3d4d5fd6e d7d8d9fd:e d;de d?d@dAfgZdBdCZdDdEZdS)Fz% Package containing all pip commands )absolute_importN) OrderedDict namedtuple)MYPY_CHECK_RUNNING)Any)Command CommandInfoz module_path, class_name, summaryZinstallzpip._internal.commands.installZInstallCommandzInstall packages.Zdownloadzpip._internal.commands.downloadZDownloadCommandzDownload packages.Z uninstallz pip._internal.commands.uninstallZUninstallCommandzUninstall packages.Zfreezezpip._internal.commands.freezeZ FreezeCommandz1Output installed packages in requirements format.listzpip._internal.commands.listZ ListCommandzList installed packages.Zshowzpip._internal.commands.showZ ShowCommandz*Show information about installed packages.Zcheckzpip._internal.commands.checkZ CheckCommandz7Verify installed packages have compatible dependencies.Zconfigz$pip._internal.commands.configurationZConfigurationCommandz&Manage local and global configuration.searchzpip._internal.commands.searchZ SearchCommandzSearch PyPI for packages.Zwheelzpip._internal.commands.wheelZ WheelCommandz$Build wheels from your requirements.hashzpip._internal.commands.hashZ HashCommandz#Compute hashes of package archives.Z completionz!pip._internal.commands.completionZCompletionCommandz-A helper command used for command completion.debugzpip._internal.commands.debugZ DebugCommandz&Show information useful for debugging.helpzpip._internal.commands.helpZ HelpCommandzShow help for commands.cKs:t|\}}}t|}t||}|f||d|}|S)zF Create an instance of the Command class with the given name. )namesummary) commands_dict importlib import_modulegetattr)rkwargsZ module_path class_namermoduleZ command_classZcommandrC/usr/lib/python3.8/site-packages/pip/_internal/commands/__init__.pycreate_commandZs   rcCs6ddlm}|}||t}|r.|dSdSdS)zCommand name auto-correct.r)get_close_matchesFN)Zdifflibrlowerrkeys)rrZclose_commandsrrrget_similar_commandsgs  r)__doc__Z __future__rr collectionsrrZpip._internal.utils.typingrtypingrZpip._internal.cli.base_commandrrrrrrrrrs     < commands/__pycache__/search.cpython-38.pyc000064400000010604152347654150014467 0ustar00U .e@sddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z e!e"Z#GdddeeZ$ddZ%dddZ&ddZ'dS))absolute_importN) OrderedDict) pkg_resources)parse) xmlrpc_client)Command)SessionCommandMixin)NO_MATCHES_FOUNDSUCCESS) CommandError)PyPI)PipXmlrpcTransport)get_terminal_size) indent_log) write_outputcs8eZdZdZdZdZfddZddZdd ZZ S) SearchCommandz@Search for PyPI packages whose name or summary contains .z %prog [options] Tcs@tt|j|||jjddddtjdd|jd|jdS)Nz-iz--indexindexZURLz3Base URL of Python Package Index (default %default))destmetavardefaulthelpr) superr__init__Zcmd_optsZ add_optionr Zpypi_urlparserZinsert_option_group)selfargskw __class__A/usr/lib/python3.8/site-packages/pip/_internal/commands/search.pyr%szSearchCommand.__init__cCsT|s td|}|||}t|}d}tjrksz!print_results..cSsg|] }|jqSr)Z project_name)r?prrr r@psr,r-r5r<   z %-*s - %sz%s (%s)zINSTALLED: %s (latest)z INSTALLED: %sz=LATEST: %s (pre-release; install with "pip install --pre")z LATEST: %s)maxrZ working_setr8r>textwrapZwrapjoinrZget_distributionrr4 parse_versionZpreUnicodeEncodeError) r*Zname_column_widthr!Zinstalled_packagesr;r,r-ZlatestZ target_widthlineZdistrrr r'gsJ          r'cCs t|tdS)N)key)rIrL)r5rrr r8sr8)NN)(Z __future__rZloggingr$rJ collectionsrZ pip._vendorrZpip._vendor.packaging.versionrrLZpip._vendor.six.movesrZpip._internal.cli.base_commandrZpip._internal.cli.req_commandrZpip._internal.cli.status_codesr r Zpip._internal.exceptionsr Zpip._internal.models.indexr Zpip._internal.network.xmlrpcr Zpip._internal.utils.compatrZpip._internal.utils.loggingrZpip._internal.utils.miscrZ getLoggerr/Zloggerrr#r'r8rrrr s*              - )commands/hash.py000064400000003463152347654150007664 0ustar00from __future__ import absolute_import import hashlib import logging import sys from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES from pip._internal.utils.misc import read_chunks, write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List logger = logging.getLogger(__name__) class HashCommand(Command): """ Compute a hash of a local package archive. These can be used with --hash in a requirements file to do repeatable installs. """ usage = '%prog [options] ...' ignore_require_venv = True def add_options(self): # type: () -> None self.cmd_opts.add_option( '-a', '--algorithm', dest='algorithm', choices=STRONG_HASHES, action='store', default=FAVORITE_HASH, help='The hash algorithm to use: one of {}'.format( ', '.join(STRONG_HASHES))) self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int if not args: self.parser.print_usage(sys.stderr) return ERROR algorithm = options.algorithm for path in args: write_output('%s:\n--hash=%s:%s', path, algorithm, _hash_of_file(path, algorithm)) return SUCCESS def _hash_of_file(path, algorithm): # type: (str, str) -> str """Return the hash digest of a file.""" with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest() commands/search.py000064400000013174152347654150010206 0ustar00from __future__ import absolute_import import logging import sys import textwrap from collections import OrderedDict from pip._vendor import pkg_resources from pip._vendor.packaging.version import parse as parse_version # NOTE: XMLRPC Client is not annotated in typeshed as on 2017-07-17, which is # why we ignore the type on this import from pip._vendor.six.moves import xmlrpc_client # type: ignore from pip._internal.cli.base_command import Command from pip._internal.cli.req_command import SessionCommandMixin from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS from pip._internal.exceptions import CommandError from pip._internal.models.index import PyPI from pip._internal.network.xmlrpc import PipXmlrpcTransport from pip._internal.utils.compat import get_terminal_size from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_distribution, write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List, Dict, Optional from typing_extensions import TypedDict TransformedHit = TypedDict( 'TransformedHit', {'name': str, 'summary': str, 'versions': List[str]}, ) logger = logging.getLogger(__name__) class SearchCommand(Command, SessionCommandMixin): """Search for PyPI packages whose name or summary contains .""" usage = """ %prog [options] """ ignore_require_venv = True def add_options(self): # type: () -> None self.cmd_opts.add_option( '-i', '--index', dest='index', metavar='URL', default=PyPI.pypi_url, help='Base URL of Python Package Index (default %default)') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int if not args: raise CommandError('Missing required argument (search query).') query = args pypi_hits = self.search(query, options) hits = transform_hits(pypi_hits) terminal_width = None if sys.stdout.isatty(): terminal_width = get_terminal_size()[0] print_results(hits, terminal_width=terminal_width) if pypi_hits: return SUCCESS return NO_MATCHES_FOUND def search(self, query, options): # type: (List[str], Values) -> List[Dict[str, str]] index_url = options.index session = self.get_default_session(options) transport = PipXmlrpcTransport(index_url, session) pypi = xmlrpc_client.ServerProxy(index_url, transport) hits = pypi.search({'name': query, 'summary': query}, 'or') return hits def transform_hits(hits): # type: (List[Dict[str, str]]) -> List[TransformedHit] """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = OrderedDict() # type: OrderedDict[str, TransformedHit] for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] if name not in packages.keys(): packages[name] = { 'name': name, 'summary': summary, 'versions': [version], } else: packages[name]['versions'].append(version) # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary return list(packages.values()) def print_results(hits, name_column_width=None, terminal_width=None): # type: (List[TransformedHit], Optional[int], Optional[int]) -> None if not hits: return if name_column_width is None: name_column_width = max([ len(hit['name']) + len(highest_version(hit.get('versions', ['-']))) for hit in hits ]) + 4 installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' latest = highest_version(hit.get('versions', ['-'])) if terminal_width is not None: target_width = terminal_width - name_column_width - 5 if target_width > 10: # wrap and indent summary to fit terminal summary_lines = textwrap.wrap(summary, target_width) summary = ('\n' + ' ' * (name_column_width + 3)).join( summary_lines) line = '{name_latest:{name_column_width}} - {summary}'.format( name_latest='{name} ({latest})'.format(**locals()), **locals()) try: write_output(line) if name in installed_packages: dist = get_distribution(name) assert dist is not None with indent_log(): if dist.version == latest: write_output('INSTALLED: %s (latest)', dist.version) else: write_output('INSTALLED: %s', dist.version) if parse_version(latest).pre: write_output('LATEST: %s (pre-release; install' ' with "pip install --pre")', latest) else: write_output('LATEST: %s', latest) except UnicodeEncodeError: pass def highest_version(versions): # type: (List[str]) -> str return max(versions, key=parse_version) commands/check.py000064400000003215152347654150010011 0ustar00import logging from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.operations.check import ( check_package_set, create_package_set_from_installed, ) from pip._internal.utils.misc import write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) if MYPY_CHECK_RUNNING: from typing import List, Any from optparse import Values class CheckCommand(Command): """Verify installed packages have compatible dependencies.""" usage = """ %prog [options]""" def run(self, options, args): # type: (Values, List[Any]) -> int package_set, parsing_probs = create_package_set_from_installed() missing, conflicting = check_package_set(package_set) for project_name in missing: version = package_set[project_name].version for dependency in missing[project_name]: write_output( "%s %s requires %s, which is not installed.", project_name, version, dependency[0], ) for project_name in conflicting: version = package_set[project_name].version for dep_name, dep_version, req in conflicting[project_name]: write_output( "%s %s has requirement %s, but you have %s %s.", project_name, version, req, dep_name, dep_version, ) if missing or conflicting or parsing_probs: return ERROR else: write_output("No broken requirements found.") return SUCCESS commands/freeze.py000064400000006574152347654150010227 0ustar00from __future__ import absolute_import import sys from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import SUCCESS from pip._internal.models.format_control import FormatControl from pip._internal.operations.freeze import freeze from pip._internal.utils.compat import stdlib_pkgs from pip._internal.utils.typing import MYPY_CHECK_RUNNING DEV_PKGS = {'pip', 'setuptools', 'distribute', 'wheel'} if MYPY_CHECK_RUNNING: from optparse import Values from typing import List class FreezeCommand(Command): """ Output installed packages in requirements format. packages are listed in a case-insensitive sorted order. """ usage = """ %prog [options]""" log_streams = ("ext://sys.stderr", "ext://sys.stderr") def add_options(self): # type: () -> None self.cmd_opts.add_option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help="Use the order in the given requirements file and its " "comments when generating output. This option can be " "used multiple times.") self.cmd_opts.add_option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='URL', help='URL for finding packages, which will be added to the ' 'output.') self.cmd_opts.add_option( '-l', '--local', dest='local', action='store_true', default=False, help='If in a virtualenv that has global access, do not output ' 'globally-installed packages.') self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') self.cmd_opts.add_option(cmdoptions.list_path()) self.cmd_opts.add_option( '--all', dest='freeze_all', action='store_true', help='Do not skip these packages in the output:' ' {}'.format(', '.join(DEV_PKGS))) self.cmd_opts.add_option( '--exclude-editable', dest='exclude_editable', action='store_true', help='Exclude editable package from output.') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int format_control = FormatControl(set(), set()) wheel_cache = WheelCache(options.cache_dir, format_control) skip = set(stdlib_pkgs) if not options.freeze_all: skip.update(DEV_PKGS) cmdoptions.check_list_path_option(options) freeze_kwargs = dict( requirement=options.requirements, find_links=options.find_links, local_only=options.local, user_only=options.user, paths=options.path, isolated=options.isolated_mode, wheel_cache=wheel_cache, skip=skip, exclude_editable=options.exclude_editable, ) for line in freeze(**freeze_kwargs): sys.stdout.write(line + '\n') return SUCCESS commands/completion.py000064400000006011152347654150011102 0ustar00from __future__ import absolute_import import sys import textwrap from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import SUCCESS from pip._internal.utils.misc import get_prog from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List from optparse import Values BASE_COMPLETION = """ # pip {shell} completion start{script}# pip {shell} completion end """ COMPLETION_SCRIPTS = { 'bash': """ _pip_completion() {{ COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\ COMP_CWORD=$COMP_CWORD \\ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) }} complete -o default -F _pip_completion {prog} """, 'zsh': """ function _pip_completion {{ local words cword read -Ac words read -cn cword reply=( $( COMP_WORDS="$words[*]" \\ COMP_CWORD=$(( cword-1 )) \\ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) }} compctl -K _pip_completion {prog} """, 'fish': """ function __fish_complete_pip set -lx COMP_WORDS (commandline -o) "" set -lx COMP_CWORD ( \\ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\ ) set -lx PIP_AUTO_COMPLETE 1 string split \\ -- (eval $COMP_WORDS[1]) end complete -fa "(__fish_complete_pip)" -c {prog} """, } class CompletionCommand(Command): """A helper command to be used for command completion.""" ignore_require_venv = True def add_options(self): # type: () -> None self.cmd_opts.add_option( '--bash', '-b', action='store_const', const='bash', dest='shell', help='Emit completion code for bash') self.cmd_opts.add_option( '--zsh', '-z', action='store_const', const='zsh', dest='shell', help='Emit completion code for zsh') self.cmd_opts.add_option( '--fish', '-f', action='store_const', const='fish', dest='shell', help='Emit completion code for fish') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int """Prints the completion code of the given shell""" shells = COMPLETION_SCRIPTS.keys() shell_options = ['--' + shell for shell in sorted(shells)] if options.shell in shells: script = textwrap.dedent( COMPLETION_SCRIPTS.get(options.shell, '').format( prog=get_prog()) ) print(BASE_COMPLETION.format(script=script, shell=options.shell)) return SUCCESS else: sys.stderr.write( 'ERROR: You must pass {}\n' .format(' or '.join(shell_options)) ) return SUCCESS commands/help.py000064400000002366152347654150007672 0ustar00from __future__ import absolute_import from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List from optparse import Values class HelpCommand(Command): """Show help for commands""" usage = """ %prog """ ignore_require_venv = True def run(self, options, args): # type: (Values, List[str]) -> int from pip._internal.commands import ( commands_dict, create_command, get_similar_commands, ) try: # 'pip help' with no args is handled by pip.__init__.parseopt() cmd_name = args[0] # the command we need help for except IndexError: return SUCCESS if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name) msg = ['unknown command "{}"'.format(cmd_name)] if guess: msg.append('maybe you meant "{}"'.format(guess)) raise CommandError(' - '.join(msg)) command = create_command(cmd_name) command.parser.print_help() return SUCCESS commands/wheel.py000064400000014423152347654150010043 0ustar00# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import os import shutil from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.misc import ensure_dir, normalize_path from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.wheel_builder import build, should_build_for_wheel_command if MYPY_CHECK_RUNNING: from optparse import Values from typing import List logger = logging.getLogger(__name__) class WheelCommand(RequirementCommand): """ Build Wheel archives for your requirements and dependencies. Wheel is a built-package format, and offers the advantage of not recompiling your software during every install. For more details, see the wheel docs: https://wheel.readthedocs.io/en/latest/ Requirements: setuptools>=0.8, and wheel. 'pip wheel' uses the bdist_wheel setuptools extension from the wheel package to build individual wheels. """ usage = """ %prog [options] ... %prog [options] -r ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...""" def add_options(self): # type: () -> None self.cmd_opts.add_option( '-w', '--wheel-dir', dest='wheel_dir', metavar='dir', default=os.curdir, help=("Build wheels into , where the default is the " "current working directory."), ) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option( '--build-option', dest='build_options', metavar='options', action='append', help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", ) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.editable()) self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.src()) self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.build_dir()) self.cmd_opts.add_option(cmdoptions.progress_bar()) self.cmd_opts.add_option( '--global-option', dest='global_options', action='append', metavar='options', help="Extra global options to be supplied to the setup.py " "call before the 'bdist_wheel' command.") self.cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) self.cmd_opts.add_option(cmdoptions.require_hashes()) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts) @with_cleanup def run(self, options, args): # type: (Values, List[str]) -> int cmdoptions.check_install_build_global(options) session = self.get_default_session(options) finder = self._build_package_finder(options, session) build_delete = (not (options.no_clean or options.build_dir)) wheel_cache = WheelCache(options.cache_dir, options.format_control) options.wheel_dir = normalize_path(options.wheel_dir) ensure_dir(options.wheel_dir) req_tracker = self.enter_context(get_requirement_tracker()) directory = TempDirectory( options.build_dir, delete=build_delete, kind="wheel", globally_managed=True, ) reqs = self.get_requirements(args, options, finder, session) preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, req_tracker=req_tracker, session=session, finder=finder, wheel_download_dir=options.wheel_dir, use_user_site=False, ) resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, wheel_cache=wheel_cache, ignore_requires_python=options.ignore_requires_python, use_pep517=options.use_pep517, ) self.trace_basic_info(finder) requirement_set = resolver.resolve( reqs, check_supported_wheels=True ) reqs_to_build = [ r for r in requirement_set.requirements.values() if should_build_for_wheel_command(r) ] # build wheels build_successes, build_failures = build( reqs_to_build, wheel_cache=wheel_cache, build_options=options.build_options or [], global_options=options.global_options or [], ) for req in build_successes: assert req.link and req.link.is_wheel assert req.local_file_path # copy from cache to target directory try: shutil.copy(req.local_file_path, options.wheel_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) build_failures.append(req) if len(build_failures) != 0: raise CommandError( "Failed to build one or more wheels" ) return SUCCESS commands/install.py000064400000070067152347654150010413 0ustar00from __future__ import absolute_import import errno import logging import operator import os import shutil import site import sys from os import path from optparse import SUPPRESS_HELP from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.exceptions import CommandError, InstallationError from pip._internal.locations import distutils_scheme from pip._internal.operations.check import check_install_conflicts from pip._internal.req import install_given_reqs from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.datetime import today_is_later_than from pip._internal.utils.distutils_args import parse_distutils_args from pip._internal.utils.filesystem import test_writable_dir from pip._internal.utils.misc import ( ensure_dir, get_installed_version, get_pip_version, protect_pip_from_modification_on_windows, write_output, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import virtualenv_no_global from pip._internal.wheel_builder import build, should_build_for_install_command if MYPY_CHECK_RUNNING: from optparse import Values from typing import Iterable, List, Optional from pip._internal.models.format_control import FormatControl from pip._internal.operations.check import ConflictDetails from pip._internal.req.req_install import InstallRequirement from pip._internal.wheel_builder import BinaryAllowedPredicate logger = logging.getLogger(__name__) def get_check_binary_allowed(format_control): # type: (FormatControl) -> BinaryAllowedPredicate def check_binary_allowed(req): # type: (InstallRequirement) -> bool if req.use_pep517: return True canonical_name = canonicalize_name(req.name) allowed_formats = format_control.get_allowed_formats(canonical_name) return "binary" in allowed_formats return check_binary_allowed class InstallCommand(RequirementCommand): """ Install packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports installing from "requirements files", which provide an easy way to specify a whole environment to be installed. """ usage = """ %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...""" def add_options(self): # type: () -> None self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.pre()) self.cmd_opts.add_option(cmdoptions.editable()) self.cmd_opts.add_option( '-t', '--target', dest='target_dir', metavar='dir', default=None, help='Install packages into . ' 'By default this will not replace existing files/folders in ' '. Use --upgrade to replace existing packages in ' 'with new versions.' ) cmdoptions.add_target_python_options(self.cmd_opts) self.cmd_opts.add_option( '--user', dest='use_user_site', action='store_true', help="Install to the Python user install directory for your " "platform. Typically ~/.local/, or %APPDATA%\\Python on " "Windows. (See the Python documentation for site.USER_BASE " "for full details.)") self.cmd_opts.add_option( '--no-user', dest='use_user_site', action='store_false', help=SUPPRESS_HELP) self.cmd_opts.add_option( '--root', dest='root_path', metavar='dir', default=None, help="Install everything relative to this alternate root " "directory.") self.cmd_opts.add_option( '--prefix', dest='prefix_path', metavar='dir', default=None, help="Installation prefix where lib, bin and other top-level " "folders are placed") self.cmd_opts.add_option(cmdoptions.build_dir()) self.cmd_opts.add_option(cmdoptions.src()) self.cmd_opts.add_option( '-U', '--upgrade', dest='upgrade', action='store_true', help='Upgrade all specified packages to the newest available ' 'version. The handling of dependencies depends on the ' 'upgrade-strategy used.' ) self.cmd_opts.add_option( '--upgrade-strategy', dest='upgrade_strategy', default='only-if-needed', choices=['only-if-needed', 'eager'], help='Determines how dependency upgrading should be handled ' '[default: %default]. ' '"eager" - dependencies are upgraded regardless of ' 'whether the currently installed version satisfies the ' 'requirements of the upgraded package(s). ' '"only-if-needed" - are upgraded only when they do not ' 'satisfy the requirements of the upgraded package(s).' ) self.cmd_opts.add_option( '--force-reinstall', dest='force_reinstall', action='store_true', help='Reinstall all packages even if they are already ' 'up-to-date.') self.cmd_opts.add_option( '-I', '--ignore-installed', dest='ignore_installed', action='store_true', help='Ignore the installed packages, overwriting them. ' 'This can break your system if the existing package ' 'is of a different version or was installed ' 'with a different package manager!' ) self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option(cmdoptions.install_options()) self.cmd_opts.add_option(cmdoptions.global_options()) self.cmd_opts.add_option( "--compile", action="store_true", dest="compile", default=True, help="Compile Python source files to bytecode", ) self.cmd_opts.add_option( "--no-compile", action="store_false", dest="compile", help="Do not compile Python source files to bytecode", ) self.cmd_opts.add_option( "--no-warn-script-location", action="store_false", dest="warn_script_location", default=True, help="Do not warn when installing scripts outside PATH", ) self.cmd_opts.add_option( "--no-warn-conflicts", action="store_false", dest="warn_about_conflicts", default=True, help="Do not warn about broken dependencies", ) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option(cmdoptions.require_hashes()) self.cmd_opts.add_option(cmdoptions.progress_bar()) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts) @with_cleanup def run(self, options, args): # type: (Values, List[str]) -> int if options.use_user_site and options.target_dir is not None: raise CommandError("Can not combine '--user' and '--target'") cmdoptions.check_install_build_global(options) def is_venv(): return (hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)) # Check whether we have root privileges and aren't in venv/virtualenv if os.getuid() == 0 and not is_venv() and not options.root_path: command = path.basename(sys.argv[0]) if command == "__main__.py": command = path.basename(sys.executable) + " -m pip" logger.warning( "Running pip install with root privileges is " "generally not a good idea. Try `%s install --user` instead." % command ) upgrade_strategy = "to-satisfy-only" if options.upgrade: upgrade_strategy = options.upgrade_strategy cmdoptions.check_dist_restriction(options, check_target=True) install_options = options.install_options or [] logger.debug("Using %s", get_pip_version()) options.use_user_site = decide_user_install( options.use_user_site, prefix_path=options.prefix_path, target_dir=options.target_dir, root_path=options.root_path, isolated_mode=options.isolated_mode, ) target_temp_dir = None # type: Optional[TempDirectory] target_temp_dir_path = None # type: Optional[str] if options.target_dir: options.ignore_installed = True options.target_dir = os.path.abspath(options.target_dir) if (os.path.exists(options.target_dir) and not os.path.isdir(options.target_dir)): raise CommandError( "Target path exists but is not a directory, will not " "continue." ) # Create a target directory for using with the target option target_temp_dir = TempDirectory(kind="target") target_temp_dir_path = target_temp_dir.path self.enter_context(target_temp_dir) global_options = options.global_options or [] session = self.get_default_session(options) target_python = make_target_python(options) finder = self._build_package_finder( options=options, session=session, target_python=target_python, ignore_requires_python=options.ignore_requires_python, ) build_delete = (not (options.no_clean or options.build_dir)) wheel_cache = WheelCache(options.cache_dir, options.format_control) req_tracker = self.enter_context(get_requirement_tracker()) directory = TempDirectory( options.build_dir, delete=build_delete, kind="install", globally_managed=True, ) try: reqs = self.get_requirements(args, options, finder, session) reject_location_related_install_options( reqs, options.install_options ) preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, req_tracker=req_tracker, session=session, finder=finder, use_user_site=options.use_user_site, ) resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, wheel_cache=wheel_cache, use_user_site=options.use_user_site, ignore_installed=options.ignore_installed, ignore_requires_python=options.ignore_requires_python, force_reinstall=options.force_reinstall, upgrade_strategy=upgrade_strategy, use_pep517=options.use_pep517, ) self.trace_basic_info(finder) requirement_set = resolver.resolve( reqs, check_supported_wheels=not options.target_dir ) try: pip_req = requirement_set.get_requirement("pip") except KeyError: modifying_pip = False else: # If we're not replacing an already installed pip, # we're not modifying it. modifying_pip = pip_req.satisfied_by is None protect_pip_from_modification_on_windows( modifying_pip=modifying_pip ) check_binary_allowed = get_check_binary_allowed( finder.format_control ) reqs_to_build = [ r for r in requirement_set.requirements.values() if should_build_for_install_command( r, check_binary_allowed ) ] _, build_failures = build( reqs_to_build, wheel_cache=wheel_cache, build_options=[], global_options=[], ) # If we're using PEP 517, we cannot do a direct install # so we fail here. pep517_build_failure_names = [ r.name # type: ignore for r in build_failures if r.use_pep517 ] # type: List[str] if pep517_build_failure_names: raise InstallationError( "Could not build wheels for {} which use" " PEP 517 and cannot be installed directly".format( ", ".join(pep517_build_failure_names) ) ) # For now, we just warn about failures building legacy # requirements, as we'll fall through to a direct # install for those. for r in build_failures: if not r.use_pep517: r.legacy_install_reason = 8368 to_install = resolver.get_installation_order( requirement_set ) # Check for conflicts in the package set we're installing. conflicts = None # type: Optional[ConflictDetails] should_warn_about_conflicts = ( not options.ignore_dependencies and options.warn_about_conflicts ) if should_warn_about_conflicts: conflicts = self._determine_conflicts(to_install) # Don't warn about script install locations if # --target has been specified warn_script_location = options.warn_script_location if options.target_dir: warn_script_location = False installed = install_given_reqs( to_install, install_options, global_options, root=options.root_path, home=target_temp_dir_path, prefix=options.prefix_path, warn_script_location=warn_script_location, use_user_site=options.use_user_site, pycompile=options.compile, ) lib_locations = get_lib_location_guesses( user=options.use_user_site, home=target_temp_dir_path, root=options.root_path, prefix=options.prefix_path, isolated=options.isolated_mode, ) working_set = pkg_resources.WorkingSet(lib_locations) installed.sort(key=operator.attrgetter('name')) items = [] for result in installed: item = result.name try: installed_version = get_installed_version( result.name, working_set=working_set ) if installed_version: item += '-' + installed_version except Exception: pass items.append(item) if conflicts is not None: self._warn_about_conflicts( conflicts, new_resolver='2020-resolver' in options.features_enabled, ) installed_desc = ' '.join(items) if installed_desc: write_output( 'Successfully installed %s', installed_desc, ) except EnvironmentError as error: show_traceback = (self.verbosity >= 1) message = create_env_error_message( error, show_traceback, options.use_user_site, ) logger.error(message, exc_info=show_traceback) # noqa return ERROR if options.target_dir: assert target_temp_dir self._handle_target_dir( options.target_dir, target_temp_dir, options.upgrade ) return SUCCESS def _handle_target_dir(self, target_dir, target_temp_dir, upgrade): # type: (str, TempDirectory, bool) -> None ensure_dir(target_dir) # Checking both purelib and platlib directories for installed # packages to be moved to target directory lib_dir_list = [] # Checking both purelib and platlib directories for installed # packages to be moved to target directory scheme = distutils_scheme('', home=target_temp_dir.path) purelib_dir = scheme['purelib'] platlib_dir = scheme['platlib'] data_dir = scheme['data'] if os.path.exists(purelib_dir): lib_dir_list.append(purelib_dir) if os.path.exists(platlib_dir) and platlib_dir != purelib_dir: lib_dir_list.append(platlib_dir) if os.path.exists(data_dir): lib_dir_list.append(data_dir) for lib_dir in lib_dir_list: for item in os.listdir(lib_dir): if lib_dir == data_dir: ddir = os.path.join(data_dir, item) if any(s.startswith(ddir) for s in lib_dir_list[:-1]): continue target_item_dir = os.path.join(target_dir, item) if os.path.exists(target_item_dir): if not upgrade: logger.warning( 'Target directory %s already exists. Specify ' '--upgrade to force replacement.', target_item_dir ) continue if os.path.islink(target_item_dir): logger.warning( 'Target directory %s already exists and is ' 'a link. pip will not automatically replace ' 'links, please remove if replacement is ' 'desired.', target_item_dir ) continue if os.path.isdir(target_item_dir): shutil.rmtree(target_item_dir) else: os.remove(target_item_dir) shutil.move( os.path.join(lib_dir, item), target_item_dir ) def _determine_conflicts(self, to_install): # type: (List[InstallRequirement]) -> Optional[ConflictDetails] try: return check_install_conflicts(to_install) except Exception: logger.exception( "Error while checking for conflicts. Please file an issue on " "pip's issue tracker: https://github.com/pypa/pip/issues/new" ) return None def _warn_about_conflicts(self, conflict_details, new_resolver): # type: (ConflictDetails, bool) -> None package_set, (missing, conflicting) = conflict_details if not missing and not conflicting: return parts = [] # type: List[str] if not new_resolver: parts.append( "After October 2020 you may experience errors when installing " "or updating packages. This is because pip will change the " "way that it resolves dependency conflicts.\n" ) parts.append( "We recommend you use --use-feature=2020-resolver to test " "your packages with the new resolver before it becomes the " "default.\n" ) elif not today_is_later_than(year=2020, month=7, day=31): # NOTE: trailing newlines here are intentional parts.append( "Pip will install or upgrade your package(s) and its " "dependencies without taking into account other packages you " "already have installed. This may cause an uncaught " "dependency conflict.\n" ) form_link = "https://forms.gle/cWKMoDs8sUVE29hz9" parts.append( "If you would like pip to take your other packages into " "account, please tell us here: {}\n".format(form_link) ) # NOTE: There is some duplication here, with commands/check.py for project_name in missing: version = package_set[project_name][0] for dependency in missing[project_name]: message = ( "{name} {version} requires {requirement}, " "which is not installed." ).format( name=project_name, version=version, requirement=dependency[1], ) parts.append(message) for project_name in conflicting: version = package_set[project_name][0] for dep_name, dep_version, req in conflicting[project_name]: message = ( "{name} {version} requires {requirement}, but you'll have " "{dep_name} {dep_version} which is incompatible." ).format( name=project_name, version=version, requirement=req, dep_name=dep_name, dep_version=dep_version, ) parts.append(message) logger.critical("\n".join(parts)) def get_lib_location_guesses( user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] isolated=False, # type: bool prefix=None # type: Optional[str] ): # type:(...) -> List[str] scheme = distutils_scheme('', user=user, home=home, root=root, isolated=isolated, prefix=prefix) return [scheme['purelib'], scheme['platlib']] def site_packages_writable(root, isolated): # type: (Optional[str], bool) -> bool return all( test_writable_dir(d) for d in set( get_lib_location_guesses(root=root, isolated=isolated)) ) def decide_user_install( use_user_site, # type: Optional[bool] prefix_path=None, # type: Optional[str] target_dir=None, # type: Optional[str] root_path=None, # type: Optional[str] isolated_mode=False, # type: bool ): # type: (...) -> bool """Determine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments. """ # In some cases (config from tox), use_user_site can be set to an integer # rather than a bool, which 'use_user_site is False' wouldn't catch. if (use_user_site is not None) and (not use_user_site): logger.debug("Non-user install by explicit request") return False if use_user_site: if prefix_path: raise CommandError( "Can not combine '--user' and '--prefix' as they imply " "different installation locations" ) if virtualenv_no_global(): raise InstallationError( "Can not perform a '--user' install. User site-packages " "are not visible in this virtualenv." ) logger.debug("User install by explicit request") return True # If we are here, user installs have not been explicitly requested/avoided assert use_user_site is None # user install incompatible with --prefix/--target if prefix_path or target_dir: logger.debug("Non-user install due to --prefix or --target option") return False # If user installs are not enabled, choose a non-user install if not site.ENABLE_USER_SITE: logger.debug("Non-user install because user site-packages disabled") return False # If we have permission for a non-user install, do that, # otherwise do a user install. if site_packages_writable(root=root_path, isolated=isolated_mode): logger.debug("Non-user install because site-packages writeable") return False logger.info("Defaulting to user installation because normal site-packages " "is not writeable") return True def reject_location_related_install_options(requirements, options): # type: (List[InstallRequirement], Optional[List[str]]) -> None """If any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning. """ def format_options(option_names): # type: (Iterable[str]) -> List[str] return ["--{}".format(name.replace("_", "-")) for name in option_names] offenders = [] for requirement in requirements: install_options = requirement.install_options location_options = parse_distutils_args(install_options) if location_options: offenders.append( "{!r} from {}".format( format_options(location_options.keys()), requirement ) ) if options: location_options = parse_distutils_args(options) if location_options: offenders.append( "{!r} from command line".format( format_options(location_options.keys()) ) ) if not offenders: return raise CommandError( "Location-changing options found in --install-option: {}." " This is unsupported, use pip-level options like --user," " --prefix, --root, and --target instead.".format( "; ".join(offenders) ) ) def create_env_error_message(error, show_traceback, using_user_site): # type: (EnvironmentError, bool, bool) -> str """Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. """ parts = [] # Mention the error if we are not going to show a traceback parts.append("Could not install packages due to an EnvironmentError") if not show_traceback: parts.append(": ") parts.append(str(error)) else: parts.append(".") # Spilt the error indication from a helper message (if any) parts[-1] += "\n" # Suggest useful actions to the user: # (1) using user site-packages or (2) verifying the permissions if error.errno == errno.EACCES: user_option_part = "Consider using the `--user` option" permissions_part = "Check the permissions" if not using_user_site: parts.extend([ user_option_part, " or ", permissions_part.lower(), ]) else: parts.append(permissions_part) parts.append(".\n") return "".join(parts).strip() + "\n" commands/show.py000064400000015524152347654150007722 0ustar00from __future__ import absolute_import import logging import os from email.parser import FeedParser from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.utils.misc import write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List, Dict, Iterator logger = logging.getLogger(__name__) class ShowCommand(Command): """ Show information about one or more installed packages. The output is in RFC-compliant mail header format. """ usage = """ %prog [options] ...""" ignore_require_venv = True def add_options(self): # type: () -> None self.cmd_opts.add_option( '-f', '--files', dest='files', action='store_true', default=False, help='Show the full list of installed files for each package.') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int if not args: logger.warning('ERROR: Please provide a package name or names.') return ERROR query = args results = search_packages_info(query) if not print_results( results, list_files=options.files, verbose=options.verbose): return ERROR return SUCCESS def search_packages_info(query): # type: (List[str]) -> Iterator[Dict[str, str]] """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_resources.working_set: installed[canonicalize_name(p.project_name)] = p query_names = [canonicalize_name(name) for name in query] missing = sorted( [name for name, pkg in zip(query, query_names) if pkg not in installed] ) if missing: logger.warning('Package(s) not found: %s', ', '.join(missing)) def get_requiring_packages(package_name): # type: (str) -> List[str] canonical_name = canonicalize_name(package_name) return [ pkg.project_name for pkg in pkg_resources.working_set if canonical_name in [canonicalize_name(required.name) for required in pkg.requires()] ] for dist in [installed[pkg] for pkg in query_names if pkg in installed]: package = { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'requires': [dep.project_name for dep in dist.requires()], 'required_by': get_requiring_packages(dist.project_name) } file_list = None metadata = '' if isinstance(dist, pkg_resources.DistInfoDistribution): # RECORDs should be part of .dist-info metadatas if dist.has_metadata('RECORD'): lines = dist.get_metadata_lines('RECORD') paths = [line.split(',')[0] for line in lines] paths = [os.path.join(dist.location, p) for p in paths] file_list = [os.path.relpath(p, dist.location) for p in paths] if dist.has_metadata('METADATA'): metadata = dist.get_metadata('METADATA') else: # Otherwise use pip's log for .egg-info's if dist.has_metadata('installed-files.txt'): paths = dist.get_metadata_lines('installed-files.txt') paths = [os.path.join(dist.egg_info, p) for p in paths] file_list = [os.path.relpath(p, dist.location) for p in paths] if dist.has_metadata('PKG-INFO'): metadata = dist.get_metadata('PKG-INFO') if dist.has_metadata('entry_points.txt'): entry_points = dist.get_metadata_lines('entry_points.txt') package['entry_points'] = entry_points if dist.has_metadata('INSTALLER'): for line in dist.get_metadata_lines('INSTALLER'): if line.strip(): package['installer'] = line.strip() break # @todo: Should pkg_resources.Distribution have a # `get_pkg_info` method? feed_parser = FeedParser() feed_parser.feed(metadata) pkg_info_dict = feed_parser.close() for key in ('metadata-version', 'summary', 'home-page', 'author', 'author-email', 'license'): package[key] = pkg_info_dict.get(key) # It looks like FeedParser cannot deal with repeated headers classifiers = [] for line in metadata.splitlines(): if line.startswith('Classifier: '): classifiers.append(line[len('Classifier: '):]) package['classifiers'] = classifiers if file_list: package['files'] = sorted(file_list) yield package def print_results(distributions, list_files=False, verbose=False): # type: (Iterator[Dict[str, str]], bool, bool) -> bool """ Print the information from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if i > 0: write_output("---") write_output("Name: %s", dist.get('name', '')) write_output("Version: %s", dist.get('version', '')) write_output("Summary: %s", dist.get('summary', '')) write_output("Home-page: %s", dist.get('home-page', '')) write_output("Author: %s", dist.get('author', '')) write_output("Author-email: %s", dist.get('author-email', '')) write_output("License: %s", dist.get('license', '')) write_output("Location: %s", dist.get('location', '')) write_output("Requires: %s", ', '.join(dist.get('requires', []))) write_output("Required-by: %s", ', '.join(dist.get('required_by', []))) if verbose: write_output("Metadata-Version: %s", dist.get('metadata-version', '')) write_output("Installer: %s", dist.get('installer', '')) write_output("Classifiers:") for classifier in dist.get('classifiers', []): write_output(" %s", classifier) write_output("Entry-points:") for entry in dist.get('entry_points', []): write_output(" %s", entry.strip()) if list_files: write_output("Files:") for line in dist.get('files', []): write_output(" %s", line.strip()) if "files" not in dist: write_output("Cannot locate installed-files.txt") return results_printed commands/download.py000064400000011466152347654150010552 0ustar00from __future__ import absolute_import import logging import os from pip._internal.cli import cmdoptions from pip._internal.cli.cmdoptions import make_target_python from pip._internal.cli.req_command import RequirementCommand, with_cleanup from pip._internal.cli.status_codes import SUCCESS from pip._internal.req.req_tracker import get_requirement_tracker from pip._internal.utils.misc import ensure_dir, normalize_path, write_output from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List logger = logging.getLogger(__name__) class DownloadCommand(RequirementCommand): """ Download packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports downloading from "requirements files", which provide an easy way to specify a whole environment to be downloaded. """ usage = """ %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] ... %prog [options] ... %prog [options] ...""" def add_options(self): # type: () -> None self.cmd_opts.add_option(cmdoptions.constraints()) self.cmd_opts.add_option(cmdoptions.requirements()) self.cmd_opts.add_option(cmdoptions.build_dir()) self.cmd_opts.add_option(cmdoptions.no_deps()) self.cmd_opts.add_option(cmdoptions.global_options()) self.cmd_opts.add_option(cmdoptions.no_binary()) self.cmd_opts.add_option(cmdoptions.only_binary()) self.cmd_opts.add_option(cmdoptions.prefer_binary()) self.cmd_opts.add_option(cmdoptions.src()) self.cmd_opts.add_option(cmdoptions.pre()) self.cmd_opts.add_option(cmdoptions.require_hashes()) self.cmd_opts.add_option(cmdoptions.progress_bar()) self.cmd_opts.add_option(cmdoptions.no_build_isolation()) self.cmd_opts.add_option(cmdoptions.use_pep517()) self.cmd_opts.add_option(cmdoptions.no_use_pep517()) self.cmd_opts.add_option( '-d', '--dest', '--destination-dir', '--destination-directory', dest='download_dir', metavar='dir', default=os.curdir, help=("Download packages into ."), ) cmdoptions.add_target_python_options(self.cmd_opts) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser, ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts) @with_cleanup def run(self, options, args): # type: (Values, List[str]) -> int options.ignore_installed = True # editable doesn't really make sense for `pip download`, but the bowels # of the RequirementSet code require that property. options.editables = [] cmdoptions.check_dist_restriction(options) options.download_dir = normalize_path(options.download_dir) ensure_dir(options.download_dir) session = self.get_default_session(options) target_python = make_target_python(options) finder = self._build_package_finder( options=options, session=session, target_python=target_python, ) build_delete = (not (options.no_clean or options.build_dir)) req_tracker = self.enter_context(get_requirement_tracker()) directory = TempDirectory( options.build_dir, delete=build_delete, kind="download", globally_managed=True, ) reqs = self.get_requirements(args, options, finder, session) preparer = self.make_requirement_preparer( temp_build_dir=directory, options=options, req_tracker=req_tracker, session=session, finder=finder, download_dir=options.download_dir, use_user_site=False, ) resolver = self.make_resolver( preparer=preparer, finder=finder, options=options, py_version_info=options.python_version, ) self.trace_basic_info(finder) requirement_set = resolver.resolve( reqs, check_supported_wheels=True ) downloaded = ' '.join([req.name # type: ignore for req in requirement_set.requirements.values() if req.successfully_downloaded]) if downloaded: write_output('Successfully downloaded %s', downloaded) return SUCCESS commands/configuration.py000064400000022200152347654150011576 0ustar00import logging import os import subprocess from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.configuration import ( Configuration, get_configuration_files, kinds, ) from pip._internal.exceptions import PipError from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import get_prog, write_output from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Any, Optional from optparse import Values from pip._internal.configuration import Kind logger = logging.getLogger(__name__) class ConfigurationCommand(Command): """ Manage local and global configuration. Subcommands: - list: List the active configuration (or from the file specified) - edit: Edit the configuration file in an editor - get: Get the value associated with name - set: Set the name=value - unset: Unset the value associated with name - debug: List the configuration files and values defined under them If none of --user, --global and --site are passed, a virtual environment configuration file is used if one is active and the file exists. Otherwise, all modifications happen on the to the user file by default. """ ignore_require_venv = True usage = """ %prog [] list %prog [] [--editor ] edit %prog [] get name %prog [] set name value %prog [] unset name %prog [] debug """ def add_options(self): # type: () -> None self.cmd_opts.add_option( '--editor', dest='editor', action='store', default=None, help=( 'Editor to use to edit the file. Uses VISUAL or EDITOR ' 'environment variables if not provided.' ) ) self.cmd_opts.add_option( '--global', dest='global_file', action='store_true', default=False, help='Use the system-wide configuration file only' ) self.cmd_opts.add_option( '--user', dest='user_file', action='store_true', default=False, help='Use the user configuration file only' ) self.cmd_opts.add_option( '--site', dest='site_file', action='store_true', default=False, help='Use the current environment configuration file only' ) self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int handlers = { "list": self.list_values, "edit": self.open_in_editor, "get": self.get_name, "set": self.set_name_value, "unset": self.unset_name, "debug": self.list_config_values, } # Determine action if not args or args[0] not in handlers: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handlers)), ) return ERROR action = args[0] # Determine which configuration files are to be loaded # Depends on whether the command is modifying. try: load_only = self._determine_file( options, need_value=(action in ["get", "set", "unset", "edit"]) ) except PipError as e: logger.error(e.args[0]) return ERROR # Load a new configuration self.configuration = Configuration( isolated=options.isolated_mode, load_only=load_only ) self.configuration.load() # Error handling happens here, not in the action-handlers. try: handlers[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR return SUCCESS def _determine_file(self, options, need_value): # type: (Values, bool) -> Optional[Kind] file_options = [key for key, value in ( (kinds.USER, options.user_file), (kinds.GLOBAL, options.global_file), (kinds.SITE, options.site_file), ) if value] if not file_options: if not need_value: return None # Default to user, unless there's a site file. elif any( os.path.exists(site_config_file) for site_config_file in get_configuration_files()[kinds.SITE] ): return kinds.SITE else: return kinds.USER elif len(file_options) == 1: return file_options[0] raise PipError( "Need exactly one file to operate upon " "(--user, --site, --global) to perform." ) def list_values(self, options, args): # type: (Values, List[str]) -> None self._get_n_args(args, "list", n=0) for key, value in sorted(self.configuration.items()): write_output("%s=%r", key, value) def get_name(self, options, args): # type: (Values, List[str]) -> None key = self._get_n_args(args, "get [name]", n=1) value = self.configuration.get_value(key) write_output("%s", value) def set_name_value(self, options, args): # type: (Values, List[str]) -> None key, value = self._get_n_args(args, "set [name] [value]", n=2) self.configuration.set_value(key, value) self._save_configuration() def unset_name(self, options, args): # type: (Values, List[str]) -> None key = self._get_n_args(args, "unset [name]", n=1) self.configuration.unset_value(key) self._save_configuration() def list_config_values(self, options, args): # type: (Values, List[str]) -> None """List config key-value pairs across different config files""" self._get_n_args(args, "debug", n=0) self.print_env_var_values() # Iterate over config files and print if they exist, and the # key-value pairs present in them if they do for variant, files in sorted(self.configuration.iter_config_files()): write_output("%s:", variant) for fname in files: with indent_log(): file_exists = os.path.exists(fname) write_output("%s, exists: %r", fname, file_exists) if file_exists: self.print_config_file_values(variant) def print_config_file_values(self, variant): # type: (Kind) -> None """Get key-value pairs from the file of a variant""" for name, value in self.configuration.\ get_values_in_config(variant).items(): with indent_log(): write_output("%s: %s", name, value) def print_env_var_values(self): # type: () -> None """Get key-values pairs present as environment variables""" write_output("%s:", 'env_var') with indent_log(): for key, value in sorted(self.configuration.get_environ_vars()): env_var = 'PIP_{}'.format(key.upper()) write_output("%s=%r", env_var, value) def open_in_editor(self, options, args): # type: (Values, List[str]) -> None editor = self._determine_editor(options) fname = self.configuration.get_file_to_edit() if fname is None: raise PipError("Could not determine appropriate file.") try: subprocess.check_call([editor, fname]) except subprocess.CalledProcessError as e: raise PipError( "Editor Subprocess exited with exit code {}" .format(e.returncode) ) def _get_n_args(self, args, example, n): # type: (List[str], str, int) -> Any """Helper to make sure the command got the right number of arguments """ if len(args) != n: msg = ( 'Got unexpected number of arguments, expected {}. ' '(example: "{} config {}")' ).format(n, get_prog(), example) raise PipError(msg) if n == 1: return args[0] else: return args def _save_configuration(self): # type: () -> None # We successfully ran a modifying command. Need to save the # configuration. try: self.configuration.save() except Exception: logger.exception( "Unable to save configuration. Please report this as a bug." ) raise PipError("Internal Error.") def _determine_editor(self, options): # type: (Values) -> str if options.editor is not None: return options.editor elif "VISUAL" in os.environ: return os.environ["VISUAL"] elif "EDITOR" in os.environ: return os.environ["EDITOR"] else: raise PipError("Could not determine editor to use.") commands/uninstall.py000064400000006357152347654150010757 0ustar00from __future__ import absolute_import from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cli.base_command import Command from pip._internal.cli.req_command import SessionCommandMixin from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import InstallationError from pip._internal.req import parse_requirements from pip._internal.req.constructors import ( install_req_from_line, install_req_from_parsed_requirement, ) from pip._internal.utils.misc import protect_pip_from_modification_on_windows from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List class UninstallCommand(Command, SessionCommandMixin): """ Uninstall packages. pip is able to uninstall most installed packages. Known exceptions are: - Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. """ usage = """ %prog [options] ... %prog [options] -r ...""" def add_options(self): # type: () -> None self.cmd_opts.add_option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Uninstall all the packages listed in the given requirements ' 'file. This option can be used multiple times.', ) self.cmd_opts.add_option( '-y', '--yes', dest='yes', action='store_true', help="Don't ask for confirmation of uninstall deletions.") self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): # type: (Values, List[str]) -> int session = self.get_default_session(options) reqs_to_uninstall = {} for name in args: req = install_req_from_line( name, isolated=options.isolated_mode, ) if req.name: reqs_to_uninstall[canonicalize_name(req.name)] = req for filename in options.requirements: for parsed_req in parse_requirements( filename, options=options, session=session): req = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode ) if req.name: reqs_to_uninstall[canonicalize_name(req.name)] = req if not reqs_to_uninstall: raise InstallationError( 'You must give at least one requirement to {self.name} (see ' '"pip help {self.name}")'.format(**locals()) ) protect_pip_from_modification_on_windows( modifying_pip="pip" in reqs_to_uninstall ) for req in reqs_to_uninstall.values(): uninstall_pathset = req.uninstall( auto_confirm=options.yes, verbose=self.verbosity > 0, ) if uninstall_pathset: uninstall_pathset.commit() return SUCCESS commands/list.py000064400000026060152347654150007712 0ustar00from __future__ import absolute_import import json import logging from pip._vendor import six from pip._internal.cli import cmdoptions from pip._internal.cli.req_command import IndexGroupCommand from pip._internal.cli.status_codes import SUCCESS from pip._internal.exceptions import CommandError from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, tabulate, write_output, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.parallel import map_multithread from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import List, Set, Tuple, Iterator from pip._internal.network.session import PipSession from pip._vendor.pkg_resources import Distribution logger = logging.getLogger(__name__) class ListCommand(IndexGroupCommand): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ ignore_require_venv = True usage = """ %prog [options]""" def add_options(self): # type: () -> None self.cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') self.cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') self.cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') self.cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') self.cmd_opts.add_option(cmdoptions.list_path()) self.cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) self.cmd_opts.add_option( '--format', action='store', dest='list_format', default="columns", choices=('columns', 'freeze', 'json'), help="Select the output format among: columns (default), freeze, " "or json", ) self.cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) self.cmd_opts.add_option( '--exclude-editable', action='store_false', dest='include_editable', help='Exclude editable package from output.', ) self.cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts) def _build_package_finder(self, options, session): # type: (Values, PipSession) -> PackageFinder """ Create a package finder appropriate to this list command. """ link_collector = LinkCollector.create(session, options=options) # Pass allow_yanked=False to ignore yanked versions. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=options.pre, ) return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, ) def run(self, options, args): # type: (Values, List[str]) -> int if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") cmdoptions.check_list_path_option(options) packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, paths=options.path, ) # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) return SUCCESS def get_outdated(self, packages, options): # type: (List[Distribution], Values) -> List[Distribution] return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): # type: (List[Distribution], Values) -> List[Distribution] return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def get_not_required(self, packages, options): # type: (List[Distribution], Values) -> List[Distribution] dep_keys = set() # type: Set[Distribution] for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) # Create a set to remove duplicate packages, and cast it to a list # to keep the return type consistent with get_outdated and # get_uptodate return list({pkg for pkg in packages if pkg.key not in dep_keys}) def iter_packages_latest_infos(self, packages, options): # type: (List[Distribution], Values) -> Iterator[Distribution] with self._build_session(options) as session: finder = self._build_package_finder(options, session) def latest_info(dist): # type: (Distribution) -> Distribution typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] evaluator = finder.make_candidate_evaluator( project_name=dist.project_name, ) best_candidate = evaluator.sort_best_candidate(all_candidates) if best_candidate is None: return None remote_version = best_candidate.version if best_candidate.link.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ return dist for dist in map_multithread(latest_info, packages): if dist is not None: yield dist def output_package_listing(self, packages, options): # type: (List[Distribution], Values) -> None packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: if options.verbose >= 1: write_output("%s==%s (%s)", dist.project_name, dist.version, dist.location) else: write_output("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json': write_output(format_for_json(packages, options)) def output_package_listing_columns(self, data, header): # type: (List[List[str]], List[str]) -> None # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes))) for val in pkg_strings: write_output(val) def format_for_columns(pkgs, options): # type: (List[Distribution], Values) -> Tuple[List[List[str]], List[str]] """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs): header.append("Location") if options.verbose >= 1: header.append("Installer") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if options.verbose >= 1 or dist_is_editable(proj): row.append(proj.location) if options.verbose >= 1: row.append(get_installer(proj)) data.append(row) return data, header def format_for_json(packages, options): # type: (List[Distribution], Values) -> str data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.verbose >= 1: info['location'] = dist.location info['installer'] = get_installer(dist) if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data) commands/__init__.py000064400000010004152347654150010465 0ustar00""" Package containing all pip commands """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False # There is currently a bug in python/typeshed mentioned at # https://github.com/python/typeshed/issues/3906 which causes the # return type of difflib.get_close_matches to be reported # as List[Sequence[str]] whereas it should have been List[str] from __future__ import absolute_import import importlib from collections import OrderedDict, namedtuple from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any from pip._internal.cli.base_command import Command CommandInfo = namedtuple('CommandInfo', 'module_path, class_name, summary') # The ordering matters for help display. # Also, even though the module path starts with the same # "pip._internal.commands" prefix in each case, we include the full path # because it makes testing easier (specifically when modifying commands_dict # in test setup / teardown by adding info for a FakeCommand class defined # in a test-related module). # Finally, we need to pass an iterable of pairs here rather than a dict # so that the ordering won't be lost when using Python 2.7. commands_dict = OrderedDict([ ('install', CommandInfo( 'pip._internal.commands.install', 'InstallCommand', 'Install packages.', )), ('download', CommandInfo( 'pip._internal.commands.download', 'DownloadCommand', 'Download packages.', )), ('uninstall', CommandInfo( 'pip._internal.commands.uninstall', 'UninstallCommand', 'Uninstall packages.', )), ('freeze', CommandInfo( 'pip._internal.commands.freeze', 'FreezeCommand', 'Output installed packages in requirements format.', )), ('list', CommandInfo( 'pip._internal.commands.list', 'ListCommand', 'List installed packages.', )), ('show', CommandInfo( 'pip._internal.commands.show', 'ShowCommand', 'Show information about installed packages.', )), ('check', CommandInfo( 'pip._internal.commands.check', 'CheckCommand', 'Verify installed packages have compatible dependencies.', )), ('config', CommandInfo( 'pip._internal.commands.configuration', 'ConfigurationCommand', 'Manage local and global configuration.', )), ('search', CommandInfo( 'pip._internal.commands.search', 'SearchCommand', 'Search PyPI for packages.', )), ('cache', CommandInfo( 'pip._internal.commands.cache', 'CacheCommand', "Inspect and manage pip's wheel cache.", )), ('wheel', CommandInfo( 'pip._internal.commands.wheel', 'WheelCommand', 'Build wheels from your requirements.', )), ('hash', CommandInfo( 'pip._internal.commands.hash', 'HashCommand', 'Compute hashes of package archives.', )), ('completion', CommandInfo( 'pip._internal.commands.completion', 'CompletionCommand', 'A helper command used for command completion.', )), ('debug', CommandInfo( 'pip._internal.commands.debug', 'DebugCommand', 'Show information useful for debugging.', )), ('help', CommandInfo( 'pip._internal.commands.help', 'HelpCommand', 'Show help for commands.', )), ]) # type: OrderedDict[str, CommandInfo] def create_command(name, **kwargs): # type: (str, **Any) -> Command """ Create an instance of the Command class with the given name. """ module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False req/__pycache__/req_install.cpython-38.opt-1.pyc000064400000055511152347654150015472 0ustar00U .e@sLddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z ddlmZddlmZddlmZddlmZdd lmZdd lmZmZdd lmZdd lmZdd lm Z ddl!m"Z"ddl#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mm?Z?ddl@mAZAddlBmCZCmDZDddlEmFZFddlGmHZHddlImJZJddlKmLZLeHr.ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTddlmUZUddlVmWZWdd lXmYZYdd!lZm[Z[dd"l\m]Z]dd#l^m_Z_e`eaZbGd$d%d%ecZddS)&)absolute_importN) change_root) pkg_resourcessix) Requirement)canonicalize_name)Version)parse)Pep517HookCaller) pep425tagswheel)NoOpBuildEnvironment)InstallationError)Link)get_metadata_generator)load_pyproject_tomlmake_pyproject_path)UninstallPathSet) native_str)Hashes) indent_log)PIP_DELETE_MARKER_FILENAMEhas_delete_marker_file) _make_build_dirask_path_exists backup_dir display_pathdist_in_install_pathdist_in_site_packagesdist_in_usersite ensure_dirget_installed_versionhide_urlredact_auth_from_urlrmtree) get_metadata)make_setuptools_shim_args)call_subprocessrunner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING)running_under_virtualenv)vcs)AnyDictIterableListOptionalSequenceUnion)BuildEnvironment) WheelCache) PackageFinder) Distribution) SpecifierSet)Markerc @speZdZdZdPddZddZd d Zd d Zd dZe ddZ e ddZ e ddZ e ddZ dQddZe ddZdRddZddZd d!Zd"d#Zd$d%Zd&d'Ze d(d)ZdSd*d+Ze d,d-Ze d.d/Ze d0d1Zd2d3Zd4d5Zd6d7Ze d8d9Zd:d;Zdd?Z!dTd@dAZ"dUdBdCZ#dVdDdEZ$dFdGZ%dHdIZ&dJdKZ'dWdLdMZ(dNdOZ)dS)XInstallRequirementz Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. NFc Cs||_||_| |_|dkr"d|_ntjtj||_||_| |_ |dkr`|r`|j r`t |j }||_ |_ | rx| |_n |rdd|jD|_nt|_|dkr|r|j}||_d|_d|_d|_d|_d|_| r| ni|_d|_d|_||_t|_d|_d|_g|_d|_ ||_!dS)NcSsh|]}t|qSr;)rZ safe_extra.0extrar;r;A/usr/lib/python3.8/site-packages/pip/_internal/req/req_install.py wsz.InstallRequirement.__init__..F)"req comes_from constraint source_dirospathnormpathabspatheditable _wheel_cacheurlrlink original_linkextrassetmarkermarkers satisfied_byconflicts_with_temp_build_dir_ideal_build_dirinstall_succeededoptionsZpreparedZ is_directisolatedr build_envmetadata_directorypyproject_requiresrequirements_to_checkpep517_backend use_pep517) selfrArBrDrIrLrQr^rXrWZ wheel_cacherCrNr;r;r?__init__TsH    zInstallRequirement.__init__cCs|jr,t|j}|jrD|dt|jj7}n|jr@t|jj}nd}|jdk rb|dt|jj7}|jrt |jt j r~|j}n |j }|r|d|7}|S)Nz from %szz in %sz (from %s)) rAstrrLr#rKrRrlocationrB isinstancer string_types from_pathr_srBr;r;r?__str__s     zInstallRequirement.__str__cCsd|jjt||jfS)Nz<%s object: %s editable=%r>) __class____name__rarIr_r;r;r?__repr__s zInstallRequirement.__repr__cs>t|t}fddt|D}dj|jjd|dS)z>An un-tested helper for getting state, for debugging. c3s|]}d||VqdS)z{}={!r}N)format)r=attrZ attributesr;r? sz2InstallRequirement.format_debug..z<{name} object: {{{state}}}>z, )namestate)varssortedrmrirjjoin)r_namesrrr;ror? format_debugs zInstallRequirement.format_debugcCsh|jdkr||||_|jdk rd|sd|j}t}|jj|j|j|d|_||jkrdtd|jdS)aEnsure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. If require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. N)rLZ package_namesupported_tagszUsing cached wheel link: %s) rLZfind_requirementrJr Z get_supportedgetrqloggerdebug)r_finderZupgradeZrequire_hashesZold_linkrxr;r;r? populate_links  z InstallRequirement.populate_linkcCs |jdkrdStt|jjSN)rArrZ safe_namerqrkr;r;r?rqs zInstallRequirement.namecCs|jjSr~)rA specifierrkr;r;r?rszInstallRequirement.specifiercCs$|j}t|dko"tt|jdkS)zReturn whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. >=====)rlennextiteroperator)r_Z specifiersr;r;r? is_pinneds zInstallRequirement.is_pinnedcCs t|jSr~)r!rqrkr;r;r?installed_versionsz$InstallRequirement.installed_versioncs0|sd}jdk r(tfdd|DSdSdS)N)c3s|]}jd|iVqdS)r>N)rQZevaluater<rkr;r?rpsz3InstallRequirement.match_markers..T)rQany)r_Zextras_requestedr;rkr? match_markers s  z InstallRequirement.match_markerscCst|jdiS)zReturn whether any known-good hashes are specified as options. These activate --require-hashes mode; hashes specified as part of a URL do not. hashes)boolrWryrkr;r;r?has_hash_optionss z#InstallRequirement.has_hash_optionsTcCsJ|jdi}|r|jn|j}|rB|jrB||jg|jt |S)aReturn a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() r) rWrycopyrLrMhash setdefaultZ hash_nameappendr)r_Ztrust_internetZ good_hashesrLr;r;r?r#s  zInstallRequirement.hashescCsR|jdkrdSt|j}|jrNt|jtjr4|j}n |j}|rN|d|7}|S)z@Format a nice indicator to show where this "comes from" Nz->)rArarBrcrrdrerfr;r;r?re9s    zInstallRequirement.from_pathcCs||jdk r|jjS|jdkr6tdd|_||_|jjS|jrH|j}n|j}tj |snt d|t |tj ||S)Nz req-buildkindzCreating directory %s)rTrFrAr)rUrIrqlowerrEexistsrzr{rru)r_ build_dirrqr;r;r?ensure_build_locationIs      z(InstallRequirement.ensure_build_locationcCs|jdk rdS|j}d|_||j}tj|rBtdt|t d|t|jt|t |j|tj tj||_t|dd|_|jr|j}tjj||jd}tj||}tj tj|}||_d|_dS)aMove self._temp_build_dir to "self._ideal_build_dir/self.req.name" For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a temporary directory and store the _ideal_build_dir. This is only called to "fix" the build directory after generating metadata. NzCannot update repository at %s; repository location is unknownfile+r)rK) rLrzr{rDZschemerKrr,Z get_backendr"obtainZexport)r_rZvc_typerKZ vcs_backendZ hidden_urlr;r;r?update_editables    z"InstallRequirement.update_editablecCsB||std|jdS|jp&|j}t|}||||S)a 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 is linked to global site-packages. z#Skipping %s as it is not installed.N) rrzrrqrRrSrZ from_distremove)r_Z auto_confirmverboserZdistZuninstalled_pathsetr;r;r? uninstalls    zInstallRequirement.uninstallcCs(|t|dd}|tjjd}|S)Nr/)rreplacerErFr)r_rqrr;r;r?_clean_zip_namesz"InstallRequirement._clean_zip_namecCs(tj||}|||}|jd|S)Nr)rErFrurrq)r_rF parentdirrootdirrqr;r;r?_get_archive_names z$InstallRequirement._get_archive_namec Csd}d|j|jdf}tj||}tj|rtdt|d}|dkrRd}nj|dkrvt d t|t |nF|d krt |}t d t|t|t ||n|d krtd |sdStj|dtjdd}|tjtj|j}t|D]\} } } d| kr| d| D]6} |j| | |d} t| d}d|_||dq | D]>}|tkrnq\|j|| |d}tj| |}|||q\qW5QRXtdt|dS)z}Saves archive to provided build_dir. Used for saving downloaded VCS requirements as part of `pip download`. Tz %s-%s.ziprz8The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)bort )iwbarFrz Deleting %srzBacking up %s to %srN)Z allowZip64z pip-egg-info)rrrirzSaved %s)rqrrErFrurrrrzrrrrrrexitzipfileZZipFileZ ZIP_DEFLATEDnormcaserHrwalkrZZipInfoZ external_attrZwritestrrwriter)r_rZcreate_archiveZ archive_nameZ archive_pathZresponseZ dest_fileZ zip_outputdirdirpathZdirnames filenamesdirnameZ dir_arcnameZzipdirfilenameZ file_arcnamer;r;r?archivesx       zInstallRequirement.archivec  sh|dk r |ng}|jr*|j|||ddS|jrnt|j} t| |j|j|j|||||dd|_ dSt ||j dg}t ||j dg}t dd} tj| jd} ||| ||} td |j} t*|j| | ||jd W5QRXW5QRXtj| s8td | W5QRdSd|_ fd d }t| \}|D],}tj|}|drX||}qqXtd|W5QRW5QRdSW5QRXg}t| L}|D]@}|}tj|r|tjj 7}|!tj"|||qW5QRX|#t$|tj|d}t|d}|%d|dW5QRXW5QRXdS)N)r)rrrrrrTrrrecordrzinstall-record.txtzRunning setup.py install for {})cmdrzRecord file %s not foundcs&dkstj|s|St|SdSr~)rErFisabsr)rFrr;r? prepend_rootsz0InstallRequirement.install..prepend_rootrz;Could not find .egg-info directory in install record for %szinstalled-files.txtr )&rIrrr Z wheel_versionrDZcheck_compatibilityrqrrVrrWryr)rErFruget_install_argsr(rmrrYrrrzr{openrrrstripisdirrrrsortr r)r_rrrrrrrrrZtemp_dirrecord_filename install_argsrrflineZ directoryZ egg_info_dirZ new_linesrZinst_files_pathr;rr?installEs           "   zInstallRequirement.installc Cst|j||jdd}|dd|g7}|dg7}|dk r@|d|g7}|dk rT|d|g7}|rd|dg7}n |d g7}trd t}|d tjt j d d ||j g7}|S)NT)rrZunbuffered_outputrz--recordz#--single-version-externally-managedz--rootz--prefixz --compilez --no-compilepythonz--install-headersZincludeZsite) r&rrXr+ sysconfigZget_python_versionrErFrurrrq)r_rrrrrrZ py_ver_strr;r;r?rs0       z#InstallRequirement.get_install_args) NFNNNFNNFr;)N)T)NNNTFT)r;N)T)FFF)NNNNTFT)*rj __module__ __qualname____doc__r`rhrlrwr}propertyrqrrrrrrrerrrrrrrrrrrrrrrrrrrrrrrrr;r;r;r?r:Ms  W      8 +     %     B `r:)eZ __future__rrZloggingrErrrrZdistutils.utilrZ pip._vendorrrZ"pip._vendor.packaging.requirementsrZpip._vendor.packaging.utilsrZpip._vendor.packaging.versionrr rZpip._vendor.pep517.wrappersr Z pip._internalr r Zpip._internal.build_envr Zpip._internal.exceptionsrZpip._internal.models.linkrZ*pip._internal.operations.generate_metadatarZpip._internal.pyprojectrrZpip._internal.req.req_uninstallrZpip._internal.utils.compatrZpip._internal.utils.hashesrZpip._internal.utils.loggingrZ pip._internal.utils.marker_filesrrZpip._internal.utils.miscrrrrrrrr r!r"r#r$Zpip._internal.utils.packagingr%Z$pip._internal.utils.setuptools_buildr&Zpip._internal.utils.subprocessr'r(Zpip._internal.utils.temp_dirr)Zpip._internal.utils.typingr*Zpip._internal.utils.virtualenvr+Zpip._internal.vcsr,typingr-r.r/r0r1r2r3r4Zpip._internal.cacher5Zpip._internal.indexr6Zpip._vendor.pkg_resourcesr7Z pip._vendor.packaging.specifiersr8Zpip._vendor.packaging.markersr9Z getLoggerrjrzobjectr:r;r;r;r?sV               8      $       req/__pycache__/req_set.cpython-38.pyc000064400000013635152347654150013661 0ustar00U .e@sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZerdd lmZmZmZmZmZdd lmZeeZGd d d eZdS))absolute_importN) OrderedDict)canonicalize_name) pep425tags)InstallationError) indent_log)MYPY_CHECK_RUNNING)Wheel)DictIterableListOptionalTuple)InstallRequirementc@sXeZdZdddZddZddZd d Zd d ZdddZddZ ddZ ddZ d S)RequirementSetFTcCs*t|_||_||_g|_g|_g|_dS)z!Create a RequirementSet. N)r requirementsrequire_hashescheck_supported_wheelsunnamed_requirementsZsuccessfully_downloadedreqs_to_cleanup)selfrrr=/usr/lib/python3.8/site-packages/pip/_internal/req/req_set.py__init__s zRequirementSet.__init__cCs4tdd|jDddd}ddd|DS)Ncss|]}|js|VqdSN)Z comes_from.0reqrrr +sz)RequirementSet.__str__..cSs t|jSrrnamerrrr,z(RequirementSet.__str__..key css|]}t|jVqdSrstrrrrrrr.s)sortedrvaluesjoin)rrrrr__str__(s zRequirementSet.__str__cCsBt|jddd}d}|j|jjt|ddd|DdS) NcSs t|jSrrr!rrrr"4r#z)RequirementSet.__repr__..r$z4<{classname} object; {count} requirement(s): {reqs}>z, css|]}t|jVqdSrr'rrrrr;sz*RequirementSet.__repr__..)Z classnamecountZreqs)r)rr*format __class____name__lenr+)rr format_stringrrr__repr__0szRequirementSet.__repr__cCs|jr t|j|dSr)r AssertionErrorrappend)r install_reqrrradd_unnamed_requirement>s z&RequirementSet.add_unnamed_requirementcCs"|js tt|j}||j|<dSr)r r4rr)rr6 project_namerrradd_named_requirementCs  z$RequirementSet.add_named_requirementNc Cs||s$td|j|jgdfS|jrd|jjrdt|jj}t }|j rd| |sdt d|j|j|dkksztd|js|||gdfSz||j}Wntk rd}YnX|dko|o|j o|j|jko|jj|jjk}|rt d|||jf|s"|||g|fS|js2|js:g|fS|joZ|joX|jj|jjk }|r||j|t d|jd|_ttt|jt|jB|_td||j|g|fS) a&Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environment markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. z6Ignoring %s: markers '%s' don't match your environmentNz-%s is not a supported wheel on this platform.zTa direct req shouldn't have a parent and also, a non direct req should have a parentz5Double requirement given: %s (already in %s, name=%r)zhCould not satisfy constraints for '%s': installation from path or url cannot be constrained to a versionFzSetting %s extras to: %s)Z match_markersloggerinfor ZmarkerslinkZis_wheelr filenamerZ get_supportedrZ supportedrZ is_directr4r7get_requirementKeyError constraintZextrasrZ specifierr9pathrr5tupler)setdebug) rr6Zparent_req_nameZextras_requestedZwheelZtagsZ existing_reqZhas_conflicting_requirementZdoes_not_satisfy_constraintrrradd_requirementJs          zRequirementSet.add_requirementcCs t|}||jko|j|j Sr)rrr@rr r8rrrhas_requirements  zRequirementSet.has_requirementcCs,t|}||jkr|j|Std|dS)NzNo project with the name %r)rrr?rFrrrr>s  zRequirementSet.get_requirementc Cs4tdt|jD] }|qW5QRXdS)zClean up files, remove builds.zCleaning up...N)r:rDrrZremove_temporary_source)rrrrr cleanup_filess  zRequirementSet.cleanup_files)FT)NN) r0 __module__ __qualname__rr,r3r7r9rErGr>rHrrrrrs   p  r)Z __future__rZlogging collectionsrZpip._vendor.packaging.utilsrZ pip._internalrZpip._internal.exceptionsrZpip._internal.utils.loggingrZpip._internal.utils.typingrZpip._internal.wheelr typingr r r r rZpip._internal.req.req_installrZ getLoggerr0r:objectrrrrrs          req/__pycache__/req_file.cpython-38.pyc000064400000022300152347654150013772 0ustar00U .e7 @sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZmZdd lmZer dd lmZmZmZmZmZm Z m!Z!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*ee"e+e!fZ,dgZ-e.dej/Z0e.dZ1e.dZ2ej3ej4ej5ej6ej7ej8ej9ej:ej;ejej?g Z@ejAejBejCgZDddeDDZEd)ddZFddZGd*ddZHddZIdd ZJd!d"ZKd#d$ZLd%d&ZMd'd(ZNdS)+z Requirements file parsing )absolute_importN) filterfalse)parse) cmdoptions)get_file_contentRequirementsFileParseError) SearchScope)install_req_from_editableinstall_req_from_line)MYPY_CHECK_RUNNING)AnyCallableIteratorListNoReturnOptionalTextTuple)InstallRequirement) WheelCache) PackageFinder) PipSessionparse_requirementsz^(http|https|file):z (^|\s+)#.*$z#(?P\$\{(?P[A-Z0-9_]+)\})cCsg|]}t|jqS)strdest).0orr>/usr/lib/python3.8/site-packages/pip/_internal/req/req_file.py Ksr Fc csj|dkrtdt|||d\}} t| |} | D]4\} } t| || |||||||d } | D] }|VqXq0dS)a1Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param session: Instance of pip.download.PipSession. :param constraint: If true, parsing a constraint file rather than requirements file. :param wheel_cache: Instance of pip.wheel.WheelCache :param use_pep517: Value of the --use-pep517 option. NzCparse_requirements() missing 1 required keyword argument: 'session') comes_fromsession) use_pep517 constraint) TypeErrorr preprocess process_line)filenamefinderr!optionsr"r$ wheel_cacher#_content lines_enum line_numberlineZreq_iterreqrrrrNs*    cCs6t|dd}t|}t|}t||}t|}|S)zSplit, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options )start) enumerate splitlines join_linesignore_comments skip_regexexpand_env_variables)r-r*r.rrrr&ys  r&c ! cst|} | } d| _|r"|j| _t|\} } tjdkrB| d} | t | | \}}d| rbdnd||f}| r|r||j nd}|rt ||i}tD]&}||jkr|j|r|j|||<qd||}t| |||||| |d Vn|jr |r|j nd}t|jd ||| ||d Vn|js0|jr|jrH|jd }d}n|jd }d }t|rpt||}n"t|stjtj||}t|||||||d }|D] }|Vqn|jr|j|_n|r|j }|j!}|jr|jg}|j"d krg}|j#r|$|j#|j rd|j d }tjtj%|}tj||}tj&|rZ|}|'|t(||d}||_)|j*r|+|j,pgD] }d||} |j-|| dqdS)a#Process a single requirements line; This can result in creating/yielding requirements, or updating the finder. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. :param constraint: If True, parsing a constraints file. :param options: OptionParser options that we may update N)utf8z%s %s (line %s)z-cz-rFz line {} of {})r!r#isolatedr*r+r$ line_sourcer)r!r#r$r>r+T)r$r+) find_links index_urls)source). build_parserZget_default_values index_urlZformat_controlbreak_args_optionssys version_infoencode parse_argsshlexsplitZ isolated_moderZcheck_install_build_globalSUPPORTED_OPTIONS_REQ_DEST__dict__formatr Z editablesr requirements constraints SCHEME_REsearch urllib_parseZurljoinospathjoindirnamerrequire_hashesr@rAno_indexZextra_index_urlsextendabspathexistsappendr search_scopepreZset_allow_all_prereleasesZ trusted_hostsZadd_trusted_host)!r0r(r/r)r!r*r"r+r#r$parserdefaultsZargs_strZ options_strZoptsr,Zline_comes_fromr>Z req_optionsrr?Zreq_pathZnested_constraintZ parsed_reqsr1r@rAvalueZreq_dirZrelative_to_reqs_filer^ZhostrBrrrr's                   r'cCsf|d}g}|dd}|D]2}|ds6|dr<qRq|||dqd|d|fS)zBreak up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex.  N-z--r)rK startswithr]poprV)r0tokensargsr*tokenrrrrEs    rEcsDtjdd}tt}|D]}|}||qfdd}||_|S)z7 Return a parser for parsing requirement lines F)Zadd_help_optioncsd|f}t|dS)NzInvalid requirement: %s %sr)selfmsgr0rr parser_exit6s z!build_parser..parser_exit)optparseZ OptionParserSUPPORTED_OPTIONSSUPPORTED_OPTIONS_REQZ add_optionexit)r0r`Zoption_factoriesZoption_factoryZoptionrmrrlrrC(s   rCccsd}g}|D]v\}}|dr(t|rjt|r:d|}|r^|||d|fVg}q||fVq |sr|}||dq |r|d|fVdS)zJoins a line ending in '' with the previous line (except when following comments). The joined line takes on the index of the first line. N\rc)endswith COMMENT_REmatchr]rVstrip)r.Zprimary_line_numberZnew_liner/r0rrrr6Bs     r6ccs4|D]*\}}td|}|}|r||fVqdS)z1 Strips comments and filter empty lines. rsN)rusubrw)r.r/r0rrrr7`s   r7cs2|r |jnd}|r.t|tfdd|}|S)zs Skip lines that match '--skip-requirements-regex' pattern Note: the regex pattern is only built once Ncs|dS)Nr2)rR)epatternrrvzskip_regex..)Zskip_requirements_regexrecompiler)r.r*r8rrzrr8ls  r8ccsL|D]B\}}t|D]$\}}t|}|s.q|||}q||fVqdS)aReplace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that contain a `$` aren't accidentally (partially) expanded. 2. Ensure consistency across platforms for requirement files. These points are the result of a discussion on the `github pull request #3514 `_. Valid characters in variable names follow the `POSIX standard `_ and are limited to uppercase letter, digits and the `_` (underscore). N) ENV_VAR_REfindallrTgetenvreplace)r.r/r0Zenv_varZvar_namerbrrrr9zs  r9)NNNNFNN)NNNNNNF)O__doc__Z __future__rrnrTr~rJrFZpip._vendor.six.movesrZpip._vendor.six.moves.urllibrrSZpip._internal.clirZpip._internal.downloadrZpip._internal.exceptionsrZ!pip._internal.models.search_scoper Zpip._internal.req.constructorsr r Zpip._internal.utils.typingr typingr rrrrrrrZpip._internal.reqrZpip._internal.cacherZpip._internal.indexrZpip._internal.network.sessionrintZ ReqFileLines__all__rIrQrurrPZeditablerOrYrDr@Zextra_index_urlZ always_unzipZ no_binaryZ only_binaryr_Z trusted_hostrXroZinstall_optionsZglobal_optionshashrprLrr&r'rErCr6r7r8r9rrrrs        (       +  req/__pycache__/req_file.cpython-38.opt-1.pyc000064400000022300152347654150014731 0ustar00U .e7 @sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZmZdd lmZer dd lmZmZmZmZmZm Z m!Z!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*ee"e+e!fZ,dgZ-e.dej/Z0e.dZ1e.dZ2ej3ej4ej5ej6ej7ej8ej9ej:ej;ejej?g Z@ejAejBejCgZDddeDDZEd)ddZFddZGd*ddZHddZIdd ZJd!d"ZKd#d$ZLd%d&ZMd'd(ZNdS)+z Requirements file parsing )absolute_importN) filterfalse)parse) cmdoptions)get_file_contentRequirementsFileParseError) SearchScope)install_req_from_editableinstall_req_from_line)MYPY_CHECK_RUNNING)AnyCallableIteratorListNoReturnOptionalTextTuple)InstallRequirement) WheelCache) PackageFinder) PipSessionparse_requirementsz^(http|https|file):z (^|\s+)#.*$z#(?P\$\{(?P[A-Z0-9_]+)\})cCsg|]}t|jqS)strdest).0orr>/usr/lib/python3.8/site-packages/pip/_internal/req/req_file.py Ksr Fc csj|dkrtdt|||d\}} t| |} | D]4\} } t| || |||||||d } | D] }|VqXq0dS)a1Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param session: Instance of pip.download.PipSession. :param constraint: If true, parsing a constraint file rather than requirements file. :param wheel_cache: Instance of pip.wheel.WheelCache :param use_pep517: Value of the --use-pep517 option. NzCparse_requirements() missing 1 required keyword argument: 'session') comes_fromsession) use_pep517 constraint) TypeErrorr preprocess process_line)filenamefinderr!optionsr"r$ wheel_cacher#_content lines_enum line_numberlineZreq_iterreqrrrrNs*    cCs6t|dd}t|}t|}t||}t|}|S)zSplit, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options )start) enumerate splitlines join_linesignore_comments skip_regexexpand_env_variables)r-r*r.rrrr&ys  r&c ! cst|} | } d| _|r"|j| _t|\} } tjdkrB| d} | t | | \}}d| rbdnd||f}| r|r||j nd}|rt ||i}tD]&}||jkr|j|r|j|||<qd||}t| |||||| |d Vn|jr |r|j nd}t|jd ||| ||d Vn|js0|jr|jrH|jd }d}n|jd }d }t|rpt||}n"t|stjtj||}t|||||||d }|D] }|Vqn|jr|j|_n|r|j }|j!}|jr|jg}|j"d krg}|j#r|$|j#|j rd|j d }tjtj%|}tj||}tj&|rZ|}|'|t(||d}||_)|j*r|+|j,pgD] }d||} |j-|| dqdS)a#Process a single requirements line; This can result in creating/yielding requirements, or updating the finder. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. :param constraint: If True, parsing a constraints file. :param options: OptionParser options that we may update N)utf8z%s %s (line %s)z-cz-rFz line {} of {})r!r#isolatedr*r+r$ line_sourcer)r!r#r$r>r+T)r$r+) find_links index_urls)source). build_parserZget_default_values index_urlZformat_controlbreak_args_optionssys version_infoencode parse_argsshlexsplitZ isolated_moderZcheck_install_build_globalSUPPORTED_OPTIONS_REQ_DEST__dict__formatr Z editablesr requirements constraints SCHEME_REsearch urllib_parseZurljoinospathjoindirnamerrequire_hashesr@rAno_indexZextra_index_urlsextendabspathexistsappendr search_scopepreZset_allow_all_prereleasesZ trusted_hostsZadd_trusted_host)!r0r(r/r)r!r*r"r+r#r$parserdefaultsZargs_strZ options_strZoptsr,Zline_comes_fromr>Z req_optionsrr?Zreq_pathZnested_constraintZ parsed_reqsr1r@rAvalueZreq_dirZrelative_to_reqs_filer^ZhostrBrrrr's                   r'cCsf|d}g}|dd}|D]2}|ds6|dr<qRq|||dqd|d|fS)zBreak up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex.  N-z--r)rK startswithr]poprV)r0tokensargsr*tokenrrrrEs    rEcsDtjdd}tt}|D]}|}||qfdd}||_|S)z7 Return a parser for parsing requirement lines F)Zadd_help_optioncsd|f}t|dS)NzInvalid requirement: %s %sr)selfmsgr0rr parser_exit6s z!build_parser..parser_exit)optparseZ OptionParserSUPPORTED_OPTIONSSUPPORTED_OPTIONS_REQZ add_optionexit)r0r`Zoption_factoriesZoption_factoryZoptionrmrrlrrC(s   rCccsd}g}|D]v\}}|dr(t|rjt|r:d|}|r^|||d|fVg}q||fVq |sr|}||dq |r|d|fVdS)zJoins a line ending in '' with the previous line (except when following comments). The joined line takes on the index of the first line. N\rc)endswith COMMENT_REmatchr]rVstrip)r.Zprimary_line_numberZnew_liner/r0rrrr6Bs     r6ccs4|D]*\}}td|}|}|r||fVqdS)z1 Strips comments and filter empty lines. rsN)rusubrw)r.r/r0rrrr7`s   r7cs2|r |jnd}|r.t|tfdd|}|S)zs Skip lines that match '--skip-requirements-regex' pattern Note: the regex pattern is only built once Ncs|dS)Nr2)rR)epatternrrvzskip_regex..)Zskip_requirements_regexrecompiler)r.r*r8rrzrr8ls  r8ccsL|D]B\}}t|D]$\}}t|}|s.q|||}q||fVqdS)aReplace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that contain a `$` aren't accidentally (partially) expanded. 2. Ensure consistency across platforms for requirement files. These points are the result of a discussion on the `github pull request #3514 `_. Valid characters in variable names follow the `POSIX standard `_ and are limited to uppercase letter, digits and the `_` (underscore). N) ENV_VAR_REfindallrTgetenvreplace)r.r/r0Zenv_varZvar_namerbrrrr9zs  r9)NNNNFNN)NNNNNNF)O__doc__Z __future__rrnrTr~rJrFZpip._vendor.six.movesrZpip._vendor.six.moves.urllibrrSZpip._internal.clirZpip._internal.downloadrZpip._internal.exceptionsrZ!pip._internal.models.search_scoper Zpip._internal.req.constructorsr r Zpip._internal.utils.typingr typingr rrrrrrrZpip._internal.reqrZpip._internal.cacherZpip._internal.indexrZpip._internal.network.sessionrintZ ReqFileLines__all__rIrQrurrPZeditablerOrYrDr@Zextra_index_urlZ always_unzipZ no_binaryZ only_binaryr_Z trusted_hostrXroZinstall_optionsZglobal_optionshashrprLrr&r'rErCr6r7r8r9rrrrs        (       +  req/__pycache__/req_uninstall.cpython-38.opt-1.pyc000064400000041635152347654150016037 0ustar00U .e&\@s|ddlmZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZmZmZddlmZddlmZmZmZmZmZmZmZmZmZdd lm Z m!Z!dd l"m#Z#e#r dd l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/e0e1Z2d dZ3ddZ4e4ddZ5ddZ6ddZ7ddZ8Gddde9Z:Gddde9Z;Gddde9Z.unique) functoolswraps)r3r4r(r2r)_unique=sr7ccstt|d}|D]t}tj|j|d}|V|drtj |\}}|dd}tj||d}|Vtj||d}|VqdS)a Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. ZRECORDr.pyN.pyc.pyo) csvreaderr Zget_metadata_linesr!r"r#locationendswithsplit)r%rrowr"Zdnr3baser(r(r)uninstallation_pathsJs   rDcsJtjjt}t|tdD]*tfdd|D}|s|q|S)zCompact 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.keyc3s:|]2}|do0t|dkVqdS)*N) startswithrstriplen).0Z shortpathr"sepr(r) lszcompact..)r!r"rMr,sortedrJanyr-)pathsZ short_pathsZ should_skipr(rLr)compactbs rRc stdd|D}t|}ttdd|Dtd}t}dd|D]tfdd|DrfqJt}t}tD]B\}}|fdd|D|fd d|Dq|||sJ| || tj qJtt |j ||BS) zReturns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. css|]}tj||fVqdSr+)r!r"normcaserKpr(r(r)rN}sz&compress_for_rename..css|]}tj|dVqdS)rN)r!r"r@rTr(r(r)rNsrEcWstjtjj|Sr+)r!r"rSr#)ar(r(r) norm_joinsz&compress_for_rename..norm_joinc3s |]}tj|VqdSr+)r!r"rSrH)rKw)rootr(r)rNsc3s|]}|VqdSr+r()rKddirnamerWrYr(r)rNsc3s|]}|VqdSr+r()rKfr[r(r)rNs)dictr,rOvaluesrJrPr!walkupdatedifference_updater-rMmap __getitem__) rQZcase_mapZ remainingZ uncheckedZ wildcardsZ all_filesZ all_subdirsZsubdirsfilesr(r[r)compress_for_renamevs6    rfc Cst|}t}t}t}|D]>}|dr.q|ds@d|krR|tj|||qtttjj|}t|}|D]d}t |D]T\}} } | D]D} | drqtj || } tj | rtj| |kr|| qqq||dd|DB}||fS)asReturns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. r:z __init__.py .dist-infocSsh|]}tj|dqS)rG)r!r"r#)rKfolderr(r(r) sz.compress_for_output_listing..) r,r?r-r!r"r\rcrSrRr`r#isfile) rQ will_remove will_skipZfoldersrer"Z_normcased_filesrhdirpath_ZdirfilesZfnameZfile_r(r(r)compress_for_output_listings4     roc@sLeZdZdZddZddZddZdd Zd d Zd d Z e ddZ dS)StashedUninstallPathSetzWA set of file rename operations to stash files while tentatively uninstalling them.cCsi|_g|_dSr+) _save_dirs_movesselfr(r(r)__init__sz StashedUninstallPathSet.__init__cCsDz t|}Wntk r*tdd}YnX||jtj|<|jS)zStashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir. uninstallZkind)rOSErrorrrqr!r"rS)rtr"save_dirr(r(r)_get_directory_stashs  z,StashedUninstallPathSet._get_directory_stashcCstj|}tj|d}}d}||krfz|j|}WqWntk rPYnXtj||}}q"tj|}tdd}||j|<tj||}|r|tjjkrtj |j|S|jS)zStashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.Nrvrw) r!r"rSr\rqKeyErrorrrelpathcurdirr#)rtr"headZold_headryr|r(r(r)_get_file_stashs"     z'StashedUninstallPathSet._get_file_stashcCsltj|otj| }|r*||}n ||}|j||f|r^tj|r^t|t |||S)zStashes the directory or file and returns its new location. Handle symlinks as files to avoid modifying the symlink targets. ) r!r"isdirislinkrzrrrr$rmdirr)rtr"Z path_is_dirnew_pathr(r(r)stashs    zStashedUninstallPathSet.stashcCs,|jD]\}}|q g|_i|_dS)z0Commits the uninstall by removing stashed files.N)rqitemsZcleanuprr)rtrnryr(r(r)commits zStashedUninstallPathSet.commitc Cs|jD]}tjd|q|jD]\}}zTtd||tj|sPtj|r\t |ntj |rpt |t ||Wq t k r}ztd|td|W5d}~XYq Xq |dS)z2Undoes the uninstall by moving stashed files back.Moving to %s from %szReplacing %s from %szFailed to restore %sz Exception: %sN)r)rrlogginginfologgerdebugr!r"rjrunlinkrrrrxerrorr)rtrUrr"Zexr(r(r)rollback&s     z StashedUninstallPathSet.rollbackcCs t|jSr+)boolrrrsr(r(r) can_rollback:sz$StashedUninstallPathSet.can_rollbackN) __name__ __module__ __qualname____doc__rurzrrrrpropertyrr(r(r(r)rps rpc@s^eZdZdZddZddZddZdd Zdd d Zd dZ ddZ ddZ e ddZ dS)UninstallPathSetzMA set of file paths to be removed in the uninstallation of a requirement.cCs(t|_t|_i|_||_t|_dSr+)r,rQ_refusepthr%rp _moved_paths)rtr%r(r(r)ruCs zUninstallPathSet.__init__cCst|S)zs Return True if the given path is one we are permitted to remove/modify, False otherwise. )r)rtr"r(r(r) _permittedKszUninstallPathSet._permittedcCstj|\}}tjt|tj|}tj|s:dS||rR|j |n |j |tj |ddkrt r| t |dS)Nr8)r!r"r@r#rrSexistsrrQr-rsplitextr r)rtr"r~tailr(r(r)r-Ts   zUninstallPathSet.addcCsLt|}||r<||jkr*t||j|<|j||n |j|dSr+)rrrUninstallPthEntriesr-r)rtpth_fileentryr(r(r)add_pthhs   zUninstallPathSet.add_pthFc Cs|jstd|jjdS|jjd|jj}td|tp|sP||r|j}t |j}t t |D]}| |t d|ql|jD] }|qtd|W5QRXdS)z[Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).z7Can't uninstall '%s'. No files were found to uninstall.N-zUninstalling %s:zRemoving file or directory %szSuccessfully uninstalled %s)rQrrr% project_nameversionr _allowed_to_proceedrrfrOrRrrrr_remove)rtZ auto_confirmverboseZdist_name_versionZmovedZ for_renamer"rr(r(r)rrs&    zUninstallPathSet.removecCsndd}|st|j\}}nt|j}t}|d||d||d|j|r`|dt|jtddd kS) zIDisplay which files would be deleted and prompt for confirmation c SsD|sdSt|t"tt|D]}t|q&W5QRXdSr+)rrr rOrR)msgrQr"r(r(r)_displays  z6UninstallPathSet._allowed_to_proceed.._displayz Would remove:z+Would not remove (might be manually added):z%Would not remove (outside of prefix):zWill actually move:zProceed (y/n)? )ynr)rorQr,rrfr )rtrrrkrlr(r(r)rs     z$UninstallPathSet._allowed_to_proceedcCsR|jjstd|jjdStd|jj|j|j D] }|q@dS)z1Rollback the changes previously made by remove().z'Can't roll back %s; was not uninstalledNzRolling back uninstall of %s) rrrrr%rrrrr_)rtrr(r(r)rs zUninstallPathSet.rollbackcCs|jdS)z?Remove temporary save dir: rollback will no longer be possible.N)rrrsr(r(r)rszUninstallPathSet.commitc st|j}t|s.td|j|tj||S|ddt dt dhDkrhtd|j|||S||}t |}d t |j}|jotj|j}t|jdd}|r|jd r|j|s||j|d r|d D]&}tjtj|j|} || qn|d r|d rB|d ngfd d|d DD]J} tj|j| } || || d|| d|| dqbn|rtd |jn|jdr ||jtj|jd} tjtj|jd} || d| n|rP|jdrPt |D]} || q.ZstdlibZ platstdlibzsz.UninstallPathSet.from_dist..r8r:r;zCannot uninstall {!r}. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.z.eggrzeasy-install.pthz./rgrAz)Not sure how to uninstall: %s - Check: %sZscriptsz.batconsole_scripts)groupF gui_scriptsT)0rr>rrrrFsysprefix sysconfigZget_pathrformatrZ to_filenamerZegg_infor!r"rgetattrZ _providerr?r-Z has_metadataZ get_metadata splitlinesnormpathr#rr@r\rrDopenrSreadlinestriprZmetadata_isdirZmetadata_listdirr rrrZ get_entry_mapkeysextendr*)clsr%Z dist_pathr'Zdevelop_egg_linkZdevelop_egg_link_egg_infoZegg_info_existsZdistutils_egg_infoZinstalled_filer"Z top_level_pkgZeasy_install_eggZeasy_install_pthfhZ link_pointerZscriptr&Z_scripts_to_removernamersr(rr) from_dists                      zUninstallPathSet.from_distN)FF)rrrrrurr-rrrrr classmethodrr(r(r(r)r@s  rc@s,eZdZddZddZddZddZd S) rcCs0tj|std|||_t|_d|_dS)Nz.Cannot remove entries from nonexistent file %s)r!r"rjrfiler,entries _saved_lines)rtrr(r(r)ruIs zUninstallPthEntries.__init__cCs<tj|}tr,tj|ds,|dd}|j|dS)Nr\/)r!r"rSr splitdrivereplacerr-)rtrr(r(r)r-Ss  zUninstallPthEntries.addc Cstd|jt|jd}|}||_W5QRXtdd|DrLd}nd}|r~|d|ds~|d|d|d<|j D]>}z$td || ||dWqt k rYqXqt|jd }| |W5QRXdS) NzRemoving pth entries from %s:rbcss|]}d|kVqdS)s Nr()rKliner(r(r)rNjsz-UninstallPthEntries.remove..z  zutf-8zRemoving entry: %swb) rrrr readlinesrrPr?encoderr ValueError writelines)rtrlinesZendlinerr(r(r)rcs"  zUninstallPthEntries.removec CsR|jdkrtd|jdStd|jt|jd}||jW5QRXdS)Nz.Cannot roll back changes to %s, none were madeFz!Rolling %s back to previous staterT)rrrrrrr)rtrr(r(r)rzs zUninstallPthEntries.rollbackN)rrrrur-rrr(r(r(r)rHs r)=Z __future__rr<r5rr!rrZ pip._vendorrZpip._internal.exceptionsrZpip._internal.locationsrrZpip._internal.utils.compatrrr Zpip._internal.utils.loggingr Zpip._internal.utils.miscr r r rrrrrrZpip._internal.utils.temp_dirrrZpip._internal.utils.typingrtypingrrrrrrrrrZpip._vendor.pkg_resourcesr Z getLoggerrrr*r7rDrRrfroobjectrprrr(r(r(r)s<    ,  ,    (3o req/__pycache__/__init__.cpython-38.pyc000064400000003244152347654150013751 0ustar00U .e @sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z erhdd l mZmZmZd d d d gZeeZddd ZdS))absolute_importN) indent_log)MYPY_CHECK_RUNNING)parse_requirements)InstallRequirement)RequirementSet)AnyListSequencerrrinstall_given_reqsc Os|r tdddd|Dt|D]}|jrbtd|jt|jdd}W5QRXz|j||f||Wn0tk r|jo|j }|r| YnX|jo|j}|r| | q,W5QRX|S)zu Install everything in the given list. (to be called after having downloaded and unpacked the packages) z!Installing collected packages: %sz, cSsg|] }|jqSr )name).0Zreqr r >/usr/lib/python3.8/site-packages/pip/_internal/req/__init__.py +sz&install_given_reqs..zFound existing installation: %sT)Z auto_confirm) loggerinfojoinrZconflicts_withZ uninstallZinstall ExceptionZinstall_succeededZrollbackZcommitZremove_temporary_source) Z to_installZinstall_optionsZglobal_optionsargskwargsZ requirementZuninstalled_pathsetZshould_rollbackZ should_commitr r rr sN)r )Z __future__rZloggingZpip._internal.utils.loggingrZpip._internal.utils.typingrZreq_filerZ req_installrZreq_setrtypingr r r __all__Z getLogger__name__rr r r r rs       req/__pycache__/constructors.cpython-38.pyc000064400000024164152347654150014766 0ustar00U .e48@sdZddlZddlZddlZddlmZddlmZmZddl m Z ddl m Z m Z ddlmZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lmZmZddlmZddl m!Z!ddl"m#Z#m$Z$ddl%m&Z&erddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/dddgZ0e1e2Z3e j45Z6ddZ7ddZ8ddZ9ddZ:ddZ;Gd d!d!e<Z=d"d#Z>d/d%dZ?d&d'Z@d(d)ZAd*d+ZBd0d,dZCd1d-d.ZDdS)2a~Backing implementation for InstallRequirement's various constructors The idea here is that these formed a major chunk of InstallRequirement's size so, moving them and support code dedicated to them outside of that class helps creates for better understandability for the rest of the code. These are meant to be used elsewhere within pip to create instances of InstallRequirement. N)Marker)InvalidRequirement Requirement) Specifier)RequirementParseErrorparse_requirements)InstallationError)PyPITestPyPI)Link)make_pyproject_path)InstallRequirement)ARCHIVE_EXTENSIONS)is_installable_dirsplitext)MYPY_CHECK_RUNNING) path_to_url)is_urlvcs)Wheel)AnyDictOptionalSetTupleUnion) WheelCacheinstall_req_from_editableinstall_req_from_lineparse_editablecCs t|d}|tkrdSdS)z9Return True if `name` is a considered as an archive file.TF)rlowerr)nameZextr#B/usr/lib/python3.8/site-packages/pip/_internal/req/constructors.pyis_archive_file4sr%cCs6td|}d}|r*|d}|d}n|}||fS)Nz^(.+)(\[[^\]]+\])$r )rematchgroup)pathmextrasZpath_no_extrasr#r#r$ _strip_extras=s   r-cCs|s tStd|jS)N placeholder)setrr!r,)r,r#r#r$convert_extrasJsr0c Cs`|}t|\}}tj|rptjtj|dshdtj|}t|}tj |r`|d7}t |t |}| drt|j}|r||td| jfS||dfStD]&}| d|rd||f}qqd |krt d ||d d d  }t|s:d |dddtjDd} t | t|j}|sVt d|||dfS)aParses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] zsetup.pyzMFile "setup.py" not found. Directory cannot be installed in editable mode: {}zb (A "pyproject.toml" file was found, but editable mode currently requires a setup.py based build.)zfile:r.Nz%s:z%s+%s+z{} is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with svn+, git+, hg+, or bzr+).r rzFor --editable=%s only z, cSsg|]}|jdqS)z+URLr").0Zbackendr#r#r$ sz"parse_editable..z is currently supportedzZCould not detect requirement name for '%s', please specify one with #egg=your_package_name)r-osr*isdirexistsjoinformatabspathr isfilerrr! startswithr egg_fragmentrr,rsplitZ get_backendZbackends) editable_requrlZ url_no_extrasr,msgZpyproject_pathZ package_nameZversion_controlZvc_typeZ error_messager#r#r$rQsb          c Csd}tj|rd}zFt|d2}tt||dd|ddd7}W5QRXWqtk rtj d |d d YqXn |d |7}|S) zReturns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path z It does exist.rz The argument you provided z(%s) appears to be az" requirements file. If that is thez# case, use the '-r' flag to installz" the packages specified within it.z2Cannot parse '%s' as requirements fileT)exc_infoz File '%s' does not exist.) r5r*r7opennextrreadrloggerdebug)reqrAfpr#r#r$deduce_helpful_msgs.   rLc@seZdZddZdS)RequirementPartscCs||_||_||_||_dSN) requirementlinkmarkersr,)selfrOrPrQr,r#r#r$__init__szRequirementParts.__init__N)__name__ __module__ __qualname__rSr#r#r#r$rMsrMcCs`t|\}}}|dk rFz t|}WqJtk rBtd|YqJXnd}t|}t||d|S)NInvalid requirement: '%s')rrrrr rM)r?r"r@Zextras_overriderJrPr#r#r$parse_req_from_editables rXFc CsLt|}|jjdkr|jjnd}t|j||d|j||||r>|ni||jd S)NfileT) source_dirZeditablerP constraint use_pep517isolatedoptions wheel_cacher,)rXrPschemeZ file_pathr rOr,) r? comes_fromr\r]r^r_r[partsrZr#r#r$rs  cCs>tjj|krdStjjdk r,tjj|kr,dS|dr:dSdS)akChecks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (which represents the current directory). TN.F)r5r*sepaltsepr<r2r#r#r$_looks_like_paths  rfcCst|r0tj|r0t|r$t|Std|t|slenrHZwarning)r*r"Z urlreq_partsr#r#r$_get_url_from_path s(   ricst|rd}nd}||krF||d\}}|}|s.with_sourcezIt looks like a path.=c3s|]}|kVqdSrNr#)r3op) req_as_stringr#r$ jsz&parse_req_from_line..z,= is not a valid operator. Did you mean == ?rBzInvalid requirement: {!r}z Hint: {}) rr>striprr5r*normpathr:r r-rir`r'searchr@rZis_wheelrfilenamer"versionr=r0rrrdrLany operatorsr9rrM)r"rlZ marker_sepZmarkers_as_stringrQr*rPZextras_as_stringpr@Zwheelr,rmrJZadd_msgrAr#)rlrpr$parse_req_from_line+sj         rzc Cs6t||}t|j||j|j|||r&|ni|||jd S)aCreates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. )rPrQr\r]r^r_r[r,)rzr rOrPrQr,) r"rar\r]r^r_r[rlrbr#r#r$rzs  cCszz t|}Wn tk r,td|YnXtjtjg}|jrh|rh|jrh|jj|krhtd|j |ft |||||dS)NrWzkPackages installed from PyPI cannot depend on packages which are not also hosted on PyPI. %s depends on %s )r]r_r\) rrrr Zfile_storage_domainr r@rPZnetlocr"r )Z req_stringrar]r_r\rJZdomains_not_allowedr#r#r$install_req_from_req_strings,  r{)NNFNNF)NNFNNFN)NFNN)E__doc__Zloggingr5r'Zpip._vendor.packaging.markersrZ"pip._vendor.packaging.requirementsrrZ pip._vendor.packaging.specifiersrZpip._vendor.pkg_resourcesrrZpip._internal.exceptionsrZpip._internal.models.indexr r Zpip._internal.models.linkr Zpip._internal.pyprojectr Zpip._internal.req.req_installr Zpip._internal.utils.filetypesrZpip._internal.utils.miscrrZpip._internal.utils.typingrZpip._internal.utils.urlsrZpip._internal.vcsrrZpip._internal.wheelrtypingrrrrrrZpip._internal.cacher__all__Z getLoggerrTrHZ _operatorskeysrxr%r-r0rrLobjectrMrXrrfrirzrr{r#r#r#r$sr                J "Q req/__pycache__/constructors.cpython-38.opt-1.pyc000064400000024164152347654150015725 0ustar00U .e48@sdZddlZddlZddlZddlmZddlmZmZddl m Z ddl m Z m Z ddlmZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lmZmZddlmZddl m!Z!ddl"m#Z#m$Z$ddl%m&Z&erddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/dddgZ0e1e2Z3e j45Z6ddZ7ddZ8ddZ9ddZ:ddZ;Gd d!d!e<Z=d"d#Z>d/d%dZ?d&d'Z@d(d)ZAd*d+ZBd0d,dZCd1d-d.ZDdS)2a~Backing implementation for InstallRequirement's various constructors The idea here is that these formed a major chunk of InstallRequirement's size so, moving them and support code dedicated to them outside of that class helps creates for better understandability for the rest of the code. These are meant to be used elsewhere within pip to create instances of InstallRequirement. N)Marker)InvalidRequirement Requirement) Specifier)RequirementParseErrorparse_requirements)InstallationError)PyPITestPyPI)Link)make_pyproject_path)InstallRequirement)ARCHIVE_EXTENSIONS)is_installable_dirsplitext)MYPY_CHECK_RUNNING) path_to_url)is_urlvcs)Wheel)AnyDictOptionalSetTupleUnion) WheelCacheinstall_req_from_editableinstall_req_from_lineparse_editablecCs t|d}|tkrdSdS)z9Return True if `name` is a considered as an archive file.TF)rlowerr)nameZextr#B/usr/lib/python3.8/site-packages/pip/_internal/req/constructors.pyis_archive_file4sr%cCs6td|}d}|r*|d}|d}n|}||fS)Nz^(.+)(\[[^\]]+\])$r )rematchgroup)pathmextrasZpath_no_extrasr#r#r$ _strip_extras=s   r-cCs|s tStd|jS)N placeholder)setrr!r,)r,r#r#r$convert_extrasJsr0c Cs`|}t|\}}tj|rptjtj|dshdtj|}t|}tj |r`|d7}t |t |}| drt|j}|r||td| jfS||dfStD]&}| d|rd||f}qqd |krt d ||d d d  }t|s:d |dddtjDd} t | t|j}|sVt d|||dfS)aParses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] zsetup.pyzMFile "setup.py" not found. Directory cannot be installed in editable mode: {}zb (A "pyproject.toml" file was found, but editable mode currently requires a setup.py based build.)zfile:r.Nz%s:z%s+%s+z{} is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with svn+, git+, hg+, or bzr+).r rzFor --editable=%s only z, cSsg|]}|jdqS)z+URLr").0Zbackendr#r#r$ sz"parse_editable..z is currently supportedzZCould not detect requirement name for '%s', please specify one with #egg=your_package_name)r-osr*isdirexistsjoinformatabspathr isfilerrr! startswithr egg_fragmentrr,rsplitZ get_backendZbackends) editable_requrlZ url_no_extrasr,msgZpyproject_pathZ package_nameZversion_controlZvc_typeZ error_messager#r#r$rQsb          c Csd}tj|rd}zFt|d2}tt||dd|ddd7}W5QRXWqtk rtj d |d d YqXn |d |7}|S) zReturns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path z It does exist.rz The argument you provided z(%s) appears to be az" requirements file. If that is thez# case, use the '-r' flag to installz" the packages specified within it.z2Cannot parse '%s' as requirements fileT)exc_infoz File '%s' does not exist.) r5r*r7opennextrreadrloggerdebug)reqrAfpr#r#r$deduce_helpful_msgs.   rLc@seZdZddZdS)RequirementPartscCs||_||_||_||_dSN) requirementlinkmarkersr,)selfrOrPrQr,r#r#r$__init__szRequirementParts.__init__N)__name__ __module__ __qualname__rSr#r#r#r$rMsrMcCs`t|\}}}|dk rFz t|}WqJtk rBtd|YqJXnd}t|}t||d|S)NInvalid requirement: '%s')rrrrr rM)r?r"r@Zextras_overriderJrPr#r#r$parse_req_from_editables rXFc CsLt|}|jjdkr|jjnd}t|j||d|j||||r>|ni||jd S)NfileT) source_dirZeditablerP constraint use_pep517isolatedoptions wheel_cacher,)rXrPschemeZ file_pathr rOr,) r? comes_fromr\r]r^r_r[partsrZr#r#r$rs  cCs>tjj|krdStjjdk r,tjj|kr,dS|dr:dSdS)akChecks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (which represents the current directory). TN.F)r5r*sepaltsepr<r2r#r#r$_looks_like_paths  rfcCst|r0tj|r0t|r$t|Std|t|slenrHZwarning)r*r"Z urlreq_partsr#r#r$_get_url_from_path s(   ricst|rd}nd}||krF||d\}}|}|s.with_sourcezIt looks like a path.=c3s|]}|kVqdSrNr#)r3op) req_as_stringr#r$ jsz&parse_req_from_line..z,= is not a valid operator. Did you mean == ?rBzInvalid requirement: {!r}z Hint: {}) rr>striprr5r*normpathr:r r-rir`r'searchr@rZis_wheelrfilenamer"versionr=r0rrrdrLany operatorsr9rrM)r"rlZ marker_sepZmarkers_as_stringrQr*rPZextras_as_stringpr@Zwheelr,rmrJZadd_msgrAr#)rlrpr$parse_req_from_line+sj         rzc Cs6t||}t|j||j|j|||r&|ni|||jd S)aCreates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. )rPrQr\r]r^r_r[r,)rzr rOrPrQr,) r"rar\r]r^r_r[rlrbr#r#r$rzs  cCszz t|}Wn tk r,td|YnXtjtjg}|jrh|rh|jrh|jj|krhtd|j |ft |||||dS)NrWzkPackages installed from PyPI cannot depend on packages which are not also hosted on PyPI. %s depends on %s )r]r_r\) rrrr Zfile_storage_domainr r@rPZnetlocr"r )Z req_stringrar]r_r\rJZdomains_not_allowedr#r#r$install_req_from_req_strings,  r{)NNFNNF)NNFNNFN)NFNN)E__doc__Zloggingr5r'Zpip._vendor.packaging.markersrZ"pip._vendor.packaging.requirementsrrZ pip._vendor.packaging.specifiersrZpip._vendor.pkg_resourcesrrZpip._internal.exceptionsrZpip._internal.models.indexr r Zpip._internal.models.linkr Zpip._internal.pyprojectr Zpip._internal.req.req_installr Zpip._internal.utils.filetypesrZpip._internal.utils.miscrrZpip._internal.utils.typingrZpip._internal.utils.urlsrZpip._internal.vcsrrZpip._internal.wheelrtypingrrrrrrZpip._internal.cacher__all__Z getLoggerrTrHZ _operatorskeysrxr%r-r0rrLobjectrMrXrrfrirzrr{r#r#r#r$sr                J "Q req/__pycache__/req_tracker.cpython-38.pyc000064400000006205152347654150014514 0ustar00U .e{ @sddlmZddlZddlZddlZddlZddlZddlmZddl m Z e rddl m Z ddl mZmZmZmZddlmZddlmZeeZGd d d eZdS) )absolute_importN) TempDirectory)MYPY_CHECK_RUNNING) TracebackType)IteratorOptionalSetType)InstallRequirement)Linkc@sReZdZddZddZddZddZd d Zd d Zd dZ e j ddZ dS)RequirementTrackercCsjtjd|_|jdkrJtddd|_|jj|_tjd<td|jnd|_td|jt |_ dS)NZPIP_REQ_TRACKERFz req-tracker)deleteZkindzCreated requirements tracker %rz Re-using requirements tracker %r) osenvironget_rootr _temp_dirpathloggerdebugset_entriesselfrA/usr/lib/python3.8/site-packages/pip/_internal/req/req_tracker.py__init__s zRequirementTracker.__init__cCs|SNrrrrr __enter__&szRequirementTracker.__enter__cCs |dSr)cleanup)rexc_typeZexc_valZexc_tbrrr__exit__*szRequirementTracker.__exit__cCs$t|j}tj|j|Sr) hashlibZsha224Zurl_without_fragmentencodeZ hexdigestrrjoinr)rlinkZhashedrrr _entry_path3szRequirementTracker._entry_pathc Cs|j}t|}||}z,t|}td||fW5QRXWnztk r}z\|jtjkrd||j ksrt t|d}| |W5QRX|j |t d||jW5d}~XYnXdS)Nz%s is already being built: %swzAdded %s to build tracker %r)r%strr&open LookupErrorreadIOErrorerrnoZENOENTrAssertionErrorwriteaddrrr)rreqr%infoZ entry_pathfperrrr08s       zRequirementTracker.addcCs6|j}|j|t||td||jdS)Nz Removed %s from build tracker %r) r%rremoverunlinkr&rrr)rr1r%rrrr5Ks zRequirementTracker.removecCsNt|jD]}||q |jdk }|r2|jtd|r@dnd|jdS)Nz%s build tracker %rZRemovedZCleaned)rrr5rrrrr)rr1r5rrrrRs    zRequirementTracker.cleanupccs||dV||dSr)r0r5)rr1rrrtrack]s zRequirementTracker.trackN) __name__ __module__ __qualname__rrr!r&r0r5r contextlibcontextmanagerr7rrrrr s   r )Z __future__rr;r-r"ZloggingrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrtypesrtypingrrrr Zpip._internal.req.req_installr Zpip._internal.models.linkr Z getLoggerr8robjectr rrrrs       req/__pycache__/req_install.cpython-38.pyc000064400000056654152347654150014544 0ustar00U .e@sLddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z ddlmZddlmZddlmZddlmZdd lmZdd lmZmZdd lmZdd lmZdd lm Z ddl!m"Z"ddl#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mm?Z?ddl@mAZAddlBmCZCmDZDddlEmFZFddlGmHZHddlImJZJddlKmLZLeHr.ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTddlmUZUddlVmWZWdd lXmYZYdd!lZm[Z[dd"l\m]Z]dd#l^m_Z_e`eaZbGd$d%d%ecZddS)&)absolute_importN) change_root) pkg_resourcessix) Requirement)canonicalize_name)Version)parse)Pep517HookCaller) pep425tagswheel)NoOpBuildEnvironment)InstallationError)Link)get_metadata_generator)load_pyproject_tomlmake_pyproject_path)UninstallPathSet) native_str)Hashes) indent_log)PIP_DELETE_MARKER_FILENAMEhas_delete_marker_file) _make_build_dirask_path_exists backup_dir display_pathdist_in_install_pathdist_in_site_packagesdist_in_usersite ensure_dirget_installed_versionhide_urlredact_auth_from_urlrmtree) get_metadata)make_setuptools_shim_args)call_subprocessrunner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING)running_under_virtualenv)vcs)AnyDictIterableListOptionalSequenceUnion)BuildEnvironment) WheelCache) PackageFinder) Distribution) SpecifierSet)Markerc @speZdZdZdPddZddZd d Zd d Zd dZe ddZ e ddZ e ddZ e ddZ dQddZe ddZdRddZddZd d!Zd"d#Zd$d%Zd&d'Ze d(d)ZdSd*d+Ze d,d-Ze d.d/Ze d0d1Zd2d3Zd4d5Zd6d7Ze d8d9Zd:d;Zdd?Z!dTd@dAZ"dUdBdCZ#dVdDdEZ$dFdGZ%dHdIZ&dJdKZ'dWdLdMZ(dNdOZ)dS)XInstallRequirementz Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. NFc Cs2|dkst|tst|||_||_| |_|dkrwsz.InstallRequirement.__init__..F)% isinstancerAssertionErrorreq comes_from constraint source_dirospathnormpathabspatheditable _wheel_cacheurlrlink original_linkextrassetmarkermarkers satisfied_byconflicts_with_temp_build_dir_ideal_build_dirinstall_succeededoptionsZpreparedZ is_directisolatedr build_envmetadata_directorypyproject_requiresrequirements_to_checkpep517_backend use_pep517) selfrCrDrFrKrNrSr`rZrYZ wheel_cacherErPr;r;r?__init__TsJ    zInstallRequirement.__init__cCs|jr,t|j}|jrD|dt|jj7}n|jr@t|jj}nd}|jdk rb|dt|jj7}|jrt |jt j r~|j}n |j }|r|d|7}|S)Nz from %szz in %sz (from %s)) rCstrrNr#rMrTrlocationrDrAr string_types from_pathrasrDr;r;r?__str__s     zInstallRequirement.__str__cCsd|jjt||jfS)Nz<%s object: %s editable=%r>) __class____name__rcrKrar;r;r?__repr__s zInstallRequirement.__repr__cs>t|t}fddt|D}dj|jjd|dS)z>An un-tested helper for getting state, for debugging. c3s|]}d||VqdS)z{}={!r}N)format)r=attrZ attributesr;r? sz2InstallRequirement.format_debug..z<{name} object: {{{state}}}>z, )namestate)varssortedrnrjrkjoin)ranamesrsr;rpr? format_debugs zInstallRequirement.format_debugcCsh|jdkr||||_|jdk rd|sd|j}t}|jj|j|j|d|_||jkrdtd|jdS)aEnsure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. If require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. N)rNZ package_namesupported_tagszUsing cached wheel link: %s) rNZfind_requirementrLr Z get_supportedgetrrloggerdebug)rafinderZupgradeZrequire_hashesZold_linkryr;r;r? populate_links  z InstallRequirement.populate_linkcCs |jdkrdStt|jjSN)rCrrZ safe_namerrrlr;r;r?rrs zInstallRequirement.namecCs|jjSr)rC specifierrlr;r;r?rszInstallRequirement.specifiercCs$|j}t|dko"tt|jdkS)zReturn whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. >=====)rlennextiteroperator)raZ specifiersr;r;r? is_pinneds zInstallRequirement.is_pinnedcCs t|jSr)r!rrrlr;r;r?installed_versionsz$InstallRequirement.installed_versioncs0|sd}jdk r(tfdd|DSdSdS)N)c3s|]}jd|iVqdS)r>N)rSZevaluater<rlr;r?rqsz3InstallRequirement.match_markers..T)rSany)raZextras_requestedr;rlr? match_markers s  z InstallRequirement.match_markerscCst|jdiS)zReturn whether any known-good hashes are specified as options. These activate --require-hashes mode; hashes specified as part of a URL do not. hashes)boolrYrzrlr;r;r?has_hash_optionss z#InstallRequirement.has_hash_optionsTcCsJ|jdi}|r|jn|j}|rB|jrB||jg|jt |S)aReturn a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() r) rYrzcopyrNrOhash setdefaultZ hash_nameappendr)raZtrust_internetZ good_hashesrNr;r;r?r#s  zInstallRequirement.hashescCsR|jdkrdSt|j}|jrNt|jtjr4|j}n |j}|rN|d|7}|S)z@Format a nice indicator to show where this "comes from" Nz->)rCrcrDrArrerfrgr;r;r?rf9s    zInstallRequirement.from_pathcCs|dk s t|jdk r*|jjs"t|jjS|jdkrNtdd|_||_|jjS|jr`|j}n|j}t j |st d|t |t j||S)Nz req-buildkindzCreating directory %s)rBrVrHrCr)rWrKrrlowerrGexistsr{r|rrv)ra build_dirrrr;r;r?ensure_build_locationIs        z(InstallRequirement.ensure_build_locationcCs|jdk rdS|jdk st|js&t|jdk r8|jjsCannot update repository at %s; repository location is unknownfile+z bad url: %rr)rMrz+Unexpected version control type (in %s): %s)rNr{r|rFrKrBZschemerMrr,Z get_backendr"obtainZexport)rarZvc_typerMZ vcs_backendZ hidden_urlr;r;r?update_editables.     z"InstallRequirement.update_editablecCsB||std|jdS|jp&|j}t|}||||S)a 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 is linked to global site-packages. z#Skipping %s as it is not installed.N) rr{rrrrTrUrZ from_distremove)raZ auto_confirmverboserZdistZuninstalled_pathsetr;r;r? uninstalls    zInstallRequirement.uninstallcCsJ||tjjs"td||f|t|dd}|tjjd}|S)Nz$name %r doesn't start with prefix %rr/) startswithrGrHrrBrreplace)rarrrr;r;r?_clean_zip_names  z"InstallRequirement._clean_zip_namecCs(tj||}|||}|jd|S)Nr)rGrHrvrrr)rarH parentdirrootdirrrr;r;r?_get_archive_names z$InstallRequirement._get_archive_namec Cs|js td}d|j|jdf}tj||}tj|rtdt |d}|dkr\d}nj|dkrt d t |t |nF|d krt |}t d t |t |t||n|d krtd |sdStj|dtjdd}|tjtj|j}t|D]\} } } d| kr&| d| D]6} |j| | |d} t| d}d|_||dq*| D]>}|tkrxqf|j|| |d}tj| |}|||qfqW5QRXt dt |dS)z}Saves archive to provided build_dir. Used for saving downloaded VCS requirements as part of `pip download`. Tz %s-%s.ziprz8The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)bort )iwbarFrz Deleting %srzBacking up %s to %srN)Z allowZip64z pip-egg-info)rrrirzSaved %s) rFrBrrrrGrHrvrrrr{rrrrrrexitzipfileZZipFileZ ZIP_DEFLATEDnormcaserJrwalkrZZipInfoZ external_attrZwritestrrwriter)rarZcreate_archiveZ archive_nameZ archive_pathZresponseZ dest_fileZ zip_outputdirdirpathZdirnames filenamesdirnameZ dir_arcnameZzipdirfilenameZ file_arcnamer;r;r?archivesz        zInstallRequirement.archivec  sh|dk r |ng}|jr*|j|||ddS|jrnt|j} t| |j|j|j|||||dd|_ dSt ||j dg}t ||j dg}t dd} tj| jd} ||| ||} td |j} t*|j| | ||jd W5QRXW5QRXtj| s8td | W5QRdSd|_ fd d }t| \}|D],}tj|}|drX||}qqXtd|W5QRW5QRdSW5QRXg}t| L}|D]@}|}tj|r|tjj 7}|!tj"|||qW5QRX|#t$|tj|d}t|d}|%d|dW5QRXW5QRXdS)N)r)rrrrrrTrrrecordrzinstall-record.txtzRunning setup.py install for {})cmdrzRecord file %s not foundcs&dkstj|s|St|SdSr)rGrHisabsr)rHrr;r? prepend_rootsz0InstallRequirement.install..prepend_rootrz;Could not find .egg-info directory in install record for %szinstalled-files.txtr )&rKrrr Z wheel_versionrFZcheck_compatibilityrrrrXrrYrzr)rGrHrvget_install_argsr(rnrr[rrr{r|openrrrstripisdirrrrsortr r)rarrrrrrrrrZtemp_dirrecord_filename install_argsrrflineZ directoryZ egg_info_dirZ new_linesrZinst_files_pathr;rr?installEs           "   zInstallRequirement.installc Cst|j||jdd}|dd|g7}|dg7}|dk r@|d|g7}|dk rT|d|g7}|rd|dg7}n |d g7}trd t}|d tjt j d d ||j g7}|S)NT)rrZunbuffered_outputrz--recordz#--single-version-externally-managedz--rootz--prefixz --compilez --no-compilepythonz--install-headersZincludeZsite) r&rrZr+ sysconfigZget_python_versionrGrHrvrrrr)rarrrrrrZ py_ver_strr;r;r?rs0       z#InstallRequirement.get_install_args) NFNNNFNNFr;)N)T)NNNTFT)r;N)T)FFF)NNNNTFT)*rk __module__ __qualname____doc__rbrirmrxr~propertyrrrrrrrrrfrrrrrrrrrrrrrrrrrrrrrrrrr;r;r;r?r:Ms  W      8 +     %     B `r:)eZ __future__rrZloggingrGrrrrZdistutils.utilrZ pip._vendorrrZ"pip._vendor.packaging.requirementsrZpip._vendor.packaging.utilsrZpip._vendor.packaging.versionrr rZpip._vendor.pep517.wrappersr Z pip._internalr r Zpip._internal.build_envr Zpip._internal.exceptionsrZpip._internal.models.linkrZ*pip._internal.operations.generate_metadatarZpip._internal.pyprojectrrZpip._internal.req.req_uninstallrZpip._internal.utils.compatrZpip._internal.utils.hashesrZpip._internal.utils.loggingrZ pip._internal.utils.marker_filesrrZpip._internal.utils.miscrrrrrrrr r!r"r#r$Zpip._internal.utils.packagingr%Z$pip._internal.utils.setuptools_buildr&Zpip._internal.utils.subprocessr'r(Zpip._internal.utils.temp_dirr)Zpip._internal.utils.typingr*Zpip._internal.utils.virtualenvr+Zpip._internal.vcsr,typingr-r.r/r0r1r2r3r4Zpip._internal.cacher5Zpip._internal.indexr6Zpip._vendor.pkg_resourcesr7Z pip._vendor.packaging.specifiersr8Zpip._vendor.packaging.markersr9Z getLoggerrkr{objectr:r;r;r;r?sV               8      $       req/__pycache__/req_uninstall.cpython-38.pyc000064400000042030152347654150015066 0ustar00U .e&\@s|ddlmZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZmZmZddlmZddlmZmZmZmZmZmZmZmZmZdd lm Z m!Z!dd l"m#Z#e#r dd l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/e0e1Z2d dZ3ddZ4e4ddZ5ddZ6ddZ7ddZ8Gddde9Z:Gddde9Z;Gddde9Z.unique) functoolswraps)r3r4r(r2r)_unique=sr7ccstt|d}|D]t}tj|j|d}|V|drtj |\}}|dd}tj||d}|Vtj||d}|VqdS)a Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. ZRECORDr.pyN.pyc.pyo) csvreaderr Zget_metadata_linesr!r"r#locationendswithsplit)r%rrowr"Zdnr3baser(r(r)uninstallation_pathsJs   rDcsJtjjt}t|tdD]*tfdd|D}|s|q|S)zCompact 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.keyc3s:|]2}|do0t|dkVqdS)*N) startswithrstriplen).0Z shortpathr"sepr(r) lszcompact..)r!r"rMr,sortedrJanyr-)pathsZ short_pathsZ should_skipr(rLr)compactbs rRc stdd|D}t|}ttdd|Dtd}t}dd|D]tfdd|DrfqJt}t}tD]B\}}|fdd|D|fd d|Dq|||sJ| || tj qJtt |j ||BS) zReturns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. css|]}tj||fVqdSr+)r!r"normcaserKpr(r(r)rN}sz&compress_for_rename..css|]}tj|dVqdS)rN)r!r"r@rTr(r(r)rNsrEcWstjtjj|Sr+)r!r"rSr#)ar(r(r) norm_joinsz&compress_for_rename..norm_joinc3s |]}tj|VqdSr+)r!r"rSrH)rKw)rootr(r)rNsc3s|]}|VqdSr+r()rKddirnamerWrYr(r)rNsc3s|]}|VqdSr+r()rKfr[r(r)rNs)dictr,rOvaluesrJrPr!walkupdatedifference_updater-rMmap __getitem__) rQZcase_mapZ remainingZ uncheckedZ wildcardsZ all_filesZ all_subdirsZsubdirsfilesr(r[r)compress_for_renamevs6    rfc Cst|}t}t}t}|D]>}|dr.q|ds@d|krR|tj|||qtttjj|}t|}|D]d}t |D]T\}} } | D]D} | drqtj || } tj | rtj| |kr|| qqq||dd|DB}||fS)asReturns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. r:z __init__.py .dist-infocSsh|]}tj|dqS)rG)r!r"r#)rKfolderr(r(r) sz.compress_for_output_listing..) r,r?r-r!r"r\rcrSrRr`r#isfile) rQ will_remove will_skipZfoldersrer"Z_normcased_filesrhdirpath_ZdirfilesZfnameZfile_r(r(r)compress_for_output_listings4     roc@sLeZdZdZddZddZddZdd Zd d Zd d Z e ddZ dS)StashedUninstallPathSetzWA set of file rename operations to stash files while tentatively uninstalling them.cCsi|_g|_dSr+) _save_dirs_movesselfr(r(r)__init__sz StashedUninstallPathSet.__init__cCsDz t|}Wntk r*tdd}YnX||jtj|<|jS)zStashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir. uninstallZkind)rOSErrorrrqr!r"rS)rtr"save_dirr(r(r)_get_directory_stashs  z,StashedUninstallPathSet._get_directory_stashcCstj|}tj|d}}d}||krfz|j|}WqWntk rPYnXtj||}}q"tj|}tdd}||j|<tj||}|r|tjjkrtj |j|S|jS)zStashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.Nrvrw) r!r"rSr\rqKeyErrorrrelpathcurdirr#)rtr"headZold_headryr|r(r(r)_get_file_stashs"     z'StashedUninstallPathSet._get_file_stashcCsltj|otj| }|r*||}n ||}|j||f|r^tj|r^t|t |||S)zStashes the directory or file and returns its new location. Handle symlinks as files to avoid modifying the symlink targets. ) r!r"isdirislinkrzrrrr$rmdirr)rtr"Z path_is_dirnew_pathr(r(r)stashs    zStashedUninstallPathSet.stashcCs,|jD]\}}|q g|_i|_dS)z0Commits the uninstall by removing stashed files.N)rqitemsZcleanuprr)rtrnryr(r(r)commits zStashedUninstallPathSet.commitc Cs|jD]}tjd|q|jD]\}}zTtd||tj|sPtj|r\t |ntj |rpt |t ||Wq t k r}ztd|td|W5d}~XYq Xq |dS)z2Undoes the uninstall by moving stashed files back.Moving to %s from %szReplacing %s from %szFailed to restore %sz Exception: %sN)r)rrlogginginfologgerdebugr!r"rjrunlinkrrrrxerrorr)rtrUrr"Zexr(r(r)rollback&s     z StashedUninstallPathSet.rollbackcCs t|jSr+)boolrrrsr(r(r) can_rollback:sz$StashedUninstallPathSet.can_rollbackN) __name__ __module__ __qualname____doc__rurzrrrrpropertyrr(r(r(r)rps rpc@s^eZdZdZddZddZddZdd Zdd d Zd dZ ddZ ddZ e ddZ dS)UninstallPathSetzMA set of file paths to be removed in the uninstallation of a requirement.cCs(t|_t|_i|_||_t|_dSr+)r,rQ_refusepthr%rp _moved_paths)rtr%r(r(r)ruCs zUninstallPathSet.__init__cCst|S)zs Return True if the given path is one we are permitted to remove/modify, False otherwise. )r)rtr"r(r(r) _permittedKszUninstallPathSet._permittedcCstj|\}}tjt|tj|}tj|s:dS||rR|j |n |j |tj |ddkrt r| t |dS)Nr8)r!r"r@r#rrSexistsrrQr-rsplitextr r)rtr"r~tailr(r(r)r-Ts   zUninstallPathSet.addcCsLt|}||r<||jkr*t||j|<|j||n |j|dSr+)rrrUninstallPthEntriesr-r)rtpth_fileentryr(r(r)add_pthhs   zUninstallPathSet.add_pthFc Cs|jstd|jjdS|jjd|jj}td|tp|sP||r|j}t |j}t t |D]}| |t d|ql|jD] }|qtd|W5QRXdS)z[Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).z7Can't uninstall '%s'. No files were found to uninstall.N-zUninstalling %s:zRemoving file or directory %szSuccessfully uninstalled %s)rQrrr% project_nameversionr _allowed_to_proceedrrfrOrRrrrr_remove)rtZ auto_confirmverboseZdist_name_versionZmovedZ for_renamer"rr(r(r)rrs&    zUninstallPathSet.removecCsndd}|st|j\}}nt|j}t}|d||d||d|j|r`|dt|jtddd kS) zIDisplay which files would be deleted and prompt for confirmation c SsD|sdSt|t"tt|D]}t|q&W5QRXdSr+)rrr rOrR)msgrQr"r(r(r)_displays  z6UninstallPathSet._allowed_to_proceed.._displayz Would remove:z+Would not remove (might be manually added):z%Would not remove (outside of prefix):zWill actually move:zProceed (y/n)? )ynr)rorQr,rrfr )rtrrrkrlr(r(r)rs     z$UninstallPathSet._allowed_to_proceedcCsR|jjstd|jjdStd|jj|j|j D] }|q@dS)z1Rollback the changes previously made by remove().z'Can't roll back %s; was not uninstalledNzRolling back uninstall of %s) rrrrr%rrrrr_)rtrr(r(r)rs zUninstallPathSet.rollbackcCs|jdS)z?Remove temporary save dir: rollback will no longer be possible.N)rrrsr(r(r)rszUninstallPathSet.commitc st|j}t|s.td|j|tj||S|ddt dt dhDkrhtd|j|||S||}t |}d t |j}|jotj|j}t|jdd}|r|jd r|j|s||j|d r|d D]&}tjtj|j|} || qn|d r|d rB|d ngfd d|d DD]J} tj|j| } || || d|| d|| dqbn2|rtd |jn|jdr"||jtj|jd} tjtj|jd} || d| n|rR|jdrRt |D]} || q>n|rt!|d} tj"| #$}W5QRX||jkst%d||j|jf||tjtj|d} || |jnt&d||j|drT|'drT|(dD]L}t)|rt*}nt+}|tj||t,r|tj||dqg}|j-dd}|.D]}|/t0||dql|j-d d}|.D]}|/t0||d!q|D]}||q|S)"Nz1Not uninstalling %s at %s, outside environment %scSsh|] }|r|qSr(r(rTr(r(r)risz-UninstallPathSet.from_dist..ZstdlibZ platstdlibzsz.UninstallPathSet.from_dist..r8r:r;zCannot uninstall {!r}. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.z.eggrzeasy-install.pthz./rgrAz;Egg-link %s does not match installed location of %s (at %s)z)Not sure how to uninstall: %s - Check: %sZscriptsz.batconsole_scripts)groupF gui_scriptsT)1rr>rrrrFsysprefix sysconfigZget_pathrformatrZ to_filenamerZegg_infor!r"rgetattrZ _providerr?r-Z has_metadataZ get_metadata splitlinesnormpathr#rr@r\rrDopenrSreadlinestripAssertionErrorrZmetadata_isdirZmetadata_listdirr rrrZ get_entry_mapkeysextendr*)clsr%Z dist_pathr'Zdevelop_egg_linkZdevelop_egg_link_egg_infoZegg_info_existsZdistutils_egg_infoZinstalled_filer"Z top_level_pkgZeasy_install_eggZeasy_install_pthfhZ link_pointerZscriptr&Z_scripts_to_removernamersr(rr) from_dists                       zUninstallPathSet.from_distN)FF)rrrrrurr-rrrrr classmethodrr(r(r(r)r@s  rc@s,eZdZddZddZddZddZd S) rcCs0tj|std|||_t|_d|_dS)Nz.Cannot remove entries from nonexistent file %s)r!r"rjrfiler,entries _saved_lines)rtrr(r(r)ruIs zUninstallPthEntries.__init__cCs<tj|}tr,tj|ds,|dd}|j|dS)Nr\/)r!r"rSr splitdrivereplacerr-)rtrr(r(r)r-Ss  zUninstallPthEntries.addc Cstd|jt|jd}|}||_W5QRXtdd|DrLd}nd}|r~|d|ds~|d|d|d<|j D]>}z$td || ||dWqt k rYqXqt|jd }| |W5QRXdS) NzRemoving pth entries from %s:rbcss|]}d|kVqdS)s Nr()rKliner(r(r)rNjsz-UninstallPthEntries.remove..z  zutf-8zRemoving entry: %swb) rrrr readlinesrrPr?encoderr ValueError writelines)rtrlinesZendlinerr(r(r)rcs"  zUninstallPthEntries.removec CsR|jdkrtd|jdStd|jt|jd}||jW5QRXdS)Nz.Cannot roll back changes to %s, none were madeFz!Rolling %s back to previous staterT)rrrrrrr)rtrr(r(r)rzs zUninstallPthEntries.rollbackN)rrrrur-rrr(r(r(r)rHs r)=Z __future__rr<r5rr!rrZ pip._vendorrZpip._internal.exceptionsrZpip._internal.locationsrrZpip._internal.utils.compatrrr Zpip._internal.utils.loggingr Zpip._internal.utils.miscr r r rrrrrrZpip._internal.utils.temp_dirrrZpip._internal.utils.typingrtypingrrrrrrrrrZpip._vendor.pkg_resourcesr Z getLoggerrrr*r7rDrRrfroobjectrprrr(r(r(r)s<    ,  ,    (3o req/__pycache__/req_tracker.cpython-38.opt-1.pyc000064400000006145152347654150015456 0ustar00U .e{ @sddlmZddlZddlZddlZddlZddlZddlmZddl m Z e rddl m Z ddl mZmZmZmZddlmZddlmZeeZGd d d eZdS) )absolute_importN) TempDirectory)MYPY_CHECK_RUNNING) TracebackType)IteratorOptionalSetType)InstallRequirement)Linkc@sReZdZddZddZddZddZd d Zd d Zd dZ e j ddZ dS)RequirementTrackercCsjtjd|_|jdkrJtddd|_|jj|_tjd<td|jnd|_td|jt |_ dS)NZPIP_REQ_TRACKERFz req-tracker)deleteZkindzCreated requirements tracker %rz Re-using requirements tracker %r) osenvironget_rootr _temp_dirpathloggerdebugset_entriesselfrA/usr/lib/python3.8/site-packages/pip/_internal/req/req_tracker.py__init__s zRequirementTracker.__init__cCs|SNrrrrr __enter__&szRequirementTracker.__enter__cCs |dSr)cleanup)rexc_typeZexc_valZexc_tbrrr__exit__*szRequirementTracker.__exit__cCs$t|j}tj|j|Sr) hashlibZsha224Zurl_without_fragmentencodeZ hexdigestrrjoinr)rlinkZhashedrrr _entry_path3szRequirementTracker._entry_pathc Cs|j}t|}||}z,t|}td||fW5QRXWnltk r}zN|jtjkrdt|d}| |W5QRX|j |t d||jW5d}~XYnXdS)Nz%s is already being built: %swzAdded %s to build tracker %r)r%strr&open LookupErrorreadIOErrorerrnoZENOENTwriteraddrrr)rreqr%infoZ entry_pathfperrrr/8s      zRequirementTracker.addcCs6|j}|j|t||td||jdS)Nz Removed %s from build tracker %r) r%rremoverunlinkr&rrr)rr0r%rrrr4Ks zRequirementTracker.removecCsNt|jD]}||q |jdk }|r2|jtd|r@dnd|jdS)Nz%s build tracker %rZRemovedZCleaned)rrr4rrrrr)rr0r4rrrrRs    zRequirementTracker.cleanupccs||dV||dSr)r/r4)rr0rrrtrack]s zRequirementTracker.trackN) __name__ __module__ __qualname__rrr!r&r/r4r contextlibcontextmanagerr6rrrrr s   r )Z __future__rr:r-r"ZloggingrZpip._internal.utils.temp_dirrZpip._internal.utils.typingrtypesrtypingrrrr Zpip._internal.req.req_installr Zpip._internal.models.linkr Z getLoggerr7robjectr rrrrs       req/__pycache__/req_set.cpython-38.opt-1.pyc000064400000013347152347654150014620 0ustar00U .e@sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZerdd lmZmZmZmZmZdd lmZeeZGd d d eZdS))absolute_importN) OrderedDict)canonicalize_name) pep425tags)InstallationError) indent_log)MYPY_CHECK_RUNNING)Wheel)DictIterableListOptionalTuple)InstallRequirementc@sXeZdZdddZddZddZd d Zd d ZdddZddZ ddZ ddZ d S)RequirementSetFTcCs*t|_||_||_g|_g|_g|_dS)z!Create a RequirementSet. N)r requirementsrequire_hashescheck_supported_wheelsunnamed_requirementsZsuccessfully_downloadedreqs_to_cleanup)selfrrr=/usr/lib/python3.8/site-packages/pip/_internal/req/req_set.py__init__s zRequirementSet.__init__cCs4tdd|jDddd}ddd|DS)Ncss|]}|js|VqdSN)Z comes_from.0reqrrr +sz)RequirementSet.__str__..cSs t|jSrrnamerrrr,z(RequirementSet.__str__..key css|]}t|jVqdSrstrrrrrrr.s)sortedrvaluesjoin)rrrrr__str__(s zRequirementSet.__str__cCsBt|jddd}d}|j|jjt|ddd|DdS) NcSs t|jSrrr!rrrr"4r#z)RequirementSet.__repr__..r$z4<{classname} object; {count} requirement(s): {reqs}>z, css|]}t|jVqdSrr'rrrrr;sz*RequirementSet.__repr__..)Z classnamecountZreqs)r)rr*format __class____name__lenr+)rr format_stringrrr__repr__0szRequirementSet.__repr__cCs|j|dSr)rappend)r install_reqrrradd_unnamed_requirement>sz&RequirementSet.add_unnamed_requirementcCst|j}||j|<dSr)rr r)rr5 project_namerrradd_named_requirementCs z$RequirementSet.add_named_requirementNc Cs||s$td|j|jgdfS|jrd|jjrdt|jj}t }|j rd| |sdt d|j|js~|||gdfSz||j}Wntk rd}YnX|dko|o|j o|j|jko|jj|jjk}|rt d|||jf|s |||g|fS|js|js"g|fS|joB|jo@|jj|jjk }|rd|j|t d|jd|_ttt|jt|jB|_td||j|g|fS)a&Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environment markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. z6Ignoring %s: markers '%s' don't match your environmentNz-%s is not a supported wheel on this platform.z5Double requirement given: %s (already in %s, name=%r)zhCould not satisfy constraints for '%s': installation from path or url cannot be constrained to a versionFzSetting %s extras to: %s)Z match_markersloggerinfor ZmarkerslinkZis_wheelr filenamerZ get_supportedrZ supportedrr6get_requirementKeyError constraintZextrasrZ specifierr8pathrr4tupler)setdebug) rr5Zparent_req_nameZextras_requestedZwheelZtagsZ existing_reqZhas_conflicting_requirementZdoes_not_satisfy_constraintrrradd_requirementJs           zRequirementSet.add_requirementcCs t|}||jko|j|j Sr)rrr?rr r7rrrhas_requirements  zRequirementSet.has_requirementcCs,t|}||jkr|j|Std|dS)NzNo project with the name %r)rrr>rErrrr=s  zRequirementSet.get_requirementc Cs4tdt|jD] }|qW5QRXdS)zClean up files, remove builds.zCleaning up...N)r9rCrrZremove_temporary_source)rrrrr cleanup_filess  zRequirementSet.cleanup_files)FT)NN) r0 __module__ __qualname__rr,r3r6r8rDrFr=rGrrrrrs   p  r)Z __future__rZlogging collectionsrZpip._vendor.packaging.utilsrZ pip._internalrZpip._internal.exceptionsrZpip._internal.utils.loggingrZpip._internal.utils.typingrZpip._internal.wheelr typingr r r r rZpip._internal.req.req_installrZ getLoggerr0r9objectrrrrrs          req/__pycache__/__init__.cpython-38.opt-1.pyc000064400000003244152347654150014710 0ustar00U .e @sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z erhdd l mZmZmZd d d d gZeeZddd ZdS))absolute_importN) indent_log)MYPY_CHECK_RUNNING)parse_requirements)InstallRequirement)RequirementSet)AnyListSequencerrrinstall_given_reqsc Os|r tdddd|Dt|D]}|jrbtd|jt|jdd}W5QRXz|j||f||Wn0tk r|jo|j }|r| YnX|jo|j}|r| | q,W5QRX|S)zu Install everything in the given list. (to be called after having downloaded and unpacked the packages) z!Installing collected packages: %sz, cSsg|] }|jqSr )name).0Zreqr r >/usr/lib/python3.8/site-packages/pip/_internal/req/__init__.py +sz&install_given_reqs..zFound existing installation: %sT)Z auto_confirm) loggerinfojoinrZconflicts_withZ uninstallZinstall ExceptionZinstall_succeededZrollbackZcommitZremove_temporary_source) Z to_installZinstall_optionsZglobal_optionsargskwargsZ requirementZuninstalled_pathsetZshould_rollbackZ should_commitr r rr sN)r )Z __future__rZloggingZpip._internal.utils.loggingrZpip._internal.utils.typingrZreq_filerZ req_installrZreq_setrtypingr r r __all__Z getLogger__name__rr r r r rs       req/req_tracker.py000064400000011122152347654150010220 0ustar00from __future__ import absolute_import import contextlib import errno import hashlib import logging import os from pip._vendor import contextlib2 from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from types import TracebackType from typing import Dict, Iterator, Optional, Set, Type, Union from pip._internal.req.req_install import InstallRequirement from pip._internal.models.link import Link logger = logging.getLogger(__name__) @contextlib.contextmanager def update_env_context_manager(**changes): # type: (str) -> Iterator[None] target = os.environ # Save values from the target and change them. non_existent_marker = object() saved_values = {} # type: Dict[str, Union[object, str]] for name, new_value in changes.items(): try: saved_values[name] = target[name] except KeyError: saved_values[name] = non_existent_marker target[name] = new_value try: yield finally: # Restore original values in the target. for name, original_value in saved_values.items(): if original_value is non_existent_marker: del target[name] else: assert isinstance(original_value, str) # for mypy target[name] = original_value @contextlib.contextmanager def get_requirement_tracker(): # type: () -> Iterator[RequirementTracker] root = os.environ.get('PIP_REQ_TRACKER') with contextlib2.ExitStack() as ctx: if root is None: root = ctx.enter_context( TempDirectory(kind='req-tracker') ).path ctx.enter_context(update_env_context_manager(PIP_REQ_TRACKER=root)) logger.debug("Initialized build tracking at %s", root) with RequirementTracker(root) as tracker: yield tracker class RequirementTracker(object): def __init__(self, root): # type: (str) -> None self._root = root self._entries = set() # type: Set[InstallRequirement] logger.debug("Created build tracker: %s", self._root) def __enter__(self): # type: () -> RequirementTracker logger.debug("Entered build tracker: %s", self._root) return self def __exit__( self, exc_type, # type: Optional[Type[BaseException]] exc_val, # type: Optional[BaseException] exc_tb # type: Optional[TracebackType] ): # type: (...) -> None self.cleanup() def _entry_path(self, link): # type: (Link) -> str hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed) def add(self, req): # type: (InstallRequirement) -> None """Add an InstallRequirement to build tracking. """ assert req.link # Get the file to write information about this requirement. entry_path = self._entry_path(req.link) # Try reading from the file. If it exists and can be read from, a build # is already in progress, so a LookupError is raised. try: with open(entry_path) as fp: contents = fp.read() except IOError as e: # if the error is anything other than "file does not exist", raise. if e.errno != errno.ENOENT: raise else: message = '{} is already being built: {}'.format( req.link, contents) raise LookupError(message) # If we're here, req should really not be building already. assert req not in self._entries # Start tracking this requirement. with open(entry_path, 'w') as fp: fp.write(str(req)) self._entries.add(req) logger.debug('Added %s to build tracker %r', req, self._root) def remove(self, req): # type: (InstallRequirement) -> None """Remove an InstallRequirement from build tracking. """ assert req.link # Delete the created file and the corresponding entries. os.unlink(self._entry_path(req.link)) self._entries.remove(req) logger.debug('Removed %s from build tracker %r', req, self._root) def cleanup(self): # type: () -> None for req in set(self._entries): self.remove(req) logger.debug("Removed build tracker: %r", self._root) @contextlib.contextmanager def track(self, req): # type: (InstallRequirement) -> Iterator[None] self.add(req) yield self.remove(req) req/req_uninstall.py000064400000056232152347654150010611 0ustar00from __future__ import absolute_import import csv import functools import logging import os import sys import sysconfig from pip._vendor import pkg_resources from pip._internal.exceptions import UninstallationError from pip._internal.locations import bin_py, bin_user from pip._internal.utils.compat import WINDOWS, cache_from_source, uses_pycache from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( FakeFile, ask, dist_in_usersite, dist_is_local, egg_link_path, is_local, normalize_path, renames, rmtree, ) from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Any, Callable, Dict, Iterable, Iterator, List, Optional, Set, Tuple, ) from pip._vendor.pkg_resources import Distribution logger = logging.getLogger(__name__) def _script_names(dist, script_name, is_gui): # type: (Distribution, str, bool) -> List[str] """Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names """ if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py exe_name = os.path.join(bin_dir, script_name) paths_to_remove = [exe_name] if WINDOWS: paths_to_remove.append(exe_name + '.exe') paths_to_remove.append(exe_name + '.exe.manifest') if is_gui: paths_to_remove.append(exe_name + '-script.pyw') else: paths_to_remove.append(exe_name + '-script.py') return paths_to_remove def _unique(fn): # type: (Callable[..., Iterator[Any]]) -> Callable[..., Iterator[Any]] @functools.wraps(fn) def unique(*args, **kw): # type: (Any, Any) -> Iterator[Any] seen = set() # type: Set[Any] for item in fn(*args, **kw): if item not in seen: seen.add(item) yield item return unique @_unique def uninstallation_paths(dist): # type: (Distribution) -> Iterator[str] """ Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. """ r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path path = os.path.join(dn, base + '.pyo') yield path def compact(paths): # type: (Iterable[str]) -> Set[str] """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.""" sep = os.path.sep short_paths = set() # type: Set[str] for path in sorted(paths, key=len): should_skip = any( path.startswith(shortpath.rstrip("*")) and path[len(shortpath.rstrip("*").rstrip(sep))] == sep for shortpath in short_paths ) if not should_skip: short_paths.add(path) return short_paths def compress_for_rename(paths): # type: (Iterable[str]) -> Set[str] """Returns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. """ case_map = dict((os.path.normcase(p), p) for p in paths) remaining = set(case_map) unchecked = sorted(set(os.path.split(p)[0] for p in case_map.values()), key=len) wildcards = set() # type: Set[str] def norm_join(*a): # type: (str) -> str return os.path.normcase(os.path.join(*a)) for root in unchecked: if any(os.path.normcase(root).startswith(w) for w in wildcards): # This directory has already been handled. continue all_files = set() # type: Set[str] all_subdirs = set() # type: Set[str] for dirname, subdirs, files in os.walk(root): all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) all_files.update(norm_join(root, dirname, f) for f in files) # If all the files we found are in our remaining set of files to # remove, then remove them from the latter set and add a wildcard # for the directory. if not (all_files - remaining): remaining.difference_update(all_files) wildcards.add(root + os.sep) return set(map(case_map.__getitem__, remaining)) | wildcards def compress_for_output_listing(paths): # type: (Iterable[str]) -> Tuple[Set[str], Set[str]] """Returns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. """ will_remove = set(paths) will_skip = set() # Determine folders and files folders = set() files = set() for path in will_remove: if path.endswith(".pyc"): continue if path.endswith("__init__.py") or ".dist-info" in path: folders.add(os.path.dirname(path)) files.add(path) # probably this one https://github.com/python/mypy/issues/390 _normcased_files = set(map(os.path.normcase, files)) # type: ignore folders = compact(folders) # This walks the tree using os.walk to not miss extra folders # that might get added. for folder in folders: for dirpath, _, dirfiles in os.walk(folder): for fname in dirfiles: if fname.endswith(".pyc"): continue file_ = os.path.join(dirpath, fname) if (os.path.isfile(file_) and os.path.normcase(file_) not in _normcased_files): # We are skipping this file. Add it to the set. will_skip.add(file_) will_remove = files | { os.path.join(folder, "*") for folder in folders } return will_remove, will_skip class StashedUninstallPathSet(object): """A set of file rename operations to stash files while tentatively uninstalling them.""" def __init__(self): # type: () -> None # Mapping from source file root to [Adjacent]TempDirectory # for files under that directory. self._save_dirs = {} # type: Dict[str, TempDirectory] # (old path, new path) tuples for each move that may need # to be undone. self._moves = [] # type: List[Tuple[str, str]] def _get_directory_stash(self, path): # type: (str) -> str """Stashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir.""" try: save_dir = AdjacentTempDirectory(path) # type: TempDirectory except OSError: save_dir = TempDirectory(kind="uninstall") self._save_dirs[os.path.normcase(path)] = save_dir return save_dir.path def _get_file_stash(self, path): # type: (str) -> str """Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.""" path = os.path.normcase(path) head, old_head = os.path.dirname(path), None save_dir = None while head != old_head: try: save_dir = self._save_dirs[head] break except KeyError: pass head, old_head = os.path.dirname(head), head else: # Did not find any suitable root head = os.path.dirname(path) save_dir = TempDirectory(kind='uninstall') self._save_dirs[head] = save_dir relpath = os.path.relpath(path, head) if relpath and relpath != os.path.curdir: return os.path.join(save_dir.path, relpath) return save_dir.path def stash(self, path): # type: (str) -> str """Stashes the directory or file and returns its new location. Handle symlinks as files to avoid modifying the symlink targets. """ path_is_dir = os.path.isdir(path) and not os.path.islink(path) if path_is_dir: new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if (path_is_dir and os.path.isdir(new_path)): # If we're moving a directory, we need to # remove the destination first or else it will be # moved to inside the existing directory. # We just created new_path ourselves, so it will # be removable. os.rmdir(new_path) renames(path, new_path) return new_path def commit(self): # type: () -> None """Commits the uninstall by removing stashed files.""" for _, save_dir in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {} def rollback(self): # type: () -> None """Undoes the uninstall by moving stashed files back.""" for p in self._moves: logger.info("Moving to %s\n from %s", *p) for new_path, path in self._moves: try: logger.debug('Replacing %s from %s', new_path, path) if os.path.isfile(new_path) or os.path.islink(new_path): os.unlink(new_path) elif os.path.isdir(new_path): rmtree(new_path) renames(path, new_path) except OSError as ex: logger.error("Failed to restore %s", new_path) logger.debug("Exception: %s", ex) self.commit() @property def can_rollback(self): # type: () -> bool return bool(self._moves) class UninstallPathSet(object): """A set of file paths to be removed in the uninstallation of a requirement.""" def __init__(self, dist): # type: (Distribution) -> None self.paths = set() # type: Set[str] self._refuse = set() # type: Set[str] self.pth = {} # type: Dict[str, UninstallPthEntries] self.dist = dist self._moved_paths = StashedUninstallPathSet() def _permitted(self, path): # type: (str) -> bool """ Return True if the given path is one we are permitted to remove/modify, False otherwise. """ return is_local(path) def add(self, path): # type: (str) -> None head, tail = os.path.split(path) # we normalize the head to resolve parent directory symlinks, but not # the tail, since we only want to uninstall symlinks, not their targets path = os.path.join(normalize_path(head), os.path.normcase(tail)) if not os.path.exists(path): return if self._permitted(path): self.paths.add(path) else: self._refuse.add(path) # __pycache__ files can show up after 'installed-files.txt' is created, # due to imports if os.path.splitext(path)[1] == '.py' and uses_pycache: self.add(cache_from_source(path)) def add_pth(self, pth_file, entry): # type: (str, str) -> None pth_file = normalize_path(pth_file) if self._permitted(pth_file): if pth_file not in self.pth: self.pth[pth_file] = UninstallPthEntries(pth_file) self.pth[pth_file].add(entry) else: self._refuse.add(pth_file) def remove(self, auto_confirm=False, verbose=False): # type: (bool, bool) -> None """Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).""" if not self.paths: logger.info( "Can't uninstall '%s'. No files were found to uninstall.", self.dist.project_name, ) return dist_name_version = ( self.dist.project_name + "-" + self.dist.version ) logger.info('Uninstalling %s:', dist_name_version) with indent_log(): if auto_confirm or self._allowed_to_proceed(verbose): moved = self._moved_paths for_rename = compress_for_rename(self.paths) for path in sorted(compact(for_rename)): moved.stash(path) logger.debug('Removing file or directory %s', path) for pth in self.pth.values(): pth.remove() logger.info('Successfully uninstalled %s', dist_name_version) def _allowed_to_proceed(self, verbose): # type: (bool) -> bool """Display which files would be deleted and prompt for confirmation """ def _display(msg, paths): # type: (str, Iterable[str]) -> None if not paths: return logger.info(msg) with indent_log(): for path in sorted(compact(paths)): logger.info(path) if not verbose: will_remove, will_skip = compress_for_output_listing(self.paths) else: # In verbose mode, display all the files that are going to be # deleted. will_remove = set(self.paths) will_skip = set() _display('Would remove:', will_remove) _display('Would not remove (might be manually added):', will_skip) _display('Would not remove (outside of prefix):', self._refuse) if verbose: _display('Will actually move:', compress_for_rename(self.paths)) return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' def rollback(self): # type: () -> None """Rollback the changes previously made by remove().""" if not self._moved_paths.can_rollback: logger.error( "Can't roll back %s; was not uninstalled", self.dist.project_name, ) return logger.info('Rolling back uninstall of %s', self.dist.project_name) self._moved_paths.rollback() for pth in self.pth.values(): pth.rollback() def commit(self): # type: () -> None """Remove temporary save dir: rollback will no longer be possible.""" self._moved_paths.commit() @classmethod def from_dist(cls, dist): # type: (Distribution) -> UninstallPathSet dist_path = normalize_path(dist.location) if not dist_is_local(dist): logger.info( "Not uninstalling %s at %s, outside environment %s", dist.key, dist_path, sys.prefix, ) return cls(dist) if dist_path in {p for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")} if p}: logger.info( "Not uninstalling %s at %s, as it is in the standard library.", dist.key, dist_path, ) return cls(dist) paths_to_remove = cls(dist) develop_egg_link = egg_link_path(dist) develop_egg_link_egg_info = '{}.egg-info'.format( pkg_resources.to_filename(dist.project_name)) egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info) # Special case for distutils installed package distutils_egg_info = getattr(dist._provider, 'path', None) # Uninstall cases order do matter as in the case of 2 installs of the # same package, pip needs to uninstall the currently detected version if (egg_info_exists and dist.egg_info.endswith('.egg-info') and not dist.egg_info.endswith(develop_egg_link_egg_info)): # if dist.egg_info.endswith(develop_egg_link_egg_info), we # are in fact in the develop_egg_link case paths_to_remove.add(dist.egg_info) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata( 'installed-files.txt').splitlines(): path = os.path.normpath( os.path.join(dist.egg_info, installed_file) ) paths_to_remove.add(path) # FIXME: need a test for this elif block # occurs with --single-version-externally-managed/--record outside # of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [ p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') paths_to_remove.add(path + '.pyo') elif distutils_egg_info: raise UninstallationError( "Cannot uninstall {!r}. It is a distutils installed project " "and thus we cannot accurately determine which files belong " "to it which would lead to only a partial uninstall.".format( dist.project_name, ) ) elif dist.location.endswith('.egg'): # package installed by easy_install # We cannot match on dist.egg_name because it can slightly vary # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg paths_to_remove.add(dist.location) easy_install_egg = os.path.split(dist.location)[1] easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif egg_info_exists and dist.egg_info.endswith('.dist-info'): for path in uninstallation_paths(dist): paths_to_remove.add(path) elif develop_egg_link: # develop egg with open(develop_egg_link, 'r') as fh: link_pointer = os.path.normcase(fh.readline().strip()) assert (link_pointer == dist.location), ( 'Egg-link {} does not match installed location of {} ' '(at {})'.format( link_pointer, dist.project_name, dist.location) ) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) else: logger.debug( 'Not sure how to uninstall: %s - Check: %s', dist, dist.location, ) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, script)) if WINDOWS: paths_to_remove.add(os.path.join(bin_dir, script) + '.bat') # find console_scripts _scripts_to_remove = [] console_scripts = dist.get_entry_map(group='console_scripts') for name in console_scripts.keys(): _scripts_to_remove.extend(_script_names(dist, name, False)) # find gui_scripts gui_scripts = dist.get_entry_map(group='gui_scripts') for name in gui_scripts.keys(): _scripts_to_remove.extend(_script_names(dist, name, True)) for s in _scripts_to_remove: paths_to_remove.add(s) return paths_to_remove class UninstallPthEntries(object): def __init__(self, pth_file): # type: (str) -> None self.file = pth_file self.entries = set() # type: Set[str] self._saved_lines = None # type: Optional[List[bytes]] def add(self, entry): # type: (str) -> None entry = os.path.normcase(entry) # On Windows, os.path.normcase converts the entry to use # backslashes. This is correct for entries that describe absolute # paths outside of site-packages, but all the others use forward # slashes. # os.path.splitdrive is used instead of os.path.isabs because isabs # treats non-absolute paths with drive letter markings like c:foo\bar # as absolute paths. It also does not recognize UNC paths if they don't # have more than "\\sever\share". Valid examples: "\\server\share\" or # "\\server\share\folder". Python 2.7.8+ support UNC in splitdrive. if WINDOWS and not os.path.splitdrive(entry)[0]: entry = entry.replace('\\', '/') self.entries.add(entry) def remove(self): # type: () -> None logger.debug('Removing pth entries from %s:', self.file) # If the file doesn't exist, log a warning and return if not os.path.isfile(self.file): logger.warning( "Cannot remove entries from nonexistent file %s", self.file ) return with open(self.file, 'rb') as fh: # windows uses '\r\n' with py3k, but uses '\n' with py2.x lines = fh.readlines() self._saved_lines = lines if any(b'\r\n' in line for line in lines): endline = '\r\n' else: endline = '\n' # handle missing trailing newline if lines and not lines[-1].endswith(endline.encode("utf-8")): lines[-1] = lines[-1] + endline.encode("utf-8") for entry in self.entries: try: logger.debug('Removing entry: %s', entry) lines.remove((entry + endline).encode("utf-8")) except ValueError: pass with open(self.file, 'wb') as fh: fh.writelines(lines) def rollback(self): # type: () -> bool if self._saved_lines is None: logger.error( 'Cannot roll back changes to %s, none were made', self.file ) return False logger.debug('Rolling %s back to previous state', self.file) with open(self.file, 'wb') as fh: fh.writelines(self._saved_lines) return True req/req_set.py000064400000017316152347654150007373 0ustar00from __future__ import absolute_import import logging from collections import OrderedDict from pip._vendor.packaging.utils import canonicalize_name from pip._internal.exceptions import InstallationError from pip._internal.models.wheel import Wheel from pip._internal.utils import compatibility_tags from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict, Iterable, List, Optional, Tuple from pip._internal.req.req_install import InstallRequirement logger = logging.getLogger(__name__) class RequirementSet(object): def __init__(self, check_supported_wheels=True): # type: (bool) -> None """Create a RequirementSet. """ self.requirements = OrderedDict() # type: Dict[str, InstallRequirement] # noqa: E501 self.check_supported_wheels = check_supported_wheels self.unnamed_requirements = [] # type: List[InstallRequirement] def __str__(self): # type: () -> str requirements = sorted( (req for req in self.requirements.values() if not req.comes_from), key=lambda req: canonicalize_name(req.name), ) return ' '.join(str(req.req) for req in requirements) def __repr__(self): # type: () -> str requirements = sorted( self.requirements.values(), key=lambda req: canonicalize_name(req.name), ) format_string = '<{classname} object; {count} requirement(s): {reqs}>' return format_string.format( classname=self.__class__.__name__, count=len(requirements), reqs=', '.join(str(req.req) for req in requirements), ) def add_unnamed_requirement(self, install_req): # type: (InstallRequirement) -> None assert not install_req.name self.unnamed_requirements.append(install_req) def add_named_requirement(self, install_req): # type: (InstallRequirement) -> None assert install_req.name project_name = canonicalize_name(install_req.name) self.requirements[project_name] = install_req def add_requirement( self, install_req, # type: InstallRequirement parent_req_name=None, # type: Optional[str] extras_requested=None # type: Optional[Iterable[str]] ): # type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501 """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environment markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. """ # If the markers do not match, ignore this requirement. if not install_req.match_markers(extras_requested): logger.info( "Ignoring %s: markers '%s' don't match your environment", install_req.name, install_req.markers, ) return [], None # If the wheel is not supported, raise an error. # Should check this after filtering out based on environment markers to # allow specifying different wheels based on the environment/OS, in a # single requirements file. if install_req.link and install_req.link.is_wheel: wheel = Wheel(install_req.link.filename) tags = compatibility_tags.get_supported() if (self.check_supported_wheels and not wheel.supported(tags)): raise InstallationError( "{} is not a supported wheel on this platform.".format( wheel.filename) ) # This next bit is really a sanity check. assert not install_req.user_supplied or parent_req_name is None, ( "a user supplied req shouldn't have a parent" ) # Unnamed requirements are scanned again and the requirement won't be # added as a dependency until after scanning. if not install_req.name: self.add_unnamed_requirement(install_req) return [install_req], None try: existing_req = self.get_requirement( install_req.name) # type: Optional[InstallRequirement] except KeyError: existing_req = None has_conflicting_requirement = ( parent_req_name is None and existing_req and not existing_req.constraint and existing_req.extras == install_req.extras and existing_req.req.specifier != install_req.req.specifier ) if has_conflicting_requirement: raise InstallationError( "Double requirement given: {} (already in {}, name={!r})" .format(install_req, existing_req, install_req.name) ) # When no existing requirement exists, add the requirement as a # dependency and it will be scanned again after. if not existing_req: self.add_named_requirement(install_req) # We'd want to rescan this requirement later return [install_req], install_req # Assume there's no need to scan, and that we've already # encountered this for scanning. if install_req.constraint or not existing_req.constraint: return [], existing_req does_not_satisfy_constraint = ( install_req.link and not ( existing_req.link and install_req.link.path == existing_req.link.path ) ) if does_not_satisfy_constraint: raise InstallationError( "Could not satisfy constraints for '{}': " "installation from path or url cannot be " "constrained to a version".format(install_req.name) ) # If we're now installing a constraint, mark the existing # object for real installation. existing_req.constraint = False # If we're now installing a user supplied requirement, # mark the existing object as such. if install_req.user_supplied: existing_req.user_supplied = True existing_req.extras = tuple(sorted( set(existing_req.extras) | set(install_req.extras) )) logger.debug( "Setting %s extras to: %s", existing_req, existing_req.extras, ) # Return the existing requirement for addition to the parent and # scanning again. return [existing_req], existing_req def has_requirement(self, name): # type: (str) -> bool project_name = canonicalize_name(name) return ( project_name in self.requirements and not self.requirements[project_name].constraint ) def get_requirement(self, name): # type: (str) -> InstallRequirement project_name = canonicalize_name(name) if project_name in self.requirements: return self.requirements[project_name] raise KeyError("No project with the name {name!r}".format(**locals())) @property def all_requirements(self): # type: () -> List[InstallRequirement] return self.unnamed_requirements + list(self.requirements.values()) req/req_file.py000064400000045770152347654150007524 0ustar00""" Requirements file parsing """ from __future__ import absolute_import import optparse import os import re import shlex import sys from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.cli import cmdoptions from pip._internal.exceptions import ( InstallationError, RequirementsFileParseError, ) from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.encoding import auto_decode from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme if MYPY_CHECK_RUNNING: from optparse import Values from typing import ( Any, Callable, Dict, Iterator, List, NoReturn, Optional, Text, Tuple, ) from pip._internal.index.package_finder import PackageFinder from pip._internal.network.session import PipSession ReqFileLines = Iterator[Tuple[int, Text]] LineParser = Callable[[Text], Tuple[str, Values]] __all__ = ['parse_requirements'] SCHEME_RE = re.compile(r'^(http|https|file):', re.I) COMMENT_RE = re.compile(r'(^|\s+)#.*$') # Matches environment variable-style values in '${MY_VARIABLE_1}' with the # variable name consisting of only uppercase letters, digits or the '_' # (underscore). This follows the POSIX standard defined in IEEE Std 1003.1, # 2013 Edition. ENV_VAR_RE = re.compile(r'(?P\$\{(?P[A-Z0-9_]+)\})') SUPPORTED_OPTIONS = [ cmdoptions.index_url, cmdoptions.extra_index_url, cmdoptions.no_index, cmdoptions.constraints, cmdoptions.requirements, cmdoptions.editable, cmdoptions.find_links, cmdoptions.no_binary, cmdoptions.only_binary, cmdoptions.prefer_binary, cmdoptions.require_hashes, cmdoptions.pre, cmdoptions.trusted_host, cmdoptions.use_new_feature, ] # type: List[Callable[..., optparse.Option]] # options to be passed to requirements SUPPORTED_OPTIONS_REQ = [ cmdoptions.install_options, cmdoptions.global_options, cmdoptions.hash, ] # type: List[Callable[..., optparse.Option]] # the 'dest' string values SUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ] class ParsedRequirement(object): def __init__( self, requirement, # type:str is_editable, # type: bool comes_from, # type: str constraint, # type: bool options=None, # type: Optional[Dict[str, Any]] line_source=None, # type: Optional[str] ): # type: (...) -> None self.requirement = requirement self.is_editable = is_editable self.comes_from = comes_from self.options = options self.constraint = constraint self.line_source = line_source class ParsedLine(object): def __init__( self, filename, # type: str lineno, # type: int comes_from, # type: Optional[str] args, # type: str opts, # type: Values constraint, # type: bool ): # type: (...) -> None self.filename = filename self.lineno = lineno self.comes_from = comes_from self.opts = opts self.constraint = constraint if args: self.is_requirement = True self.is_editable = False self.requirement = args elif opts.editables: self.is_requirement = True self.is_editable = True # We don't support multiple -e on one line self.requirement = opts.editables[0] else: self.is_requirement = False def parse_requirements( filename, # type: str session, # type: PipSession finder=None, # type: Optional[PackageFinder] comes_from=None, # type: Optional[str] options=None, # type: Optional[optparse.Values] constraint=False, # type: bool ): # type: (...) -> Iterator[ParsedRequirement] """Parse a requirements file and yield ParsedRequirement instances. :param filename: Path or url of requirements file. :param session: PipSession instance. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param constraint: If true, parsing a constraint file rather than requirements file. """ line_parser = get_line_parser(finder) parser = RequirementsFileParser(session, line_parser, comes_from) for parsed_line in parser.parse(filename, constraint): parsed_req = handle_line( parsed_line, options=options, finder=finder, session=session ) if parsed_req is not None: yield parsed_req def preprocess(content): # type: (Text) -> ReqFileLines """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file """ lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines lines_enum = join_lines(lines_enum) lines_enum = ignore_comments(lines_enum) lines_enum = expand_env_variables(lines_enum) return lines_enum def handle_requirement_line( line, # type: ParsedLine options=None, # type: Optional[optparse.Values] ): # type: (...) -> ParsedRequirement # preserve for the nested code path line_comes_from = '{} {} (line {})'.format( '-c' if line.constraint else '-r', line.filename, line.lineno, ) assert line.is_requirement if line.is_editable: # For editable requirements, we don't support per-requirement # options, so just return the parsed requirement. return ParsedRequirement( requirement=line.requirement, is_editable=line.is_editable, comes_from=line_comes_from, constraint=line.constraint, ) else: if options: # Disable wheels if the user has specified build options cmdoptions.check_install_build_global(options, line.opts) # get the options that apply to requirements req_options = {} for dest in SUPPORTED_OPTIONS_REQ_DEST: if dest in line.opts.__dict__ and line.opts.__dict__[dest]: req_options[dest] = line.opts.__dict__[dest] line_source = 'line {} of {}'.format(line.lineno, line.filename) return ParsedRequirement( requirement=line.requirement, is_editable=line.is_editable, comes_from=line_comes_from, constraint=line.constraint, options=req_options, line_source=line_source, ) def handle_option_line( opts, # type: Values filename, # type: str lineno, # type: int finder=None, # type: Optional[PackageFinder] options=None, # type: Optional[optparse.Values] session=None, # type: Optional[PipSession] ): # type: (...) -> None if options: # percolate options upward if opts.require_hashes: options.require_hashes = opts.require_hashes if opts.features_enabled: options.features_enabled.extend( f for f in opts.features_enabled if f not in options.features_enabled ) # set finder options if finder: find_links = finder.find_links index_urls = finder.index_urls if opts.index_url: index_urls = [opts.index_url] if opts.no_index is True: index_urls = [] if opts.extra_index_urls: index_urls.extend(opts.extra_index_urls) if opts.find_links: # FIXME: it would be nice to keep track of the source # of the find_links: support a find-links local path # relative to a requirements file. value = opts.find_links[0] req_dir = os.path.dirname(os.path.abspath(filename)) relative_to_reqs_file = os.path.join(req_dir, value) if os.path.exists(relative_to_reqs_file): value = relative_to_reqs_file find_links.append(value) search_scope = SearchScope( find_links=find_links, index_urls=index_urls, ) finder.search_scope = search_scope if opts.pre: finder.set_allow_all_prereleases() if opts.prefer_binary: finder.set_prefer_binary() if session: for host in opts.trusted_hosts or []: source = 'line {} of {}'.format(lineno, filename) session.add_trusted_host(host, source=source) def handle_line( line, # type: ParsedLine options=None, # type: Optional[optparse.Values] finder=None, # type: Optional[PackageFinder] session=None, # type: Optional[PipSession] ): # type: (...) -> Optional[ParsedRequirement] """Handle a single parsed requirements line; This can result in creating/yielding requirements, or updating the finder. :param line: The parsed line to be processed. :param options: CLI options. :param finder: The finder - updated by non-requirement lines. :param session: The session - updated by non-requirement lines. Returns a ParsedRequirement object if the line is a requirement line, otherwise returns None. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. """ if line.is_requirement: parsed_req = handle_requirement_line(line, options) return parsed_req else: handle_option_line( line.opts, line.filename, line.lineno, finder, options, session, ) return None class RequirementsFileParser(object): def __init__( self, session, # type: PipSession line_parser, # type: LineParser comes_from, # type: Optional[str] ): # type: (...) -> None self._session = session self._line_parser = line_parser self._comes_from = comes_from def parse(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] """Parse a given file, yielding parsed lines. """ for line in self._parse_and_recurse(filename, constraint): yield line def _parse_and_recurse(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] for line in self._parse_file(filename, constraint): if ( not line.is_requirement and (line.opts.requirements or line.opts.constraints) ): # parse a nested requirements file if line.opts.requirements: req_path = line.opts.requirements[0] nested_constraint = False else: req_path = line.opts.constraints[0] nested_constraint = True # original file is over http if SCHEME_RE.search(filename): # do a url join so relative paths work req_path = urllib_parse.urljoin(filename, req_path) # original file and nested file are paths elif not SCHEME_RE.search(req_path): # do a join so relative paths work req_path = os.path.join( os.path.dirname(filename), req_path, ) for inner_line in self._parse_and_recurse( req_path, nested_constraint, ): yield inner_line else: yield line def _parse_file(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] _, content = get_file_content( filename, self._session, comes_from=self._comes_from ) lines_enum = preprocess(content) for line_number, line in lines_enum: try: args_str, opts = self._line_parser(line) except OptionParsingError as e: # add offending line msg = 'Invalid requirement: {}\n{}'.format(line, e.msg) raise RequirementsFileParseError(msg) yield ParsedLine( filename, line_number, self._comes_from, args_str, opts, constraint, ) def get_line_parser(finder): # type: (Optional[PackageFinder]) -> LineParser def parse_line(line): # type: (Text) -> Tuple[str, Values] # Build new parser for each line since it accumulates appendable # options. parser = build_parser() defaults = parser.get_default_values() defaults.index_url = None if finder: defaults.format_control = finder.format_control args_str, options_str = break_args_options(line) # Prior to 2.7.3, shlex cannot deal with unicode entries if sys.version_info < (2, 7, 3): # https://github.com/python/mypy/issues/1174 options_str = options_str.encode('utf8') # type: ignore # https://github.com/python/mypy/issues/1174 opts, _ = parser.parse_args( shlex.split(options_str), defaults) # type: ignore return args_str, opts return parse_line def break_args_options(line): # type: (Text) -> Tuple[str, Text] """Break up the line into an args and options string. We only want to shlex (and then optparse) the options, not the args. args can contain markers which are corrupted by shlex. """ tokens = line.split(' ') args = [] options = tokens[:] for token in tokens: if token.startswith('-') or token.startswith('--'): break else: args.append(token) options.pop(0) return ' '.join(args), ' '.join(options) # type: ignore class OptionParsingError(Exception): def __init__(self, msg): # type: (str) -> None self.msg = msg def build_parser(): # type: () -> optparse.OptionParser """ Return a parser for parsing requirement lines """ parser = optparse.OptionParser(add_help_option=False) option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ for option_factory in option_factories: option = option_factory() parser.add_option(option) # By default optparse sys.exits on parsing errors. We want to wrap # that in our own exception. def parser_exit(self, msg): # type: (Any, str) -> NoReturn raise OptionParsingError(msg) # NOTE: mypy disallows assigning to a method # https://github.com/python/mypy/issues/2427 parser.exit = parser_exit # type: ignore return parser def join_lines(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line. """ primary_line_number = None new_line = [] # type: List[Text] for line_number, line in lines_enum: if not line.endswith('\\') or COMMENT_RE.match(line): if COMMENT_RE.match(line): # this ensures comments are always matched later line = ' ' + line if new_line: new_line.append(line) assert primary_line_number is not None yield primary_line_number, ''.join(new_line) new_line = [] else: yield line_number, line else: if not new_line: primary_line_number = line_number new_line.append(line.strip('\\')) # last line contains \ if new_line: assert primary_line_number is not None yield primary_line_number, ''.join(new_line) # TODO: handle space after '\'. def ignore_comments(lines_enum): # type: (ReqFileLines) -> ReqFileLines """ Strips comments and filter empty lines. """ for line_number, line in lines_enum: line = COMMENT_RE.sub('', line) line = line.strip() if line: yield line_number, line def expand_env_variables(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Replace all environment variables that can be retrieved via `os.getenv`. The only allowed format for environment variables defined in the requirement file is `${MY_VARIABLE_1}` to ensure two things: 1. Strings that contain a `$` aren't accidentally (partially) expanded. 2. Ensure consistency across platforms for requirement files. These points are the result of a discussion on the `github pull request #3514 `_. Valid characters in variable names follow the `POSIX standard `_ and are limited to uppercase letter, digits and the `_` (underscore). """ for line_number, line in lines_enum: for env_var, var_name in ENV_VAR_RE.findall(line): value = os.getenv(var_name) if not value: continue line = line.replace(env_var, value) yield line_number, line def get_file_content(url, session, comes_from=None): # type: (str, PipSession, Optional[str]) -> Tuple[str, Text] """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance. :param comes_from: Origin description of requirements. """ scheme = get_url_scheme(url) if scheme in ['http', 'https']: # FIXME: catch some errors resp = session.get(url) raise_for_status(resp) return resp.url, resp.text elif scheme == 'file': if comes_from and comes_from.startswith('http'): raise InstallationError( 'Requirements file {} references URL {}, ' 'which is local'.format(comes_from, url) ) path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib_parse.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path try: with open(url, 'rb') as f: content = auto_decode(f.read()) except IOError as exc: raise InstallationError( 'Could not open requirements file: {}'.format(exc) ) return url, content _url_slash_drive_re = re.compile(r'/*([a-z])\|', re.I) req/__init__.py000064400000006075152347654150007470 0ustar00from __future__ import absolute_import import collections import logging from pip._internal.utils.logging import indent_log from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .req_file import parse_requirements from .req_install import InstallRequirement from .req_set import RequirementSet if MYPY_CHECK_RUNNING: from typing import Iterator, List, Optional, Sequence, Tuple __all__ = [ "RequirementSet", "InstallRequirement", "parse_requirements", "install_given_reqs", ] logger = logging.getLogger(__name__) class InstallationResult(object): def __init__(self, name): # type: (str) -> None self.name = name def __repr__(self): # type: () -> str return "InstallationResult(name={!r})".format(self.name) def _validate_requirements( requirements, # type: List[InstallRequirement] ): # type: (...) -> Iterator[Tuple[str, InstallRequirement]] for req in requirements: assert req.name, "invalid to-be-installed requirement: {}".format(req) yield req.name, req def install_given_reqs( requirements, # type: List[InstallRequirement] install_options, # type: List[str] global_options, # type: Sequence[str] root, # type: Optional[str] home, # type: Optional[str] prefix, # type: Optional[str] warn_script_location, # type: bool use_user_site, # type: bool pycompile, # type: bool ): # type: (...) -> List[InstallationResult] """ Install everything in the given list. (to be called after having downloaded and unpacked the packages) """ to_install = collections.OrderedDict(_validate_requirements(requirements)) if to_install: logger.info( 'Installing collected packages: %s', ', '.join(to_install.keys()), ) installed = [] with indent_log(): for req_name, requirement in to_install.items(): if requirement.should_reinstall: logger.info('Attempting uninstall: %s', req_name) with indent_log(): uninstalled_pathset = requirement.uninstall( auto_confirm=True ) else: uninstalled_pathset = None try: requirement.install( install_options, global_options, root=root, home=home, prefix=prefix, warn_script_location=warn_script_location, use_user_site=use_user_site, pycompile=pycompile, ) except Exception: # if install did not succeed, rollback previous uninstall if uninstalled_pathset and not requirement.install_succeeded: uninstalled_pathset.rollback() raise else: if uninstalled_pathset and requirement.install_succeeded: uninstalled_pathset.commit() installed.append(InstallationResult(req_name)) return installed req/req_install.py000064400000101610152347654150010235 0ustar00# The following comment should be removed at some point in the future. # mypy: strict-optional=False from __future__ import absolute_import import logging import os import shutil import sys import uuid import zipfile from pip._vendor import pkg_resources, six from pip._vendor.packaging.requirements import Requirement from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._vendor.packaging.version import parse as parse_version from pip._vendor.pep517.wrappers import Pep517HookCaller from pip._internal.build_env import NoOpBuildEnvironment from pip._internal.exceptions import InstallationError from pip._internal.locations import get_scheme from pip._internal.models.link import Link from pip._internal.operations.build.metadata import generate_metadata from pip._internal.operations.build.metadata_legacy import \ generate_metadata as generate_metadata_legacy from pip._internal.operations.install.editable_legacy import \ install_editable as install_editable_legacy from pip._internal.operations.install.legacy import LegacyInstallFailure from pip._internal.operations.install.legacy import install as install_legacy from pip._internal.operations.install.wheel import install_wheel from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path from pip._internal.req.req_uninstall import UninstallPathSet from pip._internal.utils.deprecation import deprecated from pip._internal.utils.direct_url_helpers import direct_url_from_link from pip._internal.utils.hashes import Hashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, dist_in_install_path, dist_in_site_packages, dist_in_usersite, get_distribution, get_installed_version, hide_url, redact_auth_from_url, ) from pip._internal.utils.packaging import get_metadata from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import running_under_virtualenv from pip._internal.vcs import vcs if MYPY_CHECK_RUNNING: from typing import ( Any, Dict, Iterable, List, Optional, Sequence, Union, ) from pip._internal.build_env import BuildEnvironment from pip._vendor.pkg_resources import Distribution from pip._vendor.packaging.specifiers import SpecifierSet from pip._vendor.packaging.markers import Marker logger = logging.getLogger(__name__) def _get_dist(metadata_directory): # type: (str) -> Distribution """Return a pkg_resources.Distribution for the provided metadata directory. """ dist_dir = metadata_directory.rstrip(os.sep) # Build a PathMetadata object, from path to metadata. :wink: base_dir, dist_dir_name = os.path.split(dist_dir) metadata = pkg_resources.PathMetadata(base_dir, dist_dir) # Determine the correct Distribution object type. if dist_dir.endswith(".egg-info"): dist_cls = pkg_resources.Distribution dist_name = os.path.splitext(dist_dir_name)[0] else: assert dist_dir.endswith(".dist-info") dist_cls = pkg_resources.DistInfoDistribution dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0] return dist_cls( base_dir, project_name=dist_name, metadata=metadata, ) class InstallRequirement(object): """ Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. """ def __init__( self, req, # type: Optional[Requirement] comes_from, # type: Optional[Union[str, InstallRequirement]] editable=False, # type: bool link=None, # type: Optional[Link] markers=None, # type: Optional[Marker] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool install_options=None, # type: Optional[List[str]] global_options=None, # type: Optional[List[str]] hash_options=None, # type: Optional[Dict[str, List[str]]] constraint=False, # type: bool extras=(), # type: Iterable[str] user_supplied=False, # type: bool ): # type: (...) -> None assert req is None or isinstance(req, Requirement), req self.req = req self.comes_from = comes_from self.constraint = constraint self.editable = editable self.legacy_install_reason = None # type: Optional[int] # source_dir is the local directory where the linked requirement is # located, or unpacked. In case unpacking is needed, creating and # populating source_dir is done by the RequirementPreparer. Note this # is not necessarily the directory where pyproject.toml or setup.py is # located - that one is obtained via unpacked_source_directory. self.source_dir = None # type: Optional[str] if self.editable: assert link if link.is_file: self.source_dir = os.path.normpath( os.path.abspath(link.file_path) ) if link is None and req and req.url: # PEP 508 URL requirement link = Link(req.url) self.link = self.original_link = link self.original_link_is_in_wheel_cache = False # Path to any downloaded or already-existing package. self.local_file_path = None # type: Optional[str] if self.link and self.link.is_file: self.local_file_path = self.link.file_path if extras: self.extras = extras elif req: self.extras = { pkg_resources.safe_extra(extra) for extra in req.extras } else: self.extras = set() if markers is None and req: markers = req.marker self.markers = markers # This holds the pkg_resources.Distribution object if this requirement # is already available: self.satisfied_by = None # type: Optional[Distribution] # Whether the installation process should try to uninstall an existing # distribution before installing this requirement. self.should_reinstall = False # Temporary build location self._temp_build_dir = None # type: Optional[TempDirectory] # Set to True after successful installation self.install_succeeded = None # type: Optional[bool] # Supplied options self.install_options = install_options if install_options else [] self.global_options = global_options if global_options else [] self.hash_options = hash_options if hash_options else {} # Set to True after successful preparation of this requirement self.prepared = False # User supplied requirement are explicitly requested for installation # by the user via CLI arguments or requirements files, as opposed to, # e.g. dependencies, extras or constraints. self.user_supplied = user_supplied # Set by the legacy resolver when the requirement has been downloaded # TODO: This introduces a strong coupling between the resolver and the # requirement (the coupling was previously between the resolver # and the requirement set). This should be refactored to allow # the requirement to decide for itself when it has been # successfully downloaded - but that is more tricky to get right, # se we are making the change in stages. self.successfully_downloaded = False self.isolated = isolated self.build_env = NoOpBuildEnvironment() # type: BuildEnvironment # For PEP 517, the directory where we request the project metadata # gets stored. We need this to pass to build_wheel, so the backend # can ensure that the wheel matches the metadata (see the PEP for # details). self.metadata_directory = None # type: Optional[str] # The static build requirements (from pyproject.toml) self.pyproject_requires = None # type: Optional[List[str]] # Build requirements that we will check are available self.requirements_to_check = [] # type: List[str] # The PEP 517 backend we should use to build the project self.pep517_backend = None # type: Optional[Pep517HookCaller] # Are we using PEP 517 for this requirement? # After pyproject.toml has been loaded, the only valid values are True # and False. Before loading, None is valid (meaning "use the default"). # Setting an explicit value before loading pyproject.toml is supported, # but after loading this flag should be treated as read only. self.use_pep517 = use_pep517 def __str__(self): # type: () -> str if self.req: s = str(self.req) if self.link: s += ' from {}'.format(redact_auth_from_url(self.link.url)) elif self.link: s = redact_auth_from_url(self.link.url) else: s = '' if self.satisfied_by is not None: s += ' in {}'.format(display_path(self.satisfied_by.location)) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from # type: Optional[str] else: comes_from = self.comes_from.from_path() if comes_from: s += ' (from {})'.format(comes_from) return s def __repr__(self): # type: () -> str return '<{} object: {} editable={!r}>'.format( self.__class__.__name__, str(self), self.editable) def format_debug(self): # type: () -> str """An un-tested helper for getting state, for debugging. """ attributes = vars(self) names = sorted(attributes) state = ( "{}={!r}".format(attr, attributes[attr]) for attr in sorted(names) ) return '<{name} object: {{{state}}}>'.format( name=self.__class__.__name__, state=", ".join(state), ) # Things that are valid for all kinds of requirements? @property def name(self): # type: () -> Optional[str] if self.req is None: return None return six.ensure_str(pkg_resources.safe_name(self.req.name)) @property def specifier(self): # type: () -> SpecifierSet return self.req.specifier @property def is_pinned(self): # type: () -> bool """Return whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. """ specifiers = self.specifier return (len(specifiers) == 1 and next(iter(specifiers)).operator in {'==', '==='}) @property def installed_version(self): # type: () -> Optional[str] return get_installed_version(self.name) def match_markers(self, extras_requested=None): # type: (Optional[Iterable[str]]) -> bool if not extras_requested: # Provide an extra to safely evaluate the markers # without matching any extra extras_requested = ('',) if self.markers is not None: return any( self.markers.evaluate({'extra': extra}) for extra in extras_requested) else: return True @property def has_hash_options(self): # type: () -> bool """Return whether any known-good hashes are specified as options. These activate --require-hashes mode; hashes specified as part of a URL do not. """ return bool(self.hash_options) def hashes(self, trust_internet=True): # type: (bool) -> Hashes """Return a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() """ good_hashes = self.hash_options.copy() link = self.link if trust_internet else self.original_link if link and link.hash: good_hashes.setdefault(link.hash_name, []).append(link.hash) return Hashes(good_hashes) def from_path(self): # type: () -> Optional[str] """Format a nice indicator to show where this "comes from" """ if self.req is None: return None s = str(self.req) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from else: comes_from = self.comes_from.from_path() if comes_from: s += '->' + comes_from return s def ensure_build_location(self, build_dir, autodelete, parallel_builds): # type: (str, bool, bool) -> str assert build_dir is not None if self._temp_build_dir is not None: assert self._temp_build_dir.path return self._temp_build_dir.path if self.req is None: # Some systems have /tmp as a symlink which confuses custom # builds (such as numpy). Thus, we ensure that the real path # is returned. self._temp_build_dir = TempDirectory( kind=tempdir_kinds.REQ_BUILD, globally_managed=True ) return self._temp_build_dir.path # When parallel builds are enabled, add a UUID to the build directory # name so multiple builds do not interfere with each other. dir_name = canonicalize_name(self.name) if parallel_builds: dir_name = "{}_{}".format(dir_name, uuid.uuid4().hex) # FIXME: Is there a better place to create the build_dir? (hg and bzr # need this) if not os.path.exists(build_dir): logger.debug('Creating directory %s', build_dir) os.makedirs(build_dir) actual_build_dir = os.path.join(build_dir, dir_name) # `None` indicates that we respect the globally-configured deletion # settings, which is what we actually want when auto-deleting. delete_arg = None if autodelete else False return TempDirectory( path=actual_build_dir, delete=delete_arg, kind=tempdir_kinds.REQ_BUILD, globally_managed=True, ).path def _set_requirement(self): # type: () -> None """Set requirement after generating metadata. """ assert self.req is None assert self.metadata is not None assert self.source_dir is not None # Construct a Requirement object from the generated metadata if isinstance(parse_version(self.metadata["Version"]), Version): op = "==" else: op = "===" self.req = Requirement( "".join([ self.metadata["Name"], op, self.metadata["Version"], ]) ) def warn_on_mismatching_name(self): # type: () -> None metadata_name = canonicalize_name(self.metadata["Name"]) if canonicalize_name(self.req.name) == metadata_name: # Everything is fine. return # If we're here, there's a mismatch. Log a warning about it. logger.warning( 'Generating metadata for package %s ' 'produced metadata for project name %s. Fix your ' '#egg=%s fragments.', self.name, metadata_name, self.name ) self.req = Requirement(metadata_name) def check_if_exists(self, use_user_site): # type: (bool) -> None """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.should_reinstall appropriately. """ if self.req is None: return existing_dist = get_distribution(self.req.name) if not existing_dist: return existing_version = existing_dist.parsed_version if not self.req.specifier.contains(existing_version, prereleases=True): self.satisfied_by = None if use_user_site: if dist_in_usersite(existing_dist): self.should_reinstall = True elif (running_under_virtualenv() and dist_in_site_packages(existing_dist)): raise InstallationError( "Will not install to the user site because it will " "lack sys.path precedence to {} in {}".format( existing_dist.project_name, existing_dist.location) ) elif dist_in_install_path(existing_dist): self.should_reinstall = True else: if self.editable: self.should_reinstall = True # when installing editables, nothing pre-existing should ever # satisfy self.satisfied_by = None else: self.satisfied_by = existing_dist # Things valid for wheels @property def is_wheel(self): # type: () -> bool if not self.link: return False return self.link.is_wheel # Things valid for sdists @property def unpacked_source_directory(self): # type: () -> str return os.path.join( self.source_dir, self.link and self.link.subdirectory_fragment or '') @property def setup_py_path(self): # type: () -> str assert self.source_dir, "No source dir for {}".format(self) setup_py = os.path.join(self.unpacked_source_directory, 'setup.py') # Python2 __file__ should not be unicode if six.PY2 and isinstance(setup_py, six.text_type): setup_py = setup_py.encode(sys.getfilesystemencoding()) return setup_py @property def pyproject_toml_path(self): # type: () -> str assert self.source_dir, "No source dir for {}".format(self) return make_pyproject_path(self.unpacked_source_directory) def load_pyproject_toml(self): # type: () -> None """Load the pyproject.toml file. After calling this routine, all of the attributes related to PEP 517 processing for this requirement have been set. In particular, the use_pep517 attribute can be used to determine whether we should follow the PEP 517 or legacy (setup.py) code path. """ pyproject_toml_data = load_pyproject_toml( self.use_pep517, self.pyproject_toml_path, self.setup_py_path, str(self) ) if pyproject_toml_data is None: self.use_pep517 = False return self.use_pep517 = True requires, backend, check, backend_path = pyproject_toml_data self.requirements_to_check = check self.pyproject_requires = requires self.pep517_backend = Pep517HookCaller( self.unpacked_source_directory, backend, backend_path=backend_path, ) def _generate_metadata(self): # type: () -> str """Invokes metadata generator functions, with the required arguments. """ if not self.use_pep517: assert self.unpacked_source_directory return generate_metadata_legacy( build_env=self.build_env, setup_py_path=self.setup_py_path, source_dir=self.unpacked_source_directory, isolated=self.isolated, details=self.name or "from {}".format(self.link) ) assert self.pep517_backend is not None return generate_metadata( build_env=self.build_env, backend=self.pep517_backend, ) def prepare_metadata(self): # type: () -> None """Ensure that project metadata is available. Under PEP 517, call the backend hook to prepare the metadata. Under legacy processing, call setup.py egg-info. """ assert self.source_dir with indent_log(): self.metadata_directory = self._generate_metadata() # Act on the newly generated metadata, based on the name and version. if not self.name: self._set_requirement() else: self.warn_on_mismatching_name() self.assert_source_matches_version() @property def metadata(self): # type: () -> Any if not hasattr(self, '_metadata'): self._metadata = get_metadata(self.get_dist()) return self._metadata def get_dist(self): # type: () -> Distribution return _get_dist(self.metadata_directory) def assert_source_matches_version(self): # type: () -> None assert self.source_dir version = self.metadata['version'] if self.req.specifier and version not in self.req.specifier: logger.warning( 'Requested %s, but installing version %s', self, version, ) else: logger.debug( 'Source in %s has version %s, which satisfies requirement %s', display_path(self.source_dir), version, self, ) # For both source distributions and editables def ensure_has_source_dir( self, parent_dir, autodelete=False, parallel_builds=False, ): # type: (str, bool, bool) -> None """Ensure that a source_dir is set. This will create a temporary build dir if the name of the requirement isn't known yet. :param parent_dir: The ideal pip parent_dir for the source_dir. Generally src_dir for editables and build_dir for sdists. :return: self.source_dir """ if self.source_dir is None: self.source_dir = self.ensure_build_location( parent_dir, autodelete=autodelete, parallel_builds=parallel_builds, ) # For editable installations def update_editable(self, obtain=True): # type: (bool) -> None if not self.link: logger.debug( "Cannot update repository at %s; repository location is " "unknown", self.source_dir, ) return assert self.editable assert self.source_dir if self.link.scheme == 'file': # Static paths don't get updated return assert '+' in self.link.url, \ "bad url: {self.link.url!r}".format(**locals()) vc_type, url = self.link.url.split('+', 1) vcs_backend = vcs.get_backend(vc_type) if vcs_backend: if not self.link.is_vcs: reason = ( "This form of VCS requirement is being deprecated: {}." ).format( self.link.url ) replacement = None if self.link.url.startswith("git+git@"): replacement = ( "git+https://git@example.com/..., " "git+ssh://git@example.com/..., " "or the insecure git+git://git@example.com/..." ) deprecated(reason, replacement, gone_in="21.0", issue=7554) hidden_url = hide_url(self.link.url) if obtain: vcs_backend.obtain(self.source_dir, url=hidden_url) else: vcs_backend.export(self.source_dir, url=hidden_url) else: assert 0, ( 'Unexpected version control type (in {}): {}'.format( self.link, vc_type)) # Top-level Actions def uninstall(self, auto_confirm=False, verbose=False): # type: (bool, bool) -> Optional[UninstallPathSet] """ 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 is linked to global site-packages. """ assert self.req dist = get_distribution(self.req.name) if not dist: logger.warning("Skipping %s as it is not installed.", self.name) return None logger.info('Found existing installation: %s', dist) uninstalled_pathset = UninstallPathSet.from_dist(dist) uninstalled_pathset.remove(auto_confirm, verbose) return uninstalled_pathset def _get_archive_name(self, path, parentdir, rootdir): # type: (str, str, str) -> str def _clean_zip_name(name, prefix): # type: (str, str) -> str assert name.startswith(prefix + os.path.sep), ( "name {name!r} doesn't start with prefix {prefix!r}" .format(**locals()) ) name = name[len(prefix) + 1:] name = name.replace(os.path.sep, '/') return name path = os.path.join(parentdir, path) name = _clean_zip_name(path, rootdir) return self.name + '/' + name def archive(self, build_dir): # type: (str) -> None """Saves archive to provided build_dir. Used for saving downloaded VCS requirements as part of `pip download`. """ assert self.source_dir create_archive = True archive_name = '{}-{}.zip'.format(self.name, self.metadata["version"]) archive_path = os.path.join(build_dir, archive_name) if os.path.exists(archive_path): response = ask_path_exists( 'The file {} exists. (i)gnore, (w)ipe, ' '(b)ackup, (a)bort '.format( display_path(archive_path)), ('i', 'w', 'b', 'a')) if response == 'i': create_archive = False elif response == 'w': logger.warning('Deleting %s', display_path(archive_path)) os.remove(archive_path) elif response == 'b': dest_file = backup_dir(archive_path) logger.warning( 'Backing up %s to %s', display_path(archive_path), display_path(dest_file), ) shutil.move(archive_path, dest_file) elif response == 'a': sys.exit(-1) if not create_archive: return zip_output = zipfile.ZipFile( archive_path, 'w', zipfile.ZIP_DEFLATED, allowZip64=True, ) with zip_output: dir = os.path.normcase( os.path.abspath(self.unpacked_source_directory) ) for dirpath, dirnames, filenames in os.walk(dir): for dirname in dirnames: dir_arcname = self._get_archive_name( dirname, parentdir=dirpath, rootdir=dir, ) zipdir = zipfile.ZipInfo(dir_arcname + '/') zipdir.external_attr = 0x1ED << 16 # 0o755 zip_output.writestr(zipdir, '') for filename in filenames: file_arcname = self._get_archive_name( filename, parentdir=dirpath, rootdir=dir, ) filename = os.path.join(dirpath, filename) zip_output.write(filename, file_arcname) logger.info('Saved %s', display_path(archive_path)) def install( self, install_options, # type: List[str] global_options=None, # type: Optional[Sequence[str]] root=None, # type: Optional[str] home=None, # type: Optional[str] prefix=None, # type: Optional[str] warn_script_location=True, # type: bool use_user_site=False, # type: bool pycompile=True # type: bool ): # type: (...) -> None scheme = get_scheme( self.name, user=use_user_site, home=home, root=root, isolated=self.isolated, prefix=prefix, ) global_options = global_options if global_options is not None else [] if self.editable: install_editable_legacy( install_options, global_options, prefix=prefix, home=home, use_user_site=use_user_site, name=self.name, setup_py_path=self.setup_py_path, isolated=self.isolated, build_env=self.build_env, unpacked_source_directory=self.unpacked_source_directory, ) self.install_succeeded = True return if self.is_wheel: assert self.local_file_path direct_url = None if self.original_link: direct_url = direct_url_from_link( self.original_link, self.source_dir, self.original_link_is_in_wheel_cache, ) install_wheel( self.name, self.local_file_path, scheme=scheme, req_description=str(self.req), pycompile=pycompile, warn_script_location=warn_script_location, direct_url=direct_url, requested=self.user_supplied, ) self.install_succeeded = True return # TODO: Why don't we do this for editable installs? # Extend the list of global and install options passed on to # the setup.py call with the ones from the requirements file. # Options specified in requirements file override those # specified on the command line, since the last option given # to setup.py is the one that is used. global_options = list(global_options) + self.global_options install_options = list(install_options) + self.install_options try: success = install_legacy( install_options=install_options, global_options=global_options, root=root, home=home, prefix=prefix, use_user_site=use_user_site, pycompile=pycompile, scheme=scheme, setup_py_path=self.setup_py_path, isolated=self.isolated, req_name=self.name, build_env=self.build_env, unpacked_source_directory=self.unpacked_source_directory, req_description=str(self.req), ) except LegacyInstallFailure as exc: self.install_succeeded = False six.reraise(*exc.parent) except Exception: self.install_succeeded = True raise self.install_succeeded = success if success and self.legacy_install_reason == 8368: deprecated( reason=( "{} was installed using the legacy 'setup.py install' " "method, because a wheel could not be built for it.". format(self.name) ), replacement="to fix the wheel build issue reported above", gone_in="21.0", issue=8368, ) def check_invalid_constraint_type(req): # type: (InstallRequirement) -> str # Check for unsupported forms problem = "" if not req.name: problem = "Unnamed requirements are not allowed as constraints" elif req.link: problem = "Links are not allowed as constraints" elif req.extras: problem = "Constraints cannot have extras" if problem: deprecated( reason=( "Constraints are only allowed to take the form of a package " "name and a version specifier. Other forms were originally " "permitted as an accident of the implementation, but were " "undocumented. The new implementation of the resolver no " "longer supports these forms." ), replacement=( "replacing the constraint with a requirement." ), # No plan yet for when the new resolver becomes default gone_in=None, issue=8210 ) return problem req/constructors.py000064400000040003152347654150010466 0ustar00"""Backing implementation for InstallRequirement's various constructors The idea here is that these formed a major chunk of InstallRequirement's size so, moving them and support code dedicated to them outside of that class helps creates for better understandability for the rest of the code. These are meant to be used elsewhere within pip to create instances of InstallRequirement. """ import logging import os import re from pip._vendor.packaging.markers import Marker from pip._vendor.packaging.requirements import InvalidRequirement, Requirement from pip._vendor.packaging.specifiers import Specifier from pip._vendor.pkg_resources import RequirementParseError, parse_requirements from pip._internal.exceptions import InstallationError from pip._internal.models.index import PyPI, TestPyPI from pip._internal.models.link import Link from pip._internal.models.wheel import Wheel from pip._internal.pyproject import make_pyproject_path from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.deprecation import deprecated from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import is_installable_dir, splitext from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import is_url, vcs if MYPY_CHECK_RUNNING: from typing import ( Any, Dict, Optional, Set, Tuple, Union, ) from pip._internal.req.req_file import ParsedRequirement __all__ = [ "install_req_from_editable", "install_req_from_line", "parse_editable" ] logger = logging.getLogger(__name__) operators = Specifier._operators.keys() def is_archive_file(name): # type: (str) -> bool """Return True if `name` is a considered as an archive file.""" ext = splitext(name)[1].lower() if ext in ARCHIVE_EXTENSIONS: return True return False def _strip_extras(path): # type: (str) -> Tuple[str, Optional[str]] m = re.match(r'^(.+)(\[[^\]]+\])$', path) extras = None if m: path_no_extras = m.group(1) extras = m.group(2) else: path_no_extras = path return path_no_extras, extras def convert_extras(extras): # type: (Optional[str]) -> Set[str] if not extras: return set() return Requirement("placeholder" + extras.lower()).extras def parse_editable(editable_req): # type: (str) -> Tuple[Optional[str], str, Set[str]] """Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] """ url = editable_req # If a file path is specified with extras, strip off the extras. url_no_extras, extras = _strip_extras(url) if os.path.isdir(url_no_extras): if not os.path.exists(os.path.join(url_no_extras, 'setup.py')): msg = ( 'File "setup.py" not found. Directory cannot be installed ' 'in editable mode: {}'.format(os.path.abspath(url_no_extras)) ) pyproject_path = make_pyproject_path(url_no_extras) if os.path.isfile(pyproject_path): msg += ( '\n(A "pyproject.toml" file was found, but editable ' 'mode currently requires a setup.py based build.)' ) raise InstallationError(msg) # Treating it as code that has already been checked out url_no_extras = path_to_url(url_no_extras) if url_no_extras.lower().startswith('file:'): package_name = Link(url_no_extras).egg_fragment if extras: return ( package_name, url_no_extras, Requirement("placeholder" + extras.lower()).extras, ) else: return package_name, url_no_extras, set() for version_control in vcs: if url.lower().startswith('{}:'.format(version_control)): url = '{}+{}'.format(version_control, url) break if '+' not in url: raise InstallationError( '{} is not a valid editable requirement. ' 'It should either be a path to a local project or a VCS URL ' '(beginning with svn+, git+, hg+, or bzr+).'.format(editable_req) ) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): backends = ", ".join([bends.name + '+URL' for bends in vcs.backends]) error_message = "For --editable={}, " \ "only {} are currently supported".format( editable_req, backends) raise InstallationError(error_message) package_name = Link(url).egg_fragment if not package_name: raise InstallationError( "Could not detect requirement name for '{}', please specify one " "with #egg=your_package_name".format(editable_req) ) return package_name, url, set() def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path """ msg = "" if os.path.exists(req): msg = " It does exist." # Try to parse and check if it is a requirements file. try: with open(req, 'r') as fp: # parse first line only next(parse_requirements(fp.read())) msg += ( "The argument you provided " "({}) appears to be a" " requirements file. If that is the" " case, use the '-r' flag to install" " the packages specified within it." ).format(req) except RequirementParseError: logger.debug( "Cannot parse '%s' as requirements file", req, exc_info=True ) else: msg += " File '{}' does not exist.".format(req) return msg class RequirementParts(object): def __init__( self, requirement, # type: Optional[Requirement] link, # type: Optional[Link] markers, # type: Optional[Marker] extras, # type: Set[str] ): self.requirement = requirement self.link = link self.markers = markers self.extras = extras def parse_req_from_editable(editable_req): # type: (str) -> RequirementParts name, url, extras_override = parse_editable(editable_req) if name is not None: try: req = Requirement(name) except InvalidRequirement: raise InstallationError("Invalid requirement: '{}'".format(name)) else: req = None link = Link(url) return RequirementParts(req, link, None, extras_override) # ---- The actual constructors follow ---- def install_req_from_editable( editable_req, # type: str comes_from=None, # type: Optional[Union[InstallRequirement, str]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement parts = parse_req_from_editable(editable_req) return InstallRequirement( parts.requirement, comes_from=comes_from, user_supplied=user_supplied, editable=True, link=parts.link, constraint=constraint, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, extras=parts.extras, ) def _looks_like_path(name): # type: (str) -> bool """Checks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (which represents the current directory). """ if os.path.sep in name: return True if os.path.altsep is not None and os.path.altsep in name: return True if name.startswith("."): return True return False def _get_url_from_path(path, name): # type: (str, str) -> Optional[str] """ First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file. If false, if the path has an @, it will treat it as a PEP 440 URL requirement and return the path. """ if _looks_like_path(name) and os.path.isdir(path): if is_installable_dir(path): return path_to_url(path) raise InstallationError( "Directory {name!r} is not installable. Neither 'setup.py' " "nor 'pyproject.toml' found.".format(**locals()) ) if not is_archive_file(path): return None if os.path.isfile(path): return path_to_url(path) urlreq_parts = name.split('@', 1) if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]): # If the path contains '@' and the part before it does not look # like a path, try to treat it as a PEP 440 URL req instead. return None logger.warning( 'Requirement %r looks like a filename, but the ' 'file does not exist', name ) return path_to_url(path) def parse_req_from_line(name, line_source): # type: (str, Optional[str]) -> RequirementParts if is_url(name): marker_sep = '; ' else: marker_sep = ';' if marker_sep in name: name, markers_as_string = name.split(marker_sep, 1) markers_as_string = markers_as_string.strip() if not markers_as_string: markers = None else: markers = Marker(markers_as_string) else: markers = None name = name.strip() req_as_string = None path = os.path.normpath(os.path.abspath(name)) link = None extras_as_string = None if is_url(name): link = Link(name) else: p, extras_as_string = _strip_extras(path) url = _get_url_from_path(p, name) if url is not None: link = Link(url) # it's a local file, dir, or url if link: # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', link.url): link = Link( path_to_url(os.path.normpath(os.path.abspath(link.path)))) # wheel file if link.is_wheel: wheel = Wheel(link.filename) # can raise InvalidWheelFilename req_as_string = "{wheel.name}=={wheel.version}".format(**locals()) else: # set the req to the egg fragment. when it's not there, this # will become an 'unnamed' requirement req_as_string = link.egg_fragment # a requirement specifier else: req_as_string = name extras = convert_extras(extras_as_string) def with_source(text): # type: (str) -> str if not line_source: return text return '{} (from {})'.format(text, line_source) if req_as_string is not None: try: req = Requirement(req_as_string) except InvalidRequirement: if os.path.sep in req_as_string: add_msg = "It looks like a path." add_msg += deduce_helpful_msg(req_as_string) elif ('=' in req_as_string and not any(op in req_as_string for op in operators)): add_msg = "= is not a valid operator. Did you mean == ?" else: add_msg = '' msg = with_source( 'Invalid requirement: {!r}'.format(req_as_string) ) if add_msg: msg += '\nHint: {}'.format(add_msg) raise InstallationError(msg) else: # Deprecate extras after specifiers: "name>=1.0[extras]" # This currently works by accident because _strip_extras() parses # any extras in the end of the string and those are saved in # RequirementParts for spec in req.specifier: spec_str = str(spec) if spec_str.endswith(']'): msg = "Extras after version '{}'.".format(spec_str) replace = "moving the extras before version specifiers" deprecated(msg, replacement=replace, gone_in="21.0") else: req = None return RequirementParts(req, link, markers, extras) def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. """ parts = parse_req_from_line(name, line_source) return InstallRequirement( parts.requirement, comes_from, link=parts.link, markers=parts.markers, use_pep517=use_pep517, isolated=isolated, install_options=options.get("install_options", []) if options else [], global_options=options.get("global_options", []) if options else [], hash_options=options.get("hashes", {}) if options else {}, constraint=constraint, extras=parts.extras, user_supplied=user_supplied, ) def install_req_from_req_string( req_string, # type: str comes_from=None, # type: Optional[InstallRequirement] isolated=False, # type: bool use_pep517=None, # type: Optional[bool] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement try: req = Requirement(req_string) except InvalidRequirement: raise InstallationError("Invalid requirement: '{}'".format(req_string)) domains_not_allowed = [ PyPI.file_storage_domain, TestPyPI.file_storage_domain, ] if (req.url and comes_from and comes_from.link and comes_from.link.netloc in domains_not_allowed): # Explicitly disallow pypi packages that depend on external urls raise InstallationError( "Packages installed from PyPI cannot depend on packages " "which are not also hosted on PyPI.\n" "{} depends on {} ".format(comes_from.name, req) ) return InstallRequirement( req, comes_from, isolated=isolated, use_pep517=use_pep517, user_supplied=user_supplied, ) def install_req_from_parsed_requirement( parsed_req, # type: ParsedRequirement isolated=False, # type: bool use_pep517=None, # type: Optional[bool] user_supplied=False, # type: bool ): # type: (...) -> InstallRequirement if parsed_req.is_editable: req = install_req_from_editable( parsed_req.requirement, comes_from=parsed_req.comes_from, use_pep517=use_pep517, constraint=parsed_req.constraint, isolated=isolated, user_supplied=user_supplied, ) else: req = install_req_from_line( parsed_req.requirement, comes_from=parsed_req.comes_from, use_pep517=use_pep517, isolated=isolated, options=parsed_req.options, constraint=parsed_req.constraint, line_source=parsed_req.line_source, user_supplied=user_supplied, ) return req exceptions.py000064400000030535152347654150007321 0ustar00"""Exceptions used throughout package""" from __future__ import absolute_import from itertools import chain, groupby, repeat from pip._vendor.six import iteritems from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Optional, List, Dict, Text from pip._vendor.pkg_resources import Distribution from pip._vendor.requests.models import Response, Request from pip._vendor.six import PY3 from pip._vendor.six.moves import configparser from pip._internal.req.req_install import InstallRequirement if PY3: from hashlib import _Hash else: from hashlib import _hash as _Hash class PipError(Exception): """Base pip exception""" class ConfigurationError(PipError): """General exception in configuration""" class InstallationError(PipError): """General exception during installation""" class UninstallationError(PipError): """General exception during uninstallation""" class NoneMetadataError(PipError): """ Raised when accessing "METADATA" or "PKG-INFO" metadata for a pip._vendor.pkg_resources.Distribution object and `dist.has_metadata('METADATA')` returns True but `dist.get_metadata('METADATA')` returns None (and similarly for "PKG-INFO"). """ def __init__(self, dist, metadata_name): # type: (Distribution, str) -> None """ :param dist: A Distribution object. :param metadata_name: The name of the metadata being accessed (can be "METADATA" or "PKG-INFO"). """ self.dist = dist self.metadata_name = metadata_name def __str__(self): # type: () -> str # Use `dist` in the error message because its stringification # includes more information, like the version and location. return ( 'None {} metadata found for distribution: {}'.format( self.metadata_name, self.dist, ) ) class DistributionNotFound(InstallationError): """Raised when a distribution cannot be found to satisfy a requirement""" class RequirementsFileParseError(InstallationError): """Raised when a general error occurs parsing a requirements file line.""" class BestVersionAlreadyInstalled(PipError): """Raised when the most up-to-date version of a package is already installed.""" class BadCommand(PipError): """Raised when virtualenv or a command is not found""" class CommandError(PipError): """Raised when there is an error in command-line arguments""" class SubProcessError(PipError): """Raised when there is an error raised while executing a command in subprocess""" class PreviousBuildDirError(PipError): """Raised when there's a previous conflicting build directory""" class NetworkConnectionError(PipError): """HTTP connection error""" def __init__(self, error_msg, response=None, request=None): # type: (Text, Response, Request) -> None """ Initialize NetworkConnectionError with `request` and `response` objects. """ self.response = response self.request = request self.error_msg = error_msg if (self.response is not None and not self.request and hasattr(response, 'request')): self.request = self.response.request super(NetworkConnectionError, self).__init__( error_msg, response, request) def __str__(self): # type: () -> str return str(self.error_msg) class InvalidWheelFilename(InstallationError): """Invalid wheel filename.""" class UnsupportedWheel(InstallationError): """Unsupported wheel.""" class MetadataInconsistent(InstallationError): """Built metadata contains inconsistent information. This is raised when the metadata contains values (e.g. name and version) that do not match the information previously obtained from sdist filename or user-supplied ``#egg=`` value. """ def __init__(self, ireq, field, built): # type: (InstallRequirement, str, Any) -> None self.ireq = ireq self.field = field self.built = built def __str__(self): # type: () -> str return "Requested {} has different {} in metadata: {!r}".format( self.ireq, self.field, self.built, ) class HashErrors(InstallationError): """Multiple HashError instances rolled into one for reporting""" def __init__(self): # type: () -> None self.errors = [] # type: List[HashError] def append(self, error): # type: (HashError) -> None self.errors.append(error) def __str__(self): # type: () -> str lines = [] self.errors.sort(key=lambda e: e.order) for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__): lines.append(cls.head) lines.extend(e.body() for e in errors_of_cls) if lines: return '\n'.join(lines) return '' def __nonzero__(self): # type: () -> bool return bool(self.errors) def __bool__(self): # type: () -> bool return self.__nonzero__() class HashError(InstallationError): """ A failure to verify a package against known-good hashes :cvar order: An int sorting hash exception classes by difficulty of recovery (lower being harder), so the user doesn't bother fretting about unpinned packages when he has deeper issues, like VCS dependencies, to deal with. Also keeps error reports in a deterministic order. :cvar head: A section heading for display above potentially many exceptions of this kind :ivar req: The InstallRequirement that triggered this error. This is pasted on after the exception is instantiated, because it's not typically available earlier. """ req = None # type: Optional[InstallRequirement] head = '' order = None # type: Optional[int] def body(self): # type: () -> str """Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with its link already populated by the resolver's _populate_link(). """ return ' {}'.format(self._requirement_name()) def __str__(self): # type: () -> str return '{}\n{}'.format(self.head, self.body()) def _requirement_name(self): # type: () -> str """Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers """ return str(self.req) if self.req else 'unknown package' class VcsHashUnsupported(HashError): """A hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.""" order = 0 head = ("Can't verify hashes for these requirements because we don't " "have a way to hash version control repositories:") class DirectoryUrlHashUnsupported(HashError): """A hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.""" order = 1 head = ("Can't verify hashes for these file:// requirements because they " "point to directories:") class HashMissing(HashError): """A hash was needed for a requirement but is absent.""" order = 2 head = ('Hashes are required in --require-hashes mode, but they are ' 'missing from some requirements. Here is a list of those ' 'requirements along with the hashes their downloaded archives ' 'actually had. Add lines like these to your requirements files to ' 'prevent tampering. (If you did not enable --require-hashes ' 'manually, note that it turns on automatically when any package ' 'has a hash.)') def __init__(self, gotten_hash): # type: (str) -> None """ :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded """ self.gotten_hash = gotten_hash def body(self): # type: () -> str # Dodge circular import. from pip._internal.utils.hashes import FAVORITE_HASH package = None if self.req: # In the case of URL-based requirements, display the original URL # seen in the requirements file rather than the package name, # so the output can be directly copied into the requirements file. package = (self.req.original_link if self.req.original_link # In case someone feeds something downright stupid # to InstallRequirement's constructor. else getattr(self.req, 'req', None)) return ' {} --hash={}:{}'.format(package or 'unknown package', FAVORITE_HASH, self.gotten_hash) class HashUnpinned(HashError): """A requirement had a hash specified but was not pinned to a specific version.""" order = 3 head = ('In --require-hashes mode, all requirements must have their ' 'versions pinned with ==. These do not:') class HashMismatch(HashError): """ Distribution file hash values don't match. :ivar package_name: The name of the package that triggered the hash mismatch. Feel free to write to this after the exception is raise to improve its error message. """ order = 4 head = ('THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS ' 'FILE. If you have updated the package versions, please update ' 'the hashes. Otherwise, examine the package contents carefully; ' 'someone may have tampered with them.') def __init__(self, allowed, gots): # type: (Dict[str, List[str]], Dict[str, _Hash]) -> None """ :param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion """ self.allowed = allowed self.gots = gots def body(self): # type: () -> str return ' {}:\n{}'.format(self._requirement_name(), self._hash_comparison()) def _hash_comparison(self): # type: () -> str """ Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef """ def hash_then_or(hash_name): # type: (str) -> chain[str] # For now, all the decent hashes have 6-char names, so we can get # away with hard-coding space literals. return chain([hash_name], repeat(' or')) lines = [] # type: List[str] for hash_name, expecteds in iteritems(self.allowed): prefix = hash_then_or(hash_name) lines.extend((' Expected {} {}'.format(next(prefix), e)) for e in expecteds) lines.append(' Got {}\n'.format( self.gots[hash_name].hexdigest())) return '\n'.join(lines) class UnsupportedPythonVersion(InstallationError): """Unsupported python version according to Requires-Python package metadata.""" class ConfigurationFileCouldNotBeLoaded(ConfigurationError): """When there are errors while loading a configuration file """ def __init__(self, reason="could not be loaded", fname=None, error=None): # type: (str, Optional[str], Optional[configparser.Error]) -> None super(ConfigurationFileCouldNotBeLoaded, self).__init__(error) self.reason = reason self.fname = fname self.error = error def __str__(self): # type: () -> str if self.fname is not None: message_part = " in {}.".format(self.fname) else: assert self.error is not None message_part = ".\n{}\n".format(self.error) return "Configuration file {}{}".format(self.reason, message_part) locations.py000064400000015114152347654150007127 0ustar00"""Locations where we look for configs, install stuff, etc""" # The following comment should be removed at some point in the future. # mypy: strict-optional=False from __future__ import absolute_import import os import os.path import platform import site import sys import sysconfig from distutils import sysconfig as distutils_sysconfig from distutils.command.install import SCHEME_KEYS # type: ignore from distutils.command.install import install as distutils_install_command from pip._internal.models.scheme import Scheme from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast from pip._internal.utils.virtualenv import running_under_virtualenv if MYPY_CHECK_RUNNING: from typing import Dict, List, Optional, Union from distutils.cmd import Command as DistutilsCommand # Application Directories USER_CACHE_DIR = appdirs.user_cache_dir("pip") def get_major_minor_version(): # type: () -> str """ Return the major-minor version of the current Python as a string, e.g. "3.7" or "3.10". """ return '{}.{}'.format(*sys.version_info) def get_src_prefix(): # type: () -> str if running_under_virtualenv(): src_prefix = os.path.join(sys.prefix, 'src') else: # FIXME: keep src in cwd for now (it is not a temporary folder) try: src_prefix = os.path.join(os.getcwd(), 'src') except OSError: # In case the current working directory has been renamed or deleted sys.exit( "The folder you are executing pip from can no longer be found." ) # under macOS + virtualenv sys.prefix is not properly resolved # it is something like /path/to/python/bin/.. return os.path.abspath(src_prefix) # FIXME doesn't account for venv linked to global site-packages site_packages = sysconfig.get_path("purelib") # type: Optional[str] # This is because of a bug in PyPy's sysconfig module, see # https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths # for more information. if platform.python_implementation().lower() == "pypy": site_packages = distutils_sysconfig.get_python_lib() try: # Use getusersitepackages if this is present, as it ensures that the # value is initialised properly. user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE if WINDOWS: bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') # buildout uses 'bin' on Windows too? if not os.path.exists(bin_py): bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') else: bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') # Forcing to use /usr/local/bin for standard macOS framework installs # Also log to ~/Library/Logs/ for use with the Console.app log viewer if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/': bin_py = '/usr/local/bin' def distutils_scheme( dist_name, user=False, home=None, root=None, isolated=False, prefix=None ): # type:(str, bool, str, str, bool, str) -> Dict[str, str] """ Return a distutils install scheme """ from distutils.dist import Distribution dist_args = {'name': dist_name} # type: Dict[str, Union[str, List[str]]] if isolated: dist_args["script_args"] = ["--no-user-cfg"] d = Distribution(dist_args) d.parse_config_files() obj = None # type: Optional[DistutilsCommand] obj = d.get_command_obj('install', create=True) assert obj is not None i = cast(distutils_install_command, obj) # NOTE: setting user or home has the side-effect of creating the home dir # or user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. assert not (user and prefix), "user={} prefix={}".format(user, prefix) assert not (home and prefix), "home={} prefix={}".format(home, prefix) i.user = user or i.user if user or home: i.prefix = "" i.prefix = prefix or i.prefix i.home = home or i.home i.root = root or i.root i.finalize_options() scheme = {} for key in SCHEME_KEYS: scheme[key] = getattr(i, 'install_' + key) # install_lib specified in setup.cfg should install *everything* # into there (i.e. it takes precedence over both purelib and # platlib). Note, i.install_lib is *always* set after # finalize_options(); we only want to override here if the user # has explicitly requested it hence going back to the config if 'install_lib' in d.get_option_dict('install'): scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib)) if running_under_virtualenv(): scheme['headers'] = os.path.join( i.prefix, 'include', 'site', 'python{}'.format(get_major_minor_version()), dist_name, ) if root is not None: path_no_drive = os.path.splitdrive( os.path.abspath(scheme["headers"]))[1] scheme["headers"] = os.path.join( root, path_no_drive[1:], ) return scheme def get_scheme( dist_name, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] isolated=False, # type: bool prefix=None, # type: Optional[str] ): # type: (...) -> Scheme """ Get the "scheme" corresponding to the input parameters. The distutils documentation provides the context for the available schemes: https://docs.python.org/3/install/index.html#alternate-installation :param dist_name: the name of the package to retrieve the scheme for, used in the headers scheme path :param user: indicates to use the "user" scheme :param home: indicates to use the "home" scheme and provides the base directory for the same :param root: root under which other directories are re-based :param isolated: equivalent to --no-user-cfg, i.e. do not consider ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for scheme paths :param prefix: indicates to use the "prefix" scheme and provides the base directory for the same """ scheme = distutils_scheme( dist_name, user, home, root, isolated, prefix ) return Scheme( platlib=scheme["platlib"], purelib=scheme["purelib"], headers=scheme["headers"], scripts=scheme["scripts"], data=scheme["data"], ) main.py000064400000000665152347654150006065 0ustar00from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, List def main(args=None): # type: (Optional[List[str]]) -> int """This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper return _wrapper(args) wheel.py000064400000124110152347654150006235 0ustar00""" Support for installing and building the "wheel" binary package format. """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False from __future__ import absolute_import import collections import compileall import csv import hashlib import logging import os.path import re import shutil import stat import sys import warnings from base64 import urlsafe_b64encode from email.parser import Parser from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six import StringIO from pip._internal import pep425tags from pip._internal.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.locations import distutils_scheme, get_major_minor_version from pip._internal.models.link import Link from pip._internal.utils.logging import indent_log from pip._internal.utils.marker_files import has_delete_marker_file from pip._internal.utils.misc import captured_stdout, ensure_dir, read_chunks from pip._internal.utils.setuptools_build import make_setuptools_shim_args from pip._internal.utils.subprocess import ( LOG_DIVIDER, call_subprocess, format_command_args, runner_with_spinner_message, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.ui import open_spinner from pip._internal.utils.unpacking import unpack_file from pip._internal.utils.urls import path_to_url if MYPY_CHECK_RUNNING: from typing import ( Dict, List, Optional, Sequence, Mapping, Tuple, IO, Text, Any, Iterable, Callable, Set, ) from pip._vendor.packaging.requirements import Requirement from pip._internal.req.req_install import InstallRequirement from pip._internal.operations.prepare import ( RequirementPreparer ) from pip._internal.cache import WheelCache from pip._internal.pep425tags import Pep425Tag InstalledCSVRow = Tuple[str, ...] BinaryAllowedPredicate = Callable[[InstallRequirement], bool] VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) def normpath(src, p): return os.path.relpath(src, p).replace(os.path.sep, '/') def hash_file(path, blocksize=1 << 20): # type: (str, int) -> Tuple[Any, int] """Return (hash, length) for path using hashlib.sha256()""" h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) return (h, length) # type: ignore def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') # unicode/str python2 issues return (digest, str(length)) # type: ignore def open_for_csv(name, mode): # type: (str, Text) -> IO if sys.version_info[0] < 3: nl = {} # type: Dict[str, Any] bin = 'b' else: nl = {'newline': ''} # type: Dict[str, Any] bin = '' return open(name, mode + bin, **nl) def replace_python_tag(wheelname, new_tag): # type: (str, str) -> str """Replace the Python tag in a wheel file name with a new value. """ parts = wheelname.split('-') parts[-3] = new_tag return '-'.join(parts) def fix_script(path): # type: (str) -> Optional[bool] """Replace #!python with #!/path/to/python Return True if file was changed.""" # XXX RECORD hashes will need to be updated if os.path.isfile(path): with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True return None dist_info_re = re.compile(r"""^(?P(?P.+?)(-(?P.+?))?) \.dist-info$""", re.VERBOSE) def root_is_purelib(name, wheeldir): # type: (str, str) -> bool """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False def get_entrypoints(filename): # type: (str) -> Tuple[Dict[str, str], Dict[str, str]] if not os.path.exists(filename): return {}, {} # This is done because you can pass a string to entry_points wrappers which # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. with open(filename) as fp: data = StringIO() for line in fp: data.write(line.strip()) data.write("\n") data.seek(0) # get the entry points and then the script names entry_points = pkg_resources.EntryPoint.parse_map(data) console = entry_points.get('console_scripts', {}) gui = entry_points.get('gui_scripts', {}) def _split_ep(s): """get the string representation of EntryPoint, remove space and split on '='""" return str(s).replace(" ", "").split("=") # convert the EntryPoint objects into strings with module:function console = dict(_split_ep(v) for v in console.values()) gui = dict(_split_ep(v) for v in gui.values()) return console, gui def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scripts by the path they were installed in grouped_by_dir = collections.defaultdict(set) # type: Dict[str, Set[str]] for destfile in scripts: parent_dir = os.path.dirname(destfile) script_name = os.path.basename(destfile) grouped_by_dir[parent_dir].add(script_name) # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable))) warn_for = { parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items() if os.path.normcase(parent_dir) not in not_warn_dirs } # type: Dict[str, Set[str]] if not warn_for: return None # Format a message msg_lines = [] for parent_dir, dir_scripts in warn_for.items(): sorted_scripts = sorted(dir_scripts) # type: List[str] if len(sorted_scripts) == 1: start_text = "script {} is".format(sorted_scripts[0]) else: start_text = "scripts {} are".format( ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1] ) msg_lines.append( "The {} installed in '{}' which is not on PATH." .format(start_text, parent_dir) ) last_line_fmt = ( "Consider adding {} to PATH or, if you prefer " "to suppress this warning, use --no-warn-script-location." ) if len(msg_lines) == 1: msg_lines.append(last_line_fmt.format("this directory")) else: msg_lines.append(last_line_fmt.format("these directories")) # Returns the formatted multiline message return "\n".join(msg_lines) def sorted_outrows(outrows): # type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow] """ Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. """ # Normally, there should only be one row per path, in which case the # second and third elements don't come into play when sorting. # However, in cases in the wild where a path might happen to occur twice, # we don't want the sort operation to trigger an error (but still want # determinism). Since the third element can be an int or string, we # coerce each element to a string to avoid a TypeError in this case. # For additional background, see-- # https://github.com/pypa/pip/issues/5868 return sorted(outrows, key=lambda row: tuple(str(x) for x in row)) def get_csv_rows_for_installed( old_csv_rows, # type: Iterable[List[str]] installed, # type: Dict[str, str] changed, # type: set generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to installation RECORD path. """ installed_rows = [] # type: List[InstalledCSVRow] for row in old_csv_rows: if len(row) > 3: logger.warning( 'RECORD line has more than three elements: {}'.format(row) ) # Make a copy because we are mutating the row. row = list(row) old_path = row[0] new_path = installed.pop(old_path, old_path) row[0] = new_path if new_path in changed: digest, length = rehash(new_path) row[1] = digest row[2] = length installed_rows.append(tuple(row)) for f in generated: digest, length = rehash(f) installed_rows.append((normpath(f, lib_dir), digest, str(length))) for f in installed: installed_rows.append((installed[f], '', '')) return installed_rows class MissingCallableSuffix(Exception): pass def _raise_for_invalid_entrypoint(specification): entry = get_export_entry(specification) if entry is not None and entry.suffix is None: raise MissingCallableSuffix(str(entry)) class PipScriptMaker(ScriptMaker): def make(self, specification, options=None): _raise_for_invalid_entrypoint(specification) return super(PipScriptMaker, self).make(specification, options) def move_wheel_files( name, # type: str req, # type: Requirement wheeldir, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] pycompile=True, # type: bool scheme=None, # type: Optional[Mapping[str, str]] isolated=False, # type: bool prefix=None, # type: Optional[str] warn_script_location=True # type: bool ): # type: (...) -> None """Install a wheel""" # TODO: Investigate and break this up. # TODO: Look into moving this into a dedicated class for representing an # installation. if not scheme: scheme = distutils_scheme( name, user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] # type: List[str] data_dirs = [] source = wheeldir.rstrip(os.path.sep) + os.path.sep # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} # type: Dict[str, str] changed = set() generated = [] # type: List[str] # Compile all of the pyc files that we're going to be installing if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') compileall.compile_dir(source, force=True, quiet=True) logger.debug(stdout.getvalue()) def record_installed(srcfile, destfile, modified=False): """Map archive RECORD paths to installation RECORD paths.""" oldpath = normpath(srcfile, wheeldir) newpath = normpath(destfile, lib_dir) installed[oldpath] = newpath if modified: changed.add(destfile) def clobber(source, dest, is_base, fixer=None, filter=None): ensure_dir(dest) # common for the 'include' path for dir, subdirs, files in os.walk(source): basedir = dir[len(source):].lstrip(os.path.sep) destdir = os.path.join(dest, basedir) if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'): continue for s in subdirs: destsubdir = os.path.join(dest, basedir, s) if is_base and basedir == '' and destsubdir.endswith('.data'): data_dirs.append(s) continue elif (is_base and s.endswith('.dist-info') and canonicalize_name(s).startswith( canonicalize_name(req.name))): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir)) info_dir.append(destsubdir) for f in files: # Skip unwanted files if filter and filter(f): continue srcfile = os.path.join(dir, f) destfile = os.path.join(dest, basedir, f) # directory creation is lazy and after the file filtering above # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. ensure_dir(destdir) # copyfile (called below) truncates the destination if it # exists and then writes the new contents. This is fine in most # cases, but can cause a segfault if pip has loaded a shared # object (e.g. from pyopenssl through its vendored urllib3) # Since the shared object is mmap'd an attempt to call a # symbol in it will then cause a segfault. Unlinking the file # allows writing of new contents while allowing the process to # continue to use the old copy. if os.path.exists(destfile): os.unlink(destfile) # We use copyfile (not move, copy, or copy2) to be extra sure # that we are not moving directories over (copyfile fails for # directories) as well as to ensure that we are not copying # over any metadata because we want more control over what # metadata we actually copy over. shutil.copyfile(srcfile, destfile) # Copy over the metadata for the file, currently this only # includes the atime and mtime. st = os.stat(srcfile) if hasattr(os, "utime"): os.utime(destfile, (st.st_atime, st.st_mtime)) # If our file is executable, then make our destination file # executable. if os.access(srcfile, os.X_OK): st = os.stat(srcfile) permissions = ( st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) os.chmod(destfile, permissions) changed = False if fixer: changed = fixer(destfile) record_installed(srcfile, destfile, changed) clobber(source, lib_dir, True) assert info_dir, "%s .dist-info directory not found" % req # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file) def is_entrypoint_wrapper(name): # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) for datadir in data_dirs: fixer = None filter = None for subdir in os.listdir(os.path.join(wheeldir, datadir)): fixer = None if subdir == 'scripts': fixer = fix_script filter = is_entrypoint_wrapper source = os.path.join(wheeldir, datadir, subdir) dest = scheme[subdir] clobber(source, dest, False, fixer=fixer, filter=filter) maker = PipScriptMaker(None, scheme['scripts']) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = {''} # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True scripts_to_generate = [] # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadata 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append('pip = ' + pip_script) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": scripts_to_generate.append( 'pip%s = %s' % (sys.version_info[0], pip_script) ) scripts_to_generate.append( 'pip%s = %s' % (get_major_minor_version(), pip_script) ) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append( 'easy_install = ' + easy_install_script ) scripts_to_generate.append( 'easy_install-%s = %s' % ( get_major_minor_version(), easy_install_script ) ) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console and GUI entry points specified in the wheel scripts_to_generate.extend( '%s = %s' % kv for kv in console.items() ) gui_scripts_to_generate = [ '%s = %s' % kv for kv in gui.items() ] generated_console_scripts = [] # type: List[str] try: generated_console_scripts = maker.make_multiple(scripts_to_generate) generated.extend(generated_console_scripts) generated.extend( maker.make_multiple(gui_scripts_to_generate, {'gui': True}) ) except MissingCallableSuffix as e: entry = e.args[0] raise InstallationError( "Invalid script entry point: {} for req: {} - A callable " "suffix is required. Cf https://packaging.python.org/en/" "latest/distributing.html#console-scripts for more " "information.".format(entry, req) ) if warn_script_location: msg = message_about_scripts_not_on_PATH(generated_console_scripts) if msg is not None: logger.warning(msg) # Record pip as the installer installer = os.path.join(info_dir[0], 'INSTALLER') temp_installer = os.path.join(info_dir[0], 'INSTALLER.pip') with open(temp_installer, 'wb') as installer_file: installer_file.write(b'pip\n') shutil.move(temp_installer, installer) generated.append(installer) # Record details of all files installed record = os.path.join(info_dir[0], 'RECORD') temp_record = os.path.join(info_dir[0], 'RECORD.pip') with open_for_csv(record, 'r') as record_in: with open_for_csv(temp_record, 'w+') as record_out: reader = csv.reader(record_in) outrows = get_csv_rows_for_installed( reader, installed=installed, changed=changed, generated=generated, lib_dir=lib_dir, ) writer = csv.writer(record_out) # Sort to simplify testing. for row in sorted_outrows(outrows): writer.writerow(row) shutil.move(temp_record, record) def wheel_version(source_dir): # type: (Optional[str]) -> Optional[Tuple[int, ...]] """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except Exception: return None def check_compatibility(version, name): # type: (Optional[Tuple[int, ...]], str) -> None """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) def format_tag(file_tag): # type: (Tuple[str, ...]) -> str """ Format three tags in the form "--". :param file_tag: A 3-tuple of tags (python_tag, abi_tag, platform_tag). """ return '-'.join(file_tag) class Wheel(object): """A wheel file""" # TODO: Maybe move the class into the models sub-package # TODO: Maybe move the install code into this class wheel_file_re = re.compile( r"""^(?P(?P.+?)-(?P.*?)) ((-(?P\d[^-]*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): # type: (str) -> None """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ 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('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.build_tag = wheel_info.group('build') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = { (x, y, z) for x in self.pyversions for y in self.abis for z in self.plats } def get_formatted_file_tags(self): # type: () -> List[str] """ Return the wheel's tags as a sorted list of strings. """ return sorted(format_tag(tag) for tag in self.file_tags) def support_index_min(self, tags): # type: (List[Pep425Tag]) -> int """ Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. """ return min(tags.index(tag) for tag in self.file_tags if tag in tags) def supported(self, tags): # type: (List[Pep425Tag]) -> bool """ Return whether the wheel is compatible with one of the given tags. :param tags: the PEP 425 tags to check the wheel against. """ return not self.file_tags.isdisjoint(tags) def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s)) def should_use_ephemeral_cache( req, # type: InstallRequirement should_unpack, # type: bool cache_available, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> Optional[bool] """ Return whether to build an InstallRequirement object using the ephemeral cache. :param cache_available: whether a cache directory is available for the should_unpack=True case. :return: True or False to build the requirement with ephem_cache=True or False, respectively; or None not to build the requirement. """ if req.constraint: # never build requirements that are merely constraints return None if req.is_wheel: if not should_unpack: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) return None if not should_unpack: # i.e. pip wheel, not pip install; # return False, knowing that the caller will never cache # in this case anyway, so this return merely means "build it". # TODO improve this behavior return False if req.editable or not req.source_dir: return None if not check_binary_allowed(req): logger.info( "Skipping wheel build for %s, due to binaries " "being disabled for it.", req.name, ) return None if req.link and req.link.is_vcs: # VCS checkout. Build wheel just for this run. return True link = req.link base, ext = link.splitext() if cache_available and _contains_egg_info(base): return False # Otherwise, build the wheel just for this run using the ephemeral # cache since we are either in the case of e.g. a local directory, or # no cache directory is available to use. return True def format_command_result( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ command_desc = format_command_args(command_args) text = 'Command arguments: {}\n'.format(command_desc) if not command_output: text += 'Command output: None' elif logger.getEffectiveLevel() > logging.DEBUG: text += 'Command output: [use --verbose to show]' else: if not command_output.endswith('\n'): command_output += '\n' text += 'Command output:\n{}{}'.format(command_output, LOG_DIVIDER) return text def get_legacy_build_wheel_path( names, # type: List[str] temp_dir, # type: str req, # type: InstallRequirement command_args, # type: List[str] command_output, # type: str ): # type: (...) -> Optional[str] """ Return the path to the wheel in the temporary build directory. """ # Sort for determinism. names = sorted(names) if not names: msg = ( 'Legacy build of wheel for {!r} created no files.\n' ).format(req.name) msg += format_command_result(command_args, command_output) logger.warning(msg) return None if len(names) > 1: msg = ( 'Legacy build of wheel for {!r} created more than one file.\n' 'Filenames (choosing first): {}\n' ).format(req.name, names) msg += format_command_result(command_args, command_output) logger.warning(msg) return os.path.join(temp_dir, names[0]) def _always_true(_): return True class WheelBuilder(object): """Build wheels from a RequirementSet.""" def __init__( self, preparer, # type: RequirementPreparer wheel_cache, # type: WheelCache build_options=None, # type: Optional[List[str]] global_options=None, # type: Optional[List[str]] check_binary_allowed=None, # type: Optional[BinaryAllowedPredicate] no_clean=False # type: bool ): # type: (...) -> None if check_binary_allowed is None: # Binaries allowed by default. check_binary_allowed = _always_true self.preparer = preparer self.wheel_cache = wheel_cache self._wheel_dir = preparer.wheel_download_dir self.build_options = build_options or [] self.global_options = global_options or [] self.check_binary_allowed = check_binary_allowed self.no_clean = no_clean def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ # Install build deps into temporary directory (PEP 518) with req.build_env: return self._build_one_inside_env(req, output_dir, python_tag=python_tag) def _build_one_inside_env(self, req, output_dir, python_tag=None): with TempDirectory(kind="wheel") as temp_dir: if req.use_pep517: builder = self._build_one_pep517 else: builder = self._build_one_legacy wheel_path = builder(req, temp_dir.path, python_tag=python_tag) if wheel_path is not None: wheel_name = os.path.basename(wheel_path) dest_path = os.path.join(output_dir, wheel_name) try: wheel_hash, length = hash_file(wheel_path) shutil.move(wheel_path, dest_path) logger.info('Created wheel for %s: ' 'filename=%s size=%d sha256=%s', req.name, wheel_name, length, wheel_hash.hexdigest()) logger.info('Stored in directory: %s', output_dir) return dest_path except Exception: pass # Ignore return, we can't do anything else useful. self._clean_one(req) return None def _base_setup_args(self, req): # NOTE: Eventually, we'd want to also -S to the flags here, when we're # isolating. Currently, it breaks Python in virtualenvs, because it # relies on site.py to find parts of the standard library outside the # virtualenv. return make_setuptools_shim_args( req.setup_py_path, global_options=self.global_options, unbuffered_output=True ) def _build_one_pep517(self, req, tempd, python_tag=None): """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. """ assert req.metadata_directory is not None if self.build_options: # PEP 517 does not support --build-options logger.error('Cannot build wheel for %s using PEP 517 when ' '--build-options is present' % (req.name,)) return None try: logger.debug('Destination directory: %s', tempd) runner = runner_with_spinner_message( 'Building wheel for {} (PEP 517)'.format(req.name) ) backend = req.pep517_backend with backend.subprocess_runner(runner): wheel_name = backend.build_wheel( tempd, metadata_directory=req.metadata_directory, ) if python_tag: # General PEP 517 backends don't necessarily support # a "--python-tag" option, so we rename the wheel # file directly. new_name = replace_python_tag(wheel_name, python_tag) os.rename( os.path.join(tempd, wheel_name), os.path.join(tempd, new_name) ) # Reassign to simplify the return at the end of function wheel_name = new_name except Exception: logger.error('Failed building wheel for %s', req.name) return None return os.path.join(tempd, wheel_name) def _build_one_legacy(self, req, tempd, python_tag=None): """Build one InstallRequirement using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. """ base_args = self._base_setup_args(req) spin_message = 'Building wheel for %s (setup.py)' % (req.name,) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) wheel_args = base_args + ['bdist_wheel', '-d', tempd] \ + self.build_options if python_tag is not None: wheel_args += ["--python-tag", python_tag] try: output = call_subprocess( wheel_args, cwd=req.unpacked_source_directory, spinner=spinner, ) except Exception: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return None names = os.listdir(tempd) wheel_path = get_legacy_build_wheel_path( names=names, temp_dir=tempd, req=req, command_args=wheel_args, command_output=output, ) return wheel_path def _clean_one(self, req): base_args = self._base_setup_args(req) logger.info('Running setup.py clean for %s', req.name) clean_args = base_args + ['clean', '--all'] try: call_subprocess(clean_args, cwd=req.source_dir) return True except Exception: logger.error('Failed cleaning build dir for %s', req.name) return False def build( self, requirements, # type: Iterable[InstallRequirement] should_unpack=False # type: bool ): # type: (...) -> List[InstallRequirement] """Build wheels. :param should_unpack: If True, after building the wheel, unpack it and replace the sdist with the unpacked version in preparation for installation. :return: True if all the wheels built correctly. """ # pip install uses should_unpack=True. # pip install never provides a _wheel_dir. # pip wheel uses should_unpack=False. # pip wheel always provides a _wheel_dir (via the preparer). assert ( (should_unpack and not self._wheel_dir) or (not should_unpack and self._wheel_dir) ) buildset = [] cache_available = bool(self.wheel_cache.cache_dir) for req in requirements: ephem_cache = should_use_ephemeral_cache( req, should_unpack=should_unpack, cache_available=cache_available, check_binary_allowed=self.check_binary_allowed, ) if ephem_cache is None: continue # Determine where the wheel should go. if should_unpack: if ephem_cache: output_dir = self.wheel_cache.get_ephem_path_for_link( req.link ) else: output_dir = self.wheel_cache.get_path_for_link(req.link) else: output_dir = self._wheel_dir buildset.append((req, output_dir)) if not buildset: return [] # TODO by @pradyunsg # Should break up this method into 2 separate methods. # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for (req, _) in buildset]), ) python_tag = None if should_unpack: python_tag = pep425tags.implementation_tag with indent_log(): build_success, build_failure = [], [] for req, output_dir in buildset: try: ensure_dir(output_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) build_failure.append(req) continue wheel_file = self._build_one( req, output_dir, python_tag=python_tag, ) if wheel_file: build_success.append(req) if should_unpack: # XXX: This is mildly duplicative with prepare_files, # but not close enough to pull out to a single common # method. # The code below assumes temporary source dirs - # prevent it doing bad things. if ( req.source_dir and not has_delete_marker_file(req.source_dir) ): raise AssertionError( "bad source dir - missing marker") # Delete the source we built the wheel from req.remove_temporary_source() # set the build directory again - name is known from # the work prepare_files did. req.source_dir = req.ensure_build_location( self.preparer.build_dir ) # Update the link for this. req.link = Link(path_to_url(wheel_file)) assert req.link.is_wheel # extract the wheel into the dir unpack_file(req.link.file_path, req.source_dir) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return a list of requirements that failed to build return build_failure distributions/__pycache__/base.cpython-38.opt-1.pyc000064400000003124152347654150016173 0ustar00U .eT@s2ddlZddlmZeejGdddeZdS)N) add_metaclasscs<eZdZdZfddZejddZejddZZ S)AbstractDistributiona A base class for handling installable artifacts. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. cstt|||_dSN)superr__init__req)selfr __class__D/usr/lib/python3.8/site-packages/pip/_internal/distributions/base.pyrszAbstractDistribution.__init__cCs tdSrNotImplementedError)rr r r get_pkg_resources_distributionsz3AbstractDistribution.get_pkg_resources_distributioncCs tdSrr )rfinderZbuild_isolationr r r prepare_distribution_metadata"sz2AbstractDistribution.prepare_distribution_metadata) __name__ __module__ __qualname____doc__rabcabstractmethodrr __classcell__r r r r r s   r)rZpip._vendor.sixrABCMetaobjectrr r r r s distributions/__pycache__/wheel.cpython-38.pyc000064400000002000152347654150015416 0ustar00U .eh@s,ddlmZddlmZGdddeZdS)) pkg_resources)AbstractDistributionc@s eZdZdZddZddZdS)WheelDistributionzqRepresents a wheel distribution. This does not need any preparation as wheels can be directly unpacked. cCstt|jjdS)Nr)listrfind_distributionsZreqZ source_dir)selfrE/usr/lib/python3.8/site-packages/pip/_internal/distributions/wheel.pyget_pkg_resources_distributions z0WheelDistribution.get_pkg_resources_distributioncCsdS)Nr)rfinderZbuild_isolationrrr prepare_distribution_metadatasz/WheelDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__r r rrrr r srN)Z pip._vendorrZ pip._internal.distributions.baserrrrrr s  distributions/__pycache__/wheel.cpython-38.opt-1.pyc000064400000002000152347654150016355 0ustar00U .eh@s,ddlmZddlmZGdddeZdS)) pkg_resources)AbstractDistributionc@s eZdZdZddZddZdS)WheelDistributionzqRepresents a wheel distribution. This does not need any preparation as wheels can be directly unpacked. cCstt|jjdS)Nr)listrfind_distributionsZreqZ source_dir)selfrE/usr/lib/python3.8/site-packages/pip/_internal/distributions/wheel.pyget_pkg_resources_distributions z0WheelDistribution.get_pkg_resources_distributioncCsdS)Nr)rfinderZbuild_isolationrrr prepare_distribution_metadatasz/WheelDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__r r rrrr r srN)Z pip._vendorrZ pip._internal.distributions.baserrrrrr s  distributions/__pycache__/installed.cpython-38.pyc000064400000001700152347654150016277 0ustar00U .e@s ddlmZGdddeZdS))AbstractDistributionc@s eZdZdZddZddZdS)InstalledDistributionzRepresents an installed package. This does not need any preparation as the required information has already been computed. cCs|jjSN)ZreqZ satisfied_by)selfrI/usr/lib/python3.8/site-packages/pip/_internal/distributions/installed.pyget_pkg_resources_distributionsz4InstalledDistribution.get_pkg_resources_distributioncCsdSrr)rfinderZbuild_isolationrrrprepare_distribution_metadatasz3InstalledDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__rr rrrrrsrN)Z pip._internal.distributions.baserrrrrrs distributions/__pycache__/__init__.cpython-38.pyc000064400000001464152347654150016066 0ustar00U .e@sLddlmZddlmZddlmZer@ddlmZddlm Z ddZ dS) )SourceDistribution)WheelDistribution)MYPY_CHECK_RUNNING)AbstractDistribution)InstallRequirementcCs$|jrt|S|jrt|St|S)zs     distributions/__pycache__/installed.cpython-38.opt-1.pyc000064400000001700152347654150017236 0ustar00U .e@s ddlmZGdddeZdS))AbstractDistributionc@s eZdZdZddZddZdS)InstalledDistributionzRepresents an installed package. This does not need any preparation as the required information has already been computed. cCs|jjSN)ZreqZ satisfied_by)selfrI/usr/lib/python3.8/site-packages/pip/_internal/distributions/installed.pyget_pkg_resources_distributionsz4InstalledDistribution.get_pkg_resources_distributioncCsdSrr)rfinderZbuild_isolationrrrprepare_distribution_metadatasz3InstalledDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__rr rrrrrsrN)Z pip._internal.distributions.baserrrrrrs distributions/__pycache__/base.cpython-38.pyc000064400000003124152347654150015234 0ustar00U .eT@s2ddlZddlmZeejGdddeZdS)N) add_metaclasscs<eZdZdZfddZejddZejddZZ S)AbstractDistributiona A base class for handling installable artifacts. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. cstt|||_dSN)superr__init__req)selfr __class__D/usr/lib/python3.8/site-packages/pip/_internal/distributions/base.pyrszAbstractDistribution.__init__cCs tdSrNotImplementedError)rr r r get_pkg_resources_distributionsz3AbstractDistribution.get_pkg_resources_distributioncCs tdSrr )rfinderZbuild_isolationr r r prepare_distribution_metadata"sz2AbstractDistribution.prepare_distribution_metadata) __name__ __module__ __qualname____doc__rabcabstractmethodrr __classcell__r r r r r s   r)rZpip._vendor.sixrABCMetaobjectrr r r r s distributions/__pycache__/__init__.cpython-38.opt-1.pyc000064400000001464152347654150017025 0ustar00U .e@sLddlmZddlmZddlmZer@ddlmZddlm Z ddZ dS) )SourceDistribution)WheelDistribution)MYPY_CHECK_RUNNING)AbstractDistribution)InstallRequirementcCs$|jrt|S|jrt|St|S)zs     distributions/source/__pycache__/legacy.cpython-38.pyc000064400000006617152347654150017100 0ustar00U .ee@sVddlZddlmZddlmZddlmZddlmZe e Z GdddeZ dS)N)BuildEnvironment)AbstractDistribution)InstallationError)runner_with_spinner_messagec@s(eZdZdZddZddZddZdS) SourceDistributionaRepresents a source distribution. The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. NOTE from @pradyunsg (14 June 2019) I expect SourceDistribution class will need to be split into `legacy_source` (setup.py based) and `source` (PEP 517 based) when we start bringing logic for preparation out of InstallRequirement into this class. cCs |jSN)reqZget_dist)selfr M/usr/lib/python3.8/site-packages/pip/_internal/distributions/source/legacy.pyget_pkg_resources_distributionsz1SourceDistribution.get_pkg_resources_distributioncCs<|j|jjo|}|r$|||j|jdSr)rZload_pyproject_tomlZ use_pep517_setup_isolationZprepare_metadataZassert_source_matches_version)r finderZbuild_isolationZshould_isolater r r prepare_distribution_metadatas     z0SourceDistribution.prepare_distribution_metadatac sfdd}tj_jj|jjddjjjj\}rT|d|rtdjtdd t t t |jj4t d }jj}|||}W5QRXW5QRXjj|\}r|d jj||d d dS) Ncs6d}|jj|dddtDd}t|dS)NzZSome build dependencies for {requirement} conflict with {conflicting_with}: {description}.z, css|]\}}d||fVqdS)z%s is incompatible with %sNr ).0Z installedZwantedr r r 3szPSourceDistribution._setup_isolation.._raise_conflicts..)Z requirementconflicting_with description)formatrjoinsortedr)rZconflicting_reqs format_stringZ error_messageZ conflictingr r r _raise_conflicts+s z=SourceDistribution._setup_isolation.._raise_conflictsZoverlayzInstalling build dependenciesz"PEP 517/518 supported requirementsz4Missing build requirements in pyproject.toml for %s.z`The project does not specify a build backend, and pip cannot fall back to setuptools without %s.z and z#Getting requirements to build wheelzthe backend dependenciesZnormalzInstalling backend dependencies)rrZ build_envZinstall_requirementsZpyproject_requiresZcheck_requirementsZrequirements_to_checkloggerZwarningrmapreprrrZpep517_backendZsubprocess_runnerZget_requires_for_build_wheel)r rrZmissingZrunnerZbackendZreqsr rr r *sP    z#SourceDistribution._setup_isolationN)__name__ __module__ __qualname____doc__r rr r r r r rs  r) ZloggingZpip._internal.build_envrZ pip._internal.distributions.baserZpip._internal.exceptionsrZpip._internal.utils.subprocessrZ getLoggerrrrr r r r s      distributions/source/__pycache__/__init__.cpython-38.pyc000064400000000252152347654150017360 0ustar00U .e@sdS)NrrrO/usr/lib/python3.8/site-packages/pip/_internal/distributions/source/__init__.pydistributions/source/__pycache__/legacy.cpython-38.opt-1.pyc000064400000006617152347654150020037 0ustar00U .ee@sVddlZddlmZddlmZddlmZddlmZe e Z GdddeZ dS)N)BuildEnvironment)AbstractDistribution)InstallationError)runner_with_spinner_messagec@s(eZdZdZddZddZddZdS) SourceDistributionaRepresents a source distribution. The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. NOTE from @pradyunsg (14 June 2019) I expect SourceDistribution class will need to be split into `legacy_source` (setup.py based) and `source` (PEP 517 based) when we start bringing logic for preparation out of InstallRequirement into this class. cCs |jSN)reqZget_dist)selfr M/usr/lib/python3.8/site-packages/pip/_internal/distributions/source/legacy.pyget_pkg_resources_distributionsz1SourceDistribution.get_pkg_resources_distributioncCs<|j|jjo|}|r$|||j|jdSr)rZload_pyproject_tomlZ use_pep517_setup_isolationZprepare_metadataZassert_source_matches_version)r finderZbuild_isolationZshould_isolater r r prepare_distribution_metadatas     z0SourceDistribution.prepare_distribution_metadatac sfdd}tj_jj|jjddjjjj\}rT|d|rtdjtdd t t t |jj4t d }jj}|||}W5QRXW5QRXjj|\}r|d jj||d d dS) Ncs6d}|jj|dddtDd}t|dS)NzZSome build dependencies for {requirement} conflict with {conflicting_with}: {description}.z, css|]\}}d||fVqdS)z%s is incompatible with %sNr ).0Z installedZwantedr r r 3szPSourceDistribution._setup_isolation.._raise_conflicts..)Z requirementconflicting_with description)formatrjoinsortedr)rZconflicting_reqs format_stringZ error_messageZ conflictingr r r _raise_conflicts+s z=SourceDistribution._setup_isolation.._raise_conflictsZoverlayzInstalling build dependenciesz"PEP 517/518 supported requirementsz4Missing build requirements in pyproject.toml for %s.z`The project does not specify a build backend, and pip cannot fall back to setuptools without %s.z and z#Getting requirements to build wheelzthe backend dependenciesZnormalzInstalling backend dependencies)rrZ build_envZinstall_requirementsZpyproject_requiresZcheck_requirementsZrequirements_to_checkloggerZwarningrmapreprrrZpep517_backendZsubprocess_runnerZget_requires_for_build_wheel)r rrZmissingZrunnerZbackendZreqsr rr r *sP    z#SourceDistribution._setup_isolationN)__name__ __module__ __qualname____doc__r rr r r r r rs  r) ZloggingZpip._internal.build_envrZ pip._internal.distributions.baserZpip._internal.exceptionsrZpip._internal.utils.subprocessrZ getLoggerrrrr r r r s      distributions/source/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000252152347654150020317 0ustar00U .e@sdS)NrrrO/usr/lib/python3.8/site-packages/pip/_internal/distributions/source/__init__.pydistributions/source/legacy.py000064400000007545152347654150012613 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False import logging from pip._internal.build_env import BuildEnvironment from pip._internal.distributions.base import AbstractDistribution from pip._internal.exceptions import InstallationError from pip._internal.utils.subprocess import runner_with_spinner_message logger = logging.getLogger(__name__) class SourceDistribution(AbstractDistribution): """Represents a source distribution. The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. NOTE from @pradyunsg (14 June 2019) I expect SourceDistribution class will need to be split into `legacy_source` (setup.py based) and `source` (PEP 517 based) when we start bringing logic for preparation out of InstallRequirement into this class. """ def get_pkg_resources_distribution(self): return self.req.get_dist() def prepare_distribution_metadata(self, finder, build_isolation): # Prepare for building. We need to: # 1. Load pyproject.toml (if it exists) # 2. Set up the build environment self.req.load_pyproject_toml() should_isolate = self.req.use_pep517 and build_isolation if should_isolate: self._setup_isolation(finder) self.req.prepare_metadata() self.req.assert_source_matches_version() def _setup_isolation(self, finder): def _raise_conflicts(conflicting_with, conflicting_reqs): format_string = ( "Some build dependencies for {requirement} " "conflict with {conflicting_with}: {description}." ) error_message = format_string.format( requirement=self.req, conflicting_with=conflicting_with, description=', '.join( '%s is incompatible with %s' % (installed, wanted) for installed, wanted in sorted(conflicting) ) ) raise InstallationError(error_message) # Isolate in a BuildEnvironment and install the build-time # requirements. self.req.build_env = BuildEnvironment() self.req.build_env.install_requirements( finder, self.req.pyproject_requires, 'overlay', "Installing build dependencies" ) conflicting, missing = self.req.build_env.check_requirements( self.req.requirements_to_check ) if conflicting: _raise_conflicts("PEP 517/518 supported requirements", conflicting) if missing: logger.warning( "Missing build requirements in pyproject.toml for %s.", self.req, ) logger.warning( "The project does not specify a build backend, and " "pip cannot fall back to setuptools without %s.", " and ".join(map(repr, sorted(missing))) ) # Install any extra build dependencies that the backend requests. # This must be done in a second pass, as the pyproject.toml # dependencies must be installed before we can call the backend. with self.req.build_env: runner = runner_with_spinner_message( "Getting requirements to build wheel" ) backend = self.req.pep517_backend with backend.subprocess_runner(runner): reqs = backend.get_requires_for_build_wheel() conflicting, missing = self.req.build_env.check_requirements(reqs) if conflicting: _raise_conflicts("the backend dependencies", conflicting) self.req.build_env.install_requirements( finder, missing, 'normal', "Installing backend dependencies" ) distributions/source/__init__.py000064400000000000152347654150013061 0ustar00distributions/wheel.py000064400000002416152347654150011143 0ustar00from zipfile import ZipFile from pip._internal.distributions.base import AbstractDistribution from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel if MYPY_CHECK_RUNNING: from pip._vendor.pkg_resources import Distribution from pip._internal.index.package_finder import PackageFinder class WheelDistribution(AbstractDistribution): """Represents a wheel distribution. This does not need any preparation as wheels can be directly unpacked. """ def get_pkg_resources_distribution(self): # type: () -> Distribution """Loads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement. """ # Set as part of preparation during download. assert self.req.local_file_path # Wheels are never unnamed. assert self.req.name with ZipFile(self.req.local_file_path, allowZip64=True) as z: return pkg_resources_distribution_for_wheel( z, self.req.name, self.req.local_file_path ) def prepare_distribution_metadata(self, finder, build_isolation): # type: (PackageFinder, bool) -> None pass distributions/base.py000064400000002621152347654150010747 0ustar00import abc from pip._vendor.six import add_metaclass from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional from pip._vendor.pkg_resources import Distribution from pip._internal.req import InstallRequirement from pip._internal.index.package_finder import PackageFinder @add_metaclass(abc.ABCMeta) class AbstractDistribution(object): """A base class for handling installable artifacts. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. """ def __init__(self, req): # type: (InstallRequirement) -> None super(AbstractDistribution, self).__init__() self.req = req @abc.abstractmethod def get_pkg_resources_distribution(self): # type: () -> Optional[Distribution] raise NotImplementedError() @abc.abstractmethod def prepare_distribution_metadata(self, finder, build_isolation): # type: (PackageFinder, bool) -> None raise NotImplementedError() distributions/installed.py000064400000001370152347654150012014 0ustar00from pip._internal.distributions.base import AbstractDistribution from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional from pip._vendor.pkg_resources import Distribution from pip._internal.index.package_finder import PackageFinder class InstalledDistribution(AbstractDistribution): """Represents an installed package. This does not need any preparation as the required information has already been computed. """ def get_pkg_resources_distribution(self): # type: () -> Optional[Distribution] return self.req.satisfied_by def prepare_distribution_metadata(self, finder, build_isolation): # type: (PackageFinder, bool) -> None pass distributions/__init__.py000064400000001677152347654150011606 0ustar00from pip._internal.distributions.sdist import SourceDistribution from pip._internal.distributions.wheel import WheelDistribution from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._internal.distributions.base import AbstractDistribution from pip._internal.req.req_install import InstallRequirement def make_distribution_for_install_requirement(install_req): # type: (InstallRequirement) -> AbstractDistribution """Returns a Distribution for the given InstallRequirement """ # Editable requirements will always be source distributions. They use the # legacy logic until we create a modern standard for them. if install_req.editable: return SourceDistribution(install_req) # If it's a wheel, it's a WheelDistribution if install_req.is_wheel: return WheelDistribution(install_req) # Otherwise, a SourceDistribution return SourceDistribution(install_req) pyproject.py000064400000016350152347654150007156 0ustar00from __future__ import absolute_import import io import os import sys from collections import namedtuple from pip._vendor import six, toml from pip._vendor.packaging.requirements import InvalidRequirement, Requirement from pip._internal.exceptions import InstallationError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Optional, List def _is_list_of_str(obj): # type: (Any) -> bool return ( isinstance(obj, list) and all(isinstance(item, six.string_types) for item in obj) ) def make_pyproject_path(unpacked_source_directory): # type: (str) -> str path = os.path.join(unpacked_source_directory, 'pyproject.toml') # Python2 __file__ should not be unicode if six.PY2 and isinstance(path, six.text_type): path = path.encode(sys.getfilesystemencoding()) return path BuildSystemDetails = namedtuple('BuildSystemDetails', [ 'requires', 'backend', 'check', 'backend_path' ]) def load_pyproject_toml( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str ): # type: (...) -> Optional[BuildSystemDetails] """Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment directory paths to import the backend from (backend-path), relative to the project root. ) """ has_pyproject = os.path.isfile(pyproject_toml) has_setup = os.path.isfile(setup_py) if has_pyproject: with io.open(pyproject_toml, encoding="utf-8") as f: pp_toml = toml.load(f) build_system = pp_toml.get("build-system") else: build_system = None # The following cases must use PEP 517 # We check for use_pep517 being non-None and falsey because that means # the user explicitly requested --no-use-pep517. The value 0 as # opposed to False can occur when the value is provided via an # environment variable or config file option (due to the quirk of # strtobool() returning an integer in pip's configuration code). if has_pyproject and not has_setup: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project does not have a setup.py" ) use_pep517 = True elif build_system and "build-backend" in build_system: if use_pep517 is not None and not use_pep517: raise InstallationError( "Disabling PEP 517 processing is invalid: " "project specifies a build backend of {} " "in pyproject.toml".format( build_system["build-backend"] ) ) use_pep517 = True # If we haven't worked out whether to use PEP 517 yet, # and the user hasn't explicitly stated a preference, # we do so if the project has a pyproject.toml file. elif use_pep517 is None: use_pep517 = has_pyproject # At this point, we know whether we're going to use PEP 517. assert use_pep517 is not None # If we're using the legacy code path, there is nothing further # for us to do here. if not use_pep517: return None if build_system is None: # Either the user has a pyproject.toml with no build-system # section, or the user has no pyproject.toml, but has opted in # explicitly via --use-pep517. # In the absence of any explicit backend specification, we # assume the setuptools backend that most closely emulates the # traditional direct setup.py execution, and require wheel and # a version of setuptools that supports that backend. build_system = { "requires": ["setuptools>=40.8.0", "wheel"], "build-backend": "setuptools.build_meta:__legacy__", } # If we're using PEP 517, we have build system information (either # from pyproject.toml, or defaulted by the code above). # Note that at this point, we do not know if the user has actually # specified a backend, though. assert build_system is not None # Ensure that the build-system section in pyproject.toml conforms # to PEP 518. error_template = ( "{package} has a pyproject.toml file that does not comply " "with PEP 518: {reason}" ) # Specifying the build-system table but not the requires key is invalid if "requires" not in build_system: raise InstallationError( error_template.format(package=req_name, reason=( "it has a 'build-system' table but not " "'build-system.requires' which is mandatory in the table" )) ) # Error out if requires is not a list of strings requires = build_system["requires"] if not _is_list_of_str(requires): raise InstallationError(error_template.format( package=req_name, reason="'build-system.requires' is not a list of strings.", )) # Each requirement must be valid as per PEP 508 for requirement in requires: try: Requirement(requirement) except InvalidRequirement: raise InstallationError( error_template.format( package=req_name, reason=( "'build-system.requires' contains an invalid " "requirement: {!r}".format(requirement) ), ) ) backend = build_system.get("build-backend") backend_path = build_system.get("backend-path", []) check = [] # type: List[str] if backend is None: # If the user didn't specify a backend, we assume they want to use # the setuptools backend. But we can't be sure they have included # a version of setuptools which supplies the backend, or wheel # (which is needed by the backend) in their requirements. So we # make a note to check that those requirements are present once # we have set up the environment. # This is quite a lot of work to check for a very specific case. But # the problem is, that case is potentially quite common - projects that # adopted PEP 518 early for the ability to specify requirements to # execute setup.py, but never considered needing to mention the build # tools themselves. The original PEP 518 code had a similar check (but # implemented in a different way). backend = "setuptools.build_meta:__legacy__" check = ["setuptools>=40.8.0", "wheel"] return BuildSystemDetails(requires, backend, check, backend_path) operations/__pycache__/prepare.cpython-38.pyc000064400000013410152347654150015240 0ustar00U .e,@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z m Z mZmZmZddlmZdd lmZdd lmZdd lmZdd lmZmZdd lmZerddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(e)e*Z+ddZ,Gddde-Z.dS)z)Prepares a distribution for installation N)requests))make_distribution_for_install_requirement)InstalledDistribution) unpack_url)DirectoryUrlHashUnsupported HashUnpinnedInstallationErrorPreviousBuildDirErrorVcsHashUnsupported) expanduser) MissingHashes) indent_log)write_delete_marker_file) display_pathnormalize_path)MYPY_CHECK_RUNNING)Optional)AbstractDistribution) PackageFinder) PipSession)InstallRequirement)RequirementTrackerc Cs.t|}|||||W5QRX|S)z-Prepare a distribution for installation. )rZtrackZprepare_distribution_metadata)req req_trackerfinderbuild_isolation abstract_distrD/usr/lib/python3.8/site-packages/pip/_internal/operations/prepare.py_get_prepared_distribution,s rcsDeZdZdZfddZeddZddZdd Zd d Z Z S) RequirementPreparerzPrepares a Requirement csTtt|||_||_||_|r,t|}||_|r>t|}||_ ||_ ||_ dS)N) superr __init__src_dir build_dirrr download_dirrwheel_download_dir progress_barr)selfr$r%r#r&r'rr __class__rrr"9s zRequirementPreparer.__init__cCs<|js dStj|jrdStdtdt|jdS)NFTz!Could not find download directoryz0Could not find or access download directory '%s')r%ospathexistsloggercriticalrr)r(rrr_download_should_saveas z)RequirementPreparer._download_should_savec Cs|js t|j}|jdkr2|j}tdt|ntd|jp@|tb| |j t j t j |jdrtd||jf|r|jrtn|rt|js|jst|j| d}|r|st}|j}|jr|jr|j}zt||j||||jdWnFtj k rL} z$t!d|| t"d || |fW5d } ~ XYnX|jrh|rbd } nd } nd } | r|t#|jt$||j%||j&} |j'r|jr|(|jW5QRX| S) zCPrepare a requirement that would be obtained from req.link filez Processing %sz Collecting %szsetup.pyzpip can't proceed with requirements '%s' due to a pre-existing build directory (%s). This is likely due to a previous installation that failed. pip is being responsible and not assuming it can delete this. Please delete it and try again.)Ztrust_internet)sessionhashesr'z4Could not install requirement %s because of error %szDCould not install requirement %s because of HTTP error %s for URL %sNTF))linkAssertionErrorZschemeZ file_pathr.inforrr ensure_has_source_dirr$r+r,r-joinZ source_dirr Zis_vcsr Zis_existing_dirrZ original_linkZ is_pinnedrr3r r%Zis_wheelr&rr'rZ HTTPErrorr/rrrrrr0archive) r(rr2rrequire_hashesr4r,r3r%excZautodelete_unpackedrrrrprepare_linked_requirementos         z.RequirementPreparer.prepare_linked_requirementc Cs|jstdtd|t^|r2td|||j||j t ||j ||j }|j rp| |j||W5QRX|S)z(Prepare an editable requirement z-cannot prepare a non-editable req as editablez Obtaining %szoThe editable requirement %s cannot be installed when requiring hashes, because there is no single file to hash.)Zeditabler5r.r6r rr7r#Zupdate_editabler0rrrr9r%Zcheck_if_exists)r(rr:Z use_user_siterrrrrprepare_editable_requirements*    z0RequirementPreparer.prepare_editable_requirementc Csf|jstd|dk s&td|jftd|||jjt|rPtdt|}W5QRX|S)z1Prepare an already-installed requirement z(req should have been satisfied but isn'tNzAdid not get skip reason skipped but req.satisfied_by is set to %rzRequirement %s: %s (%s)zSince it is already installed, we are trusting this package without checking its hash. To ensure a completely repeatable environment, install into an empty virtualenv.)Z satisfied_byr5r.r6versionr debugr)r(rr:Z skip_reasonrrrrprepare_installed_requirement s&  z1RequirementPreparer.prepare_installed_requirement) __name__ __module__ __qualname____doc__r"propertyr0r<r=r@ __classcell__rrr)rr 5s ( z"r )/rDZloggingr+Z pip._vendorrZpip._internal.distributionsrZ%pip._internal.distributions.installedrZpip._internal.downloadrZpip._internal.exceptionsrrrr r Zpip._internal.utils.compatr Zpip._internal.utils.hashesr Zpip._internal.utils.loggingr Z pip._internal.utils.marker_filesrZpip._internal.utils.miscrrZpip._internal.utils.typingrtypingrrZpip._internal.indexrZpip._internal.network.sessionrZpip._internal.req.req_installrZpip._internal.req.req_trackerrZ getLoggerrAr.robjectr rrrrs.                 operations/__pycache__/generate_metadata.cpython-38.pyc000064400000007463152347654150017247 0ustar00U .e[@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZe r|dd lmZmZdd lmZeeZd d Zd dZddZddZdS)z4Metadata generation logic for source distributions. N)InstallationError) ensure_dir)make_setuptools_shim_args)call_subprocess)MYPY_CHECK_RUNNING)vcs)CallableList)InstallRequirementcCs|js tStS)aReturn a callable metadata generator for this InstallRequirement. A metadata generator takes an InstallRequirement (install_req) as an input, generates metadata via the appropriate process for that install_req and returns the generated metadata directory. )Z use_pep517_generate_metadata_legacy_generate_metadata install_reqrN/usr/lib/python3.8/site-packages/pip/_internal/operations/generate_metadata.pyget_metadata_generatorsrcsddfdd}dd}|}|r.||}ntj|d}t|}|sVtd|t|d krn|j|d tj||d S) zEFind an .egg-info in `source_directory`, based on `is_editable`. cSs0tjtj|ddp.tjtj|ddS)NbinpythonZScriptsz Python.exe)ospathlexistsjoinexists)rrrrlooks_like_virtual_env(sz._find_egg_info..looks_like_virtual_envcsg}t|D]\}}tjD]}||kr||qt|D]<}tj|r`||q>|dksp|dkr>||q>|fdd|Dqdd|DS)NZtestZtestsc3s|]}tj|VqdSN)rrr).0dir_rootrr ?szC_find_egg_info..locate_editable_egg_info..cSsg|]}|dr|qS)z .egg-info)endswith)rfrrr @s zD_find_egg_info..locate_editable_egg_info..) rwalkrZdirnamesremovelistrrextend)baseZ candidatesdirsfilesrrrrlocate_editable_egg_info/s     z0_find_egg_info..locate_editable_egg_infocSs(|tjjtjjr"|tjjp$dS)Nr)countrrsepaltsep)rrrrdepth_of_directoryBs z*_find_egg_info..depth_of_directory pip-egg-infoz!Files/directories not found in %s)keyr)rrrlistdirrlensort)Zsource_directoryZ is_editabler+r/r' filenamesrr*r_find_egg_info#s     r7c Cs|jpd|j}td|j|t|j}|jr<|dg7}g}|jsft j |j d}d|g}t ||j t|dg||j ddW5QRXt|j |jS) Nzfrom {}z2Running setup.py (path:%s) egg_info for package %sz --no-user-cfgr0z --egg-baseZegg_infozpython setup.py egg_info)cwdZ command_desc)nameformatlinkloggerdebugZ setup_py_pathrisolatedZeditablerrrZunpacked_source_directoryrZ build_envrr7)rZreq_details_strZbase_cmdZegg_base_optionZ egg_info_dirrrrr ^s6   r cCs|Sr)Zprepare_pep517_metadatar rrrr sr )__doc__ZloggingrZpip._internal.exceptionsrZpip._internal.utils.miscrZ$pip._internal.utils.setuptools_buildrZpip._internal.utils.subprocessrZpip._internal.utils.typingrZpip._internal.vcsrtypingrr Zpip._internal.req.req_installr Z getLogger__name__r<rr7r r rrrrs         ;(operations/__pycache__/check.cpython-38.pyc000064400000007110152347654150014657 0ustar00U .e@s dZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z eeZe rdd lmZdd lmZmZmZmZmZmZmZeed fZeeefZeeeefZeeeefZeeeefZ eee fZ!ed d d gZ"ddZ#dddZ$ddZ%ddZ&ddZ'dS)z'Validation of dependencies of packages N) namedtuple)canonicalize_name)RequirementParseError))make_distribution_for_install_requirement)get_installed_distributions)MYPY_CHECK_RUNNING)InstallRequirement)AnyCallableDictOptionalSetTupleListPackageDetailsversionrequiresc Ks|ikrddd}i}d}tf|D]\}t|j}zt|j|||<Wq$tk r~}ztd||d}W5d}~XYq$Xq$||fS)z8Converts a list of distributions into a PackageSet. F)Z local_onlyskipz%Error parsing requirements for %s: %sTN) rr project_namerrrrloggingZwarning)kwargs package_setZproblemsdistnameerrB/usr/lib/python3.8/site-packages/pip/_internal/operations/check.py!create_package_set_from_installed(s  rc Cs|dkrdd}i}i}|D]}t}t}||r6q||jD]l}t|j}||krd} |jdk rn|j} | r@|||fq@||j} |jj | dds@||| |fq@|rt |t d||<|rt |t d||<q||fS)zCheck if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. NcSsdS)NFrrrrr should_ignoreEsz(check_package_set..should_ignoreT)Z prereleases)key) setrrrZmarkerZevaluateaddrZ specifiercontainssortedstr) rrZmissingZ conflicting package_nameZ missing_depsZconflicting_depsreqrZmissedrrrrcheck_package_set=s4    r(cs6t\}}t||}t|||t|fdddfS)zeFor checking if the dependency graph would be consistent after installing given requirements cs|kSNrrZ whitelistrr|z)check_install_conflicts..)r)r_simulate_installation_of_create_whitelistr() to_installr_would_be_installedrr*rcheck_install_conflictsls    r2cCsLt}|D]<}t|}|}t|j}t|j|||<||q |S)zBComputes the version of packages after installing to_install. ) r!rZget_pkg_resources_distributionrr rrrr")r/rZ installedZinst_reqZ abstract_distrrrrrr-s  r-cCsLt|}|D]:}||krq ||jD] }t|j|kr$||q q$q |Sr))r!rrrr")r1rZpackages_affectedr&r'rrrr.s r.)N)(__doc__r collectionsrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrZpip._internal.distributionsrZpip._internal.utils.miscrZpip._internal.utils.typingrZ getLogger__name__ZloggerZpip._internal.req.req_installrtypingr r r r r rrr%Z PackageSetZMissingZ ConflictingZ MissingDictZConflictingDictZ CheckResultrrr(r2r-r.rrrrs.        $    /operations/__pycache__/check.cpython-38.opt-1.pyc000064400000007110152347654150015616 0ustar00U .e@s dZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z eeZe rdd lmZdd lmZmZmZmZmZmZmZeed fZeeefZeeeefZeeeefZeeeefZ eee fZ!ed d d gZ"ddZ#dddZ$ddZ%ddZ&ddZ'dS)z'Validation of dependencies of packages N) namedtuple)canonicalize_name)RequirementParseError))make_distribution_for_install_requirement)get_installed_distributions)MYPY_CHECK_RUNNING)InstallRequirement)AnyCallableDictOptionalSetTupleListPackageDetailsversionrequiresc Ks|ikrddd}i}d}tf|D]\}t|j}zt|j|||<Wq$tk r~}ztd||d}W5d}~XYq$Xq$||fS)z8Converts a list of distributions into a PackageSet. F)Z local_onlyskipz%Error parsing requirements for %s: %sTN) rr project_namerrrrloggingZwarning)kwargs package_setZproblemsdistnameerrB/usr/lib/python3.8/site-packages/pip/_internal/operations/check.py!create_package_set_from_installed(s  rc Cs|dkrdd}i}i}|D]}t}t}||r6q||jD]l}t|j}||krd} |jdk rn|j} | r@|||fq@||j} |jj | dds@||| |fq@|rt |t d||<|rt |t d||<q||fS)zCheck if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. NcSsdS)NFrrrrr should_ignoreEsz(check_package_set..should_ignoreT)Z prereleases)key) setrrrZmarkerZevaluateaddrZ specifiercontainssortedstr) rrZmissingZ conflicting package_nameZ missing_depsZconflicting_depsreqrZmissedrrrrcheck_package_set=s4    r(cs6t\}}t||}t|||t|fdddfS)zeFor checking if the dependency graph would be consistent after installing given requirements cs|kSNrrZ whitelistrr|z)check_install_conflicts..)r)r_simulate_installation_of_create_whitelistr() to_installr_would_be_installedrr*rcheck_install_conflictsls    r2cCsLt}|D]<}t|}|}t|j}t|j|||<||q |S)zBComputes the version of packages after installing to_install. ) r!rZget_pkg_resources_distributionrr rrrr")r/rZ installedZinst_reqZ abstract_distrrrrrr-s  r-cCsLt|}|D]:}||krq ||jD] }t|j|kr$||q q$q |Sr))r!rrrr")r1rZpackages_affectedr&r'rrrr.s r.)N)(__doc__r collectionsrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrZpip._internal.distributionsrZpip._internal.utils.miscrZpip._internal.utils.typingrZ getLogger__name__ZloggerZpip._internal.req.req_installrtypingr r r r r rrr%Z PackageSetZMissingZ ConflictingZ MissingDictZConflictingDictZ CheckResultrrr(r2r-r.rrrrs.        $    /operations/__pycache__/freeze.cpython-38.opt-1.pyc000064400000013142152347654150016023 0ustar00U .eb& @s4ddlmZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z mZddlmZmZddlmZdd lmZmZdd lmZerdd lmZmZmZmZmZmZm Z m!Z!m"Z"dd l#m$Z$dd l m%Z%m&Z&e ee"e'e&fe(ee'fZ)e*e+Z,dddZ-ddZ.Gddde/Z0dS))absolute_importN)six)canonicalize_name)RequirementParseError) BadCommandInstallationError)install_req_from_editableinstall_req_from_line) COMMENT_RE)dist_is_editableget_installed_distributions)MYPY_CHECK_RUNNING) IteratorOptionalList ContainerSetDictTupleIterableUnion) WheelCache) Distribution RequirementFc  cs|pg}d} |rt|j} |D]} d| Vq i} t|d||dD]b} zt| }Wn8tk r}ztd| |WYqDW5d}~XYnX|r|j rqD|| |j <qD|rt }t t}|D]}t|}|D]r}|r|ds| r| |s|dr6|}||kr|||Vq|dsN|dr|drl|d d}n|tddd }t|||d }nttd |||d }|j std ||tdq|j | kr ||j std|td ||j n||j |qt| |j V| |j =||j |qW5QRXqt|D]4\}}t|dkrdtd|dt t |qddVt | !dddD]$}t"|j | krt|VqdS)Nz-f %sr) local_onlyskip user_onlypathsz6Could not generate requirement for distribution %r: %s#) z-rz --requirementz-Zz--always-unzipz-fz --find-linksz-iz --index-urlz--prez--trusted-hostz--process-dependency-linksz--extra-index-urlz-ez --editable=)isolated wheel_cachezWSkipping line in requirement file [%s] because it's not clear what it would install: %sz9 (add #egg=PackageName to the URL to avoid this warning)zBRequirement file [%s] contains %s, but package %r is not installedz+Requirement %s included multiple times [%s]z, z7## The following requirements were added by pip freeze:cSs |jSN)namelower)xrrC/usr/lib/python3.8/site-packages/pip/_internal/operations/freeze.pyzfreeze..)key)#recompilesearchr FrozenRequirement from_distrloggerwarningeditabler'set collections defaultdictlistopenstrip startswithrstripaddlenlstriprr r subinfoappendstrrZ iteritemsjoinsortedvaluesr)Z requirementZ find_linksrrrZ skip_regexr"r#Zexclude_editablerZ skip_matchlinkZ installationsdistreqexcZemitted_optionsZ req_filesZ req_file_pathZreq_filelineZline_reqr'filesZ installationrrr*freeze+s                  rNc CsNt|sddgfStjtj|j}ddlm}m}| |}|dkrv| }t d||d |g}|d|fSz|||j}Wn|k r| }d t|j|g}|d|fYStk rt d ||jddgfYStk r}zt d |W5d}~XYnX|dk r2|dgfSt d |d g}dd|fS) zk Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). NFr)vcsRemoteNotFoundErrorz1No VCS found for editable requirement "%s" in: %rz/# Editable install with no version control ({})Tz)# Editable {} install with no remote ({})zPcannot determine version of editable source in %s (%s command not found in path)zYError when trying to get requirement for VCS system %s, falling back to uneditable formatz-Could not determine repository location of %sz-## !! Could not determine repository location)r ospathnormcaseabspathlocationZpip._internal.vcsrOrPZget_backend_for_diras_requirementr3debugformatZget_src_requirement project_nametype__name__rr4r'r)rIrUrOrPZ vcs_backendrJcommentsrKrrr*get_requirement_infosZ     r]c@s*eZdZd ddZeddZddZdS) r1rcCs||_||_||_||_dSr&)r'rJr5r\)selfr'rJr5r\rrr*__init__szFrozenRequirement.__init__cCs0t|\}}}|dkr|}||j|||dS)N)r\)r]rVrY)clsrIrJr5r\rrr*r2szFrozenRequirement.from_distcCs2|j}|jrd|}dt|jt|gdS)Nz-e %s )rJr5rEr9r\rD)r^rJrrr*__str__szFrozenRequirement.__str__N)r)r[ __module__ __qualname__r_ classmethodr2rbrrrr*r1s  r1) NNNNNNFNFr)1Z __future__rr7ZloggingrQr.Z pip._vendorrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrZpip._internal.exceptionsrrZpip._internal.req.constructorsrr Zpip._internal.req.req_filer Zpip._internal.utils.miscr r Zpip._internal.utils.typingr typingrrrrrrrrrZpip._internal.cacherrrrDboolZRequirementInfoZ getLoggerr[r3rNr]objectr1rrrr*s@      ,   >operations/__pycache__/__init__.cpython-38.pyc000064400000000240152347654150015336 0ustar00U .e@sdS)NrrrE/usr/lib/python3.8/site-packages/pip/_internal/operations/__init__.pyoperations/__pycache__/generate_metadata.cpython-38.opt-1.pyc000064400000007463152347654150020206 0ustar00U .e[@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZe r|dd lmZmZdd lmZeeZd d Zd dZddZddZdS)z4Metadata generation logic for source distributions. N)InstallationError) ensure_dir)make_setuptools_shim_args)call_subprocess)MYPY_CHECK_RUNNING)vcs)CallableList)InstallRequirementcCs|js tStS)aReturn a callable metadata generator for this InstallRequirement. A metadata generator takes an InstallRequirement (install_req) as an input, generates metadata via the appropriate process for that install_req and returns the generated metadata directory. )Z use_pep517_generate_metadata_legacy_generate_metadata install_reqrN/usr/lib/python3.8/site-packages/pip/_internal/operations/generate_metadata.pyget_metadata_generatorsrcsddfdd}dd}|}|r.||}ntj|d}t|}|sVtd|t|d krn|j|d tj||d S) zEFind an .egg-info in `source_directory`, based on `is_editable`. cSs0tjtj|ddp.tjtj|ddS)NbinpythonZScriptsz Python.exe)ospathlexistsjoinexists)rrrrlooks_like_virtual_env(sz._find_egg_info..looks_like_virtual_envcsg}t|D]\}}tjD]}||kr||qt|D]<}tj|r`||q>|dksp|dkr>||q>|fdd|Dqdd|DS)NZtestZtestsc3s|]}tj|VqdSN)rrr).0dir_rootrr ?szC_find_egg_info..locate_editable_egg_info..cSsg|]}|dr|qS)z .egg-info)endswith)rfrrr @s zD_find_egg_info..locate_editable_egg_info..) rwalkrZdirnamesremovelistrrextend)baseZ candidatesdirsfilesrrrrlocate_editable_egg_info/s     z0_find_egg_info..locate_editable_egg_infocSs(|tjjtjjr"|tjjp$dS)Nr)countrrsepaltsep)rrrrdepth_of_directoryBs z*_find_egg_info..depth_of_directory pip-egg-infoz!Files/directories not found in %s)keyr)rrrlistdirrlensort)Zsource_directoryZ is_editabler+r/r' filenamesrr*r_find_egg_info#s     r7c Cs|jpd|j}td|j|t|j}|jr<|dg7}g}|jsft j |j d}d|g}t ||j t|dg||j ddW5QRXt|j |jS) Nzfrom {}z2Running setup.py (path:%s) egg_info for package %sz --no-user-cfgr0z --egg-baseZegg_infozpython setup.py egg_info)cwdZ command_desc)nameformatlinkloggerdebugZ setup_py_pathrisolatedZeditablerrrZunpacked_source_directoryrZ build_envrr7)rZreq_details_strZbase_cmdZegg_base_optionZ egg_info_dirrrrr ^s6   r cCs|Sr)Zprepare_pep517_metadatar rrrr sr )__doc__ZloggingrZpip._internal.exceptionsrZpip._internal.utils.miscrZ$pip._internal.utils.setuptools_buildrZpip._internal.utils.subprocessrZpip._internal.utils.typingrZpip._internal.vcsrtypingrr Zpip._internal.req.req_installr Z getLogger__name__r<rr7r r rrrrs         ;(operations/__pycache__/freeze.cpython-38.pyc000064400000013142152347654150015064 0ustar00U .eb& @s4ddlmZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z mZddlmZmZddlmZdd lmZmZdd lmZerdd lmZmZmZmZmZmZm Z m!Z!m"Z"dd l#m$Z$dd l m%Z%m&Z&e ee"e'e&fe(ee'fZ)e*e+Z,dddZ-ddZ.Gddde/Z0dS))absolute_importN)six)canonicalize_name)RequirementParseError) BadCommandInstallationError)install_req_from_editableinstall_req_from_line) COMMENT_RE)dist_is_editableget_installed_distributions)MYPY_CHECK_RUNNING) IteratorOptionalList ContainerSetDictTupleIterableUnion) WheelCache) Distribution RequirementFc  cs|pg}d} |rt|j} |D]} d| Vq i} t|d||dD]b} zt| }Wn8tk r}ztd| |WYqDW5d}~XYnX|r|j rqD|| |j <qD|rt }t t}|D]}t|}|D]r}|r|ds| r| |s|dr6|}||kr|||Vq|dsN|dr|drl|d d}n|tddd }t|||d }nttd |||d }|j std ||tdq|j | kr ||j std|td ||j n||j |qt| |j V| |j =||j |qW5QRXqt|D]4\}}t|dkrdtd|dt t |qddVt | !dddD]$}t"|j | krt|VqdS)Nz-f %sr) local_onlyskip user_onlypathsz6Could not generate requirement for distribution %r: %s#) z-rz --requirementz-Zz--always-unzipz-fz --find-linksz-iz --index-urlz--prez--trusted-hostz--process-dependency-linksz--extra-index-urlz-ez --editable=)isolated wheel_cachezWSkipping line in requirement file [%s] because it's not clear what it would install: %sz9 (add #egg=PackageName to the URL to avoid this warning)zBRequirement file [%s] contains %s, but package %r is not installedz+Requirement %s included multiple times [%s]z, z7## The following requirements were added by pip freeze:cSs |jSN)namelower)xrrC/usr/lib/python3.8/site-packages/pip/_internal/operations/freeze.pyzfreeze..)key)#recompilesearchr FrozenRequirement from_distrloggerwarningeditabler'set collections defaultdictlistopenstrip startswithrstripaddlenlstriprr r subinfoappendstrrZ iteritemsjoinsortedvaluesr)Z requirementZ find_linksrrrZ skip_regexr"r#Zexclude_editablerZ skip_matchlinkZ installationsdistreqexcZemitted_optionsZ req_filesZ req_file_pathZreq_filelineZline_reqr'filesZ installationrrr*freeze+s                  rNc CsNt|sddgfStjtj|j}ddlm}m}| |}|dkrv| }t d||d |g}|d|fSz|||j}Wn|k r| }d t|j|g}|d|fYStk rt d ||jddgfYStk r}zt d |W5d}~XYnX|dk r2|dgfSt d |d g}dd|fS) zk Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). NFr)vcsRemoteNotFoundErrorz1No VCS found for editable requirement "%s" in: %rz/# Editable install with no version control ({})Tz)# Editable {} install with no remote ({})zPcannot determine version of editable source in %s (%s command not found in path)zYError when trying to get requirement for VCS system %s, falling back to uneditable formatz-Could not determine repository location of %sz-## !! Could not determine repository location)r ospathnormcaseabspathlocationZpip._internal.vcsrOrPZget_backend_for_diras_requirementr3debugformatZget_src_requirement project_nametype__name__rr4r'r)rIrUrOrPZ vcs_backendrJcommentsrKrrr*get_requirement_infosZ     r]c@s*eZdZd ddZeddZddZdS) r1rcCs||_||_||_||_dSr&)r'rJr5r\)selfr'rJr5r\rrr*__init__szFrozenRequirement.__init__cCs0t|\}}}|dkr|}||j|||dS)N)r\)r]rVrY)clsrIrJr5r\rrr*r2szFrozenRequirement.from_distcCs2|j}|jrd|}dt|jt|gdS)Nz-e %s )rJr5rEr9r\rD)r^rJrrr*__str__szFrozenRequirement.__str__N)r)r[ __module__ __qualname__r_ classmethodr2rbrrrr*r1s  r1) NNNNNNFNFr)1Z __future__rr7ZloggingrQr.Z pip._vendorrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrZpip._internal.exceptionsrrZpip._internal.req.constructorsrr Zpip._internal.req.req_filer Zpip._internal.utils.miscr r Zpip._internal.utils.typingr typingrrrrrrrrrZpip._internal.cacherrrrDboolZRequirementInfoZ getLoggerr[r3rNr]objectr1rrrr*s@      ,   >operations/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000240152347654150016275 0ustar00U .e@sdS)NrrrE/usr/lib/python3.8/site-packages/pip/_internal/operations/__init__.pyoperations/__pycache__/prepare.cpython-38.opt-1.pyc000064400000012771152347654150016210 0ustar00U .e,@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z m Z mZmZmZddlmZdd lmZdd lmZdd lmZdd lmZmZdd lmZerddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(e)e*Z+ddZ,Gddde-Z.dS)z)Prepares a distribution for installation N)requests))make_distribution_for_install_requirement)InstalledDistribution) unpack_url)DirectoryUrlHashUnsupported HashUnpinnedInstallationErrorPreviousBuildDirErrorVcsHashUnsupported) expanduser) MissingHashes) indent_log)write_delete_marker_file) display_pathnormalize_path)MYPY_CHECK_RUNNING)Optional)AbstractDistribution) PackageFinder) PipSession)InstallRequirement)RequirementTrackerc Cs.t|}|||||W5QRX|S)z-Prepare a distribution for installation. )rZtrackZprepare_distribution_metadata)req req_trackerfinderbuild_isolation abstract_distrD/usr/lib/python3.8/site-packages/pip/_internal/operations/prepare.py_get_prepared_distribution,s rcsDeZdZdZfddZeddZddZdd Zd d Z Z S) RequirementPreparerzPrepares a Requirement csTtt|||_||_||_|r,t|}||_|r>t|}||_ ||_ ||_ dS)N) superr __init__src_dir build_dirrr download_dirrwheel_download_dir progress_barr)selfr$r%r#r&r'rr __class__rrr"9s zRequirementPreparer.__init__cCs<|js dStj|jrdStdtdt|jdS)NFTz!Could not find download directoryz0Could not find or access download directory '%s')r%ospathexistsloggercriticalrr)r(rrr_download_should_saveas z)RequirementPreparer._download_should_savec Cs|j}|jdkr(|j}tdt|ntd|jp6|tb||j t j t j |jdrztd||jf|r|jrtn|rt|js|jst|j| d}|r|st}|j}|jr|jr|j}zt||j||||jdWnFtjk rB} z$t d|| t!d || |fW5d } ~ XYnX|jr^|rXd } nd } nd } | rrt"|jt#||j$||j%} |j&r|jr|'|jW5QRX| S) zCPrepare a requirement that would be obtained from req.link filez Processing %sz Collecting %szsetup.pyzpip can't proceed with requirements '%s' due to a pre-existing build directory (%s). This is likely due to a previous installation that failed. pip is being responsible and not assuming it can delete this. Please delete it and try again.)Ztrust_internet)sessionhashesr'z4Could not install requirement %s because of error %szDCould not install requirement %s because of HTTP error %s for URL %sNTF)(linkZschemeZ file_pathr.inforrr ensure_has_source_dirr$r+r,r-joinZ source_dirr Zis_vcsr Zis_existing_dirrZ original_linkZ is_pinnedrr3r r%Zis_wheelr&rr'rZ HTTPErrorr/rrrrrr0archive) r(rr2rrequire_hashesr4r,r3r%excZautodelete_unpackedrrrrprepare_linked_requirementos~         z.RequirementPreparer.prepare_linked_requirementc Csztd|t^|r$td|||j||j t||j ||j }|jrb| |j | |W5QRX|S)z(Prepare an editable requirement z Obtaining %szoThe editable requirement %s cannot be installed when requiring hashes, because there is no single file to hash.)r.r5r rr6r#Zupdate_editabler0rrrr8r%Zcheck_if_exists)r(rr9Z use_user_siterrrrrprepare_editable_requirements(   z0RequirementPreparer.prepare_editable_requirementc Cs@td|||jjt|r*tdt|}W5QRX|S)z1Prepare an already-installed requirement zRequirement %s: %s (%s)zSince it is already installed, we are trusting this package without checking its hash. To ensure a completely repeatable environment, install into an empty virtualenv.)r.r5Z satisfied_byversionr debugr)r(rr9Z skip_reasonrrrrprepare_installed_requirement sz1RequirementPreparer.prepare_installed_requirement) __name__ __module__ __qualname____doc__r"propertyr0r;r<r? __classcell__rrr)rr 5s ( z"r )/rCZloggingr+Z pip._vendorrZpip._internal.distributionsrZ%pip._internal.distributions.installedrZpip._internal.downloadrZpip._internal.exceptionsrrrr r Zpip._internal.utils.compatr Zpip._internal.utils.hashesr Zpip._internal.utils.loggingr Z pip._internal.utils.marker_filesrZpip._internal.utils.miscrrZpip._internal.utils.typingrtypingrrZpip._internal.indexrZpip._internal.network.sessionrZpip._internal.req.req_installrZpip._internal.req.req_trackerrZ getLoggerr@r.robjectr rrrrs.                 operations/prepare.py000064400000046677152347654150010777 0ustar00"""Prepares a distribution for installation """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False import logging import mimetypes import os import shutil from pip._vendor.six import PY2 from pip._internal.distributions import ( make_distribution_for_install_requirement, ) from pip._internal.distributions.installed import InstalledDistribution from pip._internal.exceptions import ( DirectoryUrlHashUnsupported, HashMismatch, HashUnpinned, InstallationError, NetworkConnectionError, PreviousBuildDirError, VcsHashUnsupported, ) from pip._internal.utils.filesystem import copy2_fixed from pip._internal.utils.hashes import MissingHashes from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( display_path, hide_url, path_to_display, rmtree, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import unpack_file from pip._internal.vcs import vcs if MYPY_CHECK_RUNNING: from typing import ( Callable, List, Optional, Tuple, ) from mypy_extensions import TypedDict from pip._internal.distributions import AbstractDistribution from pip._internal.index.package_finder import PackageFinder from pip._internal.models.link import Link from pip._internal.network.download import Downloader from pip._internal.req.req_install import InstallRequirement from pip._internal.req.req_tracker import RequirementTracker from pip._internal.utils.hashes import Hashes if PY2: CopytreeKwargs = TypedDict( 'CopytreeKwargs', { 'ignore': Callable[[str, List[str]], List[str]], 'symlinks': bool, }, total=False, ) else: CopytreeKwargs = TypedDict( 'CopytreeKwargs', { 'copy_function': Callable[[str, str], None], 'ignore': Callable[[str, List[str]], List[str]], 'ignore_dangling_symlinks': bool, 'symlinks': bool, }, total=False, ) logger = logging.getLogger(__name__) def _get_prepared_distribution( req, # type: InstallRequirement req_tracker, # type: RequirementTracker finder, # type: PackageFinder build_isolation # type: bool ): # type: (...) -> AbstractDistribution """Prepare a distribution for installation. """ abstract_dist = make_distribution_for_install_requirement(req) with req_tracker.track(req): abstract_dist.prepare_distribution_metadata(finder, build_isolation) return abstract_dist def unpack_vcs_link(link, location): # type: (Link, str) -> None vcs_backend = vcs.get_backend_for_scheme(link.scheme) assert vcs_backend is not None vcs_backend.unpack(location, url=hide_url(link.url)) class File(object): def __init__(self, path, content_type): # type: (str, str) -> None self.path = path self.content_type = content_type def get_http_url( link, # type: Link downloader, # type: Downloader download_dir=None, # type: Optional[str] hashes=None, # type: Optional[Hashes] ): # type: (...) -> File temp_dir = TempDirectory(kind="unpack", globally_managed=True) # If a download dir is specified, is the file already downloaded there? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir( link, download_dir, hashes ) if already_downloaded_path: from_path = already_downloaded_path content_type = mimetypes.guess_type(from_path)[0] else: # let's download to a tmp dir from_path, content_type = _download_http_url( link, downloader, temp_dir.path, hashes ) return File(from_path, content_type) def _copy2_ignoring_special_files(src, dest): # type: (str, str) -> None """Copying special files is not supported, but as a convenience to users we skip errors copying them. This supports tools that may create e.g. socket files in the project source directory. """ try: copy2_fixed(src, dest) except shutil.SpecialFileError as e: # SpecialFileError may be raised due to either the source or # destination. If the destination was the cause then we would actually # care, but since the destination directory is deleted prior to # copy we ignore all of them assuming it is caused by the source. logger.warning( "Ignoring special file error '%s' encountered copying %s to %s.", str(e), path_to_display(src), path_to_display(dest), ) def _copy_source_tree(source, target): # type: (str, str) -> None target_abspath = os.path.abspath(target) target_basename = os.path.basename(target_abspath) target_dirname = os.path.dirname(target_abspath) def ignore(d, names): # type: (str, List[str]) -> List[str] skipped = [] # type: List[str] if d == source: # Pulling in those directories can potentially be very slow, # exclude the following directories if they appear in the top # level dir (and only it). # See discussion at https://github.com/pypa/pip/pull/6770 skipped += ['.tox', '.nox'] if os.path.abspath(d) == target_dirname: # Prevent an infinite recursion if the target is in source. # This can happen when TMPDIR is set to ${PWD}/... # and we copy PWD to TMPDIR. skipped += [target_basename] return skipped kwargs = dict(ignore=ignore, symlinks=True) # type: CopytreeKwargs if not PY2: # Python 2 does not support copy_function, so we only ignore # errors on special file copy in Python 3. kwargs['copy_function'] = _copy2_ignoring_special_files shutil.copytree(source, target, **kwargs) def get_file_url( link, # type: Link download_dir=None, # type: Optional[str] hashes=None # type: Optional[Hashes] ): # type: (...) -> File """Get file and optionally check its hash. """ # If a download dir is specified, is the file already there and valid? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir( link, download_dir, hashes ) if already_downloaded_path: from_path = already_downloaded_path else: from_path = link.file_path # If --require-hashes is off, `hashes` is either empty, the # link's embedded hash, or MissingHashes; it is required to # match. If --require-hashes is on, we are satisfied by any # hash in `hashes` matching: a URL-based or an option-based # one; no internet-sourced hash will be in `hashes`. if hashes: hashes.check_against_path(from_path) content_type = mimetypes.guess_type(from_path)[0] return File(from_path, content_type) def unpack_url( link, # type: Link location, # type: str downloader, # type: Downloader download_dir=None, # type: Optional[str] hashes=None, # type: Optional[Hashes] ): # type: (...) -> Optional[File] """Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. """ # non-editable vcs urls if link.is_vcs: unpack_vcs_link(link, location) return None # If it's a url to a local directory if link.is_existing_dir(): if os.path.isdir(location): rmtree(location) _copy_source_tree(link.file_path, location) return None # file urls if link.is_file: file = get_file_url(link, download_dir, hashes=hashes) # http urls else: file = get_http_url( link, downloader, download_dir, hashes=hashes, ) # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies, except wheels if not link.is_wheel: unpack_file(file.path, location, file.content_type) return file def _download_http_url( link, # type: Link downloader, # type: Downloader temp_dir, # type: str hashes, # type: Optional[Hashes] ): # type: (...) -> Tuple[str, str] """Download link url into temp_dir using provided session""" download = downloader(link) file_path = os.path.join(temp_dir, download.filename) with open(file_path, 'wb') as content_file: for chunk in download.chunks: content_file.write(chunk) if hashes: hashes.check_against_path(file_path) return file_path, download.response.headers.get('content-type', '') def _check_download_dir(link, download_dir, hashes): # type: (Link, str, Optional[Hashes]) -> Optional[str] """ Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None """ download_path = os.path.join(download_dir, link.filename) if not os.path.exists(download_path): return None # If already downloaded, does its hash match? logger.info('File was already downloaded %s', download_path) if hashes: try: hashes.check_against_path(download_path) except HashMismatch: logger.warning( 'Previously-downloaded file %s has bad hash. ' 'Re-downloading.', download_path ) os.unlink(download_path) return None return download_path class RequirementPreparer(object): """Prepares a Requirement """ def __init__( self, build_dir, # type: str download_dir, # type: Optional[str] src_dir, # type: str wheel_download_dir, # type: Optional[str] build_isolation, # type: bool req_tracker, # type: RequirementTracker downloader, # type: Downloader finder, # type: PackageFinder require_hashes, # type: bool use_user_site, # type: bool ): # type: (...) -> None super(RequirementPreparer, self).__init__() self.src_dir = src_dir self.build_dir = build_dir self.req_tracker = req_tracker self.downloader = downloader self.finder = finder # Where still-packed archives should be written to. If None, they are # not saved, and are deleted immediately after unpacking. self.download_dir = download_dir # Where still-packed .whl files should be written to. If None, they are # written to the download_dir parameter. Separate to download_dir to # permit only keeping wheel archives for pip wheel. self.wheel_download_dir = wheel_download_dir # NOTE # download_dir and wheel_download_dir overlap semantically and may # be combined if we're willing to have non-wheel archives present in # the wheelhouse output by 'pip wheel'. # Is build isolation allowed? self.build_isolation = build_isolation # Should hash-checking be required? self.require_hashes = require_hashes # Should install in user site-packages? self.use_user_site = use_user_site @property def _download_should_save(self): # type: () -> bool if not self.download_dir: return False if os.path.exists(self.download_dir): return True logger.critical('Could not find download directory') raise InstallationError( "Could not find or access download directory '{}'" .format(self.download_dir)) def _log_preparing_link(self, req): # type: (InstallRequirement) -> None """Log the way the link prepared.""" if req.link.is_file: path = req.link.file_path logger.info('Processing %s', display_path(path)) else: logger.info('Collecting %s', req.req or req) def _ensure_link_req_src_dir(self, req, download_dir, parallel_builds): # type: (InstallRequirement, Optional[str], bool) -> None """Ensure source_dir of a linked InstallRequirement.""" # Since source_dir is only set for editable requirements. if req.link.is_wheel: # We don't need to unpack wheels, so no need for a source # directory. return assert req.source_dir is None # We always delete unpacked sdists after pip runs. req.ensure_has_source_dir( self.build_dir, autodelete=True, parallel_builds=parallel_builds, ) # If a checkout exists, it's unwise to keep going. version # inconsistencies are logged later, but do not fail the # installation. # FIXME: this won't upgrade when there's an existing # package unpacked in `req.source_dir` if os.path.exists(os.path.join(req.source_dir, 'setup.py')): raise PreviousBuildDirError( "pip can't proceed with requirements '{}' due to a" "pre-existing build directory ({}). This is likely " "due to a previous installation that failed . pip is " "being responsible and not assuming it can delete this. " "Please delete it and try again.".format(req, req.source_dir) ) def _get_linked_req_hashes(self, req): # type: (InstallRequirement) -> Hashes # By the time this is called, the requirement's link should have # been checked so we can tell what kind of requirements req is # and raise some more informative errors than otherwise. # (For example, we can raise VcsHashUnsupported for a VCS URL # rather than HashMissing.) if not self.require_hashes: return req.hashes(trust_internet=True) # We could check these first 2 conditions inside unpack_url # and save repetition of conditions, but then we would # report less-useful error messages for unhashable # requirements, complaining that there's no hash provided. if req.link.is_vcs: raise VcsHashUnsupported() if req.link.is_existing_dir(): raise DirectoryUrlHashUnsupported() # Unpinned packages are asking for trouble when a new version # is uploaded. This isn't a security check, but it saves users # a surprising hash mismatch in the future. # file:/// URLs aren't pinnable, so don't complain about them # not being pinned. if req.original_link is None and not req.is_pinned: raise HashUnpinned() # If known-good hashes are missing for this requirement, # shim it with a facade object that will provoke hash # computation and then raise a HashMissing exception # showing the user what the hash should be. return req.hashes(trust_internet=False) or MissingHashes() def prepare_linked_requirement(self, req, parallel_builds=False): # type: (InstallRequirement, bool) -> AbstractDistribution """Prepare a requirement to be obtained from req.link.""" assert req.link link = req.link self._log_preparing_link(req) if link.is_wheel and self.wheel_download_dir: # Download wheels to a dedicated dir when doing `pip wheel`. download_dir = self.wheel_download_dir else: download_dir = self.download_dir with indent_log(): self._ensure_link_req_src_dir(req, download_dir, parallel_builds) try: local_file = unpack_url( link, req.source_dir, self.downloader, download_dir, hashes=self._get_linked_req_hashes(req) ) except NetworkConnectionError as exc: raise InstallationError( 'Could not install requirement {} because of HTTP ' 'error {} for URL {}'.format(req, exc, link) ) # For use in later processing, preserve the file path on the # requirement. if local_file: req.local_file_path = local_file.path abstract_dist = _get_prepared_distribution( req, self.req_tracker, self.finder, self.build_isolation, ) if download_dir: if link.is_existing_dir(): logger.info('Link is a directory, ignoring download_dir') elif local_file: download_location = os.path.join( download_dir, link.filename ) if not os.path.exists(download_location): shutil.copy(local_file.path, download_location) download_path = display_path(download_location) logger.info('Saved %s', download_path) if self._download_should_save: # Make a .zip of the source_dir we already created. if link.is_vcs: req.archive(self.download_dir) return abstract_dist def prepare_editable_requirement( self, req, # type: InstallRequirement ): # type: (...) -> AbstractDistribution """Prepare an editable requirement """ assert req.editable, "cannot prepare a non-editable req as editable" logger.info('Obtaining %s', req) with indent_log(): if self.require_hashes: raise InstallationError( 'The editable requirement {} cannot be installed when ' 'requiring hashes, because there is no single file to ' 'hash.'.format(req) ) req.ensure_has_source_dir(self.src_dir) req.update_editable(not self._download_should_save) abstract_dist = _get_prepared_distribution( req, self.req_tracker, self.finder, self.build_isolation, ) if self._download_should_save: req.archive(self.download_dir) req.check_if_exists(self.use_user_site) return abstract_dist def prepare_installed_requirement( self, req, # type: InstallRequirement skip_reason # type: str ): # type: (...) -> AbstractDistribution """Prepare an already-installed requirement """ assert req.satisfied_by, "req should have been satisfied but isn't" assert skip_reason is not None, ( "did not get skip reason skipped but req.satisfied_by " "is set to {}".format(req.satisfied_by) ) logger.info( 'Requirement %s: %s (%s)', skip_reason, req, req.satisfied_by.version ) with indent_log(): if self.require_hashes: logger.debug( 'Since it is already installed, we are trusting this ' 'package without checking its hash. To ensure a ' 'completely repeatable environment, install into an ' 'empty virtualenv.' ) abstract_dist = InstalledDistribution(req) return abstract_dist operations/check.py000064400000012170152347654150010373 0ustar00"""Validation of dependencies of packages """ import logging from collections import namedtuple from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import RequirementParseError from pip._internal.distributions import ( make_distribution_for_install_requirement, ) from pip._internal.utils.misc import get_installed_distributions from pip._internal.utils.typing import MYPY_CHECK_RUNNING logger = logging.getLogger(__name__) if MYPY_CHECK_RUNNING: from pip._internal.req.req_install import InstallRequirement from typing import ( Any, Callable, Dict, Optional, Set, Tuple, List ) # Shorthands PackageSet = Dict[str, 'PackageDetails'] Missing = Tuple[str, Any] Conflicting = Tuple[str, str, Any] MissingDict = Dict[str, List[Missing]] ConflictingDict = Dict[str, List[Conflicting]] CheckResult = Tuple[MissingDict, ConflictingDict] ConflictDetails = Tuple[PackageSet, CheckResult] PackageDetails = namedtuple('PackageDetails', ['version', 'requires']) def create_package_set_from_installed(**kwargs): # type: (**Any) -> Tuple[PackageSet, bool] """Converts a list of distributions into a PackageSet. """ # Default to using all packages installed on the system if kwargs == {}: kwargs = {"local_only": False, "skip": ()} package_set = {} problems = False for dist in get_installed_distributions(**kwargs): name = canonicalize_name(dist.project_name) try: package_set[name] = PackageDetails(dist.version, dist.requires()) except (OSError, RequirementParseError) as e: # Don't crash on unreadable or broken metadata logger.warning("Error parsing requirements for %s: %s", name, e) problems = True return package_set, problems def check_package_set(package_set, should_ignore=None): # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult """Check if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. """ missing = {} conflicting = {} for package_name in package_set: # Info about dependencies of package_name missing_deps = set() # type: Set[Missing] conflicting_deps = set() # type: Set[Conflicting] if should_ignore and should_ignore(package_name): continue for req in package_set[package_name].requires: name = canonicalize_name(req.project_name) # type: str # Check if it's missing if name not in package_set: missed = True if req.marker is not None: missed = req.marker.evaluate() if missed: missing_deps.add((name, req)) continue # Check if there's a conflict version = package_set[name].version # type: str if not req.specifier.contains(version, prereleases=True): conflicting_deps.add((name, version, req)) if missing_deps: missing[package_name] = sorted(missing_deps, key=str) if conflicting_deps: conflicting[package_name] = sorted(conflicting_deps, key=str) return missing, conflicting def check_install_conflicts(to_install): # type: (List[InstallRequirement]) -> ConflictDetails """For checking if the dependency graph would be consistent after \ installing given requirements """ # Start from the current state package_set, _ = create_package_set_from_installed() # Install packages would_be_installed = _simulate_installation_of(to_install, package_set) # Only warn about directly-dependent packages; create a whitelist of them whitelist = _create_whitelist(would_be_installed, package_set) return ( package_set, check_package_set( package_set, should_ignore=lambda name: name not in whitelist ) ) def _simulate_installation_of(to_install, package_set): # type: (List[InstallRequirement], PackageSet) -> Set[str] """Computes the version of packages after installing to_install. """ # Keep track of packages that were installed installed = set() # Modify it as installing requirement_set would (assuming no errors) for inst_req in to_install: abstract_dist = make_distribution_for_install_requirement(inst_req) dist = abstract_dist.get_pkg_resources_distribution() assert dist is not None name = canonicalize_name(dist.key) package_set[name] = PackageDetails(dist.version, dist.requires()) installed.add(name) return installed def _create_whitelist(would_be_installed, package_set): # type: (Set[str], PackageSet) -> Set[str] packages_affected = set(would_be_installed) for package_name in package_set: if package_name in packages_affected: continue for req in package_set[package_name].requires: if canonicalize_name(req.name) in packages_affected: packages_affected.add(package_name) break return packages_affected operations/freeze.py000064400000024205152347654150010600 0ustar00from __future__ import absolute_import import collections import logging import os from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import RequirementParseError from pip._internal.exceptions import BadCommand, InstallationError from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_file import COMMENT_RE from pip._internal.utils.direct_url_helpers import ( direct_url_as_pep440_direct_reference, dist_get_direct_url, ) from pip._internal.utils.misc import ( dist_is_editable, get_installed_distributions, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Iterator, Optional, List, Container, Set, Dict, Tuple, Iterable, Union ) from pip._internal.cache import WheelCache from pip._vendor.pkg_resources import ( Distribution, Requirement ) RequirementInfo = Tuple[Optional[Union[str, Requirement]], bool, List[str]] logger = logging.getLogger(__name__) def freeze( requirement=None, # type: Optional[List[str]] find_links=None, # type: Optional[List[str]] local_only=False, # type: bool user_only=False, # type: bool paths=None, # type: Optional[List[str]] isolated=False, # type: bool wheel_cache=None, # type: Optional[WheelCache] exclude_editable=False, # type: bool skip=() # type: Container[str] ): # type: (...) -> Iterator[str] find_links = find_links or [] for link in find_links: yield '-f {}'.format(link) installations = {} # type: Dict[str, FrozenRequirement] for dist in get_installed_distributions( local_only=local_only, skip=(), user_only=user_only, paths=paths ): try: req = FrozenRequirement.from_dist(dist) except RequirementParseError as exc: # We include dist rather than dist.project_name because the # dist string includes more information, like the version and # location. We also include the exception message to aid # troubleshooting. logger.warning( 'Could not generate requirement for distribution %r: %s', dist, exc ) continue if exclude_editable and req.editable: continue installations[req.canonical_name] = req if requirement: # the options that don't get turned into an InstallRequirement # should only be emitted once, even if the same option is in multiple # requirements files, so we need to keep track of what has been emitted # so that we don't emit it again if it's seen again emitted_options = set() # type: Set[str] # keep track of which files a requirement is in so that we can # give an accurate warning if a requirement appears multiple times. req_files = collections.defaultdict(list) # type: Dict[str, List[str]] for req_file_path in requirement: with open(req_file_path) as req_file: for line in req_file: if (not line.strip() or line.strip().startswith('#') or line.startswith(( '-r', '--requirement', '-f', '--find-links', '-i', '--index-url', '--pre', '--trusted-host', '--process-dependency-links', '--extra-index-url', '--use-feature'))): line = line.rstrip() if line not in emitted_options: emitted_options.add(line) yield line continue if line.startswith('-e') or line.startswith('--editable'): if line.startswith('-e'): line = line[2:].strip() else: line = line[len('--editable'):].strip().lstrip('=') line_req = install_req_from_editable( line, isolated=isolated, ) else: line_req = install_req_from_line( COMMENT_RE.sub('', line).strip(), isolated=isolated, ) if not line_req.name: logger.info( "Skipping line in requirement file [%s] because " "it's not clear what it would install: %s", req_file_path, line.strip(), ) logger.info( " (add #egg=PackageName to the URL to avoid" " this warning)" ) else: line_req_canonical_name = canonicalize_name( line_req.name) if line_req_canonical_name not in installations: # either it's not installed, or it is installed # but has been processed already if not req_files[line_req.name]: logger.warning( "Requirement file [%s] contains %s, but " "package %r is not installed", req_file_path, COMMENT_RE.sub('', line).strip(), line_req.name ) else: req_files[line_req.name].append(req_file_path) else: yield str(installations[ line_req_canonical_name]).rstrip() del installations[line_req_canonical_name] req_files[line_req.name].append(req_file_path) # Warn about requirements that were included multiple times (in a # single requirements file or in different requirements files). for name, files in six.iteritems(req_files): if len(files) > 1: logger.warning("Requirement %s included multiple times [%s]", name, ', '.join(sorted(set(files)))) yield( '## The following requirements were added by ' 'pip freeze:' ) for installation in sorted( installations.values(), key=lambda x: x.name.lower()): if installation.canonical_name not in skip: yield str(installation).rstrip() def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). """ if not dist_is_editable(dist): return (None, False, []) location = os.path.normcase(os.path.abspath(dist.location)) from pip._internal.vcs import vcs, RemoteNotFoundError vcs_backend = vcs.get_backend_for_dir(location) if vcs_backend is None: req = dist.as_requirement() logger.debug( 'No VCS found for editable requirement "%s" in: %r', req, location, ) comments = [ '# Editable install with no version control ({})'.format(req) ] return (location, True, comments) try: req = vcs_backend.get_src_requirement(location, dist.project_name) except RemoteNotFoundError: req = dist.as_requirement() comments = [ '# Editable {} install with no remote ({})'.format( type(vcs_backend).__name__, req, ) ] return (location, True, comments) except BadCommand: logger.warning( 'cannot determine version of editable source in %s ' '(%s command not found in path)', location, vcs_backend.name, ) return (None, True, []) except InstallationError as exc: logger.warning( "Error when trying to get requirement for VCS system %s, " "falling back to uneditable format", exc ) else: if req is not None: return (req, True, []) logger.warning( 'Could not determine repository location of %s', location ) comments = ['## !! Could not determine repository location'] return (None, False, comments) class FrozenRequirement(object): def __init__(self, name, req, editable, comments=()): # type: (str, Union[str, Requirement], bool, Iterable[str]) -> None self.name = name self.canonical_name = canonicalize_name(name) self.req = req self.editable = editable self.comments = comments @classmethod def from_dist(cls, dist): # type: (Distribution) -> FrozenRequirement # TODO `get_requirement_info` is taking care of editable requirements. # TODO This should be refactored when we will add detection of # editable that provide .dist-info metadata. req, editable, comments = get_requirement_info(dist) if req is None and not editable: # if PEP 610 metadata is present, attempt to use it direct_url = dist_get_direct_url(dist) if direct_url: req = direct_url_as_pep440_direct_reference( direct_url, dist.project_name ) comments = [] if req is None: # name==version requirement req = dist.as_requirement() return cls(dist.project_name, req, editable, comments=comments) def __str__(self): # type: () -> str req = self.req if self.editable: req = '-e {}'.format(req) return '\n'.join(list(self.comments) + [str(req)]) + '\n' operations/__init__.py000064400000000000152347654150011042 0ustar00operations/generate_metadata.py000064400000011133152347654150012746 0ustar00"""Metadata generation logic for source distributions. """ import logging import os from pip._internal.exceptions import InstallationError from pip._internal.utils.misc import ensure_dir from pip._internal.utils.setuptools_build import make_setuptools_shim_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.vcs import vcs if MYPY_CHECK_RUNNING: from typing import Callable, List from pip._internal.req.req_install import InstallRequirement logger = logging.getLogger(__name__) def get_metadata_generator(install_req): # type: (InstallRequirement) -> Callable[[InstallRequirement], str] """Return a callable metadata generator for this InstallRequirement. A metadata generator takes an InstallRequirement (install_req) as an input, generates metadata via the appropriate process for that install_req and returns the generated metadata directory. """ if not install_req.use_pep517: return _generate_metadata_legacy return _generate_metadata def _find_egg_info(source_directory, is_editable): # type: (str, bool) -> str """Find an .egg-info in `source_directory`, based on `is_editable`. """ def looks_like_virtual_env(path): # type: (str) -> bool return ( os.path.lexists(os.path.join(path, 'bin', 'python')) or os.path.exists(os.path.join(path, 'Scripts', 'Python.exe')) ) def locate_editable_egg_info(base): # type: (str) -> List[str] candidates = [] # type: List[str] for root, dirs, files in os.walk(base): for dir_ in vcs.dirnames: if dir_ in dirs: dirs.remove(dir_) # Iterate over a copy of ``dirs``, since mutating # a list while iterating over it can cause trouble. # (See https://github.com/pypa/pip/pull/462.) for dir_ in list(dirs): if looks_like_virtual_env(os.path.join(root, dir_)): dirs.remove(dir_) # Also don't search through tests elif dir_ == 'test' or dir_ == 'tests': dirs.remove(dir_) candidates.extend(os.path.join(root, dir_) for dir_ in dirs) return [f for f in candidates if f.endswith('.egg-info')] def depth_of_directory(dir_): # type: (str) -> int return ( dir_.count(os.path.sep) + (os.path.altsep and dir_.count(os.path.altsep) or 0) ) base = source_directory if is_editable: filenames = locate_editable_egg_info(base) else: base = os.path.join(base, 'pip-egg-info') filenames = os.listdir(base) if not filenames: raise InstallationError( "Files/directories not found in %s" % base ) # If we have more than one match, we pick the toplevel one. This # can easily be the case if there is a dist folder which contains # an extracted tarball for testing purposes. if len(filenames) > 1: filenames.sort(key=depth_of_directory) return os.path.join(base, filenames[0]) def _generate_metadata_legacy(install_req): # type: (InstallRequirement) -> str req_details_str = install_req.name or "from {}".format(install_req.link) logger.debug( 'Running setup.py (path:%s) egg_info for package %s', install_req.setup_py_path, req_details_str, ) # Compose arguments for subprocess call base_cmd = make_setuptools_shim_args(install_req.setup_py_path) if install_req.isolated: base_cmd += ["--no-user-cfg"] # For non-editable installs, don't put the .egg-info files at the root, # to avoid confusion due to the source code being considered an installed # egg. egg_base_option = [] # type: List[str] if not install_req.editable: egg_info_dir = os.path.join( install_req.unpacked_source_directory, 'pip-egg-info', ) egg_base_option = ['--egg-base', egg_info_dir] # setuptools complains if the target directory does not exist. ensure_dir(egg_info_dir) with install_req.build_env: call_subprocess( base_cmd + ["egg_info"] + egg_base_option, cwd=install_req.unpacked_source_directory, command_desc='python setup.py egg_info', ) # Return the .egg-info directory. return _find_egg_info( install_req.unpacked_source_directory, install_req.editable, ) def _generate_metadata(install_req): # type: (InstallRequirement) -> str return install_req.prepare_pep517_metadata() network/__pycache__/session.cpython-38.pyc000064400000022012152347654150014571 0ustar00U .e=@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z m Z ddlmZddlmZmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd l m!Z!dd l"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1e/rhddl2m3Z3m4Z4m5Z5m6Z6m7Z7ddl8m9Z9e6e:e:e5e7e;e:ffZZ?e j@dedddddddgZAdZBddZCd d!ZDGd"d#d#eZEGd$d%d%eZFGd&d'd'e jGZHdS)(zhPipSession and supporting code, containing all pip-specific network request configuration and behavior. N)requestssixurllib3)CacheControlAdapter) BaseAdapter HTTPAdapter)Response)CaseInsensitiveDict)parse)InsecureRequestWarning) __version__)MultiDomainBasicAuth) SafeFileCache)HAS_TLS ipaddressssl)check_path_owner)libc_ver)build_url_from_netlocget_installed_version parse_netloc)MYPY_CHECK_RUNNING) url_to_path)IteratorListOptionalTupleUnion)Linkignore)category)Zhttps*r!)r!Z localhostr!)r!z 127.0.0.0/8r!)r!z::1/128r!)filer!N)Zsshr!r!)Z BUILD_BUILDIDZBUILD_IDZCIZ PIP_IS_CIcCstddtDS)z? Return whether it looks like pip is running under CI. css|]}|tjkVqdSN)osenviron).0namer(A/usr/lib/python3.8/site-packages/pip/_internal/network/session.py asz looks_like_ci..)anyCI_ENVIRONMENT_VARIABLESr(r(r(r) looks_like_ciYsr-cCsBdtdtdtid}|dddkr@t|dd<n|dddkrtjjd krltjd d }ntj}d d d|D|dd<nB|dddkrt|dd<n |dddkrt|dd<tjdrHddl m }t t ddt dddg|}t t ddt ddgt}|r:||d<|rH||d<tjdrztdrzdtdd|d<trt|did<trt|did<trt|d<trtj|d <td!}|d k r||d"<trd#nd |d$<tjd%}|d k r(||d&<d'j|tj|d(d#d)d*S)+z6 Return a string representing the user agent. pip)r'versionr')Z installerpythonimplementationr1ZCPythonr/ZPyPyfinalN.cSsg|] }t|qSr()str)r&xr(r(r) xszuser_agent..ZJythonZ IronPythonZlinuxr)distrocSs|dSNr(r6r(r(r)zuser_agent..idcSs|dSr9r(r;r(r(r)r<r=liblibcr8darwinZmacOSsystemreleaseZcpuZopenssl_versionZ setuptoolssetuptools_versionTZciZPIP_USER_AGENT_USER_DATA user_dataz9{data[installer][name]}/{data[installer][version]} {json}),:)Z separatorsZ sort_keys)datajson) r platformZpython_versionZpython_implementationsyspypy_version_info releaseleveljoin startswith pip._vendorr8dictfilterzipZlinux_distributionrZmac_verrB setdefaultrCmachinerrZOPENSSL_VERSIONrr-r$r%getformatrIdumps)rHrLr8Z distro_infosr@rDrEr(r(r) user_agentdsl           rYc@seZdZdddZddZdS)LocalFSAdapterNc Cst|j}t}d|_|j|_zt|} Wn.tk rZ} zd|_| |_W5d} ~ XYnPXtj j | j dd} t |dp~d} t| | j| d|_t|d|_|jj|_|S) NiT)Zusegmtrz text/plain)z Content-TypezContent-Lengthz Last-Modifiedrb)rurlrZ status_coder$statOSErrorrawemailZutilsZ formatdatest_mtime mimetypesZ guess_typer st_sizeheadersopenclose) selfrequeststreamtimeoutverifycertZproxiespathnameZrespZstatsexcZmodifiedZ content_typer(r(r)sends&    zLocalFSAdapter.sendcCsdSr#r()rhr(r(r)rgszLocalFSAdapter.close)NNNNN)__name__ __module__ __qualname__rprgr(r(r(r)rZs rZc@seZdZddZdS)InsecureHTTPAdaptercCsd|_d|_dS)NZ CERT_NONE)Z cert_reqsZca_certs)rhZconnr]rlrmr(r(r) cert_verifyszInsecureHTTPAdapter.cert_verifyN)rqrrrsrur(r(r(r)rtsrtcsFeZdZdZfddZd ddZddZd d Zfd d ZZ S) PipSessionNc s|dd}|dd}|dg}|dd}tt|j||g|_t|jd<t|d|_t j |d d d d gd d}|rt |st d|d}|rtt||d}n t|d}t|d}||_|d||d||dt|D]} |j| ddqdS)zj :param trusted_hosts: Domains not to emit warnings for when not using HTTPS. retriesrcacheN trusted_hosts index_urlsz User-Agent)rziiiig?)ZtotalZstatus_forcelistZbackoff_factorzThe directory '%s' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.)rx max_retries)r{zhttps://zhttp://zfile://T)suppress_logging)popsuperrv__init__pip_trusted_originsrYrer ZauthrZRetryrloggerwarningrrrrt_insecure_adaptermountrZadd_trusted_host) rhargskwargsrwrxryrzZsecure_adapterZinsecure_adapterhost __class__r(r)rs@            zPipSession.__init__FcCs|s.d|}|dk r$|d|7}t|t|}||jkrL|j||t|d|j|ds|t|d|jdS)z :param host: It is okay to provide a host that has previously been added. :param source: An optional source string, for logging where the host string came from. zadding trusted host: {!r}Nz (from {})/r:rG) rWrinforrappendrrr)rhrsourcer|msgZ host_portr(r(r)r3s     zPipSession.add_trusted_hostccs<tD] }|Vq|jD] \}}d||dkr.dn|fVqdS)Nr!)SECURE_ORIGINSr)rh secure_originrportr(r(r)iter_secure_originsMszPipSession.iter_secure_originsc Cs tt|}|j|j|j}}}|ddd}|D]}|\}}} ||kr\|dkr\qsV                O!network/__pycache__/cache.cpython-38.pyc000064400000004671152347654150014164 0ustar00U .e@sdZddlZddlmZddlmZddlmZddlm Z m Z ddl m Z ddl mZerhdd lmZed d ZGd d d eZdS)zHTTP cache implementation. N)contextmanager) BaseCache) FileCache)adjacent_tmp_filereplace) ensure_dir)MYPY_CHECK_RUNNING)Optionalc cs(z dVWnttfk r"YnXdS)zvIf we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. N)OSErrorIOErrorr r ?/usr/lib/python3.8/site-packages/pip/_internal/network/cache.pysuppressed_cache_errorss rcs@eZdZdZfddZddZddZdd Zd d ZZ S) SafeFileCachezw A file based cache which is safe to use even when the target directory may not be accessible or writable. cs(|dk stdtt|||_dS)Nz!Cache directory must not be None.)AssertionErrorsuperr__init__ directory)selfr __class__r r r&szSafeFileCache.__init__cCs4t|}t|dd|g}tjj|jf|S)N)rencodelistospathjoinr)rnameZhashedpartsr r r _get_cache_path,s zSafeFileCache._get_cache_pathc CsR||}t8t|d"}|W5QRW5QRSQRXW5QRXdS)Nrb)rropenread)rkeyrfr r r get5s  zSafeFileCache.getc CsZ||}t@ttj|t|}||W5QRXt|j |W5QRXdSN) rrrrrdirnamerwriterr)rr#valuerr$r r r set<s   zSafeFileCache.setc Cs*||}tt|W5QRXdSr&)rrrremove)rr#rr r r deleteGs zSafeFileCache.delete) __name__ __module__ __qualname____doc__rrr%r*r, __classcell__r r rr r s    r)r0r contextlibrZpip._vendor.cachecontrol.cacherZpip._vendor.cachecontrol.cachesrZpip._internal.utils.filesystemrrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingr rrr r r r s       network/__pycache__/cache.cpython-38.opt-1.pyc000064400000004566152347654150015126 0ustar00U .e@sdZddlZddlmZddlmZddlmZddlm Z m Z ddl m Z ddl mZerhdd lmZed d ZGd d d eZdS)zHTTP cache implementation. N)contextmanager) BaseCache) FileCache)adjacent_tmp_filereplace) ensure_dir)MYPY_CHECK_RUNNING)Optionalc cs(z dVWnttfk r"YnXdS)zvIf we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. N)OSErrorIOErrorr r ?/usr/lib/python3.8/site-packages/pip/_internal/network/cache.pysuppressed_cache_errorss rcs@eZdZdZfddZddZddZdd Zd d ZZ S) SafeFileCachezw A file based cache which is safe to use even when the target directory may not be accessible or writable. cstt|||_dSN)superr__init__ directory)selfr __class__r r r&szSafeFileCache.__init__cCs4t|}t|dd|g}tjj|jf|S)N)rencodelistospathjoinr)rnameZhashedpartsr r r _get_cache_path,s zSafeFileCache._get_cache_pathc CsR||}t8t|d"}|W5QRW5QRSQRXW5QRXdS)Nrb)rropenread)rkeyrfr r r get5s  zSafeFileCache.getc CsZ||}t@ttj|t|}||W5QRXt|j |W5QRXdSr) rrrrrdirnamerwriterr)rr#valuerr$r r r set<s   zSafeFileCache.setc Cs*||}tt|W5QRXdSr)rrrremove)rr#rr r r deleteGs zSafeFileCache.delete) __name__ __module__ __qualname____doc__rrr%r)r+ __classcell__r r rr r s    r)r/r contextlibrZpip._vendor.cachecontrol.cacherZpip._vendor.cachecontrol.cachesrZpip._internal.utils.filesystemrrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingr rrr r r r s       network/__pycache__/__init__.cpython-38.pyc000064400000000324152347654150014647 0ustar00U .e2@sdZdS)z+Contains purely network-related utilities. N)__doc__rrB/usr/lib/python3.8/site-packages/pip/_internal/network/__init__.pynetwork/__pycache__/xmlrpc.cpython-38.pyc000064400000003046152347654150014421 0ustar00U .e=@sPdZddlZddlmZddlmZddlmZe e Z Gdddej Z dS)z#xmlrpclib.Transport implementation N)requests) xmlrpc_client)parsec@s$eZdZdZdddZd ddZdS) PipXmlrpcTransportzRProvide a `xmlrpclib.Transport` implementation via a `PipSession` object. FcCs*tj||t|}|j|_||_dS)N)r Transport__init__ urllib_parseZurlparseZscheme_scheme_session)selfZ index_urlZsessionZ use_datetimeZ index_partsr @/usr/lib/python3.8/site-packages/pip/_internal/network/xmlrpc.pyrs zPipXmlrpcTransport.__init__c Cs|j||dddf}t|}z8ddi}|jj|||dd}|||_||jWSt j k r} zt d| j j|W5d} ~ XYnXdS)Nz Content-Typeztext/xmlT)dataheadersstreamzHTTP error %s while getting %s)r rZ urlunparser ZpostZraise_for_statusverboseZparse_responserawrZ HTTPErrorloggerZcriticalresponseZ status_code) r ZhostZhandlerZ request_bodyrpartsZurlrrexcr r r requests$  zPipXmlrpcTransport.requestN)F)F)__name__ __module__ __qualname____doc__rrr r r r rs r)rZloggingZ pip._vendorrZpip._vendor.six.movesrZpip._vendor.six.moves.urllibrrZ getLoggerrrrrr r r r s     network/__pycache__/auth.cpython-38.pyc000064400000015502152347654150014055 0ustar00U .eo+ @sdZddlZddlmZmZddlmZddlmZ ddl m Z m Z m Z mZmZddlmZerddlmZdd lmZmZmZdd lmZeeeefZeeZz ddlZWnLe k rdZYn6e!k rZ"ze#d ee"dZW5dZ"["XYnXd d Z$GdddeZ%dS)zNetwork Authentication Helpers Contains interface (MultiDomainBasicAuth) and associated glue code for providing credentials in the context of network requests. N)AuthBase HTTPBasicAuth)get_netrc_auth)parse)ask ask_input ask_passwordremove_auth_from_urlsplit_auth_netloc_from_url)MYPY_CHECK_RUNNING)Values)DictOptionalTuple)AuthInfo*Keyring is skipped due to an exception: %sc Cs|rts dSzz tj}Wntk r,Yn4Xtd||||}|dk rZ|j|jfWSWdS|rtd|t||}|r||fWSWn2tk r}zt dt |W5d}~XYnXdS)z3Return the tuple auth for a given url from keyring.Nz'Getting credentials from keyring for %sz$Getting password from keyring for %sr) keyringget_credentialAttributeErrorloggerdebugusernamepasswordZ get_password Exceptionwarningstr)urlrrZcredrexcr>/usr/lib/python3.8/site-packages/pip/_internal/network/auth.pyget_keyring_auth.s,     r c@s`eZdZdddZddZdddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS)MultiDomainBasicAuthTNcCs||_||_i|_d|_dS)N) prompting index_urls passwords_credentials_to_save)selfr"r#rrr__init__MszMultiDomainBasicAuth.__init__cCsB|r |jsdS|jD](}t|dd}||r|SqdS)aReturn the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentials then they will be included in the return value. Returns None if no matching index was found, or if --no-index was specified by the user. N/)r#r rstrip startswith)r&ruprefixrrr_get_index_urlYs   z#MultiDomainBasicAuth._get_index_urlcCst|\}}}|\}}|dk r6|dk r6td||S||} | rft| } | rf| \} } } td| | r| ddk r| \}}|dk r|dk rtd|| S|rt|} | rtd|| S|rt| |pt||}|rtd||S||fS)z2Find and return credentials for the specified URL.NzFound credentials in url for %szFound index url %srz%Found credentials in index url for %sz!Found credentials in netrc for %sz#Found credentials in keyring for %s)r rrr-rr )r& original_urlZ allow_netrcZ allow_keyringrnetlocZurl_user_passwordrrZ index_urlZ index_info_Zindex_url_user_passwordZ netrc_authZkr_authrrr_get_new_credentialsns>         z)MultiDomainBasicAuth._get_new_credentialscCst|\}}}|j|d\}}|dkr>|dkr>||\}}|dk sN|dk rl|pTd}|p\d}||f|j|<|dk r||dk s|dkr|dkstd||||fS)a_Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different username and password. NNNz'Could not load credentials from url: {})r r$getr1AssertionErrorformat)r&r.rr/r0rrrrr_get_url_and_credentialss& z-MultiDomainBasicAuth._get_url_and_credentialscCsH||j\}}}||_|dk r6|dk r6t|||}|d|j|S)Nresponse)r7rr register_hook handle_401)r&reqrrrrrr__call__s zMultiDomainBasicAuth.__call__cCsFtd|}|sdSt||}|r4|d|ddfStd}||dfS)Nz User for %s: r2rFz Password: T)rr r)r&r/rZauthrrrr_prompt_for_passwords  z)MultiDomainBasicAuth._prompt_for_passwordcCstsdStdddgdkS)NFz#Save credentials to keyring [y/N]: yn)rr)r&rrr _should_save_password_to_keyringsz5MultiDomainBasicAuth._should_save_password_to_keyringc Ks|jdkr|S|js|St|j}||j\}}}d|_|dk rv|dk rv||f|j|j<|rv| rv|j||f|_|j |j t |pd|pd|j}|d|j|jr|d|j|jj|f|}|j||S)Nr3r8) status_coder" urllib_parseZurlparserr>r/r%r$rAZcontentrawZ release_connrrequestr9 warn_on_401save_credentialsZ connectionsendhistoryappend) r&respkwargsZparsedrrZsaver;Znew_resprrrr:s(     zMultiDomainBasicAuth.handle_401cKs|jdkrtd|jjdS)z6Response callback to warn about incorrect credentials.rBz)401 Error, Credentials not correct for %sN)rCrrrFr)r&rLrMrrrrGs  z MultiDomainBasicAuth.warn_on_401cKsntdk stdtsdS|j}d|_|rj|jdkrjztdtj|Wntk rhtdYnXdS)z1Response callback to save credentials on success.Nz'should never reach here without keyringizSaving credentials to keyringzFailed to save credentials) rr5r%rCrinfoZ set_passwordrZ exception)r&rLrMZcredsrrrrHs z%MultiDomainBasicAuth.save_credentials)TN)TT) __name__ __module__ __qualname__r'r-r1r7r<r>rAr:rGrHrrrrr!Ks  2( -r!)&__doc__ZloggingZpip._vendor.requests.authrrZpip._vendor.requests.utilsrZpip._vendor.six.moves.urllibrrDZpip._internal.utils.miscrrrr r Zpip._internal.utils.typingr Zoptparser typingr rrZ pip._internal.vcs.versioncontrolrrZ CredentialsZ getLoggerrOrr ImportErrorrrrr r!rrrrs0        network/__pycache__/xmlrpc.cpython-38.opt-1.pyc000064400000003046152347654150015360 0ustar00U .e=@sPdZddlZddlmZddlmZddlmZe e Z Gdddej Z dS)z#xmlrpclib.Transport implementation N)requests) xmlrpc_client)parsec@s$eZdZdZdddZd ddZdS) PipXmlrpcTransportzRProvide a `xmlrpclib.Transport` implementation via a `PipSession` object. FcCs*tj||t|}|j|_||_dS)N)r Transport__init__ urllib_parseZurlparseZscheme_scheme_session)selfZ index_urlZsessionZ use_datetimeZ index_partsr @/usr/lib/python3.8/site-packages/pip/_internal/network/xmlrpc.pyrs zPipXmlrpcTransport.__init__c Cs|j||dddf}t|}z8ddi}|jj|||dd}|||_||jWSt j k r} zt d| j j|W5d} ~ XYnXdS)Nz Content-Typeztext/xmlT)dataheadersstreamzHTTP error %s while getting %s)r rZ urlunparser ZpostZraise_for_statusverboseZparse_responserawrZ HTTPErrorloggerZcriticalresponseZ status_code) r ZhostZhandlerZ request_bodyrpartsZurlrrexcr r r requests$  zPipXmlrpcTransport.requestN)F)F)__name__ __module__ __qualname____doc__rrr r r r rs r)rZloggingZ pip._vendorrZpip._vendor.six.movesrZpip._vendor.six.moves.urllibrrZ getLoggerrrrrr r r r s     network/__pycache__/session.cpython-38.opt-1.pyc000064400000022012152347654150015530 0ustar00U .e=@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z m Z ddlmZddlmZmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd l m!Z!dd l"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1e/rhddl2m3Z3m4Z4m5Z5m6Z6m7Z7ddl8m9Z9e6e:e:e5e7e;e:ffZZ?e j@dedddddddgZAdZBddZCd d!ZDGd"d#d#eZEGd$d%d%eZFGd&d'd'e jGZHdS)(zhPipSession and supporting code, containing all pip-specific network request configuration and behavior. N)requestssixurllib3)CacheControlAdapter) BaseAdapter HTTPAdapter)Response)CaseInsensitiveDict)parse)InsecureRequestWarning) __version__)MultiDomainBasicAuth) SafeFileCache)HAS_TLS ipaddressssl)check_path_owner)libc_ver)build_url_from_netlocget_installed_version parse_netloc)MYPY_CHECK_RUNNING) url_to_path)IteratorListOptionalTupleUnion)Linkignore)category)Zhttps*r!)r!Z localhostr!)r!z 127.0.0.0/8r!)r!z::1/128r!)filer!N)Zsshr!r!)Z BUILD_BUILDIDZBUILD_IDZCIZ PIP_IS_CIcCstddtDS)z? Return whether it looks like pip is running under CI. css|]}|tjkVqdSN)osenviron).0namer(A/usr/lib/python3.8/site-packages/pip/_internal/network/session.py asz looks_like_ci..)anyCI_ENVIRONMENT_VARIABLESr(r(r(r) looks_like_ciYsr-cCsBdtdtdtid}|dddkr@t|dd<n|dddkrtjjd krltjd d }ntj}d d d|D|dd<nB|dddkrt|dd<n |dddkrt|dd<tjdrHddl m }t t ddt dddg|}t t ddt ddgt}|r:||d<|rH||d<tjdrztdrzdtdd|d<trt|did<trt|did<trt|d<trtj|d <td!}|d k r||d"<trd#nd |d$<tjd%}|d k r(||d&<d'j|tj|d(d#d)d*S)+z6 Return a string representing the user agent. pip)r'versionr')Z installerpythonimplementationr1ZCPythonr/ZPyPyfinalN.cSsg|] }t|qSr()str)r&xr(r(r) xszuser_agent..ZJythonZ IronPythonZlinuxr)distrocSs|dSNr(r6r(r(r)zuser_agent..idcSs|dSr9r(r;r(r(r)r<r=liblibcr8darwinZmacOSsystemreleaseZcpuZopenssl_versionZ setuptoolssetuptools_versionTZciZPIP_USER_AGENT_USER_DATA user_dataz9{data[installer][name]}/{data[installer][version]} {json}),:)Z separatorsZ sort_keys)datajson) r platformZpython_versionZpython_implementationsyspypy_version_info releaseleveljoin startswith pip._vendorr8dictfilterzipZlinux_distributionrZmac_verrB setdefaultrCmachinerrZOPENSSL_VERSIONrr-r$r%getformatrIdumps)rHrLr8Z distro_infosr@rDrEr(r(r) user_agentdsl           rYc@seZdZdddZddZdS)LocalFSAdapterNc Cst|j}t}d|_|j|_zt|} Wn.tk rZ} zd|_| |_W5d} ~ XYnPXtj j | j dd} t |dp~d} t| | j| d|_t|d|_|jj|_|S) NiT)Zusegmtrz text/plain)z Content-TypezContent-Lengthz Last-Modifiedrb)rurlrZ status_coder$statOSErrorrawemailZutilsZ formatdatest_mtime mimetypesZ guess_typer st_sizeheadersopenclose) selfrequeststreamtimeoutverifycertZproxiespathnameZrespZstatsexcZmodifiedZ content_typer(r(r)sends&    zLocalFSAdapter.sendcCsdSr#r()rhr(r(r)rgszLocalFSAdapter.close)NNNNN)__name__ __module__ __qualname__rprgr(r(r(r)rZs rZc@seZdZddZdS)InsecureHTTPAdaptercCsd|_d|_dS)NZ CERT_NONE)Z cert_reqsZca_certs)rhZconnr]rlrmr(r(r) cert_verifyszInsecureHTTPAdapter.cert_verifyN)rqrrrsrur(r(r(r)rtsrtcsFeZdZdZfddZd ddZddZd d Zfd d ZZ S) PipSessionNc s|dd}|dd}|dg}|dd}tt|j||g|_t|jd<t|d|_t j |d d d d gd d}|rt |st d|d}|rtt||d}n t|d}t|d}||_|d||d||dt|D]} |j| ddqdS)zj :param trusted_hosts: Domains not to emit warnings for when not using HTTPS. retriesrcacheN trusted_hosts index_urlsz User-Agent)rziiiig?)ZtotalZstatus_forcelistZbackoff_factorzThe directory '%s' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.)rx max_retries)r{zhttps://zhttp://zfile://T)suppress_logging)popsuperrv__init__pip_trusted_originsrYrer ZauthrZRetryrloggerwarningrrrrt_insecure_adaptermountrZadd_trusted_host) rhargskwargsrwrxryrzZsecure_adapterZinsecure_adapterhost __class__r(r)rs@            zPipSession.__init__FcCs|s.d|}|dk r$|d|7}t|t|}||jkrL|j||t|d|j|ds|t|d|jdS)z :param host: It is okay to provide a host that has previously been added. :param source: An optional source string, for logging where the host string came from. zadding trusted host: {!r}Nz (from {})/r:rG) rWrinforrappendrrr)rhrsourcer|msgZ host_portr(r(r)r3s     zPipSession.add_trusted_hostccs<tD] }|Vq|jD] \}}d||dkr.dn|fVqdS)Nr!)SECURE_ORIGINSr)rh secure_originrportr(r(r)iter_secure_originsMszPipSession.iter_secure_originsc Cs tt|}|j|j|j}}}|ddd}|D]}|\}}} ||kr\|dkr\qsV                O!network/__pycache__/auth.cpython-38.opt-1.pyc000064400000015177152347654150015024 0ustar00U .eo+ @sdZddlZddlmZmZddlmZddlmZ ddl m Z m Z m Z mZmZddlmZerddlmZdd lmZmZmZdd lmZeeeefZeeZz ddlZWnLe k rdZYn6e!k rZ"ze#d ee"dZW5dZ"["XYnXd d Z$GdddeZ%dS)zNetwork Authentication Helpers Contains interface (MultiDomainBasicAuth) and associated glue code for providing credentials in the context of network requests. N)AuthBase HTTPBasicAuth)get_netrc_auth)parse)ask ask_input ask_passwordremove_auth_from_urlsplit_auth_netloc_from_url)MYPY_CHECK_RUNNING)Values)DictOptionalTuple)AuthInfo*Keyring is skipped due to an exception: %sc Cs|rts dSzz tj}Wntk r,Yn4Xtd||||}|dk rZ|j|jfWSWdS|rtd|t||}|r||fWSWn2tk r}zt dt |W5d}~XYnXdS)z3Return the tuple auth for a given url from keyring.Nz'Getting credentials from keyring for %sz$Getting password from keyring for %sr) keyringget_credentialAttributeErrorloggerdebugusernamepasswordZ get_password Exceptionwarningstr)urlrrZcredrexcr>/usr/lib/python3.8/site-packages/pip/_internal/network/auth.pyget_keyring_auth.s,     r c@s`eZdZdddZddZdddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS)MultiDomainBasicAuthTNcCs||_||_i|_d|_dS)N) prompting index_urls passwords_credentials_to_save)selfr"r#rrr__init__MszMultiDomainBasicAuth.__init__cCsB|r |jsdS|jD](}t|dd}||r|SqdS)aReturn the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentials then they will be included in the return value. Returns None if no matching index was found, or if --no-index was specified by the user. N/)r#r rstrip startswith)r&ruprefixrrr_get_index_urlYs   z#MultiDomainBasicAuth._get_index_urlcCst|\}}}|\}}|dk r6|dk r6td||S||} | rft| } | rf| \} } } td| | r| ddk r| \}}|dk r|dk rtd|| S|rt|} | rtd|| S|rt| |pt||}|rtd||S||fS)z2Find and return credentials for the specified URL.NzFound credentials in url for %szFound index url %srz%Found credentials in index url for %sz!Found credentials in netrc for %sz#Found credentials in keyring for %s)r rrr-rr )r& original_urlZ allow_netrcZ allow_keyringrnetlocZurl_user_passwordrrZ index_urlZ index_info_Zindex_url_user_passwordZ netrc_authZkr_authrrr_get_new_credentialsns>         z)MultiDomainBasicAuth._get_new_credentialscCsvt|\}}}|j|d\}}|dkr>|dkr>||\}}|dk sN|dk rl|pTd}|p\d}||f|j|<|||fS)a_Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different username and password. NNN)r r$getr1)r&r.rr/r0rrrrr_get_url_and_credentialss  z-MultiDomainBasicAuth._get_url_and_credentialscCsH||j\}}}||_|dk r6|dk r6t|||}|d|j|S)Nresponse)r5rr register_hook handle_401)r&reqrrrrrr__call__s zMultiDomainBasicAuth.__call__cCsFtd|}|sdSt||}|r4|d|ddfStd}||dfS)Nz User for %s: r2rFz Password: T)rr r)r&r/rZauthrrrr_prompt_for_passwords  z)MultiDomainBasicAuth._prompt_for_passwordcCstsdStdddgdkS)NFz#Save credentials to keyring [y/N]: yn)rr)r&rrr _should_save_password_to_keyringsz5MultiDomainBasicAuth._should_save_password_to_keyringc Ks|jdkr|S|js|St|j}||j\}}}d|_|dk rv|dk rv||f|j|j<|rv| rv|j||f|_|j |j t |pd|pd|j}|d|j|jr|d|j|jj|f|}|j||S)Nr3r6) status_coder" urllib_parseZurlparserr<r/r%r$r?ZcontentrawZ release_connrrequestr7 warn_on_401save_credentialsZ connectionsendhistoryappend) r&respkwargsZparsedrrZsaver9Znew_resprrrr8s(     zMultiDomainBasicAuth.handle_401cKs|jdkrtd|jjdS)z6Response callback to warn about incorrect credentials.r@z)401 Error, Credentials not correct for %sN)rArrrDr)r&rJrKrrrrEs  z MultiDomainBasicAuth.warn_on_401cKs^tsdS|j}d|_|rZ|jdkrZztdtj|Wntk rXtdYnXdS)z1Response callback to save credentials on success.NizSaving credentials to keyringzFailed to save credentials)rr%rArinfoZ set_passwordrZ exception)r&rJrKZcredsrrrrFs z%MultiDomainBasicAuth.save_credentials)TN)TT) __name__ __module__ __qualname__r'r-r1r5r:r<r?r8rErFrrrrr!Ks  2( -r!)&__doc__ZloggingZpip._vendor.requests.authrrZpip._vendor.requests.utilsrZpip._vendor.six.moves.urllibrrBZpip._internal.utils.miscrrrr r Zpip._internal.utils.typingr Zoptparser typingr rrZ pip._internal.vcs.versioncontrolrrZ CredentialsZ getLoggerrMrr ImportErrorrrrr r!rrrrs0        network/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000324152347654150015606 0ustar00U .e2@sdZdS)z+Contains purely network-related utilities. N)__doc__rrB/usr/lib/python3.8/site-packages/pip/_internal/network/__init__.pynetwork/cache.py000064400000004431152347654150007670 0ustar00"""HTTP cache implementation. """ import os from contextlib import contextmanager from pip._vendor.cachecontrol.cache import BaseCache from pip._vendor.cachecontrol.caches import FileCache from pip._vendor.requests.models import Response from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ensure_dir from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Iterator def is_from_cache(response): # type: (Response) -> bool return getattr(response, "from_cache", False) @contextmanager def suppressed_cache_errors(): # type: () -> Iterator[None] """If we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. """ try: yield except (OSError, IOError): pass class SafeFileCache(BaseCache): """ A file based cache which is safe to use even when the target directory may not be accessible or writable. """ def __init__(self, directory): # type: (str) -> None assert directory is not None, "Cache directory must not be None." super(SafeFileCache, self).__init__() self.directory = directory def _get_cache_path(self, name): # type: (str) -> str # From cachecontrol.caches.file_cache.FileCache._fn, brought into our # class for backwards-compatibility and to avoid using a non-public # method. hashed = FileCache.encode(name) parts = list(hashed[:5]) + [hashed] return os.path.join(self.directory, *parts) def get(self, key): # type: (str) -> Optional[bytes] path = self._get_cache_path(key) with suppressed_cache_errors(): with open(path, 'rb') as f: return f.read() def set(self, key, value): # type: (str, bytes) -> None path = self._get_cache_path(key) with suppressed_cache_errors(): ensure_dir(os.path.dirname(path)) with adjacent_tmp_file(path) as f: f.write(value) replace(f.name, path) def delete(self, key): # type: (str) -> None path = self._get_cache_path(key) with suppressed_cache_errors(): os.remove(path) network/session.py000064400000035550152347654150010316 0ustar00"""PipSession and supporting code, containing all pip-specific network request configuration and behavior. """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False import email.utils import json import logging import mimetypes import os import platform import sys import warnings from pip._vendor import requests, six, urllib3 from pip._vendor.cachecontrol import CacheControlAdapter from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter from pip._vendor.requests.models import Response from pip._vendor.requests.structures import CaseInsensitiveDict from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.urllib3.exceptions import InsecureRequestWarning from pip import __version__ from pip._internal.network.auth import MultiDomainBasicAuth from pip._internal.network.cache import SafeFileCache # Import ssl from compat so the initial import occurs in only one place. from pip._internal.utils.compat import has_tls, ipaddress from pip._internal.utils.glibc import libc_ver from pip._internal.utils.misc import ( build_url_from_netloc, get_installed_version, parse_netloc, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import url_to_path if MYPY_CHECK_RUNNING: from typing import ( Iterator, List, Optional, Tuple, Union, ) from pip._internal.models.link import Link SecureOrigin = Tuple[str, str, Optional[Union[int, str]]] logger = logging.getLogger(__name__) # Ignore warning raised when using --trusted-host. warnings.filterwarnings("ignore", category=InsecureRequestWarning) SECURE_ORIGINS = [ # protocol, hostname, port # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC) ("https", "*", "*"), ("*", "localhost", "*"), ("*", "127.0.0.0/8", "*"), ("*", "::1/128", "*"), ("file", "*", None), # ssh is always secure. ("ssh", "*", "*"), ] # type: List[SecureOrigin] # These are environment variables present when running under various # CI systems. For each variable, some CI systems that use the variable # are indicated. The collection was chosen so that for each of a number # of popular systems, at least one of the environment variables is used. # This list is used to provide some indication of and lower bound for # CI traffic to PyPI. Thus, it is okay if the list is not comprehensive. # For more background, see: https://github.com/pypa/pip/issues/5499 CI_ENVIRONMENT_VARIABLES = ( # Azure Pipelines 'BUILD_BUILDID', # Jenkins 'BUILD_ID', # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI 'CI', # Explicit environment variable. 'PIP_IS_CI', ) def looks_like_ci(): # type: () -> bool """ Return whether it looks like pip is running under CI. """ # We don't use the method of checking for a tty (e.g. using isatty()) # because some CI systems mimic a tty (e.g. Travis CI). Thus that # method doesn't provide definitive information in either direction. return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES) def user_agent(): """ Return a string representing the user agent. """ data = { "installer": {"name": "pip", "version": __version__}, "python": platform.python_version(), "implementation": { "name": platform.python_implementation(), }, } if data["implementation"]["name"] == 'CPython': data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'PyPy': if sys.pypy_version_info.releaselevel == 'final': pypy_version_info = sys.pypy_version_info[:3] else: pypy_version_info = sys.pypy_version_info data["implementation"]["version"] = ".".join( [str(x) for x in pypy_version_info] ) elif data["implementation"]["name"] == 'Jython': # Complete Guess data["implementation"]["version"] = platform.python_version() elif data["implementation"]["name"] == 'IronPython': # Complete Guess data["implementation"]["version"] = platform.python_version() if sys.platform.startswith("linux"): from pip._vendor import distro distro_infos = dict(filter( lambda x: x[1], zip(["name", "version", "id"], distro.linux_distribution()), )) libc = dict(filter( lambda x: x[1], zip(["lib", "version"], libc_ver()), )) if libc: distro_infos["libc"] = libc if distro_infos: data["distro"] = distro_infos if sys.platform.startswith("darwin") and platform.mac_ver()[0]: data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]} if platform.system(): data.setdefault("system", {})["name"] = platform.system() if platform.release(): data.setdefault("system", {})["release"] = platform.release() if platform.machine(): data["cpu"] = platform.machine() if has_tls(): import _ssl as ssl data["openssl_version"] = ssl.OPENSSL_VERSION setuptools_version = get_installed_version("setuptools") if setuptools_version is not None: data["setuptools_version"] = setuptools_version # Use None rather than False so as not to give the impression that # pip knows it is not being run under CI. Rather, it is a null or # inconclusive result. Also, we include some value rather than no # value to make it easier to know that the check has been run. data["ci"] = True if looks_like_ci() else None user_data = os.environ.get("PIP_USER_AGENT_USER_DATA") if user_data is not None: data["user_data"] = user_data return "{data[installer][name]}/{data[installer][version]} {json}".format( data=data, json=json.dumps(data, separators=(",", ":"), sort_keys=True), ) class LocalFSAdapter(BaseAdapter): def send(self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None): pathname = url_to_path(request.url) resp = Response() resp.status_code = 200 resp.url = request.url try: stats = os.stat(pathname) except OSError as exc: resp.status_code = 404 resp.raw = exc else: modified = email.utils.formatdate(stats.st_mtime, usegmt=True) content_type = mimetypes.guess_type(pathname)[0] or "text/plain" resp.headers = CaseInsensitiveDict({ "Content-Type": content_type, "Content-Length": stats.st_size, "Last-Modified": modified, }) resp.raw = open(pathname, "rb") resp.close = resp.raw.close return resp def close(self): pass class InsecureHTTPAdapter(HTTPAdapter): def cert_verify(self, conn, url, verify, cert): super(InsecureHTTPAdapter, self).cert_verify( conn=conn, url=url, verify=False, cert=cert ) class InsecureCacheControlAdapter(CacheControlAdapter): def cert_verify(self, conn, url, verify, cert): super(InsecureCacheControlAdapter, self).cert_verify( conn=conn, url=url, verify=False, cert=cert ) class PipSession(requests.Session): timeout = None # type: Optional[int] def __init__(self, *args, **kwargs): """ :param trusted_hosts: Domains not to emit warnings for when not using HTTPS. """ retries = kwargs.pop("retries", 0) cache = kwargs.pop("cache", None) trusted_hosts = kwargs.pop("trusted_hosts", []) # type: List[str] index_urls = kwargs.pop("index_urls", None) super(PipSession, self).__init__(*args, **kwargs) # Namespace the attribute with "pip_" just in case to prevent # possible conflicts with the base class. self.pip_trusted_origins = [] # type: List[Tuple[str, Optional[int]]] # Attach our User Agent to the request self.headers["User-Agent"] = user_agent() # Attach our Authentication handler to the session self.auth = MultiDomainBasicAuth(index_urls=index_urls) # Create our urllib3.Retry instance which will allow us to customize # how we handle retries. retries = urllib3.Retry( # Set the total number of retries that a particular request can # have. total=retries, # A 503 error from PyPI typically means that the Fastly -> Origin # connection got interrupted in some way. A 503 error in general # is typically considered a transient error so we'll go ahead and # retry it. # A 500 may indicate transient error in Amazon S3 # A 520 or 527 - may indicate transient error in CloudFlare status_forcelist=[500, 503, 520, 527], # Add a small amount of back off between failed requests in # order to prevent hammering the service. backoff_factor=0.25, ) # Our Insecure HTTPAdapter disables HTTPS validation. It does not # support caching so we'll use it for all http:// URLs. # If caching is disabled, we will also use it for # https:// hosts that we've marked as ignoring # TLS errors for (trusted-hosts). insecure_adapter = InsecureHTTPAdapter(max_retries=retries) # We want to _only_ cache responses on securely fetched origins or when # the host is specified as trusted. We do this because # we can't validate the response of an insecurely/untrusted fetched # origin, and we don't want someone to be able to poison the cache and # require manual eviction from the cache to fix it. if cache: secure_adapter = CacheControlAdapter( cache=SafeFileCache(cache), max_retries=retries, ) self._trusted_host_adapter = InsecureCacheControlAdapter( cache=SafeFileCache(cache), max_retries=retries, ) else: secure_adapter = HTTPAdapter(max_retries=retries) self._trusted_host_adapter = insecure_adapter self.mount("https://", secure_adapter) self.mount("http://", insecure_adapter) # Enable file:// urls self.mount("file://", LocalFSAdapter()) for host in trusted_hosts: self.add_trusted_host(host, suppress_logging=True) def add_trusted_host(self, host, source=None, suppress_logging=False): # type: (str, Optional[str], bool) -> None """ :param host: It is okay to provide a host that has previously been added. :param source: An optional source string, for logging where the host string came from. """ if not suppress_logging: msg = 'adding trusted host: {!r}'.format(host) if source is not None: msg += ' (from {})'.format(source) logger.info(msg) host_port = parse_netloc(host) if host_port not in self.pip_trusted_origins: self.pip_trusted_origins.append(host_port) self.mount( build_url_from_netloc(host) + '/', self._trusted_host_adapter ) if not host_port[1]: # Mount wildcard ports for the same host. self.mount( build_url_from_netloc(host) + ':', self._trusted_host_adapter ) def iter_secure_origins(self): # type: () -> Iterator[SecureOrigin] for secure_origin in SECURE_ORIGINS: yield secure_origin for host, port in self.pip_trusted_origins: yield ('*', host, '*' if port is None else port) def is_secure_origin(self, location): # type: (Link) -> bool # Determine if this url used a secure transport mechanism parsed = urllib_parse.urlparse(str(location)) origin_protocol, origin_host, origin_port = ( parsed.scheme, parsed.hostname, parsed.port, ) # The protocol to use to see if the protocol matches. # Don't count the repository type as part of the protocol: in # cases such as "git+ssh", only use "ssh". (I.e., Only verify against # the last scheme.) origin_protocol = origin_protocol.rsplit('+', 1)[-1] # Determine if our origin is a secure origin by looking through our # hardcoded list of secure origins, as well as any additional ones # configured on this PackageFinder instance. for secure_origin in self.iter_secure_origins(): secure_protocol, secure_host, secure_port = secure_origin if origin_protocol != secure_protocol and secure_protocol != "*": continue try: addr = ipaddress.ip_address( None if origin_host is None else six.ensure_text(origin_host) ) network = ipaddress.ip_network( six.ensure_text(secure_host) ) except ValueError: # We don't have both a valid address or a valid network, so # we'll check this origin against hostnames. if ( origin_host and origin_host.lower() != secure_host.lower() and secure_host != "*" ): continue else: # We have a valid address and network, so see if the address # is contained within the network. if addr not in network: continue # Check to see if the port matches. if ( origin_port != secure_port and secure_port != "*" and secure_port is not None ): continue # If we've gotten here, then this origin matches the current # secure origin and we should return True return True # If we've gotten to this point, then the origin isn't secure and we # will not accept it as a valid location to search. We will however # log a warning that we are ignoring it. logger.warning( "The repository located at %s is not a trusted or secure host and " "is being ignored. If this repository is available via HTTPS we " "recommend you use HTTPS instead, otherwise you may silence " "this warning and allow it anyway with '--trusted-host %s'.", origin_host, origin_host, ) return False def request(self, method, url, *args, **kwargs): # Allow setting a default timeout on a session kwargs.setdefault("timeout", self.timeout) # Dispatch the actual request return super(PipSession, self).request(method, url, *args, **kwargs) network/xmlrpc.py000064400000003532152347654150010133 0ustar00"""xmlrpclib.Transport implementation """ import logging # NOTE: XMLRPC Client is not annotated in typeshed as on 2017-07-17, which is # why we ignore the type on this import from pip._vendor.six.moves import xmlrpc_client # type: ignore from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import NetworkConnectionError from pip._internal.network.utils import raise_for_status from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict from pip._internal.network.session import PipSession logger = logging.getLogger(__name__) class PipXmlrpcTransport(xmlrpc_client.Transport): """Provide a `xmlrpclib.Transport` implementation via a `PipSession` object. """ def __init__(self, index_url, session, use_datetime=False): # type: (str, PipSession, bool) -> None xmlrpc_client.Transport.__init__(self, use_datetime) index_parts = urllib_parse.urlparse(index_url) self._scheme = index_parts.scheme self._session = session def request(self, host, handler, request_body, verbose=False): # type: (str, str, Dict[str, str], bool) -> None parts = (self._scheme, host, handler, None, None, None) url = urllib_parse.urlunparse(parts) try: headers = {'Content-Type': 'text/xml'} response = self._session.post(url, data=request_body, headers=headers, stream=True) raise_for_status(response) self.verbose = verbose return self.parse_response(response.raw) except NetworkConnectionError as exc: assert exc.response logger.critical( "HTTP error %s while getting %s", exc.response.status_code, url, ) raise network/auth.py000064400000026604152347654150007574 0ustar00"""Network Authentication Helpers Contains interface (MultiDomainBasicAuth) and associated glue code for providing credentials in the context of network requests. """ import logging from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth from pip._vendor.requests.utils import get_netrc_auth from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.misc import ( ask, ask_input, ask_password, remove_auth_from_url, split_auth_netloc_from_url, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict, Optional, Tuple, List, Any from pip._internal.vcs.versioncontrol import AuthInfo from pip._vendor.requests.models import Response, Request Credentials = Tuple[str, str, str] logger = logging.getLogger(__name__) try: import keyring # noqa except ImportError: keyring = None except Exception as exc: logger.warning( "Keyring is skipped due to an exception: %s", str(exc), ) keyring = None def get_keyring_auth(url, username): # type: (str, str) -> Optional[AuthInfo] """Return the tuple auth for a given url from keyring.""" global keyring if not url or not keyring: return None try: try: get_credential = keyring.get_credential except AttributeError: pass else: logger.debug("Getting credentials from keyring for %s", url) cred = get_credential(url, username) if cred is not None: return cred.username, cred.password return None if username: logger.debug("Getting password from keyring for %s", url) password = keyring.get_password(url, username) if password: return username, password except Exception as exc: logger.warning( "Keyring is skipped due to an exception: %s", str(exc), ) keyring = None return None class MultiDomainBasicAuth(AuthBase): def __init__(self, prompting=True, index_urls=None): # type: (bool, Optional[List[str]]) -> None self.prompting = prompting self.index_urls = index_urls self.passwords = {} # type: Dict[str, AuthInfo] # When the user is prompted to enter credentials and keyring is # available, we will offer to save them. If the user accepts, # this value is set to the credentials they entered. After the # request authenticates, the caller should call # ``save_credentials`` to save these. self._credentials_to_save = None # type: Optional[Credentials] def _get_index_url(self, url): # type: (str) -> Optional[str] """Return the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentials then they will be included in the return value. Returns None if no matching index was found, or if --no-index was specified by the user. """ if not url or not self.index_urls: return None for u in self.index_urls: prefix = remove_auth_from_url(u).rstrip("/") + "/" if url.startswith(prefix): return u return None def _get_new_credentials(self, original_url, allow_netrc=True, allow_keyring=True): # type: (str, bool, bool) -> AuthInfo """Find and return credentials for the specified URL.""" # Split the credentials and netloc from the url. url, netloc, url_user_password = split_auth_netloc_from_url( original_url, ) # Start with the credentials embedded in the url username, password = url_user_password if username is not None and password is not None: logger.debug("Found credentials in url for %s", netloc) return url_user_password # Find a matching index url for this request index_url = self._get_index_url(url) if index_url: # Split the credentials from the url. index_info = split_auth_netloc_from_url(index_url) if index_info: index_url, _, index_url_user_password = index_info logger.debug("Found index url %s", index_url) # If an index URL was found, try its embedded credentials if index_url and index_url_user_password[0] is not None: username, password = index_url_user_password if username is not None and password is not None: logger.debug("Found credentials in index url for %s", netloc) return index_url_user_password # Get creds from netrc if we still don't have them if allow_netrc: netrc_auth = get_netrc_auth(original_url) if netrc_auth: logger.debug("Found credentials in netrc for %s", netloc) return netrc_auth # If we don't have a password and keyring is available, use it. if allow_keyring: # The index url is more specific than the netloc, so try it first kr_auth = ( get_keyring_auth(index_url, username) or get_keyring_auth(netloc, username) ) if kr_auth: logger.debug("Found credentials in keyring for %s", netloc) return kr_auth return username, password def _get_url_and_credentials(self, original_url): # type: (str) -> Tuple[str, Optional[str], Optional[str]] """Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different username and password. """ url, netloc, _ = split_auth_netloc_from_url(original_url) # Use any stored credentials that we have for this netloc username, password = self.passwords.get(netloc, (None, None)) if username is None and password is None: # No stored credentials. Acquire new credentials without prompting # the user. (e.g. from netrc, keyring, or the URL itself) username, password = self._get_new_credentials(original_url) if username is not None or password is not None: # Convert the username and password if they're None, so that # this netloc will show up as "cached" in the conditional above. # Further, HTTPBasicAuth doesn't accept None, so it makes sense to # cache the value that is going to be used. username = username or "" password = password or "" # Store any acquired credentials. self.passwords[netloc] = (username, password) assert ( # Credentials were found (username is not None and password is not None) or # Credentials were not found (username is None and password is None) ), "Could not load credentials from url: {}".format(original_url) return url, username, password def __call__(self, req): # type: (Request) -> Request # Get credentials for this request url, username, password = self._get_url_and_credentials(req.url) # Set the url of the request to the url without any credentials req.url = url if username is not None and password is not None: # Send the basic auth with this request req = HTTPBasicAuth(username, password)(req) # Attach a hook to handle 401 responses req.register_hook("response", self.handle_401) return req # Factored out to allow for easy patching in tests def _prompt_for_password(self, netloc): # type: (str) -> Tuple[Optional[str], Optional[str], bool] username = ask_input("User for {}: ".format(netloc)) if not username: return None, None, False auth = get_keyring_auth(netloc, username) if auth and auth[0] is not None and auth[1] is not None: return auth[0], auth[1], False password = ask_password("Password: ") return username, password, True # Factored out to allow for easy patching in tests def _should_save_password_to_keyring(self): # type: () -> bool if not keyring: return False return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y" def handle_401(self, resp, **kwargs): # type: (Response, **Any) -> Response # We only care about 401 responses, anything else we want to just # pass through the actual response if resp.status_code != 401: return resp # We are not able to prompt the user so simply return the response if not self.prompting: return resp parsed = urllib_parse.urlparse(resp.url) # Prompt the user for a new username and password username, password, save = self._prompt_for_password(parsed.netloc) # Store the new username and password to use for future requests self._credentials_to_save = None if username is not None and password is not None: self.passwords[parsed.netloc] = (username, password) # Prompt to save the password to keyring if save and self._should_save_password_to_keyring(): self._credentials_to_save = (parsed.netloc, username, password) # Consume content and release the original connection to allow our new # request to reuse the same one. resp.content resp.raw.release_conn() # Add our new username and password to the request req = HTTPBasicAuth(username or "", password or "")(resp.request) req.register_hook("response", self.warn_on_401) # On successful request, save the credentials that were used to # keyring. (Note that if the user responded "no" above, this member # is not set and nothing will be saved.) if self._credentials_to_save: req.register_hook("response", self.save_credentials) # Send our new request new_resp = resp.connection.send(req, **kwargs) new_resp.history.append(resp) return new_resp def warn_on_401(self, resp, **kwargs): # type: (Response, **Any) -> None """Response callback to warn about incorrect credentials.""" if resp.status_code == 401: logger.warning( '401 Error, Credentials not correct for %s', resp.request.url, ) def save_credentials(self, resp, **kwargs): # type: (Response, **Any) -> None """Response callback to save credentials on success.""" assert keyring is not None, "should never reach here without keyring" if not keyring: return creds = self._credentials_to_save self._credentials_to_save = None if creds and resp.status_code < 400: try: logger.info('Saving credentials to keyring') keyring.set_password(*creds) except Exception: logger.exception('Failed to save credentials') network/__init__.py000064400000000062152347654150010360 0ustar00"""Contains purely network-related utilities. """ cli/__pycache__/main_parser.cpython-38.opt-1.pyc000064400000004157152347654150015435 0ustar00U .e @sdZddlZddlZddlmZddlmZmZddlm Z m Z ddl m Z ddl mZmZddlmZer|dd lmZmZd d gZd d Zd d ZdS)z=A single place for constructing and exposing the main parser N) cmdoptions)ConfigOptionParserUpdatingDefaultsHelpFormatter) commands_dictget_similar_commands) CommandError)get_pip_versionget_prog)MYPY_CHECK_RUNNING)TupleListcreate_main_parser parse_commandcCstddtdtd}tf|}|t|_ttj|}| |d|_ dgddt D}d ||_|S) z6Creates and returns the main parser for pip's CLI z %prog [options]Fglobal)ZusageZadd_help_optionZ formatternameprogTcSsg|]\}}d||jfqS)z%-27s %s)Zsummary).0rZ command_inforA/usr/lib/python3.8/site-packages/pip/_internal/cli/main_parser.py 2sz&create_main_parser.. )rr rZdisable_interspersed_argsrversionrZmake_option_groupZ general_groupZadd_option_groupmainritemsjoin description)Z parser_kwparserZgen_optsrrrrr s"    cCst}||\}}|jr>tj|jtjtjt|rZ|ddkrjt |dkrj| t|d}|t krt |}d|g}|r| d|td||dd}||||fS)Nrhelpzunknown command "%s"zmaybe you meant "%s"z - )r parse_argsrsysstdoutwriteoslinesepexitlenZ print_helprrappendrrremove)argsrZgeneral_optionsZ args_elseZcmd_nameZguessmsgZcmd_argsrrrr;s&    )__doc__r$r!Zpip._internal.clirZpip._internal.cli.parserrrZpip._internal.commandsrrZpip._internal.exceptionsrZpip._internal.utils.miscrr Zpip._internal.utils.typingr typingr r __all__r rrrrrs   #cli/__pycache__/status_codes.cpython-38.opt-1.pyc000064400000000555152347654150015633 0ustar00U .e@s(ddlmZdZdZdZdZdZdZdS))absolute_importN)Z __future__rSUCCESSZERRORZ UNKNOWN_ERRORZVIRTUALENV_NOT_FOUNDZPREVIOUS_BUILD_DIR_ERRORZNO_MATCHES_FOUNDr r B/usr/lib/python3.8/site-packages/pip/_internal/cli/status_codes.pys cli/__pycache__/status_codes.cpython-38.pyc000064400000000555152347654150014674 0ustar00U .e@s(ddlmZdZdZdZdZdZdZdS))absolute_importN)Z __future__rSUCCESSZERRORZ UNKNOWN_ERRORZVIRTUALENV_NOT_FOUNDZPREVIOUS_BUILD_DIR_ERRORZNO_MATCHES_FOUNDr r B/usr/lib/python3.8/site-packages/pip/_internal/cli/status_codes.pys cli/__pycache__/parser.cpython-38.pyc000064400000021421152347654150013463 0ustar00U .e%@sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZmZddlmZeeZGd d d ejZGd d d eZGd ddejZGdddeZddZdS)zBase option parser setup)absolute_importN) strtobool) string_types) UNKNOWN_ERROR) ConfigurationConfigurationError)get_terminal_sizec@sReZdZdZddZddZddd Zd d Zd d ZddZ ddZ ddZ dS)PrettyHelpFormatterz4A prettier/less verbose help formatter for optparse.cOs:d|d<d|d<tdd|d<tjj|f||dS)NZmax_help_positionZindent_incrementrwidth)roptparseIndentedHelpFormatter__init__)selfargskwargsr, )_format_option_stringsroptionrrrformat_option_strings!sz)PrettyHelpFormatter.format_option_stringsrrcCs|g}|jr||jd|jr0||jdt|dkrH|d||rr|jp^|j}|||d |S)a 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 rr ) Z _short_optsappendZ _long_optsleninsertZ takes_valuemetavardestlowerjoin)rrZmvarfmtZoptsepZoptsr rrrr$s  z*PrettyHelpFormatter._format_option_stringscCs|dkr dS|dS)NZOptionsrz: r)rZheadingrrrformat_heading;sz"PrettyHelpFormatter.format_headingcCsd|t|d}|S)zz Ensure there is only one newline between usage and the first heading if there is no description. z Usage: %s  ) indent_linestextwrapdedent)rZusagemsgrrr format_usage@sz PrettyHelpFormatter.format_usagecCsV|rNt|jdrd}nd}|d}|}|t|d}d||f}|SdSdS)NmainZCommandsZ Description r%z%s: %s r)hasattrparserlstriprstripr&r'r()r descriptionZlabelrrrformat_descriptionHs   z&PrettyHelpFormatter.format_descriptioncCs|r|SdSdS)Nrr)rZepilogrrr format_epilogZsz!PrettyHelpFormatter.format_epilogcs"fdd|dD}d|S)Ncsg|] }|qSrr).0lineindentrr bsz4PrettyHelpFormatter.indent_lines..r,)splitr#)rtextr7Z new_linesrr6rr&asz PrettyHelpFormatter.indent_linesN)rr) __name__ __module__ __qualname____doc__rrrr$r*r2r3r&rrrrr s r c@seZdZdZddZdS)UpdatingDefaultsHelpFormatterzCustom help formatter for use in ConfigOptionParser. This is updates the defaults before expanding them, allowing them to show up correctly in the help listing. cCs(|jdk r|j|jjtj||S)N)r._update_defaultsdefaultsrrexpand_defaultrrrrrBms z,UpdatingDefaultsHelpFormatter.expand_defaultN)r;r<r=r>rBrrrrr?fsr?c@s eZdZddZeddZdS)CustomOptionParsercOs(|j||}|j|j|||S)z*Insert an OptionGroup at a given position.)Zadd_option_group option_groupspopr)ridxrrgrouprrrinsert_option_groupus  z&CustomOptionParser.insert_option_groupcCs*|jdd}|jD]}||jq|S)ztd|q$|dd\}}||kr$||||fq$|D] }||D]\}}||fVqzqndS)Nglobalz:env:cSsi|] }|gqSrr)r4rOrrr szGConfigOptionParser._get_ordered_configuration_items..z7Ignoring configuration key '%s' as it's value is empty..r )rOrQitemsloggerdebugr9r)rZoverride_orderZ section_itemsZ section_keyrZZsectionrYrrr _get_ordered_configuration_itemss z3ConfigOptionParser._get_ordered_configuration_itemsc sHtj_t}D]\}ddkr>qjdkrz t|}Wn,t k rt j|} |YnXnjdkr| }fdd|D}nhjdkr| j}||}jpd}jpi}j||f||n|}||j<q|D]tj|<q&d_|S) zUpdates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).z--N) store_true store_falsecountrcsg|]}|qSr)r\)r4vrYrrrrr8sz7ConfigOptionParser._update_defaults..callbackr)rValuesrAvaluessetrcZ get_optionactionr ValueErrorinvalid_config_error_messageerrorr9addr!get_opt_stringZ convert_valueZ callback_argsZcallback_kwargsrir\getattr)rrAZ late_evalrZZ error_msgopt_strrrrrhrr@s@         z#ConfigOptionParser._update_defaultsc Cs|jst|jSz|jWn2tk rR}z|tt |W5d}~XYnX| |j }| D]4}| |j}t|trl|}|||||j<qlt|S)zOverriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.N)Zprocess_default_valuesrrjrArQloadrrXrstrr@copyZ_get_all_optionsgetr! isinstancerrrrU)rerrrArdefaultrtrrrget_default_valuess "   z%ConfigOptionParser.get_default_valuescCs |tj|td|dS)Nz%s )Z print_usagerWstderrrXr)rr)rrrrps zConfigOptionParser.errorN) r;r<r=r>rr\rcr@r|rprrrrrNs 1rNcCs |dkrd||Sd||S)zQReturns a better error message when invalid configuration option is provided.)rdrezo{0} is not a valid value for {1} option, please specify a boolean value like yes/no, true/false or 1/0 instead.z[{0} is not a valid value for {1} option, please specify a numerical value like 1/0 instead.)format)rmrYrZrrrrosro)r>Z __future__rZloggingrrWr'Zdistutils.utilrZpip._vendor.sixrZpip._internal.cli.status_codesrZpip._internal.configurationrrZpip._internal.utils.compatrZ getLoggerr;rarr r?rSrCrNrorrrrs       O wcli/__pycache__/cmdoptions.cpython-38.opt-1.pyc000064400000045506152347654150015317 0ustar00U .eh@sdZddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZerddl m!Z!m"Z"m#Z#m$Z$m%Z%ddl m&Z&m'Z'ddl(m)Z)e*e+Z,ddZ-ddZ.dddZ/dddZ0e e dddddd Z1e e d!d"d#dd$d%Z2e e d&d'd(d#de d%Z3e e d)d*d+d,dd-d%Z4e e d.d/d#dd0d%Z5e e d1d2d3d#d4d Z6e e d5d6d7d,dd8d%Z7e e d9d:d;e8e9d:e9d?d@Z;e e dAdBdCdDdEdFdGZe e dPdQdRdSdTdOZ?e e dUdVdWdXdYdZd[d\Z@e e d]d^dLdMe dOZAd_d`ZBe e dadbdLdEdcddZCe e dedfdLddEdgdhZDe e didjdkdldmejEdndoZFdpdqZGe e drdsd#ddtd%ZHdudvZIdwdxZJdydzZKd{d|ZLd}d~ZMe e ddddddeddo ZNddZOddZPddZQddZRddZSe e ddddddoZTddZUddZVe e ddddeVdLdedd ZWe e ddddddoZXe e ddddddoZYddZZddZ[ddZ\e e ddedddZ]ddZ^e e ddde^ddZ_e e dddd#ddd%Z`e e ddddddddGZae e ddd#dd Zbe e dddddd%ZcddĄZde e ddd#ddd%Zee e dddedde dɍZfe e ddddddύZge e ddddddύZhe e dd#dddՍZie e dd#dddՍZje e ddd#ddd%Zke e dddd#e d Zldd߄Zme e dddemdddZne e ddd#ddd%Zoe e ddEddd ZpddZqde1e2e3e4e6e7ee?e@eAeBeJeCeDe]e_eke5gdZrdeFeGeHeIgdZsdS)aC shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parses general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this design. )absolute_importN) strtobool)partial) SUPPRESS_HELPOption OptionGroup)dedent) CommandError)USER_CACHE_DIRget_src_prefix) FormatControl)PyPI) TargetPython) STRONG_HASHES)MYPY_CHECK_RUNNING) BAR_TYPES)AnyCallableDictOptionalTuple) OptionParserValues)ConfigOptionParsercCs.d||}td|}||dS)z Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. z {} error: {} N)formattextwrapZfilljoinspliterror)parseroptionmsgr#@/usr/lib/python3.8/site-packages/pip/_internal/cli/cmdoptions.pyraise_option_error)s r%cCs,t||d}|dD]}||q|S)z Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser nameoptions)r add_option)groupr Z option_groupr!r#r#r$make_option_group7s r*csPdkr |fdd}dddg}tt||rL|j}|tjddd dS) zDisable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. Ncs t|dSN)getattr)n check_optionsr#r$getnameOsz+check_install_build_global..getnameZ build_optionsglobal_optionsinstall_optionszeDisabling all use of wheels due to the use of --build-options / --global-options / --install-options.) stacklevel)anymapformat_controlZdisallow_binarieswarningswarn)r'r/r0namesZcontrolr#r.r$check_install_build_globalDs  r;FcCsbt|j|j|j|jg}ttdh}|j|ko6|j }|rH|rHt d|r^|r^|j s^t ddS)zFunction for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. z:all:zWhen restricting platform and interpreter constraints using --python-version, --platform, --abi, or --implementation, either --no-deps must be set, or --only-binary=:all: must be set and --no-binary must not be set (or must be set to :none:).zQCan not use any platform or abi specific options unless installing via '--target'N) r5python_versionplatformabiimplementationr setr7ignore_dependenciesr Z target_dir)r'Z check_targetZdist_restriction_setZ binary_onlyZsdist_dependencies_allowedr#r#r$check_dist_restriction[s&  rBz-hz--helphelpz Show help.)destactionrCz --isolated isolated_mode store_truezSRun pip in an isolated mode, ignoring environment variables and user configuration.rDrEdefaultrCz--require-virtualenvz--require-venvZ require_venvz-vz --verboseverbosecountzDGive more output. Option is additive, and can be used up to 3 times.z --no-colorno_colorzSuppress colored outputz-Vz --versionversionzShow version and exit.z-qz--quietquietzGive less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).z--progress-bar progress_barchoiceZonz*Specify type of progress to be displayed [|z] (default: %default))rDtypechoicesrIrCz--logz --log-filez --local-loglogpathz Path to a verbose appending log.)rDmetavarrCz --no-inputno_inputz--proxyproxystrz/src". The default for global installs is "/src".cCs t||jS)zGet a format_control object.)r,rD)valuesr!r#r#r$_get_format_controlsrycCs"t|j|}t||j|jdSr+)ryrxr handle_mutual_excludes no_binary only_binaryr!opt_strvaluer Zexistingr#r#r$_handle_no_binarys  rcCs"t|j|}t||j|jdSr+)ryrxr rzr|r{r}r#r#r$_handle_only_binarys  rc Cs$ttt}tdddtd|ddS)Nz --no-binaryr7callbackrYa^Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either :all: to disable all binary packages, :none: to empty the set, or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.rDrErrRrIrC)r r@rrr7r#r#r$r{sr{c Cs$ttt}tdddtd|ddS)Nz --only-binaryr7rrYaGDo not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either :all: to disable all source packages, :none: to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.r)r r@rrrr#r#r$r|sr|z --platformr=z[Only use wheels compatible with . Defaults to the platform of the running system.cCs|sdS|d}t|dkr"dSt|dkrV|d}t|dkrV|d|ddg}ztdd |D}Wntk rYd SX|dfS) z Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. :return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. )NN.)r#z'at most three version parts are allowedrNcss|]}t|VqdSr+)r\).0partr#r#r$ sz*_convert_python_version..)r#z$each version part must be an integer)rlentuple ValueError)rparts version_infor#r#r$_convert_python_versions    rcCs:t|\}}|dk r.d||}t|||d||j_dS)z3 Handle a provided --python-version value. Nz(invalid --python-version value: {!r}: {}r!r")rrr%rxr<)r!r~rr rZ error_msgr"r#r#r$_handle_python_version s rz--python-versionr<ra The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). )rDrVrErrRrIrCz--implementationr?zOnly use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.z--abir>zOnly use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Generally you will need to specify --implementation, --platform, and --python-version when using this option.cCs4|t|t|t|tdSr+)r(r=r<r?r>)Zcmd_optsr#r#r$add_target_python_optionsIs   rcCst|j|j|j|jd}|S)N)r=Zpy_version_infor>r?)rr=r<r>r?)r'Z target_pythonr#r#r$make_target_pythonQsrcCstddddddS)Nz--prefer-binary prefer_binaryrGFz8Prefer older binary packages over newer source packages.rHrir#r#r#r$r]srz --cache-dir cache_dirzStore the cache data in .)rDrIrVrCc CsV|dk rJz t|Wn4tk rH}zt||t|dW5d}~XYnXd|j_dS)z Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. NrF)rrr%rYrxr)r!optrr excr#r#r$_handle_no_cache_dirrs  $ rz--no-cache-dirzDisable the cache.)rDrErrCz --no-depsz--no-dependenciesrAz#Don't install package dependencies.z-bz--buildz --build-dirz--build-directory build_dira>Directory to unpack packages into and build in. Note that an initial build still takes place in a temporary directory. The location of temporary directories can be controlled by setting the TMPDIR environment variable (TEMP on Windows) appropriately. When passed, build directories are not cleaned in case of failures.z--ignore-requires-pythonignore_requires_pythonz'Ignore the Requires-Python information.z--no-build-isolationZbuild_isolationZ store_falseTzDisable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.cCs&|dk rd}t|||dd|j_dS)z Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. Na0A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. rF)r%rx use_pep517)r!rrr r"r#r#r$_handle_no_use_pep517s rz --use-pep517rz^Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).z--no-use-pep517)rDrErrIrCz--install-optionr2rhr'a"Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.)rDrErVrCz--global-optionr1zTExtra global options to be supplied to the setup.py call before the install command.z --no-cleanz!Don't clean up build directories.)rErIrCz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--disable-pip-version-checkdisable_pip_version_checkz{Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.z-Zz--always-unzip always_unzipcCs|jjsi|j_z|dd\}}Wn"tk rF|d|YnX|tkrh|d|dtf|jj|g|dS)zkGiven a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.:rzTArguments to %s must be a hash name followed by a value, like --hash=sha256:abcde...z&Allowed hash algorithms for %s are %s.z, N) rxhashesrrrrr setdefaultrh)r!r~rr ZalgoZdigestr#r#r$_handle_merge_hash)s  rz--hashrstringzgVerify that the package's archive matches this hash before installing. Example: --hash=sha256:abcdef...)rDrErrRrCz--require-hashesrequire_hasheszRequire a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.z--pathz^Restrict to the specified installation path for listing packages (can be used multiple times).cCs|jr|js|jrtddS)Nz2Cannot combine '--path' with '--user' or '--local')rUuserZlocalr )r'r#r#r$check_list_path_option_srzGeneral Options)r&r'zPackage Index Options)N)F)t__doc__Z __future__rZloggingrr8Zdistutils.utilr functoolsrZoptparserrrrZpip._internal.exceptionsr Zpip._internal.locationsr r Z#pip._internal.models.format_controlr Zpip._internal.models.indexr Z"pip._internal.models.target_pythonrZpip._internal.utils.hashesrZpip._internal.utils.typingrZpip._internal.utils.uirtypingrrrrrrrZpip._internal.cli.parserrZ getLogger__name__Zloggerr%r*r;rBZhelp_rFZrequire_virtualenvrJrLrMrNlistkeysrrOrTrWrXr[r^rarbrjrkZ simple_urlrlrnrorprrrsrurvsrcryrrr{r|r=rrr<r?r>rrrrrZno_cacheZno_depsrrZno_build_isolationrrZ no_use_pep517r2r1Zno_cleanZprerrrhashrZ list_pathrZ general_groupZ index_groupr#r#r#r$sB               ,                                         cli/__pycache__/parser.cpython-38.opt-1.pyc000064400000021365152347654150014431 0ustar00U .e%@sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZmZddlmZeeZGd d d ejZGd d d eZGd ddejZGdddeZddZdS)zBase option parser setup)absolute_importN) strtobool) string_types) UNKNOWN_ERROR) ConfigurationConfigurationError)get_terminal_sizec@sReZdZdZddZddZddd Zd d Zd d ZddZ ddZ ddZ dS)PrettyHelpFormatterz4A prettier/less verbose help formatter for optparse.cOs:d|d<d|d<tdd|d<tjj|f||dS)NZmax_help_positionZindent_incrementrwidth)roptparseIndentedHelpFormatter__init__)selfargskwargsr, )_format_option_stringsroptionrrrformat_option_strings!sz)PrettyHelpFormatter.format_option_stringsrrcCs|g}|jr||jd|jr0||jdt|dkrH|d||rr|jp^|j}|||d |S)a 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 rr ) Z _short_optsappendZ _long_optsleninsertZ takes_valuemetavardestlowerjoin)rrZmvarfmtZoptsepZoptsr rrrr$s  z*PrettyHelpFormatter._format_option_stringscCs|dkr dS|dS)NZOptionsrz: r)rZheadingrrrformat_heading;sz"PrettyHelpFormatter.format_headingcCsd|t|d}|S)zz Ensure there is only one newline between usage and the first heading if there is no description. z Usage: %s  ) indent_linestextwrapdedent)rZusagemsgrrr format_usage@sz PrettyHelpFormatter.format_usagecCsV|rNt|jdrd}nd}|d}|}|t|d}d||f}|SdSdS)NmainZCommandsZ Description r%z%s: %s r)hasattrparserlstriprstripr&r'r()r descriptionZlabelrrrformat_descriptionHs   z&PrettyHelpFormatter.format_descriptioncCs|r|SdSdS)Nrr)rZepilogrrr format_epilogZsz!PrettyHelpFormatter.format_epilogcs"fdd|dD}d|S)Ncsg|] }|qSrr).0lineindentrr bsz4PrettyHelpFormatter.indent_lines..r,)splitr#)rtextr7Z new_linesrr6rr&asz PrettyHelpFormatter.indent_linesN)rr) __name__ __module__ __qualname____doc__rrrr$r*r2r3r&rrrrr s r c@seZdZdZddZdS)UpdatingDefaultsHelpFormatterzCustom help formatter for use in ConfigOptionParser. This is updates the defaults before expanding them, allowing them to show up correctly in the help listing. cCs(|jdk r|j|jjtj||S)N)r._update_defaultsdefaultsrrexpand_defaultrrrrrBms z,UpdatingDefaultsHelpFormatter.expand_defaultN)r;r<r=r>rBrrrrr?fsr?c@s eZdZddZeddZdS)CustomOptionParsercOs(|j||}|j|j|||S)z*Insert an OptionGroup at a given position.)Zadd_option_group option_groupspopr)ridxrrgrouprrrinsert_option_groupus  z&CustomOptionParser.insert_option_groupcCs*|jdd}|jD]}||jq|S)ztd|q$|dd\}}||kr$||||fq$|D] }||D]\}}||fVqzqndS)Nglobalz:env:cSsi|] }|gqSrr)r4rOrrr szGConfigOptionParser._get_ordered_configuration_items..z7Ignoring configuration key '%s' as it's value is empty..r )rOrQitemsloggerdebugr9r)rZoverride_orderZ section_itemsZ section_keyrYZsectionrXrrr _get_ordered_configuration_itemss z3ConfigOptionParser._get_ordered_configuration_itemsc sHtj_t}D]\}ddkr>qjdkrz t|}Wn,t k rt j|} |YnXnjdkr| }fdd|D}nhjdkr| j}||}jpd}jpi}j||f||n|}||j<q|D]tj|<q&d_|S) zUpdates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).z--N) store_true store_falsecountrcsg|]}|qSr)r[)r4vrXrrrrr8sz7ConfigOptionParser._update_defaults..callbackr)rValuesrAvaluessetrbZ get_optionactionr ValueErrorinvalid_config_error_messageerrorr9addr!get_opt_stringZ convert_valueZ callback_argsZcallback_kwargsrhr[getattr)rrAZ late_evalrYZ error_msgopt_strrrrrgrr@s@         z#ConfigOptionParser._update_defaultsc Cs|jst|jSz|jWn2tk rR}z|tt |W5d}~XYnX| |j }| D]4}| |j}t|trl|}|||||j<qlt|S)zOverriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.N)Zprocess_default_valuesrrirArQloadrrWrstrr@copyZ_get_all_optionsgetr! isinstancerrqrT)rerrrArdefaultrsrrrget_default_valuess "   z%ConfigOptionParser.get_default_valuescCs |tj|td|dS)Nz%s )Z print_usagerVstderrrWr)rr)rrrros zConfigOptionParser.errorN) r;r<r=r>rr[rbr@r{rorrrrrNs 1rNcCs |dkrd||Sd||S)zQReturns a better error message when invalid configuration option is provided.)rcrdzo{0} is not a valid value for {1} option, please specify a boolean value like yes/no, true/false or 1/0 instead.z[{0} is not a valid value for {1} option, please specify a numerical value like 1/0 instead.)format)rlrXrYrrrrnsrn)r>Z __future__rZloggingrrVr'Zdistutils.utilrZpip._vendor.sixrZpip._internal.cli.status_codesrZpip._internal.configurationrrZpip._internal.utils.compatrZ getLoggerr;r`rr r?rRrCrNrnrrrrs       O wcli/__pycache__/base_command.cpython-38.pyc000064400000011661152347654150014604 0ustar00U .eh@s6dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZddlmZmZddlmZmZmZmZmZddlmZmZmZmZmZdd lmZdd l m!Z!m"Z"dd l#m$Z$dd l%m&Z&dd l'm(Z(e&rddl)m*Z*m+Z+m,Z,ddlm-Z-dgZ.e/e0Z1GdddeZ2dS)z(Base Command class, and related routines)absolute_importprint_functionN) cmdoptions)CommandContextMixIn)ConfigOptionParserUpdatingDefaultsHelpFormatter)ERRORPREVIOUS_BUILD_DIR_ERRORSUCCESS UNKNOWN_ERRORVIRTUALENV_NOT_FOUND) BadCommand CommandErrorInstallationErrorPreviousBuildDirErrorUninstallationError) deprecated)BrokenStdoutLoggingError setup_logging)get_prog)MYPY_CHECK_RUNNING)running_under_virtualenv)ListTupleAny)ValuesCommandcsNeZdZdZdZdfdd ZddZddZd d Zd d Z d dZ Z S)rNFcstt||jdt|ftd||j|d}||_||_t f||_ d|j }t |j ||_ttj|j }|j |dS)Nz%s %sF)usageprogZ formatterZadd_help_optionname descriptionisolatedz %s Options)superr__init__rrr__doc__rsummaryrparser capitalizeoptparseZ OptionGroupZcmd_optsrZmake_option_groupZ general_groupZadd_option_group)selfrr%r!Z parser_kwZ optgroup_nameZgen_opts __class__B/usr/lib/python3.8/site-packages/pip/_internal/cli/base_command.pyr#4s&   zCommand.__init__cCst|drtdS)zf This is a no-op so that commands by default do not do the pip version check. Zno_indexN)hasattrAssertionError)r)optionsr,r,r-handle_pip_version_checkPsz Command.handle_pip_version_checkcCstdSN)NotImplementedError)r)r0argsr,r,r-runZsz Command.runcCs |j|Sr2)r& parse_argsr)r4r,r,r-r6^szCommand.parse_argsc Cs>z.|||W5QRW SQRXW5tXdSr2)loggingZshutdownZ main_context_mainr7r,r,r-maincs $z Command.mainc Cs||\}}|j|j|_t|j|j|jd}tjdddkrhd}t dkrZd|}t |ddd|j rxdt jd <|jrd |jt jd <|jr|jststd ttzz(|||}t|tr|WWSWntk r2}z.tt|tjd ddtWYWRSd}~XYn>t t!t"fk r}z.tt|tjd ddt#WYWSd}~XYnt$k r}z*td|tjd ddt#WYWSd}~XYnt%k rt&dtj'd|t(j)krt*j+tj'dt#YWfSt,k rDtdtjd ddt#YW2St-k rntjdddt.YWSXW5||Xt/S)N) verbosityno_colorZ user_log_file)r=zA future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportZCPythonzPython 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. )Z replacementZgone_in1Z PIP_NO_INPUT ZPIP_EXISTS_ACTIONz2Could not find an activated virtualenv (required).zException information:T)exc_infoz%sz ERROR: Pipe to stdout was broken)filezOperation cancelled by userz Exception:)0r6verbosequietr;rr<logsys version_infoplatformZpython_implementationrZno_inputosenvironZ exists_actionjoinZ require_venvignore_require_venvrloggerZcriticalexitr r1r5 isinstanceintrstrdebugr rrr rrrprintstderrr8DEBUG traceback print_excKeyboardInterrupt BaseExceptionr r )r)r4r0Z level_numbermessageZstatusexcr,r,r-r9ksn             z Command._main)F) __name__ __module__ __qualname__rrLr#r1r5r6r:r9 __classcell__r,r,r*r-r0s )3r$Z __future__rrr8Zlogging.configr(rIrHrFrVZpip._internal.clirZ!pip._internal.cli.command_contextrZpip._internal.cli.parserrrZpip._internal.cli.status_codesrr r r r Zpip._internal.exceptionsr rrrrZpip._internal.utils.deprecationrZpip._internal.utils.loggingrrZpip._internal.utils.miscrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrtypingrrrr__all__Z getLoggerr\rMrr,r,r,r-s0        cli/__pycache__/cmdoptions.cpython-38.pyc000064400000045506152347654150014360 0ustar00U .eh@sdZddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZerddl m!Z!m"Z"m#Z#m$Z$m%Z%ddl m&Z&m'Z'ddl(m)Z)e*e+Z,ddZ-ddZ.dddZ/dddZ0e e dddddd Z1e e d!d"d#dd$d%Z2e e d&d'd(d#de d%Z3e e d)d*d+d,dd-d%Z4e e d.d/d#dd0d%Z5e e d1d2d3d#d4d Z6e e d5d6d7d,dd8d%Z7e e d9d:d;e8e9d:e9d?d@Z;e e dAdBdCdDdEdFdGZe e dPdQdRdSdTdOZ?e e dUdVdWdXdYdZd[d\Z@e e d]d^dLdMe dOZAd_d`ZBe e dadbdLdEdcddZCe e dedfdLddEdgdhZDe e didjdkdldmejEdndoZFdpdqZGe e drdsd#ddtd%ZHdudvZIdwdxZJdydzZKd{d|ZLd}d~ZMe e ddddddeddo ZNddZOddZPddZQddZRddZSe e ddddddoZTddZUddZVe e ddddeVdLdedd ZWe e ddddddoZXe e ddddddoZYddZZddZ[ddZ\e e ddedddZ]ddZ^e e ddde^ddZ_e e dddd#ddd%Z`e e ddddddddGZae e ddd#dd Zbe e dddddd%ZcddĄZde e ddd#ddd%Zee e dddedde dɍZfe e ddddddύZge e ddddddύZhe e dd#dddՍZie e dd#dddՍZje e ddd#ddd%Zke e dddd#e d Zldd߄Zme e dddemdddZne e ddd#ddd%Zoe e ddEddd ZpddZqde1e2e3e4e6e7ee?e@eAeBeJeCeDe]e_eke5gdZrdeFeGeHeIgdZsdS)aC shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parses general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this design. )absolute_importN) strtobool)partial) SUPPRESS_HELPOption OptionGroup)dedent) CommandError)USER_CACHE_DIRget_src_prefix) FormatControl)PyPI) TargetPython) STRONG_HASHES)MYPY_CHECK_RUNNING) BAR_TYPES)AnyCallableDictOptionalTuple) OptionParserValues)ConfigOptionParsercCs.d||}td|}||dS)z Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. z {} error: {} N)formattextwrapZfilljoinspliterror)parseroptionmsgr#@/usr/lib/python3.8/site-packages/pip/_internal/cli/cmdoptions.pyraise_option_error)s r%cCs,t||d}|dD]}||q|S)z Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser nameoptions)r add_option)groupr Z option_groupr!r#r#r$make_option_group7s r*csPdkr |fdd}dddg}tt||rL|j}|tjddd dS) zDisable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. Ncs t|dSN)getattr)n check_optionsr#r$getnameOsz+check_install_build_global..getnameZ build_optionsglobal_optionsinstall_optionszeDisabling all use of wheels due to the use of --build-options / --global-options / --install-options.) stacklevel)anymapformat_controlZdisallow_binarieswarningswarn)r'r/r0namesZcontrolr#r.r$check_install_build_globalDs  r;FcCsbt|j|j|j|jg}ttdh}|j|ko6|j }|rH|rHt d|r^|r^|j s^t ddS)zFunction for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. z:all:zWhen restricting platform and interpreter constraints using --python-version, --platform, --abi, or --implementation, either --no-deps must be set, or --only-binary=:all: must be set and --no-binary must not be set (or must be set to :none:).zQCan not use any platform or abi specific options unless installing via '--target'N) r5python_versionplatformabiimplementationr setr7ignore_dependenciesr Z target_dir)r'Z check_targetZdist_restriction_setZ binary_onlyZsdist_dependencies_allowedr#r#r$check_dist_restriction[s&  rBz-hz--helphelpz Show help.)destactionrCz --isolated isolated_mode store_truezSRun pip in an isolated mode, ignoring environment variables and user configuration.rDrEdefaultrCz--require-virtualenvz--require-venvZ require_venvz-vz --verboseverbosecountzDGive more output. Option is additive, and can be used up to 3 times.z --no-colorno_colorzSuppress colored outputz-Vz --versionversionzShow version and exit.z-qz--quietquietzGive less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).z--progress-bar progress_barchoiceZonz*Specify type of progress to be displayed [|z] (default: %default))rDtypechoicesrIrCz--logz --log-filez --local-loglogpathz Path to a verbose appending log.)rDmetavarrCz --no-inputno_inputz--proxyproxystrz/src". The default for global installs is "/src".cCs t||jS)zGet a format_control object.)r,rD)valuesr!r#r#r$_get_format_controlsrycCs"t|j|}t||j|jdSr+)ryrxr handle_mutual_excludes no_binary only_binaryr!opt_strvaluer Zexistingr#r#r$_handle_no_binarys  rcCs"t|j|}t||j|jdSr+)ryrxr rzr|r{r}r#r#r$_handle_only_binarys  rc Cs$ttt}tdddtd|ddS)Nz --no-binaryr7callbackrYa^Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either :all: to disable all binary packages, :none: to empty the set, or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.rDrErrRrIrC)r r@rrr7r#r#r$r{sr{c Cs$ttt}tdddtd|ddS)Nz --only-binaryr7rrYaGDo not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either :all: to disable all source packages, :none: to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.r)r r@rrrr#r#r$r|sr|z --platformr=z[Only use wheels compatible with . Defaults to the platform of the running system.cCs|sdS|d}t|dkr"dSt|dkrV|d}t|dkrV|d|ddg}ztdd |D}Wntk rYd SX|dfS) z Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. :return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. )NN.)r#z'at most three version parts are allowedrNcss|]}t|VqdSr+)r\).0partr#r#r$ sz*_convert_python_version..)r#z$each version part must be an integer)rlentuple ValueError)rparts version_infor#r#r$_convert_python_versions    rcCs:t|\}}|dk r.d||}t|||d||j_dS)z3 Handle a provided --python-version value. Nz(invalid --python-version value: {!r}: {}r!r")rrr%rxr<)r!r~rr rZ error_msgr"r#r#r$_handle_python_version s rz--python-versionr<ra The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). )rDrVrErrRrIrCz--implementationr?zOnly use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.z--abir>zOnly use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Generally you will need to specify --implementation, --platform, and --python-version when using this option.cCs4|t|t|t|tdSr+)r(r=r<r?r>)Zcmd_optsr#r#r$add_target_python_optionsIs   rcCst|j|j|j|jd}|S)N)r=Zpy_version_infor>r?)rr=r<r>r?)r'Z target_pythonr#r#r$make_target_pythonQsrcCstddddddS)Nz--prefer-binary prefer_binaryrGFz8Prefer older binary packages over newer source packages.rHrir#r#r#r$r]srz --cache-dir cache_dirzStore the cache data in .)rDrIrVrCc CsV|dk rJz t|Wn4tk rH}zt||t|dW5d}~XYnXd|j_dS)z Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. NrF)rrr%rYrxr)r!optrr excr#r#r$_handle_no_cache_dirrs  $ rz--no-cache-dirzDisable the cache.)rDrErrCz --no-depsz--no-dependenciesrAz#Don't install package dependencies.z-bz--buildz --build-dirz--build-directory build_dira>Directory to unpack packages into and build in. Note that an initial build still takes place in a temporary directory. The location of temporary directories can be controlled by setting the TMPDIR environment variable (TEMP on Windows) appropriately. When passed, build directories are not cleaned in case of failures.z--ignore-requires-pythonignore_requires_pythonz'Ignore the Requires-Python information.z--no-build-isolationZbuild_isolationZ store_falseTzDisable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.cCs&|dk rd}t|||dd|j_dS)z Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. Na0A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. rF)r%rx use_pep517)r!rrr r"r#r#r$_handle_no_use_pep517s rz --use-pep517rz^Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).z--no-use-pep517)rDrErrIrCz--install-optionr2rhr'a"Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.)rDrErVrCz--global-optionr1zTExtra global options to be supplied to the setup.py call before the install command.z --no-cleanz!Don't clean up build directories.)rErIrCz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--disable-pip-version-checkdisable_pip_version_checkz{Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.z-Zz--always-unzip always_unzipcCs|jjsi|j_z|dd\}}Wn"tk rF|d|YnX|tkrh|d|dtf|jj|g|dS)zkGiven a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.:rzTArguments to %s must be a hash name followed by a value, like --hash=sha256:abcde...z&Allowed hash algorithms for %s are %s.z, N) rxhashesrrrrr setdefaultrh)r!r~rr ZalgoZdigestr#r#r$_handle_merge_hash)s  rz--hashrstringzgVerify that the package's archive matches this hash before installing. Example: --hash=sha256:abcdef...)rDrErrRrCz--require-hashesrequire_hasheszRequire a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.z--pathz^Restrict to the specified installation path for listing packages (can be used multiple times).cCs|jr|js|jrtddS)Nz2Cannot combine '--path' with '--user' or '--local')rUuserZlocalr )r'r#r#r$check_list_path_option_srzGeneral Options)r&r'zPackage Index Options)N)F)t__doc__Z __future__rZloggingrr8Zdistutils.utilr functoolsrZoptparserrrrZpip._internal.exceptionsr Zpip._internal.locationsr r Z#pip._internal.models.format_controlr Zpip._internal.models.indexr Z"pip._internal.models.target_pythonrZpip._internal.utils.hashesrZpip._internal.utils.typingrZpip._internal.utils.uirtypingrrrrrrrZpip._internal.cli.parserrZ getLogger__name__Zloggerr%r*r;rBZhelp_rFZrequire_virtualenvrJrLrMrNlistkeysrrOrTrWrXr[r^rarbrjrkZ simple_urlrlrnrorprrrsrurvsrcryrrr{r|r=rrr<r?r>rrrrrZno_cacheZno_depsrrZno_build_isolationrrZ no_use_pep517r2r1Zno_cleanZprerrrhashrZ list_pathrZ general_groupZ index_groupr#r#r#r$sB               ,                                         cli/__pycache__/__init__.cpython-38.pyc000064400000000354152347654150013730 0ustar00U .e@sdZdS)zGSubpackage containing all of pip's command line interface related code N)__doc__rr>/usr/lib/python3.8/site-packages/pip/_internal/cli/__init__.pycli/__pycache__/base_command.cpython-38.opt-1.pyc000064400000011603152347654150015537 0ustar00U .eh@s6dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZddlmZmZddlmZmZmZmZmZddlmZmZmZmZmZdd lmZdd l m!Z!m"Z"dd l#m$Z$dd l%m&Z&dd l'm(Z(e&rddl)m*Z*m+Z+m,Z,ddlm-Z-dgZ.e/e0Z1GdddeZ2dS)z(Base Command class, and related routines)absolute_importprint_functionN) cmdoptions)CommandContextMixIn)ConfigOptionParserUpdatingDefaultsHelpFormatter)ERRORPREVIOUS_BUILD_DIR_ERRORSUCCESS UNKNOWN_ERRORVIRTUALENV_NOT_FOUND) BadCommand CommandErrorInstallationErrorPreviousBuildDirErrorUninstallationError) deprecated)BrokenStdoutLoggingError setup_logging)get_prog)MYPY_CHECK_RUNNING)running_under_virtualenv)ListTupleAny)ValuesCommandcsNeZdZdZdZdfdd ZddZddZd d Zd d Z d dZ Z S)rNFcstt||jdt|ftd||j|d}||_||_t f||_ d|j }t |j ||_ttj|j }|j |dS)Nz%s %sF)usageprogZ formatterZadd_help_optionname descriptionisolatedz %s Options)superr__init__rrr__doc__rsummaryrparser capitalizeoptparseZ OptionGroupZcmd_optsrZmake_option_groupZ general_groupZadd_option_group)selfrr%r!Z parser_kwZ optgroup_nameZgen_opts __class__B/usr/lib/python3.8/site-packages/pip/_internal/cli/base_command.pyr#4s&   zCommand.__init__cCsdS)zf This is a no-op so that commands by default do not do the pip version check. Nr,)r)optionsr,r,r-handle_pip_version_checkPsz Command.handle_pip_version_checkcCstdSN)NotImplementedError)r)r.argsr,r,r-runZsz Command.runcCs |j|Sr0)r& parse_argsr)r2r,r,r-r4^szCommand.parse_argsc Cs>z.|||W5QRW SQRXW5tXdSr0)loggingZshutdownZ main_context_mainr5r,r,r-maincs $z Command.mainc Cs||\}}|j|j|_t|j|j|jd}tjdddkrhd}t dkrZd|}t |ddd|j rxdt jd <|jrd |jt jd <|jr|jststd ttzz(|||}t|tr|WWSWntk r2}z.tt|tjd ddtWYWRSd}~XYn>t t!t"fk r}z.tt|tjd ddt#WYWSd}~XYnt$k r}z*td|tjd ddt#WYWSd}~XYnt%k rt&dtj'd|t(j)krt*j+tj'dt#YWfSt,k rDtdtjd ddt#YW2St-k rntjdddt.YWSXW5||Xt/S)N) verbosityno_colorZ user_log_file)r;zA future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportZCPythonzPython 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. )Z replacementZgone_in1Z PIP_NO_INPUT ZPIP_EXISTS_ACTIONz2Could not find an activated virtualenv (required).zException information:T)exc_infoz%sz ERROR: Pipe to stdout was broken)filezOperation cancelled by userz Exception:)0r4verbosequietr9rr:logsys version_infoplatformZpython_implementationrZno_inputosenvironZ exists_actionjoinZ require_venvignore_require_venvrloggerZcriticalexitr r/r3 isinstanceintrstrdebugr rrr rrrprintstderrr6DEBUG traceback print_excKeyboardInterrupt BaseExceptionr r )r)r2r.Z level_numbermessageZstatusexcr,r,r-r7ksn             z Command._main)F) __name__ __module__ __qualname__rrJr#r/r3r4r8r7 __classcell__r,r,r*r-r0s )3r$Z __future__rrr6Zlogging.configr(rGrFrDrTZpip._internal.clirZ!pip._internal.cli.command_contextrZpip._internal.cli.parserrrZpip._internal.cli.status_codesrr r r r Zpip._internal.exceptionsr rrrrZpip._internal.utils.deprecationrZpip._internal.utils.loggingrrZpip._internal.utils.miscrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrtypingrrrr__all__Z getLoggerrZrKrr,r,r,r-s0        cli/__pycache__/autocompletion.cpython-38.pyc000064400000011561152347654150015235 0ustar00U .e@s`dZddlZddlZddlZddlmZddlmZmZddl m Z ddZ dd Z d d Z dS) zBLogic that powers autocompletion installed by ``pip completion``. N)create_main_parser) commands_dictcreate_command)get_installed_distributionscsdtjkrdStjddd}ttjd}z||dWntk rZdYnXttg}zfdd|Dd }Wntk rd}YnXt}|r:|d krt d|d kö d  }|r>g} }t d dD].}|j |r|j |ddkr||j q|r>|D]}t|q$t dt|} | jjD]8} | jtjkrN| j| jD]} || | jfqlqNdd|d|dDfdd|D}fdd|D}t||| jj} | rt| }dd|D}|D]>} | d }| dr,| d dddkr,|d7}t|qndd|jD}||jdd|D} d r|D]$} | jtjkrt| j| j7qtnt|||} | rt| tdfddDt ddS)z?Entry Point for completion of main and subcommand options. ZPIP_AUTO_COMPLETENZ COMP_WORDSZ COMP_CWORDcsg|]}|kr|qSr).0w) subcommandsrD/usr/lib/python3.8/site-packages/pip/_internal/cli/autocompletion.py !sz autocomplete..rhelp)ZshowZ uninstall-T)Z local_onlycSsg|]}|ddqS)=r)splitr xrrr r Dscs g|]\}}|kr||fqSrr)r rv) prev_optsrr r Escs"g|]\}}|r||fqSr startswith)r krcurrentrr r Gs css|]}|dfVqdS)rNr)r optrrr Pszautocomplete..z--rcSsg|] }|jqSr) option_list)r irrr r Zscss|]}|D] }|Vq qdSNr)r itorrr r\s csg|]}|r|qSrrrrrr r gs )osenvironrint IndexErrorlistrrsysexitrlowerrkeyappendprintrparserZoption_list_allroptparse SUPPRESS_HELPZ _long_optsZ _short_optsnargsget_path_completion_typeauto_complete_pathsZ option_groupsrjoin)cwordscwordZoptionsZsubcommand_namer/Zshould_list_installedZ installedZlcZdistZ subcommandrZopt_strcompletion_typeZoptionZ opt_labeloptsr)rrr r autocompletes              r:cCs|dks||ddsdS|D]n}|jtjkr4q"t|dD]L}||ddd|krB|jrtdd|jdDrB|jSqBq"dS) aLGet the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) rrN/rrcss|]}|dkVqdS))pathfiledirNrrrrr rzsz+get_path_completion_type..)rrr0r1strrmetavarany)r6r7r9rr"rrr r3ks  r3c#stj|\}tj|}t|tjs.dStjfddt|D}|D]`}tj||}tjtj||}|dkrtj |r|VqVtj |rVtj|dVqVdS)aoIf ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories Nc3s$|]}tj|r|VqdSr )r$r<normcaserrfilenamerr rsz&auto_complete_paths..r>r) r$r<rabspathaccessR_OKrBlistdirr5isfileisdir)rr8Z directoryZ current_pathZ file_listfrZ comp_filerrCr r4s    r4)__doc__r0r$r)Zpip._internal.cli.main_parserrZpip._internal.commandsrrZpip._internal.utils.miscrr:r3r4rrrr s  [cli/__pycache__/command_context.cpython-38.opt-1.pyc000064400000002053152347654150016310 0ustar00U .e@s,ddlmZddlmZGdddeZdS))contextmanager) ExitStackcs0eZdZfddZeddZddZZS)CommandContextMixIncs tt|d|_t|_dS)NF)superr__init___in_main_contextr _main_contextself __class__E/usr/lib/python3.8/site-packages/pip/_internal/cli/command_context.pyr szCommandContextMixIn.__init__c cs0d|_z|j dVW5QRXW5d|_XdS)NTF)rrr r r r main_contexts z CommandContextMixIn.main_contextcCs |j|S)N)r enter_context)r Zcontext_providerr r rrsz!CommandContextMixIn.enter_context)__name__ __module__ __qualname__rrrr __classcell__r r r rr s  rN) contextlibrZpip._vendor.contextlib2robjectrr r r rs  cli/__pycache__/main_parser.cpython-38.pyc000064400000004157152347654150014476 0ustar00U .e @sdZddlZddlZddlmZddlmZmZddlm Z m Z ddl m Z ddl mZmZddlmZer|dd lmZmZd d gZd d Zd d ZdS)z=A single place for constructing and exposing the main parser N) cmdoptions)ConfigOptionParserUpdatingDefaultsHelpFormatter) commands_dictget_similar_commands) CommandError)get_pip_versionget_prog)MYPY_CHECK_RUNNING)TupleListcreate_main_parser parse_commandcCstddtdtd}tf|}|t|_ttj|}| |d|_ dgddt D}d ||_|S) z6Creates and returns the main parser for pip's CLI z %prog [options]Fglobal)ZusageZadd_help_optionZ formatternameprogTcSsg|]\}}d||jfqS)z%-27s %s)Zsummary).0rZ command_inforA/usr/lib/python3.8/site-packages/pip/_internal/cli/main_parser.py 2sz&create_main_parser.. )rr rZdisable_interspersed_argsrversionrZmake_option_groupZ general_groupZadd_option_groupmainritemsjoin description)Z parser_kwparserZgen_optsrrrrr s"    cCst}||\}}|jr>tj|jtjtjt|rZ|ddkrjt |dkrj| t|d}|t krt |}d|g}|r| d|td||dd}||||fS)Nrhelpzunknown command "%s"zmaybe you meant "%s"z - )r parse_argsrsysstdoutwriteoslinesepexitlenZ print_helprrappendrrremove)argsrZgeneral_optionsZ args_elseZcmd_nameZguessmsgZcmd_argsrrrr;s&    )__doc__r$r!Zpip._internal.clirZpip._internal.cli.parserrrZpip._internal.commandsrrZpip._internal.exceptionsrZpip._internal.utils.miscrr Zpip._internal.utils.typingr typingr r __all__r rrrrrs   #cli/__pycache__/req_command.cpython-38.opt-1.pyc000064400000016404152347654150015420 0ustar00U .ec,@sXdZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZdd lmZdd lmZdd lmZmZmZdd lmZddlmZmZddlmZddlm Z e r"ddl!m"Z"ddl#m$Z$m%Z%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0GdddeZ1Gdddee1Z2Gddde2Z3dS)aContains the Command base classes that depend on PipSession. The classes in this module are in a separate module so the commands not needing download / PackageFinder capability don't unnecessarily import the PackageFinder machinery and all its vendored dependencies, etc. N)partial)Command)CommandContextMixIn) CommandError) PackageFinder)Resolver)SelectionPreferences) PipSession)RequirementPreparer)install_req_from_editableinstall_req_from_lineinstall_req_from_req_string)parse_requirements)make_link_collectorpip_self_version_check)normalize_path)MYPY_CHECK_RUNNING)Values)ListOptionalTuple) WheelCache) TargetPython)RequirementSet)RequirementTracker) TempDirectorycs>eZdZdZfddZeddZddZd d d ZZ S) SessionCommandMixinzE A class mixin for command classes needing _build_session(). cstt|d|_dS)N)superr__init___session)self __class__A/usr/lib/python3.8/site-packages/pip/_internal/cli/req_command.pyr2szSessionCommandMixin.__init__cCsLg}t|dds*t|dd}|r*||t|dd}|rD|||pJdS)z7Return a list of index urls from user-provided options.no_indexFZ index_urlNZextra_index_urls)getattrappendextend)clsoptions index_urlsZurlZurlsr#r#r$_get_index_urls6s     z#SessionCommandMixin._get_index_urlscCs"|jdkr||||_|jS)zGet a default-managed session.N)r enter_context_build_session)r r*r#r#r$get_default_sessionDs z'SessionCommandMixin.get_default_sessionNcCst|jrttj|jdnd|dk r*|n|j|j||d}|j rN|j |_ |j r\|j |_ |j sf|rz|dk rr|n|j |_ |j r|j |j d|_|j |j_|S)Nhttp)cacheretries trusted_hostsr+)r0Zhttps)r cache_dirrospathjoinr2r3r,ZcertZverifyZ client_certtimeoutproxyZproxiesZno_inputZauthZ prompting)r r*r2r8sessionr#r#r$r.Ks*   z"SessionCommandMixin._build_session)NN) __name__ __module__ __qualname____doc__r classmethodr,r/r. __classcell__r#r#r!r$r-s   rc@seZdZdZddZdS)IndexGroupCommandz Abstract base class for commands with the index_group options. This also corresponds to the commands that permit the pip version check. c CsF|js |jrdS|j|dtd|jd}|t||W5QRXdS)z Do the pip version check if not disabled. This overrides the default behavior of not doing the check. Nr)r2r8)Zdisable_pip_version_checkr%r.minr8r)r r*r:r#r#r$handle_pip_version_checkzs  z*IndexGroupCommand.handle_pip_version_checkN)r;r<r=r>rDr#r#r#r$rArsrAc @s:eZdZed ddZedddZd d Zdd d ZdS)RequirementCommandNc Cs"|j}t||j|||j|j|dS)zQ Create a RequirementPreparer instance for the given parameters. )Z build_dirsrc_dir download_dirwheel_download_dir progress_barbuild_isolation req_tracker)r6r rFrIrJ)Ztemp_build_dirr*rKrGrHZtemp_build_dir_pathr#r#r$make_requirement_preparers z,RequirementCommand.make_requirement_preparerFTto-satisfy-onlyc Cs2tt|j|| d} t|||| ||j|||| | d S)zF Create a Resolver instance for the given parameters. )isolated wheel_cache use_pep517) preparerr:findermake_install_req use_user_siteignore_dependenciesignore_installedignore_requires_pythonforce_reinstallupgrade_strategypy_version_info)rr isolated_moderrU) rQr:rRr*rOrTrVrWrXrYrPrZrSr#r#r$ make_resolvers&z RequirementCommand.make_resolverc Cs,|jD].}t|d||||dD]}d|_||qq|D]*} t| d|j|j|d}d|_||q:|jD](} t| |j|j|d}d|_||ql|j D]0}t||||||jdD]}d|_||qq|j |_ |s(|js(|j s(d|j i} |j rt dt| d|j d n t d | dS) z? Marshal cmd line args into a requirement set. T)Z constraintrRr*r:rON)rNrPrO)rRr*r:rOrPnamez^You must give at least one requirement to %(name)s (maybe you meant "pip %(name)s %(links)s"?) )ZlinkszLYou must give at least one requirement to %(name)s (see "pip help %(name)s"))Z constraintsrZ is_directZadd_requirementr r[rPZ editablesr Z requirementsZrequire_hashesr]Z find_linksrdictr7) r Zrequirement_setargsr*rRr:rOfilenameZ req_to_addZreqZoptsr#r#r$populate_requirement_setsn        z+RequirementCommand.populate_requirement_setcCs4t||d}td|j|j|j|d}tj|||dS)z Create a package finder appropriate to this requirement command. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. )r*T)Z allow_yankedformat_controlZallow_all_prereleases prefer_binaryrW)link_collectorselection_prefs target_python)rrrcZprerdrZcreate)r r*r:rgrWrerfr#r#r$_build_package_finders z(RequirementCommand._build_package_finder)NN)NFTFFrMNN)NN)r;r<r= staticmethodrLr\rbrhr#r#r#r$rEs$  &GrE)4r>r5 functoolsrZpip._internal.cli.base_commandrZ!pip._internal.cli.command_contextrZpip._internal.exceptionsrZpip._internal.indexrZpip._internal.legacy_resolverZ$pip._internal.models.selection_prefsrZpip._internal.network.sessionr Z pip._internal.operations.preparer Zpip._internal.req.constructorsr r r Zpip._internal.req.req_filerZ!pip._internal.self_outdated_checkrrZpip._internal.utils.miscrZpip._internal.utils.typingrZoptparsertypingrrrZpip._internal.cacherZ"pip._internal.models.target_pythonrZpip._internal.req.req_setrZpip._internal.req.req_trackerrZpip._internal.utils.temp_dirrrrArEr#r#r#r$s4                   Ecli/__pycache__/autocompletion.cpython-38.opt-1.pyc000064400000011561152347654150016174 0ustar00U .e@s`dZddlZddlZddlZddlmZddlmZmZddl m Z ddZ dd Z d d Z dS) zBLogic that powers autocompletion installed by ``pip completion``. N)create_main_parser) commands_dictcreate_command)get_installed_distributionscsdtjkrdStjddd}ttjd}z||dWntk rZdYnXttg}zfdd|Dd }Wntk rd}YnXt}|r:|d krt d|d kö d  }|r>g} }t d dD].}|j |r|j |ddkr||j q|r>|D]}t|q$t dt|} | jjD]8} | jtjkrN| j| jD]} || | jfqlqNdd|d|dDfdd|D}fdd|D}t||| jj} | rt| }dd|D}|D]>} | d }| dr,| d dddkr,|d7}t|qndd|jD}||jdd|D} d r|D]$} | jtjkrt| j| j7qtnt|||} | rt| tdfddDt ddS)z?Entry Point for completion of main and subcommand options. ZPIP_AUTO_COMPLETENZ COMP_WORDSZ COMP_CWORDcsg|]}|kr|qSr).0w) subcommandsrD/usr/lib/python3.8/site-packages/pip/_internal/cli/autocompletion.py !sz autocomplete..rhelp)ZshowZ uninstall-T)Z local_onlycSsg|]}|ddqS)=r)splitr xrrr r Dscs g|]\}}|kr||fqSrr)r rv) prev_optsrr r Escs"g|]\}}|r||fqSr startswith)r krcurrentrr r Gs css|]}|dfVqdS)rNr)r optrrr Pszautocomplete..z--rcSsg|] }|jqSr) option_list)r irrr r Zscss|]}|D] }|Vq qdSNr)r itorrr r\s csg|]}|r|qSrrrrrr r gs )osenvironrint IndexErrorlistrrsysexitrlowerrkeyappendprintrparserZoption_list_allroptparse SUPPRESS_HELPZ _long_optsZ _short_optsnargsget_path_completion_typeauto_complete_pathsZ option_groupsrjoin)cwordscwordZoptionsZsubcommand_namer/Zshould_list_installedZ installedZlcZdistZ subcommandrZopt_strcompletion_typeZoptionZ opt_labeloptsr)rrr r autocompletes              r:cCs|dks||ddsdS|D]n}|jtjkr4q"t|dD]L}||ddd|krB|jrtdd|jdDrB|jSqBq"dS) aLGet the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) rrN/rrcss|]}|dkVqdS))pathfiledirNrrrrr rzsz+get_path_completion_type..)rrr0r1strrmetavarany)r6r7r9rr"rrr r3ks  r3c#stj|\}tj|}t|tjs.dStjfddt|D}|D]`}tj||}tjtj||}|dkrtj |r|VqVtj |rVtj|dVqVdS)aoIf ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories Nc3s$|]}tj|r|VqdSr )r$r<normcaserrfilenamerr rsz&auto_complete_paths..r>r) r$r<rabspathaccessR_OKrBlistdirr5isfileisdir)rr8Z directoryZ current_pathZ file_listfrZ comp_filerrCr r4s    r4)__doc__r0r$r)Zpip._internal.cli.main_parserrZpip._internal.commandsrrZpip._internal.utils.miscrr:r3r4rrrr s  [cli/__pycache__/req_command.cpython-38.pyc000064400000016506152347654150014464 0ustar00U .ec,@sXdZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZdd lmZdd lmZdd lmZmZmZdd lmZddlmZmZddlmZddlm Z e r"ddl!m"Z"ddl#m$Z$m%Z%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0GdddeZ1Gdddee1Z2Gddde2Z3dS)aContains the Command base classes that depend on PipSession. The classes in this module are in a separate module so the commands not needing download / PackageFinder capability don't unnecessarily import the PackageFinder machinery and all its vendored dependencies, etc. N)partial)Command)CommandContextMixIn) CommandError) PackageFinder)Resolver)SelectionPreferences) PipSession)RequirementPreparer)install_req_from_editableinstall_req_from_lineinstall_req_from_req_string)parse_requirements)make_link_collectorpip_self_version_check)normalize_path)MYPY_CHECK_RUNNING)Values)ListOptionalTuple) WheelCache) TargetPython)RequirementSet)RequirementTracker) TempDirectorycs>eZdZdZfddZeddZddZd d d ZZ S) SessionCommandMixinzE A class mixin for command classes needing _build_session(). cstt|d|_dS)N)superr__init___session)self __class__A/usr/lib/python3.8/site-packages/pip/_internal/cli/req_command.pyr2szSessionCommandMixin.__init__cCsLg}t|dds*t|dd}|r*||t|dd}|rD|||pJdS)z7Return a list of index urls from user-provided options.no_indexFZ index_urlNZextra_index_urls)getattrappendextend)clsoptions index_urlsZurlZurlsr#r#r$_get_index_urls6s     z#SessionCommandMixin._get_index_urlscCs"|jdkr||||_|jS)zGet a default-managed session.N)r enter_context_build_session)r r*r#r#r$get_default_sessionDs z'SessionCommandMixin.get_default_sessionNcCst|jrttj|jdnd|dk r*|n|j|j||d}|j rN|j |_ |j r\|j |_ |j sf|rz|dk rr|n|j |_ |j r|j |j d|_|j |j_|S)Nhttp)cacheretries trusted_hostsr+)r0Zhttps)r cache_dirrospathjoinr2r3r,ZcertZverifyZ client_certtimeoutproxyZproxiesZno_inputZauthZ prompting)r r*r2r8sessionr#r#r$r.Ks*   z"SessionCommandMixin._build_session)NN) __name__ __module__ __qualname____doc__r classmethodr,r/r. __classcell__r#r#r!r$r-s   rc@seZdZdZddZdS)IndexGroupCommandz Abstract base class for commands with the index_group options. This also corresponds to the commands that permit the pip version check. c CsTt|dst|js|jrdS|j|dtd|jd}|t||W5QRXdS)z Do the pip version check if not disabled. This overrides the default behavior of not doing the check. r%Nr)r2r8)hasattrAssertionErrorZdisable_pip_version_checkr%r.minr8r)r r*r:r#r#r$handle_pip_version_checkzs  z*IndexGroupCommand.handle_pip_version_checkN)r;r<r=r>rFr#r#r#r$rArsrAc @s:eZdZed ddZedddZd d Zdd d ZdS)RequirementCommandNc Cs.|j}|dk stt||j|||j|j|dS)zQ Create a RequirementPreparer instance for the given parameters. N)Z build_dirsrc_dir download_dirwheel_download_dir progress_barbuild_isolation req_tracker)r6rDr rHrKrL)Ztemp_build_dirr*rMrIrJZtemp_build_dir_pathr#r#r$make_requirement_preparers  z,RequirementCommand.make_requirement_preparerFTto-satisfy-onlyc Cs2tt|j|| d} t|||| ||j|||| | d S)zF Create a Resolver instance for the given parameters. )isolated wheel_cache use_pep517) preparerr:findermake_install_req use_user_siteignore_dependenciesignore_installedignore_requires_pythonforce_reinstallupgrade_strategypy_version_info)rr isolated_moderrW) rSr:rTr*rQrVrXrYrZr[rRr\rUr#r#r$ make_resolvers&z RequirementCommand.make_resolverc Cs,|jD].}t|d||||dD]}d|_||qq|D]*} t| d|j|j|d}d|_||q:|jD](} t| |j|j|d}d|_||ql|j D]0}t||||||jdD]}d|_||qq|j |_ |s(|js(|j s(d|j i} |j rt dt| d|j d n t d | dS) z? Marshal cmd line args into a requirement set. T)Z constraintrTr*r:rQN)rPrRrQ)rTr*r:rQrRnamez^You must give at least one requirement to %(name)s (maybe you meant "pip %(name)s %(links)s"?) )ZlinkszLYou must give at least one requirement to %(name)s (see "pip help %(name)s"))Z constraintsrZ is_directZadd_requirementr r]rRZ editablesr Z requirementsZrequire_hashesr_Z find_linksrdictr7) r Zrequirement_setargsr*rTr:rQfilenameZ req_to_addZreqZoptsr#r#r$populate_requirement_setsn        z+RequirementCommand.populate_requirement_setcCs4t||d}td|j|j|j|d}tj|||dS)z Create a package finder appropriate to this requirement command. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. )r*T)Z allow_yankedformat_controlZallow_all_prereleases prefer_binaryrY)link_collectorselection_prefs target_python)rrreZprerfrZcreate)r r*r:rirYrgrhr#r#r$_build_package_finders z(RequirementCommand._build_package_finder)NN)NFTFFrONN)NN)r;r<r= staticmethodrNr^rdrjr#r#r#r$rGs$  &GrG)4r>r5 functoolsrZpip._internal.cli.base_commandrZ!pip._internal.cli.command_contextrZpip._internal.exceptionsrZpip._internal.indexrZpip._internal.legacy_resolverZ$pip._internal.models.selection_prefsrZpip._internal.network.sessionr Z pip._internal.operations.preparer Zpip._internal.req.constructorsr r r Zpip._internal.req.req_filerZ!pip._internal.self_outdated_checkrrZpip._internal.utils.miscrZpip._internal.utils.typingrZoptparsertypingrrrZpip._internal.cacherZ"pip._internal.models.target_pythonrZpip._internal.req.req_setrZpip._internal.req.req_trackerrZpip._internal.utils.temp_dirrrrArGr#r#r#r$s4                   Ecli/__pycache__/command_context.cpython-38.pyc000064400000002135152347654150015352 0ustar00U .e@s,ddlmZddlmZGdddeZdS))contextmanager) ExitStackcs0eZdZfddZeddZddZZS)CommandContextMixIncs tt|d|_t|_dS)NF)superr__init___in_main_contextr _main_contextself __class__E/usr/lib/python3.8/site-packages/pip/_internal/cli/command_context.pyr szCommandContextMixIn.__init__c cs:|jr td|_z|j dVW5QRXW5d|_XdS)NTF)rAssertionErrorrr r r r main_contexts  z CommandContextMixIn.main_contextcCs|js t|j|S)N)rrr enter_context)r Zcontext_providerr r rrs z!CommandContextMixIn.enter_context)__name__ __module__ __qualname__rrrr __classcell__r r r rr s  rN) contextlibrZpip._vendor.contextlib2robjectrr r r rs  cli/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000354152347654150014667 0ustar00U .e@sdZdS)zGSubpackage containing all of pip's command line interface related code N)__doc__rr>/usr/lib/python3.8/site-packages/pip/_internal/cli/__init__.pycli/base_command.py000064400000022126152347654150010314 0ustar00"""Base Command class, and related routines""" from __future__ import absolute_import, print_function import logging import logging.config import optparse import os import platform import sys import traceback from pip._internal.cli import cmdoptions from pip._internal.cli.command_context import CommandContextMixIn from pip._internal.cli.parser import ( ConfigOptionParser, UpdatingDefaultsHelpFormatter, ) from pip._internal.cli.status_codes import ( ERROR, PREVIOUS_BUILD_DIR_ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND, ) from pip._internal.exceptions import ( BadCommand, CommandError, InstallationError, NetworkConnectionError, PreviousBuildDirError, SubProcessError, UninstallationError, ) from pip._internal.utils.deprecation import deprecated from pip._internal.utils.filesystem import check_path_owner from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging from pip._internal.utils.misc import get_prog, normalize_path from pip._internal.utils.temp_dir import ( global_tempdir_manager, tempdir_registry, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import running_under_virtualenv if MYPY_CHECK_RUNNING: from typing import List, Optional, Tuple, Any from optparse import Values from pip._internal.utils.temp_dir import ( TempDirectoryTypeRegistry as TempDirRegistry ) __all__ = ['Command'] logger = logging.getLogger(__name__) class Command(CommandContextMixIn): usage = None # type: str ignore_require_venv = False # type: bool def __init__(self, name, summary, isolated=False): # type: (str, str, bool) -> None super(Command, self).__init__() parser_kw = { 'usage': self.usage, 'prog': '{} {}'.format(get_prog(), name), 'formatter': UpdatingDefaultsHelpFormatter(), 'add_help_option': False, 'name': name, 'description': self.__doc__, 'isolated': isolated, } self.name = name self.summary = summary self.parser = ConfigOptionParser(**parser_kw) self.tempdir_registry = None # type: Optional[TempDirRegistry] # Commands should add options to this option group optgroup_name = '{} Options'.format(self.name.capitalize()) self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) # Add the general options gen_opts = cmdoptions.make_option_group( cmdoptions.general_group, self.parser, ) self.parser.add_option_group(gen_opts) self.add_options() def add_options(self): # type: () -> None pass def handle_pip_version_check(self, options): # type: (Values) -> None """ This is a no-op so that commands by default do not do the pip version check. """ # Make sure we do the pip version check if the index_group options # are present. assert not hasattr(options, 'no_index') def run(self, options, args): # type: (Values, List[Any]) -> int raise NotImplementedError def parse_args(self, args): # type: (List[str]) -> Tuple[Any, Any] # factored out for testability return self.parser.parse_args(args) def main(self, args): # type: (List[str]) -> int try: with self.main_context(): return self._main(args) finally: logging.shutdown() def _main(self, args): # type: (List[str]) -> int # We must initialize this before the tempdir manager, otherwise the # configuration would not be accessible by the time we clean up the # tempdir manager. self.tempdir_registry = self.enter_context(tempdir_registry()) # Intentionally set as early as possible so globally-managed temporary # directories are available to the rest of the code. self.enter_context(global_tempdir_manager()) options, args = self.parse_args(args) # Set verbosity so that it can be used elsewhere. self.verbosity = options.verbose - options.quiet level_number = setup_logging( verbosity=self.verbosity, no_color=options.no_color, user_log_file=options.log, ) if ( sys.version_info[:2] == (2, 7) and not options.no_python_version_warning ): message = ( "pip 21.0 will drop support for Python 2.7 in January 2021. " "More details about Python 2 support in pip can be found at " "https://pip.pypa.io/en/latest/development/release-process/#python-2-support" # noqa ) if platform.python_implementation() == "CPython": message = ( "Python 2.7 reached the end of its life on January " "1st, 2020. Please upgrade your Python as Python 2.7 " "is no longer maintained. " ) + message deprecated(message, replacement=None, gone_in="21.0") if ( sys.version_info[:2] == (3, 5) and not options.no_python_version_warning ): message = ( "Python 3.5 reached the end of its life on September " "13th, 2020. Please upgrade your Python as Python 3.5 " "is no longer maintained. pip 21.0 will drop support " "for Python 3.5 in January 2021." ) deprecated(message, replacement=None, gone_in="21.0") # TODO: Try to get these passing down from the command? # without resorting to os.environ to hold these. # This also affects isolated builds and it should. if options.no_input: os.environ['PIP_NO_INPUT'] = '1' if options.exists_action: os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action) if options.require_venv and not self.ignore_require_venv: # If a venv is required check if it can really be found if not running_under_virtualenv(): logger.critical( 'Could not find an activated virtualenv (required).' ) sys.exit(VIRTUALENV_NOT_FOUND) if options.cache_dir: options.cache_dir = normalize_path(options.cache_dir) if not check_path_owner(options.cache_dir): logger.warning( "The directory '%s' or its parent directory is not owned " "or is not writable by the current user. The cache " "has been disabled. Check the permissions and owner of " "that directory. If executing pip with sudo, you may want " "sudo's -H flag.", options.cache_dir, ) options.cache_dir = None if getattr(options, "build_dir", None): deprecated( reason=( "The -b/--build/--build-dir/--build-directory " "option is deprecated." ), replacement=( "use the TMPDIR/TEMP/TMP environment variable, " "possibly combined with --no-clean" ), gone_in="20.3", issue=8333, ) if 'resolver' in options.unstable_features: logger.critical( "--unstable-feature=resolver is no longer supported, and " "has been replaced with --use-feature=2020-resolver instead." ) sys.exit(ERROR) try: status = self.run(options, args) assert isinstance(status, int) return status except PreviousBuildDirError as exc: logger.critical(str(exc)) logger.debug('Exception information:', exc_info=True) return PREVIOUS_BUILD_DIR_ERROR except (InstallationError, UninstallationError, BadCommand, SubProcessError, NetworkConnectionError) as exc: logger.critical(str(exc)) logger.debug('Exception information:', exc_info=True) return ERROR except CommandError as exc: logger.critical('%s', exc) logger.debug('Exception information:', exc_info=True) return ERROR except BrokenStdoutLoggingError: # Bypass our logger and write any remaining messages to stderr # because stdout no longer works. print('ERROR: Pipe to stdout was broken', file=sys.stderr) if level_number <= logging.DEBUG: traceback.print_exc(file=sys.stderr) return ERROR except KeyboardInterrupt: logger.critical('Operation cancelled by user') logger.debug('Exception information:', exc_info=True) return ERROR except BaseException: logger.critical('Exception:', exc_info=True) return UNKNOWN_ERROR finally: self.handle_pip_version_check(options) cli/main_parser.py000064400000005433152347654150010206 0ustar00"""A single place for constructing and exposing the main parser """ import os import sys from pip._internal.cli import cmdoptions from pip._internal.cli.parser import ( ConfigOptionParser, UpdatingDefaultsHelpFormatter, ) from pip._internal.commands import commands_dict, get_similar_commands from pip._internal.exceptions import CommandError from pip._internal.utils.misc import get_pip_version, get_prog from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Tuple, List __all__ = ["create_main_parser", "parse_command"] def create_main_parser(): # type: () -> ConfigOptionParser """Creates and returns the main parser for pip's CLI """ parser_kw = { 'usage': '\n%prog [options]', 'add_help_option': False, 'formatter': UpdatingDefaultsHelpFormatter(), 'name': 'global', 'prog': get_prog(), } parser = ConfigOptionParser(**parser_kw) parser.disable_interspersed_args() parser.version = get_pip_version() # add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts) # so the help formatter knows parser.main = True # type: ignore # create command listing for description description = [''] + [ '{name:27} {command_info.summary}'.format(**locals()) for name, command_info in commands_dict.items() ] parser.description = '\n'.join(description) return parser def parse_command(args): # type: (List[str]) -> Tuple[str, List[str]] parser = create_main_parser() # Note: parser calls disable_interspersed_args(), so the result of this # call is to split the initial args into the general options before the # subcommand and everything else. # For example: # args: ['--timeout=5', 'install', '--user', 'INITools'] # general_options: ['--timeout==5'] # args_else: ['install', '--user', 'INITools'] general_options, args_else = parser.parse_args(args) # --version if general_options.version: sys.stdout.write(parser.version) # type: ignore sys.stdout.write(os.linesep) sys.exit() # pip || pip help -> print_help() if not args_else or (args_else[0] == 'help' and len(args_else) == 1): parser.print_help() sys.exit() # the subcommand name cmd_name = args_else[0] if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name) msg = ['unknown command "{}"'.format(cmd_name)] if guess: msg.append('maybe you meant "{}"'.format(guess)) raise CommandError(' - '.join(msg)) # all the args without the subcommand cmd_args = args[:] cmd_args.remove(cmd_name) return cmd_name, cmd_args cli/parser.py000064400000022410152347654150007174 0ustar00"""Base option parser setup""" # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import optparse import sys import textwrap from distutils.util import strtobool from pip._vendor.six import string_types from pip._internal.cli.status_codes import UNKNOWN_ERROR from pip._internal.configuration import Configuration, ConfigurationError from pip._internal.utils.compat import get_terminal_size logger = logging.getLogger(__name__) class PrettyHelpFormatter(optparse.IndentedHelpFormatter): """A prettier/less verbose help formatter for optparse.""" def __init__(self, *args, **kwargs): # help position must be aligned with __init__.parseopts.description kwargs['max_help_position'] = 30 kwargs['indent_increment'] = 1 kwargs['width'] = get_terminal_size()[0] - 2 optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs) def format_option_strings(self, option): return self._format_option_strings(option) def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '): """ 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 :param optsep: separator """ 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(mvarfmt.format(metavar.lower())) return ''.join(opts) def format_heading(self, heading): if heading == 'Options': return '' return heading + ':\n' def format_usage(self, usage): """ Ensure there is only one newline between usage and the first heading if there is no description. """ msg = '\nUsage: {}\n'.format( self.indent_lines(textwrap.dedent(usage), " ")) return msg def format_description(self, description): # leave full control over description to us if description: if hasattr(self.parser, 'main'): label = 'Commands' else: label = 'Description' # some doc strings have initial newlines, some don't description = description.lstrip('\n') # some doc strings have final newlines and spaces, some don't description = description.rstrip() # dedent, then reindent description = self.indent_lines(textwrap.dedent(description), " ") description = '{}:\n{}\n'.format(label, description) return description else: return '' def format_epilog(self, epilog): # leave full control over epilog to us if epilog: return epilog else: return '' def indent_lines(self, text, indent): new_lines = [indent + line for line in text.split('\n')] return "\n".join(new_lines) class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): """Custom help formatter for use in ConfigOptionParser. This is updates the defaults before expanding them, allowing them to show up correctly in the help listing. """ def expand_default(self, option): if self.parser is not None: self.parser._update_defaults(self.parser.defaults) return optparse.IndentedHelpFormatter.expand_default(self, option) class CustomOptionParser(optparse.OptionParser): def insert_option_group(self, idx, *args, **kwargs): """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs) self.option_groups.pop() self.option_groups.insert(idx, group) return group @property def option_list_all(self): """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list) return res class ConfigOptionParser(CustomOptionParser): """Custom option parser which updates its defaults by checking the configuration files and environmental variables""" def __init__(self, *args, **kwargs): self.name = kwargs.pop('name') isolated = kwargs.pop("isolated", False) self.config = Configuration(isolated) assert self.name optparse.OptionParser.__init__(self, *args, **kwargs) def check_default(self, option, key, val): try: return option.check_value(key, val) except optparse.OptionValueError as exc: print("An error occurred during configuration: {}".format(exc)) sys.exit(3) def _get_ordered_configuration_items(self): # Configuration gives keys in an unordered manner. Order them. override_order = ["global", self.name, ":env:"] # Pool the options into different groups section_items = {name: [] for name in override_order} for section_key, val in self.config.items(): # ignore empty values if not val: logger.debug( "Ignoring configuration key '%s' as it's value is empty.", section_key ) continue section, key = section_key.split(".", 1) if section in override_order: section_items[section].append((key, val)) # Yield each group in their override order for section in override_order: for key, val in section_items[section]: yield key, val def _update_defaults(self, defaults): """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).""" # Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option('--' + key) # Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue if option.action in ('store_true', 'store_false', 'count'): try: val = strtobool(val) except ValueError: error_msg = invalid_config_error_message( option.action, key, val ) self.error(error_msg) elif option.action == 'append': val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == 'callback': late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val) defaults[option.dest] = val for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults def get_default_values(self): """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) # Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err)) defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): default = defaults.get(option.dest) if isinstance(default, string_types): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults) def error(self, msg): self.print_usage(sys.stderr) self.exit(UNKNOWN_ERROR, "{}\n".format(msg)) def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for {1} option, " "please specify a boolean value like yes/no, " "true/false or 1/0 instead.").format(val, key) return ("{0} is not a valid value for {1} option, " "please specify a numerical value like 1/0 " "instead.").format(val, key) cli/status_codes.py000064400000000234152347654150010400 0ustar00from __future__ import absolute_import SUCCESS = 0 ERROR = 1 UNKNOWN_ERROR = 2 VIRTUALENV_NOT_FOUND = 3 PREVIOUS_BUILD_DIR_ERROR = 4 NO_MATCHES_FOUND = 23 cli/autocompletion.py000064400000014623152347654150010751 0ustar00"""Logic that powers autocompletion installed by ``pip completion``. """ import optparse import os import sys from itertools import chain from pip._internal.cli.main_parser import create_main_parser from pip._internal.commands import commands_dict, create_command from pip._internal.utils.misc import get_installed_distributions from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Iterable, List, Optional def autocomplete(): # type: () -> None """Entry Point for completion of main and subcommand options. """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' parser = create_main_parser() subcommands = list(commands_dict) options = [] # subcommand subcommand_name = None # type: Optional[str] for word in cwords: if word in subcommands: subcommand_name = word break # subcommand options if subcommand_name is not None: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = ( subcommand_name in ['show', 'uninstall'] and not current.startswith('-') ) if should_list_installed: installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = create_command(subcommand_name) for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: for opt_str in opt._long_opts + opt._short_opts: options.append((opt_str, opt.nargs)) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ````, ```` or ```` if completion_type: paths = auto_complete_paths(current, completion_type) options = [(path, 0) for path in paths] for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += '=' print(opt_label) else: # show main parser options only when necessary opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) flattened_opts = chain.from_iterable(opts) if current.startswith('-'): for opt in flattened_opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, flattened_opts) if completion_type: subcommands = list(auto_complete_paths(current, completion_type)) print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1) def get_path_completion_type(cwords, cword, opts): # type: (List[str], int, Iterable[Any]) -> Optional[str] """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith('-'): return None for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split('/'): if cwords[cword - 2].split('=')[0] == o: if not opt.metavar or any( x in ('path', 'file', 'dir') for x in opt.metavar.split('/')): return opt.metavar return None def auto_complete_paths(current, completion_type): # type: (str, str) -> Iterable[str] """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = (x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ```` after option # complete directories when there is ````, ```` or # ````after option if completion_type != 'dir' and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, '') cli/req_command.py000064400000035434152347654150010177 0ustar00"""Contains the Command base classes that depend on PipSession. The classes in this module are in a separate module so the commands not needing download / PackageFinder capability don't unnecessarily import the PackageFinder machinery and all its vendored dependencies, etc. """ import logging import os from functools import partial from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.cli.command_context import CommandContextMixIn from pip._internal.exceptions import CommandError, PreviousBuildDirError from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.network.download import Downloader from pip._internal.network.session import PipSession from pip._internal.operations.prepare import RequirementPreparer from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, install_req_from_parsed_requirement, install_req_from_req_string, ) from pip._internal.req.req_file import parse_requirements from pip._internal.self_outdated_check import pip_self_version_check from pip._internal.utils.temp_dir import tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import Any, List, Optional, Tuple from pip._internal.cache import WheelCache from pip._internal.models.target_python import TargetPython from pip._internal.req.req_install import InstallRequirement from pip._internal.req.req_tracker import RequirementTracker from pip._internal.resolution.base import BaseResolver from pip._internal.utils.temp_dir import ( TempDirectory, TempDirectoryTypeRegistry, ) logger = logging.getLogger(__name__) class SessionCommandMixin(CommandContextMixIn): """ A class mixin for command classes needing _build_session(). """ def __init__(self): # type: () -> None super(SessionCommandMixin, self).__init__() self._session = None # Optional[PipSession] @classmethod def _get_index_urls(cls, options): # type: (Values) -> Optional[List[str]] """Return a list of index urls from user-provided options.""" index_urls = [] if not getattr(options, "no_index", False): url = getattr(options, "index_url", None) if url: index_urls.append(url) urls = getattr(options, "extra_index_urls", None) if urls: index_urls.extend(urls) # Return None rather than an empty list return index_urls or None def get_default_session(self, options): # type: (Values) -> PipSession """Get a default-managed session.""" if self._session is None: self._session = self.enter_context(self._build_session(options)) # there's no type annotation on requests.Session, so it's # automatically ContextManager[Any] and self._session becomes Any, # then https://github.com/python/mypy/issues/7696 kicks in assert self._session is not None return self._session def _build_session(self, options, retries=None, timeout=None): # type: (Values, Optional[int], Optional[int]) -> PipSession assert not options.cache_dir or os.path.isabs(options.cache_dir) session = PipSession( cache=( os.path.join(options.cache_dir, "http") if options.cache_dir else None ), retries=retries if retries is not None else options.retries, trusted_hosts=options.trusted_hosts, index_urls=self._get_index_urls(options), ) # Handle custom ca-bundles from the user if options.cert: session.verify = options.cert # Handle SSL client certificate if options.client_cert: session.cert = options.client_cert # Handle timeouts if options.timeout or timeout: session.timeout = ( timeout if timeout is not None else options.timeout ) # Handle configured proxies if options.proxy: session.proxies = { "http": options.proxy, "https": options.proxy, } # Determine if we can prompt the user for authentication or not session.auth.prompting = not options.no_input return session class IndexGroupCommand(Command, SessionCommandMixin): """ Abstract base class for commands with the index_group options. This also corresponds to the commands that permit the pip version check. """ def handle_pip_version_check(self, options): # type: (Values) -> None """ Do the pip version check if not disabled. This overrides the default behavior of not doing the check. """ # Make sure the index_group options are present. assert hasattr(options, 'no_index') if options.disable_pip_version_check or options.no_index: return # Otherwise, check if we're using the latest version of pip available. session = self._build_session( options, retries=0, timeout=min(5, options.timeout) ) with session: pip_self_version_check(session, options) KEEPABLE_TEMPDIR_TYPES = [ tempdir_kinds.BUILD_ENV, tempdir_kinds.EPHEM_WHEEL_CACHE, tempdir_kinds.REQ_BUILD, ] def with_cleanup(func): # type: (Any) -> Any """Decorator for common logic related to managing temporary directories. """ def configure_tempdir_registry(registry): # type: (TempDirectoryTypeRegistry) -> None for t in KEEPABLE_TEMPDIR_TYPES: registry.set_delete(t, False) def wrapper(self, options, args): # type: (RequirementCommand, Values, List[Any]) -> Optional[int] assert self.tempdir_registry is not None if options.no_clean: configure_tempdir_registry(self.tempdir_registry) try: return func(self, options, args) except PreviousBuildDirError: # This kind of conflict can occur when the user passes an explicit # build directory with a pre-existing folder. In that case we do # not want to accidentally remove it. configure_tempdir_registry(self.tempdir_registry) raise return wrapper class RequirementCommand(IndexGroupCommand): def __init__(self, *args, **kw): # type: (Any, Any) -> None super(RequirementCommand, self).__init__(*args, **kw) self.cmd_opts.add_option(cmdoptions.no_clean()) @staticmethod def make_requirement_preparer( temp_build_dir, # type: TempDirectory options, # type: Values req_tracker, # type: RequirementTracker session, # type: PipSession finder, # type: PackageFinder use_user_site, # type: bool download_dir=None, # type: str wheel_download_dir=None, # type: str ): # type: (...) -> RequirementPreparer """ Create a RequirementPreparer instance for the given parameters. """ downloader = Downloader(session, progress_bar=options.progress_bar) temp_build_dir_path = temp_build_dir.path assert temp_build_dir_path is not None return RequirementPreparer( build_dir=temp_build_dir_path, src_dir=options.src_dir, download_dir=download_dir, wheel_download_dir=wheel_download_dir, build_isolation=options.build_isolation, req_tracker=req_tracker, downloader=downloader, finder=finder, require_hashes=options.require_hashes, use_user_site=use_user_site, ) @staticmethod def make_resolver( preparer, # type: RequirementPreparer finder, # type: PackageFinder options, # type: Values wheel_cache=None, # type: Optional[WheelCache] use_user_site=False, # type: bool ignore_installed=True, # type: bool ignore_requires_python=False, # type: bool force_reinstall=False, # type: bool upgrade_strategy="to-satisfy-only", # type: str use_pep517=None, # type: Optional[bool] py_version_info=None # type: Optional[Tuple[int, ...]] ): # type: (...) -> BaseResolver """ Create a Resolver instance for the given parameters. """ make_install_req = partial( install_req_from_req_string, isolated=options.isolated_mode, use_pep517=use_pep517, ) # The long import name and duplicated invocation is needed to convince # Mypy into correctly typechecking. Otherwise it would complain the # "Resolver" class being redefined. if '2020-resolver' in options.features_enabled: import pip._internal.resolution.resolvelib.resolver return pip._internal.resolution.resolvelib.resolver.Resolver( preparer=preparer, finder=finder, wheel_cache=wheel_cache, make_install_req=make_install_req, use_user_site=use_user_site, ignore_dependencies=options.ignore_dependencies, ignore_installed=ignore_installed, ignore_requires_python=ignore_requires_python, force_reinstall=force_reinstall, upgrade_strategy=upgrade_strategy, py_version_info=py_version_info, lazy_wheel='fast-deps' in options.features_enabled, ) import pip._internal.resolution.legacy.resolver return pip._internal.resolution.legacy.resolver.Resolver( preparer=preparer, finder=finder, wheel_cache=wheel_cache, make_install_req=make_install_req, use_user_site=use_user_site, ignore_dependencies=options.ignore_dependencies, ignore_installed=ignore_installed, ignore_requires_python=ignore_requires_python, force_reinstall=force_reinstall, upgrade_strategy=upgrade_strategy, py_version_info=py_version_info, ) def get_requirements( self, args, # type: List[str] options, # type: Values finder, # type: PackageFinder session, # type: PipSession ): # type: (...) -> List[InstallRequirement] """ Parse command-line arguments into the corresponding requirements. """ requirements = [] # type: List[InstallRequirement] for filename in options.constraints: for parsed_req in parse_requirements( filename, constraint=True, finder=finder, options=options, session=session): req_to_add = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode, user_supplied=False, ) requirements.append(req_to_add) for req in args: req_to_add = install_req_from_line( req, None, isolated=options.isolated_mode, use_pep517=options.use_pep517, user_supplied=True, ) requirements.append(req_to_add) for req in options.editables: req_to_add = install_req_from_editable( req, user_supplied=True, isolated=options.isolated_mode, use_pep517=options.use_pep517, ) requirements.append(req_to_add) # NOTE: options.require_hashes may be set if --require-hashes is True for filename in options.requirements: for parsed_req in parse_requirements( filename, finder=finder, options=options, session=session): req_to_add = install_req_from_parsed_requirement( parsed_req, isolated=options.isolated_mode, use_pep517=options.use_pep517, user_supplied=True, ) requirements.append(req_to_add) # If any requirement has hash options, enable hash checking. if any(req.has_hash_options for req in requirements): options.require_hashes = True if not (args or options.editables or options.requirements): opts = {'name': self.name} if options.find_links: raise CommandError( 'You must give at least one requirement to {name} ' '(maybe you meant "pip {name} {links}"?)'.format( **dict(opts, links=' '.join(options.find_links)))) else: raise CommandError( 'You must give at least one requirement to {name} ' '(see "pip help {name}")'.format(**opts)) return requirements @staticmethod def trace_basic_info(finder): # type: (PackageFinder) -> None """ Trace basic information about the provided objects. """ # Display where finder is looking for packages search_scope = finder.search_scope locations = search_scope.get_formatted_locations() if locations: logger.info(locations) def _build_package_finder( self, options, # type: Values session, # type: PipSession target_python=None, # type: Optional[TargetPython] ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> PackageFinder """ Create a package finder appropriate to this requirement command. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. """ link_collector = LinkCollector.create(session, options=options) selection_prefs = SelectionPreferences( allow_yanked=True, format_control=options.format_control, allow_all_prereleases=options.pre, prefer_binary=options.prefer_binary, ignore_requires_python=ignore_requires_python, ) return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, target_python=target_python, ) cli/cmdoptions.py000064400000070156152347654150010071 0ustar00""" shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parses general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this design. """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False from __future__ import absolute_import import os import textwrap import warnings from distutils.util import strtobool from functools import partial from optparse import SUPPRESS_HELP, Option, OptionGroup from textwrap import dedent from pip._internal.cli.progress_bars import BAR_TYPES from pip._internal.exceptions import CommandError from pip._internal.locations import USER_CACHE_DIR, get_src_prefix from pip._internal.models.format_control import FormatControl from pip._internal.models.index import PyPI from pip._internal.models.target_python import TargetPython from pip._internal.utils.hashes import STRONG_HASHES from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Callable, Dict, Optional, Tuple from optparse import OptionParser, Values from pip._internal.cli.parser import ConfigOptionParser def raise_option_error(parser, option, msg): # type: (OptionParser, Option, str) -> None """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = '{} error: {}'.format(option, msg) msg = textwrap.fill(' '.join(msg.split())) parser.error(msg) def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): # type: (str) -> Optional[Any] return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-option ' '/ --global-option / --install-option.', stacklevel=2, ) def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # guaranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" ) def _path_option_check(option, opt, value): # type: (Option, str, str) -> str return os.path.expanduser(value) class PipOption(Option): TYPES = Option.TYPES + ("path",) TYPE_CHECKER = Option.TYPE_CHECKER.copy() TYPE_CHECKER["path"] = _path_option_check ########### # options # ########### help_ = partial( Option, '-h', '--help', dest='help', action='help', help='Show help.', ) # type: Callable[..., Option] isolated_mode = partial( Option, "--isolated", dest="isolated_mode", action="store_true", default=False, help=( "Run pip in an isolated mode, ignoring environment variables and user " "configuration." ), ) # type: Callable[..., Option] require_virtualenv = partial( Option, # Run only if inside a virtualenv, bail if not. '--require-virtualenv', '--require-venv', dest='require_venv', action='store_true', default=False, help=SUPPRESS_HELP ) # type: Callable[..., Option] verbose = partial( Option, '-v', '--verbose', dest='verbose', action='count', default=0, help='Give more output. Option is additive, and can be used up to 3 times.' ) # type: Callable[..., Option] no_color = partial( Option, '--no-color', dest='no_color', action='store_true', default=False, help="Suppress colored output", ) # type: Callable[..., Option] version = partial( Option, '-V', '--version', dest='version', action='store_true', help='Show version and exit.', ) # type: Callable[..., Option] quiet = partial( Option, '-q', '--quiet', dest='quiet', action='count', default=0, help=( 'Give less output. Option is additive, and can be used up to 3' ' times (corresponding to WARNING, ERROR, and CRITICAL logging' ' levels).' ), ) # type: Callable[..., Option] progress_bar = partial( Option, '--progress-bar', dest='progress_bar', type='choice', choices=list(BAR_TYPES.keys()), default='on', help=( 'Specify type of progress to be displayed [' + '|'.join(BAR_TYPES.keys()) + '] (default: %default)' ), ) # type: Callable[..., Option] log = partial( PipOption, "--log", "--log-file", "--local-log", dest="log", metavar="path", type="path", help="Path to a verbose appending log." ) # type: Callable[..., Option] no_input = partial( Option, # Don't ask for input '--no-input', dest='no_input', action='store_true', default=False, help="Disable prompting for input." ) # type: Callable[..., Option] proxy = partial( Option, '--proxy', dest='proxy', type='str', default='', help="Specify a proxy in the form [user:passwd@]proxy.server:port." ) # type: Callable[..., Option] retries = partial( Option, '--retries', dest='retries', type='int', default=5, help="Maximum number of retries each connection should attempt " "(default %default times).", ) # type: Callable[..., Option] timeout = partial( Option, '--timeout', '--default-timeout', metavar='sec', dest='timeout', type='float', default=15, help='Set the socket timeout (default %default seconds).', ) # type: Callable[..., Option] def exists_action(): # type: () -> Option return Option( # Option when path already exist '--exists-action', dest='exists_action', type='choice', choices=['s', 'i', 'w', 'b', 'a'], default=[], action='append', metavar='action', help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", ) cert = partial( PipOption, '--cert', dest='cert', type='path', metavar='path', help="Path to alternate CA bundle.", ) # type: Callable[..., Option] client_cert = partial( PipOption, '--client-cert', dest='client_cert', type='path', default=None, metavar='path', help="Path to SSL client certificate, a single file containing the " "private key and the certificate in PEM format.", ) # type: Callable[..., Option] index_url = partial( Option, '-i', '--index-url', '--pypi-url', dest='index_url', metavar='URL', default=PyPI.simple_url, help="Base URL of the Python Package Index (default %default). " "This should point to a repository compliant with PEP 503 " "(the simple repository API) or a local directory laid out " "in the same format.", ) # type: Callable[..., Option] def extra_index_url(): # type: () -> Option return Option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url.", ) no_index = partial( Option, '--no-index', dest='no_index', action='store_true', default=False, help='Ignore package index (only looking at --find-links URLs instead).', ) # type: Callable[..., Option] def find_links(): # type: () -> Option return Option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='url', help="If a URL or path to an html file, then parse for links to " "archives such as sdist (.tar.gz) or wheel (.whl) files. " "If a local path or file:// URL that's a directory, " "then look for archives in the directory listing. " "Links to VCS project URLs are not supported.", ) def trusted_host(): # type: () -> Option return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host or host:port pair as trusted, even though it " "does not have valid or any HTTPS.", ) def constraints(): # type: () -> Option return Option( '-c', '--constraint', dest='constraints', action='append', default=[], metavar='file', help='Constrain versions using the given constraints file. ' 'This option can be used multiple times.' ) def requirements(): # type: () -> Option return Option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Install from the given requirements file. ' 'This option can be used multiple times.' ) def editable(): # type: () -> Option return Option( '-e', '--editable', dest='editables', action='append', default=[], metavar='path/url', help=('Install a project in editable mode (i.e. setuptools ' '"develop mode") from a local project path or a VCS url.'), ) def _handle_src(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None value = os.path.abspath(value) setattr(parser.values, option.dest, value) src = partial( PipOption, '--src', '--source', '--source-dir', '--source-directory', dest='src_dir', type='path', metavar='dir', default=get_src_prefix(), action='callback', callback=_handle_src, help='Directory to check out editable projects into. ' 'The default in a virtualenv is "/src". ' 'The default for global installs is "/src".' ) # type: Callable[..., Option] def _get_format_control(values, option): # type: (Values, Option) -> Any """Get a format_control object.""" return getattr(values, option.dest) def _handle_no_binary(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.no_binary, existing.only_binary, ) def _handle_only_binary(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.only_binary, existing.no_binary, ) def no_binary(): # type: () -> Option format_control = FormatControl(set(), set()) return Option( "--no-binary", dest="format_control", action="callback", callback=_handle_no_binary, type="str", default=format_control, help='Do not use binary packages. Can be supplied multiple times, and ' 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all binary packages, ":none:" to empty the set (notice ' 'the colons), or one or more package names with commas between ' 'them (no colons). Note that some packages are tricky to compile ' 'and may fail to install when this option is used on them.', ) def only_binary(): # type: () -> Option format_control = FormatControl(set(), set()) return Option( "--only-binary", dest="format_control", action="callback", callback=_handle_only_binary, type="str", default=format_control, help='Do not use source packages. Can be supplied multiple times, and ' 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all source packages, ":none:" to empty the set, or one ' 'or more package names with commas between them. Packages ' 'without binary distributions will fail to install when this ' 'option is used on them.', ) platform = partial( Option, '--platform', dest='platform', metavar='platform', default=None, help=("Only use wheels compatible with . " "Defaults to the platform of the running system."), ) # type: Callable[..., Option] # This was made a separate function for unit-testing purposes. def _convert_python_version(value): # type: (str) -> Tuple[Tuple[int, ...], Optional[str]] """ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. :return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. """ if not value: # The empty string is the same as not providing a value. return (None, None) parts = value.split('.') if len(parts) > 3: return ((), 'at most three version parts are allowed') if len(parts) == 1: # Then we are in the case of "3" or "37". value = parts[0] if len(value) > 1: parts = [value[0], value[1:]] try: version_info = tuple(int(part) for part in parts) except ValueError: return ((), 'each version part must be an integer') return (version_info, None) def _handle_python_version(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """ Handle a provided --python-version value. """ version_info, error_msg = _convert_python_version(value) if error_msg is not None: msg = ( 'invalid --python-version value: {!r}: {}'.format( value, error_msg, ) ) raise_option_error(parser, option=option, msg=msg) parser.values.python_version = version_info python_version = partial( Option, '--python-version', dest='python_version', metavar='python_version', action='callback', callback=_handle_python_version, type='str', default=None, help=dedent("""\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """), ) # type: Callable[..., Option] implementation = partial( Option, '--implementation', dest='implementation', metavar='implementation', default=None, help=("Only use wheels compatible with Python " "implementation , e.g. 'pp', 'jy', 'cp', " " or 'ip'. If not specified, then the current " "interpreter implementation is used. Use 'py' to force " "implementation-agnostic wheels."), ) # type: Callable[..., Option] abi = partial( Option, '--abi', dest='abi', metavar='abi', default=None, help=("Only use wheels compatible with Python " "abi , e.g. 'pypy_41'. If not specified, then the " "current interpreter abi tag is used. Generally " "you will need to specify --implementation, " "--platform, and --python-version when using " "this option."), ) # type: Callable[..., Option] def add_target_python_options(cmd_opts): # type: (OptionGroup) -> None cmd_opts.add_option(platform()) cmd_opts.add_option(python_version()) cmd_opts.add_option(implementation()) cmd_opts.add_option(abi()) def make_target_python(options): # type: (Values) -> TargetPython target_python = TargetPython( platform=options.platform, py_version_info=options.python_version, abi=options.abi, implementation=options.implementation, ) return target_python def prefer_binary(): # type: () -> Option return Option( "--prefer-binary", dest="prefer_binary", action="store_true", default=False, help="Prefer older binary packages over newer source packages." ) cache_dir = partial( PipOption, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", type='path', help="Store the cache data in ." ) # type: Callable[..., Option] def _handle_no_cache_dir(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False no_cache = partial( Option, "--no-cache-dir", dest="cache_dir", action="callback", callback=_handle_no_cache_dir, help="Disable the cache.", ) # type: Callable[..., Option] no_deps = partial( Option, '--no-deps', '--no-dependencies', dest='ignore_dependencies', action='store_true', default=False, help="Don't install package dependencies.", ) # type: Callable[..., Option] def _handle_build_dir(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None if value: value = os.path.abspath(value) setattr(parser.values, option.dest, value) build_dir = partial( PipOption, '-b', '--build', '--build-dir', '--build-directory', dest='build_dir', type='path', metavar='dir', action='callback', callback=_handle_build_dir, help='(DEPRECATED) ' 'Directory to unpack packages into and build in. Note that ' 'an initial build still takes place in a temporary directory. ' 'The location of temporary directories can be controlled by setting ' 'the TMPDIR environment variable (TEMP on Windows) appropriately. ' 'When passed, build directories are not cleaned in case of failures.' ) # type: Callable[..., Option] ignore_requires_python = partial( Option, '--ignore-requires-python', dest='ignore_requires_python', action='store_true', help='Ignore the Requires-Python information.' ) # type: Callable[..., Option] no_build_isolation = partial( Option, '--no-build-isolation', dest='build_isolation', action='store_false', default=True, help='Disable isolation when building a modern source distribution. ' 'Build dependencies specified by PEP 518 must be already installed ' 'if this option is used.' ) # type: Callable[..., Option] def _handle_no_use_pep517(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is passed via the command-line. # However, the value can be non-None if the option is triggered e.g. # by an environment variable, for example "PIP_NO_USE_PEP517=true". if value is not None: msg = """A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. """ raise_option_error(parser, option=option, msg=msg) # Otherwise, --no-use-pep517 was passed via the command-line. parser.values.use_pep517 = False use_pep517 = partial( Option, '--use-pep517', dest='use_pep517', action='store_true', default=None, help='Use PEP 517 for building source distributions ' '(use --no-use-pep517 to force legacy behaviour).' ) # type: Any no_use_pep517 = partial( Option, '--no-use-pep517', dest='use_pep517', action='callback', callback=_handle_no_use_pep517, default=None, help=SUPPRESS_HELP ) # type: Any install_options = partial( Option, '--install-option', dest='install_options', action='append', metavar='options', help="Extra arguments to be supplied to the setup.py install " "command (use like --install-option=\"--install-scripts=/usr/local/" "bin\"). Use multiple --install-option options to pass multiple " "options to setup.py install. If you are using an option with a " "directory path, be sure to use absolute path.", ) # type: Callable[..., Option] global_options = partial( Option, '--global-option', dest='global_options', action='append', metavar='options', help="Extra global options to be supplied to the setup.py " "call before the install command.", ) # type: Callable[..., Option] no_clean = partial( Option, '--no-clean', action='store_true', default=False, help="Don't clean up build directories." ) # type: Callable[..., Option] pre = partial( Option, '--pre', action='store_true', default=False, help="Include pre-release and development versions. By default, " "pip only finds stable versions.", ) # type: Callable[..., Option] disable_pip_version_check = partial( Option, "--disable-pip-version-check", dest="disable_pip_version_check", action="store_true", default=False, help="Don't periodically check PyPI to determine whether a new version " "of pip is available for download. Implied with --no-index.", ) # type: Callable[..., Option] def _handle_merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to {} must be a hash name ' # noqa 'followed by a value, like --hash=sha256:' 'abcde...'.format(opt_str)) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for {} are {}.'.format( # noqa opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest) hash = partial( Option, '--hash', # Hash values eventually end up in InstallRequirement.hashes due to # __dict__ copying in process_line(). dest='hashes', action='callback', callback=_handle_merge_hash, type='string', help="Verify that the package's archive matches this " 'hash before installing. Example: --hash=sha256:abcdef...', ) # type: Callable[..., Option] require_hashes = partial( Option, '--require-hashes', dest='require_hashes', action='store_true', default=False, help='Require a hash to check each requirement against, for ' 'repeatable installs. This option is implied when any package in a ' 'requirements file has a --hash option.', ) # type: Callable[..., Option] list_path = partial( PipOption, '--path', dest='path', type='path', action='append', help='Restrict to the specified installation path for listing ' 'packages (can be used multiple times).' ) # type: Callable[..., Option] def check_list_path_option(options): # type: (Values) -> None if options.path and (options.user or options.local): raise CommandError( "Cannot combine '--path' with '--user' or '--local'" ) no_python_version_warning = partial( Option, '--no-python-version-warning', dest='no_python_version_warning', action='store_true', default=False, help='Silence deprecation warnings for upcoming unsupported Pythons.', ) # type: Callable[..., Option] unstable_feature = partial( Option, '--unstable-feature', dest='unstable_features', metavar='feature', action='append', default=[], choices=['resolver'], help=SUPPRESS_HELP, # TODO: drop this in pip 20.3 ) # type: Callable[..., Option] use_new_feature = partial( Option, '--use-feature', dest='features_enabled', metavar='feature', action='append', default=[], choices=['2020-resolver', 'fast-deps'], help='Enable new functionality, that may be backward incompatible.', ) # type: Callable[..., Option] use_deprecated_feature = partial( Option, '--use-deprecated', dest='deprecated_features_enabled', metavar='feature', action='append', default=[], choices=[], help=( 'Enable deprecated functionality, that will be removed in the future.' ), ) # type: Callable[..., Option] ########## # groups # ########## general_group = { 'name': 'General Options', 'options': [ help_, isolated_mode, require_virtualenv, verbose, version, quiet, log, no_input, proxy, retries, timeout, exists_action, trusted_host, cert, client_cert, cache_dir, no_cache, disable_pip_version_check, no_color, no_python_version_warning, unstable_feature, use_new_feature, use_deprecated_feature, ] } # type: Dict[str, Any] index_group = { 'name': 'Package Index Options', 'options': [ index_url, extra_index_url, no_index, find_links, ] } # type: Dict[str, Any] cli/__init__.py000064400000000204152347654150007434 0ustar00"""Subpackage containing all of pip's command line interface related code """ # This file intentionally does not import submodules cli/command_context.py000064400000001717152347654150011071 0ustar00from contextlib import contextmanager from pip._vendor.contextlib2 import ExitStack from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Iterator, ContextManager, TypeVar _T = TypeVar('_T', covariant=True) class CommandContextMixIn(object): def __init__(self): # type: () -> None super(CommandContextMixIn, self).__init__() self._in_main_context = False self._main_context = ExitStack() @contextmanager def main_context(self): # type: () -> Iterator[None] assert not self._in_main_context self._in_main_context = True try: with self._main_context: yield finally: self._in_main_context = False def enter_context(self, context_provider): # type: (ContextManager[_T]) -> _T assert self._in_main_context return self._main_context.enter_context(context_provider) models/index.py000064400000002211152347654150007520 0ustar00from pip._vendor.six.moves.urllib import parse as urllib_parse class PackageIndex(object): """Represents a Package Index and provides easier access to endpoints """ __slots__ = ['url', 'netloc', 'simple_url', 'pypi_url', 'file_storage_domain'] def __init__(self, url, file_storage_domain): # type: (str, str) -> None super(PackageIndex, self).__init__() self.url = url self.netloc = urllib_parse.urlsplit(url).netloc self.simple_url = self._url_for_path('simple') self.pypi_url = self._url_for_path('pypi') # This is part of a temporary hack used to block installs of PyPI # packages which depend on external urls only necessary until PyPI can # block such packages themselves self.file_storage_domain = file_storage_domain def _url_for_path(self, path): # type: (str) -> str return urllib_parse.urljoin(self.url, path) PyPI = PackageIndex( 'https://pypi.org/', file_storage_domain='files.pythonhosted.org' ) TestPyPI = PackageIndex( 'https://test.pypi.org/', file_storage_domain='test-files.pythonhosted.org' ) models/format_control.py000064400000005407152347654150011453 0ustar00from pip._vendor.packaging.utils import canonicalize_name from pip._internal.exceptions import CommandError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Set, FrozenSet class FormatControl(object): """Helper for managing formats from which a package can be installed. """ __slots__ = ["no_binary", "only_binary"] def __init__(self, no_binary=None, only_binary=None): # type: (Optional[Set[str]], Optional[Set[str]]) -> None if no_binary is None: no_binary = set() if only_binary is None: only_binary = set() self.no_binary = no_binary self.only_binary = only_binary def __eq__(self, other): # type: (object) -> bool if not isinstance(other, self.__class__): return NotImplemented if self.__slots__ != other.__slots__: return False return all( getattr(self, k) == getattr(other, k) for k in self.__slots__ ) def __ne__(self, other): # type: (object) -> bool return not self.__eq__(other) def __repr__(self): # type: () -> str return "{}({}, {})".format( self.__class__.__name__, self.no_binary, self.only_binary ) @staticmethod def handle_mutual_excludes(value, target, other): # type: (str, Set[str], Set[str]) -> None if value.startswith('-'): raise CommandError( "--no-binary / --only-binary option requires 1 argument." ) new = value.split(',') while ':all:' in new: other.clear() target.clear() target.add(':all:') del new[:new.index(':all:') + 1] # Without a none, we want to discard everything as :all: covers it if ':none:' not in new: return for name in new: if name == ':none:': target.clear() continue name = canonicalize_name(name) other.discard(name) target.add(name) def get_allowed_formats(self, canonical_name): # type: (str) -> FrozenSet[str] result = {"binary", "source"} if canonical_name in self.only_binary: result.discard('source') elif canonical_name in self.no_binary: result.discard('binary') elif ':all:' in self.only_binary: result.discard('source') elif ':all:' in self.no_binary: result.discard('binary') return frozenset(result) def disallow_binaries(self): # type: () -> None self.handle_mutual_excludes( ':all:', self.no_binary, self.only_binary, ) models/__pycache__/link.cpython-38.pyc000064400000014775152347654150013656 0ustar00U .e@sddlZddlZddlZddlmZddlmZddlm Z m Z m Z ddl m Z ddlmZddlmZmZerddlmZmZmZmZdd lmZdd lmZGd d d e ZdS) N)parse)WHEEL_EXTENSION)redact_auth_from_urlsplit_auth_from_netlocsplitext)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) path_to_url url_to_path)OptionalTextTupleUnion)HTMLPage)Hashescs@eZdZdZd6fdd ZddZddZed d Zed d Z ed dZ eddZ eddZ eddZ ddZeddZeddZedZeddZedZedd Zed!Zed"d#Zed$d%Zed&d'Zed(d)Zd*d+Zed,d-Zed.d/Zed0d1Zed2d3Z d4d5Z!Z"S)7Linkz?Represents a parsed link from a Package Index's simple URL NcsV|drt|}t||_||_||_|r2|nd|_||_t t |j |t ddS)a` :param url: url of the resource pointed to (href of the link) :param comes_from: instance of HTMLPage where the link was found, or string. :param requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. :param yanked_reason: the reason the file has been yanked, if the file has been yanked, or None if the file hasn't been yanked. This is the value of the "data-yanked" attribute, if present, in a simple repository HTML link. If the file has been yanked but no reason was provided, this should be the empty string. See PEP 592 for more information and the specification. z\\N)keyZdefining_class) startswithr urllib_parseZurlsplit _parsed_url_url comes_fromrequires_python yanked_reasonsuperr__init__)selfurlrrr __class__=/usr/lib/python3.8/site-packages/pip/_internal/models/link.pyrs  z Link.__init__cCsD|jrd|j}nd}|jr2dt|j|j|fStt|jSdS)Nz (requires-python:%s)z%s (from %s)%s)rrrrstr)rZrpr r r!__str__Es  z Link.__str__cCsd|S)Nz r rr r r!__repr__Psz Link.__repr__cCs|jSN)rr%r r r!rSszLink.urlcCsL|jd}t|}|s,t|j\}}|St|}|sHtd|j |S)N/zURL %r produced no filename) pathrstrip posixpathbasenamernetlocrunquoteAssertionErrorr)rr)namer-Z user_passr r r!filenameXs   z Link.filenamecCs t|jSr')r rr%r r r! file_pathgszLink.file_pathcCs|jjSr')rschemer%r r r!r3lsz Link.schemecCs|jjS)z4 This can contain auth information. )rr-r%r r r!r-qsz Link.netloccCst|jjSr')rr.rr)r%r r r!r)ysz Link.pathcCstt|jdS)Nr()rr+r,r)r*r%r r r!r~sz Link.splitextcCs |dSN)rr%r r r!extszLink.extcCs$|j\}}}}}t||||dfSr')rrZ urlunsplit)rr3r-r)ZqueryZfragmentr r r!url_without_fragmentszLink.url_without_fragmentz[#&]egg=([^&]*)cCs |j|j}|sdS|dSr4)_egg_fragment_researchrgrouprmatchr r r! egg_fragmentszLink.egg_fragmentz[#&]subdirectory=([^&]*)cCs |j|j}|sdS|dSr4)_subdirectory_fragment_rer9rr:r;r r r!subdirectory_fragmentszLink.subdirectory_fragmentz2(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)cCs |j|j}|r|dSdS)N_hash_rer9rr:r;r r r!hashs z Link.hashcCs |j|j}|r|dSdSr4rAr;r r r! hash_names zLink.hash_namecCs$t|jddddddS)N#r5r?)r+r,rsplitr%r r r!show_urlsz Link.show_urlcCs |jdkS)Nfile)r3r%r r r!is_filesz Link.is_filecCs|jotj|jSr')rJosr)isdirr2r%r r r!is_existing_dirszLink.is_existing_dircCs |jtkSr')r6rr%r r r!is_wheelsz Link.is_wheelcCsddlm}|j|jkS)Nr)vcs)Zpip._internal.vcsrOr3Z all_schemes)rrOr r r!is_vcss z Link.is_vcscCs |jdk Sr')rr%r r r! is_yankedszLink.is_yankedcCs |jdk Sr')rDr%r r r!has_hashsz Link.has_hashcCs@|dks|jsdS|jdk s t|jdk s.t|j|j|jdS)zG Return True if the link has a hash and it is allowed. NF)Z hex_digest)rRrDr/rCis_hash_allowed)rZhashesr r r!rSs zLink.is_hash_allowed)NNN)#__name__ __module__ __qualname____doc__rr$r&propertyrr1r2r3r-r)rr6r7recompiler8r=r>r?rBrCrDrHrJrMrNrPrQrRrS __classcell__r r rr!rsf'                     r)rKr+rYZpip._vendor.six.moves.urllibrrZpip._internal.utils.filetypesrZpip._internal.utils.miscrrrZpip._internal.utils.modelsrZpip._internal.utils.typingrZpip._internal.utils.urlsr r typingr r r rZpip._internal.collectorrZpip._internal.utils.hashesrrr r r r!s      models/__pycache__/index.cpython-38.pyc000064400000002172152347654150014014 0ustar00U .e$@s8ddlmZGdddeZedddZedddZd S) )parsecs(eZdZdZfddZddZZS) PackageIndexzGRepresents a Package Index and provides easier access to endpoints csDtt|||_t|j|_|d|_|d|_ ||_ dS)NZsimpleZpypi) superr__init__url urllib_parseZurlsplitZnetloc _url_for_pathZ simple_urlZpypi_urlfile_storage_domain)selfrr  __class__>/usr/lib/python3.8/site-packages/pip/_internal/models/index.pyrs   zPackageIndex.__init__cCst|j|S)N)rZurljoinr)r pathr r rrszPackageIndex._url_for_path)__name__ __module__ __qualname____doc__rr __classcell__r r r rrs rzhttps://pypi.org/zfiles.pythonhosted.org)r zhttps://test.pypi.org/ztest-files.pythonhosted.orgN)Zpip._vendor.six.moves.urllibrrobjectrZPyPIZTestPyPIr r r rs models/__pycache__/target_python.cpython-38.pyc000064400000006200152347654150015570 0ustar00U .e@shddlZddlmZmZddlmZddlmZerTddlm Z m Z m Z ddlm Z Gddde ZdS) N) get_supportedversion_info_to_nodot)normalize_version_info)MYPY_CHECK_RUNNING)ListOptionalTuple) Pep425Tagc@s*eZdZdZd ddZddZddZdS) TargetPythonzx Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc. NcCsf||_|dkrtjdd}nt|}dtt|dd}||_||_||_ ||_ ||_ d|_ dS)a :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param py_version_info: An optional tuple of ints representing the Python version information to use (e.g. `sys.version_info[:3]`). This can have length 1, 2, or 3 when provided. :param abi: A string or None. This is passed to pep425tags.py's get_supported() function as is. :param implementation: A string or None. This is passed to pep425tags.py's get_supported() function as is. N.) _given_py_version_infosys version_inforjoinmapstrabiimplementationplatform py_versionpy_version_info _valid_tags)selfrrrrrrF/usr/lib/python3.8/site-packages/pip/_internal/models/target_python.py__init__szTargetPython.__init__cCsZd}|jdk r$ddd|jD}d|jfd|fd|jfd|jfg}d d d|DS) zD Format the given, non-None attributes for display. Nr css|]}t|VqdS)N)r).0partrrr Csz,TargetPython.format_given..rrrr css&|]\}}|dk rd||VqdS)Nz{}={!r})format)rkeyvaluerrrr Ms)rrrrr)rZdisplay_versionZ key_valuesrrr format_given<s   zTargetPython.format_givencCsJ|jdkrD|j}|dkrd}n t|g}t||j|j|jd}||_|jS)z Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). N)versionsrrimpl)rrrrrrr)rrr&Ztagsrrrget_tagsRs  zTargetPython.get_tags)NNNN)__name__ __module__ __qualname____doc__rr%r(rrrrr s )r )rZpip._internal.pep425tagsrrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingrrrr objectr rrrrs   models/__pycache__/format_control.cpython-38.pyc000064400000004560152347654150015740 0ustar00U .e @sPddlmZddlmZddlmZers   models/__pycache__/search_scope.cpython-38.pyc000064400000006263152347654150015350 0ustar00U .e@sddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZmZddlmZer|ddlmZeeZGd d d eZdS) N)canonicalize_name)parse)PyPI)HAS_TLS)normalize_pathredact_auth_from_url)MYPY_CHECK_RUNNING)Listc@s4eZdZdZeddZddZddZdd Zd S) SearchScopezF Encapsulates the locations that pip is configured to search. cCs~g}|D]0}|dr.t|}tj|r.|}||qtsrt||D]&}t |}|j dkrJt dqrqJ|||dS)zQ Create a SearchScope object after normalizing the `find_links`. ~Zhttpszipip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. find_links index_urls) startswithrospathexistsappendr itertoolschain urllib_parseZurlparseZschemeloggerZwarning)clsr rZbuilt_find_linkslinkZnew_linkZparsedrE/usr/lib/python3.8/site-packages/pip/_internal/models/search_scope.pycreates&     zSearchScope.createcCs||_||_dSNr )selfr rrrr__init__GszSearchScope.__init__cCslg}|jr:|jtjgkr:|dddd|jD|jrb|dddd|jDd|S)NzLooking in indexes: {}z, css|]}t|VqdSrr.0urlrrr Usz6SearchScope.get_formatted_locations..zLooking in links: {}css|]}t|VqdSrr r!rrrr$Zs )rrZ simple_urlrformatjoinr )rlinesrrrget_formatted_locationsPsz#SearchScope.get_formatted_locationscs fddfdd|jDS)zReturns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations cs,t|tt}|ds(|d}|S)N/) posixpathr'rZquoterendswith)r#Zloc) project_namerrmkurl_pypi_urlgs  z.mkurl_pypi_urlcsg|] }|qSrrr!)r.rr tsz8SearchScope.get_index_urls_locations..)r)rr-r)r.r-rget_index_urls_locations_s z$SearchScope.get_index_urls_locationsN) __name__ __module__ __qualname____doc__ classmethodrrr)r0rrrrr s  ( r )rZloggingrr+Zpip._vendor.packaging.utilsrZpip._vendor.six.moves.urllibrrZpip._internal.models.indexrZpip._internal.utils.compatrZpip._internal.utils.miscrrZpip._internal.utils.typingrtypingr Z getLoggerr1robjectr rrrrs       models/__pycache__/target_python.cpython-38.opt-1.pyc000064400000006200152347654150016527 0ustar00U .e@shddlZddlmZmZddlmZddlmZerTddlm Z m Z m Z ddlm Z Gddde ZdS) N) get_supportedversion_info_to_nodot)normalize_version_info)MYPY_CHECK_RUNNING)ListOptionalTuple) Pep425Tagc@s*eZdZdZd ddZddZddZdS) TargetPythonzx Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc. NcCsf||_|dkrtjdd}nt|}dtt|dd}||_||_||_ ||_ ||_ d|_ dS)a :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param py_version_info: An optional tuple of ints representing the Python version information to use (e.g. `sys.version_info[:3]`). This can have length 1, 2, or 3 when provided. :param abi: A string or None. This is passed to pep425tags.py's get_supported() function as is. :param implementation: A string or None. This is passed to pep425tags.py's get_supported() function as is. N.) _given_py_version_infosys version_inforjoinmapstrabiimplementationplatform py_versionpy_version_info _valid_tags)selfrrrrrrF/usr/lib/python3.8/site-packages/pip/_internal/models/target_python.py__init__szTargetPython.__init__cCsZd}|jdk r$ddd|jD}d|jfd|fd|jfd|jfg}d d d|DS) zD Format the given, non-None attributes for display. Nr css|]}t|VqdS)N)r).0partrrr Csz,TargetPython.format_given..rrrr css&|]\}}|dk rd||VqdS)Nz{}={!r})format)rkeyvaluerrrr Ms)rrrrr)rZdisplay_versionZ key_valuesrrr format_given<s   zTargetPython.format_givencCsJ|jdkrD|j}|dkrd}n t|g}t||j|j|jd}||_|jS)z Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). N)versionsrrimpl)rrrrrrr)rrr&Ztagsrrrget_tagsRs  zTargetPython.get_tags)NNNN)__name__ __module__ __qualname____doc__rr%r(rrrrr s )r )rZpip._internal.pep425tagsrrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingrrrr objectr rrrrs   models/__pycache__/__init__.cpython-38.pyc000064400000000340152347654150014437 0ustar00U .e?@sdZdS)z8A package that contains models that represent entities. N)__doc__rrA/usr/lib/python3.8/site-packages/pip/_internal/models/__init__.pymodels/__pycache__/index.cpython-38.opt-1.pyc000064400000002172152347654150014753 0ustar00U .e$@s8ddlmZGdddeZedddZedddZd S) )parsecs(eZdZdZfddZddZZS) PackageIndexzGRepresents a Package Index and provides easier access to endpoints csDtt|||_t|j|_|d|_|d|_ ||_ dS)NZsimpleZpypi) superr__init__url urllib_parseZurlsplitZnetloc _url_for_pathZ simple_urlZpypi_urlfile_storage_domain)selfrr  __class__>/usr/lib/python3.8/site-packages/pip/_internal/models/index.pyrs   zPackageIndex.__init__cCst|j|S)N)rZurljoinr)r pathr r rrszPackageIndex._url_for_path)__name__ __module__ __qualname____doc__rr __classcell__r r r rrs rzhttps://pypi.org/zfiles.pythonhosted.org)r zhttps://test.pypi.org/ztest-files.pythonhosted.orgN)Zpip._vendor.six.moves.urllibrrobjectrZPyPIZTestPyPIr r r rs models/__pycache__/search_scope.cpython-38.opt-1.pyc000064400000006263152347654150016307 0ustar00U .e@sddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZmZddlmZer|ddlmZeeZGd d d eZdS) N)canonicalize_name)parse)PyPI)HAS_TLS)normalize_pathredact_auth_from_url)MYPY_CHECK_RUNNING)Listc@s4eZdZdZeddZddZddZdd Zd S) SearchScopezF Encapsulates the locations that pip is configured to search. cCs~g}|D]0}|dr.t|}tj|r.|}||qtsrt||D]&}t |}|j dkrJt dqrqJ|||dS)zQ Create a SearchScope object after normalizing the `find_links`. ~Zhttpszipip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. find_links index_urls) startswithrospathexistsappendr itertoolschain urllib_parseZurlparseZschemeloggerZwarning)clsr rZbuilt_find_linkslinkZnew_linkZparsedrE/usr/lib/python3.8/site-packages/pip/_internal/models/search_scope.pycreates&     zSearchScope.createcCs||_||_dSNr )selfr rrrr__init__GszSearchScope.__init__cCslg}|jr:|jtjgkr:|dddd|jD|jrb|dddd|jDd|S)NzLooking in indexes: {}z, css|]}t|VqdSrr.0urlrrr Usz6SearchScope.get_formatted_locations..zLooking in links: {}css|]}t|VqdSrr r!rrrr$Zs )rrZ simple_urlrformatjoinr )rlinesrrrget_formatted_locationsPsz#SearchScope.get_formatted_locationscs fddfdd|jDS)zReturns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations cs,t|tt}|ds(|d}|S)N/) posixpathr'rZquoterendswith)r#Zloc) project_namerrmkurl_pypi_urlgs  z.mkurl_pypi_urlcsg|] }|qSrrr!)r.rr tsz8SearchScope.get_index_urls_locations..)r)rr-r)r.r-rget_index_urls_locations_s z$SearchScope.get_index_urls_locationsN) __name__ __module__ __qualname____doc__ classmethodrrr)r0rrrrr s  ( r )rZloggingrr+Zpip._vendor.packaging.utilsrZpip._vendor.six.moves.urllibrrZpip._internal.models.indexrZpip._internal.utils.compatrZpip._internal.utils.miscrrZpip._internal.utils.typingrtypingr Z getLoggerr1robjectr rrrrs       models/__pycache__/selection_prefs.cpython-38.opt-1.pyc000064400000003074152347654150017032 0ustar00U .et@s<ddlmZer(ddlmZddlmZGdddeZdS))MYPY_CHECK_RUNNING)Optional) FormatControlc@seZdZdZdddZdS)SelectionPreferenceszd Encapsulates the candidate selection preferences for downloading and installing files. FNcCs.|dkr d}||_||_||_||_||_dS)awCreate a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. NF) allow_yankedallow_all_prereleasesformat_control prefer_binaryignore_requires_python)selfrrrr r r H/usr/lib/python3.8/site-packages/pip/_internal/models/selection_prefs.py__init__szSelectionPreferences.__init__)FNFN)__name__ __module__ __qualname____doc__rr r r r rs  rN)Zpip._internal.utils.typingrtypingrZ#pip._internal.models.format_controlrobjectrr r r r s   models/__pycache__/candidate.cpython-38.opt-1.pyc000064400000002662152347654150015564 0ustar00U .e@s`ddlmZddlmZddlmZerLddlmZddlm Z ddl m Z GdddeZ d S) )parse)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) _BaseVersion)Link)Anycs0eZdZdZfddZddZddZZS)InstallationCandidatez9Represents a potential "candidate" for installation. cs:||_t||_||_tt|j|j|j|jftddS)N)keyZdefining_class)project parse_versionversionlinksuperr__init__)selfr r r  __class__B/usr/lib/python3.8/site-packages/pip/_internal/models/candidate.pyrs  zInstallationCandidate.__init__cCsd|j|j|jS)Nz)formatr r r rrrr__repr__s zInstallationCandidate.__repr__cCsd|j|j|jS)Nz!{!r} candidate (version {} at {})rrrrr__str__$s zInstallationCandidate.__str__)__name__ __module__ __qualname____doc__rrr __classcell__rrrrrs rN) Zpip._vendor.packaging.versionrr Zpip._internal.utils.modelsrZpip._internal.utils.typingrrZpip._internal.models.linkrtypingrrrrrrs      models/__pycache__/selection_prefs.cpython-38.pyc000064400000003074152347654150016073 0ustar00U .et@s<ddlmZer(ddlmZddlmZGdddeZdS))MYPY_CHECK_RUNNING)Optional) FormatControlc@seZdZdZdddZdS)SelectionPreferenceszd Encapsulates the candidate selection preferences for downloading and installing files. FNcCs.|dkr d}||_||_||_||_||_dS)awCreate a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. NF) allow_yankedallow_all_prereleasesformat_control prefer_binaryignore_requires_python)selfrrrr r r H/usr/lib/python3.8/site-packages/pip/_internal/models/selection_prefs.py__init__szSelectionPreferences.__init__)FNFN)__name__ __module__ __qualname____doc__rr r r r rs  rN)Zpip._internal.utils.typingrtypingrZ#pip._internal.models.format_controlrobjectrr r r r s   models/__pycache__/candidate.cpython-38.pyc000064400000002662152347654150014625 0ustar00U .e@s`ddlmZddlmZddlmZerLddlmZddlm Z ddl m Z GdddeZ d S) )parse)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) _BaseVersion)Link)Anycs0eZdZdZfddZddZddZZS)InstallationCandidatez9Represents a potential "candidate" for installation. cs:||_t||_||_tt|j|j|j|jftddS)N)keyZdefining_class)project parse_versionversionlinksuperr__init__)selfr r r  __class__B/usr/lib/python3.8/site-packages/pip/_internal/models/candidate.pyrs  zInstallationCandidate.__init__cCsd|j|j|jS)Nz)formatr r r rrrr__repr__s zInstallationCandidate.__repr__cCsd|j|j|jS)Nz!{!r} candidate (version {} at {})rrrrr__str__$s zInstallationCandidate.__str__)__name__ __module__ __qualname____doc__rrr __classcell__rrrrrs rN) Zpip._vendor.packaging.versionrr Zpip._internal.utils.modelsrZpip._internal.utils.typingrrZpip._internal.models.linkrtypingrrrrrrs      models/__pycache__/link.cpython-38.opt-1.pyc000064400000014617152347654150014610 0ustar00U .e@sddlZddlZddlZddlmZddlmZddlm Z m Z m Z ddl m Z ddlmZddlmZmZerddlmZmZmZmZdd lmZdd lmZGd d d e ZdS) N)parse)WHEEL_EXTENSION)redact_auth_from_urlsplit_auth_from_netlocsplitext)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) path_to_url url_to_path)OptionalTextTupleUnion)HTMLPage)Hashescs@eZdZdZd6fdd ZddZddZed d Zed d Z ed dZ eddZ eddZ eddZ ddZeddZeddZedZeddZedZedd Zed!Zed"d#Zed$d%Zed&d'Zed(d)Zd*d+Zed,d-Zed.d/Zed0d1Zed2d3Z d4d5Z!Z"S)7Linkz?Represents a parsed link from a Package Index's simple URL NcsV|drt|}t||_||_||_|r2|nd|_||_t t |j |t ddS)a` :param url: url of the resource pointed to (href of the link) :param comes_from: instance of HTMLPage where the link was found, or string. :param requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. :param yanked_reason: the reason the file has been yanked, if the file has been yanked, or None if the file hasn't been yanked. This is the value of the "data-yanked" attribute, if present, in a simple repository HTML link. If the file has been yanked but no reason was provided, this should be the empty string. See PEP 592 for more information and the specification. z\\N)keyZdefining_class) startswithr urllib_parseZurlsplit _parsed_url_url comes_fromrequires_python yanked_reasonsuperr__init__)selfurlrrr __class__=/usr/lib/python3.8/site-packages/pip/_internal/models/link.pyrs  z Link.__init__cCsD|jrd|j}nd}|jr2dt|j|j|fStt|jSdS)Nz (requires-python:%s)z%s (from %s)%s)rrrrstr)rZrpr r r!__str__Es  z Link.__str__cCsd|S)Nz r rr r r!__repr__Psz Link.__repr__cCs|jSN)rr%r r r!rSszLink.urlcCs:|jd}t|}|s,t|j\}}|St|}|SN/)pathrstrip posixpathbasenamernetlocrunquote)rr*namer.Z user_passr r r!filenameXs   z Link.filenamecCs t|jSr')r rr%r r r! file_pathgszLink.file_pathcCs|jjSr')rschemer%r r r!r3lsz Link.schemecCs|jjS)z4 This can contain auth information. )rr.r%r r r!r.qsz Link.netloccCst|jjSr')rr/rr*r%r r r!r*ysz Link.pathcCstt|jdSr()rr,r-r*r+r%r r r!r~sz Link.splitextcCs |dSN)rr%r r r!extszLink.extcCs$|j\}}}}}t||||dfSr')rrZ urlunsplit)rr3r.r*ZqueryZfragmentr r r!url_without_fragmentszLink.url_without_fragmentz[#&]egg=([^&]*)cCs |j|j}|sdS|dSr4)_egg_fragment_researchrgrouprmatchr r r! egg_fragmentszLink.egg_fragmentz[#&]subdirectory=([^&]*)cCs |j|j}|sdS|dSr4)_subdirectory_fragment_rer9rr:r;r r r!subdirectory_fragmentszLink.subdirectory_fragmentz2(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)cCs |j|j}|r|dSdS)N_hash_rer9rr:r;r r r!hashs z Link.hashcCs |j|j}|r|dSdSr4rAr;r r r! hash_names zLink.hash_namecCs$t|jddddddS)N#r5r?)r,r-rsplitr%r r r!show_urlsz Link.show_urlcCs |jdkS)Nfile)r3r%r r r!is_filesz Link.is_filecCs|jotj|jSr')rJosr*isdirr2r%r r r!is_existing_dirszLink.is_existing_dircCs |jtkSr')r6rr%r r r!is_wheelsz Link.is_wheelcCsddlm}|j|jkS)Nr)vcs)Zpip._internal.vcsrOr3Z all_schemes)rrOr r r!is_vcss z Link.is_vcscCs |jdk Sr')rr%r r r! is_yankedszLink.is_yankedcCs |jdk Sr')rDr%r r r!has_hashsz Link.has_hashcCs$|dks|jsdS|j|j|jdS)zG Return True if the link has a hash and it is allowed. NF)Z hex_digest)rRis_hash_allowedrDrC)rZhashesr r r!rSszLink.is_hash_allowed)NNN)#__name__ __module__ __qualname____doc__rr$r&propertyrr1r2r3r.r*rr6r7recompiler8r=r>r?rBrCrDrHrJrMrNrPrQrRrS __classcell__r r rr!rsf'                     r)rKr,rYZpip._vendor.six.moves.urllibrrZpip._internal.utils.filetypesrZpip._internal.utils.miscrrrZpip._internal.utils.modelsrZpip._internal.utils.typingrZpip._internal.utils.urlsr r typingr r r rZpip._internal.collectorrZpip._internal.utils.hashesrrr r r r!s      models/__pycache__/format_control.cpython-38.opt-1.pyc000064400000004560152347654150016677 0ustar00U .e @sPddlmZddlmZddlmZers   models/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000340152347654150015376 0ustar00U .e?@sdZdS)z8A package that contains models that represent entities. N)__doc__rrA/usr/lib/python3.8/site-packages/pip/_internal/models/__init__.pymodels/candidate.py000064400000002253152347654150010333 0ustar00from pip._vendor.packaging.version import parse as parse_version from pip._internal.utils.models import KeyBasedCompareMixin from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._vendor.packaging.version import _BaseVersion from pip._internal.models.link import Link class InstallationCandidate(KeyBasedCompareMixin): """Represents a potential "candidate" for installation. """ __slots__ = ["name", "version", "link"] def __init__(self, name, version, link): # type: (str, str, Link) -> None self.name = name self.version = parse_version(version) # type: _BaseVersion self.link = link super(InstallationCandidate, self).__init__( key=(self.name, self.version, self.link), defining_class=InstallationCandidate ) def __repr__(self): # type: () -> str return "".format( self.name, self.version, self.link, ) def __str__(self): # type: () -> str return '{!r} candidate (version {} at {})'.format( self.name, self.version, self.link, ) models/target_python.py000064400000007702152347654150011312 0ustar00import sys from pip._internal.utils.compatibility_tags import ( get_supported, version_info_to_nodot, ) from pip._internal.utils.misc import normalize_version_info from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Tuple from pip._vendor.packaging.tags import Tag class TargetPython(object): """ Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc. """ __slots__ = [ "_given_py_version_info", "abi", "implementation", "platform", "py_version", "py_version_info", "_valid_tags", ] def __init__( self, platform=None, # type: Optional[str] py_version_info=None, # type: Optional[Tuple[int, ...]] abi=None, # type: Optional[str] implementation=None, # type: Optional[str] ): # type: (...) -> None """ :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param py_version_info: An optional tuple of ints representing the Python version information to use (e.g. `sys.version_info[:3]`). This can have length 1, 2, or 3 when provided. :param abi: A string or None. This is passed to compatibility_tags.py's get_supported() function as is. :param implementation: A string or None. This is passed to compatibility_tags.py's get_supported() function as is. """ # Store the given py_version_info for when we call get_supported(). self._given_py_version_info = py_version_info if py_version_info is None: py_version_info = sys.version_info[:3] else: py_version_info = normalize_version_info(py_version_info) py_version = '.'.join(map(str, py_version_info[:2])) self.abi = abi self.implementation = implementation self.platform = platform self.py_version = py_version self.py_version_info = py_version_info # This is used to cache the return value of get_tags(). self._valid_tags = None # type: Optional[List[Tag]] def format_given(self): # type: () -> str """ Format the given, non-None attributes for display. """ display_version = None if self._given_py_version_info is not None: display_version = '.'.join( str(part) for part in self._given_py_version_info ) key_values = [ ('platform', self.platform), ('version_info', display_version), ('abi', self.abi), ('implementation', self.implementation), ] return ' '.join( '{}={!r}'.format(key, value) for key, value in key_values if value is not None ) def get_tags(self): # type: () -> List[Tag] """ Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). """ if self._valid_tags is None: # Pass versions=None if no py_version_info was given since # versions=None uses special default logic. py_version_info = self._given_py_version_info if py_version_info is None: version = None else: version = version_info_to_nodot(py_version_info) tags = get_supported( version=version, platform=self.platform, abi=self.abi, impl=self.implementation, ) self._valid_tags = tags return self._valid_tags models/link.py000064400000016456152347654150007366 0ustar00import os import posixpath import re from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.misc import ( redact_auth_from_url, split_auth_from_netloc, splitext, ) from pip._internal.utils.models import KeyBasedCompareMixin from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path if MYPY_CHECK_RUNNING: from typing import Optional, Text, Tuple, Union from pip._internal.index.collector import HTMLPage from pip._internal.utils.hashes import Hashes class Link(KeyBasedCompareMixin): """Represents a parsed link from a Package Index's simple URL """ __slots__ = [ "_parsed_url", "_url", "comes_from", "requires_python", "yanked_reason", "cache_link_parsing", ] def __init__( self, url, # type: str comes_from=None, # type: Optional[Union[str, HTMLPage]] requires_python=None, # type: Optional[str] yanked_reason=None, # type: Optional[Text] cache_link_parsing=True, # type: bool ): # type: (...) -> None """ :param url: url of the resource pointed to (href of the link) :param comes_from: instance of HTMLPage where the link was found, or string. :param requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. :param yanked_reason: the reason the file has been yanked, if the file has been yanked, or None if the file hasn't been yanked. This is the value of the "data-yanked" attribute, if present, in a simple repository HTML link. If the file has been yanked but no reason was provided, this should be the empty string. See PEP 592 for more information and the specification. :param cache_link_parsing: A flag that is used elsewhere to determine whether resources retrieved from this link should be cached. PyPI index urls should generally have this set to False, for example. """ # url can be a UNC windows share if url.startswith('\\\\'): url = path_to_url(url) self._parsed_url = urllib_parse.urlsplit(url) # Store the url as a private attribute to prevent accidentally # trying to set a new value. self._url = url self.comes_from = comes_from self.requires_python = requires_python if requires_python else None self.yanked_reason = yanked_reason super(Link, self).__init__(key=url, defining_class=Link) self.cache_link_parsing = cache_link_parsing def __str__(self): # type: () -> str if self.requires_python: rp = ' (requires-python:{})'.format(self.requires_python) else: rp = '' if self.comes_from: return '{} (from {}){}'.format( redact_auth_from_url(self._url), self.comes_from, rp) else: return redact_auth_from_url(str(self._url)) def __repr__(self): # type: () -> str return ''.format(self) @property def url(self): # type: () -> str return self._url @property def filename(self): # type: () -> str path = self.path.rstrip('/') name = posixpath.basename(path) if not name: # Make sure we don't leak auth information if the netloc # includes a username and password. netloc, user_pass = split_auth_from_netloc(self.netloc) return netloc name = urllib_parse.unquote(name) assert name, ( 'URL {self._url!r} produced no filename'.format(**locals())) return name @property def file_path(self): # type: () -> str return url_to_path(self.url) @property def scheme(self): # type: () -> str return self._parsed_url.scheme @property def netloc(self): # type: () -> str """ This can contain auth information. """ return self._parsed_url.netloc @property def path(self): # type: () -> str return urllib_parse.unquote(self._parsed_url.path) def splitext(self): # type: () -> Tuple[str, str] return splitext(posixpath.basename(self.path.rstrip('/'))) @property def ext(self): # type: () -> str return self.splitext()[1] @property def url_without_fragment(self): # type: () -> str scheme, netloc, path, query, fragment = self._parsed_url return urllib_parse.urlunsplit((scheme, netloc, path, query, None)) _egg_fragment_re = re.compile(r'[#&]egg=([^&]*)') @property def egg_fragment(self): # type: () -> Optional[str] match = self._egg_fragment_re.search(self._url) if not match: return None return match.group(1) _subdirectory_fragment_re = re.compile(r'[#&]subdirectory=([^&]*)') @property def subdirectory_fragment(self): # type: () -> Optional[str] match = self._subdirectory_fragment_re.search(self._url) if not match: return None return match.group(1) _hash_re = re.compile( r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)' ) @property def hash(self): # type: () -> Optional[str] match = self._hash_re.search(self._url) if match: return match.group(2) return None @property def hash_name(self): # type: () -> Optional[str] match = self._hash_re.search(self._url) if match: return match.group(1) return None @property def show_url(self): # type: () -> str return posixpath.basename(self._url.split('#', 1)[0].split('?', 1)[0]) @property def is_file(self): # type: () -> bool return self.scheme == 'file' def is_existing_dir(self): # type: () -> bool return self.is_file and os.path.isdir(self.file_path) @property def is_wheel(self): # type: () -> bool return self.ext == WHEEL_EXTENSION @property def is_vcs(self): # type: () -> bool from pip._internal.vcs import vcs return self.scheme in vcs.all_schemes @property def is_yanked(self): # type: () -> bool return self.yanked_reason is not None @property def has_hash(self): # type: () -> bool return self.hash_name is not None def is_hash_allowed(self, hashes): # type: (Optional[Hashes]) -> bool """ Return True if the link has a hash and it is allowed. """ if hashes is None or not self.has_hash: return False # Assert non-None so mypy knows self.hash_name and self.hash are str. assert self.hash_name is not None assert self.hash is not None return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) models/selection_prefs.py000064400000003774152347654150011614 0ustar00from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional from pip._internal.models.format_control import FormatControl class SelectionPreferences(object): """ Encapsulates the candidate selection preferences for downloading and installing files. """ __slots__ = ['allow_yanked', 'allow_all_prereleases', 'format_control', 'prefer_binary', 'ignore_requires_python'] # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def __init__( self, allow_yanked, # type: bool allow_all_prereleases=False, # type: bool format_control=None, # type: Optional[FormatControl] prefer_binary=False, # type: bool ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """Create a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. """ if ignore_requires_python is None: ignore_requires_python = False self.allow_yanked = allow_yanked self.allow_all_prereleases = allow_all_prereleases self.format_control = format_control self.prefer_binary = prefer_binary self.ignore_requires_python = ignore_requires_python models/__init__.py000064400000000077152347654150010160 0ustar00"""A package that contains models that represent entities. """ models/search_scope.py000064400000011217152347654150011055 0ustar00import itertools import logging import os import posixpath from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.models.index import PyPI from pip._internal.utils.compat import has_tls from pip._internal.utils.misc import normalize_path, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List logger = logging.getLogger(__name__) class SearchScope(object): """ Encapsulates the locations that pip is configured to search. """ __slots__ = ["find_links", "index_urls"] @classmethod def create( cls, find_links, # type: List[str] index_urls, # type: List[str] ): # type: (...) -> SearchScope """ Create a SearchScope object after normalizing the `find_links`. """ # Build find_links. If an argument starts with ~, it may be # a local file relative to a home directory. So try normalizing # it and if it exists, use the normalized version. # This is deliberately conservative - it might be fine just to # blindly normalize anything starting with a ~... built_find_links = [] # type: List[str] for link in find_links: if link.startswith('~'): new_link = normalize_path(link) if os.path.exists(new_link): link = new_link built_find_links.append(link) # If we don't have TLS enabled, then WARN if anyplace we're looking # relies on TLS. if not has_tls(): for link in itertools.chain(index_urls, built_find_links): parsed = urllib_parse.urlparse(link) if parsed.scheme == 'https': logger.warning( 'pip is configured with locations that require ' 'TLS/SSL, however the ssl module in Python is not ' 'available.' ) break return cls( find_links=built_find_links, index_urls=index_urls, ) def __init__( self, find_links, # type: List[str] index_urls, # type: List[str] ): # type: (...) -> None self.find_links = find_links self.index_urls = index_urls def get_formatted_locations(self): # type: () -> str lines = [] redacted_index_urls = [] if self.index_urls and self.index_urls != [PyPI.simple_url]: for url in self.index_urls: redacted_index_url = redact_auth_from_url(url) # Parse the URL purl = urllib_parse.urlsplit(redacted_index_url) # URL is generally invalid if scheme and netloc is missing # there are issues with Python and URL parsing, so this test # is a bit crude. See bpo-20271, bpo-23505. Python doesn't # always parse invalid URLs correctly - it should raise # exceptions for malformed URLs if not purl.scheme and not purl.netloc: logger.warning( 'The index url "%s" seems invalid, ' 'please provide a scheme.', redacted_index_url) redacted_index_urls.append(redacted_index_url) lines.append('Looking in indexes: {}'.format( ', '.join(redacted_index_urls))) if self.find_links: lines.append( 'Looking in links: {}'.format(', '.join( redact_auth_from_url(url) for url in self.find_links)) ) return '\n'.join(lines) def get_index_urls_locations(self, project_name): # type: (str) -> List[str] """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): # type: (str) -> str loc = posixpath.join( url, urllib_parse.quote(canonicalize_name(project_name))) # For maximum compatibility with easy_install, ensure the path # ends in a trailing slash. Although this isn't in the spec # (and PyPI can handle it without the slash) some other index # implementations might break if they relied on easy_install's # behavior. if not loc.endswith('/'): loc = loc + '/' return loc return [mkurl_pypi_url(url) for url in self.index_urls] vcs/__pycache__/bazaar.cpython-38.opt-1.pyc000064400000007243152347654150014420 0ustar00U .eu@sddlmZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z ddlmZddlmZmZe rdd lmZmZdd lmZdd lmZmZeeZGd d d eZeedS))absolute_importN)parse) display_pathrmtree) make_command)MYPY_CHECK_RUNNING) path_to_url)VersionControlvcs)OptionalTuple) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZfddZeddZ d d Z d d Z d dZ ddZ efddZeddZeddZeddZZS)Bazaarbzrz.bzrbranch)rzbzr+httpz bzr+httpszbzr+sshzbzr+sftpzbzr+ftpzbzr+lpcs0tt|j||ttddr,tjdgdS)N uses_fragmentZlp)superr__init__getattr urllib_parserextend)selfargskwargs __class__|}td||t|tdd|||}||dS)NzChecking out %s%s to %sr-q)Z to_displayloggerinforrr(r')rdestr*r+Z rev_displaycmd_argsrrr fetch_new=szBazaar.fetch_newcCs|jtd||ddS)Nswitchcwd)r'r)rr/r*r+rrrr2Ksz Bazaar.switchcCs"tdd|}|j||ddS)NZpullr,r3)rr(r')rr/r*r+r0rrrupdateOsz Bazaar.updatecs2tt||\}}}|dr(d|}|||fS)Nzssh://zbzr+)rrget_url_rev_and_auth startswith)clsr*r Z user_passrrrr6Ts zBazaar.get_url_rev_and_authcCst|jdgd|d}|D]T}|}dD]B}||r*||d}||r`t|S|Sq*qdS)Nr.Fr#r4)zcheckout of branch: zparent branch: )r' splitlinesstripr7splitZ_is_local_repositoryr)r8r)ZurlslinexZreporrrget_remote_url]s   zBazaar.get_remote_urlcCs|jdgd|d}|dS)NZrevnoFr9)r'r;)r8r)Zrevisionrrr get_revisionks zBazaar.get_revisioncCsdS)z&Always assume the versions don't matchFr)r8r/namerrris_commit_id_equalrszBazaar.is_commit_id_equal)__name__ __module__ __qualname__rCdirnameZ repo_nameZschemesr staticmethodr!r"r1r2r5 classmethodr6r@rBrD __classcell__rrrrrs&    r)Z __future__rZloggingr$Zpip._vendor.six.moves.urllibrrZpip._internal.utils.miscrrZpip._internal.utils.subprocessrZpip._internal.utils.typingrZpip._internal.utils.urlsrZ pip._internal.vcs.versioncontrolr r typingr r r rrZ getLoggerrEr-rregisterrrrrs       ^vcs/__pycache__/subversion.cpython-38.pyc000064400000020447152347654150014421 0ustar00U .e0@sddlmZddlZddlZddlZddlmZddlmZm Z m Z m Z ddl m Z ddlmZddlmZmZedZed Zed Zed Zerdd lmZmZdd l mZddlmZddlmZmZee Z!GdddeZ"e#e"dS))absolute_importN) indent_log) display_pathis_console_interactivermtreesplit_auth_from_netloc) make_command)MYPY_CHECK_RUNNING)VersionControlvcsz url="([^"]+)"zcommitted-rev="(\d+)"z\s*revision="(\d+)"z(.*))OptionalTuple) CommandArgs) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZeddZe ddZ ed d Z efd d Z efd dZ e ddZeddZeddZeddZd(fdd ZddZddZddZd d!Zd"d#Zd$d%Zd&d'ZZS)) Subversionsvnz.svncheckout)rzsvn+sshzsvn+httpz svn+httpszsvn+svncCsdS)NT)clsZ remote_urlrr@/usr/lib/python3.8/site-packages/pip/_internal/vcs/subversion.pyshould_add_vcs_url_prefix+sz$Subversion.should_add_vcs_url_prefixcCsd|gS)Nz-rr)revrrrget_base_rev_args/szSubversion.get_base_rev_argsc Csd}t|D]\}}}|j|kr0g|dd<q||jtj||jd}tj|s\q||\}}||kr||d}n|r||sg|dd<qt ||}q|S)zR Return the maximum revision for all files under a given location rNentries/) oswalkdirnameremovepathjoinexists_get_svn_url_rev startswithmax) rlocationZrevisionbasedirsfilesZ entries_fnZdirurlZlocalrevrrr get_revision3s"       zSubversion.get_revisioncs"|dkrtt|||St|S)z This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. Zssh)superrget_netloc_and_authr)rZnetlocZscheme __class__rrr-OszSubversion.get_netloc_and_authcs2tt||\}}}|dr(d|}|||fS)Nzssh://zsvn+)r,rget_url_rev_and_authr%)rurlrZ user_passr.rrr0\s zSubversion.get_url_rev_and_authcCs(g}|r|d|g7}|r$|d|g7}|S)Nz --usernamez --passwordr)ZusernameZpasswordZ extra_argsrrr make_rev_argses   zSubversion.make_rev_argscCsR|}tjtj|dsD|}tj|}||krtd|dSq||dS)Nzsetup.pyzGCould not find setup.py for directory %s (tried all parent directories)r)rr!r#r"rloggerZwarningr$)rr'Z orig_locationZ last_locationrrrget_remote_urlps zSubversion.get_remote_urlc Cspddlm}tj||jd}tj|rHt|}|}W5QRXnd}| dsj| dsj| drt t t j |d}|dd=|dd }d d |Ddg}n| d rt|}|std ||d}dd t|Ddg}n^z<|jdd|gdd} t| d}dd t| D}Wn |k rRdg}}YnX|rdt|} nd} || fS)Nr)InstallationErrorr89Z10z cSs,g|]$}t|dkr|drt|dqS) )lenint).0drrr s z/Subversion._get_svn_url_rev..zs,           *vcs/__pycache__/git.cpython-38.pyc000064400000022005152347654150012775 0ustar00U .e5@sddlmZddlZddlZddlZddlmZddl mZ ddl m Z ddl mZddlmZddlmZddlmZdd lmZdd lmZmZmZmZerdd lmZmZdd lmZdd lm Z m!Z!e j"Z"e j#Z#e$e%Z&e'dZ(ddZ)GdddeZ*e+e*dS))absolute_importN)parse)request) BadCommand) display_path) make_command) TempDirectory)MYPY_CHECK_RUNNING)RemoteNotFoundErrorVersionControl!find_path_to_setup_from_repo_rootvcs)OptionalTuple) HiddenText)AuthInfo RevOptionsz^[a-fA-F0-9]{40}$cCstt|SN)bool HASH_REGEXmatch)shar9/usr/lib/python3.8/site-packages/pip/_internal/vcs/git.pylooks_like_hash*srcseZdZdZdZdZdZdZdZe ddZ d d Z e d d Z d dZe ddZe ddZe ddZddZddZddZe ddZe d(ddZe d d!Ze fd"d#Ze d$d%Ze fd&d'ZZS))Gitgitz.gitclone)rzgit+httpz git+httpszgit+sshzgit+gitzgit+file)ZGIT_DIRZ GIT_WORK_TREEHEADcCs|gSrrrevrrrget_base_rev_args:szGit.get_base_rev_argscCs\d}|jdgdd}||r8|t|dd}nd}d|ddd}t|S) Nz git version versionF) show_stdoutr.) run_command startswithlensplitjoin parse_version)selfZ VERSION_PFXr"rrrget_git_version>s zGit.get_git_versioncCsBdddg}|j|dd|d}|}|dr>|tddSdS) zl Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). z symbolic-ref-qrFZextra_ok_returncodesr#cwdz refs/heads/N)r'stripr(r))clslocationargsoutputrefrrrget_current_branchKs  zGit.get_current_branchc CsX|ds|d}tdd2}|j|j|d|jdddd|gd |jd W5QRXd S) z@Export the Git repository at the url to the destination location/export)Zkind)urlzcheckout-indexz-az-fz--prefixFr#r3N)endswithrunpackpathr')r-r6r=Ztemp_dirrrrr<`s   z Git.exportc Cs|jd|g|ddd}i}|dD]V}|d}|s)r'r4)r5r6r Z current_revrrrrV%szGit.get_revisioncCsR|jddgd|d}tj|s2tj||}tjtj|d}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. rjz --git-dirFr>z..)r'r4osrAisabsr+abspathr )r5r6Zgit_dirZ repo_rootrrrget_subdirectory.s  zGit.get_subdirectoryc st|\}}}}}|dr|dt|d }|t|ddd}t|||||f}|dd} |d| t|| d||||f}d|krd|kst |d d }t t | |\}} } |d d }nt t | |\}} } || | fS) a9 Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. fileNr;\+r1z://zfile:zgit+z git+ssh://zssh://r$) urlsplitr?r)lstripurllib_requestZ url2pathnamereplace urlunsplitfindrRsuperrget_url_rev_and_auth) r5r=ZschemeZnetlocrAZqueryZfragmentinitial_slashesnewpathZ after_plusr Z user_pass __class__rrry=s0      zGit.get_url_rev_and_authcCs6tjtj|dsdS|jdddddg|ddS)Nz .gitmodulesZ submodulerez--initz --recursiver/rQ)rkrAexistsr+r')r5r6rrrr^`s  zGit.update_submodulescsZtt||rdSz|jdg|dddd}| WStk rTtd|YdSXdS)NTrjFrB)r3r#rCZlog_failed_cmdzKcould not determine if %s is under git control because git is not available)rxrcontrols_locationr'rrTdebug)r5r6rr|rrriszGit.controls_location)N)__name__ __module__ __qualname__rYdirnameZ repo_nameZschemesZ unset_environZdefault_arg_rev staticmethodr!r. classmethodr:r<rOrXrZr`rcrerirVrnryr^r __classcell__rrr|rr.sB     ( ,     " r),Z __future__rZloggingZos.pathrkreZpip._vendor.packaging.versionrr,Zpip._vendor.six.moves.urllibZ urllib_parserrtZpip._internal.exceptionsrZpip._internal.utils.miscrZpip._internal.utils.subprocessrZpip._internal.utils.temp_dirrZpip._internal.utils.typingr Z pip._internal.vcs.versioncontrolr r r r typingrrrrrrrrvZ getLoggerrrTcompilerrrregisterrrrrs2            Nvcs/__pycache__/__init__.cpython-38.pyc000064400000000700152347654150013747 0ustar00U .ei@s<ddlZddlZddlZddlZddlmZmZmZm Z dS)N)RemoteNotFoundErroris_urlmake_vcs_requirement_urlvcs) Zpip._internal.vcs.bazaarZpipZpip._internal.vcs.gitZpip._internal.vcs.mercurialZpip._internal.vcs.subversionZ pip._internal.vcs.versioncontrolrrrrrr>/usr/lib/python3.8/site-packages/pip/_internal/vcs/__init__.pysvcs/__pycache__/versioncontrol.cpython-38.opt-1.pyc000064400000044035152347654150016246 0ustar00U .e~S@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZddlmZddlmZmZmZmZmZmZdd lmZmZdd lmZdd lmZerdd lm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+ddlm,Z,ddlm-Z-e'e%e.e%e.fZ/dgZ0e1e2Z3ddZ4dddZ5ddZ6Gddde7Z8Gddde9Z:Gddde9Z;e;Z)r&r=r!r(r>r#r#r$__repr__szRevOptions.__repr__cCs|jdkr|jjS|jSN)r(r=default_arg_revr@r#r#r$arg_revs zRevOptions.arg_revcCs0g}|j}|dk r"||j|7}||j7}|S)z< Return the VCS-specific command arguments. N)rDr=get_base_rev_argsr<)r>argsr(r#r#r$to_argss  zRevOptions.to_argscCs|js dSd|jS)Nz (to revision {}))r(r&r@r#r#r$ to_displayszRevOptions.to_displaycCs|jj||jdS)z Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. r<)r=make_rev_optionsr<)r>r(r#r#r$make_newszRevOptions.make_new)NN) r8r9r:__doc__r?rApropertyrDrGrIrLr#r#r#r$r;js    r;cs|eZdZiZddddddgZfddZd d Zed d Zed dZ eddZ ddZ ddZ ddZ ddZZS) VcsSupportZsshZgitZhgZbzrZsftpZsvncs:tj|jttddr(tj|jtt|dS)N uses_fragment) urllib_parseZ uses_netlocextendschemesgetattrrPsuperrOr?r@ __class__r#r$r?s zVcsSupport.__init__cCs |jSrB) _registry__iter__r@r#r#r$rYszVcsSupport.__iter__cCst|jSrB)listrXvaluesr@r#r#r$backendsszVcsSupport.backendscCsdd|jDS)NcSsg|] }|jqSr#)r1).0backendr#r#r$ sz'VcsSupport.dirnames..)r\r@r#r#r$dirnamesszVcsSupport.dirnamescCs g}|jD]}||jq |SrB)r\rRrS)r>rSr^r#r#r$r s zVcsSupport.all_schemescCsHt|dstd|jdS|j|jkrD||j|j<td|jdS)Nr!zCannot register VCS %szRegistered VCS backend: %s)hasattrr2r3r8r!rXdebug)r>clsr#r#r$registers   zVcsSupport.registercCs||jkr|j|=dSrB)rXr>r!r#r#r$ unregisters zVcsSupport.unregistercCs6|jD]&}||r td||j|Sq dS)zv Return a VersionControl object if a repository of that type is found at the given directory. zDetermine that %s uses VCS: %sN)rXr[controls_locationr2rbr!)r>r5Z vcs_backendr#r#r$get_backend_for_dirs  zVcsSupport.get_backend_for_dircCs|}|j|S)z9 Return a VersionControl object or None. )lowerrXgetrer#r#r$ get_backendszVcsSupport.get_backend)r8r9r:rXrSr?rYrNr\r`r rdrfrhrk __classcell__r#r#rVr$rOs      rOc @s8eZdZdZdZdZdZdZdZe ddZ e ddZ e dd Z e d d Z ed d Ze d8ddZe ddZddZe ddZe ddZeddZddZeddZe ddZd d!Zd"d#Zd$d%Ze d&d'Zd(d)Zd*d+Ze d,d-Ze d.d/Z e d9d2d3Z!e d4d5Z"e d6d7Z#dS):VersionControlrHr#NcCs|d|j S)z Return whether the vcs prefix (e.g. "git+") should be added to a repository's remote url when used in a requirement. z{}:)ri startswithr&r!)rcZ remote_urlr#r#r$should_add_vcs_url_prefixsz(VersionControl.should_add_vcs_url_prefixcCsdS)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. Nr#rcr5r#r#r$get_subdirectoryszVersionControl.get_subdirectorycCs ||S)zR Return the revision string that should be used in a requirement. ) get_revision)rcrepo_dirr#r#r$get_requirement_revisionsz'VersionControl.get_requirement_revisioncCsV||}|dkrdS||r.d|j|}||}||}t||||d}|S)aC Return the requirement string to use to redownload the files currently at the given repository directory. Args: project_name: the (unescaped) project name. The return value has a form similar to the following: {repository_url}@{revision}#egg={project_name} Nz{}+{})r*)get_remote_urlror&r!rtrqr,)rcrsr)r'Zrevisionr*r+r#r#r$get_src_requirements    z"VersionControl.get_src_requirementcCstdS)z Return the base revision arguments for a vcs command. Args: rev: the name of a revision to install. Cannot be None. NNotImplementedError)r(r#r#r$rE8sz VersionControl.get_base_rev_argscCst|||dS)z Return a RevOptions object. Args: rev: the name of a revision to install. extra_args: a list of extra options. rJ)r;)rcr(r<r#r#r$rKBs zVersionControl.make_rev_optionscCs&tj|\}}|tjjp$t|S)zy posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\folder) )r-r. splitdrivernsepbool)rcZrepoZdrivetailr#r#r$_is_local_repositoryNsz#VersionControl._is_local_repositorycCstdS)z Export the repository at the url to the destination location i.e. only download the files, without vcs informations :param url: the repository URL starting with a vcs prefix. Nrwr>r5urlr#r#r$exportXszVersionControl.exportcCs|dfS)aZ Parse the repository URL's netloc, and return the new netloc to use along with auth information. Args: netloc: the original repository URL netloc. scheme: the repository URL's scheme without the vcs prefix. This is mainly for the Subversion class to override, so that auth information can be provided via the --username and --password options instead of through the URL. For other subclasses like Git without such an option, auth information must stay in the URL. Returns: (netloc, (username, password)). )NNr#)rcnetlocr"r#r#r$get_netloc_and_authbsz"VersionControl.get_netloc_and_authc Cst|\}}}}}d|kr*td||ddd}|||\}}d}d|krf|dd\}}t||||df}|||fS)z Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). +zvSorry, {!r} is a malformed VCS url. The format is +://, e.g. svn+http://myrepo/svn/MyApp#egg=MyAppN@rH)rQZurlsplit ValueErrorr&splitrrsplitZ urlunsplit) rcrr"rr.ZqueryZfrag user_passr(r#r#r$get_url_rev_and_authus z#VersionControl.get_url_rev_and_authcCsgS)zM Return the RevOptions "extra arguments" to use in obtain(). r#)usernamepasswordr#r#r$ make_rev_argsszVersionControl.make_rev_argsc CsT||j\}}}|\}}d}|dk r.t|}|||}|j||d} t|| fS)z Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). NrJ)rsecretr rrKr ) r>rZ secret_urlr(rrZsecret_passwordrr< rev_optionsr#r#r$get_url_rev_optionss z"VersionControl.get_url_rev_optionscCst|dS)zi Normalize a URL for comparison by unquoting it and removing any trailing slash. /)rQZunquoterstriprr#r#r$ normalize_urlszVersionControl.normalize_urlcCs||||kS)zV Compare two repo URLs for identity, ignoring incidental differences. )r)rcZurl1Zurl2r#r#r$ compare_urlsszVersionControl.compare_urlscCstdS)z Fetch a revision from a repository, in the case that this is the first fetch from the repository. Args: dest: the directory to fetch the repository to. rev_options: a RevOptions object. Nrwr>destrrr#r#r$ fetch_news zVersionControl.fetch_newcCstdS)z} Switch the repo at ``dest`` to point to ``URL``. Args: rev_options: a RevOptions object. Nrwrr#r#r$switchszVersionControl.switchcCstdS)z Update an already-existing repo to the given ``rev_options``. Args: rev_options: a RevOptions object. Nrwrr#r#r$updateszVersionControl.updatecCstdS)z Return whether the id of the current commit equals the given name. Args: dest: the repository directory. name: a string name. Nrw)rcrr!r#r#r$is_commit_id_equals z!VersionControl.is_commit_id_equalc Cs||\}}tj|s,||||dS|}||r||}|||j rt d|j t|||||jst dt||j |||||n t ddSt d|j|j t||d}nt d||j|j d}t d |j|td |d |d }|d kr$td|dkrXt dt|t|||||dS|dkrt|}t dt||t||||||dS|dkrt d|j t|||||||dS)a Install or update in editable mode the package represented by this VersionControl object. :param dest: the repository directory in which to install or update. :param url: the repository URL starting with a vcs prefix. Nz)%s in %s exists, and has correct URL (%s)zUpdating %s %s%sz$Skipping because already up-to-date.z%s %s in %s exists with URL %s)z%(s)witch, (i)gnore, (w)ipe, (b)ackup )siwbz0Directory %s already exists, and is not a %s %s.)z(i)gnore, (w)ipe, (b)ackup )rrrz+The plan is to install the %s repository %szWhat to do? %srrarz Deleting %srzBacking up %s to %srzSwitching %s %s to %s%s)rr-r.r/rrIis_repository_directoryrurrr2rb repo_nametitler rr(inforr3r!rsysexitr rshutilZmover) r>rrrZ rev_displayZ existing_urlpromptZresponseZdest_dirr#r#r$obtains           zVersionControl.obtaincCs&tj|rt||j||ddS)z Clean up current location and download the url repository (and vcs infos) into location :param url: the repository URL starting with a vcs prefix. rN)r-r.r/r rr~r#r#r$unpack?s zVersionControl.unpackcCstdS)z Return the url used at location Raises RemoteNotFoundError if the repository does not have a remote url configured. Nrwrpr#r#r$ruKszVersionControl.get_remote_urlcCstdS)zR Return the current commit id of the files at the given location. Nrwrpr#r#r$rrUszVersionControl.get_revisionTraisec Cs|t|jf|}z t||||||||j|| d WStk rv} z(| jtjkrdtd|j|jfnW5d} ~ XYnXdS)z Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available ) on_returncodeextra_ok_returncodes command_desc extra_environ unset_environspinnerlog_failed_cmdzCCannot find command %r - do you have %r installed and in your PATH?N)rr!r rOSErrorerrnoZENOENTr) rccmdZ show_stdoutcwdrrrrrrer#r#r$ run_command\s&  zVersionControl.run_commandcCs,td||j|jtjtj||jS)zL Return whether a directory path is a repository directory. zChecking in %s for %s (%s)...)r2rbr1r!r-r.r/r0)rcr.r#r#r$rs z&VersionControl.is_repository_directorycCs ||S)a6 Check if a location is controlled by the vcs. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. This can do more than is_repository_directory() alone. For example, the Git override checks that Git is actually available. )rrpr#r#r$rgs z VersionControl.controls_location)NN)TNrNNNNT)$r8r9r:r!r1rrSrrC classmethodrorqrtrv staticmethodrErKr}rrrrrrrrrrrrrrurrrrrgr#r#r#r$rmsr                 ]    ' rm)N)>rMZ __future__rrZloggingr-rrZ pip._vendorrZpip._vendor.six.moves.urllibrrQZpip._internal.exceptionsrZpip._internal.utils.compatrZpip._internal.utils.miscrrr r r r Zpip._internal.utils.subprocessr rZpip._internal.utils.typingrZpip._internal.utils.urlsrtypingrrrrrrrrrrZpip._internal.utils.uirrrstrZAuthInfo__all__Z getLoggerr8r2r%r,r6 Exceptionr7objectr;rOrrmr#r#r#r$s<        0     HGvcs/__pycache__/git.cpython-38.opt-1.pyc000064400000021715152347654150013743 0ustar00U .e5@sddlmZddlZddlZddlZddlmZddl mZ ddl m Z ddl mZddlmZddlmZddlmZdd lmZdd lmZmZmZmZerdd lmZmZdd lmZdd lm Z m!Z!e j"Z"e j#Z#e$e%Z&e'dZ(ddZ)GdddeZ*e+e*dS))absolute_importN)parse)request) BadCommand) display_path) make_command) TempDirectory)MYPY_CHECK_RUNNING)RemoteNotFoundErrorVersionControl!find_path_to_setup_from_repo_rootvcs)OptionalTuple) HiddenText)AuthInfo RevOptionsz^[a-fA-F0-9]{40}$cCstt|SN)bool HASH_REGEXmatch)shar9/usr/lib/python3.8/site-packages/pip/_internal/vcs/git.pylooks_like_hash*srcseZdZdZdZdZdZdZdZe ddZ d d Z e d d Z d dZe ddZe ddZe ddZddZddZddZe ddZe d(ddZe d d!Ze fd"d#Ze d$d%Ze fd&d'ZZS))Gitgitz.gitclone)rzgit+httpz git+httpszgit+sshzgit+gitzgit+file)ZGIT_DIRZ GIT_WORK_TREEHEADcCs|gSrrrevrrrget_base_rev_args:szGit.get_base_rev_argscCs\d}|jdgdd}||r8|t|dd}nd}d|ddd}t|S) Nz git version versionF) show_stdoutr.) run_command startswithlensplitjoin parse_version)selfZ VERSION_PFXr"rrrget_git_version>s zGit.get_git_versioncCsBdddg}|j|dd|d}|}|dr>|tddSdS) zl Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). z symbolic-ref-qrFZextra_ok_returncodesr#cwdz refs/heads/N)r'stripr(r))clslocationargsoutputrefrrrget_current_branchKs  zGit.get_current_branchc CsX|ds|d}tdd2}|j|j|d|jdddd|gd |jd W5QRXd S) z@Export the Git repository at the url to the destination location/export)Zkind)urlzcheckout-indexz-az-fz--prefixFr#r3N)endswithrunpackpathr')r-r6r=Ztemp_dirrrrr<`s   z Git.exportc Cs|jd|g|ddd}i}|dD]V}|d}|s)r'r4)r5r6r Z current_revrrrrU%szGit.get_revisioncCsR|jddgd|d}tj|s2tj||}tjtj|d}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. riz --git-dirFr>z..)r'r4osrAisabsr+abspathr )r5r6Zgit_dirZ repo_rootrrrget_subdirectory.s  zGit.get_subdirectoryc st|\}}}}}|dr|dt|d }|t|ddd}t|||||f}|dd} |d| t|| d||||f}d|kr|dd }t t | |\}} } |d d }nt t | |\}} } || | fS) a9 Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. fileNr;\+r1z://zgit+z git+ssh://zssh://r$) urlsplitr?r)lstripurllib_requestZ url2pathnamereplace urlunsplitfindsuperrget_url_rev_and_auth) r5r=ZschemeZnetlocrAZqueryZfragmentinitial_slashesnewpathZ after_plusr Z user_pass __class__rrrx=s.     zGit.get_url_rev_and_authcCs6tjtj|dsdS|jdddddg|ddS)Nz .gitmodulesZ submodulerdz--initz --recursiver/rQ)rjrAexistsr+r')r5r6rrrr]`s  zGit.update_submodulescsZtt||rdSz|jdg|dddd}| WStk rTtd|YdSXdS)NTriFrB)r3r#rCZlog_failed_cmdzKcould not determine if %s is under git control because git is not available)rwrcontrols_locationr'rrSdebug)r5r6rr{rrr~iszGit.controls_location)N)__name__ __module__ __qualname__rXdirnameZ repo_nameZschemesZ unset_environZdefault_arg_rev staticmethodr!r. classmethodr:r<rOrWrYr_rbrdrhrUrmrxr]r~ __classcell__rrr{rr.sB     ( ,     " r),Z __future__rZloggingZos.pathrjreZpip._vendor.packaging.versionrr,Zpip._vendor.six.moves.urllibZ urllib_parserrsZpip._internal.exceptionsrZpip._internal.utils.miscrZpip._internal.utils.subprocessrZpip._internal.utils.temp_dirrZpip._internal.utils.typingr Z pip._internal.vcs.versioncontrolr r r r typingrrrrrrqruZ getLoggerrrScompilerrrregisterrrrrs2            Nvcs/__pycache__/subversion.cpython-38.opt-1.pyc000064400000020447152347654150015360 0ustar00U .e0@sddlmZddlZddlZddlZddlmZddlmZm Z m Z m Z ddl m Z ddlmZddlmZmZedZed Zed Zed Zerdd lmZmZdd l mZddlmZddlmZmZee Z!GdddeZ"e#e"dS))absolute_importN) indent_log) display_pathis_console_interactivermtreesplit_auth_from_netloc) make_command)MYPY_CHECK_RUNNING)VersionControlvcsz url="([^"]+)"zcommitted-rev="(\d+)"z\s*revision="(\d+)"z(.*))OptionalTuple) CommandArgs) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZeddZe ddZ ed d Z efd d Z efd dZ e ddZeddZeddZeddZd(fdd ZddZddZddZd d!Zd"d#Zd$d%Zd&d'ZZS)) Subversionsvnz.svncheckout)rzsvn+sshzsvn+httpz svn+httpszsvn+svncCsdS)NT)clsZ remote_urlrr@/usr/lib/python3.8/site-packages/pip/_internal/vcs/subversion.pyshould_add_vcs_url_prefix+sz$Subversion.should_add_vcs_url_prefixcCsd|gS)Nz-rr)revrrrget_base_rev_args/szSubversion.get_base_rev_argsc Csd}t|D]\}}}|j|kr0g|dd<q||jtj||jd}tj|s\q||\}}||kr||d}n|r||sg|dd<qt ||}q|S)zR Return the maximum revision for all files under a given location rNentries/) oswalkdirnameremovepathjoinexists_get_svn_url_rev startswithmax) rlocationZrevisionbasedirsfilesZ entries_fnZdirurlZlocalrevrrr get_revision3s"       zSubversion.get_revisioncs"|dkrtt|||St|S)z This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. Zssh)superrget_netloc_and_authr)rZnetlocZscheme __class__rrr-OszSubversion.get_netloc_and_authcs2tt||\}}}|dr(d|}|||fS)Nzssh://zsvn+)r,rget_url_rev_and_authr%)rurlrZ user_passr.rrr0\s zSubversion.get_url_rev_and_authcCs(g}|r|d|g7}|r$|d|g7}|S)Nz --usernamez --passwordr)ZusernameZpasswordZ extra_argsrrr make_rev_argses   zSubversion.make_rev_argscCsR|}tjtj|dsD|}tj|}||krtd|dSq||dS)Nzsetup.pyzGCould not find setup.py for directory %s (tried all parent directories)r)rr!r#r"rloggerZwarningr$)rr'Z orig_locationZ last_locationrrrget_remote_urlps zSubversion.get_remote_urlc Cspddlm}tj||jd}tj|rHt|}|}W5QRXnd}| dsj| dsj| drt t t j |d}|dd=|dd }d d |Ddg}n| d rt|}|std ||d}dd t|Ddg}n^z<|jdd|gdd} t| d}dd t| D}Wn |k rRdg}}YnX|rdt|} nd} || fS)Nr)InstallationErrorr89Z10z cSs,g|]$}t|dkr|drt|dqS) )lenint).0drrr s z/Subversion._get_svn_url_rev..zs,           *vcs/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000700152347654150014706 0ustar00U .ei@s<ddlZddlZddlZddlZddlmZmZmZm Z dS)N)RemoteNotFoundErroris_urlmake_vcs_requirement_urlvcs) Zpip._internal.vcs.bazaarZpipZpip._internal.vcs.gitZpip._internal.vcs.mercurialZpip._internal.vcs.subversionZ pip._internal.vcs.versioncontrolrrrrrr>/usr/lib/python3.8/site-packages/pip/_internal/vcs/__init__.pysvcs/__pycache__/mercurial.cpython-38.opt-1.pyc000064400000011430152347654150015134 0ustar00U .e@sddlmZddlZddlZddlmZddlmZmZddl m Z ddl m Z ddl mZddlmZdd lmZdd lmZmZmZerdd l mZdd lmZeeZGd ddeZeedS))absolute_importN) configparser) BadCommandInstallationError) display_path) make_command) TempDirectory)MYPY_CHECK_RUNNING) path_to_url)VersionControl!find_path_to_setup_from_repo_rootvcs) HiddenText) RevOptionscseZdZdZdZdZdZeddZddZ d d Z d d Z d dZ e ddZe ddZe ddZe ddZe ddZe fddZZS) Mercurialhgz.hgclone)rzhg+filezhg+httpzhg+httpszhg+sshzhg+static-httpcCs|gS)N)Zrevrr?/usr/lib/python3.8/site-packages/pip/_internal/vcs/mercurial.pyget_base_rev_args'szMercurial.get_base_rev_argsc Cs@tdd,}|j|j|d|jd|gd|jdW5QRXdS)z?Export the Hg repository at the url to the destination locationexport)Zkind)urlarchiveF show_stdoutcwdN)runpackpath run_command)selflocationrZtemp_dirrrrr+s zMercurial.exportcCsP|}td||t||tddd|||jtdd||ddS)NzCloning hg %s%s to %srz --noupdate-qupdater)Z to_displayloggerinforrrto_args)rdestr rev_optionsZ rev_displayrrr fetch_new5szMercurial.fetch_newc Cstj||jd}t}z>|||dd|jt |d}| |W5QRXWn6t tj fk r}zt d||W5d}~XYn Xtdd|}|j||ddS) NZhgrcpathsdefaultwz/Could not switch Mercurial repository to %s: %sr"r!r#)osrjoindirnamerZRawConfigParserreadsetZsecretopenwriteOSErrorZNoSectionErrorr$Zwarningrr&r) rr'rr(Z repo_configZconfigZ config_fileexccmd_argsrrrswitchDs  zMercurial.switchcCs4|jddg|dtdd|}|j||ddS)NZpullr!r#r")rrr&)rr'rr(r6rrrr"UszMercurial.updatecCs2|jddgd|d}||r*t|}|S)NZ showconfigz paths.defaultFr)rstripZ_is_local_repositoryr )clsr rrrrget_remote_url[s  zMercurial.get_remote_urlcCs|jddgd|d}|S)zW Return the repository-local changeset revision number, as an integer. parentsz--template={rev}Frrr8)r9r Zcurrent_revisionrrr get_revisionds  zMercurial.get_revisioncCs|jddgd|d}|S)zh Return the changeset identification hash, as a 40-character hexadecimal string r;z--template={node}Frr<)r9r Zcurrent_rev_hashrrrget_requirement_revisionns  z"Mercurial.get_requirement_revisioncCsdS)z&Always assume the versions don't matchFr)r9r'namerrris_commit_id_equalyszMercurial.is_commit_id_equalcCsB|jdgd|d}tj|s8tjtj||}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. rootFr)rr8r-risabsabspathr.r )r9r Z repo_rootrrrget_subdirectory~s  zMercurial.get_subdirectoryc sPtt||rdSz|jdg|ddddWdSttfk rJYdSXdS)NTZidentifyFraise)rrZ on_returncodeZlog_failed_cmd)superrcontrols_locationrrr)r9r  __class__rrrGszMercurial.controls_location)__name__ __module__ __qualname__r?r/Z repo_nameZschemes staticmethodrrr)r7r" classmethodr:r=r>r@rDrG __classcell__rrrHrrs,       r)Z __future__rZloggingr-Zpip._vendor.six.movesrZpip._internal.exceptionsrrZpip._internal.utils.miscrZpip._internal.utils.subprocessrZpip._internal.utils.temp_dirrZpip._internal.utils.typingr Zpip._internal.utils.urlsr Z pip._internal.vcs.versioncontrolr r r rrZ getLoggerrJr$rregisterrrrrs          |vcs/__pycache__/mercurial.cpython-38.pyc000064400000011430152347654150014175 0ustar00U .e@sddlmZddlZddlZddlmZddlmZmZddl m Z ddl m Z ddl mZddlmZdd lmZdd lmZmZmZerdd l mZdd lmZeeZGd ddeZeedS))absolute_importN) configparser) BadCommandInstallationError) display_path) make_command) TempDirectory)MYPY_CHECK_RUNNING) path_to_url)VersionControl!find_path_to_setup_from_repo_rootvcs) HiddenText) RevOptionscseZdZdZdZdZdZeddZddZ d d Z d d Z d dZ e ddZe ddZe ddZe ddZe ddZe fddZZS) Mercurialhgz.hgclone)rzhg+filezhg+httpzhg+httpszhg+sshzhg+static-httpcCs|gS)N)Zrevrr?/usr/lib/python3.8/site-packages/pip/_internal/vcs/mercurial.pyget_base_rev_args'szMercurial.get_base_rev_argsc Cs@tdd,}|j|j|d|jd|gd|jdW5QRXdS)z?Export the Hg repository at the url to the destination locationexport)Zkind)urlarchiveF show_stdoutcwdN)runpackpath run_command)selflocationrZtemp_dirrrrr+s zMercurial.exportcCsP|}td||t||tddd|||jtdd||ddS)NzCloning hg %s%s to %srz --noupdate-qupdater)Z to_displayloggerinforrrto_args)rdestr rev_optionsZ rev_displayrrr fetch_new5szMercurial.fetch_newc Cstj||jd}t}z>|||dd|jt |d}| |W5QRXWn6t tj fk r}zt d||W5d}~XYn Xtdd|}|j||ddS) NZhgrcpathsdefaultwz/Could not switch Mercurial repository to %s: %sr"r!r#)osrjoindirnamerZRawConfigParserreadsetZsecretopenwriteOSErrorZNoSectionErrorr$Zwarningrr&r) rr'rr(Z repo_configZconfigZ config_fileexccmd_argsrrrswitchDs  zMercurial.switchcCs4|jddg|dtdd|}|j||ddS)NZpullr!r#r")rrr&)rr'rr(r6rrrr"UszMercurial.updatecCs2|jddgd|d}||r*t|}|S)NZ showconfigz paths.defaultFr)rstripZ_is_local_repositoryr )clsr rrrrget_remote_url[s  zMercurial.get_remote_urlcCs|jddgd|d}|S)zW Return the repository-local changeset revision number, as an integer. parentsz--template={rev}Frrr8)r9r Zcurrent_revisionrrr get_revisionds  zMercurial.get_revisioncCs|jddgd|d}|S)zh Return the changeset identification hash, as a 40-character hexadecimal string r;z--template={node}Frr<)r9r Zcurrent_rev_hashrrrget_requirement_revisionns  z"Mercurial.get_requirement_revisioncCsdS)z&Always assume the versions don't matchFr)r9r'namerrris_commit_id_equalyszMercurial.is_commit_id_equalcCsB|jdgd|d}tj|s8tjtj||}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. rootFr)rr8r-risabsabspathr.r )r9r Z repo_rootrrrget_subdirectory~s  zMercurial.get_subdirectoryc sPtt||rdSz|jdg|ddddWdSttfk rJYdSXdS)NTZidentifyFraise)rrZ on_returncodeZlog_failed_cmd)superrcontrols_locationrrr)r9r  __class__rrrGszMercurial.controls_location)__name__ __module__ __qualname__r?r/Z repo_nameZschemes staticmethodrrr)r7r" classmethodr:r=r>r@rDrG __classcell__rrrHrrs,       r)Z __future__rZloggingr-Zpip._vendor.six.movesrZpip._internal.exceptionsrrZpip._internal.utils.miscrZpip._internal.utils.subprocessrZpip._internal.utils.temp_dirrZpip._internal.utils.typingr Zpip._internal.utils.urlsr Z pip._internal.vcs.versioncontrolr r r rrZ getLoggerrJr$rregisterrrrrs          |vcs/__pycache__/versioncontrol.cpython-38.pyc000064400000044035152347654150015307 0ustar00U .e~S@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZddlmZddlmZmZmZmZmZmZdd lmZmZdd lmZdd lmZerdd lm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+ddlm,Z,ddlm-Z-e'e%e.e%e.fZ/dgZ0e1e2Z3ddZ4dddZ5ddZ6Gddde7Z8Gddde9Z:Gddde9Z;e;Z)r&r=r!r(r>r#r#r$__repr__szRevOptions.__repr__cCs|jdkr|jjS|jSN)r(r=default_arg_revr@r#r#r$arg_revs zRevOptions.arg_revcCs0g}|j}|dk r"||j|7}||j7}|S)z< Return the VCS-specific command arguments. N)rDr=get_base_rev_argsr<)r>argsr(r#r#r$to_argss  zRevOptions.to_argscCs|js dSd|jS)Nz (to revision {}))r(r&r@r#r#r$ to_displayszRevOptions.to_displaycCs|jj||jdS)z Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. r<)r=make_rev_optionsr<)r>r(r#r#r$make_newszRevOptions.make_new)NN) r8r9r:__doc__r?rApropertyrDrGrIrLr#r#r#r$r;js    r;cs|eZdZiZddddddgZfddZd d Zed d Zed dZ eddZ ddZ ddZ ddZ ddZZS) VcsSupportZsshZgitZhgZbzrZsftpZsvncs:tj|jttddr(tj|jtt|dS)N uses_fragment) urllib_parseZ uses_netlocextendschemesgetattrrPsuperrOr?r@ __class__r#r$r?s zVcsSupport.__init__cCs |jSrB) _registry__iter__r@r#r#r$rYszVcsSupport.__iter__cCst|jSrB)listrXvaluesr@r#r#r$backendsszVcsSupport.backendscCsdd|jDS)NcSsg|] }|jqSr#)r1).0backendr#r#r$ sz'VcsSupport.dirnames..)r\r@r#r#r$dirnamesszVcsSupport.dirnamescCs g}|jD]}||jq |SrB)r\rRrS)r>rSr^r#r#r$r s zVcsSupport.all_schemescCsHt|dstd|jdS|j|jkrD||j|j<td|jdS)Nr!zCannot register VCS %szRegistered VCS backend: %s)hasattrr2r3r8r!rXdebug)r>clsr#r#r$registers   zVcsSupport.registercCs||jkr|j|=dSrB)rXr>r!r#r#r$ unregisters zVcsSupport.unregistercCs6|jD]&}||r td||j|Sq dS)zv Return a VersionControl object if a repository of that type is found at the given directory. zDetermine that %s uses VCS: %sN)rXr[controls_locationr2rbr!)r>r5Z vcs_backendr#r#r$get_backend_for_dirs  zVcsSupport.get_backend_for_dircCs|}|j|S)z9 Return a VersionControl object or None. )lowerrXgetrer#r#r$ get_backendszVcsSupport.get_backend)r8r9r:rXrSr?rYrNr\r`r rdrfrhrk __classcell__r#r#rVr$rOs      rOc @s8eZdZdZdZdZdZdZdZe ddZ e ddZ e dd Z e d d Z ed d Ze d8ddZe ddZddZe ddZe ddZeddZddZeddZe ddZd d!Zd"d#Zd$d%Ze d&d'Zd(d)Zd*d+Ze d,d-Ze d.d/Z e d9d2d3Z!e d4d5Z"e d6d7Z#dS):VersionControlrHr#NcCs|d|j S)z Return whether the vcs prefix (e.g. "git+") should be added to a repository's remote url when used in a requirement. z{}:)ri startswithr&r!)rcZ remote_urlr#r#r$should_add_vcs_url_prefixsz(VersionControl.should_add_vcs_url_prefixcCsdS)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. Nr#rcr5r#r#r$get_subdirectoryszVersionControl.get_subdirectorycCs ||S)zR Return the revision string that should be used in a requirement. ) get_revision)rcrepo_dirr#r#r$get_requirement_revisionsz'VersionControl.get_requirement_revisioncCsV||}|dkrdS||r.d|j|}||}||}t||||d}|S)aC Return the requirement string to use to redownload the files currently at the given repository directory. Args: project_name: the (unescaped) project name. The return value has a form similar to the following: {repository_url}@{revision}#egg={project_name} Nz{}+{})r*)get_remote_urlror&r!rtrqr,)rcrsr)r'Zrevisionr*r+r#r#r$get_src_requirements    z"VersionControl.get_src_requirementcCstdS)z Return the base revision arguments for a vcs command. Args: rev: the name of a revision to install. Cannot be None. NNotImplementedError)r(r#r#r$rE8sz VersionControl.get_base_rev_argscCst|||dS)z Return a RevOptions object. Args: rev: the name of a revision to install. extra_args: a list of extra options. rJ)r;)rcr(r<r#r#r$rKBs zVersionControl.make_rev_optionscCs&tj|\}}|tjjp$t|S)zy posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\folder) )r-r. splitdrivernsepbool)rcZrepoZdrivetailr#r#r$_is_local_repositoryNsz#VersionControl._is_local_repositorycCstdS)z Export the repository at the url to the destination location i.e. only download the files, without vcs informations :param url: the repository URL starting with a vcs prefix. Nrwr>r5urlr#r#r$exportXszVersionControl.exportcCs|dfS)aZ Parse the repository URL's netloc, and return the new netloc to use along with auth information. Args: netloc: the original repository URL netloc. scheme: the repository URL's scheme without the vcs prefix. This is mainly for the Subversion class to override, so that auth information can be provided via the --username and --password options instead of through the URL. For other subclasses like Git without such an option, auth information must stay in the URL. Returns: (netloc, (username, password)). )NNr#)rcnetlocr"r#r#r$get_netloc_and_authbsz"VersionControl.get_netloc_and_authc Cst|\}}}}}d|kr*td||ddd}|||\}}d}d|krf|dd\}}t||||df}|||fS)z Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). +zvSorry, {!r} is a malformed VCS url. The format is +://, e.g. svn+http://myrepo/svn/MyApp#egg=MyAppN@rH)rQZurlsplit ValueErrorr&splitrrsplitZ urlunsplit) rcrr"rr.ZqueryZfrag user_passr(r#r#r$get_url_rev_and_authus z#VersionControl.get_url_rev_and_authcCsgS)zM Return the RevOptions "extra arguments" to use in obtain(). r#)usernamepasswordr#r#r$ make_rev_argsszVersionControl.make_rev_argsc CsT||j\}}}|\}}d}|dk r.t|}|||}|j||d} t|| fS)z Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). NrJ)rsecretr rrKr ) r>rZ secret_urlr(rrZsecret_passwordrr< rev_optionsr#r#r$get_url_rev_optionss z"VersionControl.get_url_rev_optionscCst|dS)zi Normalize a URL for comparison by unquoting it and removing any trailing slash. /)rQZunquoterstriprr#r#r$ normalize_urlszVersionControl.normalize_urlcCs||||kS)zV Compare two repo URLs for identity, ignoring incidental differences. )r)rcZurl1Zurl2r#r#r$ compare_urlsszVersionControl.compare_urlscCstdS)z Fetch a revision from a repository, in the case that this is the first fetch from the repository. Args: dest: the directory to fetch the repository to. rev_options: a RevOptions object. Nrwr>destrrr#r#r$ fetch_news zVersionControl.fetch_newcCstdS)z} Switch the repo at ``dest`` to point to ``URL``. Args: rev_options: a RevOptions object. Nrwrr#r#r$switchszVersionControl.switchcCstdS)z Update an already-existing repo to the given ``rev_options``. Args: rev_options: a RevOptions object. Nrwrr#r#r$updateszVersionControl.updatecCstdS)z Return whether the id of the current commit equals the given name. Args: dest: the repository directory. name: a string name. Nrw)rcrr!r#r#r$is_commit_id_equals z!VersionControl.is_commit_id_equalc Cs||\}}tj|s,||||dS|}||r||}|||j rt d|j t|||||jst dt||j |||||n t ddSt d|j|j t||d}nt d||j|j d}t d |j|td |d |d }|d kr$td|dkrXt dt|t|||||dS|dkrt|}t dt||t||||||dS|dkrt d|j t|||||||dS)a Install or update in editable mode the package represented by this VersionControl object. :param dest: the repository directory in which to install or update. :param url: the repository URL starting with a vcs prefix. Nz)%s in %s exists, and has correct URL (%s)zUpdating %s %s%sz$Skipping because already up-to-date.z%s %s in %s exists with URL %s)z%(s)witch, (i)gnore, (w)ipe, (b)ackup )siwbz0Directory %s already exists, and is not a %s %s.)z(i)gnore, (w)ipe, (b)ackup )rrrz+The plan is to install the %s repository %szWhat to do? %srrarz Deleting %srzBacking up %s to %srzSwitching %s %s to %s%s)rr-r.r/rrIis_repository_directoryrurrr2rb repo_nametitler rr(inforr3r!rsysexitr rshutilZmover) r>rrrZ rev_displayZ existing_urlpromptZresponseZdest_dirr#r#r$obtains           zVersionControl.obtaincCs&tj|rt||j||ddS)z Clean up current location and download the url repository (and vcs infos) into location :param url: the repository URL starting with a vcs prefix. rN)r-r.r/r rr~r#r#r$unpack?s zVersionControl.unpackcCstdS)z Return the url used at location Raises RemoteNotFoundError if the repository does not have a remote url configured. Nrwrpr#r#r$ruKszVersionControl.get_remote_urlcCstdS)zR Return the current commit id of the files at the given location. Nrwrpr#r#r$rrUszVersionControl.get_revisionTraisec Cs|t|jf|}z t||||||||j|| d WStk rv} z(| jtjkrdtd|j|jfnW5d} ~ XYnXdS)z Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available ) on_returncodeextra_ok_returncodes command_desc extra_environ unset_environspinnerlog_failed_cmdzCCannot find command %r - do you have %r installed and in your PATH?N)rr!r rOSErrorerrnoZENOENTr) rccmdZ show_stdoutcwdrrrrrrer#r#r$ run_command\s&  zVersionControl.run_commandcCs,td||j|jtjtj||jS)zL Return whether a directory path is a repository directory. zChecking in %s for %s (%s)...)r2rbr1r!r-r.r/r0)rcr.r#r#r$rs z&VersionControl.is_repository_directorycCs ||S)a6 Check if a location is controlled by the vcs. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. This can do more than is_repository_directory() alone. For example, the Git override checks that Git is actually available. )rrpr#r#r$rgs z VersionControl.controls_location)NN)TNrNNNNT)$r8r9r:r!r1rrSrrC classmethodrorqrtrv staticmethodrErKr}rrrrrrrrrrrrrrurrrrrgr#r#r#r$rmsr                 ]    ' rm)N)>rMZ __future__rrZloggingr-rrZ pip._vendorrZpip._vendor.six.moves.urllibrrQZpip._internal.exceptionsrZpip._internal.utils.compatrZpip._internal.utils.miscrrr r r r Zpip._internal.utils.subprocessr rZpip._internal.utils.typingrZpip._internal.utils.urlsrtypingrrrrrrrrrrZpip._internal.utils.uirrrstrZAuthInfo__all__Z getLoggerr8r2r%r,r6 Exceptionr7objectr;rOrrmr#r#r#r$s<        0     HGvcs/__pycache__/bazaar.cpython-38.pyc000064400000007243152347654150013461 0ustar00U .eu@sddlmZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z ddlmZddlmZmZe rdd lmZmZdd lmZdd lmZmZeeZGd d d eZeedS))absolute_importN)parse) display_pathrmtree) make_command)MYPY_CHECK_RUNNING) path_to_url)VersionControlvcs)OptionalTuple) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZfddZeddZ d d Z d d Z d dZ ddZ efddZeddZeddZeddZZS)Bazaarbzrz.bzrbranch)rzbzr+httpz bzr+httpszbzr+sshzbzr+sftpzbzr+ftpzbzr+lpcs0tt|j||ttddr,tjdgdS)N uses_fragmentZlp)superr__init__getattr urllib_parserextend)selfargskwargs __class__|}td||t|tdd|||}||dS)NzChecking out %s%s to %sr-q)Z to_displayloggerinforrr(r')rdestr*r+Z rev_displaycmd_argsrrr fetch_new=szBazaar.fetch_newcCs|jtd||ddS)Nswitchcwd)r'r)rr/r*r+rrrr2Ksz Bazaar.switchcCs"tdd|}|j||ddS)NZpullr,r3)rr(r')rr/r*r+r0rrrupdateOsz Bazaar.updatecs2tt||\}}}|dr(d|}|||fS)Nzssh://zbzr+)rrget_url_rev_and_auth startswith)clsr*r Z user_passrrrr6Ts zBazaar.get_url_rev_and_authcCst|jdgd|d}|D]T}|}dD]B}||r*||d}||r`t|S|Sq*qdS)Nr.Fr#r4)zcheckout of branch: zparent branch: )r' splitlinesstripr7splitZ_is_local_repositoryr)r8r)ZurlslinexZreporrrget_remote_url]s   zBazaar.get_remote_urlcCs|jdgd|d}|dS)NZrevnoFr9)r'r;)r8r)Zrevisionrrr get_revisionks zBazaar.get_revisioncCsdS)z&Always assume the versions don't matchFr)r8r/namerrris_commit_id_equalrszBazaar.is_commit_id_equal)__name__ __module__ __qualname__rCdirnameZ repo_nameZschemesr staticmethodr!r"r1r2r5 classmethodr6r@rBrD __classcell__rrrrrs&    r)Z __future__rZloggingr$Zpip._vendor.six.moves.urllibrrZpip._internal.utils.miscrrZpip._internal.utils.subprocessrZpip._internal.utils.typingrZpip._internal.utils.urlsrZ pip._internal.vcs.versioncontrolr r typingr r r rrZ getLoggerrEr-rregisterrrrrs       ^vcs/mercurial.py000064400000012052152347654150007710 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os from pip._vendor.six.moves import configparser from pip._internal.exceptions import BadCommand, SubProcessError from pip._internal.utils.misc import display_path from pip._internal.utils.subprocess import make_command from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs.versioncontrol import ( VersionControl, find_path_to_setup_from_repo_root, vcs, ) if MYPY_CHECK_RUNNING: from pip._internal.utils.misc import HiddenText from pip._internal.vcs.versioncontrol import RevOptions logger = logging.getLogger(__name__) class Mercurial(VersionControl): name = 'hg' dirname = '.hg' repo_name = 'clone' schemes = ( 'hg', 'hg+file', 'hg+http', 'hg+https', 'hg+ssh', 'hg+static-http', ) @staticmethod def get_base_rev_args(rev): return [rev] def export(self, location, url): # type: (str, HiddenText) -> None """Export the Hg repository at the url to the destination location""" with TempDirectory(kind="export") as temp_dir: self.unpack(temp_dir.path, url=url) self.run_command( ['archive', location], cwd=temp_dir.path ) def fetch_new(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None rev_display = rev_options.to_display() logger.info( 'Cloning hg %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(make_command('clone', '--noupdate', '-q', url, dest)) self.run_command( make_command('update', '-q', rev_options.to_args()), cwd=dest, ) def switch(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None repo_config = os.path.join(dest, self.dirname, 'hgrc') config = configparser.RawConfigParser() try: config.read(repo_config) config.set('paths', 'default', url.secret) with open(repo_config, 'w') as config_file: config.write(config_file) except (OSError, configparser.NoSectionError) as exc: logger.warning( 'Could not switch Mercurial repository to %s: %s', url, exc, ) else: cmd_args = make_command('update', '-q', rev_options.to_args()) self.run_command(cmd_args, cwd=dest) def update(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None self.run_command(['pull', '-q'], cwd=dest) cmd_args = make_command('update', '-q', rev_options.to_args()) self.run_command(cmd_args, cwd=dest) @classmethod def get_remote_url(cls, location): url = cls.run_command( ['showconfig', 'paths.default'], cwd=location).strip() if cls._is_local_repository(url): url = path_to_url(url) return url.strip() @classmethod def get_revision(cls, location): """ Return the repository-local changeset revision number, as an integer. """ current_revision = cls.run_command( ['parents', '--template={rev}'], cwd=location).strip() return current_revision @classmethod def get_requirement_revision(cls, location): """ Return the changeset identification hash, as a 40-character hexadecimal string """ current_rev_hash = cls.run_command( ['parents', '--template={node}'], cwd=location).strip() return current_rev_hash @classmethod def is_commit_id_equal(cls, dest, name): """Always assume the versions don't match""" return False @classmethod def get_subdirectory(cls, location): """ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. """ # find the repo root repo_root = cls.run_command( ['root'], cwd=location).strip() if not os.path.isabs(repo_root): repo_root = os.path.abspath(os.path.join(location, repo_root)) return find_path_to_setup_from_repo_root(location, repo_root) @classmethod def get_repository_root(cls, location): loc = super(Mercurial, cls).get_repository_root(location) if loc: return loc try: r = cls.run_command( ['root'], cwd=location, log_failed_cmd=False, ) except BadCommand: logger.debug("could not determine if %s is under hg control " "because hg is not available", location) return None except SubProcessError: return None return os.path.normpath(r.rstrip('\r\n')) vcs.register(Mercurial) vcs/versioncontrol.py000064400000062556152347654150011031 0ustar00"""Handles all VCS (version control) support""" from __future__ import absolute_import import errno import logging import os import shutil import subprocess import sys from pip._vendor import pkg_resources from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import ( BadCommand, InstallationError, SubProcessError, ) from pip._internal.utils.compat import console_to_str, samefile from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import ( ask_path_exists, backup_dir, display_path, hide_url, hide_value, rmtree, ) from pip._internal.utils.subprocess import ( format_command_args, make_command, make_subprocess_output_error, reveal_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import get_url_scheme if MYPY_CHECK_RUNNING: from typing import ( Dict, Iterable, Iterator, List, Optional, Text, Tuple, Type, Union, Mapping, Any ) from pip._internal.utils.misc import HiddenText from pip._internal.utils.subprocess import CommandArgs AuthInfo = Tuple[Optional[str], Optional[str]] __all__ = ['vcs'] logger = logging.getLogger(__name__) def is_url(name): # type: (Union[str, Text]) -> bool """ Return true if the name looks like a URL. """ scheme = get_url_scheme(name) if scheme is None: return False return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None): # type: (str, str, str, Optional[str]) -> str """ Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. """ egg_project_name = pkg_resources.to_filename(project_name) req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name) if subdir: req += '&subdirectory={}'.format(subdir) return req def call_subprocess( cmd, # type: Union[List[str], CommandArgs] cwd=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] extra_ok_returncodes=None, # type: Optional[Iterable[int]] log_failed_cmd=True # type: Optional[bool] ): # type: (...) -> Text """ Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. log_failed_cmd: if false, failed commands are not logged, only raised. """ if extra_ok_returncodes is None: extra_ok_returncodes = [] # log the subprocess output at DEBUG level. log_subprocess = subprocess_logger.debug env = os.environ.copy() if extra_environ: env.update(extra_environ) # Whether the subprocess will be visible in the console. showing_subprocess = True command_desc = format_command_args(cmd) try: proc = subprocess.Popen( # Convert HiddenText objects to the underlying str. reveal_command_args(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if proc.stdin: proc.stdin.close() except Exception as exc: if log_failed_cmd: subprocess_logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise all_output = [] while True: # The "line" value is a unicode string in Python 2. line = None if proc.stdout: line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') # Show the line immediately. log_subprocess(line) try: proc.wait() finally: if proc.stdout: proc.stdout.close() proc_had_error = ( proc.returncode and proc.returncode not in extra_ok_returncodes ) if proc_had_error: if not showing_subprocess and log_failed_cmd: # Then the subprocess streams haven't been logged to the # console yet. msg = make_subprocess_output_error( cmd_args=cmd, cwd=cwd, lines=all_output, exit_status=proc.returncode, ) subprocess_logger.error(msg) exc_msg = ( 'Command errored out with exit status {}: {} ' 'Check the logs for full command output.' ).format(proc.returncode, command_desc) raise SubProcessError(exc_msg) return ''.join(all_output) def find_path_to_setup_from_repo_root(location, repo_root): # type: (str, str) -> Optional[str] """ Find the path to `setup.py` by searching up the filesystem from `location`. Return the path to `setup.py` relative to `repo_root`. Return None if `setup.py` is in `repo_root` or cannot be found. """ # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None if samefile(repo_root, location): return None return os.path.relpath(location, repo_root) class RemoteNotFoundError(Exception): pass class RevOptions(object): """ Encapsulates a VCS-specific revision to install, along with any VCS install options. Instances of this class should be treated as if immutable. """ def __init__( self, vc_class, # type: Type[VersionControl] rev=None, # type: Optional[str] extra_args=None, # type: Optional[CommandArgs] ): # type: (...) -> None """ Args: vc_class: a VersionControl subclass. rev: the name of the revision to install. extra_args: a list of extra options. """ if extra_args is None: extra_args = [] self.extra_args = extra_args self.rev = rev self.vc_class = vc_class self.branch_name = None # type: Optional[str] def __repr__(self): # type: () -> str return ''.format(self.vc_class.name, self.rev) @property def arg_rev(self): # type: () -> Optional[str] if self.rev is None: return self.vc_class.default_arg_rev return self.rev def to_args(self): # type: () -> CommandArgs """ Return the VCS-specific command arguments. """ args = [] # type: CommandArgs rev = self.arg_rev if rev is not None: args += self.vc_class.get_base_rev_args(rev) args += self.extra_args return args def to_display(self): # type: () -> str if not self.rev: return '' return ' (to revision {})'.format(self.rev) def make_new(self, rev): # type: (str) -> RevOptions """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vc_class.make_rev_options(rev, extra_args=self.extra_args) class VcsSupport(object): _registry = {} # type: Dict[str, VersionControl] schemes = ['ssh', 'git', 'hg', 'bzr', 'sftp', 'svn'] def __init__(self): # type: () -> None # Register more schemes with urlparse for various version control # systems urllib_parse.uses_netloc.extend(self.schemes) # Python >= 2.7.4, 3.3 doesn't have uses_fragment if getattr(urllib_parse, 'uses_fragment', None): urllib_parse.uses_fragment.extend(self.schemes) super(VcsSupport, self).__init__() def __iter__(self): # type: () -> Iterator[str] return self._registry.__iter__() @property def backends(self): # type: () -> List[VersionControl] return list(self._registry.values()) @property def dirnames(self): # type: () -> List[str] return [backend.dirname for backend in self.backends] @property def all_schemes(self): # type: () -> List[str] schemes = [] # type: List[str] for backend in self.backends: schemes.extend(backend.schemes) return schemes def register(self, cls): # type: (Type[VersionControl]) -> None if not hasattr(cls, 'name'): logger.warning('Cannot register VCS %s', cls.__name__) return if cls.name not in self._registry: self._registry[cls.name] = cls() logger.debug('Registered VCS backend: %s', cls.name) def unregister(self, name): # type: (str) -> None if name in self._registry: del self._registry[name] def get_backend_for_dir(self, location): # type: (str) -> Optional[VersionControl] """ Return a VersionControl object if a repository of that type is found at the given directory. """ vcs_backends = {} for vcs_backend in self._registry.values(): repo_path = vcs_backend.get_repository_root(location) if not repo_path: continue logger.debug('Determine that %s uses VCS: %s', location, vcs_backend.name) vcs_backends[repo_path] = vcs_backend if not vcs_backends: return None # Choose the VCS in the inner-most directory. Since all repository # roots found here would be either `location` or one of its # parents, the longest path should have the most path components, # i.e. the backend representing the inner-most repository. inner_most_repo_path = max(vcs_backends, key=len) return vcs_backends[inner_most_repo_path] def get_backend_for_scheme(self, scheme): # type: (str) -> Optional[VersionControl] """ Return a VersionControl object or None. """ for vcs_backend in self._registry.values(): if scheme in vcs_backend.schemes: return vcs_backend return None def get_backend(self, name): # type: (str) -> Optional[VersionControl] """ Return a VersionControl object or None. """ name = name.lower() return self._registry.get(name) vcs = VcsSupport() class VersionControl(object): name = '' dirname = '' repo_name = '' # List of supported schemes for this Version Control schemes = () # type: Tuple[str, ...] # Iterable of environment variable names to pass to call_subprocess(). unset_environ = () # type: Tuple[str, ...] default_arg_rev = None # type: Optional[str] @classmethod def should_add_vcs_url_prefix(cls, remote_url): # type: (str) -> bool """ Return whether the vcs prefix (e.g. "git+") should be added to a repository's remote url when used in a requirement. """ return not remote_url.lower().startswith('{}:'.format(cls.name)) @classmethod def get_subdirectory(cls, location): # type: (str) -> Optional[str] """ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. """ return None @classmethod def get_requirement_revision(cls, repo_dir): # type: (str) -> str """ Return the revision string that should be used in a requirement. """ return cls.get_revision(repo_dir) @classmethod def get_src_requirement(cls, repo_dir, project_name): # type: (str, str) -> Optional[str] """ Return the requirement string to use to redownload the files currently at the given repository directory. Args: project_name: the (unescaped) project name. The return value has a form similar to the following: {repository_url}@{revision}#egg={project_name} """ repo_url = cls.get_remote_url(repo_dir) if repo_url is None: return None if cls.should_add_vcs_url_prefix(repo_url): repo_url = '{}+{}'.format(cls.name, repo_url) revision = cls.get_requirement_revision(repo_dir) subdir = cls.get_subdirectory(repo_dir) req = make_vcs_requirement_url(repo_url, revision, project_name, subdir=subdir) return req @staticmethod def get_base_rev_args(rev): # type: (str) -> List[str] """ Return the base revision arguments for a vcs command. Args: rev: the name of a revision to install. Cannot be None. """ raise NotImplementedError def is_immutable_rev_checkout(self, url, dest): # type: (str, str) -> bool """ Return true if the commit hash checked out at dest matches the revision in url. Always return False, if the VCS does not support immutable commit hashes. This method does not check if there are local uncommitted changes in dest after checkout, as pip currently has no use case for that. """ return False @classmethod def make_rev_options(cls, rev=None, extra_args=None): # type: (Optional[str], Optional[CommandArgs]) -> RevOptions """ Return a RevOptions object. Args: rev: the name of a revision to install. extra_args: a list of extra options. """ return RevOptions(cls, rev, extra_args=extra_args) @classmethod def _is_local_repository(cls, repo): # type: (str) -> bool """ posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\\folder) """ drive, tail = os.path.splitdrive(repo) return repo.startswith(os.path.sep) or bool(drive) def export(self, location, url): # type: (str, HiddenText) -> None """ Export the repository at the url to the destination location i.e. only download the files, without vcs informations :param url: the repository URL starting with a vcs prefix. """ raise NotImplementedError @classmethod def get_netloc_and_auth(cls, netloc, scheme): # type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]] """ Parse the repository URL's netloc, and return the new netloc to use along with auth information. Args: netloc: the original repository URL netloc. scheme: the repository URL's scheme without the vcs prefix. This is mainly for the Subversion class to override, so that auth information can be provided via the --username and --password options instead of through the URL. For other subclasses like Git without such an option, auth information must stay in the URL. Returns: (netloc, (username, password)). """ return netloc, (None, None) @classmethod def get_url_rev_and_auth(cls, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] """ Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). """ scheme, netloc, path, query, frag = urllib_parse.urlsplit(url) if '+' not in scheme: raise ValueError( "Sorry, {!r} is a malformed VCS url. " "The format is +://, " "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url) ) # Remove the vcs prefix. scheme = scheme.split('+', 1)[1] netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme) rev = None if '@' in path: path, rev = path.rsplit('@', 1) if not rev: raise InstallationError( "The URL {!r} has an empty revision (after @) " "which is not supported. Include a revision after @ " "or remove @ from the URL.".format(url) ) url = urllib_parse.urlunsplit((scheme, netloc, path, query, '')) return url, rev, user_pass @staticmethod def make_rev_args(username, password): # type: (Optional[str], Optional[HiddenText]) -> CommandArgs """ Return the RevOptions "extra arguments" to use in obtain(). """ return [] def get_url_rev_options(self, url): # type: (HiddenText) -> Tuple[HiddenText, RevOptions] """ Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). """ secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret) username, secret_password = user_pass password = None # type: Optional[HiddenText] if secret_password is not None: password = hide_value(secret_password) extra_args = self.make_rev_args(username, password) rev_options = self.make_rev_options(rev, extra_args=extra_args) return hide_url(secret_url), rev_options @staticmethod def normalize_url(url): # type: (str) -> str """ Normalize a URL for comparison by unquoting it and removing any trailing slash. """ return urllib_parse.unquote(url).rstrip('/') @classmethod def compare_urls(cls, url1, url2): # type: (str, str) -> bool """ Compare two repo URLs for identity, ignoring incidental differences. """ return (cls.normalize_url(url1) == cls.normalize_url(url2)) def fetch_new(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None """ Fetch a revision from a repository, in the case that this is the first fetch from the repository. Args: dest: the directory to fetch the repository to. rev_options: a RevOptions object. """ raise NotImplementedError def switch(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None """ Switch the repo at ``dest`` to point to ``URL``. Args: rev_options: a RevOptions object. """ raise NotImplementedError def update(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None """ Update an already-existing repo to the given ``rev_options``. Args: rev_options: a RevOptions object. """ raise NotImplementedError @classmethod def is_commit_id_equal(cls, dest, name): # type: (str, Optional[str]) -> bool """ Return whether the id of the current commit equals the given name. Args: dest: the repository directory. name: a string name. """ raise NotImplementedError def obtain(self, dest, url): # type: (str, HiddenText) -> None """ Install or update in editable mode the package represented by this VersionControl object. :param dest: the repository directory in which to install or update. :param url: the repository URL starting with a vcs prefix. """ url, rev_options = self.get_url_rev_options(url) if not os.path.exists(dest): self.fetch_new(dest, url, rev_options) return rev_display = rev_options.to_display() if self.is_repository_directory(dest): existing_url = self.get_remote_url(dest) if self.compare_urls(existing_url, url.secret): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.is_commit_id_equal(dest, rev_options.rev): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, url, rev_options) else: logger.info('Skipping because already up-to-date.') return logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) # https://github.com/python/mypy/issues/1174 prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore ('i', 'w', 'b')) logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? {}'.format( prompt[0]), prompt[1]) if response == 'a': sys.exit(-1) if response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) self.fetch_new(dest, url, rev_options) return if response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) self.fetch_new(dest, url, rev_options) return # Do nothing if the response is "i". if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options) def unpack(self, location, url): # type: (str, HiddenText) -> None """ Clean up current location and download the url repository (and vcs infos) into location :param url: the repository URL starting with a vcs prefix. """ if os.path.exists(location): rmtree(location) self.obtain(location, url=url) @classmethod def get_remote_url(cls, location): # type: (str) -> str """ Return the url used at location Raises RemoteNotFoundError if the repository does not have a remote url configured. """ raise NotImplementedError @classmethod def get_revision(cls, location): # type: (str) -> str """ Return the current commit id of the files at the given location. """ raise NotImplementedError @classmethod def run_command( cls, cmd, # type: Union[List[str], CommandArgs] cwd=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] extra_ok_returncodes=None, # type: Optional[Iterable[int]] log_failed_cmd=True # type: bool ): # type: (...) -> Text """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available """ cmd = make_command(cls.name, *cmd) try: return call_subprocess(cmd, cwd, extra_environ=extra_environ, extra_ok_returncodes=extra_ok_returncodes, log_failed_cmd=log_failed_cmd) except OSError as e: # errno.ENOENT = no such file or directory # In other words, the VCS executable isn't available if e.errno == errno.ENOENT: raise BadCommand( 'Cannot find command {cls.name!r} - do you have ' '{cls.name!r} installed and in your ' 'PATH?'.format(**locals())) else: raise # re-raise exception if a different error occurred @classmethod def is_repository_directory(cls, path): # type: (str) -> bool """ Return whether a directory path is a repository directory. """ logger.debug('Checking in %s for %s (%s)...', path, cls.dirname, cls.name) return os.path.exists(os.path.join(path, cls.dirname)) @classmethod def get_repository_root(cls, location): # type: (str) -> Optional[str] """ Return the "root" (top-level) directory controlled by the vcs, or `None` if the directory is not in any. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. This can do more than is_repository_directory() alone. For example, the Git override checks that Git is actually available. """ if cls.is_repository_directory(location): return location return None vcs/bazaar.py000064400000007457152347654150007202 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.misc import display_path, rmtree from pip._internal.utils.subprocess import make_command from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs.versioncontrol import VersionControl, vcs if MYPY_CHECK_RUNNING: from typing import Optional, Tuple from pip._internal.utils.misc import HiddenText from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions logger = logging.getLogger(__name__) class Bazaar(VersionControl): name = 'bzr' dirname = '.bzr' repo_name = 'branch' schemes = ( 'bzr', 'bzr+http', 'bzr+https', 'bzr+ssh', 'bzr+sftp', 'bzr+ftp', 'bzr+lp', ) def __init__(self, *args, **kwargs): super(Bazaar, self).__init__(*args, **kwargs) # This is only needed for python <2.7.5 # Register lp but do not expose as a scheme to support bzr+lp. if getattr(urllib_parse, 'uses_fragment', None): urllib_parse.uses_fragment.extend(['lp']) @staticmethod def get_base_rev_args(rev): return ['-r', rev] def export(self, location, url): # type: (str, HiddenText) -> None """ Export the Bazaar repository at the url to the destination location """ # Remove the location to make sure Bazaar can export it correctly if os.path.exists(location): rmtree(location) url, rev_options = self.get_url_rev_options(url) self.run_command( make_command('export', location, url, rev_options.to_args()) ) def fetch_new(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None rev_display = rev_options.to_display() logger.info( 'Checking out %s%s to %s', url, rev_display, display_path(dest), ) cmd_args = ( make_command('branch', '-q', rev_options.to_args(), url, dest) ) self.run_command(cmd_args) def switch(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None self.run_command(make_command('switch', url), cwd=dest) def update(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None cmd_args = make_command('pull', '-q', rev_options.to_args()) self.run_command(cmd_args, cwd=dest) @classmethod def get_url_rev_and_auth(cls, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] # hotfix the URL scheme after removing bzr+ from bzr+ssh:// readd it url, rev, user_pass = super(Bazaar, cls).get_url_rev_and_auth(url) if url.startswith('ssh://'): url = 'bzr+' + url return url, rev, user_pass @classmethod def get_remote_url(cls, location): urls = cls.run_command(['info'], cwd=location) for line in urls.splitlines(): line = line.strip() for x in ('checkout of branch: ', 'parent branch: '): if line.startswith(x): repo = line.split(x)[1] if cls._is_local_repository(repo): return path_to_url(repo) return repo return None @classmethod def get_revision(cls, location): revision = cls.run_command( ['revno'], cwd=location, ) return revision.splitlines()[-1] @classmethod def is_commit_id_equal(cls, dest, name): """Always assume the versions don't match""" return False vcs.register(Bazaar) vcs/subversion.py000064400000030157152347654150010132 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os import re from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( display_path, is_console_interactive, rmtree, split_auth_from_netloc, ) from pip._internal.utils.subprocess import make_command from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.vcs.versioncontrol import VersionControl, vcs _svn_xml_url_re = re.compile('url="([^"]+)"') _svn_rev_re = re.compile(r'committed-rev="(\d+)"') _svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"') _svn_info_xml_url_re = re.compile(r'(.*)') if MYPY_CHECK_RUNNING: from typing import Optional, Tuple from pip._internal.utils.subprocess import CommandArgs from pip._internal.utils.misc import HiddenText from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions logger = logging.getLogger(__name__) class Subversion(VersionControl): name = 'svn' dirname = '.svn' repo_name = 'checkout' schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn') @classmethod def should_add_vcs_url_prefix(cls, remote_url): return True @staticmethod def get_base_rev_args(rev): return ['-r', rev] @classmethod def get_revision(cls, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, _ in os.walk(location): if cls.dirname not in dirs: dirs[:] = [] continue # no sense walking uncontrolled subdirs dirs.remove(cls.dirname) entries_fn = os.path.join(base, cls.dirname, 'entries') if not os.path.exists(entries_fn): # FIXME: should we warn? continue dirurl, localrev = cls._get_svn_url_rev(base) if base == location: base = dirurl + '/' # save the root url elif not dirurl or not dirurl.startswith(base): dirs[:] = [] continue # not part of the same svn tree, skip it revision = max(revision, localrev) return revision @classmethod def get_netloc_and_auth(cls, netloc, scheme): """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for # svn+ssh URLs, so keep the auth information in the URL. return super(Subversion, cls).get_netloc_and_auth(netloc, scheme) return split_auth_from_netloc(netloc) @classmethod def get_url_rev_and_auth(cls, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it url, rev, user_pass = super(Subversion, cls).get_url_rev_and_auth(url) if url.startswith('ssh://'): url = 'svn+' + url return url, rev, user_pass @staticmethod def make_rev_args(username, password): # type: (Optional[str], Optional[HiddenText]) -> CommandArgs extra_args = [] # type: CommandArgs if username: extra_args += ['--username', username] if password: extra_args += ['--password', password] return extra_args @classmethod def get_remote_url(cls, location): # In cases where the source is in a subdirectory, not alongside # setup.py we have to look up in the location until we find a real # setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None return cls._get_svn_url_rev(location)[0] @classmethod def _get_svn_url_rev(cls, location): from pip._internal.exceptions import SubProcessError entries_path = os.path.join(location, cls.dirname, 'entries') if os.path.exists(entries_path): with open(entries_path) as f: data = f.read() else: # subversion >= 1.7 does not have the 'entries' file data = '' if (data.startswith('8') or data.startswith('9') or data.startswith('10')): data = list(map(str.splitlines, data.split('\n\x0c\n'))) del data[0][0] # get rid of the '8' url = data[0][3] revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0] elif data.startswith('= 1.7 # Note that using get_remote_call_options is not necessary here # because `svn info` is being run against a local directory. # We don't need to worry about making sure interactive mode # is being used to prompt for passwords, because passwords # are only potentially needed for remote server requests. xml = cls.run_command( ['info', '--xml', location], ) url = _svn_info_xml_url_re.search(xml).group(1) revs = [ int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml) ] except SubProcessError: url, revs = None, [] if revs: rev = max(revs) else: rev = 0 return url, rev @classmethod def is_commit_id_equal(cls, dest, name): """Always assume the versions don't match""" return False def __init__(self, use_interactive=None): # type: (bool) -> None if use_interactive is None: use_interactive = is_console_interactive() self.use_interactive = use_interactive # This member is used to cache the fetched version of the current # ``svn`` client. # Special value definitions: # None: Not evaluated yet. # Empty tuple: Could not parse version. self._vcs_version = None # type: Optional[Tuple[int, ...]] super(Subversion, self).__init__() def call_vcs_version(self): # type: () -> Tuple[int, ...] """Query the version of the currently installed Subversion client. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. """ # Example versions: # svn, version 1.10.3 (r1842928) # compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0 # svn, version 1.7.14 (r1542130) # compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu # svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0) # compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2 version_prefix = 'svn, version ' version = self.run_command(['--version']) if not version.startswith(version_prefix): return () version = version[len(version_prefix):].split()[0] version_list = version.partition('-')[0].split('.') try: parsed_version = tuple(map(int, version_list)) except ValueError: return () return parsed_version def get_vcs_version(self): # type: () -> Tuple[int, ...] """Return the version of the currently installed Subversion client. If the version of the Subversion client has already been queried, a cached value will be used. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. """ if self._vcs_version is not None: # Use cached version, if available. # If parsing the version failed previously (empty tuple), # do not attempt to parse it again. return self._vcs_version vcs_version = self.call_vcs_version() self._vcs_version = vcs_version return vcs_version def get_remote_call_options(self): # type: () -> CommandArgs """Return options to be used on calls to Subversion that contact the server. These options are applicable for the following ``svn`` subcommands used in this class. - checkout - export - switch - update :return: A list of command line arguments to pass to ``svn``. """ if not self.use_interactive: # --non-interactive switch is available since Subversion 0.14.4. # Subversion < 1.8 runs in interactive mode by default. return ['--non-interactive'] svn_version = self.get_vcs_version() # By default, Subversion >= 1.8 runs in non-interactive mode if # stdin is not a TTY. Since that is how pip invokes SVN, in # call_subprocess(), pip must pass --force-interactive to ensure # the user can be prompted for a password, if required. # SVN added the --force-interactive option in SVN 1.8. Since # e.g. RHEL/CentOS 7, which is supported until 2024, ships with # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip # can't safely add the option if the SVN version is < 1.8 (or unknown). if svn_version >= (1, 8): return ['--force-interactive'] return [] def export(self, location, url): # type: (str, HiddenText) -> None """Export the svn repository at the url to the destination location""" url, rev_options = self.get_url_rev_options(url) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exists(location): # Subversion doesn't like to check out over an existing # directory --force fixes this, but was only added in svn 1.5 rmtree(location) cmd_args = make_command( 'export', self.get_remote_call_options(), rev_options.to_args(), url, location, ) self.run_command(cmd_args) def fetch_new(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None rev_display = rev_options.to_display() logger.info( 'Checking out %s%s to %s', url, rev_display, display_path(dest), ) cmd_args = make_command( 'checkout', '-q', self.get_remote_call_options(), rev_options.to_args(), url, dest, ) self.run_command(cmd_args) def switch(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None cmd_args = make_command( 'switch', self.get_remote_call_options(), rev_options.to_args(), url, dest, ) self.run_command(cmd_args) def update(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None cmd_args = make_command( 'update', self.get_remote_call_options(), rev_options.to_args(), dest, ) self.run_command(cmd_args) vcs.register(Subversion) vcs/git.py000064400000033241152347654150006513 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os.path import re from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import BadCommand, SubProcessError from pip._internal.utils.misc import display_path, hide_url from pip._internal.utils.subprocess import make_command from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.vcs.versioncontrol import ( RemoteNotFoundError, VersionControl, find_path_to_setup_from_repo_root, vcs, ) if MYPY_CHECK_RUNNING: from typing import Optional, Tuple from pip._internal.utils.misc import HiddenText from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions urlsplit = urllib_parse.urlsplit urlunsplit = urllib_parse.urlunsplit logger = logging.getLogger(__name__) HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$') def looks_like_hash(sha): return bool(HASH_REGEX.match(sha)) class Git(VersionControl): name = 'git' dirname = '.git' repo_name = 'clone' schemes = ( 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file', ) # Prevent the user's environment variables from interfering with pip: # https://github.com/pypa/pip/issues/1130 unset_environ = ('GIT_DIR', 'GIT_WORK_TREE') default_arg_rev = 'HEAD' @staticmethod def get_base_rev_args(rev): return [rev] def is_immutable_rev_checkout(self, url, dest): # type: (str, str) -> bool _, rev_options = self.get_url_rev_options(hide_url(url)) if not rev_options.rev: return False if not self.is_commit_id_equal(dest, rev_options.rev): # the current commit is different from rev, # which means rev was something else than a commit hash return False # return False in the rare case rev is both a commit hash # and a tag or a branch; we don't want to cache in that case # because that branch/tag could point to something else in the future is_tag_or_branch = bool( self.get_revision_sha(dest, rev_options.rev)[0] ) return not is_tag_or_branch def get_git_version(self): VERSION_PFX = 'git version ' version = self.run_command(['version']) if version.startswith(VERSION_PFX): version = version[len(VERSION_PFX):].split()[0] else: version = '' # get first 3 positions of the git version because # on windows it is x.y.z.windows.t, and this parses as # LegacyVersion which always smaller than a Version. version = '.'.join(version.split('.')[:3]) return parse_version(version) @classmethod def get_current_branch(cls, location): """ Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). """ # git-symbolic-ref exits with empty stdout if "HEAD" is a detached # HEAD rather than a symbolic ref. In addition, the -q causes the # command to exit with status code 1 instead of 128 in this case # and to suppress the message to stderr. args = ['symbolic-ref', '-q', 'HEAD'] output = cls.run_command( args, extra_ok_returncodes=(1, ), cwd=location, ) ref = output.strip() if ref.startswith('refs/heads/'): return ref[len('refs/heads/'):] return None def export(self, location, url): # type: (str, HiddenText) -> None """Export the Git repository at the url to the destination location""" if not location.endswith('/'): location = location + '/' with TempDirectory(kind="export") as temp_dir: self.unpack(temp_dir.path, url=url) self.run_command( ['checkout-index', '-a', '-f', '--prefix', location], cwd=temp_dir.path ) @classmethod def get_revision_sha(cls, dest, rev): """ Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. """ # Pass rev to pre-filter the list. output = '' try: output = cls.run_command(['show-ref', rev], cwd=dest) except SubProcessError: pass refs = {} for line in output.strip().splitlines(): try: sha, ref = line.split() except ValueError: # Include the offending line to simplify troubleshooting if # this error ever occurs. raise ValueError('unexpected show-ref line: {!r}'.format(line)) refs[ref] = sha branch_ref = 'refs/remotes/origin/{}'.format(rev) tag_ref = 'refs/tags/{}'.format(rev) sha = refs.get(branch_ref) if sha is not None: return (sha, True) sha = refs.get(tag_ref) return (sha, False) @classmethod def resolve_revision(cls, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> RevOptions """ Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. """ rev = rev_options.arg_rev # The arg_rev property's implementation for Git ensures that the # rev return value is always non-None. assert rev is not None sha, is_branch = cls.get_revision_sha(dest, rev) if sha is not None: rev_options = rev_options.make_new(sha) rev_options.branch_name = rev if is_branch else None return rev_options # Do not show a warning for the common case of something that has # the form of a Git commit hash. if not looks_like_hash(rev): logger.warning( "Did not find branch or tag '%s', assuming revision or ref.", rev, ) if not rev.startswith('refs/'): return rev_options # If it looks like a ref, we have to fetch it explicitly. cls.run_command( make_command('fetch', '-q', url, rev_options.to_args()), cwd=dest, ) # Change the revision to the SHA of the ref we fetched sha = cls.get_revision(dest, rev='FETCH_HEAD') rev_options = rev_options.make_new(sha) return rev_options @classmethod def is_commit_id_equal(cls, dest, name): """ Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name. """ if not name: # Then avoid an unnecessary subprocess call. return False return cls.get_revision(dest) == name def fetch_new(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None rev_display = rev_options.to_display() logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest)) self.run_command(make_command('clone', '-q', url, dest)) if rev_options.rev: # Then a specific revision was requested. rev_options = self.resolve_revision(dest, url, rev_options) branch_name = getattr(rev_options, 'branch_name', None) if branch_name is None: # Only do a checkout if the current commit id doesn't match # the requested revision. if not self.is_commit_id_equal(dest, rev_options.rev): cmd_args = make_command( 'checkout', '-q', rev_options.to_args(), ) self.run_command(cmd_args, cwd=dest) elif self.get_current_branch(dest) != branch_name: # Then a specific branch was requested, and that branch # is not yet checked out. track_branch = 'origin/{}'.format(branch_name) cmd_args = [ 'checkout', '-b', branch_name, '--track', track_branch, ] self.run_command(cmd_args, cwd=dest) #: repo may contain submodules self.update_submodules(dest) def switch(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None self.run_command( make_command('config', 'remote.origin.url', url), cwd=dest, ) cmd_args = make_command('checkout', '-q', rev_options.to_args()) self.run_command(cmd_args, cwd=dest) self.update_submodules(dest) def update(self, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> None # First fetch changes from the default remote if self.get_git_version() >= parse_version('1.9.0'): # fetch tags in addition to everything else self.run_command(['fetch', '-q', '--tags'], cwd=dest) else: self.run_command(['fetch', '-q'], cwd=dest) # Then reset to wanted revision (maybe even origin/master) rev_options = self.resolve_revision(dest, url, rev_options) cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args()) self.run_command(cmd_args, cwd=dest) #: update submodules self.update_submodules(dest) @classmethod def get_remote_url(cls, location): """ Return URL of the first remote encountered. Raises RemoteNotFoundError if the repository does not have a remote url configured. """ # We need to pass 1 for extra_ok_returncodes since the command # exits with return code 1 if there are no matching lines. stdout = cls.run_command( ['config', '--get-regexp', r'remote\..*\.url'], extra_ok_returncodes=(1, ), cwd=location, ) remotes = stdout.splitlines() try: found_remote = remotes[0] except IndexError: raise RemoteNotFoundError for remote in remotes: if remote.startswith('remote.origin.url '): found_remote = remote break url = found_remote.split(' ')[1] return url.strip() @classmethod def get_revision(cls, location, rev=None): if rev is None: rev = 'HEAD' current_rev = cls.run_command( ['rev-parse', rev], cwd=location, ) return current_rev.strip() @classmethod def get_subdirectory(cls, location): """ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. """ # find the repo root git_dir = cls.run_command( ['rev-parse', '--git-dir'], cwd=location).strip() if not os.path.isabs(git_dir): git_dir = os.path.join(location, git_dir) repo_root = os.path.abspath(os.path.join(git_dir, '..')) return find_path_to_setup_from_repo_root(location, repo_root) @classmethod def get_url_rev_and_auth(cls, url): # type: (str) -> Tuple[str, Optional[str], AuthInfo] """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. """ # Works around an apparent Git bug # (see https://article.gmane.org/gmane.comp.version-control.git/146500) scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = ( initial_slashes + urllib_request.url2pathname(path) .replace('\\', '/').lstrip('/') ) url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit( (scheme[after_plus:], netloc, newpath, query, fragment), ) if '://' not in url: assert 'file:' not in url url = url.replace('git+', 'git+ssh://') url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url) url = url.replace('ssh://', '') else: url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url) return url, rev, user_pass @classmethod def update_submodules(cls, location): if not os.path.exists(os.path.join(location, '.gitmodules')): return cls.run_command( ['submodule', 'update', '--init', '--recursive', '-q'], cwd=location, ) @classmethod def get_repository_root(cls, location): loc = super(Git, cls).get_repository_root(location) if loc: return loc try: r = cls.run_command( ['rev-parse', '--show-toplevel'], cwd=location, log_failed_cmd=False, ) except BadCommand: logger.debug("could not determine if %s is under git control " "because git is not available", location) return None except SubProcessError: return None return os.path.normpath(r.rstrip('\r\n')) vcs.register(Git) vcs/__init__.py000064400000001151152347654150007462 0ustar00# Expose a limited set of classes and functions so callers outside of # the vcs package don't need to import deeper than `pip._internal.vcs`. # (The test directory and imports protected by MYPY_CHECK_RUNNING may # still need to import from a vcs sub-package.) # Import all vcs modules to register each VCS in the VcsSupport object. import pip._internal.vcs.bazaar import pip._internal.vcs.git import pip._internal.vcs.mercurial import pip._internal.vcs.subversion # noqa: F401 from pip._internal.vcs.versioncontrol import ( # noqa: F401 RemoteNotFoundError, is_url, make_vcs_requirement_url, vcs, ) download.py000064400000050505152347654150006746 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import cgi import logging import mimetypes import os import re import shutil import sys from pip._vendor import requests from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response from pip._vendor.six import PY2 from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.exceptions import HashMismatch, InstallationError from pip._internal.models.index import PyPI from pip._internal.network.session import PipSession from pip._internal.utils.encoding import auto_decode from pip._internal.utils.filesystem import copy2_fixed from pip._internal.utils.misc import ( ask_path_exists, backup_dir, consume, display_path, format_size, hide_url, path_to_display, rmtree, splitext, ) from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.ui import DownloadProgressProvider from pip._internal.utils.unpacking import unpack_file from pip._internal.utils.urls import get_url_scheme from pip._internal.vcs import vcs if MYPY_CHECK_RUNNING: from typing import ( IO, Callable, List, Optional, Text, Tuple, ) from mypy_extensions import TypedDict from pip._internal.models.link import Link from pip._internal.utils.hashes import Hashes from pip._internal.vcs.versioncontrol import VersionControl if PY2: CopytreeKwargs = TypedDict( 'CopytreeKwargs', { 'ignore': Callable[[str, List[str]], List[str]], 'symlinks': bool, }, total=False, ) else: CopytreeKwargs = TypedDict( 'CopytreeKwargs', { 'copy_function': Callable[[str, str], None], 'ignore': Callable[[str, List[str]], List[str]], 'ignore_dangling_symlinks': bool, 'symlinks': bool, }, total=False, ) __all__ = ['get_file_content', 'unpack_vcs_link', 'unpack_file_url', 'unpack_http_url', 'unpack_url', 'parse_content_disposition', 'sanitize_content_filename'] logger = logging.getLogger(__name__) def get_file_content(url, comes_from=None, session=None): # type: (str, Optional[str], Optional[PipSession]) -> Tuple[str, Text] """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. :param url: File path or url. :param comes_from: Origin description of requirements. :param session: Instance of pip.download.PipSession. """ if session is None: raise TypeError( "get_file_content() missing 1 required keyword argument: 'session'" ) scheme = get_url_scheme(url) if scheme in ['http', 'https']: # FIXME: catch some errors resp = session.get(url) resp.raise_for_status() return resp.url, resp.text elif scheme == 'file': if comes_from and comes_from.startswith('http'): raise InstallationError( 'Requirements file %s references URL %s, which is local' % (comes_from, url)) path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib_parse.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path try: with open(url, 'rb') as f: content = auto_decode(f.read()) except IOError as exc: raise InstallationError( 'Could not open requirements file: %s' % str(exc) ) return url, content _url_slash_drive_re = re.compile(r'/*([a-z])\|', re.I) def unpack_vcs_link(link, location): # type: (Link, str) -> None vcs_backend = _get_used_vcs_backend(link) assert vcs_backend is not None vcs_backend.unpack(location, url=hide_url(link.url)) def _get_used_vcs_backend(link): # type: (Link) -> Optional[VersionControl] """ Return a VersionControl object or None. """ for vcs_backend in vcs.backends: if link.scheme in vcs_backend.schemes: return vcs_backend return None def _progress_indicator(iterable, *args, **kwargs): return iterable def _download_url( resp, # type: Response link, # type: Link content_file, # type: IO hashes, # type: Optional[Hashes] progress_bar # type: str ): # type: (...) -> None try: total_length = int(resp.headers['content-length']) except (ValueError, KeyError, TypeError): total_length = 0 cached_resp = getattr(resp, "from_cache", False) if logger.getEffectiveLevel() > logging.INFO: show_progress = False elif cached_resp: show_progress = False elif total_length > (40 * 1000): show_progress = True elif not total_length: show_progress = True else: show_progress = False show_url = link.show_url def resp_read(chunk_size): try: # Special case for urllib3. for chunk in resp.raw.stream( chunk_size, # We use decode_content=False here because we don't # want urllib3 to mess with the raw bytes we get # from the server. If we decompress inside of # urllib3 then we cannot verify the checksum # because the checksum will be of the compressed # file. This breakage will only occur if the # server adds a Content-Encoding header, which # depends on how the server was configured: # - Some servers will notice that the file isn't a # compressible file and will leave the file alone # and with an empty Content-Encoding # - Some servers will notice that the file is # already compressed and will leave the file # alone and will add a Content-Encoding: gzip # header # - Some servers won't notice anything at all and # will take a file that's already been compressed # and compress it again and set the # Content-Encoding: gzip header # # By setting this not to decode automatically we # hope to eliminate problems with the second case. decode_content=False): yield chunk except AttributeError: # Standard file-like object. while True: chunk = resp.raw.read(chunk_size) if not chunk: break yield chunk def written_chunks(chunks): for chunk in chunks: content_file.write(chunk) yield chunk progress_indicator = _progress_indicator if link.netloc == PyPI.netloc: url = show_url else: url = link.url_without_fragment if show_progress: # We don't show progress on cached responses progress_indicator = DownloadProgressProvider(progress_bar, max=total_length) if total_length: logger.info("Downloading %s (%s)", url, format_size(total_length)) else: logger.info("Downloading %s", url) elif cached_resp: logger.info("Using cached %s", url) else: logger.info("Downloading %s", url) downloaded_chunks = written_chunks( progress_indicator( resp_read(CONTENT_CHUNK_SIZE), CONTENT_CHUNK_SIZE ) ) if hashes: hashes.check_against_chunks(downloaded_chunks) else: consume(downloaded_chunks) def _copy_file(filename, location, link): copy = True download_location = os.path.join(location, link.filename) if os.path.exists(download_location): response = ask_path_exists( 'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)abort' % display_path(download_location), ('i', 'w', 'b', 'a')) if response == 'i': copy = False elif response == 'w': logger.warning('Deleting %s', display_path(download_location)) os.remove(download_location) elif response == 'b': dest_file = backup_dir(download_location) logger.warning( 'Backing up %s to %s', display_path(download_location), display_path(dest_file), ) shutil.move(download_location, dest_file) elif response == 'a': sys.exit(-1) if copy: shutil.copy(filename, download_location) logger.info('Saved %s', display_path(download_location)) def unpack_http_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] session=None, # type: Optional[PipSession] hashes=None, # type: Optional[Hashes] progress_bar="on" # type: str ): # type: (...) -> None if session is None: raise TypeError( "unpack_http_url() missing 1 required keyword argument: 'session'" ) with TempDirectory(kind="unpack") as temp_dir: # If a download dir is specified, is the file already downloaded there? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir(link, download_dir, hashes) if already_downloaded_path: from_path = already_downloaded_path content_type = mimetypes.guess_type(from_path)[0] else: # let's download to a tmp dir from_path, content_type = _download_http_url(link, session, temp_dir.path, hashes, progress_bar) # unpack the archive to the build dir location. even when only # downloading archives, they have to be unpacked to parse dependencies unpack_file(from_path, location, content_type) # a download dir is specified; let's copy the archive there if download_dir and not already_downloaded_path: _copy_file(from_path, download_dir, link) if not already_downloaded_path: os.unlink(from_path) def _copy2_ignoring_special_files(src, dest): # type: (str, str) -> None """Copying special files is not supported, but as a convenience to users we skip errors copying them. This supports tools that may create e.g. socket files in the project source directory. """ try: copy2_fixed(src, dest) except shutil.SpecialFileError as e: # SpecialFileError may be raised due to either the source or # destination. If the destination was the cause then we would actually # care, but since the destination directory is deleted prior to # copy we ignore all of them assuming it is caused by the source. logger.warning( "Ignoring special file error '%s' encountered copying %s to %s.", str(e), path_to_display(src), path_to_display(dest), ) def _copy_source_tree(source, target): # type: (str, str) -> None target_abspath = os.path.abspath(target) target_basename = os.path.basename(target_abspath) target_dirname = os.path.dirname(target_abspath) def ignore(d, names): skipped = [] # type: List[str] if d == source: # Pulling in those directories can potentially be very slow, # exclude the following directories if they appear in the top # level dir (and only it). # See discussion at https://github.com/pypa/pip/pull/6770 skipped += ['.tox', '.nox'] if os.path.abspath(d) == target_dirname: # Prevent an infinite recursion if the target is in source. # This can happen when TMPDIR is set to ${PWD}/... # and we copy PWD to TMPDIR. skipped += [target_basename] return skipped kwargs = dict(ignore=ignore, symlinks=True) # type: CopytreeKwargs if not PY2: # Python 2 does not support copy_function, so we only ignore # errors on special file copy in Python 3. kwargs['copy_function'] = _copy2_ignoring_special_files shutil.copytree(source, target, **kwargs) def unpack_file_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] hashes=None # type: Optional[Hashes] ): # type: (...) -> None """Unpack link into location. If download_dir is provided and link points to a file, make a copy of the link file inside download_dir. """ link_path = link.file_path # If it's a url to a local directory if link.is_existing_dir(): if os.path.isdir(location): rmtree(location) _copy_source_tree(link_path, location) if download_dir: logger.info('Link is a directory, ignoring download_dir') return # If --require-hashes is off, `hashes` is either empty, the # link's embedded hash, or MissingHashes; it is required to # match. If --require-hashes is on, we are satisfied by any # hash in `hashes` matching: a URL-based or an option-based # one; no internet-sourced hash will be in `hashes`. if hashes: hashes.check_against_path(link_path) # If a download dir is specified, is the file already there and valid? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir(link, download_dir, hashes) if already_downloaded_path: from_path = already_downloaded_path else: from_path = link_path content_type = mimetypes.guess_type(from_path)[0] # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies unpack_file(from_path, location, content_type) # a download dir is specified and not already downloaded if download_dir and not already_downloaded_path: _copy_file(from_path, download_dir, link) def unpack_url( link, # type: Link location, # type: str download_dir=None, # type: Optional[str] session=None, # type: Optional[PipSession] hashes=None, # type: Optional[Hashes] progress_bar="on" # type: str ): # type: (...) -> None """Unpack link. If link is a VCS link: if only_download, export into download_dir and ignore location else unpack into location for other types of link: - unpack into location - if download_dir, copy the file into download_dir - if only_download, mark location for deletion :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. """ # non-editable vcs urls if link.is_vcs: unpack_vcs_link(link, location) # file urls elif link.is_file: unpack_file_url(link, location, download_dir, hashes=hashes) # http urls else: if session is None: session = PipSession() unpack_http_url( link, location, download_dir, session, hashes=hashes, progress_bar=progress_bar ) def sanitize_content_filename(filename): # type: (str) -> str """ Sanitize the "filename" value from a Content-Disposition header. """ return os.path.basename(filename) def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = params.get('filename') if filename: # We need to sanitize the filename to prevent directory traversal # in case the filename contains ".." path parts. filename = sanitize_content_filename(filename) return filename or default_filename def _download_http_url( link, # type: Link session, # type: PipSession temp_dir, # type: str hashes, # type: Optional[Hashes] progress_bar # type: str ): # type: (...) -> Tuple[str, str] """Download link url into temp_dir using provided session""" target_url = link.url.split('#', 1)[0] try: resp = session.get( target_url, # We use Accept-Encoding: identity here because requests # defaults to accepting compressed responses. This breaks in # a variety of ways depending on how the server is configured. # - Some servers will notice that the file isn't a compressible # file and will leave the file alone and with an empty # Content-Encoding # - Some servers will notice that the file is already # compressed and will leave the file alone and will add a # Content-Encoding: gzip header # - Some servers won't notice anything at all and will take # a file that's already been compressed and compress it again # and set the Content-Encoding: gzip header # By setting this to request only the identity encoding We're # hoping to eliminate the third case. Hopefully there does not # exist a server which when given a file will notice it is # already compressed and that you're not asking for a # compressed file and will then decompress it before sending # because if that's the case I don't think it'll ever be # possible to make this work. headers={"Accept-Encoding": "identity"}, stream=True, ) resp.raise_for_status() except requests.HTTPError as exc: logger.critical( "HTTP error %s while getting %s", exc.response.status_code, link, ) raise content_type = resp.headers.get('content-type', '') filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension(content_type) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext file_path = os.path.join(temp_dir, filename) with open(file_path, 'wb') as content_file: _download_url(resp, link, content_file, hashes, progress_bar) return file_path, content_type def _check_download_dir(link, download_dir, hashes): # type: (Link, str, Optional[Hashes]) -> Optional[str] """ Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None """ download_path = os.path.join(download_dir, link.filename) if not os.path.exists(download_path): return None # If already downloaded, does its hash match? logger.info('File was already downloaded %s', download_path) if hashes: try: hashes.check_against_path(download_path) except HashMismatch: logger.warning( 'Previously-downloaded file %s has bad hash. ' 'Re-downloading.', download_path ) os.unlink(download_path) return None return download_path configuration.py000064400000033443152347654150010010 0ustar00"""Configuration management setup Some terminology: - name As written in config files. - value Value associated with a name - key Name combined with it's section (section.name) - variant A single word describing where the configuration key-value pair came from """ import locale import logging import os import sys from pip._vendor.six.moves import configparser from pip._internal.exceptions import ( ConfigurationError, ConfigurationFileCouldNotBeLoaded, ) from pip._internal.utils import appdirs from pip._internal.utils.compat import WINDOWS, expanduser from pip._internal.utils.misc import ensure_dir, enum from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Any, Dict, Iterable, List, NewType, Optional, Tuple ) RawConfigParser = configparser.RawConfigParser # Shorthand Kind = NewType("Kind", str) logger = logging.getLogger(__name__) # NOTE: Maybe use the optionx attribute to normalize keynames. def _normalize_name(name): # type: (str) -> str """Make a name consistent regardless of source (environment or file) """ name = name.lower().replace('_', '-') if name.startswith('--'): name = name[2:] # only prefer long opts return name def _disassemble_key(name): # type: (str) -> List[str] if "." not in name: error_message = ( "Key does not contain dot separated section and key. " "Perhaps you wanted to use 'global.{}' instead?" ).format(name) raise ConfigurationError(error_message) return name.split(".", 1) # The kinds of configurations there are. kinds = enum( USER="user", # User Specific GLOBAL="global", # System Wide SITE="site", # [Virtual] Environment Specific ENV="env", # from PIP_CONFIG_FILE ENV_VAR="env-var", # from Environment Variables ) CONFIG_BASENAME = 'pip.ini' if WINDOWS else 'pip.conf' def get_configuration_files(): # type: () -> Dict[Kind, List[str]] global_config_files = [ os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs('pip') ] site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME) legacy_config_file = os.path.join( expanduser('~'), 'pip' if WINDOWS else '.pip', CONFIG_BASENAME, ) new_config_file = os.path.join( appdirs.user_config_dir("pip"), CONFIG_BASENAME ) return { kinds.GLOBAL: global_config_files, kinds.SITE: [site_config_file], kinds.USER: [legacy_config_file, new_config_file], } class Configuration(object): """Handles management of configuration. Provides an interface to accessing and managing configuration files. This class converts provides an API that takes "section.key-name" style keys and stores the value associated with it as "key-name" under the section "section". This allows for a clean interface wherein the both the section and the key-name are preserved in an easy to manage form in the configuration files and the data stored is also nice. """ def __init__(self, isolated, load_only=None): # type: (bool, Optional[Kind]) -> None super(Configuration, self).__init__() _valid_load_only = [kinds.USER, kinds.GLOBAL, kinds.SITE, None] if load_only not in _valid_load_only: raise ConfigurationError( "Got invalid value for load_only - should be one of {}".format( ", ".join(map(repr, _valid_load_only[:-1])) ) ) self.isolated = isolated self.load_only = load_only # The order here determines the override order. self._override_order = [ kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR ] self._ignore_env_names = ["version", "help"] # Because we keep track of where we got the data from self._parsers = { variant: [] for variant in self._override_order } # type: Dict[Kind, List[Tuple[str, RawConfigParser]]] self._config = { variant: {} for variant in self._override_order } # type: Dict[Kind, Dict[str, Any]] self._modified_parsers = [] # type: List[Tuple[str, RawConfigParser]] def load(self): # type: () -> None """Loads configuration from configuration files and environment """ self._load_config_files() if not self.isolated: self._load_environment_vars() def get_file_to_edit(self): # type: () -> Optional[str] """Returns the file with highest priority in configuration """ assert self.load_only is not None, \ "Need to be specified a file to be editing" try: return self._get_parser_to_modify()[0] except IndexError: return None def items(self): # type: () -> Iterable[Tuple[str, Any]] """Returns key-value pairs like dict.items() representing the loaded configuration """ return self._dictionary.items() def get_value(self, key): # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError("No such key - {}".format(key)) def set_value(self, key, value): # type: (str, Any) -> None """Modify a value in the configuration. """ self._ensure_have_load_only() assert self.load_only fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _disassemble_key(key) # Modify the parser and the configuration if not parser.has_section(section): parser.add_section(section) parser.set(section, name, value) self._config[self.load_only][key] = value self._mark_as_modified(fname, parser) def unset_value(self, key): # type: (str) -> None """Unset a value in the configuration.""" self._ensure_have_load_only() assert self.load_only if key not in self._config[self.load_only]: raise ConfigurationError("No such key - {}".format(key)) fname, parser = self._get_parser_to_modify() if parser is not None: section, name = _disassemble_key(key) if not (parser.has_section(section) and parser.remove_option(section, name)): # The option was not removed. raise ConfigurationError( "Fatal Internal error [id=1]. Please report as a bug." ) # The section may be empty after the option was removed. if not parser.items(section): parser.remove_section(section) self._mark_as_modified(fname, parser) del self._config[self.load_only][key] def save(self): # type: () -> None """Save the current in-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(fname)) with open(fname, "w") as f: parser.write(f) # # Private routines # def _ensure_have_load_only(self): # type: () -> None if self.load_only is None: raise ConfigurationError("Needed a specific file to be modifying.") logger.debug("Will be working with %s variant only", self.load_only) @property def _dictionary(self): # type: () -> Dict[str, Any] """A dictionary representing the loaded configuration. """ # NOTE: Dictionaries are not populated if not loaded. So, conditionals # are not needed here. retval = {} for variant in self._override_order: retval.update(self._config[variant]) return retval def _load_config_files(self): # type: () -> None """Loads configuration from configuration files """ config_files = dict(self.iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( "Skipping loading configuration files due to " "environment's PIP_CONFIG_FILE being os.devnull" ) return for variant, files in config_files.items(): for fname in files: # If there's specific variant set in `load_only`, load only # that variant, not the others. if self.load_only is not None and variant != self.load_only: logger.debug( "Skipping file '%s' (variant: %s)", fname, variant ) continue parser = self._load_file(variant, fname) # Keeping track of the parsers used self._parsers[variant].append((fname, parser)) def _load_file(self, variant, fname): # type: (Kind, str) -> RawConfigParser logger.debug("For variant '%s', will try loading '%s'", variant, fname) parser = self._construct_parser(fname) for section in parser.sections(): items = parser.items(section) self._config[variant].update(self._normalized_keys(section, items)) return parser def _construct_parser(self, fname): # type: (str) -> RawConfigParser parser = configparser.RawConfigParser() # If there is no such file, don't bother reading it but create the # parser anyway, to hold the data. # Doing this is useful when modifying and saving files, where we don't # need to construct a parser. if os.path.exists(fname): try: parser.read(fname) except UnicodeDecodeError: # See https://github.com/pypa/pip/issues/4963 raise ConfigurationFileCouldNotBeLoaded( reason="contains invalid {} characters".format( locale.getpreferredencoding(False) ), fname=fname, ) except configparser.Error as error: # See https://github.com/pypa/pip/issues/4893 raise ConfigurationFileCouldNotBeLoaded(error=error) return parser def _load_environment_vars(self): # type: () -> None """Loads configuration from environment variables """ self._config[kinds.ENV_VAR].update( self._normalized_keys(":env:", self.get_environ_vars()) ) def _normalized_keys(self, section, items): # type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any] """Normalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment. """ normalized = {} for name, val in items: key = section + "." + _normalize_name(name) normalized[key] = val return normalized def get_environ_vars(self): # type: () -> Iterable[Tuple[str, str]] """Returns a generator with all environmental vars with prefix PIP_""" for key, val in os.environ.items(): should_be_yielded = ( key.startswith("PIP_") and key[4:].lower() not in self._ignore_env_names ) if should_be_yielded: yield key[4:].lower(), val # XXX: This is patched in the tests. def iter_config_files(self): # type: () -> Iterable[Tuple[Kind, List[str]]] """Yields variant and configuration files associated with it. This should be treated like items of a dictionary. """ # SMELL: Move the conditions out of this function # environment variables have the lowest priority config_file = os.environ.get('PIP_CONFIG_FILE', None) if config_file is not None: yield kinds.ENV, [config_file] else: yield kinds.ENV, [] config_files = get_configuration_files() # at the base we have any global configuration yield kinds.GLOBAL, config_files[kinds.GLOBAL] # per-user configuration next should_load_user_config = not self.isolated and not ( config_file and os.path.exists(config_file) ) if should_load_user_config: # The legacy config file is overridden by the new config file yield kinds.USER, config_files[kinds.USER] # finally virtualenv configuration first trumping others yield kinds.SITE, config_files[kinds.SITE] def get_values_in_config(self, variant): # type: (Kind) -> Dict[str, Any] """Get values present in a config file""" return self._config[variant] def _get_parser_to_modify(self): # type: () -> Tuple[str, RawConfigParser] # Determine which parser to modify assert self.load_only parsers = self._parsers[self.load_only] if not parsers: # This should not happen if everything works correctly. raise ConfigurationError( "Fatal Internal error [id=2]. Please report as a bug." ) # Use the highest priority parser. return parsers[-1] # XXX: This is patched in the tests. def _mark_as_modified(self, fname, parser): # type: (str, RawConfigParser) -> None file_parser_tuple = (fname, parser) if file_parser_tuple not in self._modified_parsers: self._modified_parsers.append(file_parser_tuple) def __repr__(self): # type: () -> str return "{}({!r})".format(self.__class__.__name__, self._dictionary) utils/typing.py000064400000002571152347654150007611 0ustar00"""For neatly implementing static typing in pip. `mypy` - the static type analysis tool we use - uses the `typing` module, which provides core functionality fundamental to mypy's functioning. Generally, `typing` would be imported at runtime and used in that fashion - it acts as a no-op at runtime and does not have any run-time overhead by design. As it turns out, `typing` is not vendorable - it uses separate sources for Python 2/Python 3. Thus, this codebase can not expect it to be present. To work around this, mypy allows the typing import to be behind a False-y optional to prevent it from running at runtime and type-comments can be used to remove the need for the types to be accessible directly during runtime. This module provides the False-y guard in a nicely named fashion so that a curious maintainer can reach here to read this. In pip, all static-typing related imports should be guarded as follows: from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 """ MYPY_CHECK_RUNNING = False if MYPY_CHECK_RUNNING: from typing import cast else: # typing's cast() is needed at runtime, but we don't want to import typing. # Thus, we use a dummy no-op version, which we tell mypy to ignore. def cast(type_, value): # type: ignore return value utils/logging.py000064400000031445152347654150007727 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import contextlib import errno import logging import logging.handlers import os import sys from logging import Filter, getLogger from pip._vendor.six import PY2 from pip._internal.utils.compat import WINDOWS from pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX from pip._internal.utils.misc import ensure_dir try: import threading except ImportError: import dummy_threading as threading # type: ignore try: # Use "import as" and set colorama in the else clause to avoid mypy # errors and get the following correct revealed type for colorama: # `Union[_importlib_modulespec.ModuleType, None]` # Otherwise, we get an error like the following in the except block: # > Incompatible types in assignment (expression has type "None", # variable has type Module) # TODO: eliminate the need to use "import as" once mypy addresses some # of its issues with conditional imports. Here is an umbrella issue: # https://github.com/python/mypy/issues/1297 from pip._vendor import colorama as _colorama # Lots of different errors can come from this, including SystemError and # ImportError. except Exception: colorama = None else: # Import Fore explicitly rather than accessing below as colorama.Fore # to avoid the following error running mypy: # > Module has no attribute "Fore" # TODO: eliminate the need to import Fore once mypy addresses some of its # issues with conditional imports. This particular case could be an # instance of the following issue (but also see the umbrella issue above): # https://github.com/python/mypy/issues/3500 from pip._vendor.colorama import Fore colorama = _colorama _log_state = threading.local() subprocess_logger = getLogger('pip.subprocessor') class BrokenStdoutLoggingError(Exception): """ Raised if BrokenPipeError occurs for the stdout stream while logging. """ pass # BrokenPipeError does not exist in Python 2 and, in addition, manifests # differently in Windows and non-Windows. if WINDOWS: # In Windows, a broken pipe can show up as EINVAL rather than EPIPE: # https://bugs.python.org/issue19612 # https://bugs.python.org/issue30418 if PY2: def _is_broken_pipe_error(exc_class, exc): """See the docstring for non-Windows Python 3 below.""" return (exc_class is IOError and exc.errno in (errno.EINVAL, errno.EPIPE)) else: # In Windows, a broken pipe IOError became OSError in Python 3. def _is_broken_pipe_error(exc_class, exc): """See the docstring for non-Windows Python 3 below.""" return ((exc_class is BrokenPipeError) or # noqa: F821 (exc_class is OSError and exc.errno in (errno.EINVAL, errno.EPIPE))) elif PY2: def _is_broken_pipe_error(exc_class, exc): """See the docstring for non-Windows Python 3 below.""" return (exc_class is IOError and exc.errno == errno.EPIPE) else: # Then we are in the non-Windows Python 3 case. def _is_broken_pipe_error(exc_class, exc): """ Return whether an exception is a broken pipe error. Args: exc_class: an exception class. exc: an exception instance. """ return (exc_class is BrokenPipeError) # noqa: F821 @contextlib.contextmanager def indent_log(num=2): """ A context manager which will cause the log output to be indented for any log messages emitted inside it. """ # For thread-safety _log_state.indentation = get_indentation() _log_state.indentation += num try: yield finally: _log_state.indentation -= num def get_indentation(): return getattr(_log_state, 'indentation', 0) class IndentingFormatter(logging.Formatter): def __init__(self, *args, **kwargs): """ A logging.Formatter that obeys the indent_log() context manager. :param add_timestamp: A bool indicating output lines should be prefixed with their record's timestamp. """ self.add_timestamp = kwargs.pop("add_timestamp", False) super(IndentingFormatter, self).__init__(*args, **kwargs) def get_message_start(self, formatted, levelno): """ Return the start of the formatted log message (not counting the prefix to add to each line). """ if levelno < logging.WARNING: return '' if formatted.startswith(DEPRECATION_MSG_PREFIX): # Then the message already has a prefix. We don't want it to # look like "WARNING: DEPRECATION: ...." return '' if levelno < logging.ERROR: return 'WARNING: ' return 'ERROR: ' def format(self, record): """ Calls the standard formatter, but will indent all of the log message lines by our current indentation level. """ formatted = super(IndentingFormatter, self).format(record) message_start = self.get_message_start(formatted, record.levelno) formatted = message_start + formatted prefix = '' if self.add_timestamp: # TODO: Use Formatter.default_time_format after dropping PY2. t = self.formatTime(record, "%Y-%m-%dT%H:%M:%S") prefix = '{t},{record.msecs:03.0f} '.format(**locals()) prefix += " " * get_indentation() formatted = "".join([ prefix + line for line in formatted.splitlines(True) ]) return formatted def _color_wrap(*colors): def wrapped(inp): return "".join(list(colors) + [inp, colorama.Style.RESET_ALL]) return wrapped class ColorizedStreamHandler(logging.StreamHandler): # Don't build up a list of colors if we don't have colorama if colorama: COLORS = [ # This needs to be in order from highest logging level to lowest. (logging.ERROR, _color_wrap(Fore.RED)), (logging.WARNING, _color_wrap(Fore.YELLOW)), ] else: COLORS = [] def __init__(self, stream=None, no_color=None): logging.StreamHandler.__init__(self, stream) self._no_color = no_color if WINDOWS and colorama: self.stream = colorama.AnsiToWin32(self.stream) def _using_stdout(self): """ Return whether the handler is using sys.stdout. """ if WINDOWS and colorama: # Then self.stream is an AnsiToWin32 object. return self.stream.wrapped is sys.stdout return self.stream is sys.stdout def should_color(self): # Don't colorize things if we do not have colorama or if told not to if not colorama or self._no_color: return False real_stream = ( self.stream if not isinstance(self.stream, colorama.AnsiToWin32) else self.stream.wrapped ) # If the stream is a tty we should color it if hasattr(real_stream, "isatty") and real_stream.isatty(): return True # If we have an ANSI term we should color it if os.environ.get("TERM") == "ANSI": return True # If anything else we should not color it return False def format(self, record): msg = logging.StreamHandler.format(self, record) if self.should_color(): for level, color in self.COLORS: if record.levelno >= level: msg = color(msg) break return msg # The logging module says handleError() can be customized. def handleError(self, record): exc_class, exc = sys.exc_info()[:2] # If a broken pipe occurred while calling write() or flush() on the # stdout stream in logging's Handler.emit(), then raise our special # exception so we can handle it in main() instead of logging the # broken pipe error and continuing. if (exc_class and self._using_stdout() and _is_broken_pipe_error(exc_class, exc)): raise BrokenStdoutLoggingError() return super(ColorizedStreamHandler, self).handleError(record) class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler): def _open(self): ensure_dir(os.path.dirname(self.baseFilename)) return logging.handlers.RotatingFileHandler._open(self) class MaxLevelFilter(Filter): def __init__(self, level): self.level = level def filter(self, record): return record.levelno < self.level class ExcludeLoggerFilter(Filter): """ A logging Filter that excludes records from a logger (or its children). """ def filter(self, record): # The base Filter class allows only records from a logger (or its # children). return not super(ExcludeLoggerFilter, self).filter(record) def setup_logging(verbosity, no_color, user_log_file): """Configures and sets up all of the logging Returns the requested logging level, as its integer value. """ # Determine the level to be logging at. if verbosity >= 1: level = "DEBUG" elif verbosity == -1: level = "WARNING" elif verbosity == -2: level = "ERROR" elif verbosity <= -3: level = "CRITICAL" else: level = "INFO" level_number = getattr(logging, level) # The "root" logger should match the "console" level *unless* we also need # to log to a user log file. include_user_log = user_log_file is not None if include_user_log: additional_log_file = user_log_file root_level = "DEBUG" else: additional_log_file = "/dev/null" root_level = level # Disable any logging besides WARNING unless we have DEBUG level logging # enabled for vendored libraries. vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG" # Shorthands for clarity log_streams = { "stdout": "ext://sys.stdout", "stderr": "ext://sys.stderr", } handler_classes = { "stream": "pip._internal.utils.logging.ColorizedStreamHandler", "file": "pip._internal.utils.logging.BetterRotatingFileHandler", } handlers = ["console", "console_errors", "console_subprocess"] + ( ["user_log"] if include_user_log else [] ) logging.config.dictConfig({ "version": 1, "disable_existing_loggers": False, "filters": { "exclude_warnings": { "()": "pip._internal.utils.logging.MaxLevelFilter", "level": logging.WARNING, }, "restrict_to_subprocess": { "()": "logging.Filter", "name": subprocess_logger.name, }, "exclude_subprocess": { "()": "pip._internal.utils.logging.ExcludeLoggerFilter", "name": subprocess_logger.name, }, }, "formatters": { "indent": { "()": IndentingFormatter, "format": "%(message)s", }, "indent_with_timestamp": { "()": IndentingFormatter, "format": "%(message)s", "add_timestamp": True, }, }, "handlers": { "console": { "level": level, "class": handler_classes["stream"], "no_color": no_color, "stream": log_streams["stdout"], "filters": ["exclude_subprocess", "exclude_warnings"], "formatter": "indent", }, "console_errors": { "level": "WARNING", "class": handler_classes["stream"], "no_color": no_color, "stream": log_streams["stderr"], "filters": ["exclude_subprocess"], "formatter": "indent", }, # A handler responsible for logging to the console messages # from the "subprocessor" logger. "console_subprocess": { "level": level, "class": handler_classes["stream"], "no_color": no_color, "stream": log_streams["stderr"], "filters": ["restrict_to_subprocess"], "formatter": "indent", }, "user_log": { "level": "DEBUG", "class": handler_classes["file"], "filename": additional_log_file, "delay": True, "formatter": "indent_with_timestamp", }, }, "root": { "level": root_level, "handlers": handlers, }, "loggers": { "pip._vendor": { "level": vendored_log_level } }, }) return level_number utils/__pycache__/inject_securetransport.cpython-38.pyc000064400000001644152347654150017364 0ustar00U .e*@sdZddlZddZedS)a-A helper module that injects SecureTransport, on import. The import should be done as early as possible, to ensure all requests and sessions (or whatever) are created after injecting SecureTransport. Note that we only do the injection on macOS, when the linked OpenSSL is too old to handle TLSv1.2. Nc CsxtjdkrdSz ddl}Wntk r0YdSX|jdkr@dSzddlm}Wnttfk rjYdSX|dS)Ndarwinri)securetransport) sysplatformssl ImportErrorZOPENSSL_VERSION_NUMBERZpip._vendor.urllib3.contribrOSErrorZinject_into_urllib3)rrr N/usr/lib/python3.8/site-packages/pip/_internal/utils/inject_securetransport.pyinject_securetransport s   r )__doc__rr r r r r s utils/__pycache__/logging.cpython-38.opt-1.pyc000064400000021707152347654150015154 0ustar00U .e2@sddlmZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z ddl m Z ddlmZddlmZz ddlZWnek rddlZYnXzddlmZWnek rdZYnXdd lmZeZeZde_e d ZGd d d eZe r&e rd dZ nddZ ne r6ddZ nddZ ej!d%ddZ"ddZ#Gdddej$Z%ddZ&Gdddej'Z(Gdddej)j*Z+Gdd d eZ,Gd!d"d"eZ-d#d$Z.dS)&)absolute_importN)Filter getLogger)PY2)WINDOWS)DEPRECATION_MSG_PREFIX) ensure_dir)colorama)Forezpip.subprocessorc@seZdZdZdS)BrokenStdoutLoggingErrorzO Raised if BrokenPipeError occurs for the stdout stream while logging. N)__name__ __module__ __qualname____doc__rr?/usr/lib/python3.8/site-packages/pip/_internal/utils/logging.pyr ;sr cCs|tko|jtjtjfkSz1See the docstring for non-Windows Python 3 below.)IOErrorerrnoEINVALEPIPE exc_classexcrrr_is_broken_pipe_errorIsrcCs"|tkp |tko |jtjtjfkSr)BrokenPipeErrorOSErrorrrrrrrrrOscCs|tko|jtjkSr)rrrrrrrrUscCs|tkS)z Return whether an exception is a broken pipe error. Args: exc_class: an exception class. exc: an exception instance. )rrrrrrZsc cs.tj|7_z dVW5tj|8_XdS)zv A context manager which will cause the log output to be indented for any log messages emitted inside it. N) _log_state indentation)Znumrrr indent_loges r cCs ttddS)Nrr)getattrrrrrrget_indentationrsr"cs0eZdZfddZddZfddZZS)IndentingFormattercs$|dd|_tt|j||dS)z A logging.Formatter that obeys the indent_log() context manager. :param add_timestamp: A bool indicating output lines should be prefixed with their record's timestamp. add_timestampFN)popr$superr#__init__)selfargskwargs __class__rrr'xszIndentingFormatter.__init__cCs.|tjkrdS|trdS|tjkr*dSdS)zv Return the start of the formatted log message (not counting the prefix to add to each line). z WARNING: zERROR: )loggingWARNING startswithrERROR)r( formattedlevelnorrrget_message_starts   z$IndentingFormatter.get_message_startcsztt||}|||j}||}d|jrJ||d}d||jfdt7d fdd| dD}|S)z Calls the standard formatter, but will indent all of the log message lines by our current indentation level. r-z%Y-%m-%dT%H:%M:%Sz%s,%03d  csg|] }|qSrr).0lineprefixrr sz-IndentingFormatter.format..T) r&r#formatr4r3r$Z formatTimeZmsecsr"join splitlines)r(recordr2Z message_starttr+r8rr;s zIndentingFormatter.format)r r rr'r4r; __classcell__rrr+rr#vs r#csfdd}|S)Ncsdt|tjjgS)Nr-)r<listr ZStyleZ RESET_ALL)Zinpcolorsrrwrappedsz_color_wrap..wrappedr)rCrDrrBr _color_wraps rEcsheZdZer.ejeejfej eej fgZ ngZ d ddZ ddZ ddZdd Zfd d ZZS) ColorizedStreamHandlerNcCs.tj||||_tr*tr*t|j|_dSN)r. StreamHandlerr' _no_colorrr AnsiToWin32stream)r(rKno_colorrrrr'szColorizedStreamHandler.__init__cCs"trtr|jjtjkS|jtjkS)zA Return whether the handler is using sys.stdout. )rr rKrDsysstdoutr(rrr _using_stdoutsz$ColorizedStreamHandler._using_stdoutcCsXtr |jrdSt|jtjs"|jn|jj}t|dr@|r@dStj ddkrTdSdS)NFisattyTZTERMZANSI) r rI isinstancerKrJrDhasattrrQosenvironget)r(Z real_streamrrr should_colors z#ColorizedStreamHandler.should_colorcCs@tj||}|r<|jD]\}}|j|kr||}qmsglevelZcolorrrrr;s zColorizedStreamHandler.formatcs@tdd\}}|r0|r0t||r0ttt||S)Nr)rMexc_inforPrr r&rF handleError)r(r>rrr+rrr\s  z"ColorizedStreamHandler.handleError)NN)r r rr r.r1rEr ZREDr/ZYELLOWrXr'rPrWr;r\r@rrr+rrFs   rFc@seZdZddZdS)BetterRotatingFileHandlercCs ttj|jtjj|SrG) rrTpathdirnameZ baseFilenamer.handlersRotatingFileHandler_openrOrrrrbszBetterRotatingFileHandler._openN)r r rrbrrrrr]sr]c@seZdZddZddZdS)MaxLevelFiltercCs ||_dSrG)rZ)r(rZrrrr'szMaxLevelFilter.__init__cCs |j|jkSrG)r3rZr(r>rrrfilterszMaxLevelFilter.filterN)r r rr'rerrrrrcsrccs eZdZdZfddZZS)ExcludeLoggerFilterzQ A logging Filter that excludes records from a logger (or its children). cstt|| SrG)r&rfrerdr+rrreszExcludeLoggerFilter.filter)r r rrrer@rrr+rrf srfc Csf|dkrd}n.|dkrd}n |dkr*d}n|dkr8d}nd }tt|}|d k }|r\|}d}nd }|}|d krpdnd}d dd} ddd} dddg|rdgng} tjdddtjddtjddtjddtddtdd d!d"|| d#|| d$d%d&gd'd(d| d#|| d)d%gd'd(|| d#|| d)d*gd'd(d| d+|d d,d-d.|| d/d0d1|iid2|S)3znConfigures and sets up all of the logging Returns the requested logging level, as its integer value. DEBUGr/r1ZCRITICALINFONz /dev/null)rlr1zext://sys.stdoutzext://sys.stderr)rNstderrz2pip._internal.utils.logging.ColorizedStreamHandlerz5pip._internal.utils.logging.BetterRotatingFileHandler)rKfileconsoleconsole_errorsconsole_subprocessuser_logFz*pip._internal.utils.logging.MaxLevelFilter)()rZzlogging.Filter)rsnamez/pip._internal.utils.logging.ExcludeLoggerFilter)exclude_warningsrestrict_to_subprocessexclude_subprocessz %(message)s)rsr;T)rsr;r$)indentindent_with_timestamprKrNrwrurx)rZclassrLrKfilters formatterrmrvrnry)rZrzfilenameZdelayr|)rorprqrr)rZr`z pip._vendorrZ)versionZdisable_existing_loggersr{Z formattersr`rootZloggers)r!r.ZconfigZ dictConfigr/subprocess_loggerrtr#) verbosityrLZ user_log_filerZZ level_numberZinclude_user_logZadditional_log_fileZ root_levelZvendored_log_levelZ log_streamsZhandler_classesr`rrr setup_loggings      $Jr)r)/Z __future__r contextlibrr.Zlogging.handlersrTrMrrZpip._vendor.sixrZpip._internal.utils.compatrZpip._internal.utils.deprecationrZpip._internal.utils.miscrZ threading ImportErrorZdummy_threadingZ pip._vendorr Z _colorama ExceptionZpip._vendor.coloramar Zlocalrrrr rcontextmanagerr r"Z Formatterr#rErHrFr`rar]rcrfrrrrrsT              2K  utils/__pycache__/encoding.cpython-38.opt-1.pyc000064400000002337152347654150015312 0ustar00U .e(@sddlZddlZddlZddlZddlmZerDddlmZmZm Z ej dfej dfej dfej dfejdfejd fejd fgZed Zd d ZdS)N)MYPY_CHECK_RUNNING)ListTupleTextzutf-8zutf-16z utf-16-bez utf-16-lezutf-32z utf-32-bez utf-32-lescoding[:=]\s*([-\w.]+)cCstD],\}}||r|t|d|Sq|dddD]D}|dddkrDt|rDt|dd}||SqD|t dpt S) zCheck a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3N r#asciiF) BOMS startswithlendecodesplit ENCODING_REsearchgroupslocaleZgetpreferredencodingsysgetdefaultencoding)dataZbomencodingliner@/usr/lib/python3.8/site-packages/pip/_internal/utils/encoding.py auto_decodes  r)codecsrrerZpip._internal.utils.typingrtypingrrrBOM_UTF8 BOM_UTF16 BOM_UTF16_BE BOM_UTF16_LE BOM_UTF32 BOM_UTF32_BE BOM_UTF32_LEr compilerrrrrrs   utils/__pycache__/appdirs.cpython-38.opt-1.pyc000064400000017553152347654150015174 0ustar00U .e&&@sdZddlmZddlZddlZddlmZmZddlm Z m Z ddl m Z e r\ddl mZdd Zdd d ZdddZddZddZddZe rzddlZeZWnek reZYnXddZdS)zd This code was taken from https://github.com/ActiveState/appdirs and modified to suit our purposes. )absolute_importN)PY2 text_type)WINDOWS expanduser)MYPY_CHECK_RUNNING)ListcCstr Unix: ~/.cache/ (XDG default) Windows: C:\Users\\AppData\Local\\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. CSIDL_LOCAL_APPDATAZCachedarwinz~/Library/CachesZXDG_CACHE_HOMEz~/.cache)rospathnormpath_get_win_folderr isinstancer_win_path_to_bytesjoinsysplatformrgetenv)appnamer r?/usr/lib/python3.8/site-packages/pip/_internal/utils/appdirs.pyuser_cache_dirs rFcCstr,|r dpd}tjtjt||}ndtjdkrvtjtjt d|rbtjt d|ntjt d|}ntjt dt d|}|S)a Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/ if it exists, else ~/.config/ Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\\ ... ...Application Data\ Win XP (roaming): C:\Documents and Settings\\Local ... ...Settings\Application Data\ Win 7 (not roaming): C:\\Users\\AppData\Local\ Win 7 (roaming): C:\\Users\\AppData\Roaming\ For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/". CSIDL_APPDATAr r z~/Library/Application Support/z ~/.config/Z XDG_DATA_HOMEz~/.local/share) rr r rr rrrisdirrr)rroamingconstr rrr user_data_dirHs,    rTcCsHtrt||d}n2tjdkr&t|}ntdtd}tj||}|S)arReturn full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default True) can be set False to not use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/ Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/". )rr ZXDG_CONFIG_HOMEz ~/.config) rrrrr rrr r)rrr rrruser_config_dir}s  rcstr&tjtd}tj|g}nVtjdkrBtjdg}n:tdd}|rnfdd| tj D}ng}| d|S) aReturn a list of potential user-shared config dirs for this application. "appname" is the name of application. Typical user config directories are: macOS: /Library/Application Support// Unix: /etc or $XDG_CONFIG_DIRS[i]// for each value in $XDG_CONFIG_DIRS Win XP: C:\Documents and Settings\All Users\Application ... ...Data\\ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: Hidden, but writeable on Win 7: C:\ProgramData\\ CSIDL_COMMON_APPDATAr z/Library/Application SupportZXDG_CONFIG_DIRSz/etc/xdgcsg|]}tjt|qSr)r r rr).0xrrr sz$site_config_dirs..z/etc) rr r r rrrrrsplitpathsepappend)rr ZpathlistZxdg_config_dirsrr"rsite_config_dirss     r'cCs:ddl}dddd|}||jd}|||\}}|S)z This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. rNZAppDatazCommon AppDataz Local AppDatarrr z@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)_winregOpenKeyHKEY_CURRENT_USERZ QueryValueEx) csidl_namer)Zshell_folder_namekeyZ directoryZ_typerrr_get_win_folder_from_registrysr.cCsdddd|}td}tj}|jd|dd|d}|D]}t|dkr. If encoding using ASCII and MBCS fails, return the original Unicode path. )ASCIIZMBCS)encodeUnicodeEncodeError LookupError)r encodingrrrrs r)F)T)__doc__Z __future__rr rZpip._vendor.sixrrZpip._internal.utils.compatrrZpip._internal.utils.typingrtypingrrrrr'r.r8r3r ImportErrorrrrrrs*   1 5 ") utils/__pycache__/hashes.cpython-38.opt-1.pyc000064400000010060152347654150014767 0ustar00U .e@sddlmZddlZddlmZmZmZddlmZm Z m Z ddl m Z ddl mZerddlmZmZmZmZmZddlmZerdd lmZn dd lmZd Zd d d gZGdddeZGdddeZdS))absolute_importN) iteritemsiterkeys itervalues) HashMismatch HashMissingInstallationError) read_chunks)MYPY_CHECK_RUNNING)DictListBinaryIONoReturnIterator)PY3)_Hash)_hashZsha256Zsha384Zsha512c@s^eZdZdZdddZeddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS)HasheszaA wrapper that builds multiple hashes at once and checks them against known-good values NcCs|dkr in||_dS)zo :param hashes: A dict of algorithm names pointing to lists of allowed hex digests N)_allowed)selfhashesr>/usr/lib/python3.8/site-packages/pip/_internal/utils/hashes.py__init__,szHashes.__init__cCstdd|jDS)Ncss|]}t|VqdSN)len).0Zdigestsrrr 7sz&Hashes.digest_count..)sumrvaluesrrrr digest_count4szHashes.digest_countcCs||j|gkS)z/Return whether the given hex digest is allowed.)rget)r hash_nameZ hex_digestrrris_hash_allowed9szHashes.is_hash_allowedc Csi}t|jD]<}zt|||<Wqttfk rHtd|YqXq|D]}t|D]}||q\qPt |D] \}}| |j|krvdSqv| |dS)zCheck good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. zUnknown hash name: %sN) rrhashlibnew ValueError TypeErrorrrupdater hexdigest_raise)rZchunksgotsr#chunkhashZgotrrrcheck_against_chunksAs zHashes.check_against_chunkscCst|j|dSr)rrrr,rrrr+Ysz Hashes._raisecCs|t|S)zaCheck good hashes against a file-like object Raise HashMismatch if none match. )r/r )rfilerrrcheck_against_file]szHashes.check_against_filec Cs,t|d}||W5QRSQRXdS)Nrb)openr2)rpathr1rrrcheck_against_pathfs zHashes.check_against_pathcCs t|jS)z,Return whether I know any known-good hashes.)boolrr rrr __nonzero__kszHashes.__nonzero__cCs|Sr)r8r rrr__bool__pszHashes.__bool__)N)__name__ __module__ __qualname____doc__rpropertyr!r$r/r+r2r6r8r9rrrrr's   rcs(eZdZdZfddZddZZS) MissingHasheszA workalike for Hashes used when we're missing a hash for a requirement It computes the actual hash of the requirement and raises a HashMissing exception showing it to the user. cstt|jtgiddS)z!Don't offer the ``hashes`` kwarg.)rN)superr?r FAVORITE_HASHr  __class__rrr|szMissingHashes.__init__cCst|tdSr)rrAr*r0rrrr+szMissingHashes._raise)r:r;r<r=rr+ __classcell__rrrBrr?us r?)Z __future__rr%Zpip._vendor.sixrrrZpip._internal.exceptionsrrrZpip._internal.utils.miscr Zpip._internal.utils.typingr typingr r r rrrrrrAZ STRONG_HASHESobjectrr?rrrrs      Nutils/__pycache__/deprecation.cpython-38.pyc000064400000005412152347654150015057 0ustar00U .e @sdZddlmZddlZddlZddlmZddlmZ ddl m Z e rXddl m Z mZdZGd d d eZdadd d Zd dZdddZdS)zN A module that implements tooling to enable easy warnings about deprecations. )absolute_importN)parse) __version__)MYPY_CHECK_RUNNING)AnyOptionalz DEPRECATION: c@s eZdZdS)PipDeprecationWarningN)__name__ __module__ __qualname__r r C/usr/lib/python3.8/site-packages/pip/_internal/utils/deprecation.pyrsrcCsZ|dk r$tdk rVt||||||n2t|trDtd}||nt||||||dS)Nzpip._internal.deprecations)_original_showwarning issubclassrloggingZ getLoggerZwarning)messagecategoryfilenamelinenofilelineZloggerr r r _showwarning!s*   rcCs(tjdtddtdkr$tjatt_dS)NdefaultT)append)warnings simplefilterrr showwarningrr r r r install_warning_logger2srcCsh|tdf|df|df|dfg}ddd|D}|dk rTttt|krTt|tj|td d dS) aHelper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. z{}z2pip {} will remove support for this functionality.zA possible replacement is {}.zPYou can find discussion regarding this at https://github.com/pypa/pip/issues/{}. css$|]\}}|dk r||VqdS)N)format).0valtemplater r r `szdeprecated..N)r stacklevel)DEPRECATION_MSG_PREFIXjoinrcurrent_versionrrwarn)reasonZ replacementZgone_inZissueZ sentencesrr r r deprecated>s  r+)NN)N)__doc__Z __future__rrrZpip._vendor.packaging.versionrZpiprr(Zpip._internal.utils.typingrtypingrrr&Warningrrrrr+r r r r s      utils/__pycache__/urls.cpython-38.opt-1.pyc000064400000002506152347654150014507 0ustar00U .e@shddlZddlZddlmZddlmZddlmZerLddl m Z m Z m Z ddZ dd Zd d ZdS) N)parse)request)MYPY_CHECK_RUNNING)OptionalTextUnioncCs d|kr dS|dddS)N:r)splitlower)urlr s    utils/__pycache__/misc.cpython-38.pyc000064400000055526152347654150013530 0ustar00U .ec@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZddlmZddlmZmZddlmZddlmZdd lmZdd lmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0m1Z1er8ddlm2Z3n ddlm3Z3e.rddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>ddl?m@Z@edddddddddd d!d"d#d$gZCeDeEZFd%d&ZGd'd(ZHd)d"ZId*d ZJed+d,d-dd/dZKd0d1ZLd2d3ZMd4dZNdd6dZOd7d8ZPd9d:ZQd;dZRdd?ZTd@dZUdAdZVejWfdBdCZXddEdZYdFdZZdGdZ[dHdIZ\dJdKZ]dLdMZ^dNdOZ_dPdQZ`dRdSZadDe)dDd.d.dfdTdUZbdVdWZcdXdYZddZd[Zed\d]ZfGd^d_d_egZhGd`dadae3ZiejjdbdcZkddd!ZldedfZmGdgdhdhegZnddid#ZodjdkZpdldmZqdndoZrddqdrZsdsdtZtdudvZudwdxZvdydzZwd{d|Zxd}d~ZyddZzdd$Z{ddZ|GdddegZ}ddZ~ddZddZddZdS))absolute_importNdeque) pkg_resources)retry)PY2 text_type)input)parse)unquote) __version__) CommandError)distutils_schemeget_major_minor_version site_packages user_site)WINDOWS expanduser stdlib_pkgsstr_to_display)write_delete_marker_file)MYPY_CHECK_RUNNING)running_under_virtualenvvirtualenv_no_global)BytesIO)StringIO) AnyAnyStr ContainerIterableListOptionalTextTupleUnioncast) DistributioncCs|SN)Ztype_valuer(r(}z|jtjkr.W5d}~XYnXdS)z os.path.makedirs without EEXIST.N)r9makedirsOSErrorerrnoZEEXIST)r:er(r(r*r6qs  c CsPz0tjtjd}|dkr(dtjWS|WSWntttfk rJYnXdS)Nr)z __main__.pyz-cz %s -m pippip) r9r:basenamesysargv executableAttributeError TypeError IndexError)progr(r(r*r4{s  i i)Zstop_max_delayZ wait_fixedFcCstj||tddS)N) ignore_errorsonerror)shutilr+rmtree_errorhandler)dirrRr(r(r*r+sc CsXzt|jtj@ }Wnttfk r2YdSX|rRt|tj||dSdS)zOn Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.N)r9statst_modeS_IWRITEIOErrorrFchmod)funcr:exc_infoZhas_attr_readonlyr(r(r*rUsrUcCsd|dkr dSt|tr|Sz|td}Wn0tk r^trRtd|}nt |}YnX|S)z Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str paths are already text. Nstrictzb{!r}) isinstancerdecoderKgetfilesystemencodingUnicodeDecodeErrorrrr?ascii)r:r,r(r(r*path_to_displays  rdcCsttjtj|}tjddkrB|td}|t d}| t tjj rpd|t t d}|S)zTGives the display value for a given path, making it relative to cwd if possible.rreplace.N)r9r:normcaser>rK version_infor`raencodegetdefaultencoding startswithgetcwdseprCr:r(r(r*r,s.bakcCs6d}|}tj||r.|d7}|t|}q||S)z\Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc))r9r:existsstr)rVextn extensionr(r(r*r-s cCs2tjddD]}||kr|Sqt||S)NZPIP_EXISTS_ACTION)r9environgetsplitr.)messageoptionsactionr(r(r*ask_path_existss r~cCstjdrtd|dS)z&Raise an error if no input is allowed.Z PIP_NO_INPUTz7No input was expected ($PIP_NO_INPUT set); question: %sN)r9rxry Exceptionr{r(r(r*_check_no_inputs  rcCsFt|t|}|}||krrh)r:Zresolve_symlinksr(r(r*r23s  cCs@t|\}}|dr8|dd|}|dd}||fS)z,Like os.path.splitext, but take off .tar tooz.tarN) posixpathr/rendswith)r:basertr(r(r*r/As  cCsztj|\}}|r.|r.tj|s.t|t||tj|\}}|rv|rvzt|Wntk rtYnXdS)z7Like os.renames(), but handles renaming across devices.N) r9r:rzrrrErTZmove removedirsrF)oldnewheadtailr(r(r*r3Ks  cCsts dS|ttjS)z Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. T)rrlr2rKprefixror(r(r*is_local]s rcCs tt|S)z Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. )r dist_locationdistr(r(r* dist_is_localls rcCst|ttS)zF Return True if given Distribution is installed in user site. )rrlr2rrr(r(r*dist_in_usersitexsrcCst|ttS)z[ Return True if given Distribution is installed in sysconfig.get_python_lib(). )rrlr2rrr(r(r*dist_in_site_packagessrcCs,tt|}|ttddddS)zf Return True if given Distribution is installed in path matching distutils_scheme layout. rwZpurelibpythonr)r2rrlrrz)rZ norm_pathr(r(r*dist_in_install_paths rcCs6tjD]*}tj||jd}tj|rdSqdS)zC Return True if given Distribution is an editable install. .egg-linkTF)rKr:r9r; project_namer)rZ path_itemegg_linkr(r(r*dist_is_editables   rcs|rt|}ntj}|r tndd|r6ddndd|rLddndd|r^tnd d fd d |DS) a^ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. cSsdSNTr(dr(r(r* local_testsz/get_installed_distributions..local_testcSsdSrr(rr(r(r* editable_testsz2get_installed_distributions..editable_testcSs t| Sr'rrr(r(r*rscSst|Sr'rrr(r(r*editables_only_testsz8get_installed_distributions..editables_only_testcSsdSrr(rr(r(r*rscSsdSrr(rr(r(r* user_testsz.get_installed_distributions..user_testcs:g|]2}|r|jkr|r|r|r|qSr()key).0rrrrskiprr(r* s z/get_installed_distributions..)r WorkingSet working_setrr)Z local_onlyrZinclude_editablesZeditables_onlyZ user_onlypathsrr(rr*get_installed_distributionss    rcCsxg}tr*|ttsBtrB|tntr8|t|t|D],}tj||jd}tj |rF|SqFdS)a Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packages, then site.USER_SITE (don't look in global location) For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations. This method will just return the first one found. rN) rappendrrrr9r:r;rr)rZsitesZsiteZegglinkr(r(r* egg_link_paths       rcCst|}|rt|St|jS)aO Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks removed). )rr2location)rrr(r(r*rs rcGstj|f|dSr')loggerinfo)msgargsr(r(r* write_outputsrcCst|t|dSr')r9rEr)Z build_dirr(r(r*_make_build_dirs rc@s(eZdZdZddZddZddZdS) FakeFilezQWrap a list of lines in an object with readline() to make ConfigParser happy.cCsdd|D|_dS)Ncss|] }|VqdSr'r()rlr(r(r* &sz$FakeFile.__init__.._gen)selflinesr(r(r*__init__%szFakeFile.__init__cCsPz4zt|jWWStk r0|jYWSXWntk rJYdSXdS)Nrw)nextr NameError StopIterationrr(r(r*readline(szFakeFile.readlinecCs|jSr'rrr(r(r*__iter__1szFakeFile.__iter__N)__name__ __module__ __qualname____doc__rrrr(r(r(r*r"s rc@s$eZdZeddZeddZdS) StreamWrappercCs ||_|Sr') orig_stream)clsrr(r(r* from_stream7szStreamWrapper.from_streamcCs|jjSr')rencodingrr(r(r*r=szStreamWrapper.encodingN)rrr classmethodrpropertyrr(r(r(r*r5s rc cs@tt|}tt|t|ztt|VW5tt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. N)getattrrKsetattrrr)Z stream_nameZ orig_stdoutr(r(r*captured_outputBs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello ') Taken from Lib/support/__init__.py in the CPython repo. stdoutrr(r(r(r*r5Qs cCstdS)z See captured_stdout(). stderrrr(r(r(r*captured_stderr]src@s eZdZdZddZddZdS)cached_propertyzA property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/blob/0.11.5/bottle.py#L175 cCst|d|_||_dS)Nr)rrr\)rr\r(r(r*rls zcached_property.__init__cCs(|dkr |S||}|j|jj<|Sr')r\__dict__r)robjrr)r(r(r*__get__pszcached_property.__get__N)rrrrrrr(r(r(r*rdsrcCs4tj|}|dkrt}||}|r0|jSdS)zCGet the installed version of dist_name avoiding pkg_resources cacheN)rZ Requirementr rfindversion)Z dist_namerZreqrr(r(r*r7xs   cCst|dddS)zConsume an iterable at C speed.r)maxlenNr)iteratorr(r(r*consumesrcOs@tt|tt|f|}dd|D}||d<tdd|S)NcSsi|]\}}||qSr(r()rrr)r(r(r* szenum..Zreverse_mappingEnumr()dictziprangerCitemstype)Z sequentialZnamedZenumsreverser(r(r*enumsrcCs*|dkr |Sd|krd|}d||S)z. Build a netloc from a host-port pair N:[{}]z{}:{})r?)Zhostportr(r(r* build_netlocs  rhttpscCs4|ddkr(d|kr(d|kr(d|}d||S)z) Build a full URL from a netloc. rre@[rz{}://{})countr?)netlocschemer(r(r*build_url_from_netlocs rcCst|}t|}|j|jfS)z2 Return the host-port pair from a netloc. )r urllib_parseZurlparseZhostnamer)rurlZparsedr(r(r* parse_netlocs rcCsXd|kr|dfS|dd\}}d|kr6|dd}n|df}tdd|D}||fS)zp Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). r)NNrqrNcss"|]}|dkrdnt|VqdSr')urllib_unquote)rxr(r(r*rsz)split_auth_from_netloc..)rsplitrztuple)rauthZ user_passr(r(r*split_auth_from_netlocsrcCsLt|\}\}}|dkr|S|dkr.d}d}nt|}d}dj|||dS)z Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" N****rwz:****z{user}{password}@{netloc})userpasswordr)rrZquoter?)rr r r(r(r* redact_netlocs  r cCs@t|}||j}|j|d|j|j|jf}t|}||fS)aRTransform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netloc as item 1. r)rZurlsplitrrr:ZqueryZfragmentZ urlunsplit)rZtransform_netlocZpurlZ netloc_tupleZ url_piecesZsurlr(r(r*_transform_urls   r cCst|Sr')rrr(r(r* _get_netlocsrcCs t|fSr')r r r(r(r*_redact_netlocsrcCst|t\}\}}|||fS)z Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) r r)rZurl_without_authrrr(r(r*split_auth_netloc_from_urlsrcCst|tdS)z7Return a copy of url with 'username:password@' removed.rrrr(r(r*r8scCst|tdS)z.Replace the password in a given url with ****.r)r rrr(r(r*redact_auth_from_urlsrc@s4eZdZddZddZddZddZd d Zd S) HiddenTextcCs||_||_dSr')secretredacted)rrrr(r(r*r"szHiddenText.__init__cCsdt|S)Nz)r?rsrr(r(r*__repr__+szHiddenText.__repr__cCs|jSr'rrr(r(r*__str__/szHiddenText.__str__cCs t|t|krdS|j|jkS)NF)rrrotherr(r(r*__eq__4szHiddenText.__eq__cCs ||k Sr'r(rr(r(r*__ne__?szHiddenText.__ne__N)rrrrrrrrr(r(r(r*r!s   rcCs t|ddS)Nrr)r)r)r(r(r* hide_valueDsrcCst|}t||dS)Nr)rr)rrr(r(r*hide_urlIsrcCst}dD]P}|dj|d|djtjd|d|djtjddd |iq |oxtoxtjtj d|k}|rtj d d gtj d d}t d d |dS)zProtection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... )rwz.exezpip{ext})rtz pip{}{ext}rz pip{}.{}{ext}Nrertz-mrIrqz3To modify pip, please run the following command: {} ) setaddr?rKrirr9r:rJrLrMr r;)Z modifying_pipZ pip_namesrtZshould_show_use_python_msgZ new_commandr(r(r*(protect_pip_from_modification_on_windowsOs," r#cCstjdk otjS)z!Is this console interactive? N)rKstdinisattyr(r(r(r*is_console_interactivemsr&)F)rp)T)N)r)Z __future__r contextlibrGrioZloggingr9rrTrWrK collectionsrZ pip._vendorrZpip._vendor.retryingrZpip._vendor.sixrrZpip._vendor.six.movesr Zpip._vendor.six.moves.urllibr rZ"pip._vendor.six.moves.urllib.parser rrIr Zpip._internal.exceptionsr Zpip._internal.locationsrrrrZpip._internal.utils.compatrrrrZ pip._internal.utils.marker_filesrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrrrrtypingrrrrr r!r"r#r$r%Zpip._vendor.pkg_resourcesr&intrB__all__Z getLoggerrrr@rDr6r4r+rUrdr,r-r~rr.rrr0r1DEFAULT_BUFFER_SIZErr2r/r3rrrrrrrrrrrobjectrrcontextmanagerrr5rrr7rrrrrrr r rrrr8rrrrr#r&r(r(r(r*s            0      "          E$       #utils/__pycache__/misc.cpython-38.opt-1.pyc000064400000055526152347654150014467 0ustar00U .ec@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZddlmZddlmZmZddlmZddlmZdd lmZdd lmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0m1Z1er8ddlm2Z3n ddlm3Z3e.rddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>ddl?m@Z@edddddddddd d!d"d#d$gZCeDeEZFd%d&ZGd'd(ZHd)d"ZId*d ZJed+d,d-dd/dZKd0d1ZLd2d3ZMd4dZNdd6dZOd7d8ZPd9d:ZQd;dZRdd?ZTd@dZUdAdZVejWfdBdCZXddEdZYdFdZZdGdZ[dHdIZ\dJdKZ]dLdMZ^dNdOZ_dPdQZ`dRdSZadDe)dDd.d.dfdTdUZbdVdWZcdXdYZddZd[Zed\d]ZfGd^d_d_egZhGd`dadae3ZiejjdbdcZkddd!ZldedfZmGdgdhdhegZnddid#ZodjdkZpdldmZqdndoZrddqdrZsdsdtZtdudvZudwdxZvdydzZwd{d|Zxd}d~ZyddZzdd$Z{ddZ|GdddegZ}ddZ~ddZddZddZdS))absolute_importNdeque) pkg_resources)retry)PY2 text_type)input)parse)unquote) __version__) CommandError)distutils_schemeget_major_minor_version site_packages user_site)WINDOWS expanduser stdlib_pkgsstr_to_display)write_delete_marker_file)MYPY_CHECK_RUNNING)running_under_virtualenvvirtualenv_no_global)BytesIO)StringIO) AnyAnyStr ContainerIterableListOptionalTextTupleUnioncast) DistributioncCs|SN)Ztype_valuer(r(}z|jtjkr.W5d}~XYnXdS)z os.path.makedirs without EEXIST.N)r9makedirsOSErrorerrnoZEEXIST)r:er(r(r*r6qs  c CsPz0tjtjd}|dkr(dtjWS|WSWntttfk rJYnXdS)Nr)z __main__.pyz-cz %s -m pippip) r9r:basenamesysargv executableAttributeError TypeError IndexError)progr(r(r*r4{s  i i)Zstop_max_delayZ wait_fixedFcCstj||tddS)N) ignore_errorsonerror)shutilr+rmtree_errorhandler)dirrRr(r(r*r+sc CsXzt|jtj@ }Wnttfk r2YdSX|rRt|tj||dSdS)zOn Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.N)r9statst_modeS_IWRITEIOErrorrFchmod)funcr:exc_infoZhas_attr_readonlyr(r(r*rUsrUcCsd|dkr dSt|tr|Sz|td}Wn0tk r^trRtd|}nt |}YnX|S)z Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str paths are already text. Nstrictzb{!r}) isinstancerdecoderKgetfilesystemencodingUnicodeDecodeErrorrrr?ascii)r:r,r(r(r*path_to_displays  rdcCsttjtj|}tjddkrB|td}|t d}| t tjj rpd|t t d}|S)zTGives the display value for a given path, making it relative to cwd if possible.rreplace.N)r9r:normcaser>rK version_infor`raencodegetdefaultencoding startswithgetcwdseprCr:r(r(r*r,s.bakcCs6d}|}tj||r.|d7}|t|}q||S)z\Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc))r9r:existsstr)rVextn extensionr(r(r*r-s cCs2tjddD]}||kr|Sqt||S)NZPIP_EXISTS_ACTION)r9environgetsplitr.)messageoptionsactionr(r(r*ask_path_existss r~cCstjdrtd|dS)z&Raise an error if no input is allowed.Z PIP_NO_INPUTz7No input was expected ($PIP_NO_INPUT set); question: %sN)r9rxry Exceptionr{r(r(r*_check_no_inputs  rcCsFt|t|}|}||krrh)r:Zresolve_symlinksr(r(r*r23s  cCs@t|\}}|dr8|dd|}|dd}||fS)z,Like os.path.splitext, but take off .tar tooz.tarN) posixpathr/rendswith)r:basertr(r(r*r/As  cCsztj|\}}|r.|r.tj|s.t|t||tj|\}}|rv|rvzt|Wntk rtYnXdS)z7Like os.renames(), but handles renaming across devices.N) r9r:rzrrrErTZmove removedirsrF)oldnewheadtailr(r(r*r3Ks  cCsts dS|ttjS)z Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. T)rrlr2rKprefixror(r(r*is_local]s rcCs tt|S)z Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. )r dist_locationdistr(r(r* dist_is_localls rcCst|ttS)zF Return True if given Distribution is installed in user site. )rrlr2rrr(r(r*dist_in_usersitexsrcCst|ttS)z[ Return True if given Distribution is installed in sysconfig.get_python_lib(). )rrlr2rrr(r(r*dist_in_site_packagessrcCs,tt|}|ttddddS)zf Return True if given Distribution is installed in path matching distutils_scheme layout. rwZpurelibpythonr)r2rrlrrz)rZ norm_pathr(r(r*dist_in_install_paths rcCs6tjD]*}tj||jd}tj|rdSqdS)zC Return True if given Distribution is an editable install. .egg-linkTF)rKr:r9r; project_namer)rZ path_itemegg_linkr(r(r*dist_is_editables   rcs|rt|}ntj}|r tndd|r6ddndd|rLddndd|r^tnd d fd d |DS) a^ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. cSsdSNTr(dr(r(r* local_testsz/get_installed_distributions..local_testcSsdSrr(rr(r(r* editable_testsz2get_installed_distributions..editable_testcSs t| Sr'rrr(r(r*rscSst|Sr'rrr(r(r*editables_only_testsz8get_installed_distributions..editables_only_testcSsdSrr(rr(r(r*rscSsdSrr(rr(r(r* user_testsz.get_installed_distributions..user_testcs:g|]2}|r|jkr|r|r|r|qSr()key).0rrrrskiprr(r* s z/get_installed_distributions..)r WorkingSet working_setrr)Z local_onlyrZinclude_editablesZeditables_onlyZ user_onlypathsrr(rr*get_installed_distributionss    rcCsxg}tr*|ttsBtrB|tntr8|t|t|D],}tj||jd}tj |rF|SqFdS)a Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packages, then site.USER_SITE (don't look in global location) For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations. This method will just return the first one found. rN) rappendrrrr9r:r;rr)rZsitesZsiteZegglinkr(r(r* egg_link_paths       rcCst|}|rt|St|jS)aO Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks removed). )rr2location)rrr(r(r*rs rcGstj|f|dSr')loggerinfo)msgargsr(r(r* write_outputsrcCst|t|dSr')r9rEr)Z build_dirr(r(r*_make_build_dirs rc@s(eZdZdZddZddZddZdS) FakeFilezQWrap a list of lines in an object with readline() to make ConfigParser happy.cCsdd|D|_dS)Ncss|] }|VqdSr'r()rlr(r(r* &sz$FakeFile.__init__.._gen)selflinesr(r(r*__init__%szFakeFile.__init__cCsPz4zt|jWWStk r0|jYWSXWntk rJYdSXdS)Nrw)nextr NameError StopIterationrr(r(r*readline(szFakeFile.readlinecCs|jSr'rrr(r(r*__iter__1szFakeFile.__iter__N)__name__ __module__ __qualname____doc__rrrr(r(r(r*r"s rc@s$eZdZeddZeddZdS) StreamWrappercCs ||_|Sr') orig_stream)clsrr(r(r* from_stream7szStreamWrapper.from_streamcCs|jjSr')rencodingrr(r(r*r=szStreamWrapper.encodingN)rrr classmethodrpropertyrr(r(r(r*r5s rc cs@tt|}tt|t|ztt|VW5tt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. N)getattrrKsetattrrr)Z stream_nameZ orig_stdoutr(r(r*captured_outputBs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello ') Taken from Lib/support/__init__.py in the CPython repo. stdoutrr(r(r(r*r5Qs cCstdS)z See captured_stdout(). stderrrr(r(r(r*captured_stderr]src@s eZdZdZddZddZdS)cached_propertyzA property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/blob/0.11.5/bottle.py#L175 cCst|d|_||_dS)Nr)rrr\)rr\r(r(r*rls zcached_property.__init__cCs(|dkr |S||}|j|jj<|Sr')r\__dict__r)robjrr)r(r(r*__get__pszcached_property.__get__N)rrrrrrr(r(r(r*rdsrcCs4tj|}|dkrt}||}|r0|jSdS)zCGet the installed version of dist_name avoiding pkg_resources cacheN)rZ Requirementr rfindversion)Z dist_namerZreqrr(r(r*r7xs   cCst|dddS)zConsume an iterable at C speed.r)maxlenNr)iteratorr(r(r*consumesrcOs@tt|tt|f|}dd|D}||d<tdd|S)NcSsi|]\}}||qSr(r()rrr)r(r(r* szenum..Zreverse_mappingEnumr()dictziprangerCitemstype)Z sequentialZnamedZenumsreverser(r(r*enumsrcCs*|dkr |Sd|krd|}d||S)z. Build a netloc from a host-port pair N:[{}]z{}:{})r?)Zhostportr(r(r* build_netlocs  rhttpscCs4|ddkr(d|kr(d|kr(d|}d||S)z) Build a full URL from a netloc. rre@[rz{}://{})countr?)netlocschemer(r(r*build_url_from_netlocs rcCst|}t|}|j|jfS)z2 Return the host-port pair from a netloc. )r urllib_parseZurlparseZhostnamer)rurlZparsedr(r(r* parse_netlocs rcCsXd|kr|dfS|dd\}}d|kr6|dd}n|df}tdd|D}||fS)zp Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). r)NNrqrNcss"|]}|dkrdnt|VqdSr')urllib_unquote)rxr(r(r*rsz)split_auth_from_netloc..)rsplitrztuple)rauthZ user_passr(r(r*split_auth_from_netlocsrcCsLt|\}\}}|dkr|S|dkr.d}d}nt|}d}dj|||dS)z Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" N****rwz:****z{user}{password}@{netloc})userpasswordr)rrZquoter?)rr r r(r(r* redact_netlocs  r cCs@t|}||j}|j|d|j|j|jf}t|}||fS)aRTransform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netloc as item 1. r)rZurlsplitrrr:ZqueryZfragmentZ urlunsplit)rZtransform_netlocZpurlZ netloc_tupleZ url_piecesZsurlr(r(r*_transform_urls   r cCst|Sr')rrr(r(r* _get_netlocsrcCs t|fSr')r r r(r(r*_redact_netlocsrcCst|t\}\}}|||fS)z Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) r r)rZurl_without_authrrr(r(r*split_auth_netloc_from_urlsrcCst|tdS)z7Return a copy of url with 'username:password@' removed.rrrr(r(r*r8scCst|tdS)z.Replace the password in a given url with ****.r)r rrr(r(r*redact_auth_from_urlsrc@s4eZdZddZddZddZddZd d Zd S) HiddenTextcCs||_||_dSr')secretredacted)rrrr(r(r*r"szHiddenText.__init__cCsdt|S)Nz)r?rsrr(r(r*__repr__+szHiddenText.__repr__cCs|jSr'rrr(r(r*__str__/szHiddenText.__str__cCs t|t|krdS|j|jkS)NF)rrrotherr(r(r*__eq__4szHiddenText.__eq__cCs ||k Sr'r(rr(r(r*__ne__?szHiddenText.__ne__N)rrrrrrrrr(r(r(r*r!s   rcCs t|ddS)Nrr)r)r)r(r(r* hide_valueDsrcCst|}t||dS)Nr)rr)rrr(r(r*hide_urlIsrcCst}dD]P}|dj|d|djtjd|d|djtjddd |iq |oxtoxtjtj d|k}|rtj d d gtj d d}t d d |dS)zProtection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... )rwz.exezpip{ext})rtz pip{}{ext}rz pip{}.{}{ext}Nrertz-mrIrqz3To modify pip, please run the following command: {} ) setaddr?rKrirr9r:rJrLrMr r;)Z modifying_pipZ pip_namesrtZshould_show_use_python_msgZ new_commandr(r(r*(protect_pip_from_modification_on_windowsOs," r#cCstjdk otjS)z!Is this console interactive? N)rKstdinisattyr(r(r(r*is_console_interactivemsr&)F)rp)T)N)r)Z __future__r contextlibrGrioZloggingr9rrTrWrK collectionsrZ pip._vendorrZpip._vendor.retryingrZpip._vendor.sixrrZpip._vendor.six.movesr Zpip._vendor.six.moves.urllibr rZ"pip._vendor.six.moves.urllib.parser rrIr Zpip._internal.exceptionsr Zpip._internal.locationsrrrrZpip._internal.utils.compatrrrrZ pip._internal.utils.marker_filesrZpip._internal.utils.typingrZpip._internal.utils.virtualenvrrrrtypingrrrrr r!r"r#r$r%Zpip._vendor.pkg_resourcesr&intrB__all__Z getLoggerrrr@rDr6r4r+rUrdr,r-r~rr.rrr0r1DEFAULT_BUFFER_SIZErr2r/r3rrrrrrrrrrrobjectrrcontextmanagerrr5rrr7rrrrrrr r rrrr8rrrrr#r&r(r(r(r*s            0      "          E$       #utils/__pycache__/glibc.cpython-38.pyc000064400000004321152347654150013640 0ustar00U .e-@sxddlmZddlZddlZddlZddlmZerDddlmZm Z ddZ ddZ d d Z d d Z d dZddZdS))absolute_importN)MYPY_CHECK_RUNNING)OptionalTuplecCs tp tS)z9Returns glibc version string, or None if not using glibc.)glibc_version_string_confstrglibc_version_string_ctypesrr=/usr/lib/python3.8/site-packages/pip/_internal/utils/glibc.pyglibc_version_stringsr c Cs8ztd\}}Wntttfk r2YdSX|S)z@Primary implementation of glibc_version_string using os.confstr.CS_GNU_LIBC_VERSIONN)osconfstrsplitAttributeErrorOSError ValueError)_versionrrr rs rcCsvz ddl}Wntk r"YdSX|d}z |j}Wntk rNYdSX|j|_|}t|tsr| d}|S)z=Fallback implementation of glibc_version_string using ctypes.rNascii) ctypes ImportErrorZCDLLgnu_get_libc_versionrZc_char_pZrestype isinstancestrdecode)rZprocess_namespacer version_strrrr r&s     rcCsHtd|}|s$td|tdSt|d|koFt|d|kS)Nz$(?P[0-9]+)\.(?P[0-9]+)z=Expected glibc version with 2 components major.minor, got: %sFmajorminor)rematchwarningswarnRuntimeWarningintgroup)rrequired_major minimum_minormrrr check_glibc_versionFs r(cCst}|dkrdSt|||S)NF)r r()r%r&rrrr have_compatible_glibcWsr)cCst}|dkrdSd|fSdS)zTry to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. N)r*Zglibc)r )Z glibc_versionrrr libc_verpsr+)Z __future__rr rr Zpip._internal.utils.typingrtypingrrr rrr(r)r+rrrr s   utils/__pycache__/filesystem.cpython-38.opt-1.pyc000064400000005325152347654150015710 0ustar00U .e @sddlZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZddlmZerdd lmZmZGd d d eZd d ZddZddZeddZe dddZe reddZn eejZdS)N)contextmanager)NamedTemporaryFile)retry)PY2) get_path_uid)cast)MYPY_CHECK_RUNNING)BinaryIOIteratorc@seZdZeddZdS)NamedTemporaryFileResultcCsdSN)selfr r B/usr/lib/python3.8/site-packages/pip/_internal/utils/filesystem.pyfileszNamedTemporaryFileResult.fileN)__name__ __module__ __qualname__propertyrr r r rr sr cCsttdsdSd}||krtj|rntdkr^z t|}Wntk rTYdSX|dkSt|tjSq|tj |}}qdS)NgeteuidTrF) hasattrospathlexistsrrOSErroraccessW_OKdirname)rZpreviousZpath_uidr r rcheck_path_owners    rc Csrzt||Wn\ttfk rl||fD]8}z t|}Wntk rPYq,X|r,td|q,YnXdS)zWrap shutil.copy2() but map errors copying socket files to SpecialFileError as expected. See also https://bugs.python.org/issue37700. z`%s` is a socketN)shutilZcopy2rIOError is_socketZSpecialFileError)srcdestfZis_socket_filer r r copy2_fixed5s  r%cCstt|jSr )statS_ISSOCKrlstatst_mode)rr r rr!Msr!c csbtdtj|tj|dd8}td|}z |VW5|jt|j XW5QRXdS)zGiven a path to a file, open a temp file next to it securely and ensure it is written to disk after the context reaches its end. Fz.tmp)deletedirprefixsuffixr N) rrrrbasenamerrflushfsyncfileno)rr$resultr r radjacent_tmp_fileRs     r3i)Zstop_max_delayZ wait_fixedcCs@zt||Wn*tk r:t|t||YnXdSr )rrenamerremove)r"r#r r rreplaceis  r7)rZos.pathrr& contextlibrZtempfilerZpip._vendor.retryingrZpip._vendor.sixrZpip._internal.utils.compatrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingr r r rr%r!r3Z_replace_retryr7r r r rs.          utils/__pycache__/glibc.cpython-38.opt-1.pyc000064400000004321152347654150014577 0ustar00U .e-@sxddlmZddlZddlZddlZddlmZerDddlmZm Z ddZ ddZ d d Z d d Z d dZddZdS))absolute_importN)MYPY_CHECK_RUNNING)OptionalTuplecCs tp tS)z9Returns glibc version string, or None if not using glibc.)glibc_version_string_confstrglibc_version_string_ctypesrr=/usr/lib/python3.8/site-packages/pip/_internal/utils/glibc.pyglibc_version_stringsr c Cs8ztd\}}Wntttfk r2YdSX|S)z@Primary implementation of glibc_version_string using os.confstr.CS_GNU_LIBC_VERSIONN)osconfstrsplitAttributeErrorOSError ValueError)_versionrrr rs rcCsvz ddl}Wntk r"YdSX|d}z |j}Wntk rNYdSX|j|_|}t|tsr| d}|S)z=Fallback implementation of glibc_version_string using ctypes.rNascii) ctypes ImportErrorZCDLLgnu_get_libc_versionrZc_char_pZrestype isinstancestrdecode)rZprocess_namespacer version_strrrr r&s     rcCsHtd|}|s$td|tdSt|d|koFt|d|kS)Nz$(?P[0-9]+)\.(?P[0-9]+)z=Expected glibc version with 2 components major.minor, got: %sFmajorminor)rematchwarningswarnRuntimeWarningintgroup)rrequired_major minimum_minormrrr check_glibc_versionFs r(cCst}|dkrdSt|||S)NF)r r()r%r&rrrr have_compatible_glibcWsr)cCst}|dkrdSd|fSdS)zTry to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. N)r*Zglibc)r )Z glibc_versionrrr libc_verpsr+)Z __future__rr rr Zpip._internal.utils.typingrtypingrrr rrr(r)r+rrrr s   utils/__pycache__/unpacking.cpython-38.pyc000064400000014055152347654150014544 0ustar00U .e%@sXdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z mZmZddlmZddlmZerddlmZmZmZmZmZeeZee ZzddlZee 7ZWnek re d YnXzddl!Z!ee7ZWn ek re d YnXd d Z"d dZ#ddZ$ddZ%dddZ&ddZ'dddZ(dS)zUtilities related archives. )absolute_importN)InstallationError)BZ2_EXTENSIONSTAR_EXTENSIONS XZ_EXTENSIONSZIP_EXTENSIONS) ensure_dir)MYPY_CHECK_RUNNING)IterableListOptionalTextUnionzbz2 module is not availablezlzma module is not availablecCstd}t||S)zBGet the current umask which involves having to set it temporarily.r)osumask)maskrA/usr/lib/python3.8/site-packages/pip/_internal/utils/unpacking.py current_umask2s  rcCsh|dd}d|krHd|kr4|d|dksd}n8|trRd}n$|drfd}ntd|d }t||}zt d d | D}| D]}|j }|rt |d }tj||}t||sd }t||||zt|j|d|Wntjk rYnX|r4t|q|rz|||Wn>tk r} ztd||j | WYqW5d} ~ XYnXqz||} WnBttfk r} ztd||j | WYqW5d} ~ XYnXttj|t|d} t | | W5QRX| |!|||j"d@rt#|dt$dBqW5| XdS)a Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. z.gzz.tgzzr:gzzr:bz2zr:xzz.tarrz-Cannot determine compression type for file %szr:*cSsg|] }|jqSrr=).0memberrrr szuntar_file..rzQThe tar file ({}) has a file ({}) trying to install outside target directory ({})rFz/In the tar file %s the member %s is invalid: %sNr*r(r))%rlowerr2rrloggerZwarningtarfiler+r,r!Z getmembersr=rrrr/r%rr1Z data_filterreplaceZLinkOutsideDestinationErrorisdirZissymZ_extract_member ExceptionZ extractfileKeyErrorAttributeErrorr0r6r7utimerBr5r) r.r8rBZtarr;rHr>rr@excrArCrrr untar_files           rTcCstj|}|dks,|ts,t|rDt|||d dnR|dkslt |sl|t t t rxt||ntd|||td|dS)Nzapplication/zipz.whl)r9zapplication/x-gzipzZCannot unpack file %s (downloaded from %s, content-type: %s); cannot detect archive formatz%Cannot determine archive format of {})rrrealpathrJr2rr-Z is_zipfilerDrLZ is_tarfilerrrrTrKZcriticalrr1)r.r8Z content_typerrr unpack_files<     rV)T)N))__doc__Z __future__rZloggingrr6r3rLr-Zpip._internal.exceptionsrZpip._internal.utils.filetypesrrrrZpip._internal.utils.miscrZpip._internal.utils.typingr typingr r r r rZ getLogger__name__rKZSUPPORTED_EXTENSIONSbz2 ImportErrordebugZlzmarrr!r%rDrTrVrrrrsB        4^utils/__pycache__/ui.cpython-38.opt-1.pyc000064400000026753152347654150014151 0ustar00U .eR6@sxddlmZmZddlZddlZddlZddlZddlZddlm Z m Z mZddl m Z ddl mZmZddlmZmZmZddlmZddlmZdd lmZdd lmZdd lmZerdd lmZm Z m!Z!zdd l m"Z"Wne#k rdZ"YnXe$e%Z&ddZ'e'eeZ(Gddde)Z*GdddeZ+GdddeZ,Gddde)Z-Gddde)Z.Gddde.e*e-Z/Gddde/e(Z0Gddde/e+Z1Gd d!d!e/eZ2Gd"d#d#e/eZ3Gd$d%d%e/e,Z4Gd&d'd'e.e*e-eZ5e1e1fe0e5fe2e5fe3e5fe4e5fd(Z6d7d)d*Z7ej8d+d,Z9Gd-d.d.e)Z:Gd/d0d0e)Z;Gd1d2d2e;ZdS)8)absolute_importdivisionN)SIGINTdefault_int_handlersignal)six) HIDE_CURSOR SHOW_CURSOR)BarFillingCirclesBarIncrementalBar)Spinner)WINDOWS)get_indentation) format_size)MYPY_CHECK_RUNNING)AnyIteratorIO)coloramacCst|jdd}|s|St|dtt|dtg}|tt|dg7}zt||Wntk rz|YSX|SdS)NencodingZ empty_fillZfillphases)getattrfilerZ text_typelistjoinencodeUnicodeEncodeError)Z preferredZfallbackrZ charactersr:/usr/lib/python3.8/site-packages/pip/_internal/utils/ui.py_select_progress_class%s r cs4eZdZdZfddZfddZddZZS)InterruptibleMixina Helper to ensure that self.finish() gets called on keyboard interrupt. This allows downloads to be interrupted without leaving temporary state (like hidden cursors) behind. This class is similar to the progress library's existing SigIntMixin helper, but as of version 1.2, that helper has the following problems: 1. It calls sys.exit(). 2. It discards the existing SIGINT handler completely. 3. It leaves its own handler in place even after an uninterrupted finish, which will have unexpected delayed effects if the user triggers an unrelated keyboard interrupt some time after a progress-displaying download has already completed, for example. cs4tt|j||tt|j|_|jdkr0t|_dS)z= Save the original SIGINT handler for later. N)superr!__init__rr handle_sigintoriginal_handlerrselfargskwargs __class__rrr#Us zInterruptibleMixin.__init__cstt|tt|jdS)z Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. N)r"r!finishrrr%r'r*rrr,eszInterruptibleMixin.finishcCs||||dS)z Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. N)r,r%)r'Zsignumframerrrr$osz InterruptibleMixin.handle_sigint)__name__ __module__ __qualname____doc__r#r,r$ __classcell__rrr*rr!Cs  r!c@seZdZddZdS) SilentBarcCsdSNrr-rrrupdate|szSilentBar.updateN)r/r0r1r6rrrrr4zsr4c@seZdZdZdZdZdZdS) BlueEmojiBar %(percent)d%% )u🔹u🔷u🔵N)r/r0r1suffixZ bar_prefixZ bar_suffixrrrrrr7sr7csJeZdZfddZeddZeddZeddZd d d ZZ S) DownloadProgressMixincs,tt|j||dtd|j|_dS)Nr9)r"r;r#rmessager&r*rrr#szDownloadProgressMixin.__init__cCs t|jSr5)rindexr-rrr downloadedsz DownloadProgressMixin.downloadedcCs |jdkrdStd|jdS)Ngz...z/s)Zavgrr-rrrdownload_speeds z$DownloadProgressMixin.download_speedcCs|jrd|jSdS)Nzeta %s)ZetaZeta_tdr-rrr pretty_etas z DownloadProgressMixin.pretty_etar@ccs&|D]}|V||q|dSr5)nextr,)r'itnxrrriters zDownloadProgressMixin.iter)r@) r/r0r1r#propertyr?rArCrHr3rrr*rr;s    r;cseZdZfddZZS) WindowsMixincs\trjrd_ttj||trXtrXtj_fddj_fddj_ dS)NFcs jjSr5)rwrappedisattyrr-rrz'WindowsMixin.__init__..cs jjSr5)rrKflushrr-rrrMrN) rZ hide_cursorr"rJr#rZ AnsiToWin32rrLrOr&r*r-rr#s zWindowsMixin.__init__)r/r0r1r#r3rrr*rrJsrJc@seZdZejZdZdZdS)BaseDownloadProgressBarr8z0%(downloaded)s %(download_speed)s %(pretty_eta)sN)r/r0r1sysstdoutrr=r:rrrrrPsrPc@s eZdZdS)DefaultDownloadProgressBarNr/r0r1rrrrrSsrSc@s eZdZdS)DownloadSilentBarNrTrrrrrUsrUc@s eZdZdS) DownloadBarNrTrrrrrVsrVc@s eZdZdS)DownloadFillingCirclesBarNrTrrrrrWsrWc@s eZdZdS)DownloadBlueEmojiProgressBarNrTrrrrrXsrXc@s&eZdZejZdZddZddZdS)DownloadProgressSpinnerz!%(downloaded)s %(download_speed)scCs"t|dst|j|_t|jS)N_phaser)hasattr itertoolscyclerrZrDr-rrr next_phases z"DownloadProgressSpinner.next_phasecCsN|j|}|}|j|}d||r*dnd||r6dnd|g}||dS)NrBr9)r=r^r:rZwriteln)r'r=Zphaser:linerrrr6s    zDownloadProgressSpinner.updateN) r/r0r1rQrRrr:r^r6rrrrrYsrY)ZoffZonasciiZprettyZemojicCs8|dks|dkr t|djSt|d|djSdS)Nrr@)max) BAR_TYPESrH)Z progress_barrarrrDownloadProgressProvider srcc csPtr dVn@|r"ttjkr*dVn"|tz dVW5|tXdSr5) rrLloggergetEffectiveLevelloggingINFOwriterr )rrrr hidden_cursors  ric@s$eZdZddZddZddZdS) RateLimitercCs||_d|_dS)Nr)_min_update_interval_seconds _last_update)r'min_update_interval_secondsrrrr#-szRateLimiter.__init__cCst}||j}||jkSr5)timerlrk)r'ZnowZdeltarrrready2s zRateLimiter.readycCst|_dSr5)rnrlr-rrrreset8szRateLimiter.resetN)r/r0r1r#rorprrrrrj,srjc@seZdZddZddZdS)SpinnerInterfacecCs tdSr5NotImplementedErrorr-rrrspin>szSpinnerInterface.spincCs tdSr5rrr'Z final_statusrrrr,BszSpinnerInterface.finishN)r/r0r1rtr,rrrrrq=srqc@s.eZdZd ddZddZdd Zd d ZdS) InteractiveSpinnerN-\|/?cCs\||_|dkrtj}||_t||_d|_t||_ |j dt |jdd|_ dS)NFr9z ... r) _messagerQrR_filerj _rate_limiter _finishedr\r] _spin_cyclerhr_width)r'r=rZ spin_charsrmrrrr#Hs  zInteractiveSpinner.__init__cCsRd|j}|j|d|j||j|t||_|j|jdS)Nr9)r~rzrhlenrOr{rp)r'statusZbackuprrr_writeWs     zInteractiveSpinner._writecCs,|jr dS|jsdS|t|jdSr5)r|r{rorrDr}r-rrrrtcs  zInteractiveSpinner.spincCs4|jr dS|||jd|jd|_dS)N T)r|rrzrhrOrurrrr,ks    zInteractiveSpinner.finish)Nrwrx)r/r0r1r#rrtr,rrrrrvGs   rvc@s.eZdZd ddZddZddZdd Zd S) NonInteractiveSpinner<cCs$||_d|_t||_|ddS)NFZstarted)ryr|rjr{_update)r'r=rmrrrr#zs zNonInteractiveSpinner.__init__cCs|jtd|j|dS)Nz%s: %s)r{rprdinfory)r'rrrrrs zNonInteractiveSpinner._updatecCs&|jr dS|jsdS|ddS)Nzstill running...)r|r{rorr-rrrrts  zNonInteractiveSpinner.spincCs$|jr dS|d|fd|_dS)Nzfinished with status '%s'T)r|rrurrrr,szNonInteractiveSpinner.finishN)r)r/r0r1r#rrtr,rrrrrys rc cstjr"ttjkr"t|}nt|}z t tj |VW5QRXWn>t k rj| dYn*t k r| dYn X| ddS)NZcancelederrorZdone) rQrRrLrdrerfrgrvrriKeyboardInterruptr, Exception)r=Zspinnerrrr open_spinners    r)N)?Z __future__rr contextlibr\rfrQrnrrrZ pip._vendorrZpip._vendor.progressrr Zpip._vendor.progress.barr r r Zpip._vendor.progress.spinnerr Zpip._internal.utils.compatrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingrrrrrZ getLoggerr/rdr Z_BaseBarobjectr!r4r7r;rJrPrSrUrVrWrXrYrbrccontextmanagerrirjrqrvrrrrrrs~         7       2utils/__pycache__/filesystem.cpython-38.pyc000064400000005325152347654150014751 0ustar00U .e @sddlZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZddlmZerdd lmZmZGd d d eZd d ZddZddZeddZe dddZe reddZn eejZdS)N)contextmanager)NamedTemporaryFile)retry)PY2) get_path_uid)cast)MYPY_CHECK_RUNNING)BinaryIOIteratorc@seZdZeddZdS)NamedTemporaryFileResultcCsdSN)selfr r B/usr/lib/python3.8/site-packages/pip/_internal/utils/filesystem.pyfileszNamedTemporaryFileResult.fileN)__name__ __module__ __qualname__propertyrr r r rr sr cCsttdsdSd}||krtj|rntdkr^z t|}Wntk rTYdSX|dkSt|tjSq|tj |}}qdS)NgeteuidTrF) hasattrospathlexistsrrOSErroraccessW_OKdirname)rZpreviousZpath_uidr r rcheck_path_owners    rc Csrzt||Wn\ttfk rl||fD]8}z t|}Wntk rPYq,X|r,td|q,YnXdS)zWrap shutil.copy2() but map errors copying socket files to SpecialFileError as expected. See also https://bugs.python.org/issue37700. z`%s` is a socketN)shutilZcopy2rIOError is_socketZSpecialFileError)srcdestfZis_socket_filer r r copy2_fixed5s  r%cCstt|jSr )statS_ISSOCKrlstatst_mode)rr r rr!Msr!c csbtdtj|tj|dd8}td|}z |VW5|jt|j XW5QRXdS)zGiven a path to a file, open a temp file next to it securely and ensure it is written to disk after the context reaches its end. Fz.tmp)deletedirprefixsuffixr N) rrrrbasenamerrflushfsyncfileno)rr$resultr r radjacent_tmp_fileRs     r3i)Zstop_max_delayZ wait_fixedcCs@zt||Wn*tk r:t|t||YnXdSr )rrenamerremove)r"r#r r rreplaceis  r7)rZos.pathrr& contextlibrZtempfilerZpip._vendor.retryingrZpip._vendor.sixrZpip._internal.utils.compatrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingr r r rr%r!r3Z_replace_retryr7r r r rs.          utils/__pycache__/marker_files.cpython-38.pyc000064400000001640152347654150015224 0ustar00U .e7@s$ddlZdZdZddZddZdS)NzThis file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). zpip-delete-this-directory.txtcCstjtj|tS)N)ospathexistsjoinPIP_DELETE_MARKER_FILENAME) directoryrD/usr/lib/python3.8/site-packages/pip/_internal/utils/marker_files.pyhas_delete_marker_filesr c Cs2tj|t}t|d}|tW5QRXdS)z? Write the pip delete marker file into this directory. wN)rrrropenwriteDELETE_MARKER_MESSAGE)rfilepathZ marker_fprrr write_delete_marker_files r)Zos.pathrrrr rrrrr sutils/__pycache__/filetypes.cpython-38.pyc000064400000001054152347654150014564 0ustar00U .e;@sLdZddlmZer ddlmZdZdZdZdefZdZ eee eZ d S) zFiletype information. )MYPY_CHECK_RUNNING)Tuplez.whl)z.tar.bz2z.tbz)z.tar.xzz.txzz.tlzz.tar.lzz .tar.lzmaz.zip)z.tar.gzz.tgzz.tarN) __doc__Zpip._internal.utils.typingrtypingrZWHEEL_EXTENSIONZBZ2_EXTENSIONSZ XZ_EXTENSIONSZZIP_EXTENSIONSZTAR_EXTENSIONSZARCHIVE_EXTENSIONSrrA/usr/lib/python3.8/site-packages/pip/_internal/utils/filetypes.pys  utils/__pycache__/subprocess.cpython-38.opt-1.pyc000064400000012736152347654150015720 0ustar00U .e& @sddlmZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z ddlmZmZddlmZdd lmZerdd lmZmZmZmZmZmZmZmZdd lmZeeeefZ d Z!d dZ"ddZ#ddZ$ddZ%dddZ&ddZ'dS))absolute_importN) shlex_quote)InstallationError)console_to_strstr_to_display)subprocess_logger) HiddenTextpath_to_display)MYPY_CHECK_RUNNING) open_spinner)AnyCallableIterableListMappingOptionalTextUnion)SpinnerInterfacez(----------------------------------------cGs2g}|D]$}t|tr"||q||q|S)z& Create a CommandArgs object. ) isinstancelistextendappend)argsZ command_argsargrB/usr/lib/python3.8/site-packages/pip/_internal/utils/subprocess.py make_commands    rcCsddd|DS)z/ Format command arguments for display.  css,|]$}t|trtt|nt|VqdS)N)rrrstr.0rrrr ;sz&format_command_args..)joinrrrrformat_command_args1s r%cCsdd|DS)z= Return the arguments in their raw, unredacted form. cSs g|]}t|tr|jn|qSr)rrZsecretr rrr Fsz'reveal_command_args..rr$rrrreveal_command_argsAsr'c CsDt|}t|dd}t|}d|}dj|||t||td}|S)z Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline. z command bytes)ZdesczCommand errored out with exit status {exit_status}: command: {command_display} cwd: {cwd_display} Complete output ({line_count} lines): {output}{divider}) exit_statuscommand_display cwd_displayZ line_countoutputZdivider)r%rr r#formatlen LOG_DIVIDER) cmd_argscwdlinesr)Zcommandr*r+r,msgrrrmake_subprocess_output_errorKs    r4FraiseTc  Cs4|dkr g}|dkrg}|r*tj} tj} n tj} tj} t| k} | oN|dk } |dkr`t|}| d|tj }|r| ||D]}| |dqz.t jt|t jt jt j||d}|jWn6tk r}z| rtd||W5d}~XYnXg}t|j}|sqJ|}||d| || r|qz |W5|jrj|jX|jo||j|k}| r|r|dn |d|r*|dkr| s| rt||||jd }t |d !|j|}t"|n:|d krt#d ||j|n|d krnt$dt%|d&|S)a Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. NzRunning command %s)stderrstdinstdoutr1envz#Error %s while executing command %s errorZdoner5)r0r1r2r)zSCommand errored out with exit status {}: {} Check the logs for full command output.warnz$Command "%s" had error code %s in %signorezInvalid value: on_returncode=%sr()'rinfologgingINFOdebugDEBUGZgetEffectiveLevelr%osenvironcopyupdatepop subprocessPopenr'ZSTDOUTPIPEr7close ExceptionZcriticalrr8readlinerstriprZspinwait returncodeZfinishr4r;r-rZwarning ValueErrorreprr#)cmdZ show_stdoutr1Z on_returncodeZextra_ok_returncodesZ command_desc extra_environZ unset_environspinnerZlog_failed_cmdZlog_subprocessZ used_levelZshowing_subprocessZ use_spinnerr9nameprocexcZ all_outputlineZproc_had_errorr3Zexc_msgrrrcall_subprocessus               rZcsdfdd }|S)zProvide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. Nc s(t}t||||dW5QRXdS)N)r1rTrU)r rZ)rSr1rTrUmessagerrrunners z+runner_with_spinner_message..runner)NNr)r\r]rr[rrunner_with_spinner_messages r^) FNr5NNNNNT)(Z __future__rr?rCrHZpip._vendor.six.movesrZpip._internal.exceptionsrZpip._internal.utils.compatrrZpip._internal.utils.loggingrZpip._internal.utils.miscrr Zpip._internal.utils.typingr Zpip._internal.utils.uir typingr r rrrrrrrrZ CommandArgsr/rr%r'r4rZr^rrrrs>      (  ,  utils/__pycache__/marker_files.cpython-38.opt-1.pyc000064400000001640152347654150016163 0ustar00U .e7@s$ddlZdZdZddZddZdS)NzThis file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). zpip-delete-this-directory.txtcCstjtj|tS)N)ospathexistsjoinPIP_DELETE_MARKER_FILENAME) directoryrD/usr/lib/python3.8/site-packages/pip/_internal/utils/marker_files.pyhas_delete_marker_filesr c Cs2tj|t}t|d}|tW5QRXdS)z? Write the pip delete marker file into this directory. wN)rrrropenwriteDELETE_MARKER_MESSAGE)rfilepathZ marker_fprrr write_delete_marker_files r)Zos.pathrrrr rrrrr sutils/__pycache__/setuptools_build.cpython-38.opt-1.pyc000064400000002352152347654150017121 0ustar00U .e_@s:ddlZddlmZer(ddlmZmZdZdddZdS) N)MYPY_CHECK_RUNNING)ListSequencezimport sys, setuptools, tokenize; sys.argv[0] = {0!r}; __file__={0!r};f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))FcCsJtjg}|r|d|dt|g|r8|||rF|d|S)ao Get setuptools command arguments with shim wrapped setup file invocation. :param setup_py_path: The path to setup.py to be wrapped. :param global_options: Additional global options. :param no_user_config: If True, disables personal user configuration. :param unbuffered_output: If True, adds the unbuffered switch to the argument list. z-uz-cz --no-user-cfg)sys executableappendextend_SETUPTOOLS_SHIMformat)Z setup_py_pathZglobal_optionsZno_user_configZunbuffered_outputargsr H/usr/lib/python3.8/site-packages/pip/_internal/utils/setuptools_build.pymake_setuptools_shim_argss   r)NFF)rZpip._internal.utils.typingrtypingrrr rr r r r s   utils/__pycache__/__init__.cpython-38.pyc000064400000000233152347654150014315 0ustar00U .e@sdS)Nrrr@/usr/lib/python3.8/site-packages/pip/_internal/utils/__init__.pyutils/__pycache__/models.cpython-38.pyc000064400000003604152347654150014046 0ustar00U .e|@s dZddlZGdddeZdS)zUtilities for defining models Nc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS)KeyBasedCompareMixinz/usr/lib/python3.8/site-packages/pip/_internal/utils/models.py__init__ szKeyBasedCompareMixin.__init__cCs t|jSr)hashr)rrrr __hash__szKeyBasedCompareMixin.__hash__cCs||tjSr)_compareoperator__lt__rotherrrr rszKeyBasedCompareMixin.__lt__cCs||tjSr)r r__le__rrrr rszKeyBasedCompareMixin.__le__cCs||tjSr)r r__gt__rrrr rszKeyBasedCompareMixin.__gt__cCs||tjSr)r r__ge__rrrr rszKeyBasedCompareMixin.__ge__cCs||tjSr)r r__eq__rrrr r szKeyBasedCompareMixin.__eq__cCs||tjSr)r r__ne__rrrr r#szKeyBasedCompareMixin.__ne__cCst||jstS||j|jSr) isinstancerNotImplementedr)rrmethodrrr r &s zKeyBasedCompareMixin._compareN) __name__ __module__ __qualname____doc__r r rrrrrrr rrrr r sr)rrobjectrrrrr sutils/__pycache__/inject_securetransport.cpython-38.opt-1.pyc000064400000001644152347654150020323 0ustar00U .e*@sdZddlZddZedS)a-A helper module that injects SecureTransport, on import. The import should be done as early as possible, to ensure all requests and sessions (or whatever) are created after injecting SecureTransport. Note that we only do the injection on macOS, when the linked OpenSSL is too old to handle TLSv1.2. Nc CsxtjdkrdSz ddl}Wntk r0YdSX|jdkr@dSzddlm}Wnttfk rjYdSX|dS)Ndarwinri)securetransport) sysplatformssl ImportErrorZOPENSSL_VERSION_NUMBERZpip._vendor.urllib3.contribrOSErrorZinject_into_urllib3)rrr N/usr/lib/python3.8/site-packages/pip/_internal/utils/inject_securetransport.pyinject_securetransport s   r )__doc__rr r r r r s utils/__pycache__/packaging.cpython-38.opt-1.pyc000064400000005060152347654150015444 0ustar00U .e @sddlmZddlZddlmZddlmZddlmZm Z ddl m Z ddl m Z ddlmZerdd lmZmZdd lmZdd lmZeeZd d ZddZddZddZdS))absolute_importN) FeedParser) pkg_resources) specifiersversion)NoneMetadataError) display_path)MYPY_CHECK_RUNNING)OptionalTuple)Message) DistributioncCs4|dkr dSt|}tdtt|}||kS)a Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. NT.)rZ SpecifierSetrparsejoinmapstr)requires_python version_infoZrequires_python_specifierZpython_versionrA/usr/lib/python3.8/site-packages/pip/_internal/utils/packaging.pycheck_requires_pythons  rcCsd}t|tjr&||r&||}n0|dr@d}||}ntdt|jd}|dkrht ||t }| || S)z :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. ZMETADATAzPKG-INFOzNo metadata found in %sN) isinstancerZDistInfoDistribution has_metadata get_metadataloggerZwarningrlocationrrZfeedclose)distZ metadata_nameZmetadataZ feed_parserrrrr,s      rcCs&t|}|d}|dk r"t|}|S)z_ Return the "Requires-Python" metadata for a distribution, or None if not present. zRequires-PythonN)rgetr)rZ pkg_info_dictrrrrget_requires_pythonGs  r!cCs2|dr.|dD]}|r|SqdS)NZ INSTALLERr)rZget_metadata_linesstrip)rlinerrr get_installerXs  r$)Z __future__rZloggingZ email.parserrZ pip._vendorrZpip._vendor.packagingrrZpip._internal.exceptionsrZpip._internal.utils.miscrZpip._internal.utils.typingr typingr r Z email.messager Zpip._vendor.pkg_resourcesr Z getLogger__name__rrrr!r$rrrrs         utils/__pycache__/models.cpython-38.opt-1.pyc000064400000003604152347654150015005 0ustar00U .e|@s dZddlZGdddeZdS)zUtilities for defining models Nc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS)KeyBasedCompareMixinz/usr/lib/python3.8/site-packages/pip/_internal/utils/models.py__init__ szKeyBasedCompareMixin.__init__cCs t|jSr)hashr)rrrr __hash__szKeyBasedCompareMixin.__hash__cCs||tjSr)_compareoperator__lt__rotherrrr rszKeyBasedCompareMixin.__lt__cCs||tjSr)r r__le__rrrr rszKeyBasedCompareMixin.__le__cCs||tjSr)r r__gt__rrrr rszKeyBasedCompareMixin.__gt__cCs||tjSr)r r__ge__rrrr rszKeyBasedCompareMixin.__ge__cCs||tjSr)r r__eq__rrrr r szKeyBasedCompareMixin.__eq__cCs||tjSr)r r__ne__rrrr r#szKeyBasedCompareMixin.__ne__cCst||jstS||j|jSr) isinstancerNotImplementedr)rrmethodrrr r &s zKeyBasedCompareMixin._compareN) __name__ __module__ __qualname____doc__r r rrrrrrr rrrr r sr)rrobjectrrrrr sutils/__pycache__/setuptools_build.cpython-38.pyc000064400000002352152347654150016162 0ustar00U .e_@s:ddlZddlmZer(ddlmZmZdZdddZdS) N)MYPY_CHECK_RUNNING)ListSequencezimport sys, setuptools, tokenize; sys.argv[0] = {0!r}; __file__={0!r};f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))FcCsJtjg}|r|d|dt|g|r8|||rF|d|S)ao Get setuptools command arguments with shim wrapped setup file invocation. :param setup_py_path: The path to setup.py to be wrapped. :param global_options: Additional global options. :param no_user_config: If True, disables personal user configuration. :param unbuffered_output: If True, adds the unbuffered switch to the argument list. z-uz-cz --no-user-cfg)sys executableappendextend_SETUPTOOLS_SHIMformat)Z setup_py_pathZglobal_optionsZno_user_configZunbuffered_outputargsr H/usr/lib/python3.8/site-packages/pip/_internal/utils/setuptools_build.pymake_setuptools_shim_argss   r)NFF)rZpip._internal.utils.typingrtypingrrr rr r r r s   utils/__pycache__/virtualenv.cpython-38.pyc000064400000001556152347654150014766 0ustar00U .e{@s,ddlZddlZddlZddZddZdS)NcCs*ttdrdStjttdtjkr&dSdS)zM Return True if we're running inside a virtualenv, False otherwise. Z real_prefixT base_prefixF)hasattrsysprefixgetattrrrB/usr/lib/python3.8/site-packages/pip/_internal/utils/virtualenv.pyrunning_under_virtualenvs  r cCsBtjtjtj}tj|d}tr:tj|r:dSdSdS)z? Return True if in a venv and no system site packages. zno-global-site-packages.txtTFN) ospathdirnameabspathsite__file__joinr isfile)Z site_mod_dirZno_global_filerrrvirtualenv_no_globals r)Zos.pathr rrr rrrrrsutils/__pycache__/typing.cpython-38.opt-1.pyc000064400000002405152347654150015032 0ustar00U .ee@s dZdZdS)aBFor neatly implementing static typing in pip. `mypy` - the static type analysis tool we use - uses the `typing` module, which provides core functionality fundamental to mypy's functioning. Generally, `typing` would be imported at runtime and used in that fashion - it acts as a no-op at runtime and does not have any run-time overhead by design. As it turns out, `typing` is not vendorable - it uses separate sources for Python 2/Python 3. Thus, this codebase can not expect it to be present. To work around this, mypy allows the typing import to be behind a False-y optional to prevent it from running at runtime and type-comments can be used to remove the need for the types to be accessible directly during runtime. This module provides the False-y guard in a nicely named fashion so that a curious maintainer can reach here to read this. In pip, all static-typing related imports should be guarded as follows: from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 FN)__doc__ZMYPY_CHECK_RUNNINGrr>/usr/lib/python3.8/site-packages/pip/_internal/utils/typing.pysutils/__pycache__/compat.cpython-38.opt-1.pyc000064400000015267152347654150015015 0ustar00U .e]% @s~dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl m Z m Z ddl mZddlmZerddlmZmZmZmZz ddlZWnek rdZYnXeZz ddlZWnVek rzddlmZWn.ek rddlZeje_eje_YnXYnXd d d d d dddddg Z e!e"Z#edk pDeZ$e rddl%Z%z e%j&Z&Wne'k rxdZ&YnXe&dk Z(ndZ(ddl)m&Z&e rddZ*e+de*dZ,ndZ,d/ddZ-dd Z.e rd0dd Z/n d1dd Z/dd Z0e r dd l%m1Z1d!dZ2ndd"l3m4Z4d#dZ2d$d%Z5d&d'd(hZ6e j78d)pRe j7d*koRej9d+kZ:d,dZ;e/usr/lib/python3.8/site-packages/pip/_internal/utils/compat.py Lsz-backslashreplace_decode_fn..css|]}t|VqdSr)ord)rbrrrrNscss|]}d|VqdS)z\x%xNr)rcrrrrOs)rangestartendjoin)rZ raw_bytesrrrbackslashreplace_decode_fnKsr(backslashreplace_decodebackslashreplacecCst|tr|St}|r*t|jdkr.d}z||}WnDtk r|dkrXd}d |}t |||j|t d}YnXt t tdddd}|r|j|d d}||}|S) a For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. asciiutf-8Nz Bytes objectz&{} does not appear to be encoded as %s)errors __stderr__encodingr*) isinstancerlocaleZgetpreferredencodingcodecslookupnamedecodeUnicodeDecodeErrorformatloggerZwarningr)getattrsysencode)datadescr/Z decoded_dataZ msg_formatZoutput_encodingZoutput_encodedrrrstr_to_displayYs0     r>cCs t|ddS)z)r<rrrrsFcCst|tr|dS|S)Nr,)r0rr;sreplacerrrrs  cCs"t|tr|d|rdndS|S)Nr,rAstrict)r0bytesr5r?rrrrs cCs`ttdr6t|tjtjB}t|j}t|n&tj |sPt |j}n t d||S)a) Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. O_NOFOLLOWz1%s is a symlink; Will not return uid for symlinks) hasattrosopenO_RDONLYrDfstatst_uidclosepathislinkstatOSError)rLfdZfile_uidrrrrs     get_suffixescCsddtDS)NcSsg|] }|dqS)rr)rsuffixrrr sz*get_extension_suffixes..rQrrrrrsEXTENSION_SUFFIXEScCstSrrUrrrrrscCs0tj|}|dr,|dr,|dd}|S)zm Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 z~/z//N)rFrL expanduser startswith)rLZexpandedrrrrXs  rXpythonZwsgirefargparsewinZclintcCsNttjdrtj||Stjtj|}tjtj|}||kSdS)z>Provide an alternative for os.path.samefile on Windows/Python2rN)rErFrLrnormcaseabspath)Zfile1Zfile2Zpath1Zpath2rrrrs  cCs ttS) Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. )tupleshutilrrrrrrscCsdd}|dp|dp|d}|sbz(tttj}||}t|Wntk r`YnX|stjddtjdd f}t|dt|dfS) r`cSs\z4ddl}ddl}ddl}|d|||jd}Wntk rJYdSX|dkrXdS|S)NrZhhZ12345678)rr)fcntltermiosstruct unpack_fromZioctlZ TIOCGWINSZ Exception)rPrcrdrecrrrr ioctl_GWINSZsz'get_terminal_size..ioctl_GWINSZrrWZLINESZCOLUMNSP) rFrGctermidrHrKrgenvirongetint)rirhrPrrrr s)N)F)F)>__doc__Z __future__rrr2r1ZloggingrFrbr:Zpip._vendor.sixrrZpip._vendor.urllib3.utilrZpip._internal.utils.typingrtypingrr r r Z_ssl ImportErrorZsslr Z pip._vendorZipaddrZ IPAddressZ ip_addressZ IPNetworkZ ip_network__all__Z getLogger__name__r8ZHAS_TLSZimprAttributeErrorr importlib.utilr(register_errorr)r>rrrrRrZimportlib.machineryrVrXrplatformrYr4rrrErrrrrs           B        utils/__pycache__/logging.cpython-38.pyc000064400000021707152347654150014215 0ustar00U .e2@sddlmZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z ddl m Z ddlmZddlmZz ddlZWnek rddlZYnXzddlmZWnek rdZYnXdd lmZeZeZde_e d ZGd d d eZe r&e rd dZ nddZ ne r6ddZ nddZ ej!d%ddZ"ddZ#Gdddej$Z%ddZ&Gdddej'Z(Gdddej)j*Z+Gdd d eZ,Gd!d"d"eZ-d#d$Z.dS)&)absolute_importN)Filter getLogger)PY2)WINDOWS)DEPRECATION_MSG_PREFIX) ensure_dir)colorama)Forezpip.subprocessorc@seZdZdZdS)BrokenStdoutLoggingErrorzO Raised if BrokenPipeError occurs for the stdout stream while logging. N)__name__ __module__ __qualname____doc__rr?/usr/lib/python3.8/site-packages/pip/_internal/utils/logging.pyr ;sr cCs|tko|jtjtjfkSz1See the docstring for non-Windows Python 3 below.)IOErrorerrnoEINVALEPIPE exc_classexcrrr_is_broken_pipe_errorIsrcCs"|tkp |tko |jtjtjfkSr)BrokenPipeErrorOSErrorrrrrrrrrOscCs|tko|jtjkSr)rrrrrrrrUscCs|tkS)z Return whether an exception is a broken pipe error. Args: exc_class: an exception class. exc: an exception instance. )rrrrrrZsc cs.tj|7_z dVW5tj|8_XdS)zv A context manager which will cause the log output to be indented for any log messages emitted inside it. N) _log_state indentation)Znumrrr indent_loges r cCs ttddS)Nrr)getattrrrrrrget_indentationrsr"cs0eZdZfddZddZfddZZS)IndentingFormattercs$|dd|_tt|j||dS)z A logging.Formatter that obeys the indent_log() context manager. :param add_timestamp: A bool indicating output lines should be prefixed with their record's timestamp. add_timestampFN)popr$superr#__init__)selfargskwargs __class__rrr'xszIndentingFormatter.__init__cCs.|tjkrdS|trdS|tjkr*dSdS)zv Return the start of the formatted log message (not counting the prefix to add to each line). z WARNING: zERROR: )loggingWARNING startswithrERROR)r( formattedlevelnorrrget_message_starts   z$IndentingFormatter.get_message_startcsztt||}|||j}||}d|jrJ||d}d||jfdt7d fdd| dD}|S)z Calls the standard formatter, but will indent all of the log message lines by our current indentation level. r-z%Y-%m-%dT%H:%M:%Sz%s,%03d  csg|] }|qSrr).0lineprefixrr sz-IndentingFormatter.format..T) r&r#formatr4r3r$Z formatTimeZmsecsr"join splitlines)r(recordr2Z message_starttr+r8rr;s zIndentingFormatter.format)r r rr'r4r; __classcell__rrr+rr#vs r#csfdd}|S)Ncsdt|tjjgS)Nr-)r<listr ZStyleZ RESET_ALL)Zinpcolorsrrwrappedsz_color_wrap..wrappedr)rCrDrrBr _color_wraps rEcsheZdZer.ejeejfej eej fgZ ngZ d ddZ ddZ ddZdd Zfd d ZZS) ColorizedStreamHandlerNcCs.tj||||_tr*tr*t|j|_dSN)r. StreamHandlerr' _no_colorrr AnsiToWin32stream)r(rKno_colorrrrr'szColorizedStreamHandler.__init__cCs"trtr|jjtjkS|jtjkS)zA Return whether the handler is using sys.stdout. )rr rKrDsysstdoutr(rrr _using_stdoutsz$ColorizedStreamHandler._using_stdoutcCsXtr |jrdSt|jtjs"|jn|jj}t|dr@|r@dStj ddkrTdSdS)NFisattyTZTERMZANSI) r rI isinstancerKrJrDhasattrrQosenvironget)r(Z real_streamrrr should_colors z#ColorizedStreamHandler.should_colorcCs@tj||}|r<|jD]\}}|j|kr||}qmsglevelZcolorrrrr;s zColorizedStreamHandler.formatcs@tdd\}}|r0|r0t||r0ttt||S)Nr)rMexc_inforPrr r&rF handleError)r(r>rrr+rrr\s  z"ColorizedStreamHandler.handleError)NN)r r rr r.r1rEr ZREDr/ZYELLOWrXr'rPrWr;r\r@rrr+rrFs   rFc@seZdZddZdS)BetterRotatingFileHandlercCs ttj|jtjj|SrG) rrTpathdirnameZ baseFilenamer.handlersRotatingFileHandler_openrOrrrrbszBetterRotatingFileHandler._openN)r r rrbrrrrr]sr]c@seZdZddZddZdS)MaxLevelFiltercCs ||_dSrG)rZ)r(rZrrrr'szMaxLevelFilter.__init__cCs |j|jkSrG)r3rZr(r>rrrfilterszMaxLevelFilter.filterN)r r rr'rerrrrrcsrccs eZdZdZfddZZS)ExcludeLoggerFilterzQ A logging Filter that excludes records from a logger (or its children). cstt|| SrG)r&rfrerdr+rrreszExcludeLoggerFilter.filter)r r rrrer@rrr+rrf srfc Csf|dkrd}n.|dkrd}n |dkr*d}n|dkr8d}nd }tt|}|d k }|r\|}d}nd }|}|d krpdnd}d dd} ddd} dddg|rdgng} tjdddtjddtjddtjddtddtdd d!d"|| d#|| d$d%d&gd'd(d| d#|| d)d%gd'd(|| d#|| d)d*gd'd(d| d+|d d,d-d.|| d/d0d1|iid2|S)3znConfigures and sets up all of the logging Returns the requested logging level, as its integer value. DEBUGr/r1ZCRITICALINFONz /dev/null)rlr1zext://sys.stdoutzext://sys.stderr)rNstderrz2pip._internal.utils.logging.ColorizedStreamHandlerz5pip._internal.utils.logging.BetterRotatingFileHandler)rKfileconsoleconsole_errorsconsole_subprocessuser_logFz*pip._internal.utils.logging.MaxLevelFilter)()rZzlogging.Filter)rsnamez/pip._internal.utils.logging.ExcludeLoggerFilter)exclude_warningsrestrict_to_subprocessexclude_subprocessz %(message)s)rsr;T)rsr;r$)indentindent_with_timestamprKrNrwrurx)rZclassrLrKfilters formatterrmrvrnry)rZrzfilenameZdelayr|)rorprqrr)rZr`z pip._vendorrZ)versionZdisable_existing_loggersr{Z formattersr`rootZloggers)r!r.ZconfigZ dictConfigr/subprocess_loggerrtr#) verbosityrLZ user_log_filerZZ level_numberZinclude_user_logZadditional_log_fileZ root_levelZvendored_log_levelZ log_streamsZhandler_classesr`rrr setup_loggings      $Jr)r)/Z __future__r contextlibrr.Zlogging.handlersrTrMrrZpip._vendor.sixrZpip._internal.utils.compatrZpip._internal.utils.deprecationrZpip._internal.utils.miscrZ threading ImportErrorZdummy_threadingZ pip._vendorr Z _colorama ExceptionZpip._vendor.coloramar Zlocalrrrr rcontextmanagerr r"Z Formatterr#rErHrFr`rar]rcrfrrrrrsT              2K  utils/__pycache__/unpacking.cpython-38.opt-1.pyc000064400000014055152347654150015503 0ustar00U .e%@sXdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z mZmZddlmZddlmZerddlmZmZmZmZmZeeZee ZzddlZee 7ZWnek re d YnXzddl!Z!ee7ZWn ek re d YnXd d Z"d dZ#ddZ$ddZ%dddZ&ddZ'dddZ(dS)zUtilities related archives. )absolute_importN)InstallationError)BZ2_EXTENSIONSTAR_EXTENSIONS XZ_EXTENSIONSZIP_EXTENSIONS) ensure_dir)MYPY_CHECK_RUNNING)IterableListOptionalTextUnionzbz2 module is not availablezlzma module is not availablecCstd}t||S)zBGet the current umask which involves having to set it temporarily.r)osumask)maskrA/usr/lib/python3.8/site-packages/pip/_internal/utils/unpacking.py current_umask2s  rcCsh|dd}d|krHd|kr4|d|dksd}n8|trRd}n$|drfd}ntd|d }t||}zt d d | D}| D]}|j }|rt |d }tj||}t||sd }t||||zt|j|d|Wntjk rYnX|r4t|q|rz|||Wn>tk r} ztd||j | WYqW5d} ~ XYnXqz||} WnBttfk r} ztd||j | WYqW5d} ~ XYnXttj|t|d} t | | W5QRX| |!|||j"d@rt#|dt$dBqW5| XdS)a Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. z.gzz.tgzzr:gzzr:bz2zr:xzz.tarrz-Cannot determine compression type for file %szr:*cSsg|] }|jqSrr=).0memberrrr szuntar_file..rzQThe tar file ({}) has a file ({}) trying to install outside target directory ({})rFz/In the tar file %s the member %s is invalid: %sNr*r(r))%rlowerr2rrloggerZwarningtarfiler+r,r!Z getmembersr=rrrr/r%rr1Z data_filterreplaceZLinkOutsideDestinationErrorisdirZissymZ_extract_member ExceptionZ extractfileKeyErrorAttributeErrorr0r6r7utimerBr5r) r.r8rBZtarr;rHr>rr@excrArCrrr untar_files           rTcCstj|}|dks,|ts,t|rDt|||d dnR|dkslt |sl|t t t rxt||ntd|||td|dS)Nzapplication/zipz.whl)r9zapplication/x-gzipzZCannot unpack file %s (downloaded from %s, content-type: %s); cannot detect archive formatz%Cannot determine archive format of {})rrrealpathrJr2rr-Z is_zipfilerDrLZ is_tarfilerrrrTrKZcriticalrr1)r.r8Z content_typerrr unpack_files<     rV)T)N))__doc__Z __future__rZloggingrr6r3rLr-Zpip._internal.exceptionsrZpip._internal.utils.filetypesrrrrZpip._internal.utils.miscrZpip._internal.utils.typingr typingr r r r rZ getLogger__name__rKZSUPPORTED_EXTENSIONSbz2 ImportErrordebugZlzmarrr!r%rDrTrVrrrrsB        4^utils/__pycache__/virtualenv.cpython-38.opt-1.pyc000064400000001556152347654150015725 0ustar00U .e{@s,ddlZddlZddlZddZddZdS)NcCs*ttdrdStjttdtjkr&dSdS)zM Return True if we're running inside a virtualenv, False otherwise. Z real_prefixT base_prefixF)hasattrsysprefixgetattrrrB/usr/lib/python3.8/site-packages/pip/_internal/utils/virtualenv.pyrunning_under_virtualenvs  r cCsBtjtjtj}tj|d}tr:tj|r:dSdSdS)z? Return True if in a venv and no system site packages. zno-global-site-packages.txtTFN) ospathdirnameabspathsite__file__joinr isfile)Z site_mod_dirZno_global_filerrrvirtualenv_no_globals r)Zos.pathr rrr rrrrrsutils/__pycache__/compat.cpython-38.pyc000064400000015267152347654150014056 0ustar00U .e]% @s~dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl m Z m Z ddl mZddlmZerddlmZmZmZmZz ddlZWnek rdZYnXeZz ddlZWnVek rzddlmZWn.ek rddlZeje_eje_YnXYnXd d d d d dddddg Z e!e"Z#edk pDeZ$e rddl%Z%z e%j&Z&Wne'k rxdZ&YnXe&dk Z(ndZ(ddl)m&Z&e rddZ*e+de*dZ,ndZ,d/ddZ-dd Z.e rd0dd Z/n d1dd Z/dd Z0e r dd l%m1Z1d!dZ2ndd"l3m4Z4d#dZ2d$d%Z5d&d'd(hZ6e j78d)pRe j7d*koRej9d+kZ:d,dZ;e/usr/lib/python3.8/site-packages/pip/_internal/utils/compat.py Lsz-backslashreplace_decode_fn..css|]}t|VqdSr)ord)rbrrrrNscss|]}d|VqdS)z\x%xNr)rcrrrrOs)rangestartendjoin)rZ raw_bytesrrrbackslashreplace_decode_fnKsr(backslashreplace_decodebackslashreplacecCst|tr|St}|r*t|jdkr.d}z||}WnDtk r|dkrXd}d |}t |||j|t d}YnXt t tdddd}|r|j|d d}||}|S) a For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. asciiutf-8Nz Bytes objectz&{} does not appear to be encoded as %s)errors __stderr__encodingr*) isinstancerlocaleZgetpreferredencodingcodecslookupnamedecodeUnicodeDecodeErrorformatloggerZwarningr)getattrsysencode)datadescr/Z decoded_dataZ msg_formatZoutput_encodingZoutput_encodedrrrstr_to_displayYs0     r>cCs t|ddS)z)r<rrrrsFcCst|tr|dS|S)Nr,)r0rr;sreplacerrrrs  cCs"t|tr|d|rdndS|S)Nr,rAstrict)r0bytesr5r?rrrrs cCs`ttdr6t|tjtjB}t|j}t|n&tj |sPt |j}n t d||S)a) Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. O_NOFOLLOWz1%s is a symlink; Will not return uid for symlinks) hasattrosopenO_RDONLYrDfstatst_uidclosepathislinkstatOSError)rLfdZfile_uidrrrrs     get_suffixescCsddtDS)NcSsg|] }|dqS)rr)rsuffixrrr sz*get_extension_suffixes..rQrrrrrsEXTENSION_SUFFIXEScCstSrrUrrrrrscCs0tj|}|dr,|dr,|dd}|S)zm Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 z~/z//N)rFrL expanduser startswith)rLZexpandedrrrrXs  rXpythonZwsgirefargparsewinZclintcCsNttjdrtj||Stjtj|}tjtj|}||kSdS)z>Provide an alternative for os.path.samefile on Windows/Python2rN)rErFrLrnormcaseabspath)Zfile1Zfile2Zpath1Zpath2rrrrs  cCs ttS) Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. )tupleshutilrrrrrrscCsdd}|dp|dp|d}|sbz(tttj}||}t|Wntk r`YnX|stjddtjdd f}t|dt|dfS) r`cSs\z4ddl}ddl}ddl}|d|||jd}Wntk rJYdSX|dkrXdS|S)NrZhhZ12345678)rr)fcntltermiosstruct unpack_fromZioctlZ TIOCGWINSZ Exception)rPrcrdrecrrrr ioctl_GWINSZsz'get_terminal_size..ioctl_GWINSZrrWZLINESZCOLUMNSP) rFrGctermidrHrKrgenvirongetint)rirhrPrrrr s)N)F)F)>__doc__Z __future__rrr2r1ZloggingrFrbr:Zpip._vendor.sixrrZpip._vendor.urllib3.utilrZpip._internal.utils.typingrtypingrr r r Z_ssl ImportErrorZsslr Z pip._vendorZipaddrZ IPAddressZ ip_addressZ IPNetworkZ ip_network__all__Z getLogger__name__r8ZHAS_TLSZimprAttributeErrorr importlib.utilr(register_errorr)r>rrrrRrZimportlib.machineryrVrXrplatformrYr4rrrErrrrrs           B        utils/__pycache__/encoding.cpython-38.pyc000064400000002337152347654150014353 0ustar00U .e(@sddlZddlZddlZddlZddlmZerDddlmZmZm Z ej dfej dfej dfej dfejdfejd fejd fgZed Zd d ZdS)N)MYPY_CHECK_RUNNING)ListTupleTextzutf-8zutf-16z utf-16-bez utf-16-lezutf-32z utf-32-bez utf-32-lescoding[:=]\s*([-\w.]+)cCstD],\}}||r|t|d|Sq|dddD]D}|dddkrDt|rDt|dd}||SqD|t dpt S) zCheck a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3N r#asciiF) BOMS startswithlendecodesplit ENCODING_REsearchgroupslocaleZgetpreferredencodingsysgetdefaultencoding)dataZbomencodingliner@/usr/lib/python3.8/site-packages/pip/_internal/utils/encoding.py auto_decodes  r)codecsrrerZpip._internal.utils.typingrtypingrrrBOM_UTF8 BOM_UTF16 BOM_UTF16_BE BOM_UTF16_LE BOM_UTF32 BOM_UTF32_BE BOM_UTF32_LEr compilerrrrrrs   utils/__pycache__/filetypes.cpython-38.opt-1.pyc000064400000001054152347654150015523 0ustar00U .e;@sLdZddlmZer ddlmZdZdZdZdefZdZ eee eZ d S) zFiletype information. )MYPY_CHECK_RUNNING)Tuplez.whl)z.tar.bz2z.tbz)z.tar.xzz.txzz.tlzz.tar.lzz .tar.lzmaz.zip)z.tar.gzz.tgzz.tarN) __doc__Zpip._internal.utils.typingrtypingrZWHEEL_EXTENSIONZBZ2_EXTENSIONSZ XZ_EXTENSIONSZZIP_EXTENSIONSZTAR_EXTENSIONSZARCHIVE_EXTENSIONSrrA/usr/lib/python3.8/site-packages/pip/_internal/utils/filetypes.pys  utils/__pycache__/deprecation.cpython-38.opt-1.pyc000064400000005412152347654150016016 0ustar00U .e @sdZddlmZddlZddlZddlmZddlmZ ddl m Z e rXddl m Z mZdZGd d d eZdadd d Zd dZdddZdS)zN A module that implements tooling to enable easy warnings about deprecations. )absolute_importN)parse) __version__)MYPY_CHECK_RUNNING)AnyOptionalz DEPRECATION: c@s eZdZdS)PipDeprecationWarningN)__name__ __module__ __qualname__r r C/usr/lib/python3.8/site-packages/pip/_internal/utils/deprecation.pyrsrcCsZ|dk r$tdk rVt||||||n2t|trDtd}||nt||||||dS)Nzpip._internal.deprecations)_original_showwarning issubclassrloggingZ getLoggerZwarning)messagecategoryfilenamelinenofilelineZloggerr r r _showwarning!s*   rcCs(tjdtddtdkr$tjatt_dS)NdefaultT)append)warnings simplefilterrr showwarningrr r r r install_warning_logger2srcCsh|tdf|df|df|dfg}ddd|D}|dk rTttt|krTt|tj|td d dS) aHelper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. z{}z2pip {} will remove support for this functionality.zA possible replacement is {}.zPYou can find discussion regarding this at https://github.com/pypa/pip/issues/{}. css$|]\}}|dk r||VqdS)N)format).0valtemplater r r `szdeprecated..N)r stacklevel)DEPRECATION_MSG_PREFIXjoinrcurrent_versionrrwarn)reasonZ replacementZgone_inZissueZ sentencesrr r r deprecated>s  r+)NN)N)__doc__Z __future__rrrZpip._vendor.packaging.versionrZpiprr(Zpip._internal.utils.typingrtypingrrr&Warningrrrrr+r r r r s      utils/__pycache__/ui.cpython-38.pyc000064400000027042152347654150013202 0ustar00U .eR6@sxddlmZmZddlZddlZddlZddlZddlZddlm Z m Z mZddl m Z ddl mZmZddlmZmZmZddlmZddlmZdd lmZdd lmZdd lmZerdd lmZm Z m!Z!zdd l m"Z"Wne#k rdZ"YnXe$e%Z&ddZ'e'eeZ(Gddde)Z*GdddeZ+GdddeZ,Gddde)Z-Gddde)Z.Gddde.e*e-Z/Gddde/e(Z0Gddde/e+Z1Gd d!d!e/eZ2Gd"d#d#e/eZ3Gd$d%d%e/e,Z4Gd&d'd'e.e*e-eZ5e1e1fe0e5fe2e5fe3e5fe4e5fd(Z6d7d)d*Z7ej8d+d,Z9Gd-d.d.e)Z:Gd/d0d0e)Z;Gd1d2d2e;ZdS)8)absolute_importdivisionN)SIGINTdefault_int_handlersignal)six) HIDE_CURSOR SHOW_CURSOR)BarFillingCirclesBarIncrementalBar)Spinner)WINDOWS)get_indentation) format_size)MYPY_CHECK_RUNNING)AnyIteratorIO)coloramacCst|jdd}|s|St|dtt|dtg}|tt|dg7}zt||Wntk rz|YSX|SdS)NencodingZ empty_fillZfillphases)getattrfilerZ text_typelistjoinencodeUnicodeEncodeError)Z preferredZfallbackrZ charactersr:/usr/lib/python3.8/site-packages/pip/_internal/utils/ui.py_select_progress_class%s r cs4eZdZdZfddZfddZddZZS)InterruptibleMixina Helper to ensure that self.finish() gets called on keyboard interrupt. This allows downloads to be interrupted without leaving temporary state (like hidden cursors) behind. This class is similar to the progress library's existing SigIntMixin helper, but as of version 1.2, that helper has the following problems: 1. It calls sys.exit(). 2. It discards the existing SIGINT handler completely. 3. It leaves its own handler in place even after an uninterrupted finish, which will have unexpected delayed effects if the user triggers an unrelated keyboard interrupt some time after a progress-displaying download has already completed, for example. cs4tt|j||tt|j|_|jdkr0t|_dS)z= Save the original SIGINT handler for later. N)superr!__init__rr handle_sigintoriginal_handlerrselfargskwargs __class__rrr#Us zInterruptibleMixin.__init__cstt|tt|jdS)z Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. N)r"r!finishrrr%r'r*rrr,eszInterruptibleMixin.finishcCs||||dS)z Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. N)r,r%)r'Zsignumframerrrr$osz InterruptibleMixin.handle_sigint)__name__ __module__ __qualname____doc__r#r,r$ __classcell__rrr*rr!Cs  r!c@seZdZddZdS) SilentBarcCsdSNrr-rrrupdate|szSilentBar.updateN)r/r0r1r6rrrrr4zsr4c@seZdZdZdZdZdZdS) BlueEmojiBar %(percent)d%% )u🔹u🔷u🔵N)r/r0r1suffixZ bar_prefixZ bar_suffixrrrrrr7sr7csJeZdZfddZeddZeddZeddZd d d ZZ S) DownloadProgressMixincs,tt|j||dtd|j|_dS)Nr9)r"r;r#rmessager&r*rrr#szDownloadProgressMixin.__init__cCs t|jSr5)rindexr-rrr downloadedsz DownloadProgressMixin.downloadedcCs |jdkrdStd|jdS)Ngz...z/s)Zavgrr-rrrdownload_speeds z$DownloadProgressMixin.download_speedcCs|jrd|jSdS)Nzeta %s)ZetaZeta_tdr-rrr pretty_etas z DownloadProgressMixin.pretty_etar@ccs&|D]}|V||q|dSr5)nextr,)r'itnxrrriters zDownloadProgressMixin.iter)r@) r/r0r1r#propertyr?rArCrHr3rrr*rr;s    r;cseZdZfddZZS) WindowsMixincs\trjrd_ttj||trXtrXtj_fddj_fddj_ dS)NFcs jjSr5)rwrappedisattyrr-rrz'WindowsMixin.__init__..cs jjSr5)rrKflushrr-rrrMrN) rZ hide_cursorr"rJr#rZ AnsiToWin32rrLrOr&r*r-rr#s zWindowsMixin.__init__)r/r0r1r#r3rrr*rrJsrJc@seZdZejZdZdZdS)BaseDownloadProgressBarr8z0%(downloaded)s %(download_speed)s %(pretty_eta)sN)r/r0r1sysstdoutrr=r:rrrrrPsrPc@s eZdZdS)DefaultDownloadProgressBarNr/r0r1rrrrrSsrSc@s eZdZdS)DownloadSilentBarNrTrrrrrUsrUc@s eZdZdS) DownloadBarNrTrrrrrVsrVc@s eZdZdS)DownloadFillingCirclesBarNrTrrrrrWsrWc@s eZdZdS)DownloadBlueEmojiProgressBarNrTrrrrrXsrXc@s&eZdZejZdZddZddZdS)DownloadProgressSpinnerz!%(downloaded)s %(download_speed)scCs"t|dst|j|_t|jS)N_phaser)hasattr itertoolscyclerrZrDr-rrr next_phases z"DownloadProgressSpinner.next_phasecCsN|j|}|}|j|}d||r*dnd||r6dnd|g}||dS)NrBr9)r=r^r:rZwriteln)r'r=Zphaser:linerrrr6s    zDownloadProgressSpinner.updateN) r/r0r1rQrRrr:r^r6rrrrrYsrY)ZoffZonasciiZprettyZemojicCs8|dks|dkr t|djSt|d|djSdS)Nrr@)max) BAR_TYPESrH)Z progress_barrarrrDownloadProgressProvider srcc csPtr dVn@|r"ttjkr*dVn"|tz dVW5|tXdSr5) rrLloggergetEffectiveLevelloggingINFOwriterr )rrrr hidden_cursors  ric@s$eZdZddZddZddZdS) RateLimitercCs||_d|_dS)Nr)_min_update_interval_seconds _last_update)r'min_update_interval_secondsrrrr#-szRateLimiter.__init__cCst}||j}||jkSr5)timerlrk)r'ZnowZdeltarrrready2s zRateLimiter.readycCst|_dSr5)rnrlr-rrrreset8szRateLimiter.resetN)r/r0r1r#rorprrrrrj,srjc@seZdZddZddZdS)SpinnerInterfacecCs tdSr5NotImplementedErrorr-rrrspin>szSpinnerInterface.spincCs tdSr5rrr'Z final_statusrrrr,BszSpinnerInterface.finishN)r/r0r1rtr,rrrrrq=srqc@s.eZdZd ddZddZdd Zd d ZdS) InteractiveSpinnerN-\|/?cCs\||_|dkrtj}||_t||_d|_t||_ |j dt |jdd|_ dS)NFr9z ... r) _messagerQrR_filerj _rate_limiter _finishedr\r] _spin_cyclerhr_width)r'r=rZ spin_charsrmrrrr#Hs  zInteractiveSpinner.__init__cCs\|jr td|j}|j|d|j||j|t||_|j|jdS)Nr9) r|AssertionErrorr~rzrhlenrOr{rp)r'statusZbackuprrr_writeWs     zInteractiveSpinner._writecCs,|jr dS|jsdS|t|jdSr5)r|r{rorrDr}r-rrrrtcs  zInteractiveSpinner.spincCs4|jr dS|||jd|jd|_dS)N T)r|rrzrhrOrurrrr,ks    zInteractiveSpinner.finish)Nrwrx)r/r0r1r#rrtr,rrrrrvGs   rvc@s.eZdZd ddZddZddZdd Zd S) NonInteractiveSpinner<cCs$||_d|_t||_|ddS)NFZstarted)ryr|rjr{_update)r'r=rmrrrr#zs zNonInteractiveSpinner.__init__cCs(|jr t|jtd|j|dS)Nz%s: %s)r|rr{rprdinfory)r'rrrrrs  zNonInteractiveSpinner._updatecCs&|jr dS|jsdS|ddS)Nzstill running...)r|r{rorr-rrrrts  zNonInteractiveSpinner.spincCs$|jr dS|d|fd|_dS)Nzfinished with status '%s'T)r|rrurrrr,szNonInteractiveSpinner.finishN)r)r/r0r1r#rrtr,rrrrrys rc cstjr"ttjkr"t|}nt|}z t tj |VW5QRXWn>t k rj| dYn*t k r| dYn X| ddS)NZcancelederrorZdone) rQrRrLrdrerfrgrvrriKeyboardInterruptr, Exception)r=Zspinnerrrr open_spinners    r)N)?Z __future__rr contextlibr\rfrQrnrrrZ pip._vendorrZpip._vendor.progressrr Zpip._vendor.progress.barr r r Zpip._vendor.progress.spinnerr Zpip._internal.utils.compatrZpip._internal.utils.loggingrZpip._internal.utils.miscrZpip._internal.utils.typingrtypingrrrrrZ getLoggerr/rdr Z_BaseBarobjectr!r4r7r;rJrPrSrUrVrWrXrYrbrccontextmanagerrirjrqrvrrrrrrs~         7       2utils/__pycache__/appdirs.cpython-38.pyc000064400000017553152347654150014235 0ustar00U .e&&@sdZddlmZddlZddlZddlmZmZddlm Z m Z ddl m Z e r\ddl mZdd Zdd d ZdddZddZddZddZe rzddlZeZWnek reZYnXddZdS)zd This code was taken from https://github.com/ActiveState/appdirs and modified to suit our purposes. )absolute_importN)PY2 text_type)WINDOWS expanduser)MYPY_CHECK_RUNNING)ListcCstr Unix: ~/.cache/ (XDG default) Windows: C:\Users\\AppData\Local\\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir`). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. CSIDL_LOCAL_APPDATAZCachedarwinz~/Library/CachesZXDG_CACHE_HOMEz~/.cache)rospathnormpath_get_win_folderr isinstancer_win_path_to_bytesjoinsysplatformrgetenv)appnamer r?/usr/lib/python3.8/site-packages/pip/_internal/utils/appdirs.pyuser_cache_dirs rFcCstr,|r dpd}tjtjt||}ndtjdkrvtjtjt d|rbtjt d|ntjt d|}ntjt dt d|}|S)a Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/ if it exists, else ~/.config/ Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\\ ... ...Application Data\ Win XP (roaming): C:\Documents and Settings\\Local ... ...Settings\Application Data\ Win 7 (not roaming): C:\\Users\\AppData\Local\ Win 7 (roaming): C:\\Users\\AppData\Roaming\ For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/". CSIDL_APPDATAr r z~/Library/Application Support/z ~/.config/Z XDG_DATA_HOMEz~/.local/share) rr r rr rrrisdirrr)rroamingconstr rrr user_data_dirHs,    rTcCsHtrt||d}n2tjdkr&t|}ntdtd}tj||}|S)arReturn full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default True) can be set False to not use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/ Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/". )rr ZXDG_CONFIG_HOMEz ~/.config) rrrrr rrr r)rrr rrruser_config_dir}s  rcstr&tjtd}tj|g}nVtjdkrBtjdg}n:tdd}|rnfdd| tj D}ng}| d|S) aReturn a list of potential user-shared config dirs for this application. "appname" is the name of application. Typical user config directories are: macOS: /Library/Application Support// Unix: /etc or $XDG_CONFIG_DIRS[i]// for each value in $XDG_CONFIG_DIRS Win XP: C:\Documents and Settings\All Users\Application ... ...Data\\ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: Hidden, but writeable on Win 7: C:\ProgramData\\ CSIDL_COMMON_APPDATAr z/Library/Application SupportZXDG_CONFIG_DIRSz/etc/xdgcsg|]}tjt|qSr)r r rr).0xrrr sz$site_config_dirs..z/etc) rr r r rrrrrsplitpathsepappend)rr ZpathlistZxdg_config_dirsrr"rsite_config_dirss     r'cCs:ddl}dddd|}||jd}|||\}}|S)z This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. rNZAppDatazCommon AppDataz Local AppDatarrr z@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)_winregOpenKeyHKEY_CURRENT_USERZ QueryValueEx) csidl_namer)Zshell_folder_namekeyZ directoryZ_typerrr_get_win_folder_from_registrysr.cCsdddd|}td}tj}|jd|dd|d}|D]}t|dkr. If encoding using ASCII and MBCS fails, return the original Unicode path. )ASCIIZMBCS)encodeUnicodeEncodeError LookupError)r encodingrrrrs r)F)T)__doc__Z __future__rr rZpip._vendor.sixrrZpip._internal.utils.compatrrZpip._internal.utils.typingrtypingrrrrr'r.r8r3r ImportErrorrrrrrs*   1 5 ") utils/__pycache__/temp_dir.cpython-38.opt-1.pyc000064400000011365152347654150015330 0ustar00U .e@sddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z e r\ddl m Z eeZGdddeZGdd d eZdS) )absolute_importN)rmtree)MYPY_CHECK_RUNNING)OptionalcsVeZdZdZdfdd ZeddZdd Zd d Zd d Z ddZ ddZ Z S) TempDirectoryaMHelper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. NtempcsPtt||dkr"|dkr"d}|dkr4||}||_d|_||_||_dS)NTF)superr__init___create_path_deleteddeletekind)selfpathr r __class__@/usr/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.pyr +s zTempDirectory.__init__cCs|jSN)r rrrrr@szTempDirectory.pathcCsd|jj|jS)Nz <{} {!r}>)formatr__name__rrrrr__repr__HszTempDirectory.__repr__cCs|Srrrrrr __enter__KszTempDirectory.__enter__cCs|jr|dSr)r cleanup)rexcvaluetbrrr__exit__NszTempDirectory.__exit__cCs.tjtjd|d}td||S)zECreate a temporary directory and store its path in self.path pip-{}-prefixCreated temporary directory: {})osrrealpathtempfilemkdtemprloggerdebug)rrrrrrr Rs zTempDirectory._createcCs"d|_tj|jrt|jdS)z?Remove the temporary directory created and reset state TN)r r$rexistsr rrrrrr_szTempDirectory.cleanup)NNr) r __module__ __qualname____doc__r propertyrrrrr r __classcell__rrrrrs  rcs:eZdZdZdZd fdd ZeddZdd ZZ S) AdjacentTempDirectoryaHelper class that creates a temporary directory adjacent to a real one. Attributes: original The original directory to create a temp directory for. path After calling create() or entering, contains the full path to the temporary directory. delete Whether the directory should be deleted when exiting (when used as a contextmanager) z-~.=%0123456789Ncs"|d|_tt|j|ddS)Nz/\)r )rstriporiginalrr0r )rr2r rrrr |s zAdjacentTempDirectory.__init__ccstdt|D]D}t|j|dD],}dd|||d}||kr$|Vq$qtt|jD]8}t|j|D]$}dd||}||krt|VqtqbdS)a Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). ~N)rangelen itertoolscombinations_with_replacement LEADING_CHARSjoin)clsnamei candidatenew_namerrr_generate_namess  z%AdjacentTempDirectory._generate_namesc Cstj|j\}}||D]b}tj||}zt|Wn0tk rl}z|jtj kr\W5d}~XYqXtj |}qqtj t j d |d}td ||S)Nr r!r#)r$rsplitr2rAr;mkdirOSErrorerrnoZEEXISTr%r&r'rr(r))rrrootr=r?rZexrrrr s  zAdjacentTempDirectory._create)N) rr+r,r-r:r classmethodrAr r/rrrrr0gs  r0)Z __future__rrEr8ZloggingZos.pathr$r&Zpip._internal.utils.miscrZpip._internal.utils.typingrtypingrZ getLoggerrr(objectrr0rrrrs     Qutils/__pycache__/urls.cpython-38.pyc000064400000002671152347654150013553 0ustar00U .e@shddlZddlZddlmZddlmZddlmZerLddl m Z m Z m Z ddZ dd Zd d ZdS) N)parse)request)MYPY_CHECK_RUNNING)OptionalTextUnioncCs d|kr dS|dddS)N:r)splitlower)urlr s    utils/__pycache__/typing.cpython-38.pyc000064400000002405152347654150014073 0ustar00U .ee@s dZdZdS)aBFor neatly implementing static typing in pip. `mypy` - the static type analysis tool we use - uses the `typing` module, which provides core functionality fundamental to mypy's functioning. Generally, `typing` would be imported at runtime and used in that fashion - it acts as a no-op at runtime and does not have any run-time overhead by design. As it turns out, `typing` is not vendorable - it uses separate sources for Python 2/Python 3. Thus, this codebase can not expect it to be present. To work around this, mypy allows the typing import to be behind a False-y optional to prevent it from running at runtime and type-comments can be used to remove the need for the types to be accessible directly during runtime. This module provides the False-y guard in a nicely named fashion so that a curious maintainer can reach here to read this. In pip, all static-typing related imports should be guarded as follows: from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 FN)__doc__ZMYPY_CHECK_RUNNINGrr>/usr/lib/python3.8/site-packages/pip/_internal/utils/typing.pysutils/__pycache__/__init__.cpython-38.opt-1.pyc000064400000000233152347654150015254 0ustar00U .e@sdS)Nrrr@/usr/lib/python3.8/site-packages/pip/_internal/utils/__init__.pyutils/__pycache__/hashes.cpython-38.pyc000064400000010060152347654150014030 0ustar00U .e@sddlmZddlZddlmZmZmZddlmZm Z m Z ddl m Z ddl mZerddlmZmZmZmZmZddlmZerdd lmZn dd lmZd Zd d d gZGdddeZGdddeZdS))absolute_importN) iteritemsiterkeys itervalues) HashMismatch HashMissingInstallationError) read_chunks)MYPY_CHECK_RUNNING)DictListBinaryIONoReturnIterator)PY3)_Hash)_hashZsha256Zsha384Zsha512c@s^eZdZdZdddZeddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS)HasheszaA wrapper that builds multiple hashes at once and checks them against known-good values NcCs|dkr in||_dS)zo :param hashes: A dict of algorithm names pointing to lists of allowed hex digests N)_allowed)selfhashesr>/usr/lib/python3.8/site-packages/pip/_internal/utils/hashes.py__init__,szHashes.__init__cCstdd|jDS)Ncss|]}t|VqdSN)len).0Zdigestsrrr 7sz&Hashes.digest_count..)sumrvaluesrrrr digest_count4szHashes.digest_countcCs||j|gkS)z/Return whether the given hex digest is allowed.)rget)r hash_nameZ hex_digestrrris_hash_allowed9szHashes.is_hash_allowedc Csi}t|jD]<}zt|||<Wqttfk rHtd|YqXq|D]}t|D]}||q\qPt |D] \}}| |j|krvdSqv| |dS)zCheck good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. zUnknown hash name: %sN) rrhashlibnew ValueError TypeErrorrrupdater hexdigest_raise)rZchunksgotsr#chunkhashZgotrrrcheck_against_chunksAs zHashes.check_against_chunkscCst|j|dSr)rrrr,rrrr+Ysz Hashes._raisecCs|t|S)zaCheck good hashes against a file-like object Raise HashMismatch if none match. )r/r )rfilerrrcheck_against_file]szHashes.check_against_filec Cs,t|d}||W5QRSQRXdS)Nrb)openr2)rpathr1rrrcheck_against_pathfs zHashes.check_against_pathcCs t|jS)z,Return whether I know any known-good hashes.)boolrr rrr __nonzero__kszHashes.__nonzero__cCs|Sr)r8r rrr__bool__pszHashes.__bool__)N)__name__ __module__ __qualname____doc__rpropertyr!r$r/r+r2r6r8r9rrrrr's   rcs(eZdZdZfddZddZZS) MissingHasheszA workalike for Hashes used when we're missing a hash for a requirement It computes the actual hash of the requirement and raises a HashMissing exception showing it to the user. cstt|jtgiddS)z!Don't offer the ``hashes`` kwarg.)rN)superr?r FAVORITE_HASHr  __class__rrr|szMissingHashes.__init__cCst|tdSr)rrAr*r0rrrr+szMissingHashes._raise)r:r;r<r=rr+ __classcell__rrrBrr?us r?)Z __future__rr%Zpip._vendor.sixrrrZpip._internal.exceptionsrrrZpip._internal.utils.miscr Zpip._internal.utils.typingr typingr r r rrrrrrAZ STRONG_HASHESobjectrr?rrrrs      Nutils/__pycache__/subprocess.cpython-38.pyc000064400000012736152347654150014761 0ustar00U .e& @sddlmZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z ddlmZmZddlmZdd lmZerdd lmZmZmZmZmZmZmZmZdd lmZeeeefZ d Z!d dZ"ddZ#ddZ$ddZ%dddZ&ddZ'dS))absolute_importN) shlex_quote)InstallationError)console_to_strstr_to_display)subprocess_logger) HiddenTextpath_to_display)MYPY_CHECK_RUNNING) open_spinner)AnyCallableIterableListMappingOptionalTextUnion)SpinnerInterfacez(----------------------------------------cGs2g}|D]$}t|tr"||q||q|S)z& Create a CommandArgs object. ) isinstancelistextendappend)argsZ command_argsargrB/usr/lib/python3.8/site-packages/pip/_internal/utils/subprocess.py make_commands    rcCsddd|DS)z/ Format command arguments for display.  css,|]$}t|trtt|nt|VqdS)N)rrrstr.0rrrr ;sz&format_command_args..)joinrrrrformat_command_args1s r%cCsdd|DS)z= Return the arguments in their raw, unredacted form. cSs g|]}t|tr|jn|qSr)rrZsecretr rrr Fsz'reveal_command_args..rr$rrrreveal_command_argsAsr'c CsDt|}t|dd}t|}d|}dj|||t||td}|S)z Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline. z command bytes)ZdesczCommand errored out with exit status {exit_status}: command: {command_display} cwd: {cwd_display} Complete output ({line_count} lines): {output}{divider}) exit_statuscommand_display cwd_displayZ line_countoutputZdivider)r%rr r#formatlen LOG_DIVIDER) cmd_argscwdlinesr)Zcommandr*r+r,msgrrrmake_subprocess_output_errorKs    r4FraiseTc  Cs4|dkr g}|dkrg}|r*tj} tj} n tj} tj} t| k} | oN|dk } |dkr`t|}| d|tj }|r| ||D]}| |dqz.t jt|t jt jt j||d}|jWn6tk r}z| rtd||W5d}~XYnXg}t|j}|sqJ|}||d| || r|qz |W5|jrj|jX|jo||j|k}| r|r|dn |d|r*|dkr| s| rt||||jd }t |d !|j|}t"|n:|d krt#d ||j|n|d krnt$dt%|d&|S)a Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. NzRunning command %s)stderrstdinstdoutr1envz#Error %s while executing command %s errorZdoner5)r0r1r2r)zSCommand errored out with exit status {}: {} Check the logs for full command output.warnz$Command "%s" had error code %s in %signorezInvalid value: on_returncode=%sr()'rinfologgingINFOdebugDEBUGZgetEffectiveLevelr%osenvironcopyupdatepop subprocessPopenr'ZSTDOUTPIPEr7close ExceptionZcriticalrr8readlinerstriprZspinwait returncodeZfinishr4r;r-rZwarning ValueErrorreprr#)cmdZ show_stdoutr1Z on_returncodeZextra_ok_returncodesZ command_desc extra_environZ unset_environspinnerZlog_failed_cmdZlog_subprocessZ used_levelZshowing_subprocessZ use_spinnerr9nameprocexcZ all_outputlineZproc_had_errorr3Zexc_msgrrrcall_subprocessus               rZcsdfdd }|S)zProvide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. Nc s(t}t||||dW5QRXdS)N)r1rTrU)r rZ)rSr1rTrUmessagerrrunners z+runner_with_spinner_message..runner)NNr)r\r]rr[rrunner_with_spinner_messages r^) FNr5NNNNNT)(Z __future__rr?rCrHZpip._vendor.six.movesrZpip._internal.exceptionsrZpip._internal.utils.compatrrZpip._internal.utils.loggingrZpip._internal.utils.miscrr Zpip._internal.utils.typingr Zpip._internal.utils.uir typingr r rrrrrrrrZ CommandArgsr/rr%r'r4rZr^rrrrs>      (  ,  utils/__pycache__/packaging.cpython-38.pyc000064400000005060152347654150014505 0ustar00U .e @sddlmZddlZddlmZddlmZddlmZm Z ddl m Z ddl m Z ddlmZerdd lmZmZdd lmZdd lmZeeZd d ZddZddZddZdS))absolute_importN) FeedParser) pkg_resources) specifiersversion)NoneMetadataError) display_path)MYPY_CHECK_RUNNING)OptionalTuple)Message) DistributioncCs4|dkr dSt|}tdtt|}||kS)a Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. NT.)rZ SpecifierSetrparsejoinmapstr)requires_python version_infoZrequires_python_specifierZpython_versionrA/usr/lib/python3.8/site-packages/pip/_internal/utils/packaging.pycheck_requires_pythons  rcCsd}t|tjr&||r&||}n0|dr@d}||}ntdt|jd}|dkrht ||t }| || S)z :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. ZMETADATAzPKG-INFOzNo metadata found in %sN) isinstancerZDistInfoDistribution has_metadata get_metadataloggerZwarningrlocationrrZfeedclose)distZ metadata_nameZmetadataZ feed_parserrrrr,s      rcCs&t|}|d}|dk r"t|}|S)z_ Return the "Requires-Python" metadata for a distribution, or None if not present. zRequires-PythonN)rgetr)rZ pkg_info_dictrrrrget_requires_pythonGs  r!cCs2|dr.|dD]}|r|SqdS)NZ INSTALLERr)rZget_metadata_linesstrip)rlinerrr get_installerXs  r$)Z __future__rZloggingZ email.parserrZ pip._vendorrZpip._vendor.packagingrrZpip._internal.exceptionsrZpip._internal.utils.miscrZpip._internal.utils.typingr typingr r Z email.messager Zpip._vendor.pkg_resourcesr Z getLogger__name__rrrr!r$rrrrs         utils/__pycache__/temp_dir.cpython-38.pyc000064400000011517152347654150014370 0ustar00U .e@sddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z e r\ddl m Z eeZGdddeZGdd d eZdS) )absolute_importN)rmtree)MYPY_CHECK_RUNNING)OptionalcsVeZdZdZdfdd ZeddZdd Zd d Zd d Z ddZ ddZ Z S) TempDirectoryaMHelper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. NtempcsPtt||dkr"|dkr"d}|dkr4||}||_d|_||_||_dS)NTF)superr__init___create_path_deleteddeletekind)selfpathr r __class__@/usr/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.pyr +s zTempDirectory.__init__cCs|jrtd|j|jS)Nz$Attempted to access deleted path: {})r AssertionErrorformatr rrrrr@s zTempDirectory.pathcCsd|jj|jS)Nz <{} {!r}>)rr__name__rrrrr__repr__HszTempDirectory.__repr__cCs|SNrrrrr __enter__KszTempDirectory.__enter__cCs|jr|dSr)r cleanup)rexcvaluetbrrr__exit__NszTempDirectory.__exit__cCs.tjtjd|d}td||S)zECreate a temporary directory and store its path in self.path pip-{}-prefixCreated temporary directory: {})osrrealpathtempfilemkdtemprloggerdebug)rrrrrrr Rs zTempDirectory._createcCs"d|_tj|jrt|jdS)z?Remove the temporary directory created and reset state TN)r r%rexistsr rrrrrr_szTempDirectory.cleanup)NNr) r __module__ __qualname____doc__r propertyrrrr r r __classcell__rrrrrs  rcs:eZdZdZdZd fdd ZeddZdd ZZ S) AdjacentTempDirectoryaHelper class that creates a temporary directory adjacent to a real one. Attributes: original The original directory to create a temp directory for. path After calling create() or entering, contains the full path to the temporary directory. delete Whether the directory should be deleted when exiting (when used as a contextmanager) z-~.=%0123456789Ncs"|d|_tt|j|ddS)Nz/\)r )rstriporiginalrr1r )rr3r rrrr |s zAdjacentTempDirectory.__init__ccstdt|D]D}t|j|dD],}dd|||d}||kr$|Vq$qtt|jD]8}t|j|D]$}dd||}||krt|VqtqbdS)a Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). ~N)rangelen itertoolscombinations_with_replacement LEADING_CHARSjoin)clsnamei candidatenew_namerrr_generate_namess  z%AdjacentTempDirectory._generate_namesc Cstj|j\}}||D]b}tj||}zt|Wn0tk rl}z|jtj kr\W5d}~XYqXtj |}qqtj t j d |d}td ||S)Nr!r"r$)r%rsplitr3rBr<mkdirOSErrorerrnoZEEXISTr&r'r(rr)r*)rrrootr>r@rZexrrrr s  zAdjacentTempDirectory._create)N) rr,r-r.r;r classmethodrBr r0rrrrr1gs  r1)Z __future__rrFr9ZloggingZos.pathr%r'Zpip._internal.utils.miscrZpip._internal.utils.typingrtypingrZ getLoggerrr)objectrr1rrrrs     Qutils/filesystem.py000064400000015437152347654150010470 0ustar00import errno import fnmatch import os import os.path import random import shutil import stat import sys from contextlib import contextmanager from tempfile import NamedTemporaryFile # NOTE: retrying is not annotated in typeshed as on 2017-07-17, which is # why we ignore the type on this import. from pip._vendor.retrying import retry # type: ignore from pip._vendor.six import PY2 from pip._internal.utils.compat import get_path_uid from pip._internal.utils.misc import format_size from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast if MYPY_CHECK_RUNNING: from typing import Any, BinaryIO, Iterator, List, Union class NamedTemporaryFileResult(BinaryIO): @property def file(self): # type: () -> BinaryIO pass def check_path_owner(path): # type: (str) -> bool # If we don't have a way to check the effective uid of this process, then # we'll just assume that we own the directory. if sys.platform == "win32" or not hasattr(os, "geteuid"): return True assert os.path.isabs(path) previous = None while path != previous: if os.path.lexists(path): # Check if path is writable by current user. if os.geteuid() == 0: # Special handling for root user in order to handle properly # cases where users use sudo without -H flag. try: path_uid = get_path_uid(path) except OSError: return False return path_uid == 0 else: return os.access(path, os.W_OK) else: previous, path = path, os.path.dirname(path) return False # assume we don't own the path def copy2_fixed(src, dest): # type: (str, str) -> None """Wrap shutil.copy2() but map errors copying socket files to SpecialFileError as expected. See also https://bugs.python.org/issue37700. """ try: shutil.copy2(src, dest) except (OSError, IOError): for f in [src, dest]: try: is_socket_file = is_socket(f) except OSError: # An error has already occurred. Another error here is not # a problem and we can ignore it. pass else: if is_socket_file: raise shutil.SpecialFileError( "`{f}` is a socket".format(**locals())) raise def is_socket(path): # type: (str) -> bool return stat.S_ISSOCK(os.lstat(path).st_mode) @contextmanager def adjacent_tmp_file(path, **kwargs): # type: (str, **Any) -> Iterator[NamedTemporaryFileResult] """Return a file-like object pointing to a tmp file next to path. The file is created securely and is ensured to be written to disk after the context reaches its end. kwargs will be passed to tempfile.NamedTemporaryFile to control the way the temporary file will be opened. """ with NamedTemporaryFile( delete=False, dir=os.path.dirname(path), prefix=os.path.basename(path), suffix='.tmp', **kwargs ) as f: result = cast('NamedTemporaryFileResult', f) try: yield result finally: result.file.flush() os.fsync(result.file.fileno()) _replace_retry = retry(stop_max_delay=1000, wait_fixed=250) if PY2: @_replace_retry def replace(src, dest): # type: (str, str) -> None try: os.rename(src, dest) except OSError: os.remove(dest) os.rename(src, dest) else: replace = _replace_retry(os.replace) # test_writable_dir and _test_writable_dir_win are copied from Flit, # with the author's agreement to also place them under pip's license. def test_writable_dir(path): # type: (str) -> bool """Check if a directory is writable. Uses os.access() on POSIX, tries creating files on Windows. """ # If the directory doesn't exist, find the closest parent that does. while not os.path.isdir(path): parent = os.path.dirname(path) if parent == path: break # Should never get here, but infinite loops are bad path = parent if os.name == 'posix': return os.access(path, os.W_OK) return _test_writable_dir_win(path) def _test_writable_dir_win(path): # type: (str) -> bool # os.access doesn't work on Windows: http://bugs.python.org/issue2528 # and we can't use tempfile: http://bugs.python.org/issue22107 basename = 'accesstest_deleteme_fishfingers_custard_' alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789' for _ in range(10): name = basename + ''.join(random.choice(alphabet) for _ in range(6)) file = os.path.join(path, name) try: fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) # Python 2 doesn't support FileExistsError and PermissionError. except OSError as e: # exception FileExistsError if e.errno == errno.EEXIST: continue # exception PermissionError if e.errno == errno.EPERM or e.errno == errno.EACCES: # This could be because there's a directory with the same name. # But it's highly unlikely there's a directory called that, # so we'll assume it's because the parent dir is not writable. # This could as well be because the parent dir is not readable, # due to non-privileged user access. return False raise else: os.close(fd) os.unlink(file) return True # This should never be reached raise EnvironmentError( 'Unexpected condition testing for writable directory' ) def find_files(path, pattern): # type: (str, str) -> List[str] """Returns a list of absolute paths of files beneath path, recursively, with filenames which match the UNIX-style shell glob pattern.""" result = [] # type: List[str] for root, _, files in os.walk(path): matches = fnmatch.filter(files, pattern) result.extend(os.path.join(root, f) for f in matches) return result def file_size(path): # type: (str) -> Union[int, float] # If it's a symlink, return 0. if os.path.islink(path): return 0 return os.path.getsize(path) def format_file_size(path): # type: (str) -> str return format_size(file_size(path)) def directory_size(path): # type: (str) -> Union[int, float] size = 0.0 for root, _dirs, files in os.walk(path): for filename in files: file_path = os.path.join(root, filename) size += file_size(file_path) return size def format_directory_size(path): # type: (str) -> str return format_size(directory_size(path)) utils/glibc.py000064400000006341152347654150007356 0ustar00# The following comment should be removed at some point in the future. # mypy: strict-optional=False from __future__ import absolute_import import os import sys from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Tuple def glibc_version_string(): # type: () -> Optional[str] "Returns glibc version string, or None if not using glibc." return glibc_version_string_confstr() or glibc_version_string_ctypes() def glibc_version_string_confstr(): # type: () -> Optional[str] "Primary implementation of glibc_version_string using os.confstr." # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module: # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183 if sys.platform == "win32": return None try: # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17": _, version = os.confstr("CS_GNU_LIBC_VERSION").split() except (AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version def glibc_version_string_ctypes(): # type: () -> Optional[str] "Fallback implementation of glibc_version_string using ctypes." try: import ctypes except ImportError: return None # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. process_namespace = ctypes.CDLL(None) try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None # Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return version_str # platform.libc_ver regularly returns completely nonsensical glibc # versions. E.g. on my computer, platform says: # # ~$ python2.7 -c 'import platform; print(platform.libc_ver())' # ('glibc', '2.7') # ~$ python3.5 -c 'import platform; print(platform.libc_ver())' # ('glibc', '2.9') # # But the truth is: # # ~$ ldd --version # ldd (Debian GLIBC 2.22-11) 2.22 # # This is unfortunate, because it means that the linehaul data on libc # versions that was generated by pip 8.1.2 and earlier is useless and # misleading. Solution: instead of using platform, use our code that actually # works. def libc_ver(): # type: () -> Tuple[str, str] """Try to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. """ glibc_version = glibc_version_string() if glibc_version is None: return ("", "") else: return ("glibc", glibc_version) utils/deprecation.py000064400000006366152347654150010602 0ustar00""" A module that implements tooling to enable easy warnings about deprecations. """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import warnings from pip._vendor.packaging.version import parse from pip import __version__ as current_version from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Optional DEPRECATION_MSG_PREFIX = "DEPRECATION: " class PipDeprecationWarning(Warning): pass _original_showwarning = None # type: Any # Warnings <-> Logging Integration def _showwarning(message, category, filename, lineno, file=None, line=None): if file is not None: if _original_showwarning is not None: _original_showwarning( message, category, filename, lineno, file, line, ) elif issubclass(category, PipDeprecationWarning): # We use a specially named logger which will handle all of the # deprecation messages for pip. logger = logging.getLogger("pip._internal.deprecations") logger.warning(message) else: _original_showwarning( message, category, filename, lineno, file, line, ) def install_warning_logger(): # type: () -> None # Enable our Deprecation Warnings warnings.simplefilter("default", PipDeprecationWarning, append=True) global _original_showwarning if _original_showwarning is None: _original_showwarning = warnings.showwarning warnings.showwarning = _showwarning def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is eagerly formatted as we want it to get logged as if someone # typed this entire message out. sentences = [ (reason, DEPRECATION_MSG_PREFIX + "{}"), (gone_in, "pip {} will remove support for this functionality."), (replacement, "A possible replacement is {}."), (issue, ( "You can find discussion regarding this at " "https://github.com/pypa/pip/issues/{}." )), ] message = " ".join( template.format(val) for val, template in sentences if val is not None ) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2) utils/misc.py000064400000067253152347654150007242 0ustar00# The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False from __future__ import absolute_import import contextlib import errno import getpass import hashlib import io import logging import os import posixpath import shutil import stat import sys from collections import deque from itertools import tee from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name # NOTE: retrying is not annotated in typeshed as on 2017-07-17, which is # why we ignore the type on this import. from pip._vendor.retrying import retry # type: ignore from pip._vendor.six import PY2, text_type from pip._vendor.six.moves import filter, filterfalse, input, map, zip_longest from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib.parse import unquote as urllib_unquote from pip import __version__ from pip._internal.exceptions import CommandError from pip._internal.locations import ( distutils_scheme, get_major_minor_version, site_packages, user_site, ) from pip._internal.utils.compat import ( WINDOWS, expanduser, stdlib_pkgs, str_to_display, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast from pip._internal.utils.virtualenv import ( running_under_virtualenv, virtualenv_no_global, ) if PY2: from io import BytesIO as StringIO else: from io import StringIO if MYPY_CHECK_RUNNING: from typing import ( Any, AnyStr, Callable, Container, Iterable, Iterator, List, Optional, Text, Tuple, TypeVar, Union, ) from pip._vendor.pkg_resources import Distribution VersionInfo = Tuple[int, int, int] T = TypeVar("T") __all__ = ['rmtree', 'display_path', 'backup_dir', 'ask', 'splitext', 'format_size', 'is_installable_dir', 'normalize_path', 'renames', 'get_prog', 'captured_stdout', 'ensure_dir', 'get_installed_version', 'remove_auth_from_url'] logger = logging.getLogger(__name__) def get_pip_version(): # type: () -> str pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..") pip_pkg_dir = os.path.abspath(pip_pkg_dir) return ( 'pip {} from {} (python {})'.format( __version__, pip_pkg_dir, get_major_minor_version(), ) ) def normalize_version_info(py_version_info): # type: (Tuple[int, ...]) -> Tuple[int, int, int] """ Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple can have any length. :return: a tuple of length three if `py_version_info` is non-None. Otherwise, return `py_version_info` unchanged (i.e. None). """ if len(py_version_info) < 3: py_version_info += (3 - len(py_version_info)) * (0,) elif len(py_version_info) > 3: py_version_info = py_version_info[:3] return cast('VersionInfo', py_version_info) def ensure_dir(path): # type: (AnyStr) -> None """os.path.makedirs without EEXIST.""" try: os.makedirs(path) except OSError as e: # Windows can raise spurious ENOTEMPTY errors. See #6426. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY: raise def get_prog(): # type: () -> str try: prog = os.path.basename(sys.argv[0]) if prog in ('__main__.py', '-c'): return "{} -m pip".format(sys.executable) else: return prog except (AttributeError, TypeError, IndexError): pass return 'pip' # Retry every half second for up to 3 seconds @retry(stop_max_delay=3000, wait_fixed=500) def rmtree(dir, ignore_errors=False): # type: (Text, bool) -> None shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler) def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" try: has_attr_readonly = not (os.stat(path).st_mode & stat.S_IWRITE) except (IOError, OSError): # it's equivalent to os.path.exists return if has_attr_readonly: # convert to read/write os.chmod(path, stat.S_IWRITE) # use the original function to repeat the operation func(path) return else: raise def path_to_display(path): # type: (Optional[Union[str, Text]]) -> Optional[Text] """ Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str paths are already text. """ if path is None: return None if isinstance(path, text_type): return path # Otherwise, path is a bytes object (str in Python 2). try: display_path = path.decode(sys.getfilesystemencoding(), 'strict') except UnicodeDecodeError: # Include the full bytes to make troubleshooting easier, even though # it may not be very human readable. if PY2: # Convert the bytes to a readable str representation using # repr(), and then convert the str to unicode. # Also, we add the prefix "b" to the repr() return value both # to make the Python 2 output look like the Python 3 output, and # to signal to the user that this is a bytes representation. display_path = str_to_display('b{!r}'.format(path)) else: # Silence the "F821 undefined name 'ascii'" flake8 error since # in Python 3 ascii() is a built-in. display_path = ascii(path) # noqa: F821 return display_path def display_path(path): # type: (Union[str, Text]) -> str """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path = path.encode(sys.getdefaultencoding(), 'replace') if path.startswith(os.getcwd() + os.path.sep): path = '.' + path[len(os.getcwd()):] return path def backup_dir(dir, ext='.bak'): # type: (str, str) -> str """Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)""" n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension def ask_path_exists(message, options): # type: (str, Iterable[str]) -> str for action in os.environ.get('PIP_EXISTS_ACTION', '').split(): if action in options: return action return ask(message, options) def _check_no_input(message): # type: (str) -> None """Raise an error if no input is allowed.""" if os.environ.get('PIP_NO_INPUT'): raise Exception( 'No input was expected ($PIP_NO_INPUT set); question: {}'.format( message) ) def ask(message, options): # type: (str, Iterable[str]) -> str """Ask the message interactively, with the given possible responses""" while 1: _check_no_input(message) response = input(message) response = response.strip().lower() if response not in options: print( 'Your response ({!r}) was not one of the expected responses: ' '{}'.format(response, ', '.join(options)) ) else: return response def ask_input(message): # type: (str) -> str """Ask for input interactively.""" _check_no_input(message) return input(message) def ask_password(message): # type: (str) -> str """Ask for a password interactively.""" _check_no_input(message) return getpass.getpass(message) def format_size(bytes): # type: (float) -> str if bytes > 1000 * 1000: return '{:.1f} MB'.format(bytes / 1000.0 / 1000) elif bytes > 10 * 1000: return '{} kB'.format(int(bytes / 1000)) elif bytes > 1000: return '{:.1f} kB'.format(bytes / 1000.0) else: return '{} bytes'.format(int(bytes)) def tabulate(rows): # type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]] """Return a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4]) """ rows = [tuple(map(str, row)) for row in rows] sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue='')] table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows] return table, sizes def is_installable_dir(path): # type: (str) -> bool """Is path is a directory containing setup.py or pyproject.toml? """ if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True pyproject_toml = os.path.join(path, 'pyproject.toml') if os.path.isfile(pyproject_toml): return True return False def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): """Yield pieces of data from a file-like object until EOF.""" while True: chunk = file.read(size) if not chunk: break yield chunk def normalize_path(path, resolve_symlinks=True): # type: (str, bool) -> str """ Convert a path to its canonical, case-normalized, absolute version. """ path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) return os.path.normcase(path) def splitext(path): # type: (str) -> Tuple[str, str] """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext def renames(old, new): # type: (str, str) -> None """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.split(old) if head and tail: try: os.removedirs(head) except OSError: pass def is_local(path): # type: (str) -> bool """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. """ if not running_under_virtualenv(): return True return path.startswith(normalize_path(sys.prefix)) def dist_is_local(dist): # type: (Distribution) -> bool """ Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. """ return is_local(dist_location(dist)) def dist_in_usersite(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in user site. """ return dist_location(dist).startswith(normalize_path(user_site)) def dist_in_site_packages(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in sysconfig.get_python_lib(). """ return dist_location(dist).startswith(normalize_path(site_packages)) def dist_in_install_path(dist): """ Return True if given Distribution is installed in path matching distutils_scheme layout. """ norm_path = normalize_path(dist_location(dist)) return norm_path.startswith(normalize_path( distutils_scheme("")['purelib'].split('python')[0])) def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return False def get_installed_distributions( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None # type: Optional[List[str]] ): # type: (...) -> List[Distribution] """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. """ if paths: working_set = pkg_resources.WorkingSet(paths) else: working_set = pkg_resources.working_set if local_only: local_test = dist_is_local else: def local_test(d): return True if include_editables: def editable_test(d): return True else: def editable_test(d): return not dist_is_editable(d) if editables_only: def editables_only_test(d): return dist_is_editable(d) else: def editables_only_test(d): return True if user_only: user_test = dist_in_usersite else: def user_test(d): return True return [d for d in working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) and user_test(d) ] def _search_distribution(req_name): # type: (str) -> Optional[Distribution] """Find a distribution matching the ``req_name`` in the environment. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. """ # Canonicalize the name before searching in the list of # installed distributions and also while creating the package # dictionary to get the Distribution object req_name = canonicalize_name(req_name) packages = get_installed_distributions( local_only=False, skip=(), include_editables=True, editables_only=False, user_only=False, paths=None, ) pkg_dict = {canonicalize_name(p.key): p for p in packages} return pkg_dict.get(req_name) def get_distribution(req_name): # type: (str) -> Optional[Distribution] """Given a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. """ # Search the distribution by looking through the working set dist = _search_distribution(req_name) # If distribution could not be found, call working_set.require # to update the working set, and try to find the distribution # again. # This might happen for e.g. when you install a package # twice, once using setup.py develop and again using setup.py install. # Now when run pip uninstall twice, the package gets removed # from the working set in the first uninstall, so we have to populate # the working set again so that pip knows about it and the packages # gets picked up and is successfully uninstalled the second time too. if not dist: try: pkg_resources.working_set.require(req_name) except pkg_resources.DistributionNotFound: return None return _search_distribution(req_name) def egg_link_path(dist): # type: (Distribution) -> Optional[str] """ Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packages, then site.USER_SITE (don't look in global location) For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations. This method will just return the first one found. """ sites = [] if running_under_virtualenv(): sites.append(site_packages) if not virtualenv_no_global() and user_site: sites.append(user_site) else: if user_site: sites.append(user_site) sites.append(site_packages) for site in sites: egglink = os.path.join(site, dist.project_name) + '.egg-link' if os.path.isfile(egglink): return egglink return None def dist_location(dist): # type: (Distribution) -> str """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks removed). """ egg_link = egg_link_path(dist) if egg_link: return normalize_path(egg_link) return normalize_path(dist.location) def write_output(msg, *args): # type: (Any, Any) -> None logger.info(msg, *args) class FakeFile(object): """Wrap a list of lines in an object with readline() to make ConfigParser happy.""" def __init__(self, lines): self._gen = iter(lines) def readline(self): try: return next(self._gen) except StopIteration: return '' def __iter__(self): return self._gen class StreamWrapper(StringIO): @classmethod def from_stream(cls, orig_stream): cls.orig_stream = orig_stream return cls() # compileall.compile_dir() needs stdout.encoding to print to stdout @property def encoding(self): return self.orig_stream.encoding @contextlib.contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. """ orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout)) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo. """ return captured_output('stdout') def captured_stderr(): """ See captured_stdout(). """ return captured_output('stderr') def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having this cached, so we need to construct a new # working set each time. working_set = pkg_resources.WorkingSet() # Get the installed distribution from our working set dist = working_set.find(req) # Check to see if we got an installed distribution or not, if we did # we want to return it's version. return dist.version if dist else None def consume(iterator): """Consume an iterable at C speed.""" deque(iterator, maxlen=0) # Simulates an enum def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = {value: key for key, value in enums.items()} enums['reverse_mapping'] = reverse return type('Enum', (), enums) def build_netloc(host, port): # type: (str, Optional[int]) -> str """ Build a netloc from a host-port pair """ if port is None: return host if ':' in host: # Only wrap host with square brackets when it is IPv6 host = '[{}]'.format(host) return '{}:{}'.format(host, port) def build_url_from_netloc(netloc, scheme='https'): # type: (str, str) -> str """ Build a full URL from a netloc. """ if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc: # It must be a bare IPv6 address, so wrap it with brackets. netloc = '[{}]'.format(netloc) return '{}://{}'.format(scheme, netloc) def parse_netloc(netloc): # type: (str) -> Tuple[str, Optional[int]] """ Return the host-port pair from a netloc. """ url = build_url_from_netloc(netloc) parsed = urllib_parse.urlparse(url) return parsed.hostname, parsed.port def split_auth_from_netloc(netloc): """ Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). """ if '@' not in netloc: return netloc, (None, None) # Split from the right because that's how urllib.parse.urlsplit() # behaves if more than one @ is present (which can be checked using # the password attribute of urlsplit()'s return value). auth, netloc = netloc.rsplit('@', 1) if ':' in auth: # Split from the left because that's how urllib.parse.urlsplit() # behaves if more than one : is present (which again can be checked # using the password attribute of the return value) user_pass = auth.split(':', 1) else: user_pass = auth, None user_pass = tuple( None if x is None else urllib_unquote(x) for x in user_pass ) return netloc, user_pass def redact_netloc(netloc): # type: (str) -> str """ Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" """ netloc, (user, password) = split_auth_from_netloc(netloc) if user is None: return netloc if password is None: user = '****' password = '' else: user = urllib_parse.quote(user) password = ':****' return '{user}{password}@{netloc}'.format(user=user, password=password, netloc=netloc) def _transform_url(url, transform_netloc): """Transform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netloc as item 1. """ purl = urllib_parse.urlsplit(url) netloc_tuple = transform_netloc(purl.netloc) # stripped url url_pieces = ( purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment ) surl = urllib_parse.urlunsplit(url_pieces) return surl, netloc_tuple def _get_netloc(netloc): return split_auth_from_netloc(netloc) def _redact_netloc(netloc): return (redact_netloc(netloc),) def split_auth_netloc_from_url(url): # type: (str) -> Tuple[str, str, Tuple[str, str]] """ Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) """ url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc) return url_without_auth, netloc, auth def remove_auth_from_url(url): # type: (str) -> str """Return a copy of url with 'username:password@' removed.""" # username/pass params are passed to subversion through flags # and are not recognized in the url. return _transform_url(url, _get_netloc)[0] def redact_auth_from_url(url): # type: (str) -> str """Replace the password in a given url with ****.""" return _transform_url(url, _redact_netloc)[0] class HiddenText(object): def __init__( self, secret, # type: str redacted, # type: str ): # type: (...) -> None self.secret = secret self.redacted = redacted def __repr__(self): # type: (...) -> str return ''.format(str(self)) def __str__(self): # type: (...) -> str return self.redacted # This is useful for testing. def __eq__(self, other): # type: (Any) -> bool if type(self) != type(other): return False # The string being used for redaction doesn't also have to match, # just the raw, original string. return (self.secret == other.secret) # We need to provide an explicit __ne__ implementation for Python 2. # TODO: remove this when we drop PY2 support. def __ne__(self, other): # type: (Any) -> bool return not self == other def hide_value(value): # type: (str) -> HiddenText return HiddenText(value, redacted='****') def hide_url(url): # type: (str) -> HiddenText redacted = redact_auth_from_url(url) return HiddenText(url, redacted=redacted) def protect_pip_from_modification_on_windows(modifying_pip): # type: (bool) -> None """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_info[0]), "pip{}.{}.exe".format(*sys.version_info[:2]) ] # See https://github.com/pypa/pip/issues/1299 for more discussion should_show_use_python_msg = ( modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names ) if should_show_use_python_msg: new_command = [ sys.executable, "-m", "pip" ] + sys.argv[1:] raise CommandError( 'To modify pip, please run the following command:\n{}' .format(" ".join(new_command)) ) def is_console_interactive(): # type: () -> bool """Is this console interactive? """ return sys.stdin is not None and sys.stdin.isatty() def hash_file(path, blocksize=1 << 20): # type: (Text, int) -> Tuple[Any, int] """Return (hash, length) for path using hashlib.sha256() """ h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) return h, length def is_wheel_installed(): """ Return whether the wheel package is installed. """ try: import wheel # noqa: F401 except ImportError: return False return True def pairwise(iterable): # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]] """ Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ... """ iterable = iter(iterable) return zip_longest(iterable, iterable) def partition( pred, # type: Callable[[T], bool] iterable, # type: Iterable[T] ): # type: (...) -> Tuple[Iterable[T], Iterable[T]] """ Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 """ t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) utils/models.py000064400000002261152347654150007556 0ustar00"""Utilities for defining models """ # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False import operator class KeyBasedCompareMixin(object): """Provides comparison capabilities that is based on a key """ __slots__ = ['_compare_key', '_defining_class'] def __init__(self, key, defining_class): self._compare_key = key self._defining_class = defining_class def __hash__(self): return hash(self._compare_key) def __lt__(self, other): return self._compare(other, operator.__lt__) def __le__(self, other): return self._compare(other, operator.__le__) def __gt__(self, other): return self._compare(other, operator.__gt__) def __ge__(self, other): return self._compare(other, operator.__ge__) def __eq__(self, other): return self._compare(other, operator.__eq__) def __ne__(self, other): return self._compare(other, operator.__ne__) def _compare(self, other, method): if not isinstance(other, self._defining_class): return NotImplemented return method(self._compare_key, other._compare_key) utils/hashes.py000064400000011106152347654150007544 0ustar00from __future__ import absolute_import import hashlib from pip._vendor.six import iteritems, iterkeys, itervalues from pip._internal.exceptions import ( HashMismatch, HashMissing, InstallationError, ) from pip._internal.utils.misc import read_chunks from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Dict, List, BinaryIO, NoReturn, Iterator ) from pip._vendor.six import PY3 if PY3: from hashlib import _Hash else: from hashlib import _hash as _Hash # The recommended hash algo of the moment. Change this whenever the state of # the art changes; it won't hurt backward compatibility. FAVORITE_HASH = 'sha256' # Names of hashlib algorithms allowed by the --hash option and ``pip hash`` # Currently, those are the ones at least as collision-resistant as sha256. STRONG_HASHES = ['sha256', 'sha384', 'sha512'] class Hashes(object): """A wrapper that builds multiple hashes at once and checks them against known-good values """ def __init__(self, hashes=None): # type: (Dict[str, List[str]]) -> None """ :param hashes: A dict of algorithm names pointing to lists of allowed hex digests """ self._allowed = {} if hashes is None else hashes def __and__(self, other): # type: (Hashes) -> Hashes if not isinstance(other, Hashes): return NotImplemented # If either of the Hashes object is entirely empty (i.e. no hash # specified at all), all hashes from the other object are allowed. if not other: return self if not self: return other # Otherwise only hashes that present in both objects are allowed. new = {} for alg, values in iteritems(other._allowed): if alg not in self._allowed: continue new[alg] = [v for v in values if v in self._allowed[alg]] return Hashes(new) @property def digest_count(self): # type: () -> int return sum(len(digests) for digests in self._allowed.values()) def is_hash_allowed( self, hash_name, # type: str hex_digest, # type: str ): # type: (...) -> bool """Return whether the given hex digest is allowed.""" return hex_digest in self._allowed.get(hash_name, []) def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError( 'Unknown hash name: {}'.format(hash_name) ) for chunk in chunks: for hash in itervalues(gots): hash.update(chunk) for hash_name, got in iteritems(gots): if got.hexdigest() in self._allowed[hash_name]: return self._raise(gots) def _raise(self, gots): # type: (Dict[str, _Hash]) -> NoReturn raise HashMismatch(self._allowed, gots) def check_against_file(self, file): # type: (BinaryIO) -> None """Check good hashes against a file-like object Raise HashMismatch if none match. """ return self.check_against_chunks(read_chunks(file)) def check_against_path(self, path): # type: (str) -> None with open(path, 'rb') as file: return self.check_against_file(file) def __nonzero__(self): # type: () -> bool """Return whether I know any known-good hashes.""" return bool(self._allowed) def __bool__(self): # type: () -> bool return self.__nonzero__() class MissingHashes(Hashes): """A workalike for Hashes used when we're missing a hash for a requirement It computes the actual hash of the requirement and raises a HashMissing exception showing it to the user. """ def __init__(self): # type: () -> None """Don't offer the ``hashes`` kwarg.""" # Pass our favorite hash in to generate a "gotten hash". With the # empty list, it will never match, so an error will always raise. super(MissingHashes, self).__init__(hashes={FAVORITE_HASH: []}) def _raise(self, gots): # type: (Dict[str, _Hash]) -> NoReturn raise HashMissing(gots[FAVORITE_HASH].hexdigest()) utils/urls.py000064400000002767152347654150007273 0ustar00import os import sys from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Text, Union def get_url_scheme(url): # type: (Union[str, Text]) -> Optional[Text] if ':' not in url: return None return url.split(':', 1)[0].lower() def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url def url_to_path(url): # type: (str) -> str """ Convert a file: URL to a path. """ assert url.startswith('file:'), ( "You can only turn file: urls into filenames (not {url!r})" .format(**locals())) _, netloc, path, _, _ = urllib_parse.urlsplit(url) if not netloc or netloc == 'localhost': # According to RFC 8089, same as empty authority. netloc = '' elif sys.platform == 'win32': # If we have a UNC path, prepend UNC share notation. netloc = '\\\\' + netloc else: raise ValueError( 'non-local file URIs are not supported on this platform: {url!r}' .format(**locals()) ) path = urllib_request.url2pathname(netloc + path) return path utils/subprocess.py000064400000023304152347654150010464 0ustar00from __future__ import absolute_import import logging import os import subprocess from pip._vendor.six.moves import shlex_quote from pip._internal.cli.spinners import SpinnerInterface, open_spinner from pip._internal.exceptions import InstallationError from pip._internal.utils.compat import console_to_str, str_to_display from pip._internal.utils.logging import subprocess_logger from pip._internal.utils.misc import HiddenText, path_to_display from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Any, Callable, Iterable, List, Mapping, Optional, Text, Union, ) CommandArgs = List[Union[str, HiddenText]] LOG_DIVIDER = '----------------------------------------' def make_command(*args): # type: (Union[str, HiddenText, CommandArgs]) -> CommandArgs """ Create a CommandArgs object. """ command_args = [] # type: CommandArgs for arg in args: # Check for list instead of CommandArgs since CommandArgs is # only known during type-checking. if isinstance(arg, list): command_args.extend(arg) else: # Otherwise, arg is str or HiddenText. command_args.append(arg) return command_args def format_command_args(args): # type: (Union[List[str], CommandArgs]) -> str """ Format command arguments for display. """ # For HiddenText arguments, display the redacted form by calling str(). # Also, we don't apply str() to arguments that aren't HiddenText since # this can trigger a UnicodeDecodeError in Python 2 if the argument # has type unicode and includes a non-ascii character. (The type # checker doesn't ensure the annotations are correct in all cases.) return ' '.join( shlex_quote(str(arg)) if isinstance(arg, HiddenText) else shlex_quote(arg) for arg in args ) def reveal_command_args(args): # type: (Union[List[str], CommandArgs]) -> List[str] """ Return the arguments in their raw, unredacted form. """ return [ arg.secret if isinstance(arg, HiddenText) else arg for arg in args ] def make_subprocess_output_error( cmd_args, # type: Union[List[str], CommandArgs] cwd, # type: Optional[str] lines, # type: List[Text] exit_status, # type: int ): # type: (...) -> Text """ Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline. """ command = format_command_args(cmd_args) # Convert `command` and `cwd` to text (unicode in Python 2) so we can use # them as arguments in the unicode format string below. This avoids # "UnicodeDecodeError: 'ascii' codec can't decode byte ..." in Python 2 # if either contains a non-ascii character. command_display = str_to_display(command, desc='command bytes') cwd_display = path_to_display(cwd) # We know the joined output value ends in a newline. output = ''.join(lines) msg = ( # Use a unicode string to avoid "UnicodeEncodeError: 'ascii' # codec can't encode character ..." in Python 2 when a format # argument (e.g. `output`) has a non-ascii character. u'Command errored out with exit status {exit_status}:\n' ' command: {command_display}\n' ' cwd: {cwd_display}\n' 'Complete output ({line_count} lines):\n{output}{divider}' ).format( exit_status=exit_status, command_display=command_display, cwd_display=cwd_display, line_count=len(lines), output=output, divider=LOG_DIVIDER, ) return msg def call_subprocess( cmd, # type: Union[List[str], CommandArgs] show_stdout=False, # type: bool cwd=None, # type: Optional[str] on_returncode='raise', # type: str extra_ok_returncodes=None, # type: Optional[Iterable[int]] command_desc=None, # type: Optional[str] extra_environ=None, # type: Optional[Mapping[str, Any]] unset_environ=None, # type: Optional[Iterable[str]] spinner=None, # type: Optional[SpinnerInterface] log_failed_cmd=True # type: Optional[bool] ): # type: (...) -> Text """ Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. """ if extra_ok_returncodes is None: extra_ok_returncodes = [] if unset_environ is None: unset_environ = [] # Most places in pip use show_stdout=False. What this means is-- # # - We connect the child's output (combined stderr and stdout) to a # single pipe, which we read. # - We log this output to stderr at DEBUG level as it is received. # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't # requested), then we show a spinner so the user can still see the # subprocess is in progress. # - If the subprocess exits with an error, we log the output to stderr # at ERROR level if it hasn't already been displayed to the console # (e.g. if --verbose logging wasn't enabled). This way we don't log # the output to the console twice. # # If show_stdout=True, then the above is still done, but with DEBUG # replaced by INFO. if show_stdout: # Then log the subprocess output at INFO level. log_subprocess = subprocess_logger.info used_level = logging.INFO else: # Then log the subprocess output using DEBUG. This also ensures # it will be logged to the log file (aka user_log), if enabled. log_subprocess = subprocess_logger.debug used_level = logging.DEBUG # Whether the subprocess will be visible in the console. showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level # Only use the spinner if we're not showing the subprocess output # and we have a spinner. use_spinner = not showing_subprocess and spinner is not None if command_desc is None: command_desc = format_command_args(cmd) log_subprocess("Running command %s", command_desc) env = os.environ.copy() if extra_environ: env.update(extra_environ) for name in unset_environ: env.pop(name, None) try: proc = subprocess.Popen( # Convert HiddenText objects to the underlying str. reveal_command_args(cmd), stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, env=env, ) assert proc.stdin assert proc.stdout proc.stdin.close() except Exception as exc: if log_failed_cmd: subprocess_logger.critical( "Error %s while executing command %s", exc, command_desc, ) raise all_output = [] while True: # The "line" value is a unicode string in Python 2. line = console_to_str(proc.stdout.readline()) if not line: break line = line.rstrip() all_output.append(line + '\n') # Show the line immediately. log_subprocess(line) # Update the spinner. if use_spinner: assert spinner spinner.spin() try: proc.wait() finally: if proc.stdout: proc.stdout.close() proc_had_error = ( proc.returncode and proc.returncode not in extra_ok_returncodes ) if use_spinner: assert spinner if proc_had_error: spinner.finish("error") else: spinner.finish("done") if proc_had_error: if on_returncode == 'raise': if not showing_subprocess and log_failed_cmd: # Then the subprocess streams haven't been logged to the # console yet. msg = make_subprocess_output_error( cmd_args=cmd, cwd=cwd, lines=all_output, exit_status=proc.returncode, ) subprocess_logger.error(msg) exc_msg = ( 'Command errored out with exit status {}: {} ' 'Check the logs for full command output.' ).format(proc.returncode, command_desc) raise InstallationError(exc_msg) elif on_returncode == 'warn': subprocess_logger.warning( 'Command "%s" had error code %s in %s', command_desc, proc.returncode, cwd, ) elif on_returncode == 'ignore': pass else: raise ValueError('Invalid value: on_returncode={!r}'.format( on_returncode)) return ''.join(all_output) def runner_with_spinner_message(message): # type: (str) -> Callable[..., None] """Provide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. """ def runner( cmd, # type: List[str] cwd=None, # type: Optional[str] extra_environ=None # type: Optional[Mapping[str, Any]] ): # type: (...) -> None with open_spinner(message) as spinner: call_subprocess( cmd, cwd=cwd, extra_environ=extra_environ, spinner=spinner, ) return runner utils/unpacking.py000064400000022420152347654150010251 0ustar00"""Utilities related archives. """ from __future__ import absolute_import import logging import os import shutil import stat import tarfile import zipfile from pip._internal.exceptions import InstallationError from pip._internal.utils.filetypes import ( BZ2_EXTENSIONS, TAR_EXTENSIONS, XZ_EXTENSIONS, ZIP_EXTENSIONS, ) from pip._internal.utils.misc import ensure_dir from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Iterable, List, Optional, Text, Union from zipfile import ZipInfo logger = logging.getLogger(__name__) SUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS try: import bz2 # noqa SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS except ImportError: logger.debug('bz2 module is not available') try: # Only for Python 3.3+ import lzma # noqa SUPPORTED_EXTENSIONS += XZ_EXTENSIONS except ImportError: logger.debug('lzma module is not available') def current_umask(): # type: () -> int """Get the current umask which involves having to set it temporarily.""" mask = os.umask(0) os.umask(mask) return mask def split_leading_dir(path): # type: (Union[str, Text]) -> List[Union[str, Text]] path = path.lstrip('/').lstrip('\\') if ( '/' in path and ( ('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path ) ): return path.split('/', 1) elif '\\' in path: return path.split('\\', 1) else: return [path, ''] def has_leading_dir(paths): # type: (Iterable[Union[str, Text]]) -> bool """Returns true if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive)""" common_prefix = None for path in paths: prefix, rest = split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def is_within_directory(directory, target): # type: ((Union[str, Text]), (Union[str, Text])) -> bool """ Return true if the absolute path of target is within the directory """ abs_directory = os.path.abspath(directory) abs_target = os.path.abspath(target) prefix = os.path.commonprefix([abs_directory, abs_target]) return prefix == abs_directory def set_extracted_file_to_default_mode_plus_executable(path): # type: (Union[str, Text]) -> None """ Make file present at path have execute for user/group/world (chmod +x) is no-op on windows per python docs """ os.chmod(path, (0o777 & ~current_umask() | 0o111)) def zip_item_is_executable(info): # type: (ZipInfo) -> bool mode = info.external_attr >> 16 # if mode and regular file and any execute permissions for # user/group/world? return bool(mode and stat.S_ISREG(mode) and mode & 0o111) def unzip_file(filename, location, flatten=True): # type: (str, str, bool) -> None """ Unzip the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. """ ensure_dir(location) zipfp = open(filename, 'rb') try: zip = zipfile.ZipFile(zipfp, allowZip64=True) leading = has_leading_dir(zip.namelist()) and flatten for info in zip.infolist(): name = info.filename fn = name if leading: fn = split_leading_dir(name)[1] fn = os.path.join(location, fn) dir = os.path.dirname(fn) if not is_within_directory(location, fn): message = ( 'The zip file ({}) has a file ({}) trying to install ' 'outside target directory ({})' ) raise InstallationError(message.format(filename, fn, location)) if fn.endswith('/') or fn.endswith('\\'): # A directory ensure_dir(fn) else: ensure_dir(dir) # Don't use read() to avoid allocating an arbitrarily large # chunk of memory for the file's content fp = zip.open(name) try: with open(fn, 'wb') as destfp: shutil.copyfileobj(fp, destfp) finally: fp.close() if zip_item_is_executable(info): set_extracted_file_to_default_mode_plus_executable(fn) finally: zipfp.close() def untar_file(filename, location): # type: (str, str) -> None """ Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. """ ensure_dir(location) if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'): mode = 'r:gz' elif filename.lower().endswith(BZ2_EXTENSIONS): mode = 'r:bz2' elif filename.lower().endswith(XZ_EXTENSIONS): mode = 'r:xz' elif filename.lower().endswith('.tar'): mode = 'r' else: logger.warning( 'Cannot determine compression type for file %s', filename, ) mode = 'r:*' tar = tarfile.open(filename, mode) try: leading = has_leading_dir([ member.name for member in tar.getmembers() ]) for member in tar.getmembers(): fn = member.name if leading: # https://github.com/python/mypy/issues/1174 fn = split_leading_dir(fn)[1] # type: ignore path = os.path.join(location, fn) if not is_within_directory(location, path): message = ( 'The tar file ({}) has a file ({}) trying to install ' 'outside target directory ({})' ) raise InstallationError( message.format(filename, path, location) ) if member.isdir(): ensure_dir(path) elif member.issym(): try: # https://github.com/python/typeshed/issues/2673 tar._extract_member(member, path) # type: ignore except Exception as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue else: try: fp = tar.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue ensure_dir(os.path.dirname(path)) assert fp is not None with open(path, 'wb') as destfp: shutil.copyfileobj(fp, destfp) fp.close() # Update the timestamp (useful for cython compiled files) # https://github.com/python/typeshed/issues/2673 tar.utime(member, path) # type: ignore # member have any execute permissions for user/group/world? if member.mode & 0o111: set_extracted_file_to_default_mode_plus_executable(path) finally: tar.close() def unpack_file( filename, # type: str location, # type: str content_type=None, # type: Optional[str] ): # type: (...) -> None filename = os.path.realpath(filename) if ( content_type == 'application/zip' or filename.lower().endswith(ZIP_EXTENSIONS) or zipfile.is_zipfile(filename) ): unzip_file( filename, location, flatten=not filename.endswith('.whl') ) elif ( content_type == 'application/x-gzip' or tarfile.is_tarfile(filename) or filename.lower().endswith( TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS ) ): untar_file(filename, location) else: # FIXME: handle? # FIXME: magic signatures? logger.critical( 'Cannot unpack file %s (downloaded from %s, content-type: %s); ' 'cannot detect archive format', filename, location, content_type, ) raise InstallationError( 'Cannot determine archive format of {}'.format(location) ) utils/appdirs.py000064400000002505152347654150007736 0ustar00""" This code wraps the vendored appdirs module to so the return values are compatible for the current pip code base. The intention is to rewrite current usages gradually, keeping the tests pass, and eventually drop this after all usages are changed. """ from __future__ import absolute_import import os from pip._vendor import appdirs as _appdirs from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List def user_cache_dir(appname): # type: (str) -> str return _appdirs.user_cache_dir(appname, appauthor=False) def user_config_dir(appname, roaming=True): # type: (str, bool) -> str path = _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming) if _appdirs.system == "darwin" and not os.path.isdir(path): path = os.path.expanduser('~/.config/') if appname: path = os.path.join(path, appname) return path # for the discussion regarding site_config_dir locations # see def site_config_dirs(appname): # type: (str) -> List[str] dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True) if _appdirs.system not in ["win32", "darwin"]: # always look in /etc directly as well return dirval.split(os.pathsep) + ['/etc'] return [dirval] utils/ui.py000064400000033122152347654150006710 0ustar00# The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False from __future__ import absolute_import, division import contextlib import itertools import logging import sys import time from signal import SIGINT, default_int_handler, signal from pip._vendor import six from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar from pip._vendor.progress.spinner import Spinner from pip._internal.utils.compat import WINDOWS from pip._internal.utils.logging import get_indentation from pip._internal.utils.misc import format_size from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Iterator, IO try: from pip._vendor import colorama # Lots of different errors can come from this, including SystemError and # ImportError. except Exception: colorama = None logger = logging.getLogger(__name__) def _select_progress_class(preferred, fallback): encoding = getattr(preferred.file, "encoding", None) # If we don't know what encoding this file is in, then we'll just assume # that it doesn't support unicode and use the ASCII bar. if not encoding: return fallback # Collect all of the possible characters we want to use with the preferred # bar. characters = [ getattr(preferred, "empty_fill", six.text_type()), getattr(preferred, "fill", six.text_type()), ] characters += list(getattr(preferred, "phases", [])) # Try to decode the characters we're using for the bar using the encoding # of the given file, if this works then we'll assume that we can use the # fancier bar and if not we'll fall back to the plaintext bar. try: six.text_type().join(characters).encode(encoding) except UnicodeEncodeError: return fallback else: return preferred _BaseBar = _select_progress_class(IncrementalBar, Bar) # type: Any class InterruptibleMixin(object): """ Helper to ensure that self.finish() gets called on keyboard interrupt. This allows downloads to be interrupted without leaving temporary state (like hidden cursors) behind. This class is similar to the progress library's existing SigIntMixin helper, but as of version 1.2, that helper has the following problems: 1. It calls sys.exit(). 2. It discards the existing SIGINT handler completely. 3. It leaves its own handler in place even after an uninterrupted finish, which will have unexpected delayed effects if the user triggers an unrelated keyboard interrupt some time after a progress-displaying download has already completed, for example. """ def __init__(self, *args, **kwargs): """ Save the original SIGINT handler for later. """ super(InterruptibleMixin, self).__init__(*args, **kwargs) self.original_handler = signal(SIGINT, self.handle_sigint) # If signal() returns None, the previous handler was not installed from # Python, and we cannot restore it. This probably should not happen, # but if it does, we must restore something sensible instead, at least. # The least bad option should be Python's default SIGINT handler, which # just raises KeyboardInterrupt. if self.original_handler is None: self.original_handler = default_int_handler def finish(self): """ Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. """ super(InterruptibleMixin, self).finish() signal(SIGINT, self.original_handler) def handle_sigint(self, signum, frame): """ Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. """ self.finish() self.original_handler(signum, frame) class SilentBar(Bar): def update(self): pass class BlueEmojiBar(IncrementalBar): suffix = "%(percent)d%%" bar_prefix = " " bar_suffix = " " phases = (u"\U0001F539", u"\U0001F537", u"\U0001F535") # type: Any class DownloadProgressMixin(object): def __init__(self, *args, **kwargs): super(DownloadProgressMixin, self).__init__(*args, **kwargs) self.message = (" " * (get_indentation() + 2)) + self.message @property def downloaded(self): return format_size(self.index) @property def download_speed(self): # Avoid zero division errors... if self.avg == 0.0: return "..." return format_size(1 / self.avg) + "/s" @property def pretty_eta(self): if self.eta: return "eta %s" % self.eta_td return "" def iter(self, it, n=1): for x in it: yield x self.next(n) self.finish() class WindowsMixin(object): def __init__(self, *args, **kwargs): # The Windows terminal does not support the hide/show cursor ANSI codes # even with colorama. So we'll ensure that hide_cursor is False on # Windows. # This call needs to go before the super() call, so that hide_cursor # is set in time. The base progress bar class writes the "hide cursor" # code to the terminal in its init, so if we don't set this soon # enough, we get a "hide" with no corresponding "show"... if WINDOWS and self.hide_cursor: self.hide_cursor = False super(WindowsMixin, self).__init__(*args, **kwargs) # Check if we are running on Windows and we have the colorama module, # if we do then wrap our file with it. if WINDOWS and colorama: self.file = colorama.AnsiToWin32(self.file) # The progress code expects to be able to call self.file.isatty() # but the colorama.AnsiToWin32() object doesn't have that, so we'll # add it. self.file.isatty = lambda: self.file.wrapped.isatty() # The progress code expects to be able to call self.file.flush() # but the colorama.AnsiToWin32() object doesn't have that, so we'll # add it. self.file.flush = lambda: self.file.wrapped.flush() class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin): file = sys.stdout message = "%(percent)d%%" suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" # NOTE: The "type: ignore" comments on the following classes are there to # work around https://github.com/python/typing/issues/241 class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar): pass class DownloadSilentBar(BaseDownloadProgressBar, SilentBar): # type: ignore pass class DownloadBar(BaseDownloadProgressBar, # type: ignore Bar): pass class DownloadFillingCirclesBar(BaseDownloadProgressBar, # type: ignore FillingCirclesBar): pass class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, # type: ignore BlueEmojiBar): pass class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner): file = sys.stdout suffix = "%(downloaded)s %(download_speed)s" def next_phase(self): if not hasattr(self, "_phaser"): self._phaser = itertools.cycle(self.phases) return next(self._phaser) def update(self): message = self.message % self phase = self.next_phase() suffix = self.suffix % self line = ''.join([ message, " " if message else "", phase, " " if suffix else "", suffix, ]) self.writeln(line) BAR_TYPES = { "off": (DownloadSilentBar, DownloadSilentBar), "on": (DefaultDownloadProgressBar, DownloadProgressSpinner), "ascii": (DownloadBar, DownloadProgressSpinner), "pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner), "emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner) } def DownloadProgressProvider(progress_bar, max=None): if max is None or max == 0: return BAR_TYPES[progress_bar][1]().iter else: return BAR_TYPES[progress_bar][0](max=max).iter ################################################################ # Generic "something is happening" spinners # # We don't even try using progress.spinner.Spinner here because it's actually # simpler to reimplement from scratch than to coerce their code into doing # what we need. ################################################################ @contextlib.contextmanager def hidden_cursor(file): # type: (IO) -> Iterator[None] # The Windows terminal does not support the hide/show cursor ANSI codes, # even via colorama. So don't even try. if WINDOWS: yield # We don't want to clutter the output with control characters if we're # writing to a file, or if the user is running with --quiet. # See https://github.com/pypa/pip/issues/3418 elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO: yield else: file.write(HIDE_CURSOR) try: yield finally: file.write(SHOW_CURSOR) class RateLimiter(object): def __init__(self, min_update_interval_seconds): # type: (float) -> None self._min_update_interval_seconds = min_update_interval_seconds self._last_update = 0 # type: float def ready(self): # type: () -> bool now = time.time() delta = now - self._last_update return delta >= self._min_update_interval_seconds def reset(self): # type: () -> None self._last_update = time.time() class SpinnerInterface(object): def spin(self): # type: () -> None raise NotImplementedError() def finish(self, final_status): # type: (str) -> None raise NotImplementedError() class InteractiveSpinner(SpinnerInterface): def __init__(self, message, file=None, spin_chars="-\\|/", # Empirically, 8 updates/second looks nice min_update_interval_seconds=0.125): self._message = message if file is None: file = sys.stdout self._file = file self._rate_limiter = RateLimiter(min_update_interval_seconds) self._finished = False self._spin_cycle = itertools.cycle(spin_chars) self._file.write(" " * get_indentation() + self._message + " ... ") self._width = 0 def _write(self, status): assert not self._finished # Erase what we wrote before by backspacing to the beginning, writing # spaces to overwrite the old text, and then backspacing again backup = "\b" * self._width self._file.write(backup + " " * self._width + backup) # Now we have a blank slate to add our status self._file.write(status) self._width = len(status) self._file.flush() self._rate_limiter.reset() def spin(self): # type: () -> None if self._finished: return if not self._rate_limiter.ready(): return self._write(next(self._spin_cycle)) def finish(self, final_status): # type: (str) -> None if self._finished: return self._write(final_status) self._file.write("\n") self._file.flush() self._finished = True # Used for dumb terminals, non-interactive installs (no tty), etc. # We still print updates occasionally (once every 60 seconds by default) to # act as a keep-alive for systems like Travis-CI that take lack-of-output as # an indication that a task has frozen. class NonInteractiveSpinner(SpinnerInterface): def __init__(self, message, min_update_interval_seconds=60): # type: (str, float) -> None self._message = message self._finished = False self._rate_limiter = RateLimiter(min_update_interval_seconds) self._update("started") def _update(self, status): assert not self._finished self._rate_limiter.reset() logger.info("%s: %s", self._message, status) def spin(self): # type: () -> None if self._finished: return if not self._rate_limiter.ready(): return self._update("still running...") def finish(self, final_status): # type: (str) -> None if self._finished: return self._update("finished with status '%s'" % (final_status,)) self._finished = True @contextlib.contextmanager def open_spinner(message): # type: (str) -> Iterator[SpinnerInterface] # Interactive spinner goes directly to sys.stdout rather than being routed # through the logging system, but it acts like it has level INFO, # i.e. it's only displayed if we're at level INFO or better. # Non-interactive spinner goes through the logging system, so it is always # in sync with logging configuration. if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO: spinner = InteractiveSpinner(message) # type: SpinnerInterface else: spinner = NonInteractiveSpinner(message) try: with hidden_cursor(sys.stdout): yield spinner except KeyboardInterrupt: spinner.finish("canceled") raise except Exception: spinner.finish("error") raise else: spinner.finish("done") utils/setuptools_build.py000064400000011702152347654150011673 0ustar00import sys from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Sequence # Shim to wrap setup.py invocation with setuptools # # We set sys.argv[0] to the path to the underlying setup.py file so # setuptools / distutils don't take the path to the setup.py to be "-c" when # invoking via the shim. This avoids e.g. the following manifest_maker # warning: "warning: manifest_maker: standard file '-c' not found". _SETUPTOOLS_SHIM = ( "import sys, setuptools, tokenize; sys.argv[0] = {0!r}; __file__={0!r};" "f=getattr(tokenize, 'open', open)(__file__);" "code=f.read().replace('\\r\\n', '\\n');" "f.close();" "exec(compile(code, __file__, 'exec'))" ) def make_setuptools_shim_args( setup_py_path, # type: str global_options=None, # type: Sequence[str] no_user_config=False, # type: bool unbuffered_output=False # type: bool ): # type: (...) -> List[str] """ Get setuptools command arguments with shim wrapped setup file invocation. :param setup_py_path: The path to setup.py to be wrapped. :param global_options: Additional global options. :param no_user_config: If True, disables personal user configuration. :param unbuffered_output: If True, adds the unbuffered switch to the argument list. """ args = [sys.executable] if unbuffered_output: args += ["-u"] args += ["-c", _SETUPTOOLS_SHIM.format(setup_py_path)] if global_options: args += global_options if no_user_config: args += ["--no-user-cfg"] return args def make_setuptools_bdist_wheel_args( setup_py_path, # type: str global_options, # type: Sequence[str] build_options, # type: Sequence[str] destination_dir, # type: str ): # type: (...) -> List[str] # NOTE: Eventually, we'd want to also -S to the flags here, when we're # isolating. Currently, it breaks Python in virtualenvs, because it # relies on site.py to find parts of the standard library outside the # virtualenv. args = make_setuptools_shim_args( setup_py_path, global_options=global_options, unbuffered_output=True ) args += ["bdist_wheel", "-d", destination_dir] args += build_options return args def make_setuptools_clean_args( setup_py_path, # type: str global_options, # type: Sequence[str] ): # type: (...) -> List[str] args = make_setuptools_shim_args( setup_py_path, global_options=global_options, unbuffered_output=True ) args += ["clean", "--all"] return args def make_setuptools_develop_args( setup_py_path, # type: str global_options, # type: Sequence[str] install_options, # type: Sequence[str] no_user_config, # type: bool prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool ): # type: (...) -> List[str] assert not (use_user_site and prefix) args = make_setuptools_shim_args( setup_py_path, global_options=global_options, no_user_config=no_user_config, ) args += ["develop", "--no-deps"] args += install_options if prefix: args += ["--prefix", prefix] if home is not None: args += ["--home", home] if use_user_site: args += ["--user", "--prefix="] return args def make_setuptools_egg_info_args( setup_py_path, # type: str egg_info_dir, # type: Optional[str] no_user_config, # type: bool ): # type: (...) -> List[str] args = make_setuptools_shim_args( setup_py_path, no_user_config=no_user_config ) args += ["egg_info"] if egg_info_dir: args += ["--egg-base", egg_info_dir] return args def make_setuptools_install_args( setup_py_path, # type: str global_options, # type: Sequence[str] install_options, # type: Sequence[str] record_filename, # type: str root, # type: Optional[str] prefix, # type: Optional[str] header_dir, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool no_user_config, # type: bool pycompile # type: bool ): # type: (...) -> List[str] assert not (use_user_site and prefix) assert not (use_user_site and root) args = make_setuptools_shim_args( setup_py_path, global_options=global_options, no_user_config=no_user_config, unbuffered_output=True ) args += ["install", "--record", record_filename] args += ["--single-version-externally-managed"] if root is not None: args += ["--root", root] if prefix is not None: args += ["--prefix", prefix] if home is not None: args += ["--home", home] if use_user_site: args += ["--user", "--prefix="] if pycompile: args += ["--compile"] else: args += ["--no-compile"] if header_dir: args += ["--install-headers", header_dir] args += install_options return args utils/packaging.py000064400000005733152347654150010226 0ustar00from __future__ import absolute_import import logging from email.parser import FeedParser from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers, version from pip._internal.exceptions import NoneMetadataError from pip._internal.utils.misc import display_path from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, Tuple from email.message import Message from pip._vendor.pkg_resources import Distribution logger = logging.getLogger(__name__) def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information return True requires_python_specifier = specifiers.SpecifierSet(requires_python) python_version = version.parse('.'.join(map(str, version_info))) return python_version in requires_python_specifier def get_metadata(dist): # type: (Distribution) -> Message """ :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. """ metadata_name = 'METADATA' if (isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata(metadata_name)): metadata = dist.get_metadata(metadata_name) elif dist.has_metadata('PKG-INFO'): metadata_name = 'PKG-INFO' metadata = dist.get_metadata(metadata_name) else: logger.warning("No metadata found in %s", display_path(dist.location)) metadata = '' if metadata is None: raise NoneMetadataError(dist, metadata_name) feed_parser = FeedParser() # The following line errors out if with a "NoneType" TypeError if # passed metadata=None. feed_parser.feed(metadata) return feed_parser.close() def get_requires_python(dist): # type: (pkg_resources.Distribution) -> Optional[str] """ Return the "Requires-Python" metadata for a distribution, or None if not present. """ pkg_info_dict = get_metadata(dist) requires_python = pkg_info_dict.get('Requires-Python') if requires_python is not None: # Convert to a str to satisfy the type checker, since requires_python # can be a Header object. requires_python = str(requires_python) return requires_python def get_installer(dist): # type: (Distribution) -> str if dist.has_metadata('INSTALLER'): for line in dist.get_metadata_lines('INSTALLER'): if line.strip(): return line.strip() return '' utils/compat.py000064400000022421152347654150007556 0ustar00"""Stuff that differs in different Python versions and platform distributions.""" # The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import, division import codecs import functools import locale import logging import os import shutil import sys from pip._vendor.six import PY2, text_type from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Callable, Optional, Protocol, Text, Tuple, TypeVar, Union # Used in the @lru_cache polyfill. F = TypeVar('F') class LruCache(Protocol): def __call__(self, maxsize=None): # type: (Optional[int]) -> Callable[[F], F] raise NotImplementedError try: import ipaddress except ImportError: try: from pip._vendor import ipaddress # type: ignore except ImportError: import ipaddr as ipaddress # type: ignore ipaddress.ip_address = ipaddress.IPAddress # type: ignore ipaddress.ip_network = ipaddress.IPNetwork # type: ignore __all__ = [ "ipaddress", "uses_pycache", "console_to_str", "get_path_uid", "stdlib_pkgs", "WINDOWS", "samefile", "get_terminal_size", ] logger = logging.getLogger(__name__) if PY2: import imp try: cache_from_source = imp.cache_from_source # type: ignore except AttributeError: # does not use __pycache__ cache_from_source = None uses_pycache = cache_from_source is not None else: uses_pycache = True from importlib.util import cache_from_source if PY2: # In Python 2.7, backslashreplace exists # but does not support use for decoding. # We implement our own replace handler for this # situation, so that we can consistently use # backslash replacement for all versions. def backslashreplace_decode_fn(err): raw_bytes = (err.object[i] for i in range(err.start, err.end)) # Python 2 gave us characters - convert to numeric bytes raw_bytes = (ord(b) for b in raw_bytes) return u"".join(map(u"\\x{:x}".format, raw_bytes)), err.end codecs.register_error( "backslashreplace_decode", backslashreplace_decode_fn, ) backslashreplace_decode = "backslashreplace_decode" else: backslashreplace_decode = "backslashreplace" def has_tls(): # type: () -> bool try: import _ssl # noqa: F401 # ignore unused return True except ImportError: pass from pip._vendor.urllib3.util import IS_PYOPENSSL return IS_PYOPENSSL def str_to_display(data, desc=None): # type: (Union[bytes, Text], Optional[str]) -> Text """ For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ if isinstance(data, text_type): return data # Otherwise, data is a bytes object (str in Python 2). # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( '%s does not appear to be encoded as %s', desc or 'Bytes object', encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. """ return str_to_display(data, desc='Subprocess output') def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "{} is a symlink; Will not return uid for symlinks".format( path) ) return file_uid def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded # packages in the stdlib that may have installation metadata, but should not be # considered 'installed'. this theoretically could be determined based on # dist.location (py27:`sysconfig.get_paths()['stdlib']`, # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may # make this ineffective, so hard-coding stdlib_pkgs = {"python", "wsgiref", "argparse"} # windows detection, covers cpython and ironpython WINDOWS = (sys.platform.startswith("win") or (sys.platform == 'cli' and os.name == 'nt')) def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2 if hasattr(shutil, 'get_terminal_size'): def get_terminal_size(): # type: () -> Tuple[int, int] """ Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. """ return tuple(shutil.get_terminal_size()) # type: ignore else: def get_terminal_size(): # type: () -> Tuple[int, int] """ Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. """ def ioctl_GWINSZ(fd): try: import fcntl import termios import struct cr = struct.unpack_from( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678') ) except Exception: return None if cr == (0, 0): return None return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: if sys.platform != "win32": try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except Exception: pass if not cr: cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80)) return int(cr[1]), int(cr[0]) # Fallback to noop_lru_cache in Python 2 # TODO: this can be removed when python 2 support is dropped! def noop_lru_cache(maxsize=None): # type: (Optional[int]) -> Callable[[F], F] def _wrapper(f): # type: (F) -> F return f return _wrapper lru_cache = getattr(functools, "lru_cache", noop_lru_cache) # type: LruCache utils/virtualenv.py000064400000007172152347654150010500 0ustar00from __future__ import absolute_import import io import logging import os import re import site import sys from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional logger = logging.getLogger(__name__) _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile( r"include-system-site-packages\s*=\s*(?Ptrue|false)" ) def _running_under_venv(): # type: () -> bool """Checks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments. """ return sys.prefix != getattr(sys, "base_prefix", sys.prefix) def _running_under_regular_virtualenv(): # type: () -> bool """Checks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv. """ # pypa/virtualenv case return hasattr(sys, 'real_prefix') def running_under_virtualenv(): # type: () -> bool """Return True if we're running inside a virtualenv, False otherwise. """ return _running_under_venv() or _running_under_regular_virtualenv() def _get_pyvenv_cfg_lines(): # type: () -> Optional[List[str]] """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file. """ pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg') try: # Although PEP 405 does not specify, the built-in venv module always # writes with UTF-8. (pypa/pip#8717) with io.open(pyvenv_cfg_file, encoding='utf-8') as f: return f.read().splitlines() # avoids trailing newlines except IOError: return None def _no_global_under_venv(): # type: () -> bool """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-site-packages = false Additionally, log a warning if accessing the file fails. """ cfg_lines = _get_pyvenv_cfg_lines() if cfg_lines is None: # We're not in a "sane" venv, so assume there is no system # site-packages access (since that's PEP 405's default state). logger.warning( "Could not access 'pyvenv.cfg' despite a virtual environment " "being active. Assuming global site-packages is not accessible " "in this environment." ) return True for line in cfg_lines: match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line) if match is not None and match.group('value') == 'false': return True return False def _no_global_under_regular_virtualenv(): # type: () -> bool """Check if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment. """ site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_site_packages_file = os.path.join( site_mod_dir, 'no-global-site-packages.txt', ) return os.path.exists(no_global_site_packages_file) def virtualenv_no_global(): # type: () -> bool """Returns a boolean, whether running in venv with no system site-packages. """ # PEP 405 compliance needs to be checked first since virtualenv >=20 would # return True for both checks, but is only able to use the PEP 405 config. if _running_under_venv(): return _no_global_under_venv() if _running_under_regular_virtualenv(): return _no_global_under_regular_virtualenv() return False utils/temp_dir.py000064400000020272152347654150010100 0ustar00from __future__ import absolute_import import errno import itertools import logging import os.path import tempfile from contextlib import contextmanager from pip._vendor.contextlib2 import ExitStack from pip._vendor.six import ensure_text from pip._internal.utils.misc import enum, rmtree from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Dict, Iterator, Optional, TypeVar, Union _T = TypeVar('_T', bound='TempDirectory') logger = logging.getLogger(__name__) # Kinds of temporary directories. Only needed for ones that are # globally-managed. tempdir_kinds = enum( BUILD_ENV="build-env", EPHEM_WHEEL_CACHE="ephem-wheel-cache", REQ_BUILD="req-build", ) _tempdir_manager = None # type: Optional[ExitStack] @contextmanager def global_tempdir_manager(): # type: () -> Iterator[None] global _tempdir_manager with ExitStack() as stack: old_tempdir_manager, _tempdir_manager = _tempdir_manager, stack try: yield finally: _tempdir_manager = old_tempdir_manager class TempDirectoryTypeRegistry(object): """Manages temp directory behavior """ def __init__(self): # type: () -> None self._should_delete = {} # type: Dict[str, bool] def set_delete(self, kind, value): # type: (str, bool) -> None """Indicate whether a TempDirectory of the given kind should be auto-deleted. """ self._should_delete[kind] = value def get_delete(self, kind): # type: (str) -> bool """Get configured auto-delete flag for a given TempDirectory type, default True. """ return self._should_delete.get(kind, True) _tempdir_registry = None # type: Optional[TempDirectoryTypeRegistry] @contextmanager def tempdir_registry(): # type: () -> Iterator[TempDirectoryTypeRegistry] """Provides a scoped global tempdir registry that can be used to dictate whether directories should be deleted. """ global _tempdir_registry old_tempdir_registry = _tempdir_registry _tempdir_registry = TempDirectoryTypeRegistry() try: yield _tempdir_registry finally: _tempdir_registry = old_tempdir_registry class _Default(object): pass _default = _Default() class TempDirectory(object): """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. """ def __init__( self, path=None, # type: Optional[str] delete=_default, # type: Union[bool, None, _Default] kind="temp", # type: str globally_managed=False, # type: bool ): super(TempDirectory, self).__init__() if delete is _default: if path is not None: # If we were given an explicit directory, resolve delete option # now. delete = False else: # Otherwise, we wait until cleanup and see what # tempdir_registry says. delete = None if path is None: path = self._create(kind) self._path = path self._deleted = False self.delete = delete self.kind = kind if globally_managed: assert _tempdir_manager is not None _tempdir_manager.enter_context(self) @property def path(self): # type: () -> str assert not self._deleted, ( "Attempted to access deleted path: {}".format(self._path) ) return self._path def __repr__(self): # type: () -> str return "<{} {!r}>".format(self.__class__.__name__, self.path) def __enter__(self): # type: (_T) -> _T return self def __exit__(self, exc, value, tb): # type: (Any, Any, Any) -> None if self.delete is not None: delete = self.delete elif _tempdir_registry: delete = _tempdir_registry.get_delete(self.kind) else: delete = True if delete: self.cleanup() def _create(self, kind): # type: (str) -> str """Create a temporary directory and store its path in self.path """ # We realpath here because some systems have their default tmpdir # symlinked to another directory. This tends to confuse build # scripts, so we canonicalize the path by traversing potential # symlinks here. path = os.path.realpath( tempfile.mkdtemp(prefix="pip-{}-".format(kind)) ) logger.debug("Created temporary directory: %s", path) return path def cleanup(self): # type: () -> None """Remove the temporary directory created and reset state """ self._deleted = True if os.path.exists(self._path): # Make sure to pass unicode on Python 2 to make the contents also # use unicode, ensuring non-ASCII names and can be represented. rmtree(ensure_text(self._path)) class AdjacentTempDirectory(TempDirectory): """Helper class that creates a temporary directory adjacent to a real one. Attributes: original The original directory to create a temp directory for. path After calling create() or entering, contains the full path to the temporary directory. delete Whether the directory should be deleted when exiting (when used as a contextmanager) """ # The characters that may be used to name the temp directory # We always prepend a ~ and then rotate through these until # a usable name is found. # pkg_resources raises a different error for .dist-info folder # with leading '-' and invalid metadata LEADING_CHARS = "-~.=%0123456789" def __init__(self, original, delete=None): # type: (str, Optional[bool]) -> None self.original = original.rstrip('/\\') super(AdjacentTempDirectory, self).__init__(delete=delete) @classmethod def _generate_names(cls, name): # type: (str) -> Iterator[str] """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name def _create(self, kind): # type: (str) -> str root, name = os.path.split(self.original) for candidate in self._generate_names(name): path = os.path.join(root, candidate) try: os.mkdir(path) except OSError as ex: # Continue if the name exists already if ex.errno != errno.EEXIST: raise else: path = os.path.realpath(path) break else: # Final fallback on the default behavior. path = os.path.realpath( tempfile.mkdtemp(prefix="pip-{}-".format(kind)) ) logger.debug("Created temporary directory: %s", path) return path utils/marker_files.py000064400000001467152347654150010745 0ustar00# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False import os.path DELETE_MARKER_MESSAGE = '''\ This file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). ''' PIP_DELETE_MARKER_FILENAME = 'pip-delete-this-directory.txt' def has_delete_marker_file(directory): return os.path.exists(os.path.join(directory, PIP_DELETE_MARKER_FILENAME)) def write_delete_marker_file(directory): # type: (str) -> None """ Write the pip delete marker file into this directory. """ filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME) with open(filepath, 'w') as marker_fp: marker_fp.write(DELETE_MARKER_MESSAGE) utils/filetypes.py000064400000001073152347654150010277 0ustar00"""Filetype information. """ from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Tuple WHEEL_EXTENSION = '.whl' BZ2_EXTENSIONS = ('.tar.bz2', '.tbz') # type: Tuple[str, ...] XZ_EXTENSIONS = ('.tar.xz', '.txz', '.tlz', '.tar.lz', '.tar.lzma') # type: Tuple[str, ...] ZIP_EXTENSIONS = ('.zip', WHEEL_EXTENSION) # type: Tuple[str, ...] TAR_EXTENSIONS = ('.tar.gz', '.tgz', '.tar') # type: Tuple[str, ...] ARCHIVE_EXTENSIONS = ( ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS ) utils/__init__.py000064400000000000152347654150010017 0ustar00utils/encoding.py000064400000002404152347654150010060 0ustar00import codecs import locale import re import sys from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Tuple, Text BOMS = [ (codecs.BOM_UTF8, 'utf-8'), (codecs.BOM_UTF16, 'utf-16'), (codecs.BOM_UTF16_BE, 'utf-16-be'), (codecs.BOM_UTF16_LE, 'utf-16-le'), (codecs.BOM_UTF32, 'utf-32'), (codecs.BOM_UTF32_BE, 'utf-32-be'), (codecs.BOM_UTF32_LE, 'utf-32-le'), ] # type: List[Tuple[bytes, Text]] ENCODING_RE = re.compile(br'coding[:=]\s*([-\w.]+)') def auto_decode(data): # type: (bytes) -> Text """Check a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3""" for bom, encoding in BOMS: if data.startswith(bom): return data[len(bom):].decode(encoding) # Lets check the first two lines as in PEP263 for line in data.split(b'\n')[:2]: if line[0:1] == b'#' and ENCODING_RE.search(line): result = ENCODING_RE.search(line) assert result is not None encoding = result.groups()[0].decode('ascii') return data.decode(encoding) return data.decode( locale.getpreferredencoding(False) or sys.getdefaultencoding(), ) utils/inject_securetransport.py000064400000001452152347654150013073 0ustar00"""A helper module that injects SecureTransport, on import. The import should be done as early as possible, to ensure all requests and sessions (or whatever) are created after injecting SecureTransport. Note that we only do the injection on macOS, when the linked OpenSSL is too old to handle TLSv1.2. """ import sys def inject_securetransport(): # type: () -> None # Only relevant on macOS if sys.platform != "darwin": return try: import ssl except ImportError: return # Checks for OpenSSL 1.0.1 if ssl.OPENSSL_VERSION_NUMBER >= 0x1000100f: return try: from pip._vendor.urllib3.contrib import securetransport except (ImportError, OSError): return securetransport.inject_into_urllib3() inject_securetransport() build_env.py000064400000017630152347654150007110 0ustar00"""Build Environment used for isolation during sdist building """ import logging import os import sys import textwrap from collections import OrderedDict from distutils.sysconfig import get_python_lib from sysconfig import get_paths from pip._vendor.pkg_resources import Requirement, VersionConflict, WorkingSet from pip import __file__ as pip_location from pip._internal.cli.spinners import open_spinner from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from types import TracebackType from typing import Tuple, Set, Iterable, Optional, List, Type from pip._internal.index.package_finder import PackageFinder logger = logging.getLogger(__name__) class _Prefix: def __init__(self, path): # type: (str) -> None self.path = path self.setup = False self.bin_dir = get_paths( 'nt' if os.name == 'nt' else 'posix_prefix', vars={'base': path, 'platbase': path} )['scripts'] # Note: prefer distutils' sysconfig to get the # library paths so PyPy is correctly supported. purelib = get_python_lib(plat_specific=False, prefix=path) platlib = get_python_lib(plat_specific=True, prefix=path) if purelib == platlib: self.lib_dirs = [purelib] else: self.lib_dirs = [purelib, platlib] class BuildEnvironment(object): """Creates and manages an isolated environment to install build deps """ def __init__(self): # type: () -> None temp_dir = TempDirectory( kind=tempdir_kinds.BUILD_ENV, globally_managed=True ) self._prefixes = OrderedDict(( (name, _Prefix(os.path.join(temp_dir.path, name))) for name in ('normal', 'overlay') )) self._bin_dirs = [] # type: List[str] self._lib_dirs = [] # type: List[str] for prefix in reversed(list(self._prefixes.values())): self._bin_dirs.append(prefix.bin_dir) self._lib_dirs.extend(prefix.lib_dirs) # Customize site to: # - ensure .pth files are honored # - prevent access to system site packages system_sites = { os.path.normcase(site) for site in ( get_python_lib(plat_specific=False), get_python_lib(plat_specific=True), ) } self._site_dir = os.path.join(temp_dir.path, 'site') if not os.path.exists(self._site_dir): os.mkdir(self._site_dir) with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp: fp.write(textwrap.dedent( ''' import os, site, sys # First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path # Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) ''' ).format(system_sites=system_sites, lib_dirs=self._lib_dirs)) def __enter__(self): # type: () -> None self._save_env = { name: os.environ.get(name, None) for name in ('PATH', 'PYTHONNOUSERSITE', 'PYTHONPATH') } path = self._bin_dirs[:] old_path = self._save_env['PATH'] if old_path: path.extend(old_path.split(os.pathsep)) pythonpath = [self._site_dir] os.environ.update({ 'PATH': os.pathsep.join(path), 'PYTHONNOUSERSITE': '1', 'PYTHONPATH': os.pathsep.join(pythonpath), }) def __exit__( self, exc_type, # type: Optional[Type[BaseException]] exc_val, # type: Optional[BaseException] exc_tb # type: Optional[TracebackType] ): # type: (...) -> None for varname, old_value in self._save_env.items(): if old_value is None: os.environ.pop(varname, None) else: os.environ[varname] = old_value def check_requirements(self, reqs): # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]] """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = set() if reqs: ws = WorkingSet(self._lib_dirs) for req in reqs: try: if ws.find(Requirement.parse(req)) is None: missing.add(req) except VersionConflict as e: conflicting.add((str(e.args[0].as_requirement()), str(e.args[1]))) return conflicting, missing def install_requirements( self, finder, # type: PackageFinder requirements, # type: Iterable[str] prefix_as_string, # type: str message # type: str ): # type: (...) -> None prefix = self._prefixes[prefix_as_string] assert not prefix.setup prefix.setup = True if not requirements: return args = [ sys.executable, os.path.dirname(pip_location), 'install', '--ignore-installed', '--no-user', '--prefix', prefix.path, '--no-warn-script-location', ] # type: List[str] if logger.getEffectiveLevel() <= logging.DEBUG: args.append('-v') for format_control in ('no_binary', 'only_binary'): formats = getattr(finder.format_control, format_control) args.extend(('--' + format_control.replace('_', '-'), ','.join(sorted(formats or {':none:'})))) index_urls = finder.index_urls if index_urls: args.extend(['-i', index_urls[0]]) for extra_index in index_urls[1:]: args.extend(['--extra-index-url', extra_index]) else: args.append('--no-index') for link in finder.find_links: args.extend(['--find-links', link]) for host in finder.trusted_hosts: args.extend(['--trusted-host', host]) if finder.allow_all_prereleases: args.append('--pre') if finder.prefer_binary: args.append('--prefer-binary') args.append('--') args.extend(requirements) with open_spinner(message) as spinner: call_subprocess(args, spinner=spinner) class NoOpBuildEnvironment(BuildEnvironment): """A no-op drop-in replacement for BuildEnvironment """ def __init__(self): # type: () -> None pass def __enter__(self): # type: () -> None pass def __exit__( self, exc_type, # type: Optional[Type[BaseException]] exc_val, # type: Optional[BaseException] exc_tb # type: Optional[TracebackType] ): # type: (...) -> None pass def cleanup(self): # type: () -> None pass def install_requirements( self, finder, # type: PackageFinder requirements, # type: Iterable[str] prefix_as_string, # type: str message # type: str ): # type: (...) -> None raise NotImplementedError() __init__.py000064400000000775152347654150006702 0ustar00import pip._internal.utils.inject_securetransport # noqa from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, List def main(args=None): # type: (Optional[List[str]]) -> int """This is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper return _wrapper(args, _nowarn=True) self_outdated_check.py000064400000015173152347654150011120 0ustar00from __future__ import absolute_import import datetime import hashlib import json import logging import os.path import sys from pip._vendor.packaging import version as packaging_version from pip._vendor.six import ensure_binary from pip._internal.index.collector import LinkCollector from pip._internal.index.package_finder import PackageFinder from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.utils.filesystem import ( adjacent_tmp_file, check_path_owner, replace, ) from pip._internal.utils.misc import ( ensure_dir, get_distribution, get_installed_version, ) from pip._internal.utils.packaging import get_installer from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: import optparse from typing import Any, Dict, Text, Union from pip._internal.network.session import PipSession SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ" logger = logging.getLogger(__name__) def _get_statefile_name(key): # type: (Union[str, Text]) -> str key_bytes = ensure_binary(key) name = hashlib.sha224(key_bytes).hexdigest() return name class SelfCheckState(object): def __init__(self, cache_dir): # type: (str) -> None self.state = {} # type: Dict[str, Any] self.statefile_path = None # Try to load the existing state if cache_dir: self.statefile_path = os.path.join( cache_dir, "selfcheck", _get_statefile_name(self.key) ) try: with open(self.statefile_path) as statefile: self.state = json.load(statefile) except (IOError, ValueError, KeyError): # Explicitly suppressing exceptions, since we don't want to # error out if the cache file is invalid. pass @property def key(self): # type: () -> str return sys.prefix def save(self, pypi_version, current_time): # type: (str, datetime.datetime) -> None # If we do not have a path to cache in, don't bother saving. if not self.statefile_path: return # Check to make sure that we own the directory if not check_path_owner(os.path.dirname(self.statefile_path)): return # Now that we've ensured the directory is owned by this user, we'll go # ahead and make sure that all our directories are created. ensure_dir(os.path.dirname(self.statefile_path)) state = { # Include the key so it's easy to tell which pip wrote the # file. "key": self.key, "last_check": current_time.strftime(SELFCHECK_DATE_FMT), "pypi_version": pypi_version, } text = json.dumps(state, sort_keys=True, separators=(",", ":")) with adjacent_tmp_file(self.statefile_path) as f: f.write(ensure_binary(text)) try: # Since we have a prefix-specific state file, we can just # overwrite whatever is there, no need to check. replace(f.name, self.statefile_path) except OSError: # Best effort. pass def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ dist = get_distribution(pkg) if not dist: return False return "pip" == get_installer(dist) def pip_self_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is link_collector = LinkCollector.create( session, options=options, suppress_no_index=True, ) # Pass allow_yanked=False so we don't suggest upgrading to a # yanked version. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=False, # Explicitly set to False ) finder = PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, ) best_candidate = finder.find_best_candidate("pip").best_candidate if best_candidate is None: return pypi_version = str(best_candidate.version) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) local_version_is_older = ( pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip') ) # Determine if our pypi_version is older if not local_version_is_older: return # We cannot tell how the current pip is available in the current # command context, so be pragmatic here and suggest the command # that's always available. This does not accommodate spaces in # `sys.executable`. pip_cmd = "{} -m pip".format(sys.executable) logger.warning( "You are using pip version %s; however, version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, ) __pycache__/self_outdated_check.cpython-37.pyc000064400000010656152352421740015377 0ustar00B Re{@s"ddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlmZddlmZddlmZddlmZmZmZdd lmZmZmZdd lmZdd lmZerddl Z dd l!m"Z"m#Z#m$Z$m%Z%dd l&m'Z'dZ(e)e*Z+ddZ,Gddde-Z.ddZ/ddZ0dS))absolute_importN)version) ensure_binary) LinkCollector) PackageFinder)SelectionPreferences)adjacent_tmp_filecheck_path_ownerreplace) ensure_dirget_distributionget_installed_version) get_installer)MYPY_CHECK_RUNNING)AnyDictTextUnion) PipSessionz%Y-%m-%dT%H:%M:%SZcCst|}t|}|S)N)rhashlibsha224 hexdigest)key key_bytesnamer/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/self_outdated_check.py_get_statefile_name*src@s(eZdZddZeddZddZdS)SelfCheckStatec Csni|_d|_|rjtj|dt|j|_y&t|j}t ||_WdQRXWnt t t fk rhYnXdS)N selfcheck) statestatefile_pathospathjoinrropenjsonloadIOError ValueErrorKeyError)self cache_dir statefilerrr__init__2s zSelfCheckState.__init__cCstjS)N)sysprefix)r+rrrrDszSelfCheckState.keyc Cs|js dSttj|js dSttj|j|j|t|d}t j |ddd}t |j}| t |WdQRXyt|j|jWntk rYnXdS)N)r last_check pypi_versionT),:) sort_keys separators)r!r r"r#dirnamer rstrftimeSELFCHECK_DATE_FMTr&dumpsrwriterr rOSError)r+r2 current_timer textfrrrsaveIs zSelfCheckState.saveN)__name__ __module__ __qualname__r.propertyrr@rrrrr1s rcCst|}|sdSdt|kS)zChecks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. Fpip)r r)pkgdistrrrwas_installed_by_pipmsrHcCsRtd}|sdSt|}d}yt|jd}tj}d|jkrzd|jkrztj|jdt }|| dkrz|jd}|dkrt j ||dd}t d d d } tj || d } | dj} | dkrdSt| j}|||t|} || ko|j| jkotd} | s dSd tj}td |||Wn$tk rLtjdddYnXdS)zCheck for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. rEN)r,r1r2i: T)optionssuppress_no_indexF) allow_yankedallow_all_prereleases)link_collectorselection_prefsz {} -m pipzYou are using pip version %s; however, version %s is available. You should consider upgrading via the '%s install --upgrade pip' command.z5There was an error checking the latest version of pip)exc_info)r packaging_versionparserr,datetimeutcnowr strptimer9 total_secondsrcreaterrfind_best_candidatebest_candidatestrrr@ base_versionrHformatr/ executableloggerwarning Exceptiondebug)sessionrIinstalled_version pip_versionr2r r=r1rMrNfinderrXremote_versionlocal_version_is_olderpip_cmdrrrpip_self_version_checkzsX          rh)1 __future__rrRrr&loggingos.pathr"r/Zpip._vendor.packagingrrPZpip._vendor.sixrpip._internal.index.collectorr"pip._internal.index.package_finderr$pip._internal.models.selection_prefsrpip._internal.utils.filesystemrr r pip._internal.utils.miscr r r pip._internal.utils.packagingrpip._internal.utils.typingroptparsetypingrrrrpip._internal.network.sessionrr9 getLoggerrAr]robjectrrHrhrrrrs2          < __pycache__/main.cpython-37.pyc000064400000001252152352421740012334 0ustar00B Re@s.ddlmZer ddlmZmZdddZdS))MYPY_CHECK_RUNNING)OptionalListNcCsddlm}||S)zThis is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. r)_wrapper)pip._internal.utils.entrypointsr)argsrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/main.pymains r )N)pip._internal.utils.typingrtypingrrr rrrr s __pycache__/pyproject.cpython-37.pyc000064400000007267152352421740013443 0ustar00B Re@sddlmZddlZddlZddlZddlmZddlmZm Z ddl m Z m Z ddl mZddlmZerddlmZmZmZd d Zd d Zed ddddgZddZdS))absolute_importN) namedtuple)sixtoml)InvalidRequirement Requirement)InstallationError)MYPY_CHECK_RUNNING)AnyOptionalListcCst|totdd|DS)Ncss|]}t|tjVqdS)N) isinstancer string_types).0itemr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/pyproject.py sz"_is_list_of_str..)r listall)objrrr_is_list_of_strs rcCs2tj|d}tjr.t|tjr.|t }|S)Nzpyproject.toml) ospathjoinrPY2r text_typeencodesysgetfilesystemencoding)unpacked_source_directoryrrrrmake_pyproject_pathsr!BuildSystemDetailsrequiresbackendcheck backend_pathc Cstj|}tj|}|rLtj|dd}t|}WdQRX|d}nd}|rr|sr|dk rl|sltdd}n<|rd|kr|dk r|std |dd}n |dkr|}|dk st |sdS|dkrd d gd d }|dk st d } d|krt| j |dd|d} t | s(t| j |ddxJ| D]B} y t | Wn.t k rlt| j |d | dYnXq.W|d} |dg} g}| dkrd } d d g}t| | || S)aBLoad the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file req_name - The name of the requirement we're processing (for error reporting) Returns: None if we should use the legacy code path, otherwise a tuple ( requirements from pyproject.toml, name of PEP 517 backend, requirements we should check are installed after setting up the build environment directory paths to import the backend from (backend-path), relative to the project root. ) zutf-8)encodingNz build-systemzIDisabling PEP 517 processing is invalid: project does not have a setup.pyTz build-backendzbDisabling PEP 517 processing is invalid: project specifies a build backend of {} in pyproject.tomlzsetuptools>=40.8.0wheelz setuptools.build_meta:__legacy__)r#z build-backendzO{package} has a pyproject.toml file that does not comply with PEP 518: {reason}r#z]it has a 'build-system' table but not 'build-system.requires' which is mandatory in the table)packagereasonz1'build-system.requires' is not a list of strings.z='build-system.requires' contains an invalid requirement: {!r}z backend-path)rrisfileioopenrloadgetrformatAssertionErrorrrrr") use_pep517pyproject_tomlsetup_pyreq_name has_pyproject has_setupfpp_toml build_systemerror_templater# requirementr$r&r%rrrload_pyproject_toml*sj                   r=) __future__rr,rr collectionsr pip._vendorrrZ"pip._vendor.packaging.requirementsrrpip._internal.exceptionsrpip._internal.utils.typingr typingr r r rr!r"r=rrrrs     __pycache__/build_env.cpython-37.pyc000064400000016477152352421740013376 0ustar00B Re@sdZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZddlmZddlmZdd lmZdd lmZmZdd lmZerdd lmZdd lmZmZm Z m!Z!m"Z"m#Z#ddl$m%Z%e&e'Z(GdddZ)Gddde*Z+Gddde+Z,dS)z;Build Environment used for isolation during sdist building N) OrderedDict)get_python_lib) get_paths) RequirementVersionConflict WorkingSet)__file__) open_spinner)call_subprocess) TempDirectory tempdir_kinds)MYPY_CHECK_RUNNING) TracebackType)TupleSetIterableOptionalListType) PackageFinderc@seZdZddZdS)_PrefixcCsj||_d|_ttjdkrdnd||ddd|_td|d}td|d}||kr\|g|_n ||g|_dS) NFnt posix_prefix)baseplatbase)varsscripts) plat_specificprefixT)pathsetuprosnamebin_dirrlib_dirs)selfrpurelibplatlibr(/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/build_env.py__init__s    z_Prefix.__init__N)__name__ __module__ __qualname__r*r(r(r(r)rsrc@s8eZdZdZddZddZddZdd Zd d Zd S) BuildEnvironmentzFCreates and manages an isolated environment to install build deps c sttjddtfdddD|_g|_g|_x6tt|j D] }|j |j |j |j qFWddtdd tdd fD}tjjd |_tj|jst|jttj|jd d "}|td j||jdWdQRXdS)NT)kindglobally_managedc3s&|]}|ttjj|fVqdS)N)rr!rjoin).0r")temp_dirr(r) ;sz,BuildEnvironment.__init__..)normaloverlaycSsh|]}tj|qSr()r!rnormcase)r2siter(r(r) Hsz,BuildEnvironment.__init__..F)rr8zsitecustomize.pywa import os, site, sys # First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path # Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) ) system_sitesr$)r r BUILD_ENVr _prefixes _bin_dirs _lib_dirsreversedlistvaluesappendr#extendr$rr!rr1 _site_direxistsmkdiropenwritetextwrapdedentformat)r%rr;fpr()r3r)r*4s(    zBuildEnvironment.__init__cCsndddD|_|jdd}|jd}|r>||tj|jg}tjtj |dtj |ddS)NcSsi|]}tj|d|qS)N)r!environget)r2r"r(r(r) osz.BuildEnvironment.__enter__..)PATHPYTHONNOUSERSITE PYTHONPATHrQ1) _save_envr>rDsplitr!pathseprErNupdater1)r%rold_path pythonpathr(r(r) __enter__ms   zBuildEnvironment.__enter__cCs>x8|jD]*\}}|dkr,tj|dq |tj|<q WdS)N)rUitemsr!rNpop)r%exc_typeexc_valexc_tbvarname old_valuer(r(r)__exit__szBuildEnvironment.__exit__c Cst}t}|rt|j}xx|D]p}y"|t|dkrD||Wq tk r}z*|t|j d t|j dfWdd}~XYq Xq W||fS)zReturn 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs Nr) setrr?findrparseaddrstrargsas_requirement)r%reqsmissing conflictingwsreqer(r(r)check_requirementss  (z#BuildEnvironment.check_requirementsc Cs|j|}|jrtd|_|s"dStjtjtdddd|jdg}t t j krZ| dxBdD]:}t|j|}|d |d d d t|pd hfq`W|j} | r|d| dgx.| ddD]} |d| gqWn | dx|jD]} |d| gqWx|jD]} |d| gqW|jr:| d|jrL| d| d ||t|} t|| dWdQRXdS)NTinstallz--ignore-installedz --no-userz--prefixz--no-warn-script-locationz-v) no_binary only_binaryz--_-,z:none:z-irrdz--extra-index-urlz --no-indexz --find-linksz--trusted-hostz--prez--prefer-binary)spinner)r=r AssertionErrorsys executabler!rdirname pip_locationloggergetEffectiveLevelloggingDEBUGrCgetattrformat_controlrDreplacer1sorted index_urls find_links trusted_hostsallow_all_prereleases prefer_binaryr r )r%finder requirementsprefix_as_stringmessagerrjrformatsr extra_indexlinkhostryr(r(r)install_requirementss@              z%BuildEnvironment.install_requirementsN) r+r,r-__doc__r*r[rcrrrr(r(r(r)r.0s 9 r.c@s8eZdZdZddZddZddZdd Zd d Zd S) NoOpBuildEnvironmentz5A no-op drop-in replacement for BuildEnvironment cCsdS)Nr()r%r(r(r)r*szNoOpBuildEnvironment.__init__cCsdS)Nr()r%r(r(r)r[szNoOpBuildEnvironment.__enter__cCsdS)Nr()r%r^r_r`r(r(r)rcszNoOpBuildEnvironment.__exit__cCsdS)Nr()r%r(r(r)cleanupszNoOpBuildEnvironment.cleanupcCs tdS)N)NotImplementedError)r%rrrrr(r(r)rsz)NoOpBuildEnvironment.install_requirementsN) r+r,r-rr*r[rcrrr(r(r(r)rs  r)-rrr!r{rJ collectionsrdistutils.sysconfigr sysconfigrZpip._vendor.pkg_resourcesrrrpiprr~pip._internal.cli.spinnersr pip._internal.utils.subprocessr pip._internal.utils.temp_dirr r pip._internal.utils.typingr typesrtypingrrrrrr"pip._internal.index.package_finderr getLoggerr+rrobjectr.rr(r(r(r)s,           !__pycache__/exceptions.cpython-37.pyc000064400000035006152352421740013575 0ustar00B Re]1@sNdZddlmZddlmZmZmZddlmZddl m Z e rddl m Z m Z mZmZmZddlmZddlmZmZdd lmZdd lmZdd lmZerdd lmZn dd lmZGdddeZGdddeZ GdddeZ!GdddeZ"GdddeZ#Gddde!Z$Gddde!Z%GdddeZ&GdddeZ'Gd d!d!eZ(Gd"d#d#eZ)Gd$d%d%eZ*Gd&d'd'eZ+Gd(d)d)e!Z,Gd*d+d+e!Z-Gd,d-d-e!Z.Gd.d/d/e!Z/Gd0d1d1e!Z0Gd2d3d3e0Z1Gd4d5d5e0Z2Gd6d7d7e0Z3Gd8d9d9e0Z4Gd:d;d;e0Z5Gdd?d?e Z7d@S)Az"Exceptions used throughout package)absolute_import)chaingroupbyrepeat) iteritems)MYPY_CHECK_RUNNING)AnyOptionalListDictText) Distribution)ResponseRequest)PY3) configparser)InstallRequirement)_Hash)_hashc@seZdZdZdS)PipErrorzBase pip exceptionN)__name__ __module__ __qualname____doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/exceptions.pyrsrc@seZdZdZdS)ConfigurationErrorz"General exception in configurationN)rrrrrrrrrsrc@seZdZdZdS)InstallationErrorz%General exception during installationN)rrrrrrrrr#src@seZdZdZdS)UninstallationErrorz'General exception during uninstallationN)rrrrrrrrr'src@s eZdZdZddZddZdS)NoneMetadataErrora Raised when accessing "METADATA" or "PKG-INFO" metadata for a pip._vendor.pkg_resources.Distribution object and `dist.has_metadata('METADATA')` returns True but `dist.get_metadata('METADATA')` returns None (and similarly for "PKG-INFO"). cCs||_||_dS)z :param dist: A Distribution object. :param metadata_name: The name of the metadata being accessed (can be "METADATA" or "PKG-INFO"). N)dist metadata_name)selfr r!rrr__init__4szNoneMetadataError.__init__cCsd|j|jS)Nz+None {} metadata found for distribution: {})formatr!r )r"rrr__str__>szNoneMetadataError.__str__N)rrrrr#r%rrrrr+s rc@seZdZdZdS)DistributionNotFoundzCRaised when a distribution cannot be found to satisfy a requirementN)rrrrrrrrr&Isr&c@seZdZdZdS)RequirementsFileParseErrorzDRaised when a general error occurs parsing a requirements file line.N)rrrrrrrrr'Msr'c@seZdZdZdS)BestVersionAlreadyInstalledzNRaised when the most up-to-date version of a package is already installed.N)rrrrrrrrr(Qsr(c@seZdZdZdS) BadCommandz0Raised when virtualenv or a command is not foundN)rrrrrrrrr)Vsr)c@seZdZdZdS) CommandErrorz7Raised when there is an error in command-line argumentsN)rrrrrrrrr*Zsr*c@seZdZdZdS)SubProcessErrorzPRaised when there is an error raised while executing a command in subprocessN)rrrrrrrrr+^sr+c@seZdZdZdS)PreviousBuildDirErrorz:Raised when there's a previous conflicting build directoryN)rrrrrrrrr,csr,cs*eZdZdZdfdd ZddZZS)NetworkConnectionErrorzHTTP connection errorNcsN||_||_||_|jdk r6|js6t|dr6|jj|_tt||||dS)zc Initialize NetworkConnectionError with `request` and `response` objects. Nrequest)responser. error_msghasattrsuperr-r#)r"r0r/r.) __class__rrr#js   zNetworkConnectionError.__init__cCs t|jS)N)strr0)r"rrrr%yszNetworkConnectionError.__str__)NN)rrrrr#r% __classcell__rr)r3rr-gsr-c@seZdZdZdS)InvalidWheelFilenamezInvalid wheel filename.N)rrrrrrrrr6~sr6c@seZdZdZdS)UnsupportedWheelzUnsupported wheel.N)rrrrrrrrr7sr7c@s eZdZdZddZddZdS)MetadataInconsistentzBuilt metadata contains inconsistent information. This is raised when the metadata contains values (e.g. name and version) that do not match the information previously obtained from sdist filename or user-supplied ``#egg=`` value. cCs||_||_||_dS)N)ireqfieldbuilt)r"r9r:r;rrrr#szMetadataInconsistent.__init__cCsd|j|j|jS)Nz/Requested {} has different {} in metadata: {!r})r$r9r:r;)r"rrrr%szMetadataInconsistent.__str__N)rrrrr#r%rrrrr8sr8c@s8eZdZdZddZddZddZdd Zd d Zd S) HashErrorsz:Multiple HashError instances rolled into one for reportingcCs g|_dS)N)errors)r"rrrr#szHashErrors.__init__cCs|j|dS)N)r=append)r"errorrrrr>szHashErrors.appendcCsfg}|jjdddxz$HashErrors.__str__..)keycSs|jS)N)r3)rArrrrBrCcss|]}|VqdS)N)body).0rArrr sz%HashErrors.__str__.. )r=sortrr>headextendjoin)r"linescls errors_of_clsrrrr%s  zHashErrors.__str__cCs t|jS)N)boolr=)r"rrr __nonzero__szHashErrors.__nonzero__cCs|S)N)rR)r"rrr__bool__szHashErrors.__bool__N) rrrrr#r>r%rRrSrrrrr<s  r<c@s4eZdZdZdZdZdZddZddZdd Z dS) HashErrora A failure to verify a package against known-good hashes :cvar order: An int sorting hash exception classes by difficulty of recovery (lower being harder), so the user doesn't bother fretting about unpinned packages when he has deeper issues, like VCS dependencies, to deal with. Also keeps error reports in a deterministic order. :cvar head: A section heading for display above potentially many exceptions of this kind :ivar req: The InstallRequirement that triggered this error. This is pasted on after the exception is instantiated, because it's not typically available earlier. NrIcCsd|S)a=Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with its link already populated by the resolver's _populate_link(). z {})r$_requirement_name)r"rrrrEs zHashError.bodycCsd|j|S)Nz{} {})r$rKrE)r"rrrr%szHashError.__str__cCs|jrt|jSdS)zReturn a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers zunknown package)reqr4)r"rrrrUszHashError._requirement_name) rrrrrVrKr@rEr%rUrrrrrTs rTc@seZdZdZdZdZdS)VcsHashUnsupportedzuA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.rzlCan't verify hashes for these requirements because we don't have a way to hash version control repositories:N)rrrrr@rKrrrrrWsrWc@seZdZdZdZdZdS)DirectoryUrlHashUnsupportedzuA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.zUCan't verify hashes for these file:// requirements because they point to directories:N)rrrrr@rKrrrrrXsrXc@s(eZdZdZdZdZddZddZdS) HashMissingz2A hash was needed for a requirement but is absent.awHashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If you did not enable --require-hashes manually, note that it turns on automatically when any package has a hash.)cCs ||_dS)zq :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded N) gotten_hash)r"r\rrrr#szHashMissing.__init__cCsHddlm}d}|jr4|jjr&|jjn t|jdd}d|p>d||jS)Nr) FAVORITE_HASHrVz {} --hash={}:{}zunknown package)pip._internal.utils.hashesr]rV original_linkgetattrr$r\)r"r]packagerrrrEs  zHashMissing.bodyN)rrrrr@rKr#rErrrrrZs rZc@seZdZdZdZdZdS) HashUnpinnedzPA requirement had a hash specified but was not pinned to a specific version.zaIn --require-hashes mode, all requirements must have their versions pinned with ==. These do not:N)rrrrr@rKrrrrrb"srbc@s0eZdZdZdZdZddZddZdd Zd S) HashMismatchz Distribution file hash values don't match. :ivar package_name: The name of the package that triggered the hash mismatch. Feel free to write to this after the exception is raise to improve its error message. zTHESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.cCs||_||_dS)z :param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion N)allowedgots)r"rfrgrrrr#:szHashMismatch.__init__cCsd||S)Nz {}: {})r$rU_hash_comparison)r"rrrrEEs zHashMismatch.bodycshdd}g}xPt|jD]B\}}|||fdd|D|d|j|qWd|S)aE Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef cSst|gtdS)Nz or)rr) hash_namerrr hash_then_orVsz3HashMismatch._hash_comparison..hash_then_orc3s|]}dt|VqdS)z Expected {} {}N)r$next)rFrA)prefixrrrG_sz0HashMismatch._hash_comparison..z Got {} rH)rrfrLr>r$rg hexdigestrM)r"rjrNri expectedsr)rlrrhJs  zHashMismatch._hash_comparisonN) rrrrr@rKr#rErhrrrrrd+s  rdc@seZdZdZdS)UnsupportedPythonVersionzMUnsupported python version according to Requires-Python package metadata.N)rrrrrrrrrofsrocs*eZdZdZdfdd ZddZZS) !ConfigurationFileCouldNotBeLoadedz=When there are errors while loading a configuration file could not be loadedNcs&tt||||_||_||_dS)N)r2rpr#reasonfnamer?)r"rrrsr?)r3rrr#osz*ConfigurationFileCouldNotBeLoaded.__init__cCs@|jdk rd|j}n|jdk s&td|j}d|j|S)Nz in {}.z. {} zConfiguration file {}{})rsr$r?AssertionErrorrr)r" message_partrrrr%vs   z)ConfigurationFileCouldNotBeLoaded.__str__)rqNN)rrrrr#r%r5rr)r3rrpksrpN)8r __future__r itertoolsrrrZpip._vendor.sixrpip._internal.utils.typingrtypingrr r r r Zpip._vendor.pkg_resourcesr Zpip._vendor.requests.modelsrrrpip._vendor.six.movesrZpip._internal.req.req_installrhashlibrr Exceptionrrrrrr&r'r(r)r*r+r,r-r6r7r8r<rTrWrXrZrbrdrorprrrrsN        0  ' ;__pycache__/__init__.cpython-37.pyc000064400000001371152352421740013151 0ustar00B Re@s6ddlZddlmZer(ddlmZmZdddZdS)N)MYPY_CHECK_RUNNING)OptionalListcCsddlm}||ddS)zThis is preserved for old console scripts that may still be referencing it. For additional details, see https://github.com/pypa/pip/issues/7498. r)_wrapperT)_nowarn)pip._internal.utils.entrypointsr)argsrr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/__init__.pymains r )N)*pip._internal.utils.inject_securetransportpippip._internal.utils.typingrtypingrrr r r r r s __pycache__/configuration.cpython-37.pyc000064400000025127152352421740014266 0ustar00B Re#7@sdZddlZddlZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z mZddlmZmZddlmZerdd lmZmZmZmZmZmZmZejZed eZee Z!d d Z"d dZ#eddddddZ$e rdndZ%ddZ&Gddde'Z(dS)a Configuration management setup Some terminology: - name As written in config files. - value Value associated with a name - key Name combined with it's section (section.name) - variant A single word describing where the configuration key-value pair came from N) configparser)ConfigurationError!ConfigurationFileCouldNotBeLoaded)appdirs)WINDOWS expanduser) ensure_direnum)MYPY_CHECK_RUNNING)AnyDictIterableListNewTypeOptionalTupleKindcCs*|dd}|dr&|dd}|S)zFMake a name consistent regardless of source (environment or file) _-z--N)lowerreplace startswith)namer/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/configuration.py_normalize_name*s  rcCs&d|krd|}t||ddS)N.zbKey does not contain dot separated section and key. Perhaps you wanted to use 'global.{}' instead?)formatrsplit)r error_messagerrr_disassemble_key4s r"userglobalsiteenvzenv-var)USERGLOBALSITEENVENV_VARzpip.inizpip.confcCspddtdD}tjtjt}tjtdt r8dndt}tjt dt}t j |t j |gt j||giS)NcSsg|]}tj|tqSr)ospathjoinCONFIG_BASENAME).0r-rrr Osz+get_configuration_files..pip~z.pip)rsite_config_dirsr,r-r.sysprefixr/rruser_config_dirkindsr(r)r')global_config_filessite_config_filelegacy_config_filenew_config_filerrrget_configuration_filesLs r=cseZdZdZd-fdd ZddZddZd d Zd d Zd dZ ddZ ddZ ddZ e ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,ZZS). ConfigurationaHandles management of configuration. Provides an interface to accessing and managing configuration files. This class converts provides an API that takes "section.key-name" style keys and stores the value associated with it as "key-name" under the section "section". This allows for a clean interface wherein the both the section and the key-name are preserved in an easy to manage form in the configuration files and the data stored is also nice. Nc stt|tjtjtjdg}||krJtdd t t |dd||_ ||_ tjtjtjtjtjg|_ddg|_dd|jD|_dd|jD|_g|_dS) Nz5Got invalid value for load_only - should be one of {}z, versionhelpcSsi|] }g|qSrr)r0variantrrr sz*Configuration.__init__..cSsi|] }i|qSrr)r0rBrrrrCs)superr>__init__r8r'r(r)rrr.mapreprisolated load_onlyr*r+_override_order_ignore_env_names_parsers_config_modified_parsers)selfrHrI_valid_load_only) __class__rrrEqs   zConfiguration.__init__cCs||js|dS)zELoads configuration from configuration files and environment N)_load_config_filesrH_load_environment_vars)rOrrrloadszConfiguration.loadcCs8|jdk stdy |dStk r2dSXdS)z@Returns the file with highest priority in configuration Nz)Need to be specified a file to be editingr)rIAssertionError_get_parser_to_modify IndexError)rOrrrget_file_to_edits   zConfiguration.get_file_to_editcCs |jS)z`Returns key-value pairs like dict.items() representing the loaded configuration ) _dictionaryitems)rOrrrrZszConfiguration.itemscCs2y |j|Stk r,td|YnXdS)z,Get a value from the configuration. zNo such key - {}N)rYKeyErrorrr)rOkeyrrr get_values zConfiguration.get_valuecCst||jst|\}}|dk rTt|\}}||sF||||||||j|j|<| ||dS)z-Modify a value in the configuration. N) _ensure_have_load_onlyrIrUrVr" has_section add_sectionsetrM_mark_as_modified)rOr\valuefnameparsersectionrrrr set_values     zConfiguration.set_valuecCs||jst||j|jkr0td||\}}|dk rt|\}}||rf| ||sntd| |s| || |||j|j|=dS)z#Unset a value in the configuration.zNo such key - {}Nz4Fatal Internal error [id=1]. Please report as a bug.) r^rIrUrMrrrVr"r_ remove_optionrZremove_sectionrb)rOr\rdrerfrrrr unset_values        zConfiguration.unset_valuec Cs\|xN|jD]D\}}td|ttj|t|d}| |WdQRXqWdS)z*Save the current in-memory state. z Writing to %swN) r^rNloggerinforr,r-dirnameopenwrite)rOrdrefrrrsaves   zConfiguration.savecCs$|jdkrtdtd|jdS)Nz'Needed a specific file to be modifying.z$Will be working with %s variant only)rIrrldebug)rOrrrr^s z$Configuration._ensure_have_load_onlycCs(i}x|jD]}||j|q W|S)zWdS)z5Loads configuration from configuration files rrzZSkipping loading configuration files due to environment's PIP_CONFIG_FILE being os.devnullNz Skipping file '%s' (variant: %s)) dictiter_config_filesr8r*r,devnullrlrsrZrI _load_filerLappend)rO config_filesrBfilesrdrerrrrR s    z Configuration._load_config_filescCsPtd||||}x2|D]&}||}|j||||q"W|S)Nz'For variant '%s', will try loading '%s')rlrs_construct_parsersectionsrZrMrt_normalized_keys)rOrBrdrerfrZrrrry$s   zConfiguration._load_filec Cst}tj|r|y||WnXtk rNtdt d|dYn.tj k rz}zt|dWdd}~XYnX|S)Nzcontains invalid {} charactersF)reasonrd)error) rRawConfigParserr,r-existsreadUnicodeDecodeErrorrrlocalegetpreferredencodingError)rOrdrerrrrr}/s   zConfiguration._construct_parsercCs"|jtj|d|dS)z7Loads configuration from environment variables z:env:N)rMr8r+rtrget_environ_vars)rOrrrrSFs z$Configuration._load_environment_varscCs2i}x(|D] \}}|dt|}|||<q W|S)zNormalizes items to construct a dictionary with normalized keys. This routine is where the names become keys and are made the same regardless of source - configuration files or environment. r)r)rOrfrZ normalizedrvalr\rrrrNs  zConfiguration._normalized_keysccsVxPtjD]B\}}|do2|dd|jk}|r |dd|fVq WdS)z@Returns a generator with all environmental vars with prefix PIP_PIP_N)r,environrZrrrK)rOr\rshould_be_yieldedrrrr[s  zConfiguration.get_environ_varsccstjdd}|dk r&tj|gfVn tjgfVt}tj|tjfV|j ob|o`tj | }|rztj |tj fVtj |tj fVdS)zYields variant and configuration files associated with it. This should be treated like items of a dictionary. PIP_CONFIG_FILEN) r,rgetr8r*r=r(rHr-rr'r))rO config_filer{should_load_user_configrrrrwgs  zConfiguration.iter_config_filescCs |j|S)z#Get values present in a config file)rM)rOrBrrrget_values_in_configsz"Configuration.get_values_in_configcCs*|js t|j|j}|s"td|dS)Nz4Fatal Internal error [id=2]. Please report as a bug.r?)rIrUrLr)rOparsersrrrrVs   z#Configuration._get_parser_to_modifycCs"||f}||jkr|j|dS)N)rNrz)rOrdrefile_parser_tuplerrrrbs zConfiguration._mark_as_modifiedcCsd|jj|jS)Nz{}({!r}))rrQ__name__rY)rOrrr__repr__szConfiguration.__repr__)N)r __module__ __qualname____doc__rErTrXrZr]rgrjrrr^propertyrYrRryr}rSrrrwrrVrbr __classcell__rr)rQrr>cs,       r>))rrloggingr,r5pip._vendor.six.movesrpip._internal.exceptionsrrZpip._internal.utilsrpip._internal.utils.compatrrpip._internal.utils.miscrr pip._internal.utils.typingr typingr r r rrrrrstrr getLoggerrrlrr"r8r/r=objectr>rrrr s4   $     __pycache__/cache.cpython-37.pyc000064400000021626152352421740012462 0ustar00B Re/@s*dZddlZddlZddlZddlZddlmZmZddlm Z ddl m Z ddl m Z ddlmZddlmZmZdd lmZdd lmZerdd lmZmZmZmZmZdd lmZdd lmZe e!Z"ddZ#Gddde$Z%Gddde%Z&Gddde&Z'Gddde$Z(Gddde%Z)dS)zCache Management N)interpreter_nameinterpreter_version)canonicalize_name)InvalidWheelFilename)Link)Wheel) TempDirectory tempdir_kinds)MYPY_CHECK_RUNNING) path_to_url)OptionalSetListAnyDict)Tag) FormatControlcCs&tj|dddd}t|dS)z'Return a stable sha224 of a dictionary.T),:) sort_keys separators ensure_asciiascii)jsondumpshashlibsha224encode hexdigest)dsr!/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cache.py _hash_dictsr#csPeZdZdZfddZddZddZdd Zd d Zd d Z ddZ Z S)CacheaAn abstract class - provides cache directories for data from links :param cache_dir: The root of the cache. :param format_control: An object of FormatControl class to limit binaries being read from the cache. :param allowed_formats: which formats of files the cache should store. ('binary' and 'source' are the only allowed values) csXtt||r"tj|s"t|p(d|_||_||_ ddh}|j ||ksTtdS)Nsourcebinary) superr$__init__ospathisabsAssertionError cache_dirformat_controlallowed_formatsunion)selfr-r.r/_valid_formats) __class__r!r"r(/s zCache.__init__cCs|jg}|jdk r4|jdk r4|d|j|jgd|}t|}|dd|dd|dd|ddg}|S)zGet parts of part that must be os.path.joined with cache_dir Legacy cache key (pip < 20) for compatibility with older caches. N=#) url_without_fragment hash_namehashappendjoinrrrr)r1link key_partskey_urlhashedpartsr!r!r"_get_cache_path_parts_legacy:s  ,z"Cache._get_cache_path_parts_legacycCsd|ji}|jdk r*|jdk r*|j||j<|jr:|j|d<t|d<t|d<t|}|dd|dd|dd|ddg}|S) zEGet parts of part that must be os.path.joined with cache_dir urlN subdirectoryrrr6r7r8)r9r:r;subdirectory_fragmentrrr#)r1r>r?rArBr!r!r"_get_cache_path_partsVs     ,zCache._get_cache_path_partsc Cs|j p| p| }|rgS|j|}|j|s8gSg}||}tj|rtx t |D]}| ||fq^W| |}tj|rx t |D]}| ||fqW|S)N) r-r.get_allowed_formatsr/ intersectionget_path_for_linkr)r*isdirlistdirr<get_path_for_link_legacy) r1r>canonical_package_name can_not_cacheformats candidatesr* candidate legacy_pathr!r!r"_get_candidatesys&     zCache._get_candidatescCs tdS)N)NotImplementedError)r1r>r!r!r"rMszCache.get_path_for_link_legacycCs tdS)z>Return a directory to store cached items in for link. N)rU)r1r>r!r!r"rJszCache.get_path_for_linkcCs tdS)zaReturns a link to a cached item if it exists, otherwise returns the passed link. N)rU)r1r> package_namesupported_tagsr!r!r"gets z Cache.get) __name__ __module__ __qualname____doc__r(rCrGrTrMrJrX __classcell__r!r!)r3r"r$$s  #r$cs8eZdZdZfddZddZddZdd ZZS) SimpleWheelCachez+A cache of wheels for future installs. cstt|||dhdS)Nr&)r'r^r()r1r-r.)r3r!r"r(s zSimpleWheelCache.__init__cCs*||}|jsttjj|jdf|S)Nwheels)rCr-r,r)r*r=)r1r>rBr!r!r"rMs  z)SimpleWheelCache.get_path_for_link_legacycCs*||}|jsttjj|jdf|S)aReturn a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param link: The link of the sdist for which this will cache wheels. r_)rGr-r,r)r*r=)r1r>rBr!r!r"rJs  z"SimpleWheelCache.get_path_for_linkc Csg}|s |St|}x~|||D]n\}}y t|}Wntk rLw"YnXt|j|krntd|||q"||szq"|| |||fq"W|s|St |\} }}t t t j||S)NzWIgnoring cached wheel %s for %s as it does not match the expected distribution name %s.)rrTrrnameloggerdebug supportedr<support_index_minminrr r)r*r=) r1r>rVrWrQrN wheel_name wheel_dirwheel_r!r!r"rXs2    zSimpleWheelCache.get) rYrZr[r\r(rMrJrXr]r!r!)r3r"r^s  r^cs eZdZdZfddZZS)EphemWheelCachezGA SimpleWheelCache that creates it's own temporary cache directory cs*ttjdd|_tt||jj|dS)NT)kindglobally_managed)rr EPHEM_WHEEL_CACHE _temp_dirr'rjr(r*)r1r.)r3r!r"r(s   zEphemWheelCache.__init__)rYrZr[r\r(r]r!r!)r3r"rjsrjc@seZdZddZdS) CacheEntrycCs||_||_dS)N)r> persistent)r1r>rpr!r!r"r(szCacheEntry.__init__N)rYrZr[r(r!r!r!r"rosrocsHeZdZdZfddZddZddZdd Zd d Zd d Z Z S) WheelCachezWraps EphemWheelCache and SimpleWheelCache into a single Cache This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. cs0tt|||dht|||_t||_dS)Nr&)r'rqr(r^ _wheel_cacherj _ephem_cache)r1r-r.)r3r!r"r(s   zWheelCache.__init__cCs |j|S)N)rrrM)r1r>r!r!r"rM'sz#WheelCache.get_path_for_link_legacycCs |j|S)N)rrrJ)r1r>r!r!r"rJ+szWheelCache.get_path_for_linkcCs |j|S)N)rsrJ)r1r>r!r!r"get_ephem_path_for_link/sz"WheelCache.get_ephem_path_for_linkcCs ||||}|dkr|S|jS)N)get_cache_entryr>)r1r>rVrW cache_entryr!r!r"rX3szWheelCache.getcCsP|jj|||d}||k r&t|ddS|jj|||d}||k rLt|ddSdS)zReturns a CacheEntry with a link to a cached item if it exists or None. The cache entry indicates if the item was found in the persistent or ephemeral cache. )r>rVrWT)rpFN)rrrXrors)r1r>rVrWretvalr!r!r"ru?s   zWheelCache.get_cache_entry) rYrZr[r\r(rMrJrtrXrur]r!r!)r3r"rqs  rq)*r\rrloggingr)pip._vendor.packaging.tagsrrZpip._vendor.packaging.utilsrpip._internal.exceptionsrpip._internal.models.linkrpip._internal.models.wheelrpip._internal.utils.temp_dirrr pip._internal.utils.typingr pip._internal.utils.urlsr typingr r rrrr#pip._internal.models.format_controlr getLoggerrYrar#objectr$r^rjrorqr!r!r!r"s0          R __pycache__/wheel_builder.cpython-37.pyc000064400000015211152352421740014222 0ustar00B Re2%@sdZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z ddlmZmZmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZerddlmZm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(e e(ge)fZ*e$e"e(e"e(fZ+e,e-Z.e/dej0Z1ddZ2ddZ3ddZ4ddZ5ddZ6ddZ7ddZ8d d!Z9d"d#Z:d$d%Z;d&d'ZdS||sXtd|jdS|jsvtsvtd|jdSdS)zBReturn whether an InstallRequirement should be built into a wheel.Fz(Skipping %s, due to already being wheel.TzCSkipping wheel build for %s, due to binaries being disabled for it.zOUsing legacy 'setup.py install' for %s, since package 'wheel' is not installed.) constraintis_wheelloggerinfonameeditable source_dir use_pep517r)req need_wheelcheck_binary_allowedrrr _should_build.s,   r)cCst|dtdS)NT)r'r()r) _always_true)r&rrrshould_build_for_wheel_command[sr+cCst|d|dS)NF)r'r()r))r&r(rrr should_build_for_install_commanddsr,cCs|js |jsdS|jrb|jjrb|jr(t|js2tt|jj}|sHt||jj |jr^dSdS|jslt|j \}}t |rdSdS)z Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. FT) r#r$linkis_vcsAssertionErrorrget_backend_for_schemeschemeis_immutable_rev_checkouturlsplitextr)r& vcs_backendbaseextrrr _should_cachens    r8cCs>t|j}|jst|r.t|r.||j}n ||j}|S)zdReturn the persistent or temporary cache directory where the built wheel need to be stored. )r cache_dirr-r/r8get_path_for_linkget_ephem_path_for_link)r& wheel_cachecache_availabler9rrr_get_cache_dirs     r>cCsdS)NTr)_rrrr*sr*c Cs`y t|Wn2tk r>}ztd|j|dSd}~XYnX|jt||||SQRXdS)zaBuild one wheel. :return: The filename of the built wheel, or None if the build failed. z Building wheel for %s failed: %sN)rOSErrorr warningr" build_env_build_one_inside_env)r& output_dir build_optionsglobal_optionserrr _build_ones   rHc Cstdd}|jst|jrD|js(tt|j|j|j||jd}nt|j|j |j |||jd}|dk rt j |}t j ||}y@t|\}} t||td|j|| |td||Stk r} ztd|j| Wdd} ~ XYnX|jst||dSQRXdS)Nwheel)kind)r"backendmetadata_directoryrEtempd)r" setup_py_pathr$rFrErMz3Created wheel for %s: filename=%s size=%d sha256=%szStored in directory: %sz Building wheel for %s failed: %s)r r"r/r%rLrpep517_backendpathrrNunpacked_source_directoryosbasenamejoinrshutilmover r! hexdigest ExceptionrA_clean_one_legacy) r&rDrErFtemp_dir wheel_path wheel_name dest_path wheel_hashlengthrGrrrrCsF          rCcCsVt|j|d}td|jyt||jddStk rPtd|jdSXdS)N)rFzRunning setup.py clean for %s)cwdTz Failed cleaning build dir for %sF) r rNr r!r"r r$rXerror)r&rF clean_argsrrrrYsrYc Cs|s ggfStdddd|Dttgg}}xb|D]Z}t||}t||||}|rtt||_|jj |_ |jj st | |q@| |q@WWdQRX|rtdddd |D|rtd dd d |D||fS) zBuild wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build. z*Building wheels for collected packages: %sz, css|] }|jVqdS)N)r").0r&rrr szbuild..NzSuccessfully built %s cSsg|] }|jqSr)r")rcr&rrr ,szbuild..zFailed to build %scSsg|] }|jqSr)r")rcr&rrrrf1s)r r!rTrr>rHrr r- file_pathlocal_file_pathrr/append) requirementsr<rErFbuild_successesbuild_failuresr&r9 wheel_filerrrbuilds4        rn)=__doc__loggingos.pathrRrerUpip._internal.models.linkr$pip._internal.operations.build.wheelr+pip._internal.operations.build.wheel_legacyrpip._internal.utils.loggingrpip._internal.utils.miscrrr$pip._internal.utils.setuptools_buildr pip._internal.utils.subprocessr pip._internal.utils.temp_dirr pip._internal.utils.typingr pip._internal.utils.urlsr pip._internal.vcsrtypingrrrrrrpip._internal.cacherZpip._internal.req.req_installrrZBinaryAllowedPredicateZ BuildResult getLogger__name__r compile IGNORECASErrr)r+r,r8r>r*rHrCrYrnrrrrsD               -  !3__pycache__/locations.cpython-37.pyc000064400000010634152352421740013407 0ustar00B ReL@sdZddlmZddlZddlZddlZddlZddlZddlZddl mZ ddl m Z ddl m ZddlmZddlmZdd lmZdd lmZmZdd lmZerdd lmZmZmZmZdd lm Z!e"dZ#ddZ$ddZ%e&dZ'e()dkr e *Z'y e+Z,Wne-k r2ej.Z,YnXerej/0ej1dZ2ej/0e,dZ3ej/4e2sej/0ej1dZ2ej/0e,dZ3nJej/0ej1dZ2ej/0e,dZ3ejdddkrej1dddkrdZ2d!ddZ5d"dd Z6dS)#z7Locations where we look for configs, install stuff, etc)absolute_importN) sysconfig) SCHEME_KEYS)install)Scheme)appdirs)WINDOWS)MYPY_CHECK_RUNNINGcast)running_under_virtualenv)DictListOptionalUnion)CommandpipcCs djtjS)ze Return the major-minor version of the current Python as a string, e.g. "3.7" or "3.10". z{}.{})formatsys version_inforr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/locations.pyget_major_minor_version"srcCsZtrtjtjd}n6ytjtd}Wntk rLtdYnXtj |S)Nsrcz=The folder you are executing pip from can no longer be found.) r ospathjoinrprefixgetcwdOSErrorexitabspath) src_prefixrrrget_src_prefix+s r"purelibpypyZScriptsbindarwinz/System/Library/z/usr/local/binFcCsddlm}d|i}|r"dg|d<||}|d} |jddd } | dk sPttt| } |rr|rrtd |||r|rtd |||p| j| _|s|rd | _ |p| j | _ |p| j | _ |p| j | _ | i} xt D]} t| d | | | <qWd|dkr| t| j| jdtrtj| j dddt|| d<|dk rtjtj| dd} tj|| dd| d<| S)z+ Return a distutils install scheme r) Distributionnamez --no-user-cfg script_argsNrT)createzuser={} prefix={}zhome={} prefix={}install_ install_lib)r#platlibincludesitezpython{}headers)distutils.distr)parse_config_filesget_command_objAssertionErrorr distutils_install_commandruserrhomerootfinalize_optionsrgetattrget_option_dictupdatedictr/r rrrr splitdriver ) dist_namer:r;r<isolatedrr) dist_argsdobjischemekey path_no_driverrrdistutils_scheme_sL            rLcCs8t||||||}t|d|d|d|d|ddS)a; Get the "scheme" corresponding to the input parameters. The distutils documentation provides the context for the available schemes: https://docs.python.org/3/install/index.html#alternate-installation :param dist_name: the name of the package to retrieve the scheme for, used in the headers scheme path :param user: indicates to use the "user" scheme :param home: indicates to use the "home" scheme and provides the base directory for the same :param root: root under which other directories are re-based :param isolated: equivalent to --no-user-cfg, i.e. do not consider ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for scheme paths :param prefix: indicates to use the "prefix" scheme and provides the base directory for the same r0r#r3scriptsdata)r0r#r3rMrN)rLr)rCr:r;r<rDrrIrrr get_schemesrO)FNNFN)FNNFN)7__doc__ __future__rros.pathplatformr2rr distutilsdistutils_sysconfigdistutils.command.installrrr9pip._internal.models.schemerZpip._internal.utilsrpip._internal.utils.compatrpip._internal.utils.typingr r pip._internal.utils.virtualenvr typingr r rr distutils.cmdrZDistutilsCommanduser_cache_dirUSER_CACHE_DIRrr"get_path site_packagespython_implementationlowerget_python_libgetusersitepackages user_siteAttributeError USER_SITErrrbin_pybin_userexistsrLrOrrrrsX              ( Acommands/__pycache__/wheel.cpython-37.pyc000064400000011761152352421740014323 0ustar00B Re@sddlmZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZmZerdd lmZddlmZe e!Z"Gddde Z#dS))absolute_importN) WheelCache) cmdoptions)RequirementCommand with_cleanup)SUCCESS) CommandError)get_requirement_tracker) ensure_dirnormalize_path) TempDirectory)MYPY_CHECK_RUNNING)buildshould_build_for_wheel_command)Values)Listc@s(eZdZdZdZddZeddZdS) WheelCommanda Build Wheel archives for your requirements and dependencies. Wheel is a built-package format, and offers the advantage of not recompiling your software during every install. For more details, see the wheel docs: https://wheel.readthedocs.io/en/latest/ Requirements: setuptools>=0.8, and wheel. 'pip wheel' uses the bdist_wheel setuptools extension from the wheel package to build individual wheels. z %prog [options] ... %prog [options] -r ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...cCs||jjddddtjdd|jt|jt|jt|jjddd d d d |jt|jt |jt |jt |jt |jt |jt|jt|jt|jt|jt|jjd dd d dd|jjddddd|jtttj|j}|jd||jd|jdS)Nz-wz --wheel-dir wheel_dirdirzLBuild wheels into , where the default is the current working directory.)destmetavardefaulthelpz--build-option build_optionsoptionsappendz9Extra arguments to be supplied to 'setup.py bdist_wheel'.)rractionrz--global-optionglobal_optionszZExtra global options to be supplied to the setup.py call before the 'bdist_wheel' command.)rrrrz--pre store_trueFzYInclude pre-release and development versions. By default, pip only finds stable versions.)rrrr)cmd_opts add_optionoscurdirr no_binary only_binary prefer_binaryno_build_isolation use_pep517 no_use_pep517 constraintseditable requirementssrcignore_requires_pythonno_deps build_dir progress_barrequire_hashesmake_option_group index_groupparserinsert_option_group)self index_optsr8/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/wheel.py add_options2sVzWheelCommand.add_optionsc Cst|||}|||}|jp*|j }t|j|j}t |j |_ t |j | t }t|j|ddd}|||||} |j||||||j dd} |j| ||||j|jd} ||| j| dd} dd | jD} t| ||jpg|jpgd \}}x|D]|}|jr|jjs t|js,tyt |j|j Wn>t!k r~}zt"#d |j$||%|Wdd}~XYnXqWt&|d krt'd t(S)NwheelT)deletekindglobally_managedF)temp_build_dirr req_trackersessionfinderwheel_download_dir use_user_site)preparerrBr wheel_cacher-r')check_supported_wheelscSsg|]}t|r|qSr8)r).0rr8r8r9 sz$WheelCommand.run..)rFrrz Building wheel for %s failed: %srz"Failed to build one or more wheels))rcheck_install_build_globalget_default_session_build_package_finderno_cleanr/r cache_dirformat_controlr rr enter_contextr r get_requirementsmake_requirement_preparer make_resolverr-r'trace_basic_inforesolver+valuesrrrlinkis_wheelAssertionErrorlocal_file_pathshutilcopyOSErrorloggerwarningnamerlenrr)r6rargsrArB build_deleterFr@ directoryreqsrEresolverrequirement_set reqs_to_buildbuild_successesbuild_failuresreqer8r8r9runmsh            "zWheelCommand.runN)__name__ __module__ __qualname____doc__usager:rrnr8r8r8r9rs ;r)$ __future__rloggingr!r\pip._internal.cacherZpip._internal.clirpip._internal.cli.req_commandrrpip._internal.cli.status_codesrpip._internal.exceptionsrpip._internal.req.req_trackerr pip._internal.utils.miscr r pip._internal.utils.temp_dirr pip._internal.utils.typingr pip._internal.wheel_builderrroptparsertypingr getLoggerror_rr8r8r8r9s$           commands/__pycache__/completion.cpython-37.pyc000064400000006201152352421740015361 0ustar00B Re @sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z e rhddl m Z ddlmZd Zd d d d ZGdddeZdS))absolute_importN)Command)SUCCESS)get_prog)MYPY_CHECK_RUNNING)List)ValueszD # pip {shell} completion start{script}# pip {shell} completion end a _pip_completion() {{ COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \ COMP_CWORD=$COMP_CWORD \ PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) }} complete -o default -F _pip_completion {prog} aM function _pip_completion {{ local words cword read -Ac words read -cn cword reply=( $( COMP_WORDS="$words[*]" \ COMP_CWORD=$(( cword-1 )) \ PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) }} compctl -K _pip_completion {prog} au function __fish_complete_pip set -lx COMP_WORDS (commandline -o) "" set -lx COMP_CWORD ( \ math (contains -i -- (commandline -t) $COMP_WORDS)-1 \ ) set -lx PIP_AUTO_COMPLETE 1 string split \ -- (eval $COMP_WORDS[1]) end complete -fa "(__fish_complete_pip)" -c {prog} )bashzshfishc@s$eZdZdZdZddZddZdS)CompletionCommandz3A helper command to be used for command completion.TcCs\|jjddddddd|jjdd dd dd d|jjd d ddddd|jd|jdS)Nz--bashz-b store_constr shellzEmit completion code for bash)actionconstdesthelpz--zshz-zr zEmit completion code for zshz--fishz-fr zEmit completion code for fishr)cmd_opts add_optionparserinsert_option_group)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/completion.py add_options;s&zCompletionCommand.add_optionscCszt}ddt|D}|j|krZtt|jdjtd}t t j||jdt St j dd|t SdS) z-Prints the completion code of the given shellcSsg|] }d|qS)z--r).0rrrr Vsz)CompletionCommand.run..)prog)scriptrzERROR: You must pass {} z or N)COMPLETION_SCRIPTSkeyssortedrtextwrapdedentgetformatrprintBASE_COMPLETIONrsysstderrwritejoin)roptionsargsZshellsZ shell_optionsrrrrrunRs  zCompletionCommand.runN)__name__ __module__ __qualname____doc__ignore_require_venvrr/rrrrr 6sr ) __future__rr)r#pip._internal.cli.base_commandrpip._internal.cli.status_codesrpip._internal.utils.miscrpip._internal.utils.typingrtypingroptparserr(r r rrrrs          commands/__pycache__/freeze.cpython-37.pyc000064400000005754152352421740014504 0ustar00B Re| @sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZdd lmZd d d dhZerddlmZddlmZGdddeZdS))absolute_importN) WheelCache) cmdoptions)Command)SUCCESS) FormatControl)freeze) stdlib_pkgs)MYPY_CHECK_RUNNINGpip setuptoolsZ distributewheel)Values)Listc@s(eZdZdZdZdZddZddZdS) FreezeCommandzx Output installed packages in requirements format. packages are listed in a case-insensitive sorted order. z %prog [options])zext://sys.stderrzext://sys.stderrc Cs|jjddddgddd|jjdd d dgd d d|jjd dddddd|jjdddddd|jt|jjdddddtd|jjddddd|jd|jdS) Nz-rz --requirement requirementsappendfilez}Use the order in the given requirements file and its comments when generating output. This option can be used multiple times.)destactiondefaultmetavarhelpz-fz --find-links find_linksURLzs            commands/__pycache__/uninstall.cpython-37.pyc000064400000005647152352421740015236 0ustar00B Re @sddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZmZdd lmZdd lmZerdd lmZdd lmZGd ddeeZdS))absolute_import)canonicalize_name)Command)SessionCommandMixin)SUCCESS)InstallationError)parse_requirements)install_req_from_line#install_req_from_parsed_requirement)(protect_pip_from_modification_on_windows)MYPY_CHECK_RUNNING)Values)Listc@s$eZdZdZdZddZddZdS)UninstallCommandaB Uninstall packages. pip is able to uninstall most installed packages. Known exceptions are: - Pure distutils packages installed with ``python setup.py install``, which leave behind no metadata to determine what files were installed. - Script wrappers installed by ``python setup.py develop``. zU %prog [options] ... %prog [options] -r ...c CsD|jjddddgddd|jjdd d d d d |jd|jdS)Nz-rz --requirement requirementsappendfilezjUninstall all the packages listed in the given requirements file. This option can be used multiple times.)destactiondefaultmetavarhelpz-yz--yesyes store_truez2Don't ask for confirmation of uninstall deletions.)rrrr)cmd_opts add_optionparserinsert_option_group)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/uninstall.py add_options%szUninstallCommand.add_optionsc Cs||}i}x.|D]&}t||jd}|jr||t|j<qWxH|jD]>}x8t|||dD]&}t||jd}|jrZ||t|j<qZWqFW|stdj ft t d|kdx2| D]&}|j |j|jdkd} | r| qWtS)N)isolated)optionssessionzRYou must give at least one requirement to {self.name} (see "pip help {self.name}")pip) modifying_pipr) auto_confirmverbose)get_default_sessionr isolated_modenamerrrr rformatlocalsr values uninstallr verbositycommitr) rr#argsr$Zreqs_to_uninstallr+reqfilename parsed_reqZuninstall_pathsetrrr run8s:         zUninstallCommand.runN)__name__ __module__ __qualname____doc__usager!r6rrrr rs rN) __future__rZpip._vendor.packaging.utilsrpip._internal.cli.base_commandrpip._internal.cli.req_commandrpip._internal.cli.status_codesrpip._internal.exceptionsrZpip._internal.reqrpip._internal.req.constructorsr r pip._internal.utils.miscr pip._internal.utils.typingr optparser typingrrrrrr s           commands/__pycache__/install.cpython-37.pyc000064400000042437152352421740014671 0ustar00B Re7p@sddlmZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZmZdd lmZmZdd lmZmZdd lm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddl-m.Z.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:m;Z;e6rddl mZ>m?Z?m@Z@ddlAmBZBddl!mCZCddlDmEZEddl9mFZFeGeHZIdd ZJGd!d"d"eZKd.d$d%ZLd&d'ZMd/d(d)ZNd*d+ZOd,d-ZPdS)0)absolute_importN)path) SUPPRESS_HELP) pkg_resources)canonicalize_name) WheelCache) cmdoptions)make_target_python)RequirementCommand with_cleanup)ERRORSUCCESS) CommandErrorInstallationError)distutils_scheme)check_install_conflicts)install_given_reqs)get_requirement_tracker)today_is_later_than)parse_distutils_args)test_writable_dir) ensure_dirget_installed_versionget_pip_version(protect_pip_from_modification_on_windows write_output) TempDirectory)MYPY_CHECK_RUNNING)virtualenv_no_global)build should_build_for_install_command)Values)IterableListOptional) FormatControl)ConflictDetails)InstallRequirement)BinaryAllowedPredicatecsfdd}|S)Ncs&|jr dSt|j}|}d|kS)NTbinary) use_pep517rnameget_allowed_formats)reqcanonical_nameallowed_formats)format_control/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/install.pycheck_binary_allowed8s   z6get_check_binary_allowed..check_binary_allowedr1)r0r3r1)r0r2get_check_binary_allowed6s r4c@s@eZdZdZdZddZeddZddZd d Z d d Z d S)InstallCommandaI Install packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports installing from "requirements files", which provide an easy way to specify a whole environment to be installed. a% %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] [-e] ... %prog [options] [-e] ... %prog [options] ...cCsz|jt|jt|jt|jt|jt|jjdddddddt|j|jjddd d d |jjd dd t d |jjdddddd|jjdddddd|jt |jt |jjdddd dd |jjdddddgdd|jjddd d d |jjd!d"d#d d$d |jt |jt |jt|jt|jt|jt|jjd%d d&d'd(d)|jjd*d d&d+d,|jjd-d d.d'd/d)|jjd0d d1d'd2d)|jt|jt|jt|jt|jtttj|j}|jd3||jd3|jdS)4Nz-tz--target target_dirdirzInstall packages into . By default this will not replace existing files/folders in . Use --upgrade to replace existing packages in with new versions.)destmetavardefaulthelpz--user use_user_site store_truezInstall to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.))r8actionr;z --no-user store_falsez--root root_pathz=Install everything relative to this alternate root directory.z--prefix prefix_pathzIInstallation prefix where lib, bin and other top-level folders are placedz-Uz --upgradeupgradezUpgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.z--upgrade-strategyupgrade_strategyzonly-if-neededeageraGDetermines how dependency upgrading should be handled [default: %default]. "eager" - dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not satisfy the requirements of the upgraded package(s).)r8r:choicesr;z--force-reinstallforce_reinstallz;Reinstall all packages even if they are already up-to-date.z-Iz--ignore-installedignore_installedzIgnore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!z --compilecompileTz'Compile Python source files to bytecode)r>r8r:r;z --no-compilez.Do not compile Python source files to bytecode)r>r8r;z--no-warn-script-locationwarn_script_locationz0Do not warn when installing scripts outside PATHz--no-warn-conflictswarn_about_conflictsz%Do not warn about broken dependenciesr)cmd_opts add_optionr requirements constraintsno_depspreeditableadd_target_python_optionsr build_dirsrcignore_requires_pythonno_build_isolationr* no_use_pep517install_optionsglobal_options no_binary only_binary prefer_binaryrequire_hashes progress_barmake_option_group index_groupparserinsert_option_group)self index_optsr1r1r2 add_optionsWs  zInstallCommand.add_optionsc+ s~|jr|jdk rtdt|dd}tdkrx|sx|jsxt t j d}|dkrjt t j d}t d|d}|jr|j}tj|d d |jpg}t d tt|j|j|j|j|jd |_d}d}|jr4d |_tj|j|_tj|jrtj|jstd tdd}|j}|||jp>g} ||} t |} |j!|| | |j"d} |j#pr|j$ } t%|j&|j'}|t(}t|j$| dd d}yf|)||| | }t*||j|j+|||| | |jd}|j,|| |||j|j|j"|j-||j.d }|/| |j0||j d}y|1d}Wnt2k rFd}Yn X|j3dk}t4|dt5| j'fdd|j67D}t8||ggd\}}dd|D}|rt9d:d;|x|D]}|j.sd|_<qW|=|}d}|j> o|j?}|r|@|}|jA}|jrd}tB||| |j||j||j|jCd } tD|j||j|j|jd!}!tEF|!}"| jGtHId"d#g}#xZ| D]R}$|$jJ}%y$tK|$jJ|"d$}&|&r|%d%|&7}%WntLk rYnX|#M|%qzW|dk r|jN|d&|jOkd'd(;|#}'|'rtPd)|'WnJtQk rT}(z*|jRd*k})tS|(|)|j}*t jT|*|)d+tUSd}(~(XYnX|jrz|shtV|W|j||jtXS),Nz'Can not combine '--user' and '--target'cSs ttdpttdotjtjkS)N real_prefix base_prefix)hasattrsysrgprefixr1r1r1r2is_venvs  z#InstallCommand.run..is_venvrz __main__.pyz -m pipzgRunning pip install with root privileges is generally not a good idea. Try `%s install --user` instead.zto-satisfy-onlyT) check_targetzUsing %s)rAr6r@ isolated_modez=Target path exists but is not a directory, will not continue.target)kind)optionssession target_pythonrUinstall)deleteroglobally_managed)temp_build_dirrp req_trackerrqfinderr<) preparerrxrp wheel_cacher<rGrUrFrCr*)check_supported_wheelspipF) modifying_pipcsg|]}t|r|qSr1)r ).0r)r3r1r2 ksz&InstallCommand.run..)rz build_optionsrYcSsg|]}|jr|jqSr1)r*r+)r~rr1r1r2r{szPCould not build wheels for {} which use PEP 517 and cannot be installed directlyz, i )roothomerjrIr< pycompile)userrrrjisolatedr+)key) working_set-z 2020-resolver) new_resolver zSuccessfully installed %s)exc_info)Yr<r6rrcheck_install_build_globalosgetuidr@rbasenameriargv executableloggerwarningrBrCcheck_dist_restrictionrXdebugrdecide_user_installrArmrGabspathexistsisdirr enter_contextrYget_default_sessionr _build_package_finderrUno_cleanrSr cache_dirr0rget_requirements'reject_location_related_install_optionsmake_requirement_preparer make_resolverrFr*trace_basic_inforesolveget_requirementKeyError satisfied_byrr4rMvaluesrrformatjoinlegacy_install_reasonget_installation_orderignore_dependenciesrJ_determine_conflictsrIrrHget_lib_location_guessesr WorkingSetsortoperator attrgetterr+r Exceptionappend_warn_about_conflictsfeatures_enabledrEnvironmentError verbositycreate_env_error_messageerrorr AssertionError_handle_target_dirr )+rcrpargsrkcommandrCrXtarget_temp_dirtarget_temp_dir_pathrYrqrrrx build_deleterzrw directoryreqsryresolverrequirement_setpip_reqr} reqs_to_build_build_failurespep517_build_failure_namesr to_install conflictsshould_warn_about_conflictsrI installed lib_locationsritemsresultiteminstalled_versioninstalled_descrshow_tracebackmessager1)r3r2runs<                               zInstallCommand.runc s\t|g}td|jd}|d}|d}|d}tj|rH||tj|rf||krf||tj|r|||x|D]} xt| D]} | |krtj|| tfdd|ddDrqtj|| } tj| r:|st d | qtj | rt d | qtj | r0t | n t| t tj| | | qWqWdS) N)rpurelibplatlibdatac3s|]}|VqdS)N) startswith)r~s)ddirr1r2 sz4InstallCommand._handle_target_dir..zKTarget directory %s already exists. Specify --upgrade to force replacement.zTarget directory %s already exists and is a link. pip will not automatically replace links, please remove if replacement is desired.)rrrrrrlistdirranyrrislinkrshutilrmtreeremovemove) rcr6rrB lib_dir_listscheme purelib_dir platlib_dirdata_dirlib_dirrtarget_item_dirr1)rr2rsH         z!InstallCommand._handle_target_dircCs,yt|Stk r&tddSXdS)NzwError while checking for conflicts. Please file an issue on pip's issue tracker: https://github.com/pypa/pip/issues/new)rrr exception)rcrr1r1r2rs z#InstallCommand._determine_conflictsc Cs|\}\}}|s|sdSg}|s6|d|dn,tddddsb|dd}|d |xH|D]@}||d } x.||D]"} d j|| | d d } || qWqhWxN|D]F}||d } x4||D](\} } }dj|| || | d} || qWqWtd|dS)NzAfter October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts. z|We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default. i)yearmonthdayzPip will install or upgrade your package(s) and its dependencies without taking into account other packages you already have installed. This may cause an uncaught dependency conflict. z#https://forms.gle/cWKMoDs8sUVE29hz9zXIf you would like pip to take your other packages into account, please tell us here: {} rz@{name} {version} requires {requirement}, which is not installed.r)r+version requirementzh{name} {version} requires {requirement}, but you'll have {dep_name} {dep_version} which is incompatible.)r+rrdep_name dep_version )rrrrcriticalr)rcconflict_detailsr package_setmissing conflictingparts form_link project_namer dependencyrrrr-r1r1r2r#sF      z$InstallCommand._warn_about_conflictsN) __name__ __module__ __qualname____doc__usagerer rrrrr1r1r1r2r5Cs  z8 r5FcCs$td|||||d}|d|dgS)Nr)rrrrrjrr)r)rrrrrjrr1r1r2rcs  rcCstddtt||dDS)Ncss|]}t|VqdS)N)r)r~dr1r1r2rssz)site_packages_writable..)rr)allsetr)rrr1r1r2site_packages_writablepsrcCs|dk r|stddS|rF|r*tdtr8tdtddS|dksRt|sZ|rhtddStjs|td dSt||d rtd dSt d dS) aZDetermine whether to do a user install based on the input options. If use_user_site is False, no additional checks are done. If use_user_site is True, it is checked for compatibility with other options. If use_user_site is None, the default behaviour depends on the environment, which is provided by the other arguments. Nz$Non-user install by explicit requestFzVCan not combine '--user' and '--prefix' as they imply different installation locationszZCan not perform a '--user' install. User site-packages are not visible in this virtualenv.z User install by explicit requestTz3Non-user install due to --prefix or --target optionz4Non-user install because user site-packages disabled)rrz0Non-user install because site-packages writeablezMDefaulting to user installation because normal site-packages is not writeable) rrrrrrsiteENABLE_USER_SITErinfo)r<rAr6r@rmr1r1r2rxs0         rcCsdd}g}x8|D]0}|j}t|}|r|d|||qW|rnt|}|rn|d|||svdStdd|dS)zIf any location-changing --install-option arguments were passed for requirements or on the command-line, then show a deprecation warning. cSsdd|DS)NcSsg|]}d|ddqS)z--{}rr)rreplace)r~r+r1r1r2rszSreject_location_related_install_options..format_options..r1) option_namesr1r1r2format_optionssz?reject_location_related_install_options..format_optionsz {!r} from {}z{!r} from command lineNzLocation-changing options found in --install-option: {}. This is unsupported, use pip-level options like --user, --prefix, --root, and --target instead.z; )rXrrrkeysrr)rMrpr offendersrrXlocation_optionsr1r1r2rs( rcCsg}|d|s,|d|t|n |d|dd7<|jtjkrd}d}|st||d|gn |||d d |dS) z{Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. z5Could not install packages due to an EnvironmentErrorz: .rrz"Consider using the `--user` optionzCheck the permissionsz or z. r)rstrerrnoEACCESextendlowerrstrip)rrusing_user_siteruser_option_partpermissions_partr1r1r2rs"      r)FNNFN)NNNF)Q __future__rrloggingrrrrriroptparser pip._vendorrZpip._vendor.packaging.utilsrpip._internal.cacherZpip._internal.clirZpip._internal.cli.cmdoptionsr pip._internal.cli.req_commandr r pip._internal.cli.status_codesr r pip._internal.exceptionsrrpip._internal.locationsrpip._internal.operations.checkrZpip._internal.reqrpip._internal.req.req_trackerrpip._internal.utils.datetimer"pip._internal.utils.distutils_argsrpip._internal.utils.filesystemrpip._internal.utils.miscrrrrrpip._internal.utils.temp_dirrpip._internal.utils.typingrpip._internal.utils.virtualenvrpip._internal.wheel_builderrr r!typingr"r#r$#pip._internal.models.format_controlr%r&Zpip._internal.req.req_installr'r( getLoggerrrr4r5rrrrrr1r1r1r2sn                         %   7*commands/__pycache__/search.cpython-37.pyc000064400000011440152352421740014456 0ustar00B Re|@sVddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddlmZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z m!Z!ddl"m#Z#e#rddl$m%Z%ddl&m'Z'm(Z(m)Z)ddl*m+Z+e+de,e,e'e,dZ-e.e/Z0GdddeeZ1ddZ2dddZ3ddZ4dS))absolute_importN) OrderedDict) pkg_resources)parse) xmlrpc_client)Command)SessionCommandMixin)NO_MATCHES_FOUNDSUCCESS) CommandError)PyPI)PipXmlrpcTransport)get_terminal_size) indent_log)get_distribution write_output)MYPY_CHECK_RUNNING)Values)ListDictOptional) TypedDictTransformedHit)namesummaryversionsc@s0eZdZdZdZdZddZddZdd Zd S) SearchCommandz@Search for PyPI packages whose name or summary contains .z %prog [options] TcCs.|jjddddtjdd|jd|jdS)Nz-iz--indexindexURLz3Base URL of Python Package Index (default %default))destmetavardefaulthelpr)cmd_opts add_optionr pypi_urlparserinsert_option_group)selfr)/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/search.py add_options,szSearchCommand.add_optionscCsT|s td|}|||}t|}d}tjrtk rbYq>Xq>WdS)Nc Ss.g|]&}t|dtt|ddgqS)rr-)lenrHget).0rLr)r)r* wsz!print_results..cSsg|] }|jqSr)) project_name)rPpr)r)r*rQ{srrrrM   z-{name_latest:{name_column_width}} - {summary}Z name_latestz{name} ({latest})zINSTALLED: %s (latest)z INSTALLED: %sz=LATEST: %s (pre-release; install with "pip install --pre")z LATEST: %s)maxr working_setrHrOtextwrapwrapjoinformatlocalsrrAssertionErrorrrE parse_versionpreUnicodeEncodeError) r6Zname_column_widthr,Zinstalled_packagesrLrrZlatestZ target_widthZ summary_lineslinedistr)r)r*r2qsH         r2cCs t|tdS)N)key)r[rc)rr)r)r*rHsrH)NN)5 __future__rloggingr/r] collectionsr pip._vendorrpip._vendor.packaging.versionrrcpip._vendor.six.movesrpip._internal.cli.base_commandrpip._internal.cli.req_commandrpip._internal.cli.status_codesr r pip._internal.exceptionsr pip._internal.models.indexr Zpip._internal.network.xmlrpcr pip._internal.utils.compatrpip._internal.utils.loggingrpip._internal.utils.miscrrpip._internal.utils.typingroptparsertypingrrrZtyping_extensionsrstrr getLoggerr?loggerrr.r2rHr)r)r)r*s:                / -commands/__pycache__/list.cpython-37.pyc000064400000021107152352421740014165 0ustar00B Re0,@s&ddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZdd lmZmZmZmZdd lmZdd lmZddlmZerddlm Z ddl!m"Z"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)e*e+Z,Gddde Z-ddZ.ddZ/dS))absolute_importN)six) cmdoptions)IndexGroupCommand)SUCCESS) CommandError) LinkCollector) PackageFinder)SelectionPreferences)dist_is_editableget_installed_distributionstabulate write_output) get_installer)map_multithread)MYPY_CHECK_RUNNING)Values)ListSetTupleIterator) PipSession) Distributionc@s`eZdZdZdZdZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZdS) ListCommandzt List installed packages, including editables. Packages are listed in a case-insensitive sorted order. Tz %prog [options]cCs|jjdddddd|jjddddd d|jjd d ddd d|jjd ddddd|jjdddddd|jt|jjddddd|jjddddddd|jjddddd |jjd!d"d#d$d |jjd%dd#d&d'd(ttj|j}|jd)||jd)|jdS)*Nz-oz --outdated store_trueFzList outdated packages)actiondefaulthelpz-uz --uptodatezList uptodate packagesz-ez --editablezList editable projects.z-lz--localzSIf in a virtualenv that has global access, do not list globally-installed packages.z--useruserz,Only output packages installed in user-site.)destrrrz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--formatstore list_formatcolumns)r"freezejsonzBSelect the output format among: columns (default), freeze, or json)rrrchoicesrz--not-required not_requiredz>List packages that are not dependencies of installed packages.)rrrz--exclude-editable store_falseinclude_editablez%Exclude editable package from output.z--include-editablez%Include editable package from output.T)rrrrr)cmd_opts add_optionr list_pathmake_option_group index_groupparserinsert_option_group)self index_optsr2/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/list.py add_options.sv zListCommand.add_optionscCs*tj||d}td|jd}tj||dS)zK Create a package finder appropriate to this list command. )optionsF) allow_yankedallow_all_prereleases)link_collectorselection_prefs)rcreater prer )r0r5sessionr8r9r2r2r3_build_package_finder{s z!ListCommand._build_package_findercCs|jr|jrtdt|t|j|j|j|j |j d}|j rL| ||}|jr`| ||}n|jrr|||}|||tS)Nz5Options --outdated and --uptodate cannot be combined.) local_only user_onlyeditables_onlyinclude_editablespaths)outdatedZuptodaterrcheck_list_path_optionr localreditabler(pathr&get_not_required get_outdated get_uptodateoutput_package_listingr)r0r5argspackagesr2r2r3runs$      zListCommand.runcCsdd|||DS)NcSsg|]}|j|jkr|qSr2)latest_versionparsed_version).0distr2r2r3 sz,ListCommand.get_outdated..)iter_packages_latest_infos)r0rMr5r2r2r3rIszListCommand.get_outdatedcCsdd|||DS)NcSsg|]}|j|jkr|qSr2)rOrP)rQrRr2r2r3rSsz,ListCommand.get_uptodate..)rT)r0rMr5r2r2r3rJszListCommand.get_uptodatecsBtx$|D]}dd|Dq Wtfdd|DS)Ncss|] }|jVqdS)N)key)rQ requirementr2r2r3 sz/ListCommand.get_not_required..csh|]}|jkr|qSr2)rU)rQpkg)dep_keysr2r3 sz/ListCommand.get_not_required..)setupdaterequireslist)r0rMr5rRr2)rYr3rHs zListCommand.get_not_requiredc #sV|B}||fdd}x t||D]}|dk r2|Vq2WWdQRXdS)Ncspd}|j}js$dd|D}j|jd}||}|dkrHdS|j}|jjr\d}nd}||_ ||_ |S)NunknowncSsg|]}|jjs|qSr2)version is_prerelease)rQ candidater2r2r3rSszOListCommand.iter_packages_latest_infos..latest_info..) project_namewheelsdist) find_all_candidatesrUr;make_candidate_evaluatorrcsort_best_candidater`linkis_wheelrOlatest_filetype)rRtypZall_candidatesZ evaluatorbest_candidateremote_version)finderr5r2r3 latest_infos    z;ListCommand.iter_packages_latest_infos..latest_info)_build_sessionr=r)r0rMr5r<rprRr2)ror5r3rTs   z&ListCommand.iter_packages_latest_infoscCst|ddd}|jdkr:|r:t||\}}|||nb|jdkrxV|D]4}|jdkrntd|j|j|jqJtd|j|jqJWn|jd krtt ||dS) NcSs |jS)N)rclower)rRr2r2r3z4ListCommand.output_package_listing..)rUr"r#z %s==%s (%s)z%s==%sr$) sortedr!format_for_columnsoutput_package_listing_columnsverboserrcr`locationformat_for_json)r0rMr5dataheaderrRr2r2r3rKs     z"ListCommand.output_package_listingcCsft|dkr|d|t|\}}t|dkrL|ddtdd|x|D] }t|qRWdS)Nrru cSsd|S)N-r2)xr2r2r3rsrtz.)leninsertr joinmapr)r0r|r}Z pkg_stringssizesvalr2r2r3rxs     z*ListCommand.output_package_listing_columnsN)__name__ __module__ __qualname____doc__ignore_require_venvusager4r=rNrIrJrHrTrKrxr2r2r2r3r#sM #rcCs|j}|rddddg}nddg}g}|jdks@tdd|DrJ|d|jdkr^|d xt|D]l}|j|jg}|r||j||j|jdkst|r||j |jdkr|t |||qdW||fS) z_ Convert the package data into something usable by output_package_listing_columns. PackageVersionZLatestTyperucss|]}t|VqdS)N)r )rQrr2r2r3rWsz%format_for_columns..ZLocationZ Installer) rCryanyappendrcr`rOrkr rzr)pkgsr5Zrunning_outdatedr}r|Zprojrowr2r2r3rw s(         rwcCszg}xj|D]b}|jt|jd}|jdkrB|j|d<t||d<|jrbt|j|d<|j |d<| |q Wt |S)N)namer`rurz installerrOrk) rcr text_typer`ryrzrrCrOrkrr$dumps)rMr5r|rRinfor2r2r3r{1s     r{)0 __future__rr$logging pip._vendorrZpip._internal.clirpip._internal.cli.req_commandrpip._internal.cli.status_codesrpip._internal.exceptionsrpip._internal.index.collectorr"pip._internal.index.package_finderr $pip._internal.models.selection_prefsr pip._internal.utils.miscr r r rpip._internal.utils.packagingrZpip._internal.utils.parallelrpip._internal.utils.typingroptparsertypingrrrrpip._internal.network.sessionrZpip._vendor.pkg_resourcesr getLoggerrloggerrrwr{r2r2r2r3s0                i&commands/__pycache__/help.cpython-37.pyc000064400000002576152352421740014153 0ustar00B Re@slddlmZddlmZddlmZddlmZddlm Z e rXddl m Z ddl m Z Gdd d eZd S) )absolute_import)Command)SUCCESS) CommandError)MYPY_CHECK_RUNNING)List)Valuesc@s eZdZdZdZdZddZdS) HelpCommandzShow help for commandsz %prog Tc Csddlm}m}m}y |d}Wntk r4tSX||krt||}d|g}|rf|d|td |||} | j tS)Nr) commands_dictcreate_commandget_similar_commandszunknown command "{}"zmaybe you meant "{}"z - ) pip._internal.commandsr r r IndexErrorrformatappendrjoinparser print_help) selfoptionsargsr r r cmd_nameguessmsgcommandr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/help.pyruns   zHelpCommand.runN)__name__ __module__ __qualname____doc__usageignore_require_venvrrrrrr sr N) __future__rpip._internal.cli.base_commandrpip._internal.cli.status_codesrpip._internal.exceptionsrpip._internal.utils.typingrtypingroptparserr rrrrs       commands/__pycache__/hash.cpython-37.pyc000064400000004154152352421740014140 0ustar00B Re3@sddlmZddlZddlZddlZddlmZddlmZm Z ddl m Z m Z ddl mZmZddlmZerddlmZdd lmZeeZGd d d eZd d ZdS))absolute_importN)Command)ERRORSUCCESS) FAVORITE_HASH STRONG_HASHES) read_chunks write_output)MYPY_CHECK_RUNNING)Values)Listc@s(eZdZdZdZdZddZddZdS) HashCommandz Compute a hash of a local package archive. These can be used with --hash in a requirements file to do repeatable installs. z%prog [options] ...Tc Cs:|jjdddtdtddtd|jd|jdS) Nz-az --algorithm algorithmstorez$The hash algorithm to use: one of {}z, )destchoicesactiondefaulthelpr)cmd_opts add_optionrrformatjoinparserinsert_option_group)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/hash.py add_optionsszHashCommand.add_optionscCsB|s|jtjtS|j}x |D]}td||t||q"WtS)Nz%s: --hash=%s:%s) r print_usagesysstderrrrr _hash_of_filer)roptionsargsrpathrrrrun+s zHashCommand.runN)__name__ __module__ __qualname____doc__usageignore_require_venvrr&rrrrr s  r c CsDt|d,}t|}xt|D]}||q WWdQRX|S)z!Return the hash digest of a file.rbN)openhashlibnewrupdate hexdigest)r%rarchivehashchunkrrrr"8s   r") __future__rr/loggingr pip._internal.cli.base_commandrpip._internal.cli.status_codesrrpip._internal.utils.hashesrrpip._internal.utils.miscrr pip._internal.utils.typingr optparser typingr getLoggerr'loggerr r"rrrrs      $commands/__pycache__/show.cpython-37.pyc000064400000014565152352421740014204 0ustar00B ReT@sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z mZddlmZdd lmZerdd lmZdd lmZmZmZeeZGd d d e ZddZdddZdS))absolute_importN) FeedParser) pkg_resources)canonicalize_name)Command)ERRORSUCCESS) write_output)MYPY_CHECK_RUNNING)Values)ListDictIteratorc@s(eZdZdZdZdZddZddZdS) ShowCommandzx Show information about one or more installed packages. The output is in RFC-compliant mail header format. z$ %prog [options] ...TcCs,|jjddddddd|jd|jdS) Nz-fz--filesfiles store_trueFz7Show the full list of installed files for each package.)destactiondefaulthelpr)cmd_opts add_optionparserinsert_option_group)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/show.py add_options!szShowCommand.add_optionscCs8|stdtS|}t|}t||j|jds4tStS)Nz.ERROR: Please provide a package name or names.) list_filesverbose)loggerwarningrsearch_packages_info print_resultsrrr)roptionsargsqueryresultsrrrrun,s zShowCommand.runN)__name__ __module__ __qualname____doc__usageignore_require_venvrr(rrrrrs  rc#sfixtjD]}|t|j<q Wdd|D}tfddt||D}|rbtdd|dd}xfdd|DD]܉jj j d d D|jd }d }d }t tj r&d rd }dd|D} fdd| D} fdd| D}drvd}nPdr`d} fdd| D} fdd| D}drvd}drd} | |d<drx,dD]} | r| |d<PqWt} | || } xdD]}| |||<qWg}x4|D](} | dr|| tdd qW||d<|rXt||d<|VqWd S)z Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. cSsg|] }t|qSr)r).0namerrr Fsz(search_packages_info..csg|]\}}|kr|qSrr)r/r0pkg) installedrrr1HszPackage(s) not found: %sz, cst|fddtjDS)Ncs(g|] }dd|Dkr|jqS)cSsg|]}t|jqSr)rr0)r/requiredrrrr1SszSsearch_packages_info..get_requiring_packages...)requires project_name)r/r2)canonical_namerrr1QszHsearch_packages_info..get_requiring_packages..)rr working_set) package_namer)r7rget_requiring_packagesMsz4search_packages_info..get_requiring_packagescsg|]}|kr|qSrr)r/r2)r3rrr1WscSsg|] }|jqSr)r6)r/deprrrr1\s)r0versionlocationr5 required_byNRECORDcSsg|]}|ddqS),r)split)r/linerrrr1escsg|]}tjj|qSr)ospathjoinr=)r/p)distrrr1fscsg|]}tj|jqSr)rDrErelpathr=)r/rG)rHrrr1gsMETADATAzinstalled-files.txtcsg|]}tjj|qSr)rDrErFegg_info)r/rG)rHrrr1oscsg|]}tj|jqSr)rDrErIr=)r/rG)rHrrr1pszPKG-INFOzentry_points.txt entry_points INSTALLER installer)zmetadata-versionsummaryz home-pageauthorz author-emaillicensez Classifier: classifiersr)rr8rr6sortedzipr r!rFr<r=r5 isinstanceDistInfoDistribution has_metadataget_metadata_lines get_metadatastriprfeedcloseget splitlines startswithappendlen)r&rGZ query_namesmissingr:package file_listmetadatalinespathsrLrC feed_parser pkg_info_dictkeyrRr)rHr3rr":sh                   r"Fc Csd}xt|D]\}}d}|dkr.tdtd|ddtd|d dtd |d dtd |d dtd|ddtd|ddtd|ddtd|ddtdd|dgtdd|dg|rptd|ddtd|ddtdx |d gD]}td!|q.Wtd"x$|d#gD]}td!|qXW|rtd$x$|d%gD]}td!|qWd%|krtd&qW|S)'zC Print the information from installed distributions found. FTrz---zName: %sr0r?z Version: %sr<z Summary: %srOz Home-page: %sz home-pagez Author: %srPzAuthor-email: %sz author-emailz License: %srQz Location: %sr=z Requires: %sz, r5zRequired-by: %sr>zMetadata-Version: %szmetadata-versionz Installer: %srNz Classifiers:rRz %sz Entry-points:rLzFiles:rz!Cannot locate installed-files.txt) enumerater r]rFrZ) distributionsrrZresults_printedirH classifierentryrCrrrr#s@ r#)FF) __future__rloggingrD email.parserr pip._vendorrZpip._vendor.packaging.utilsrpip._internal.cli.base_commandrpip._internal.cli.status_codesrrpip._internal.utils.miscr pip._internal.utils.typingr optparser typingr r r getLoggerr)r rr"r#rrrrs         $Zcommands/__pycache__/__init__.cpython-37.pyc000064400000005627152352421740014762 0ustar00B Re@sHdZddlmZddlZddlmZmZddlmZerPddl m Z ddl m Z edd Z ed e d d d fde dddfde dddfde dddfde dddfde dd d!fd"e d#d$d%fd&e d'd(d)fd*e d+d,d-fd.e d/d0d1fd2e d3d4d5fd6e d7d8d9fd:e d;de d?d@dAfdBe dCdDdEfgZdFdGZdHdIZdS)Jz% Package containing all pip commands )absolute_importN) OrderedDict namedtuple)MYPY_CHECK_RUNNING)Any)Command CommandInfoz module_path, class_name, summaryinstallzpip._internal.commands.installInstallCommandzInstall packages.downloadzpip._internal.commands.downloadDownloadCommandzDownload packages. uninstallz pip._internal.commands.uninstallUninstallCommandzUninstall packages.freezezpip._internal.commands.freeze FreezeCommandz1Output installed packages in requirements format.listzpip._internal.commands.list ListCommandzList installed packages.showzpip._internal.commands.show ShowCommandz*Show information about installed packages.checkzpip._internal.commands.check CheckCommandz7Verify installed packages have compatible dependencies.configz$pip._internal.commands.configurationConfigurationCommandz&Manage local and global configuration.searchzpip._internal.commands.search SearchCommandzSearch PyPI for packages.cachezpip._internal.commands.cache CacheCommandz%Inspect and manage pip's wheel cache.wheelzpip._internal.commands.wheel WheelCommandz$Build wheels from your requirements.hashzpip._internal.commands.hash HashCommandz#Compute hashes of package archives. completionz!pip._internal.commands.completionCompletionCommandz-A helper command used for command completion.debugzpip._internal.commands.debug DebugCommandz&Show information useful for debugging.helpzpip._internal.commands.help HelpCommandzShow help for commands.cKs:t|\}}}t|}t||}|f||d|}|S)zF Create an instance of the Command class with the given name. )namesummary) commands_dict importlib import_modulegetattr)r'kwargs module_path class_namer(module command_classcommandr3/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/__init__.pycreate_commandbs   r5cCs6ddlm}|}||t}|r.|dSdSdS)zCommand name auto-correct.r)get_close_matchesFN)difflibr6lowerr)keys)r'r6close_commandsr3r3r4get_similar_commandsos  r;)__doc__ __future__rr* collectionsrrpip._internal.utils.typingrtypingrpip._internal.cli.base_commandrrr)r5r;r3r3r3r4sp       commands/__pycache__/debug.cpython-37.pyc000064400000014402152352421740014300 0ustar00B Re@sNddlmZddlZddlZddlZddlZddlZddlmZddl m Z ddlm Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZerdd lmZddlmZmZm Z ddl!m"Z"ddl#m$Z$e%e&Z'ddZ(ddZ)ddZ*ddZ+ddZ,ddZ-ddZ.dd Z/d!d"Z0Gd#d$d$eZ1dS)%)absolute_importN) pkg_resources)where)__file__) cmdoptions)Command)make_target_python)SUCCESS) indent_log)get_pip_version)MYPY_CHECK_RUNNING) ModuleType)ListOptionalDict)Values) ConfigurationcCstd||dS)Nz%s: %s)loggerinfo)namevaluer/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/debug.py show_valuesrc CsFtdttdr"tj}|j}nd}ttd|WdQRXdS)Nzsys.implementation:implementationr)rrhasattrsysrrr r)rimplementation_namerrrshow_sys_implementation#s  rc CsPtjtjtdd}t|}dd|D}WdQRXtdd|DS)N_vendorz vendor.txtcSs(g|] }d|kr|dddqS)z== r)stripsplit).0linerrr ;sz)create_vendor_txt_map..css|]}|ddVqdS)z==r"N)r$)r%r&rrr ?sz(create_vendor_txt_map..)ospathjoindirname pip_locationopen readlinesdict)Zvendor_txt_pathflinesrrrcreate_vendor_txt_map0s  r3cCs:|}|dkrd}td|ttddttj|S)N setuptoolsrzpip._vendor.{}r)level)lower __import__formatglobalslocalsgetattrpipr ) module_namerrrget_module_from_module_nameBsr>cCsPt|}t|dd}|sLttj|jg}|tj |}t|dd}|S)N __version__version) r>r;r WorkingSetr)r*r,rfind Requirementparse)r=moduler@Zpkg_setpackagerrrget_vendor_version_from_moduleSs  rGcCsVxP|D]D\}}d}t|}|s,d}|}n||kr>d|}td|||q WdS)z{Log the actual version and print extra info if there is a conflict or if the actual version could not be imported. rzM (Unable to locate actual module version, using vendor.txt specified version)z5 (CONFLICT: vendor.txt suggests version should be {})z%s==%s%sN)itemsrGr8rr)vendor_txt_versionsr=Zexpected_versionZ extra_messageZactual_versionrrrshow_actual_vendor_versionsgsrJc Cs.tdt}tt|WdQRXdS)Nzvendored library versions:)rrr3r rJ)rIrrrshow_vendor_versionsys rKc Csd}t|}|}|}d}|r.d|}dt||}t||jdkrpt||krpd}|d|}nd}t<x|D]}tt |qW|rdj|d }t|WdQRXdS) N rz (target: {})zCompatible tags: {}{}r"TFz?... [First {tag_limit} tags shown. Pass --verbose to show all.]) tag_limit) rget_tags format_givenr8lenrrverboser str) optionsrM target_pythontagsZformatted_targetsuffixmsgZ tags_limitedtagrrr show_tagss(   rYcsxt}x(|D]\}}||ddqW|s8dSdddgfdd|D}|s\d Sd |krn|d d |S) N.rz Not specifiedinstallwheeldownloadcsg|]}|kr|qSrr)r%r5)levels_that_override_globalrrr'sz"ca_bundle_info..globalz, )setrHaddr$remover+)configlevelskey_Zglobal_overriding_levelr)r^rca_bundle_infos  rgc@s(eZdZdZdZdZddZddZdS) DebugCommandz$ Display debug information. z %prog TcCs,t|j|jd|j|jjdS)Nr)radd_target_python_optionscmd_optsparserinsert_option_grouprcload)selfrrr add_optionss zDebugCommand.add_optionscCstdtdttdtjtdtjtdttdttdt tdtj t td t |jjtd tjd td tjd td ttd tjjtt|tS)NzThis command is only meant for debugging. Do not use this with automation for parsing and getting these details, since the output and options of this command may change without notice.z pip versionz sys.versionzsys.executablezsys.getdefaultencodingzsys.getfilesystemencodingzlocale.getpreferredencodingz sys.platformz'cert' config valueREQUESTS_CA_BUNDLECURL_CA_BUNDLEzpip._vendor.certifi.where()zpip._vendor.DEBUNDLED)rwarningrr rr@ executablegetdefaultencodinggetfilesystemencodinglocalegetpreferredencodingplatformrrgrkrcr)environgetrr<r DEBUNDLEDrKrYr )rnrSargsrrrruns&      zDebugCommand.runN)__name__ __module__ __qualname____doc__usageignore_require_venvror}rrrrrhs rh)2 __future__rrvloggingr)r pip._vendorr<rpip._vendor.certifirrr-Zpip._internal.clirpip._internal.cli.base_commandrZpip._internal.cli.cmdoptionsrpip._internal.cli.status_codesr pip._internal.utils.loggingr pip._internal.utils.miscr pip._internal.utils.typingr typesr typingrrroptparserpip._internal.configurationr getLoggerr~rrrr3r>rGrJrKrYrgrhrrrrs>                 "commands/__pycache__/download.cpython-37.pyc000064400000007766152352421740015040 0ustar00B Re6@sddlmZddlZddlZddlmZddlmZddlm Z m Z ddl m Z ddl mZddlmZmZmZdd lmZdd lmZerdd lmZdd lmZeeZGd dde ZdS))absolute_importN) cmdoptions)make_target_python)RequirementCommand with_cleanup)SUCCESS)get_requirement_tracker) ensure_dirnormalize_path write_output) TempDirectory)MYPY_CHECK_RUNNING)Values)Listc@s(eZdZdZdZddZeddZdS)DownloadCommandaL Download packages from: - PyPI (and other indexes) using requirement specifiers. - VCS project urls. - Local project directories. - Local or remote source archives. pip also supports downloading from "requirements files", which provide an easy way to specify a whole environment to be downloaded. a %prog [options] [package-index-options] ... %prog [options] -r [package-index-options] ... %prog [options] ... %prog [options] ... %prog [options] ...c CsL|jt|jt|jt|jt|jt|jt|jt |jt |jt |jt |jt |jt|jt|jt|jt|jjddddddtjddt|jttj|j}|jd ||jd |jdS) Nz-dz--destz--destination-dirz--destination-directory download_dirdirzDownload packages into .)destmetavardefaulthelpr)cmd_opts add_optionr constraints requirements build_dirno_depsglobal_options no_binary only_binary prefer_binarysrcprerequire_hashes progress_barno_build_isolation use_pep517 no_use_pep517oscurdiradd_target_python_optionsmake_option_group index_groupparserinsert_option_group)self index_optsr1/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/download.py add_options*s6 zDownloadCommand.add_optionsc Csd|_g|_t|t|j|_t|j||}t|}|j |||d}|j pX|j }| t }t|j |ddd}|||||} |j||||||jdd} |j| |||jd} ||| j| dd} d d d | jD} | rtd | tS) NT)optionssession target_pythondownload)deletekindglobally_managedF)temp_build_dirr4 req_trackerr5finderr use_user_site)preparerr=r4py_version_info)check_supported_wheels cSsg|]}|jr|jqSr1)successfully_downloadedname).0reqr1r1r2 sz'DownloadCommand.run..zSuccessfully downloaded %s)ignore_installed editablesrcheck_dist_restrictionr rr get_default_sessionr_build_package_finderno_cleanr enter_contextrr get_requirementsmake_requirement_preparer make_resolverpython_versiontrace_basic_inforesolvejoinrvaluesr r)r/r4argsr5r6r= build_deleter< directoryreqsr?resolverrequirement_set downloadedr1r1r2runNsP          zDownloadCommand.runN)__name__ __module__ __qualname____doc__usager3rr^r1r1r1r2rs $r) __future__rloggingr(Zpip._internal.clirZpip._internal.cli.cmdoptionsrpip._internal.cli.req_commandrrpip._internal.cli.status_codesrpip._internal.req.req_trackerrpip._internal.utils.miscr r r pip._internal.utils.temp_dirr pip._internal.utils.typingr optparsertypingr getLoggerr_loggerrr1r1r1r2s          commands/__pycache__/check.cpython-37.pyc000064400000003133152352421740014266 0ustar00B Re@sddlZddlmZddlmZmZddlmZmZddl m Z ddl m Z e eZe rvddlmZmZddlmZGd d d eZdS) N)Command)ERRORSUCCESS)check_package_set!create_package_set_from_installed) write_output)MYPY_CHECK_RUNNING)ListAny)Valuesc@seZdZdZdZddZdS) CheckCommandz7Verify installed packages have compatible dependencies.z %prog [options]c Cst\}}t|\}}x:|D]2}||j}x"||D]} td||| dq4WqWx@|D]8}||j}x(||D]\} } } td||| | | qpWqXW|s|s|rtStdtSdS)Nz*%s %s requires %s, which is not installed.rz-%s %s has requirement %s, but you have %s %s.zNo broken requirements found.)rrversionrrr) selfoptionsargs package_setZ parsing_probsmissing conflicting project_namer dependencydep_name dep_versionreqr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/check.pyruns$       zCheckCommand.runN)__name__ __module__ __qualname____doc__usagerrrrrr sr )loggingpip._internal.cli.base_commandrpip._internal.cli.status_codesrrpip._internal.operations.checkrrpip._internal.utils.miscrpip._internal.utils.typingr getLoggerrloggertypingr r optparser r rrrrs     commands/__pycache__/configuration.cpython-37.pyc000064400000017617152352421740016074 0ustar00B Re$@sddlZddlZddlZddlmZddlmZmZddlm Z m Z m Z ddl m Z ddlmZddlmZmZddlmZerdd lmZmZmZdd lmZdd lmZeeZGd d d eZdS)N)Command)ERRORSUCCESS) Configurationget_configuration_fileskinds)PipError) indent_log)get_prog write_output)MYPY_CHECK_RUNNING)ListAnyOptional)Values)Kindc@seZdZdZdZdZddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZddZddZddZd S)!ConfigurationCommandah Manage local and global configuration. Subcommands: - list: List the active configuration (or from the file specified) - edit: Edit the configuration file in an editor - get: Get the value associated with name - set: Set the name=value - unset: Unset the value associated with name - debug: List the configuration files and values defined under them If none of --user, --global and --site are passed, a virtual environment configuration file is used if one is active and the file exists. Otherwise, all modifications happen on the to the user file by default. Ta %prog [] list %prog [] [--editor ] edit %prog [] get name %prog [] set name value %prog [] unset name %prog [] debug cCsl|jjdddddd|jjdddd d d|jjd d dd d d|jjdddd dd|jd|jdS)Nz--editoreditorstorez\Editor to use to edit the file. Uses VISUAL or EDITOR environment variables if not provided.)destactiondefaulthelpz--global global_file store_trueFz+Use the system-wide configuration file onlyz--user user_filez$Use the user configuration file onlyz--site site_filez3Use the current environment configuration file onlyr)cmd_opts add_optionparserinsert_option_group)selfr"/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/commands/configuration.py add_options8s2z ConfigurationCommand.add_optionsc Cs|j|j|j|j|j|jd}|r.|d|krHtddt |t S|d}y|j ||dkd}Wn2t k r}zt|j dt Sd}~XYnXt|j|d|_|jy||||ddWn4t k r}zt|j dt Sd}~XYnXtS) N)listeditgetsetunsetdebugrzNeed an action (%s) to perform.z, )r'r(r)r&) need_value)isolated load_only) list_valuesopen_in_editorget_nameset_name_value unset_namelist_config_valuesloggererrorjoinsortedr_determine_filerargsr isolated_mode configurationloadr)r!optionsr:handlersrr-er"r"r#run_s6  zConfigurationCommand.runcCsddtj|jftj|jftj|jffD}|s`|s8dStddttjDrXtjStjSnt |dkrt|dSt ddS)NcSsg|]\}}|r|qSr"r").0keyvaluer"r"r# sz8ConfigurationCommand._determine_file..css|]}tj|VqdS)N)ospathexists)rBsite_config_filer"r"r# sz7ConfigurationCommand._determine_file..r.rzLNeed exactly one file to operate upon (--user, --site, --global) to perform.) rUSERrGLOBALrSITEranyrlenr)r!r>r+Z file_optionsr"r"r#r9s    z$ConfigurationCommand._determine_filecCs<|j|dddx&t|jD]\}}td||q WdS)Nr%r)nz%s=%r) _get_n_argsr8r<itemsr )r!r>r:rCrDr"r"r#r/sz ConfigurationCommand.list_valuescCs*|j|ddd}|j|}td|dS)Nz get [name]r.)rPz%s)rQr< get_valuer )r!r>r:rCrDr"r"r#r1s zConfigurationCommand.get_namecCs.|j|ddd\}}|j|||dS)Nzset [name] [value])rP)rQr< set_value_save_configuration)r!r>r:rCrDr"r"r#r2sz#ConfigurationCommand.set_name_valuecCs(|j|ddd}|j||dS)Nz unset [name]r.)rP)rQr< unset_valuerV)r!r>r:rCr"r"r#r3s zConfigurationCommand.unset_namec Cs|j|ddd|xjt|jD]X\}}td|xD|D]<}t,tj |}td|||rr| |WdQRXq@Wq(WdS)z9List config key-value pairs across different config filesr*r)rPz%s:z%s, exists: %rN) rQprint_env_var_valuesr8r<iter_config_filesr r rFrGrHprint_config_file_values)r!r>r:variantfilesfnameZ file_existsr"r"r#r4s   z'ConfigurationCommand.list_config_valuesc Cs@x:|j|D]&\}}ttd||WdQRXqWdS)z.Get key-value pairs from the file of a variantz%s: %sN)r<get_values_in_configrRr r )r!r[namerDr"r"r#rZsz-ConfigurationCommand.print_config_file_valuesc CsVtddt<x4t|jD]"\}}d|}td||q"WWdQRXdS)z5Get key-values pairs present as environment variablesz%s:env_varzPIP_{}z%s=%rN)r r r8r<get_environ_varsformatupper)r!rCrDr`r"r"r#rXs  z)ConfigurationCommand.print_env_var_valuesc Csp||}|j}|dkr$tdyt||gWn4tjk rj}ztd|jWdd}~XYnXdS)Nz%Could not determine appropriate file.z*Editor Subprocess exited with exit code {}) _determine_editorr<get_file_to_editr subprocess check_callCalledProcessErrorrb returncode)r!r>r:rr]r@r"r"r#r0s  z#ConfigurationCommand.open_in_editorcCs<t||kr$d|t|}t||dkr4|dS|SdS)zJHelper to make sure the command got the right number of arguments zJGot unexpected number of arguments, expected {}. (example: "{} config {}")r.rN)rOrbr r)r!r:ZexamplerPmsgr"r"r#rQs  z ConfigurationCommand._get_n_argscCs:y|jWn&tk r4tdtdYnXdS)Nz:Unable to save configuration. Please report this as a bug.zInternal Error.)r<save Exceptionr5 exceptionr)r!r"r"r#rVs z(ConfigurationCommand._save_configurationcCsD|jdk r|jSdtjkr$tjdSdtjkr8tjdStddS)NZVISUALZEDITORz"Could not determine editor to use.)rrFenvironr)r!r>r"r"r#rds     z&ConfigurationCommand._determine_editorN)__name__ __module__ __qualname____doc__ignore_require_venvusager$rAr9r/r1r2r3r4rZrXr0rQrVrdr"r"r"r#rs" '.  r) loggingrFrfpip._internal.cli.base_commandrpip._internal.cli.status_codesrrpip._internal.configurationrrrpip._internal.exceptionsrpip._internal.utils.loggingr pip._internal.utils.miscr r pip._internal.utils.typingr typingr rroptparserr getLoggerror5rr"r"r"r#s       commands/__pycache__/cache.cpython-37.pyc000064400000010600152352421740014251 0ustar00B Re,@sddlmZddlZddlZddlZddlmmmZddl m Z ddl m Z m Z ddlmZmZddlmZerddlmZddlmZmZeeZGd d d e ZdS) )absolute_importN)Command)ERRORSUCCESS) CommandErrorPipError)MYPY_CHECK_RUNNING)Values)AnyListc@sXeZdZdZdZdZddZddZdd Zd d Z d d Z ddZ ddZ ddZ dS) CacheCommandaw Inspect and manage pip's wheel cache. Subcommands: - dir: Show the cache directory. - info: Show information about the cache. - list: List filenames of packages stored in the cache. - remove: Remove one or more package from the cache. - purge: Remove all items from the cache. ```` can be a glob expression or a package name. Tz| %prog dir %prog info %prog list [] %prog remove %prog purge c Cs|j|j|j|j|jd}|js.tdtS|r>|d|krXtdd t |tS|d}y||||ddWn2t k r}zt|j dtSd}~XYnXt S)N)dirinfolistremovepurgezs     commands/cache.py000064400000013054152352421740007772 0ustar00from __future__ import absolute_import import logging import os import textwrap import pip._internal.utils.filesystem as filesystem from pip._internal.cli.base_command import Command from pip._internal.cli.status_codes import ERROR, SUCCESS from pip._internal.exceptions import CommandError, PipError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from optparse import Values from typing import Any, List logger = logging.getLogger(__name__) class CacheCommand(Command): """ Inspect and manage pip's wheel cache. Subcommands: - dir: Show the cache directory. - info: Show information about the cache. - list: List filenames of packages stored in the cache. - remove: Remove one or more package from the cache. - purge: Remove all items from the cache. ```` can be a glob expression or a package name. """ ignore_require_venv = True usage = """ %prog dir %prog info %prog list [] %prog remove %prog purge """ def run(self, options, args): # type: (Values, List[Any]) -> int handlers = { "dir": self.get_cache_dir, "info": self.get_cache_info, "list": self.list_cache_items, "remove": self.remove_cache_items, "purge": self.purge_cache, } if not options.cache_dir: logger.error("pip cache commands can not " "function since cache is disabled.") return ERROR # Determine action if not args or args[0] not in handlers: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handlers)), ) return ERROR action = args[0] # Error handling happens here, not in the action-handlers. try: handlers[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR return SUCCESS def get_cache_dir(self, options, args): # type: (Values, List[Any]) -> None if args: raise CommandError('Too many arguments') logger.info(options.cache_dir) def get_cache_info(self, options, args): # type: (Values, List[Any]) -> None if args: raise CommandError('Too many arguments') num_packages = len(self._find_wheels(options, '*')) cache_location = self._wheels_cache_dir(options) cache_size = filesystem.format_directory_size(cache_location) message = textwrap.dedent(""" Location: {location} Size: {size} Number of wheels: {package_count} """).format( location=cache_location, package_count=num_packages, size=cache_size, ).strip() logger.info(message) def list_cache_items(self, options, args): # type: (Values, List[Any]) -> None if len(args) > 1: raise CommandError('Too many arguments') if args: pattern = args[0] else: pattern = '*' files = self._find_wheels(options, pattern) if not files: logger.info('Nothing cached.') return results = [] for filename in files: wheel = os.path.basename(filename) size = filesystem.format_file_size(filename) results.append(' - {} ({})'.format(wheel, size)) logger.info('Cache contents:\n') logger.info('\n'.join(sorted(results))) def remove_cache_items(self, options, args): # type: (Values, List[Any]) -> None if len(args) > 1: raise CommandError('Too many arguments') if not args: raise CommandError('Please provide a pattern') files = self._find_wheels(options, args[0]) if not files: raise CommandError('No matching packages') for filename in files: os.unlink(filename) logger.debug('Removed %s', filename) logger.info('Files removed: %s', len(files)) def purge_cache(self, options, args): # type: (Values, List[Any]) -> None if args: raise CommandError('Too many arguments') return self.remove_cache_items(options, ['*']) def _wheels_cache_dir(self, options): # type: (Values) -> str return os.path.join(options.cache_dir, 'wheels') def _find_wheels(self, options, pattern): # type: (Values, str) -> List[str] wheel_dir = self._wheels_cache_dir(options) # The wheel filename format, as specified in PEP 427, is: # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl # # Additionally, non-alphanumeric values in the distribution are # normalized to underscores (_), meaning hyphens can never occur # before `-{version}`. # # Given that information: # - If the pattern we're given contains a hyphen (-), the user is # providing at least the version. Thus, we can just append `*.whl` # to match the rest of it. # - If the pattern we're given doesn't contain a hyphen (-), the # user is only providing the name. Thus, we append `-*.whl` to # match the hyphen before the version, followed by anything else. # # PEP 427: https://www.python.org/dev/peps/pep-0427/ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl") return filesystem.find_files(wheel_dir, pattern) req/__pycache__/req_file.cpython-37.pyc000064400000031600152352421750013766 0ustar00B ReK@sVdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZmZddlmZddlmZdd lmZdd lmZdd lmZerdd lmZdd lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(ee$e)e#fZ*ee#ge$e+effZ,dgZ-e.dej/Z0e.dZ1e.dZ2e j3e j4e j5e j6e j7e j8e j9e j:e j;e je j?e j@gZAe jBe jCe jDgZEddeEDZFGdddeGZHGdddeGZId7ddZJddZKd8ddZLd9d d!ZMd:d"d#ZNGd$d%d%eGZOd&d'ZPd(d)ZQGd*d+d+eRZSd,d-ZTd.d/ZUd0d1ZVd2d3ZWd;d4d5ZXe.d6ej/ZYdS)\$\{(?P[A-Z0-9_]+)\})cCsg|]}t|jqS)strdest).0orr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/req_file.py Lsrc@seZdZdddZdS)ParsedRequirementNcCs(||_||_||_||_||_||_dS)N) requirement is_editable comes_fromoptions constraint line_source)selfr!r"r#r%r$r&rrr__init__Ps zParsedRequirement.__init__)NN)__name__ __module__ __qualname__r(rrrrr Osr c@seZdZddZdS) ParsedLinecCs`||_||_||_||_||_|r6d|_d|_||_n&|jrVd|_d|_|jd|_nd|_dS)NTFr) filenamelinenor#optsr%is_requirementr"r! editables)r'r-r.r#argsr/r%rrrr(cs zParsedLine.__init__N)r)r*r+r(rrrrr,bsr,Fc csLt|}t|||}x2|||D]"}t||||d} | dk r"| Vq"WdS)aParse a requirements file and yield ParsedRequirement instances. :param filename: Path or url of requirements file. :param session: PipSession instance. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param constraint: If true, parsing a constraint file rather than requirements file. )r$findersessionN)get_line_parserRequirementsFileParserr handle_line) r-r4r3r#r$r% line_parserparser parsed_line parsed_reqrrrrs cCs,t|dd}t|}t|}t|}|S)zxSplit, filter, and join lines, and return a line iterator :param content: the content of the requirements file )start) enumerate splitlines join_linesignore_commentsexpand_env_variables)content lines_enumrrr preprocesss rEcCsd|jrdnd|j|j}|js&t|jrBt|j|j||jdS|rTt ||j i}x4t D],}||j j kr^|j j |r^|j j |||<q^Wd|j|j}t|j|j||j||dSdS)Nz{} {} (line {})z-cz-r)r!r"r#r%z line {} of {})r!r"r#r%r$r&)formatr%r-r.r0AssertionErrorr"r r!rcheck_install_build_globalr/SUPPORTED_OPTIONS_REQ_DEST__dict__)liner$line_comes_from req_optionsrr&rrrhandle_requirement_lines.   rNcs(r4|jr|j_|jr4jfdd|jD|r$|j}|j}|jrT|jg}|jdkrbg}|jrt||j|jr|jd}tj tj |} tj | |} tj | r| }||t||d} | |_|jr||jr||r$x.|jpgD] } d||} |j| | dqWdS)Nc3s|]}|jkr|VqdS)N)features_enabled)rf)r$rr sz%handle_option_line..Tr) find_links index_urlsz line {} of {})source)require_hashesrOextendrRrS index_urlno_indexextra_index_urlsospathdirnameabspathjoinexistsappendr search_scopepreset_allow_all_prereleases prefer_binaryset_prefer_binary trusted_hostsrFadd_trusted_host)r/r-r.r3r$r4rRrSvaluereq_dirrelative_to_reqs_filerahostrTr)r$rhandle_option_linesD       rlcCs4|jrt||}|St|j|j|j|||dSdS)aHandle a single parsed requirements line; This can result in creating/yielding requirements, or updating the finder. :param line: The parsed line to be processed. :param options: CLI options. :param finder: The finder - updated by non-requirement lines. :param session: The session - updated by non-requirement lines. Returns a ParsedRequirement object if the line is a requirement line, otherwise returns None. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. N)r0rNrlr/r-r.)rKr$r3r4r;rrrr7s r7c@s,eZdZddZddZddZddZd S) r6cCs||_||_||_dS)N)_session _line_parser _comes_from)r'r4r8r#rrrr(CszRequirementsFileParser.__init__ccs x|||D] }|VqWdS)z3Parse a given file, yielding parsed lines. N)_parse_and_recurse)r'r-r%rKrrrrNszRequirementsFileParser.parseccsx|||D]}|js|jjs(|jjr|jjrB|jjd}d}n|jjd}d}t|rjt||}n t|st j t j ||}x"| ||D] }|VqWq|VqWdS)NrFT) _parse_filer0r/ requirements constraints SCHEME_REsearch urllib_parseurljoinrZr[r^r\rp)r'r-r%rKreq_pathnested_constraint inner_linerrrrpUs"      z)RequirementsFileParser._parse_and_recursec cst||j|jd\}}t|}xr|D]j\}}y||\}} Wn8tk rv} zd|| j} t| Wdd} ~ XYnXt |||j|| |Vq$WdS)N)r#zInvalid requirement: {} {}) get_file_contentrmrorErnOptionParsingErrorrFmsgrr,) r'r-r%_rCrD line_numberrKargs_strr/er}rrrrqvs z"RequirementsFileParser._parse_fileN)r)r*r+r(rrprqrrrrr6Bs !r6csfdd}|S)Ncs^t}|}d|_r j|_t|\}}tjdkr@|d}|t ||\}}||fS)N)utf8) build_parserget_default_valuesrWformat_controlbreak_args_optionssys version_infoencode parse_argsshlexsplit)rKr9defaultsr options_strr/r~)r3rr parse_lines   z#get_line_parser..parse_liner)r3rr)r3rr5s r5cCsh|d}g}|dd}x8|D]0}|ds8|dr.parser_exit)optparse OptionParserSUPPORTED_OPTIONSSUPPORTED_OPTIONS_REQ add_optionexit)r9option_factoriesoption_factoryoptionrrrrrs  rccsd}g}x|D]\}}|dr*t|rxt|r`_. Valid characters in variable names follow the `POSIX standard `_ and are limited to uppercase letter, digits and the `_` (underscore). N) ENV_VAR_REfindallrZgetenvreplace)rDrrKenv_varvar_namerhrrrrBs rBc Cs$t|}|dkr.||}t||j|jfS|dkr|rT|drTtd|||ddd}| dd}t |}|r| dd|d dd}t |}|drd|d}|}y&t|d }t|}Wd QRXWn2tk r} ztd | Wd d } ~ XYnX||fS) aZGets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode. Respects # -*- coding: declarations on the retrieved files. :param url: File path or url. :param session: PipSession instance. :param comes_from: Origin description of requirements. )httphttpsfilerz6Requirements file {} references URL {}, which is local:r<r/|rbNz$Could not open requirements file: {})r getrurltextrrrFrr_url_slash_drive_rergrouprvunquotelstripopenr readIOError) rr4r#schemerespr[rrPrCexcrrrr{#s4         r{z /*([a-z])\|)NNNF)N)NNN)NNN)N)Z__doc__ __future__rrrZrerrZpip._vendor.six.moves.urllibrrvZpip._internal.clirpip._internal.exceptionsrr!pip._internal.models.search_scoperpip._internal.network.utilsrpip._internal.utils.encodingr pip._internal.utils.typingr pip._internal.utils.urlsr r typingr rrrrrrrr"pip._internal.index.package_finderrpip._internal.network.sessionrintZ ReqFileLinesrZ LineParser__all__compileIrtrrrWextra_index_urlrXrsrreditablerR no_binary only_binaryrdrUrb trusted_hostuse_new_featurerinstall_optionsglobal_optionshashrrIobjectr r,rrErNrlr7r6r5r Exceptionr|rr@rArBr{rrrrrs         ,    !  . 7 )N   -req/__pycache__/constructors.cpython-37.pyc000064400000025642152352421750014761 0ustar00B Re@@sdZddlZddlZddlZddlmZddlmZmZddl m Z ddl m Z m Z ddlmZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'm(Z(e#r"ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1dddgZ2e3e4Z5e j67Z8ddZ9ddZ:ddZ;ddZZ?d#d$Z@d2d&dZAd'd(ZBd)d*ZCd+d,ZDd3d-dZEd4d.d/ZFd5d0d1ZGdS)6a~Backing implementation for InstallRequirement's various constructors The idea here is that these formed a major chunk of InstallRequirement's size so, moving them and support code dedicated to them outside of that class helps creates for better understandability for the rest of the code. These are meant to be used elsewhere within pip to create instances of InstallRequirement. N)Marker)InvalidRequirement Requirement) Specifier)RequirementParseErrorparse_requirements)InstallationError)PyPITestPyPI)Link)Wheel)make_pyproject_path)InstallRequirement) deprecated)ARCHIVE_EXTENSIONS)is_installable_dirsplitext)MYPY_CHECK_RUNNING) path_to_url)is_urlvcs)AnyDictOptionalSetTupleUnion)ParsedRequirementinstall_req_from_editableinstall_req_from_lineparse_editablecCs t|d}|tkrdSdS)z9Return True if `name` is a considered as an archive file.TF)rlowerr)nameextr%/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/constructors.pyis_archive_file1sr'cCs6td|}d}|r*|d}|d}n|}||fS)Nz^(.+)(\[[^\]]+\])$r!)rematchgroup)pathmextraspath_no_extrasr%r%r& _strip_extras:s   r0cCs|s tStd|jS)N placeholder)setrr"r.)r.r%r%r&convert_extrasGsr3c Csj|}t|\}}tj|rptjtj|dshdtj|}t|}tj |r`|d7}t |t |}| drt|j}|r||td| jfS||tfSx.tD]&}| d|rd||}PqWd|krt d ||dd d  }t|s@d d dtjD} d|| } t | t|j}|s^t d|||tfS)aParses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] zsetup.pyzMFile "setup.py" not found. Directory cannot be installed in editable mode: {}zb (A "pyproject.toml" file was found, but editable mode currently requires a setup.py based build.)zfile:r1z{}:z{}+{}+z{} is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with svn+, git+, hg+, or bzr+).r!rz, cSsg|]}|jdqS)z+URL)r#).0bendsr%r%r& sz"parse_editable..z2For --editable={}, only {} are currently supportedzZCould not detect requirement name for '{}', please specify one with #egg=your_package_name)r0osr,isdirexistsjoinformatabspathr isfilerrr" startswithr egg_fragmentrr.r2rsplit get_backendbackends) editable_requrl url_no_extrasr.msgpyproject_path package_nameversion_controlvc_typerC error_messager%r%r&r NsN          c Csd}tj|rtd}y8t|d$}tt||d|7}WdQRXWqtk rpt j d|ddYqXn|d |7}|S) zReturns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path z It does exist.rzThe argument you provided ({}) appears to be a requirements file. If that is the case, use the '-r' flag to install the packages specified within it.Nz&Cannot parse '%s' as requirements fileT)exc_infoz File '{}' does not exist.) r8r,r:opennextrreadr<rloggerdebug)reqrGfpr%r%r&deduce_helpful_msgs  rWc@seZdZddZdS)RequirementPartscCs||_||_||_||_dS)N) requirementlinkmarkersr.)selfrYrZr[r.r%r%r&__init__szRequirementParts.__init__N)__name__ __module__ __qualname__r]r%r%r%r&rXsrXcCsbt|\}}}|dk rHy t|}WqLtk rDtd|YqLXnd}t|}t||d|S)NzInvalid requirement: '{}')r rrrr<r rX)rDr#rEextras_overriderUrZr%r%r&parse_req_from_editables rbFcCs^t|}t|j||d|j||||r.|dgng|r@|dgng|rR|dini|jd S)NTinstall_optionsglobal_optionshashes) comes_from user_suppliededitablerZ constraint use_pep517isolatedrcrd hash_optionsr.)rbrrYrZgetr.)rDrfrjrkoptionsrirgpartsr%r%r&rs cCs>tjj|krdStjjdk r,tjj|kr,dS|dr:dSdS)akChecks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (which represents the current directory). TN.F)r8r,sepaltsepr?)r#r%r%r&_looks_like_paths  rscCst|r6tj|r6t|r$t|Stdjftt |sBdStj |rVt|S| dd}t |dkr~t|ds~dSt d|t|S)ad First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file. If false, if the path has an @, it will treat it as a PEP 440 URL requirement and return the path. zUDirectory {name!r} is not installable. Neither 'setup.py' nor 'pyproject.toml' found.N@r!r(rzARequirement %r looks like a filename, but the file does not exist)rsr8r,r9rrrr<localsr'r>rAlenrSwarning)r,r# urlreq_partsr%r%r&_get_url_from_path s"    rycs"t|rd}nd}||krF||d\}}|}|s.with_sourcezIt looks like a path.=c3s|]}|kVqdS)Nr%)r5op) req_as_stringr%r& msz&parse_req_from_line..z,= is not a valid operator. Did you mean == ?rMzInvalid requirement: {!r}z Hint: {}]zExtras after version '{}'.z+moving the extras before version specifiersz21.0) replacementgone_in)#rrAstriprr8r,normpathr=r r0ryschemer)searchrEris_wheelr filenamer<rur@r3rrrqrWany operatorsr specifierstrendswithrrX)r#r} marker_sepmarkers_as_stringr[r,rZextras_as_stringprEwheelr.r~rUadd_msgrGspecspec_strreplacer%)r}rr&parse_req_from_line-sp             rc Csbt||}t|j||j|j|||r.|dgng|r@|dgng|rR|dini||j|d S)aCreates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error. rcrdre) rZr[rjrkrcrdrlrir.rg)rrrYrZr[rmr.) r#rfrjrkrnrir}rgror%r%r&rs cCs|y t|}Wn"tk r.td|YnXtjtjg}|jrj|rj|jrj|jj |krjtd|j |t |||||dS)NzInvalid requirement: '{}'zkPackages installed from PyPI cannot depend on packages which are not also hosted on PyPI. {} depends on {} )rkrjrg) rrrr<r file_storage_domainr rErZnetlocr#r) req_stringrfrkrjrgrUdomains_not_allowedr%r%r&install_req_from_req_strings"   rc CsH|jr"t|j|j||j||d}n"t|j|j|||j|j|j|d}|S)N)rfrjrirkrg)rfrjrkrnrir}rg) is_editablerrYrfrirrnr}) parsed_reqrkrjrgrUr%r%r&#install_req_from_parsed_requirements$ r)NNFNFF)NNFNFNF)NFNF)FNF)H__doc__loggingr8r)Zpip._vendor.packaging.markersrZ"pip._vendor.packaging.requirementsrrZ pip._vendor.packaging.specifiersrZpip._vendor.pkg_resourcesrrpip._internal.exceptionsrpip._internal.models.indexr r pip._internal.models.linkr pip._internal.models.wheelr pip._internal.pyprojectr Zpip._internal.req.req_installrpip._internal.utils.deprecationrpip._internal.utils.filetypesrpip._internal.utils.miscrrpip._internal.utils.typingrpip._internal.utils.urlsrpip._internal.vcsrrtypingrrrrrrZpip._internal.req.req_filer__all__ getLoggerr^rS _operatorskeysrr'r0r3r rWobjectrXrbrrsryrrrrr%r%r%r& sp                 K "]  req/__pycache__/req_uninstall.cpython-37.pyc000064400000041776152352421750015077 0ustar00B Re\@s|ddlmZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZmZmZddlmZddlmZmZmZmZmZmZmZmZmZdd lm Z m!Z!dd l"m#Z#e#r dd l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/e0e1Z2d dZ3ddZ4e4ddZ5ddZ6ddZ7ddZ8Gddde9Z:Gddde9Z;Gddde9Z.unique) functoolswraps)r4r5r+)r4r,_unique=sr8ccstt|d}x||D]t}tj|j|d}|V|drtj |\}}|dd}tj||d}|Vtj||d}|VqWdS)a Yield all the uninstallation paths for dist based on RECORD-without-.py[co] Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc and .pyo in the same directory. UninstallPathSet.add() takes care of the __pycache__ .py[co]. RECORDrz.pyNz.pycz.pyo) csvreaderr get_metadata_linesr!r"r#locationendswithsplit)r%rrowr"dnr4baser+r+r,uninstallation_pathsJs    rEcsNtjjt}x:t|tdD]*tfdd|D}|s|qW|S)zCompact 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.)keyc3s:|]2}|do0t|dkVqdS)*N) startswithrstriplen).0 shortpath)r"sepr+r, mszcompact..)r!r"rMr.sortedrJanyr/)paths short_paths should_skipr+)r"rMr,compactbs  rTc stdd|D}t|}ttdd|Dtd}t}ddx|D]tfdd|DrhqLt}t}xPtD]B\}}|fdd|D|fd d|DqW||sL| || tj qLWtt |j ||BS) zReturns a set containing the paths that need to be renamed. This set may include directories when the original sequence of paths included every file on disk. css|]}tj||fVqdS)N)r!r"normcase)rKpr+r+r,rN}sz&compress_for_rename..css|]}tj|dVqdS)rN)r!r"r@)rKrVr+r+r,rNs)rFcWstjtjj|S)N)r!r"rUr#)ar+r+r, norm_joinsz&compress_for_rename..norm_joinc3s |]}tj|VqdS)N)r!r"rUrH)rKw)rootr+r,rNsc3s|]}|VqdS)Nr+)rKd)dirnamerXrZr+r,rNsc3s|]}|VqdS)Nr+)rKf)r\rXrZr+r,rNs)dictr.rOvaluesrJrPr!walkupdatedifference_updater/rMmap __getitem__) rQcase_map remaining unchecked wildcards all_files all_subdirssubdirsfilesr+)r\rXrZr,compress_for_renamevs*      rmc Cs t|}t}t}t}xF|D]>}|dr0q |dsBd|krT|tj|||q Wtttjj|}t|}xt|D]l}xft |D]X\}} } xL| D]D} | drqtj || } tj | rtj| |kr|| qWqWqW|dd|DB}||fS)asReturns a tuple of 2 sets of which paths to display to user The first set contains paths that would be deleted. Files of a package are not added and the top-level directory of the package has a '*' added at the end - to signify that all it's contents are removed. The second set contains files that would have been skipped in the above folders. z.pycz __init__.pyz .dist-infocSsh|]}tj|dqS)rG)r!r"r#)rKfolderr+r+r, sz.compress_for_output_listing..) r.r?r/r!r"r\rcrUrTr`r#isfile) rQ will_remove will_skipfoldersrlr"_normcased_filesrndirpath_dirfilesfnamefile_r+r+r,compress_for_output_listings0        rzc@sLeZdZdZddZddZddZdd Zd d Zd d Z e ddZ dS)StashedUninstallPathSetzWA set of file rename operations to stash files while tentatively uninstalling them.cCsi|_g|_dS)N) _save_dirs_moves)selfr+r+r,__init__sz StashedUninstallPathSet.__init__cCsDy t|}Wntk r*tdd}YnX||jtj|<|jS)zStashes a directory. Directories are stashed adjacent to their original location if possible, or else moved/copied into the user's temp dir. uninstall)kind)rOSErrorrr|r!r"rU)r~r"save_dirr+r+r,_get_directory_stashs  z,StashedUninstallPathSet._get_directory_stashcCstj|}tj|d}}d}xd||krfy|j|}PWntk rPYnXtj||}}q$Wtj|}tdd}||j|<tj||}|r|tjjkrtj |j|S|jS)zStashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.Nr)r) r!r"rUr\r|KeyErrorrrelpathcurdirr#)r~r"headold_headrrr+r+r,_get_file_stashs"      z'StashedUninstallPathSet._get_file_stashcCsltj|otj| }|r*||}n ||}|j||f|r^tj|r^t|t |||S)zStashes the directory or file and returns its new location. Handle symlinks as files to avoid modifying the symlink targets. ) r!r"isdirislinkrrr}r$rmdirr)r~r" path_is_dirnew_pathr+r+r,stashs    zStashedUninstallPathSet.stashcCs0x|jD]\}}|q Wg|_i|_dS)z0Commits the uninstall by removing stashed files.N)r|itemscleanupr})r~rvrr+r+r,commits zStashedUninstallPathSet.commitc Csx|jD]}tjd|qWx|jD]\}}yTtd||tj|sVtj|rbt|ntj |rvt |t ||Wq&t k r}zt d|td|Wdd}~XYq&Xq&W|dS)z2Undoes the uninstall by moving stashed files back.Moving to %s from %szReplacing %s from %szFailed to restore %sz Exception: %sN)r)r}loggerinfodebugr!r"rprunlinkrrrrerrorr)r~rVrr"exr+r+r,rollback&s    "z StashedUninstallPathSet.rollbackcCs t|jS)N)boolr})r~r+r+r, can_rollback:sz$StashedUninstallPathSet.can_rollbackN) __name__ __module__ __qualname____doc__rrrrrrpropertyrr+r+r+r,r{s r{c@s^eZdZdZddZddZddZdd Zdd d Zd dZ ddZ ddZ e ddZ dS)UninstallPathSetzMA set of file paths to be removed in the uninstallation of a requirement.cCs(t|_t|_i|_||_t|_dS)N)r.rQ_refusepthr%r{ _moved_paths)r~r%r+r+r,rCs zUninstallPathSet.__init__cCst|S)zs Return True if the given path is one we are permitted to remove/modify, False otherwise. )r)r~r"r+r+r, _permittedKszUninstallPathSet._permittedcCstj|\}}tjt|tj|}tj|s:dS||rR|j |n |j |tj |ddkrt r| t |dS)Nz.py)r!r"r@r#rrUexistsrrQr/rsplitextr r)r~r"rtailr+r+r,r/Ts   zUninstallPathSet.addcCsLt|}||r<||jkr*t||j|<|j||n |j|dS)N)rrrUninstallPthEntriesr/r)r~pth_fileentryr+r+r,add_pthhs   zUninstallPathSet.add_pthFc Cs|jstd|jjdS|jjd|jj}td|tx|sP||r|j}t |j}x*t t |D]}| |t d|qnWx|jD] }|qWtd|WdQRXdS)z[Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).z7Can't uninstall '%s'. No files were found to uninstall.N-zUninstalling %s:zRemoving file or directory %szSuccessfully uninstalled %s)rQrrr% project_nameversionr _allowed_to_proceedrrmrOrTrrrr_remove)r~ auto_confirmverbosedist_name_versionmoved for_renamer"rr+r+r,rrs"     zUninstallPathSet.removecCsndd}|st|j\}}nt|j}t}|d||d||d|j|r`|dt|jtddd kS) zIDisplay which files would be deleted and prompt for confirmation c SsH|sdSt|t&xtt|D]}t|q(WWdQRXdS)N)rrr rOrT)msgrQr"r+r+r,_displays  z6UninstallPathSet._allowed_to_proceed.._displayz Would remove:z+Would not remove (might be manually added):z%Would not remove (outside of prefix):zWill actually move:zProceed (y/n)? )ynr)rzrQr.rrmr )r~rrrqrrr+r+r,rs     z$UninstallPathSet._allowed_to_proceedcCsV|jjstd|jjdStd|jj|jx|j D] }|qBWdS)z1Rollback the changes previously made by remove().z'Can't roll back %s; was not uninstalledNzRolling back uninstall of %s) rrrrr%rrrrr_)r~rr+r+r,rs  zUninstallPathSet.rollbackcCs|jdS)z?Remove temporary save dir: rollback will no longer be possible.N)rr)r~r+r+r,rszUninstallPathSet.commitc st|j}t|s.td|j|tj||S|ddt dt dhDkrhtd|j|||S||}t |}d t |j}|jotj|j}t|jdd}|r|jd r|j|s||j|d r"x|d D]&}tjtj|j|} || qWn|d r|d rF|d ngxjfd d|d DD]J} tj|j| } || || d|| d|| dqhWn6|rtd |jn|jdr*||jtj|jd} tjtj|jd} || d| n|r^|jdr^xt |D]} || qHWn|rt!|d} tj"| #$}WdQRX||jkst%d ||j|j||tjtj|d} || |jnt&d||j|drd|'drdxZ|(dD]L}t)|r(t*}nt+}|tj||t,r|tj||dqWg}|j-dd}x$|.D]}|/t0||dq~W|j-d d}x$|.D]}|/t0||d!qWx|D]}||qW|S)"Nz1Not uninstalling %s at %s, outside environment %scSsh|] }|r|qSr+r+)rKrVr+r+r,rosz-UninstallPathSet.from_dist..stdlib platstdlibzsz.UninstallPathSet.from_dist..z.pyz.pycz.pyozCannot uninstall {!r}. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.z.eggrzeasy-install.pthz./z .dist-inforAz;Egg-link {} does not match installed location of {} (at {})z)Not sure how to uninstall: %s - Check: %sscriptsz.batconsole_scripts)groupF gui_scriptsT)1rr>rrrrFsysprefix sysconfigget_pathrformatr to_filenameregg_infor!r"rgetattr _providerr?r/ has_metadata get_metadata splitlinesnormpathr#rr@r\rrEopenrUreadlinestripAssertionErrorrmetadata_isdirmetadata_listdirr rrr get_entry_mapkeysextendr-)clsr% dist_pathr*develop_egg_linkdevelop_egg_link_egg_infoegg_info_existsdistutils_egg_infoinstalled_filer" top_level_pkgeasy_install_eggeasy_install_pthfh link_pointerscriptr(_scripts_to_removernamersr+)rr, from_dists                zUninstallPathSet.from_distN)FF)rrrrrrr/rrrrr classmethodrr+r+r+r,r@s  rc@s,eZdZddZddZddZddZd S) rcCs||_t|_d|_dS)N)filer.entries _saved_lines)r~rr+r+r,rJszUninstallPthEntries.__init__cCs<tj|}tr,tj|ds,|dd}|j|dS)Nr\/)r!r"rUr splitdrivereplacerr/)r~rr+r+r,r/Ps  zUninstallPthEntries.addc Cstd|jtj|js.td|jdSt|jd}|}||_ WdQRXt dd|Drld}nd}|r|d | d s|d| d |d<xH|j D]>}y$td |||| d Wqtk rYqXqWt|jd }||WdQRXdS) NzRemoving pth entries from %s:z.Cannot remove entries from nonexistent file %srbcss|]}d|kVqdS)s Nr+)rKliner+r+r,rNnsz-UninstallPthEntries.remove..z  zutf-8zRemoving entry: %swb)rrrr!r"rpwarningr readlinesrrPr?encoderr ValueError writelines)r~rlinesendlinerr+r+r,r`s*    zUninstallPthEntries.removec CsR|jdkrtd|jdStd|jt|jd}||jWdQRXdS)Nz.Cannot roll back changes to %s, none were madeFz!Rolling %s back to previous staterT)rrrrrrr)r~rr+r+r,r~s  zUninstallPthEntries.rollbackN)rrrrr/rrr+r+r+r,rIsr)= __future__rr;r6loggingr!rr pip._vendorrpip._internal.exceptionsrpip._internal.locationsrrpip._internal.utils.compatrrr pip._internal.utils.loggingr pip._internal.utils.miscr r r rrrrrrpip._internal.utils.temp_dirrrpip._internal.utils.typingrtypingrrrrrrrrrZpip._vendor.pkg_resourcesr getLoggerrrr-r8rErTrmrzobjectr{rrr+r+r+r,s:    ,  ,   (3o req/__pycache__/req_set.cpython-37.pyc000064400000013253152352421750013646 0ustar00B Re@sddlmZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl mZerdd lmZmZmZmZmZdd lmZeeZGd d d eZdS) )absolute_importN) OrderedDict)canonicalize_name)InstallationError)Wheel)compatibility_tags)MYPY_CHECK_RUNNING)DictIterableListOptionalTuple)InstallRequirementc@s\eZdZdddZddZddZdd Zd d Zdd dZddZ ddZ e ddZ d S)RequirementSetTcCst|_||_g|_dS)z!Create a RequirementSet. N)r requirementscheck_supported_wheelsunnamed_requirements)selfrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/req_set.py__init__szRequirementSet.__init__cCs4tdd|jDddd}ddd|DS)Ncss|]}|js|VqdS)N) comes_from).0reqrrr $sz)RequirementSet.__str__..cSs t|jS)N)rname)rrrr%z(RequirementSet.__str__..)key css|]}t|jVqdS)N)strr)rrrrrr's)sortedrvaluesjoin)rrrrr__str__!s zRequirementSet.__str__cCsBt|jddd}d}|j|jjt|ddd|DdS) NcSs t|jS)N)rr)rrrrr-rz)RequirementSet.__repr__..)rz4<{classname} object; {count} requirement(s): {reqs}>z, css|]}t|jVqdS)N)r r)rrrrrr4sz*RequirementSet.__repr__..) classnamecountreqs)r!rr"format __class____name__lenr#)rr format_stringrrr__repr__)s zRequirementSet.__repr__cCs|jr t|j|dS)N)rAssertionErrorrappend)r install_reqrrradd_unnamed_requirement7s z&RequirementSet.add_unnamed_requirementcCs"|js tt|j}||j|<dS)N)rr.rr)rr0 project_namerrradd_named_requirement<s  z$RequirementSet.add_named_requirementNc Cs||s$td|j|jgdfS|jrf|jjrft|jj}t }|j rf| |sft d|j|jr||dks|td|js|||gdfSy||j}Wntk rd}YnX|dko|o|j o|j|jko|jj|jjk}|r t d|||j|s$|||g|fS|js4|jss  zRequirementSet.get_requirementcCs|jt|jS)N)rlistrr")rrrrall_requirementsszRequirementSet.all_requirements)T)NN) r* __module__ __qualname__rr$r-r1r3rNrOr>propertyrRrrrrrs   o  r) __future__rlogging collectionsrZpip._vendor.packaging.utilsrpip._internal.exceptionsrpip._internal.models.wheelrZpip._internal.utilsrpip._internal.utils.typingrtypingr r r r r Zpip._internal.req.req_installr getLoggerr*r5objectrrrrrs         req/__pycache__/req_tracker.cpython-37.pyc000064400000010027152352421750014502 0ustar00B ReR@sddlmZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z e rddl mZddlmZmZmZmZmZmZddlmZdd lmZeeZejd d Zejd d ZGddde Z!dS))absolute_importN) contextlib2) TempDirectory)MYPY_CHECK_RUNNING) TracebackType)DictIteratorOptionalSetTypeUnion)InstallRequirement)Linkc kstj}t}i}xJ|D]>\}}y||||<Wntk rN|||<YnX|||<qWz dVWdx:|D].\}}||kr||=qrt|tst|||<qrWXdS)N)osenvironobjectitemsKeyError isinstancestrAssertionError)changestargetnon_existent_marker saved_valuesname new_valueoriginal_valuer/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/req_tracker.pyupdate_env_context_managers   r c csttjd}tV}|dkrL|tddj}|t|dt d|t | }|VWdQRXWdQRXdS)NPIP_REQ_TRACKERz req-tracker)kind)r!z Initialized build tracking at %s) rrgetr ExitStack enter_contextrpathr loggerdebugRequirementTracker)rootctxtrackerrrrget_requirement_tracker2s    r-c@sReZdZddZddZddZddZd d Zd d Zd dZ e j ddZ dS)r)cCs ||_t|_td|jdS)NzCreated build tracker: %s)_rootset_entriesr'r()selfr*rrr__init__DszRequirementTracker.__init__cCstd|j|S)NzEntered build tracker: %s)r'r(r.)r1rrr __enter__JszRequirementTracker.__enter__cCs |dS)N)cleanup)r1exc_typeexc_valexc_tbrrr__exit__OszRequirementTracker.__exit__cCs$t|j}tj|j|S)N) hashlibsha224url_without_fragmentencode hexdigestrr&joinr.)r1linkhashedrrr _entry_pathXszRequirementTracker._entry_pathc Cs|js t||j}y t|}|}WdQRXWn0tk rf}z|jtjkrVWdd}~XYnXd|j|}t |||j kstt|d}| t |WdQRX|j |td||jdS)z5Add an InstallRequirement to build tracking. Nz{} is already being built: {}wzAdded %s to build tracker %r)r?rrAopenreadIOErrorerrnoENOENTformat LookupErrorr0writeraddr'r(r.)r1req entry_pathfpcontentsemessagerrrrK]s        zRequirementTracker.addcCs<|js tt||j|j|td||j dS)z:Remove an InstallRequirement from build tracking. z Removed %s from build tracker %rN) r?rrunlinkrAr0remover'r(r.)r1rLrrrrS~s  zRequirementTracker.removecCs0xt|jD]}||q Wtd|jdS)NzRemoved build tracker: %r)r/r0rSr'r(r.)r1rLrrrr4szRequirementTracker.cleanupccs||dV||dS)N)rKrS)r1rLrrrtracks zRequirementTracker.trackN) __name__ __module__ __qualname__r2r3r8rArKrSr4 contextlibcontextmanagerrTrrrrr)Bs ! r))" __future__rrXrFr9loggingr pip._vendorrpip._internal.utils.temp_dirrpip._internal.utils.typingrtypesrtypingrrr r r r Zpip._internal.req.req_installr pip._internal.models.linkr getLoggerrUr'rYr r-rr)rrrrs"         req/__pycache__/__init__.cpython-37.pyc000064400000004671152352421750013747 0ustar00B Re= @sddlmZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z erxdd lmZmZmZmZmZd d d d gZeeZGdddeZddZdd ZdS))absolute_importN) indent_log)MYPY_CHECK_RUNNING)parse_requirements)InstallRequirement)RequirementSet)IteratorListOptionalSequenceTuplerrrinstall_given_reqsc@seZdZddZddZdS)InstallationResultcCs ||_dS)N)name)selfrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/__init__.py__init__szInstallationResult.__init__cCs d|jS)NzInstallationResult(name={!r}))formatr)rrrr__repr__szInstallationResult.__repr__N)__name__ __module__ __qualname__rrrrrrrsrccs2x,|D]$}|jstd||j|fVqWdS)Nz'invalid to-be-installed requirement: {})rAssertionErrorr) requirementsreqrrr_validate_requirements"s rc  Cstt|} | r(tdd| g} tx| D]\} } | j rxtd| t| j dd} WdQRXnd} y| j ||||||||dWn(t k r| r| j s| YnX| r| j r| | t| q>WWdQRX| S)zu Install everything in the given list. (to be called after having downloaded and unpacked the packages) z!Installing collected packages: %sz, zAttempting uninstall: %sT) auto_confirmN)roothomeprefixwarn_script_location use_user_site pycompile) collections OrderedDictrloggerinfojoinkeysritemsshould_reinstall uninstallinstall Exceptioninstall_succeededrollbackcommitappendr)rinstall_optionsglobal_optionsrr r!r"r#r$ to_install installedreq_name requirementuninstalled_pathsetrrrr+s@    ) __future__rr%loggingpip._internal.utils.loggingrpip._internal.utils.typingrreq_filer req_installrreq_setrtypingr r r r r __all__ getLoggerrr'objectrrrrrrrs         req/__pycache__/req_install.cpython-37.pyc000064400000051535152352421750014526 0ustar00B Re@sDddlmZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddl mZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZdd lmZ ddl!m"Z#ddl$m%Z%ddl$m&Z'ddl(m)Z)ddl*m+Z+m,Z,ddl-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAddlBmCZCddlDmEZEmFZFddlGmHZHddlImJZJddlKmLZLeHrddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTddlmUZUdd lVmWZWdd!lXmYZYdd"lZm[Z[e\e]Z^d#d$Z_Gd%d&d&e`Zad'd(ZbdS)))absolute_importN) pkg_resourcessix) Requirement)canonicalize_name)Version)parse)Pep517HookCaller)NoOpBuildEnvironment)InstallationError) get_scheme)Link)generate_metadata)install_editable)LegacyInstallFailure)install) install_wheel)load_pyproject_tomlmake_pyproject_path)UninstallPathSet) deprecated)direct_url_from_link)Hashes) indent_log) ask_path_exists backup_dir display_pathdist_in_install_pathdist_in_site_packagesdist_in_usersiteget_distributionget_installed_versionhide_urlredact_auth_from_url) get_metadata) TempDirectory tempdir_kinds)MYPY_CHECK_RUNNING)running_under_virtualenv)vcs)AnyDictIterableListOptionalSequenceUnion)BuildEnvironment) Distribution) SpecifierSet)MarkercCs|tj}tj|\}}t||}|drJtj}tj |d}n.|dsXt tj }tj |ddd}||||dS)zQReturn a pkg_resources.Distribution for the provided metadata directory. z .egg-inforz .dist-info-) project_namemetadata) rstriposseppathsplitr PathMetadataendswithr2splitextAssertionErrorDistInfoDistribution)metadata_directorydist_dirbase_dir dist_dir_namer7dist_cls dist_namerH/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/req/req_install.py _get_distEs   rJc @sFeZdZdZdFddZddZd d Zd d Zed dZ eddZ eddZ eddZ dGddZ eddZdHddZddZddZd d!Zd"d#Zd$d%Zed&d'Zed(d)Zed*d+Zed,d-Zd.d/Zd0d1Zd2d3Zed4d5Zd6d7Zd8d9ZdId:d;ZdJdd?Z!d@dAZ"dBdCZ#dLdDdEZ$dS)MInstallRequirementz Represents something that may be installed later on, may have information about where to fetch the relevant requirement and also contains logic for installing the said requirement. FNrHcCs|dkst|tst|||_||_| |_||_d|_d|_|jrj|sLt|j rjt j t j |j|_|dkr|r|jrt|j}||_|_d|_d|_|jr|jj r|jj|_| r| |_n |rdd|jD|_nt|_|dkr|r|j}||_d|_d|_d|_d|_|r|ng|_| r,| ng|_| r<| ni|_d|_ | |_!d|_"||_#t$|_%d|_&d|_'g|_(d|_)||_*dS)NFcSsh|]}t|qSrH)r safe_extra).0extrarHrHrI sz.InstallRequirement.__init__..)+ isinstancerr@req comes_from constrainteditablelegacy_install_reason source_diris_filer9r;normpathabspath file_pathurlr link original_linkoriginal_link_is_in_wheel_cachelocal_file_pathextrassetmarkermarkers satisfied_byshould_reinstall_temp_build_dirinstall_succeededinstall_optionsglobal_options hash_optionsprepared user_suppliedsuccessfully_downloadedisolatedr build_envrBpyproject_requiresrequirements_to_checkpep517_backend use_pep517)selfrQrRrTr\rcrsrnrhrirjrSr`rlrHrHrI__init__gsZ     zInstallRequirement.__init__cCs|jr.t|j}|jrF|dt|jj7}n|jrBt|jj}nd}|jdk rf|dt|jj7}|j rt |j t j r|j }n |j }|r|d|7}|S)Nz from {}zz in {}z (from {}))rQstrr\formatr#r[rdrlocationrRrPr string_types from_path)rtsrRrHrHrI__str__s    zInstallRequirement.__str__cCsd|jjt||jS)Nz<{} object: {} editable={!r}>)rw __class____name__rvrT)rtrHrHrI__repr__szInstallRequirement.__repr__cs>t|t}fddt|D}dj|jjd|dS)z>An un-tested helper for getting state, for debugging. c3s|]}d||VqdS)z{}={!r}N)rw)rMattr) attributesrHrI sz2InstallRequirement.format_debug..z<{name} object: {{{state}}}>z, )namestate)varssortedrwr}r~join)rtnamesrrH)rrI format_debugs zInstallRequirement.format_debugcCs"|jdkrdStt|jjS)N)rQr ensure_strr safe_namer)rtrHrHrIrs zInstallRequirement.namecCs|jjS)N)rQ specifier)rtrHrHrIr szInstallRequirement.specifiercCs$|j}t|dko"tt|jdkS)zReturn whether I am pinned to an exact version. For example, some-package==1.2 is pinned; some-package>1.2 is not. >=====)rlennextiteroperator)rt specifiersrHrHrI is_pinneds zInstallRequirement.is_pinnedcCs t|jS)N)r!r)rtrHrHrIinstalled_versionsz$InstallRequirement.installed_versioncs0|sd}jdk r(tfdd|DSdSdS)N)c3s|]}jd|iVqdS)rNN)rcevaluate)rMrN)rtrHrIr(sz3InstallRequirement.match_markers..T)rcany)rtextras_requestedrH)rtrI match_markers s   z InstallRequirement.match_markerscCs t|jS)zReturn whether any known-good hashes are specified as options. These activate --require-hashes mode; hashes specified as part of a URL do not. )boolrj)rtrHrHrIhas_hash_options-s z#InstallRequirement.has_hash_optionsTcCsB|j}|r|jn|j}|r:|jr:||jg|jt|S)aReturn a hash-comparer that considers my option- and URL-based hashes to be known-good. Hashes in URLs--ones embedded in the requirements file, not ones downloaded from an index server--are almost peers with ones from flags. They satisfy --require-hashes (whether it was implicitly or explicitly activated) but do not activate it. md5 and sha224 are not allowed in flags, which should nudge people toward good algos. We always OR all hashes together, even ones from URLs. :param trust_internet: Whether to trust URL-based (#md5=...) hashes downloaded from the internet, as by populate_link() ) rjcopyr\r]hash setdefault hash_nameappendr)rttrust_internet good_hashesr\rHrHrIhashes8s   zInstallRequirement.hashescCsR|jdkrdSt|j}|jrNt|jtjr4|j}n |j}|rN|d|7}|S)z@Format a nice indicator to show where this "comes from" Nz->)rQrvrRrPrryrz)rtr{rRrHrHrIrzNs    zInstallRequirement.from_pathcCs|dk s t|jdk r*|jjs"t|jjS|jdkrLttjdd|_|jjSt|j}|rld |t j }t j|std|t |t j||}|rdnd}t||tjddjS)NT)kindglobally_managedz{}_{}zCreating directory %sF)r;deleterr)r@rfr;rQr%r& REQ_BUILDrrrwuuiduuid4hexr9existsloggerdebugmakedirsr)rt build_dir autodeleteparallel_buildsdir_nameactual_build_dir delete_argrHrHrIensure_build_location^s*         z(InstallRequirement.ensure_build_locationcCsn|jdkst|jdk st|jdk s*ttt|jdtrDd}nd}td|jd||jdg|_dS)z3Set requirement after generating metadata. Nrz==z===rName) rQr@r7rVrP parse_versionrrr)rtoprHrHrI_set_requirementsz#InstallRequirement._set_requirementcCsDt|jd}t|jj|kr"dStd|j||jt||_dS)NrzeGenerating metadata for package %s produced metadata for project name %s. Fix your #egg=%s fragments.)rr7rQrrwarningr)rt metadata_namerHrHrIwarn_on_mismatching_namesz+InstallRequirement.warn_on_mismatching_namecCs|jdkrdSt|jj}|s"dS|j}|jjj|ddsd|_|rxt|rTd|_qt rt |rt d |j |jqt|rd|_n|jrd|_d|_n||_dS)zFind an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.should_reinstall appropriately. NT) prereleaseszVWill not install to the user site because it will lack sys.path precedence to {} in {})rQr rparsed_versionrcontainsrdrrer(rr rwr6rxrrT)rt use_user_site existing_distexisting_versionrHrHrIcheck_if_existss,  z"InstallRequirement.check_if_existscCs|js dS|jjS)NF)r\is_wheel)rtrHrHrIrszInstallRequirement.is_wheelcCstj|j|jr|jjpdS)Nr)r9r;rrVr\subdirectory_fragment)rtrHrHrIunpacked_source_directorysz,InstallRequirement.unpacked_source_directorycCsH|jstd|tj|jd}tjrDt |tj rD| t }|S)NzNo source dir for {}zsetup.py)rVr@rwr9r;rrrPY2rP text_typeencodesysgetfilesystemencoding)rtsetup_pyrHrHrI setup_py_paths z InstallRequirement.setup_py_pathcCs|jstd|t|jS)NzNo source dir for {})rVr@rwrr)rtrHrHrIpyproject_toml_pathsz&InstallRequirement.pyproject_toml_pathcCs^t|j|j|jt|}|dkr*d|_dSd|_|\}}}}||_||_t|j||d|_ dS)aALoad the pyproject.toml file. After calling this routine, all of the attributes related to PEP 517 processing for this requirement have been set. In particular, the use_pep517 attribute can be used to determine whether we should follow the PEP 517 or legacy (setup.py) code path. NFT) backend_path) rrsrrrvrqrpr rrr)rtpyproject_toml_datarequiresbackendcheckrrHrHrIrs   z&InstallRequirement.load_pyproject_tomlcCsV|js8|jstt|j|j|j|j|jp2d|j dS|j dk sFtt |j|j dS)zKInvokes metadata generator functions, with the required arguments. zfrom {})rorrVrndetailsN)ror) rsrr@generate_metadata_legacyrorrnrrwr\rrr)rtrHrHrI_generate_metadata s z%InstallRequirement._generate_metadatac CsJ|js tt||_WdQRX|js6|n||dS)zEnsure that project metadata is available. Under PEP 517, call the backend hook to prepare the metadata. Under legacy processing, call setup.py egg-info. N) rVr@rrrBrrrassert_source_matches_version)rtrHrHrIprepare_metadata"s  z#InstallRequirement.prepare_metadatacCst|dst||_|jS)N _metadata)hasattrr$get_distr)rtrHrHrIr76s zInstallRequirement.metadatacCs t|jS)N)rJrB)rtrHrHrIr>szInstallRequirement.get_distcCsR|js t|jd}|jjr8||jjkr8td||ntdt|j||dS)Nversionz'Requested %s, but installing version %sz;Source in %s has version %s, which satisfies requirement %s) rVr@r7rQrrrrr)rtrrHrHrIrBs  z0InstallRequirement.assert_source_matches_versioncCs |jdkr|j|||d|_dS)aAEnsure that a source_dir is set. This will create a temporary build dir if the name of the requirement isn't known yet. :param parent_dir: The ideal pip parent_dir for the source_dir. Generally src_dir for editables and build_dir for sdists. :return: self.source_dir N)rr)rVr)rt parent_dirrrrHrHrIensure_has_source_dirUs  z(InstallRequirement.ensure_has_source_dircCs|jstd|jdS|js"t|js,t|jjdkrCannot update repository at %s; repository location is unknownfile+zbad url: {self.link.url!r}rz5This form of VCS requirement is being deprecated: {}.zgit+git@zmgit+https://git@example.com/..., git+ssh://git@example.com/..., or the insecure git+git://git@example.com/...z21.0i)gone_inissue)r[rz+Unexpected version control type (in {}): {})r\rrrVrTr@schemer[rwlocalsr<r) get_backendis_vcs startswithrr"obtainexport)rtrvc_typer[ vcs_backendreason replacement hidden_urlrHrHrIupdate_editablems8      z"InstallRequirement.update_editablecCsR|js tt|jj}|s,td|jdStd|t|}| |||S)a 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 is linked to global site-packages. z#Skipping %s as it is not installed.NzFound existing installation: %s) rQr@r rrrinfor from_distremove)rt auto_confirmverbosedistuninstalled_pathsetrHrHrI uninstalls     zInstallRequirement.uninstallcCs.dd}tj||}|||}|jd|S)NcSsL||tjjs$tdjft|t|dd}|tjjd}|S)Nz2name {name!r} doesn't start with prefix {prefix!r}r/) rr9r;r:r@rwrrreplace)rprefixrHrHrI_clean_zip_names  z=InstallRequirement._get_archive_name.._clean_zip_namer)r9r;rr)rtr; parentdirrootdirrrrHrHrI_get_archive_names  z$InstallRequirement._get_archive_namec Cs|js td}d|j|jd}tj||}tj|rt dt |d}|dkr^d}nj|dkrt d t |t |nF|d krt|}t d t |t |t||n|d krtd |sdStj|dtjdd}|tjtj|j}xt|D]\} } } x>| D]6} |j| | |d} t| d}d|_||dqWx8| D]0}|j|| |d}tj| |}|||q\Wq WWdQRXt dt |dS)z}Saves archive to provided build_dir. Used for saving downloaded VCS requirements as part of `pip download`. Tz {}-{}.ziprz8The file {} exists. (i)gnore, (w)ipe, (b)ackup, (a)bort )iwbarFrz Deleting %srzBacking up %s to %srN) allowZip64)rrrirzSaved %s) rVr@rwrr7r9r;rrrrrrrrshutilmoverexitzipfileZipFile ZIP_DEFLATEDnormcaserYrwalkrZipInfo external_attrwritestrwriter)rtrcreate_archive archive_name archive_pathresponse dest_file zip_outputdirdirpathdirnames filenamesdirname dir_arcnamezipdirfilename file_arcnamerHrHrIarchivesV         "zInstallRequirement.archivec Cst|j||||j|d} |dk r$|ng}|jr^t||||||j|j|j|j|jd d|_dS|j r|j snt d} |j rt |j |j|j} t|j|j | t|j||| |jdd|_dSt||j}t||j}y8t|||||||| |j|j|j|j|jt|jd} WnRtk rB} zd|_tj| jWdd} ~ XYntk r^d|_YnX| |_| r|jdkrtd|jd d dd dS) N)userhomerootrnr)rr$rrrrnrorT)rreq_description pycompilewarn_script_location direct_url requested)rhrir%r$rrr'rrrnreq_namerorr&Fi zg{} was installed using the legacy 'setup.py install' method, because a wheel could not be built for it.z+to fix the wheel build issue reported abovez21.0)rrrr) r rrnrTinstall_editable_legacyrrorrgrr_r@r]rrVr^rrvrQrllistrirhinstall_legacyrrreraiseparent ExceptionrUrrw) rtrhrir%r$rr(rr'rr)successexcrHrHrIrs     zInstallRequirement.install) FNNNFNNNFrHF)N)T)FF)T)FF)NNNNTFT)%r~ __module__ __qualname____doc__rur|rrpropertyrrrrrrrrzrrrrrrrrrrrr7rrrrrrr"rrHrHrHrIrK`sd e    &%      , @rKcCs>d}|jsd}n|jrd}n |jr&d}|r:tddddd|S) Nrz3Unnamed requirements are not allowed as constraintsz$Links are not allowed as constraintszConstraints cannot have extrasaConstraints are only allowed to take the form of a package name and a version specifier. Other forms were originally permitted as an accident of the implementation, but were undocumented. The new implementation of the resolver no longer supports these forms.z,replacing the constraint with a requirement.i )rrrr)rr\r`r)rQproblemrHrHrIcheck_invalid_constraint_typemsr9)c __future__rloggingr9rrrr  pip._vendorrrZ"pip._vendor.packaging.requirementsrZpip._vendor.packaging.utilsrpip._vendor.packaging.versionrrrpip._vendor.pep517.wrappersr pip._internal.build_envr pip._internal.exceptionsr pip._internal.locationsr pip._internal.models.linkr 'pip._internal.operations.build.metadatar.pip._internal.operations.build.metadata_legacyr0pip._internal.operations.install.editable_legacyrr,'pip._internal.operations.install.legacyrrr.&pip._internal.operations.install.wheelrpip._internal.pyprojectrrpip._internal.req.req_uninstallrpip._internal.utils.deprecationr&pip._internal.utils.direct_url_helpersrpip._internal.utils.hashesrpip._internal.utils.loggingrpip._internal.utils.miscrrrrrrr r!r"r#pip._internal.utils.packagingr$pip._internal.utils.temp_dirr%r&pip._internal.utils.typingr'pip._internal.utils.virtualenvr(pip._internal.vcsr)typingr*r+r,r-r.r/r0r1Zpip._vendor.pkg_resourcesr2Z pip._vendor.packaging.specifiersr3Zpip._vendor.packaging.markersr4 getLoggerr~rrJobjectrKr9rHrHrHrIsd                     0    $     wheel_builder.py000064400000022462152352421750007744 0ustar00"""Orchestrator for building wheels from InstallRequirements. """ import logging import os.path import re import shutil from pip._internal.models.link import Link from pip._internal.operations.build.wheel import build_wheel_pep517 from pip._internal.operations.build.wheel_legacy import build_wheel_legacy from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed from pip._internal.utils.setuptools_build import make_setuptools_clean_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url from pip._internal.vcs import vcs if MYPY_CHECK_RUNNING: from typing import ( Any, Callable, Iterable, List, Optional, Tuple, ) from pip._internal.cache import WheelCache from pip._internal.req.req_install import InstallRequirement BinaryAllowedPredicate = Callable[[InstallRequirement], bool] BuildResult = Tuple[List[InstallRequirement], List[InstallRequirement]] logger = logging.getLogger(__name__) _egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.IGNORECASE) def _contains_egg_info(s): # type: (str) -> bool """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s)) def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are merely constraints return False if req.is_wheel: if need_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) return False if need_wheel: # i.e. pip wheel, not pip install return True # From this point, this concerns the pip install command only # (need_wheel=False). if req.editable or not req.source_dir: return False if not check_binary_allowed(req): logger.info( "Skipping wheel build for %s, due to binaries " "being disabled for it.", req.name, ) return False if not req.use_pep517 and not is_wheel_installed(): # we don't build legacy requirements if wheel is not installed logger.info( "Using legacy 'setup.py install' for %s, " "since package 'wheel' is not installed.", req.name, ) return False return True def should_build_for_wheel_command( req, # type: InstallRequirement ): # type: (...) -> bool return _should_build( req, need_wheel=True, check_binary_allowed=_always_true ) def should_build_for_install_command( req, # type: InstallRequirement check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool return _should_build( req, need_wheel=False, check_binary_allowed=check_binary_allowed ) def _should_cache( req, # type: InstallRequirement ): # type: (...) -> Optional[bool] """ Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. """ if req.editable or not req.source_dir: # never cache editable requirements return False if req.link and req.link.is_vcs: # VCS checkout. Do not cache # unless it points to an immutable commit hash. assert not req.editable assert req.source_dir vcs_backend = vcs.get_backend_for_scheme(req.link.scheme) assert vcs_backend if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir): return True return False assert req.link base, ext = req.link.splitext() if _contains_egg_info(base): return True # Otherwise, do not cache. return False def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) assert req.link if cache_available and _should_cache(req): cache_dir = wheel_cache.get_path_for_link(req.link) else: cache_dir = wheel_cache.get_ephem_path_for_link(req.link) return cache_dir def _always_true(_): # type: (Any) -> bool return True def _build_one( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ensure_dir(output_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) return None # Install build deps into temporary directory (PEP 518) with req.build_env: return _build_one_inside_env( req, output_dir, build_options, global_options ) def _build_one_inside_env( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] with TempDirectory(kind="wheel") as temp_dir: assert req.name if req.use_pep517: assert req.metadata_directory wheel_path = build_wheel_pep517( name=req.name, backend=req.pep517_backend, metadata_directory=req.metadata_directory, build_options=build_options, tempd=temp_dir.path, ) else: wheel_path = build_wheel_legacy( name=req.name, setup_py_path=req.setup_py_path, source_dir=req.unpacked_source_directory, global_options=global_options, build_options=build_options, tempd=temp_dir.path, ) if wheel_path is not None: wheel_name = os.path.basename(wheel_path) dest_path = os.path.join(output_dir, wheel_name) try: wheel_hash, length = hash_file(wheel_path) shutil.move(wheel_path, dest_path) logger.info('Created wheel for %s: ' 'filename=%s size=%d sha256=%s', req.name, wheel_name, length, wheel_hash.hexdigest()) logger.info('Stored in directory: %s', output_dir) return dest_path except Exception as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) # Ignore return, we can't do anything else useful. if not req.use_pep517: _clean_one_legacy(req, global_options) return None def _clean_one_legacy(req, global_options): # type: (InstallRequirement, List[str]) -> bool clean_args = make_setuptools_clean_args( req.setup_py_path, global_options=global_options, ) logger.info('Running setup.py clean for %s', req.name) try: call_subprocess(clean_args, cwd=req.source_dir) return True except Exception: logger.error('Failed cleaning build dir for %s', req.name) return False def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build. """ if not requirements: return [], [] # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join(req.name for req in requirements), # type: ignore ) with indent_log(): build_successes, build_failures = [], [] for req in requirements: cache_dir = _get_cache_dir(req, wheel_cache) wheel_file = _build_one( req, cache_dir, build_options, global_options ) if wheel_file: # Update the link for this. req.link = Link(path_to_url(wheel_file)) req.local_file_path = req.link.file_path assert req.link.is_wheel build_successes.append(req) else: build_failures.append(req) # notify success/failure if build_successes: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_successes]), # type: ignore ) if build_failures: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failures]), # type: ignore ) # Return a list of requirements that failed to build return build_successes, build_failures distributions/sdist.py000064400000007766152352421750011174 0ustar00import logging from pip._internal.build_env import BuildEnvironment from pip._internal.distributions.base import AbstractDistribution from pip._internal.exceptions import InstallationError from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Set, Tuple from pip._vendor.pkg_resources import Distribution from pip._internal.index.package_finder import PackageFinder logger = logging.getLogger(__name__) class SourceDistribution(AbstractDistribution): """Represents a source distribution. The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. """ def get_pkg_resources_distribution(self): # type: () -> Distribution return self.req.get_dist() def prepare_distribution_metadata(self, finder, build_isolation): # type: (PackageFinder, bool) -> None # Load pyproject.toml, to determine whether PEP 517 is to be used self.req.load_pyproject_toml() # Set up the build isolation, if this requirement should be isolated should_isolate = self.req.use_pep517 and build_isolation if should_isolate: self._setup_isolation(finder) self.req.prepare_metadata() def _setup_isolation(self, finder): # type: (PackageFinder) -> None def _raise_conflicts(conflicting_with, conflicting_reqs): # type: (str, Set[Tuple[str, str]]) -> None format_string = ( "Some build dependencies for {requirement} " "conflict with {conflicting_with}: {description}." ) error_message = format_string.format( requirement=self.req, conflicting_with=conflicting_with, description=', '.join( '{} is incompatible with {}'.format(installed, wanted) for installed, wanted in sorted(conflicting) ) ) raise InstallationError(error_message) # Isolate in a BuildEnvironment and install the build-time # requirements. pyproject_requires = self.req.pyproject_requires assert pyproject_requires is not None self.req.build_env = BuildEnvironment() self.req.build_env.install_requirements( finder, pyproject_requires, 'overlay', "Installing build dependencies" ) conflicting, missing = self.req.build_env.check_requirements( self.req.requirements_to_check ) if conflicting: _raise_conflicts("PEP 517/518 supported requirements", conflicting) if missing: logger.warning( "Missing build requirements in pyproject.toml for %s.", self.req, ) logger.warning( "The project does not specify a build backend, and " "pip cannot fall back to setuptools without %s.", " and ".join(map(repr, sorted(missing))) ) # Install any extra build dependencies that the backend requests. # This must be done in a second pass, as the pyproject.toml # dependencies must be installed before we can call the backend. with self.req.build_env: runner = runner_with_spinner_message( "Getting requirements to build wheel" ) backend = self.req.pep517_backend assert backend is not None with backend.subprocess_runner(runner): reqs = backend.get_requires_for_build_wheel() conflicting, missing = self.req.build_env.check_requirements(reqs) if conflicting: _raise_conflicts("the backend dependencies", conflicting) self.req.build_env.install_requirements( finder, missing, 'normal', "Installing backend dependencies" ) distributions/__pycache__/wheel.cpython-37.pyc000064400000003101152352421750015412 0ustar00B Re@s`ddlmZddlmZddlmZddlmZerLddlm Z ddl m Z GdddeZ d S) )ZipFile)AbstractDistribution)MYPY_CHECK_RUNNING)$pkg_resources_distribution_for_wheel) Distribution) PackageFinderc@s eZdZdZddZddZdS)WheelDistributionzqRepresents a wheel distribution. This does not need any preparation as wheels can be directly unpacked. c CsH|jjs t|jjstt|jjdd}t||jj|jjSQRXdS)zLoads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement. T) allowZip64N)reqlocal_file_pathAssertionErrornamerr)selfzr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/distributions/wheel.pyget_pkg_resources_distributions   z0WheelDistribution.get_pkg_resources_distributioncCsdS)Nr)rfinderbuild_isolationrrrprepare_distribution_metadata"sz/WheelDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__rrrrrrr srN) zipfiler pip._internal.distributions.baserpip._internal.utils.typingrpip._internal.utils.wheelrZpip._vendor.pkg_resourcesr"pip._internal.index.package_finderrrrrrrs      distributions/__pycache__/installed.cpython-37.pyc000064400000002361152352421750016274 0ustar00B Re@sTddlmZddlmZer@ddlmZddlmZddlm Z GdddeZ dS) )AbstractDistribution)MYPY_CHECK_RUNNING)Optional) Distribution) PackageFinderc@s eZdZdZddZddZdS)InstalledDistributionzRepresents an installed package. This does not need any preparation as the required information has already been computed. cCs|jjS)N)req satisfied_by)selfr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/distributions/installed.pyget_pkg_resources_distributionsz4InstalledDistribution.get_pkg_resources_distributioncCsdS)Nr )r finderbuild_isolationr r r prepare_distribution_metadatasz3InstalledDistribution.prepare_distribution_metadataN)__name__ __module__ __qualname____doc__r rr r r r r srN) pip._internal.distributions.baserpip._internal.utils.typingrtypingrZpip._vendor.pkg_resourcesr"pip._internal.index.package_finderrrr r r r s     distributions/__pycache__/base.cpython-37.pyc000064400000003673152352421750015236 0ustar00B Re@srddlZddlmZddlmZerTddlmZddlmZddl m Z ddl m Z eej Gdd d eZdS) N) add_metaclass)MYPY_CHECK_RUNNING)Optional) Distribution)InstallRequirement) PackageFindercs<eZdZdZfddZejddZejddZZ S)AbstractDistributiona A base class for handling installable artifacts. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. cstt|||_dS)N)superr__init__req)selfr ) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/distributions/base.pyr szAbstractDistribution.__init__cCs tdS)N)NotImplementedError)r rrrget_pkg_resources_distribution%sz3AbstractDistribution.get_pkg_resources_distributioncCs tdS)N)r)r finderbuild_isolationrrrprepare_distribution_metadata*sz2AbstractDistribution.prepare_distribution_metadata) __name__ __module__ __qualname____doc__r abcabstractmethodrr __classcell__rr)r rrs r)rZpip._vendor.sixrpip._internal.utils.typingrtypingrZpip._vendor.pkg_resourcesrZpip._internal.reqr"pip._internal.index.package_finderrABCMetaobjectrrrrrs      distributions/__pycache__/sdist.cpython-37.pyc000064400000006647152352421750015456 0ustar00B Re@sddlZddlmZddlmZddlmZddlmZddl m Z e rpddl m Z m Z ddlmZdd lmZeeZGd d d eZdS) N)BuildEnvironment)AbstractDistribution)InstallationError)runner_with_spinner_message)MYPY_CHECK_RUNNING)SetTuple) Distribution) PackageFinderc@s(eZdZdZddZddZddZdS) SourceDistributionzRepresents a source distribution. The preparation step for these needs metadata for the packages to be generated, either using PEP 517 or using the legacy `setup.py egg_info`. cCs |jS)N)reqget_dist)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/distributions/sdist.pyget_pkg_resources_distributionsz1SourceDistribution.get_pkg_resources_distributioncCs2|j|jjo|}|r$|||jdS)N)r load_pyproject_toml use_pep517_setup_isolationprepare_metadata)rfinderbuild_isolationshould_isolaterrrprepare_distribution_metadatas    z0SourceDistribution.prepare_distribution_metadatac sfdd}jj}|dk s"ttj_jj||ddjjjj\}rd|d|rt djt dd t t t |jj@td }jj}|dk st|||}WdQRXWdQRXjj|\}r|d jj||d d dS) Ncs6d}|jj|dddtDd}t|dS)NzZSome build dependencies for {requirement} conflict with {conflicting_with}: {description}.z, css|]\}}d||VqdS)z{} is incompatible with {}N)format).0 installedwantedrrr 6szPSourceDistribution._setup_isolation.._raise_conflicts..) requirementconflicting_with description)rr joinsortedr)r conflicting_reqs format_string error_message) conflictingrrr_raise_conflicts,sz=SourceDistribution._setup_isolation.._raise_conflictsoverlayzInstalling build dependenciesz"PEP 517/518 supported requirementsz4Missing build requirements in pyproject.toml for %s.z`The project does not specify a build backend, and pip cannot fall back to setuptools without %s.z and z#Getting requirements to build wheelzthe backend dependenciesnormalzInstalling backend dependencies)r pyproject_requiresAssertionErrorr build_envinstall_requirementscheck_requirementsrequirements_to_checkloggerwarningr"mapreprr#rpep517_backendsubprocess_runnerget_requires_for_build_wheel)rrr(r+missingrunnerbackendreqsr)r'rrr*s@      z#SourceDistribution._setup_isolationN)__name__ __module__ __qualname____doc__rrrrrrrr s r )loggingpip._internal.build_envr pip._internal.distributions.baserpip._internal.exceptionsrpip._internal.utils.subprocessrpip._internal.utils.typingrtypingrrZpip._vendor.pkg_resourcesr "pip._internal.index.package_finderr getLoggerr<r1r rrrrs        distributions/__pycache__/__init__.cpython-37.pyc000064400000001557152352421750016062 0ustar00B Re@sLddlmZddlmZddlmZer@ddlmZddlm Z ddZ dS) )SourceDistribution)WheelDistribution)MYPY_CHECK_RUNNING)AbstractDistribution)InstallRequirementcCs$|jrt|S|jrt|St|S)zs     operations/__pycache__/freeze.cpython-37.pyc000064400000013373152352421750015063 0ustar00B Re( @s<ddlmZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z ddlmZmZddlmZdd lmZmZdd lmZmZdd lmZer dd lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&ddl m'Z'm(Z(e"ee$e)e(fe*ee)fZ+e,e-Z.dddZ/ddZ0Gddde1Z2dS))absolute_importN)six)canonicalize_name)RequirementParseError) BadCommandInstallationError)install_req_from_editableinstall_req_from_line) COMMENT_RE)%direct_url_as_pep440_direct_referencedist_get_direct_url)dist_is_editableget_installed_distributions)MYPY_CHECK_RUNNING) IteratorOptionalList ContainerSetDictTupleIterableUnion) WheelCache) Distribution RequirementFc  cs|pg}x|D]} d| VqWi} xpt|d||dD]\} yt| } Wn2tk r|} ztd| | w8Wdd} ~ XYnX|r| jrq8| | | j<q8W|rt }t t }x|D]}t |r}xh|D]^}|r|ds|dr|}||kr|||Vq|ds2|drx|drP|d d}n|tddd }t||d }nttd ||d }|jstd ||tdqt|j}|| kr||jstd|td ||jn||j|qt| |V| |=||j|qWWdQRXqWxBt|D]4\}}t|dkrNtd|dt t |qNWdVx8t | !dddD] }|j|krt|VqWdS)Nz-f {}r) local_onlyskip user_onlypathsz6Could not generate requirement for distribution %r: %s#) z-rz --requirementz-fz --find-linksz-iz --index-urlz--prez--trusted-hostz--process-dependency-linksz--extra-index-urlz --use-featurez-ez --editable=)isolatedzWSkipping line in requirement file [%s] because it's not clear what it would install: %sz9 (add #egg=PackageName to the URL to avoid this warning)zBRequirement file [%s] contains %s, but package %r is not installedz+Requirement %s included multiple times [%s]z, z7## The following requirements were added by pip freeze:cSs |jS)N)namelower)xrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/freeze.pyzfreeze..)key)"formatrFrozenRequirement from_distrloggerwarningeditablecanonical_nameset collections defaultdictlistopenstrip startswithrstripaddlenlstriprr r subr'inforappendstrr iteritemsjoinsortedvalues) requirement find_linksrrr r$ wheel_cacheZexclude_editablerlinkZ installationsdistreqexcZemitted_optionsZ req_filesZ req_file_pathreq_filelineZline_reqZline_req_canonical_namer'filesZ installationrrr*freeze*s             " rRc CsFt|sddgfStjtj|j}ddlm}m}| |}|dkrv| }t d||d |g}|d|fSy|||j}Wn|k r| }d t|j|g}|d|fStk rt d ||jddgfStk r}zt d |Wdd}~XYnX|dk r*|dgfSt d |d g}dd|fS) zk Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). NFr)vcsRemoteNotFoundErrorz1No VCS found for editable requirement "%s" in: %rz/# Editable install with no version control ({})Tz)# Editable {} install with no remote ({})zPcannot determine version of editable source in %s (%s command not found in path)zYError when trying to get requirement for VCS system %s, falling back to uneditable formatz-Could not determine repository location of %sz-## !! Could not determine repository location)r ospathnormcaseabspathlocationpip._internal.vcsrSrTget_backend_for_diras_requirementr1debugr.get_src_requirement project_nametype__name__rr2r'r)rLrYrSrT vcs_backendrMcommentsrNrrr*get_requirement_infosF        rdc@s*eZdZd ddZeddZddZdS) r/rcCs&||_t||_||_||_||_dS)N)r'rr4rMr3rc)selfr'rMr3rcrrr*__init__s  zFrozenRequirement.__init__cCsXt|\}}}|dkr6|s6t|}|r6t||j}g}|dkrF|}||j|||dS)N)rc)rdr r r_r\)clsrLrMr3rc direct_urlrrr*r0s  zFrozenRequirement.from_distcCs4|j}|jrd|}dt|jt|gdS)Nz-e {} )rMr3r.rEr8rcrC)rerMrrr*__str__ s zFrozenRequirement.__str__N)r)ra __module__ __qualname__rf classmethodr0rjrrrr*r/s  r/) NNFFNFNFr)3 __future__rr6loggingrU pip._vendorrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrpip._internal.exceptionsrrpip._internal.req.constructorsrr Zpip._internal.req.req_filer &pip._internal.utils.direct_url_helpersr r pip._internal.utils.miscr rpip._internal.utils.typingrtypingrrrrrrrrrpip._internal.cacherrrrCboolZRequirementInfo getLoggerrar1rRrdobjectr/rrrr*s:      ,   |>operations/__pycache__/__init__.cpython-37.pyc000064400000000347152352421750015337 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/__init__.pyoperations/__pycache__/prepare.cpython-37.pyc000064400000026165152352421750015244 0ustar00B ReM@s:dZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZmZmZmZmZddlmZddlmZdd lmZdd lmZmZmZmZdd lmZdd l m!Z!dd l"m#Z#ddl$m%Z%e!rddl&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddlm-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5ddl6m7Z7ddlm8Z8ere,de'e9e(e9ge(e9fe:dddZ;n8e,de'e9e9gdfe'e9e(e9ge(e9fe:e:dddZ;eddZ?dd Z@Gd!d"d"eAZBd3d#d$ZCd%d&ZDd'd(ZEd4d)d*ZFd5d+d,ZGd-d.ZHd/d0ZIGd1d2d2eAZJdS)6z)Prepares a distribution for installation N)PY2))make_distribution_for_install_requirement)InstalledDistribution)DirectoryUrlHashUnsupported HashMismatch HashUnpinnedInstallationErrorNetworkConnectionErrorPreviousBuildDirErrorVcsHashUnsupported) copy2_fixed) MissingHashes) indent_log) display_pathhide_urlpath_to_displayrmtree) TempDirectory)MYPY_CHECK_RUNNING) unpack_file)vcs)CallableListOptionalTuple) TypedDict)AbstractDistribution) PackageFinder)Link) Downloader)InstallRequirement)RequirementTracker)HashesCopytreeKwargs)ignoresymlinksF)total) copy_functionr$ignore_dangling_symlinksr%c Cs.t|}|||||WdQRX|S)z-Prepare a distribution for installation. N)rtrackprepare_distribution_metadata)req req_trackerfinderbuild_isolation abstract_distr0/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/prepare.py_get_prepared_distributionPs  r2cCs0t|j}|dk st|j|t|jddS)N)url)rget_backend_for_schemeschemeAssertionErrorunpackrr3)linklocation vcs_backendr0r0r1unpack_vcs_link_s  r;c@seZdZddZdS)FilecCs||_||_dS)N)path content_type)selfr=r>r0r0r1__init__gsz File.__init__N)__name__ __module__ __qualname__r@r0r0r0r1r<fsr<cCsVtddd}d}|r t|||}|r8|}t|d}nt|||j|\}}t||S)Nr7T)kindglobally_managedr)r_check_download_dir mimetypes guess_type_download_http_urlr=r<)r8 downloader download_dirhashestemp_diralready_downloaded_path from_pathr>r0r0r1 get_http_urlms  rPc CsTyt||Wn@tjk rN}z tdt|t|t|Wdd}~XYnXdS)zCopying special files is not supported, but as a convenience to users we skip errors copying them. This supports tools that may create e.g. socket files in the project source directory. z>Ignoring special file error '%s' encountered copying %s to %s.N)r shutilSpecialFileErrorloggerwarningstrr)srcdester0r0r1_copy2_ignoring_special_filessrYcs`tj|}tj|tj|fdd}t|dd}tsLt|d<tj |f|dS)Ncs6g}|kr|ddg7}tj|kr2|g7}|S)Nz.toxz.nox)osr=abspath)dnamesskipped)sourcetarget_basenametarget_dirnamer0r1r$s   z!_copy_source_tree..ignoreT)r$r%r') rZr=r[basenamedirnamedictrrYrQcopytree)r_targettarget_abspathr$kwargsr0)r_r`rar1_copy_source_trees    ricCsJd}|rt|||}|r|}n|j}|r2||t|d}t||S)z,Get file and optionally check its hash. Nr)rF file_pathcheck_against_pathrGrHr<)r8rKrLrNrOr>r0r0r1 get_file_urls   rlcCs|jrt||dS|r@tj|r0t|t|j|dS|j rVt |||d}nt ||||d}|j s|t |j||j|S)a_Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. N)rL)is_vcsr;is_existing_dirrZr=isdirrrirjis_filerlrPis_wheelrr>)r8r9rJrKrLfiler0r0r1 unpack_urls$   rsc Csj||}tj||j}t|d }x|jD]}||q,WWdQRX|rV||||jj ddfS)z6Download link url into temp_dir using provided sessionwbNz content-type) rZr=joinfilenameopenchunkswriterkresponseheadersget)r8rJrMrLdownloadrj content_filechunkr0r0r1rIs   rIcCsntj||j}tj|s dStd||rjy||Wn*tk rht d|t |dSX|S)z Check download_dir for previously downloaded file with correct hash If a correct file is found return its path else None NzFile was already downloaded %sz;Previously-downloaded file %s has bad hash. Re-downloading.) rZr=rvrwexistsrSinforkrrTunlink)r8rKrL download_pathr0r0r1rF#s   rFcs^eZdZdZfddZeddZddZdd Zd d Z dd dZ ddZ ddZ Z S)RequirementPreparerzPrepares a Requirement c sNtt|||_||_||_||_||_||_||_ ||_ | |_ | |_ dS)N) superrr@src_dir build_dirr,rJr-rKwheel_download_dirr.require_hashes use_user_site) r?rrKrrr.r,rJr-rr) __class__r0r1r@AszRequirementPreparer.__init__cCs:|js dStj|jrdStdtd|jdS)NFTz!Could not find download directoryz0Could not find or access download directory '{}')rKrZr=rrScriticalrformat)r?r0r0r1_download_should_savens z)RequirementPreparer._download_should_savecCs8|jjr"|jj}tdt|ntd|jp0|dS)zLog the way the link prepared.z Processing %sz Collecting %sN)r8rprjrSrrr+)r?r+r=r0r0r1_log_preparing_link|sz'RequirementPreparer._log_preparing_linkcCsZ|jjr dS|jdkst|j|jd|dtjtj |jdrVt d ||jdS)z1Ensure source_dir of a linked InstallRequirement.NT) autodeleteparallel_buildszsetup.pyzpip can't proceed with requirements '{}' due to apre-existing build directory ({}). This is likely due to a previous installation that failed . pip is being responsible and not assuming it can delete this. Please delete it and try again.) r8rq source_dirr6ensure_has_source_dirrrZr=rrvr r)r?r+rKrr0r0r1_ensure_link_req_src_dirsz,RequirementPreparer._ensure_link_req_src_dircCsX|js|jddS|jjr t|jr0t|jdkrF|jsFt |jddpVt S)NT)trust_internetF) rrLr8rmr rnr original_link is_pinnedrr )r?r+r0r0r1_get_linked_req_hashess  z*RequirementPreparer._get_linked_req_hashesFc CsL|js t|j}|||jr.|jr.|j}n|j}t||||y t||j |j || |d}Wn4t k r}zt d|||Wdd}~XYnX|r|j|_t||j|j|j}|r"|rtdnF|r"tj||j}tj|s"t|j|t|} td| |jr>|j r>|!|jWdQRX|S)z3Prepare a requirement to be obtained from req.link.)rLzDCould not install requirement {} because of HTTP error {} for URL {}Nz*Link is a directory, ignoring download_dirzSaved %s)"r8r6rrqrrKrrrsrrJrr rrr=local_file_pathr2r,r-r.rnrSrrZrvrwrrQcopyrrrmarchive) r?r+rr8rK local_fileexcr/download_locationrr0r0r1prepare_linked_requirementsD        z.RequirementPreparer.prepare_linked_requirementc Cs|jstdtd|tf|jr6td|||j | |j t ||j |j|j}|j rv||j||jWdQRX|S)z(Prepare an editable requirement z-cannot prepare a non-editable req as editablez Obtaining %szoThe editable requirement {} cannot be installed when requiring hashes, because there is no single file to hash.N)editabler6rSrrrrrrrupdate_editablerr2r,r-r.rrKcheck_if_existsr)r?r+r/r0r0r1prepare_editable_requirements   z0RequirementPreparer.prepare_editable_requirementc Csh|jstd|dk s&td|jtd|||jjt|jrRtdt |}WdQRX|S)z1Prepare an already-installed requirement z(req should have been satisfied but isn'tNzAdid not get skip reason skipped but req.satisfied_by is set to {}zRequirement %s: %s (%s)zSince it is already installed, we are trusting this package without checking its hash. To ensure a completely repeatable environment, install into an empty virtualenv.) satisfied_byr6rrSrversionrrdebugr)r?r+ skip_reasonr/r0r0r1prepare_installed_requirements  z1RequirementPreparer.prepare_installed_requirement)F)rArBrC__doc__r@propertyrrrrrrr __classcell__r0r0)rr1r=s -  ! 4r)NN)NN)NN)KrloggingrGrZrQZpip._vendor.sixrpip._internal.distributionsr%pip._internal.distributions.installedrpip._internal.exceptionsrrrrr r r pip._internal.utils.filesystemr pip._internal.utils.hashesr pip._internal.utils.loggingrpip._internal.utils.miscrrrrpip._internal.utils.temp_dirrpip._internal.utils.typingrpip._internal.utils.unpackingrpip._internal.vcsrtypingrrrrZmypy_extensionsrr"pip._internal.index.package_finderrpip._internal.models.linkrpip._internal.network.downloadrZpip._internal.req.req_installr pip._internal.req.req_trackerr!r"rUboolr# getLoggerrArSr2r;objectr<rPrYrirlrsrIrFrr0r0r0r1sl   $                   " " +operations/__pycache__/check.cpython-37.pyc000064400000007111152352421750014651 0ustar00B Rex@s,dZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z eeZe rdd lmZdd lmZmZmZmZmZmZmZeed fZeeefZeeeefZeeeefZeeeefZ eee fZ!eee!fZ"ed d d gZ#ddZ$dddZ%ddZ&ddZ'ddZ(dS)z'Validation of dependencies of packages N) namedtuple)canonicalize_name)RequirementParseError))make_distribution_for_install_requirement)get_installed_distributions)MYPY_CHECK_RUNNING)InstallRequirement)AnyCallableDictOptionalSetTupleListPackageDetailsversionrequiresc Ks|ikrddd}i}d}xntf|D]`}t|j}yt|j|||<Wq&ttfk r}zt d||d}Wdd}~XYq&Xq&W||fS)z8Converts a list of distributions into a PackageSet. F) local_onlyskipz%Error parsing requirements for %s: %sTN) rr project_namerrrOSErrorrloggerwarning)kwargs package_setproblemsdistnameerr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/check.py!create_package_set_from_installed%s  r!c Csi}i}x|D]}t}t}|r,||r,qxz||jD]l}t|j}||krzd} |jdk rf|j} | r8|||fq8||j} |jj | dds8||| |fq8W|rt |t d||<|rt |t d||<qW||fS)zCheck if a package set is consistent If should_ignore is passed, it should be a callable that takes a package name and returns a boolean. TN) prereleases)key) setrrrmarkerevaluateaddr specifiercontainssortedstr) r should_ignoremissing conflicting package_name missing_depsconflicting_depsreqrmissedrrrr check_package_set:s0      r4cs6t\}}t||}t|||t|fdddfS)zeFor checking if the dependency graph would be consistent after installing given requirements cs|kS)Nr)r) whitelistrr vz)check_install_conflicts..)r,)r!_simulate_installation_of_create_whitelistr4) to_installr_would_be_installedr)r5r check_install_conflictsfs    r=cCs\t}xP|D]H}t|}|}|dk s,tt|j}t|j|||<| |q W|S)zBComputes the version of packages after installing to_install. N) r$rget_pkg_resources_distributionAssertionErrorrr#rrrr')r:r installedinst_req abstract_distrrrrr r8{s   r8cCsRt|}xD|D]<}||krqx,||jD]}t|j|kr(||Pq(WqW|S)N)r$rrrr')r<rpackages_affectedr/r2rrr r9s   r9)N))__doc__logging collectionsrZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrpip._internal.distributionsrpip._internal.utils.miscrpip._internal.utils.typingr getLogger__name__rZpip._internal.req.req_installrtypingr r r r r rrr+Z PackageSetZMissingZ ConflictingZ MissingDictZConflictingDictZ CheckResultZConflictDetailsrr!r4r=r8r9rrrr s0        $     ,operations/build/__pycache__/wheel.cpython-37.pyc000064400000002521152352421750015777 0ustar00B Re@s^ddlZddlZddlmZddlmZerHddlmZmZddl m Z e e Z ddZdS)N)runner_with_spinner_message)MYPY_CHECK_RUNNING)ListOptional)Pep517HookCallerc Cs|dk s t|r td|dSyBtd|td|}|||j||d}WdQRXWn tk rtd|dSXt j ||S)zBuild one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. NzFCannot build wheel for %s using PEP 517 when --build-option is presentzDestination directory: %szBuilding wheel for {} (PEP 517))metadata_directoryzFailed building wheel for %s) AssertionErrorloggererrordebugrformatsubprocess_runner build_wheel Exceptionospathjoin)namebackendr build_optionstempdrunner wheel_namer/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/build/wheel.pybuild_wheel_pep517s"     r)loggingrpip._internal.utils.subprocessrpip._internal.utils.typingrtypingrrpip._vendor.pep517.wrappersr getLogger__name__r rrrrrs    operations/build/__pycache__/metadata_legacy.cpython-37.pyc000064400000003700152352421750017777 0ustar00B Re@s~dZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z e r`ddl mZeeZd d Zd d ZdS) z;Metadata generation logic for legacy source distributions. N)InstallationError)make_setuptools_egg_info_args)call_subprocess) TempDirectory)MYPY_CHECK_RUNNING)BuildEnvironmentcCsRddt|D}|s&td|t|dkr@td|tj||dS)z3Find an .egg-info subdirectory in `directory`. cSsg|]}|dr|qS)z .egg-info)endswith).0fr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/build/metadata_legacy.py sz"_find_egg_info..z"No .egg-info directory found in {}z-More than one .egg-info directory found in {}r)oslistdirrformatlenpathjoin) directory filenamesr r r _find_egg_infos  rc CsPtd||tdddj}t|||d}|t||ddWdQRXt|S) znGenerate metadata using setup.py-based defacto mechanisms. Returns the generated metadata directory. z2Running setup.py (path:%s) egg_info for package %sz pip-egg-infoT)kindglobally_managed) egg_info_dirno_user_configzpython setup.py egg_info)cwd command_descN)loggerdebugrrrrr) build_env setup_py_path source_dirisolateddetailsrargsr r r generate_metadata*s  r&)__doc__loggingrpip._internal.exceptionsr$pip._internal.utils.setuptools_buildrpip._internal.utils.subprocessrpip._internal.utils.temp_dirrpip._internal.utils.typingrpip._internal.build_envr getLogger__name__rrr&r r r r s       operations/build/__pycache__/metadata.cpython-37.pyc000064400000002272152352421750016456 0ustar00B Re@sXdZddlZddlmZddlmZddlmZerLddlm Z ddl m Z dd Z dS) z4Metadata generation logic for source distributions. N)runner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING)BuildEnvironment)Pep517HookCallerc CsXtddd}|j}|.td}||||}WdQRXWdQRXtj||S)zlGenerate metadata using mechanisms described in PEP 517. Returns the generated metadata directory. zmodern-metadataT)kindglobally_managedzPreparing wheel metadataN)rpathrsubprocess_runner prepare_metadata_for_build_wheelosjoin) build_envbackendmetadata_tmpdir metadata_dirrunner distinfo_dirr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/build/metadata.pygenerate_metadatas  r) __doc__r pip._internal.utils.subprocessrpip._internal.utils.temp_dirrpip._internal.utils.typingrpip._internal.build_envrpip._vendor.pep517.wrappersrrrrrrs     operations/build/__pycache__/__init__.cpython-37.pyc000064400000000355152352421750016435 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/build/__init__.pyoperations/build/__pycache__/wheel_legacy.cpython-37.pyc000064400000005043152352421750017325 0ustar00B Re @sddlZddlZddlmZddlmZddlmZm Z m Z ddl m Z e r`ddl mZmZmZeeZddZd d Zd d ZdS) N) open_spinner) make_setuptools_bdist_wheel_args) LOG_DIVIDERcall_subprocessformat_command_args)MYPY_CHECK_RUNNING)ListOptionalTextcCs^t|}d|}|s |d7}n:ttjkr8|d7}n"|dsJ|d7}|d|t7}|S)z'Format command information for logging.zCommand arguments: {} zCommand output: Nonez'Command output: [use --verbose to show] zCommand output: {}{})rformatloggergetEffectiveLevelloggingDEBUGendswithr) command_argscommand_output command_desctextr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/build/wheel_legacy.pyformat_command_results    rcCstt|}|s2d|}|t||7}t|dSt|dkrbd||}|t||7}t|tj||dS)z>Return the path to the wheel in the temporary build directory.z1Legacy build of wheel for {!r} created no files. NzZLegacy build of wheel for {!r} created more than one file. Filenames (choosing first): {} r) sortedr rr warninglenospathjoin)namestemp_dirnamerrmsgrrrget_legacy_build_wheel_path*s    r$c Cst||||d}d|}t|l}td|yt|||d} Wn*tk rl|dtd|dSXt |} t | |||| d} | SQRXdS) zBuild one unpacked package using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. )global_options build_optionsdestination_dirz Building wheel for {} (setup.py)zDestination directory: %s)cwdspinnererrorzFailed building wheel for %sN)r r!r"rr) rr rr debugr Exceptionfinishr*rlistdirr$) r" setup_py_path source_dirr%r&tempd wheel_args spin_messager)outputr wheel_pathrrrbuild_wheel_legacyHs2        r6)ros.pathrpip._internal.cli.spinnersr$pip._internal.utils.setuptools_buildrpip._internal.utils.subprocessrrrpip._internal.utils.typingrtypingrr r getLogger__name__r rr$r6rrrrs    operations/build/wheel_legacy.py000064400000006434152352421750013045 0ustar00import logging import os.path from pip._internal.cli.spinners import open_spinner from pip._internal.utils.setuptools_build import ( make_setuptools_bdist_wheel_args, ) from pip._internal.utils.subprocess import ( LOG_DIVIDER, call_subprocess, format_command_args, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Text logger = logging.getLogger(__name__) def format_command_result( command_args, # type: List[str] command_output, # type: Text ): # type: (...) -> str """Format command information for logging.""" command_desc = format_command_args(command_args) text = 'Command arguments: {}\n'.format(command_desc) if not command_output: text += 'Command output: None' elif logger.getEffectiveLevel() > logging.DEBUG: text += 'Command output: [use --verbose to show]' else: if not command_output.endswith('\n'): command_output += '\n' text += 'Command output:\n{}{}'.format(command_output, LOG_DIVIDER) return text def get_legacy_build_wheel_path( names, # type: List[str] temp_dir, # type: str name, # type: str command_args, # type: List[str] command_output, # type: Text ): # type: (...) -> Optional[str] """Return the path to the wheel in the temporary build directory.""" # Sort for determinism. names = sorted(names) if not names: msg = ( 'Legacy build of wheel for {!r} created no files.\n' ).format(name) msg += format_command_result(command_args, command_output) logger.warning(msg) return None if len(names) > 1: msg = ( 'Legacy build of wheel for {!r} created more than one file.\n' 'Filenames (choosing first): {}\n' ).format(name, names) msg += format_command_result(command_args, command_output) logger.warning(msg) return os.path.join(temp_dir, names[0]) def build_wheel_legacy( name, # type: str setup_py_path, # type: str source_dir, # type: str global_options, # type: List[str] build_options, # type: List[str] tempd, # type: str ): # type: (...) -> Optional[str] """Build one unpacked package using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. """ wheel_args = make_setuptools_bdist_wheel_args( setup_py_path, global_options=global_options, build_options=build_options, destination_dir=tempd, ) spin_message = 'Building wheel for {} (setup.py)'.format(name) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) try: output = call_subprocess( wheel_args, cwd=source_dir, spinner=spinner, ) except Exception: spinner.finish("error") logger.error('Failed building wheel for %s', name) return None names = os.listdir(tempd) wheel_path = get_legacy_build_wheel_path( names=names, temp_dir=tempd, name=name, command_args=wheel_args, command_output=output, ) return wheel_path operations/build/wheel.py000064400000002671152352421750011520 0ustar00import logging import os from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional from pip._vendor.pep517.wrappers import Pep517HookCaller logger = logging.getLogger(__name__) def build_wheel_pep517( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str build_options, # type: List[str] tempd, # type: str ): # type: (...) -> Optional[str] """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. """ assert metadata_directory is not None if build_options: # PEP 517 does not support --build-options logger.error('Cannot build wheel for %s using PEP 517 when ' '--build-option is present', name) return None try: logger.debug('Destination directory: %s', tempd) runner = runner_with_spinner_message( 'Building wheel for {} (PEP 517)'.format(name) ) with backend.subprocess_runner(runner): wheel_name = backend.build_wheel( tempd, metadata_directory=metadata_directory, ) except Exception: logger.error('Failed building wheel for %s', name) return None return os.path.join(tempd, wheel_name) operations/build/metadata_legacy.py000064400000003733152352421750013520 0ustar00"""Metadata generation logic for legacy source distributions. """ import logging import os from pip._internal.exceptions import InstallationError from pip._internal.utils.setuptools_build import make_setuptools_egg_info_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._internal.build_env import BuildEnvironment logger = logging.getLogger(__name__) def _find_egg_info(directory): # type: (str) -> str """Find an .egg-info subdirectory in `directory`. """ filenames = [ f for f in os.listdir(directory) if f.endswith(".egg-info") ] if not filenames: raise InstallationError( "No .egg-info directory found in {}".format(directory) ) if len(filenames) > 1: raise InstallationError( "More than one .egg-info directory found in {}".format( directory ) ) return os.path.join(directory, filenames[0]) def generate_metadata( build_env, # type: BuildEnvironment setup_py_path, # type: str source_dir, # type: str isolated, # type: bool details, # type: str ): # type: (...) -> str """Generate metadata using setup.py-based defacto mechanisms. Returns the generated metadata directory. """ logger.debug( 'Running setup.py (path:%s) egg_info for package %s', setup_py_path, details, ) egg_info_dir = TempDirectory( kind="pip-egg-info", globally_managed=True ).path args = make_setuptools_egg_info_args( setup_py_path, egg_info_dir=egg_info_dir, no_user_config=isolated, ) with build_env: call_subprocess( args, cwd=source_dir, command_desc='python setup.py egg_info', ) # Return the .egg-info directory. return _find_egg_info(egg_info_dir) operations/build/metadata.py000064400000002346152352421750012173 0ustar00"""Metadata generation logic for source distributions. """ import os from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from pip._internal.build_env import BuildEnvironment from pip._vendor.pep517.wrappers import Pep517HookCaller def generate_metadata(build_env, backend): # type: (BuildEnvironment, Pep517HookCaller) -> str """Generate metadata using mechanisms described in PEP 517. Returns the generated metadata directory. """ metadata_tmpdir = TempDirectory( kind="modern-metadata", globally_managed=True ) metadata_dir = metadata_tmpdir.path with build_env: # Note that Pep517HookCaller implements a fallback for # prepare_metadata_for_build_wheel, so we don't have to # consider the possibility that this hook doesn't exist. runner = runner_with_spinner_message("Preparing wheel metadata") with backend.subprocess_runner(runner): distinfo_dir = backend.prepare_metadata_for_build_wheel( metadata_dir ) return os.path.join(metadata_dir, distinfo_dir) operations/build/__init__.py000064400000000000152352421750012133 0ustar00operations/install/__pycache__/wheel.cpython-37.pyc000064400000050516152352421750016355 0ustar00B ReNz@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZmZddlmZddlmZddlmZdd lmZdd lmZmZmZm Z m!Z!m"Z"dd l#m$Z$m%Z%dd l&m'Z'dd l(m)Z)ddl*m+Z+m,Z,ddl-m.Z.ddl/m0Z0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:m;Z;mm?Z?m@Z@e8sddl7mAZAnddlBmCZCddlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmAZAddlmSZSddlTmUZUddl-mVZVddl/mWZWeLde"ZXeQeXeYeReZeYffZ[GdddeNZ\e]e^Z_dJd d!Z`d"d#Zad$d%Zbd&d'Zcd(d)Zdd*d+Zed,d-Zfd.d/ZgdKd0d1Zhd2d3Zid4d5Zjd6d7ZkGd8d9d9elZmGd:d;d;elZnGdd?ZpGd@dAdAeZqdLdDdEZrejsdFdGZtdMdHdIZudS)NzGSupport for installing and building the "wheel" binary package format. )absolute_importN)urlsafe_b64encode)chainstarmap)ZipFile) pkg_resources) ScriptMaker)get_export_entry)PY2 ensure_str ensure_text itervaluesreraise text_type) filterfalsemap)InstallationError)get_major_minor_version)DIRECT_URL_METADATA_NAME DirectUrl) SCHEME_KEYS)adjacent_tmp_filereplace)captured_stdout ensure_dir hash_file partition)MYPY_CHECK_RUNNING) current_umaskis_within_directory2set_extracted_file_to_default_mode_plus_executablezip_item_is_executable) parse_wheel$pkg_resources_distribution_for_wheel)cast)Message)AnyCallableDictIOIterableIteratorListNewTypeOptionalProtocolSequenceSetTupleUnionr$)ZipInfo) Distribution)Scheme)NamedTemporaryFileResult RecordPathc@s eZdZdZdZdZddZdS)FileNcCsdS)N)selfr:r:/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.pysave`sz File.save)__name__ __module__ __qualname__src_record_path dest_pathchangedr=r:r:r:r<r9[sr9cCs6t||\}}dt|dd}|t|fS)z?Return (encoded_digest, length) for path using hashlib.sha256()zsha256=latin1=)rrdigestdecoderstripstr)path blocksizehlengthrGr:r:r<rehashhs  rOcCs"trdd|iS|dddSdS)zPReturn keyword arguments to properly open a CSV file in the given mode. modez{}bzutf-8)rPnewlineencodingN)r format)rPr:r:r< csv_io_kwargsssrUc Cstj|stt|dH}|}|ds2dStj t }d|tj d}| }WdQRXt|d}| || |WdQRXdS) zQReplace #!python with #!/path/to/python Return True if file was changed. rbs#!pythonFs#!asciiNwbT)osrKisfileAssertionErroropenreadline startswithsys executableencodegetfilesystemencodinglinesepreadwrite)rKscript firstlineexenamerestr:r:r< fix_script~s    rjcCs|dddkS)NzRoot-Is-PurelibrQtrue)getlower)metadatar:r:r<wheel_root_is_purelibsrocsvy|d}|d}Wntk r0iifSXddtfdd|D}tfdd|D}||fS)Nconsole_scripts gui_scriptscSs&t|ddd}|d|dfS)z[get the string representation of EntryPoint, remove space and split on '='  rQrFr)rJrsplit)s split_partsr:r:r< _split_epsz"get_entrypoints.._split_epc3s|]}|VqdS)Nr:).0v)rwr:r< sz"get_entrypoints..c3s|]}|VqdS)Nr:)rxry)rwr:r<rzs) get_entry_mapKeyErrordictvalues) distributionconsoleguir:)rwr<get_entrypointss   rc s|sdStt}x2|D]*}tj|}tj|}|||qWddtj dd tj D tj tjtjfdd|D}|sdSg}xn|D]b\}}t|}t|dkrd |d } n$d d |dd d|d } | d| |qWd} t|dkr8| | dn| | dtddtj dd tj D} | rd} | | d|S)zDetermine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. NcSs g|]}tj|tjqSr:)rYrKnormcaserIsep)rxir:r:r< sz5message_about_scripts_not_on_PATH..PATHrQcs&i|]\}}tj|kr||qSr:)rYrKr)rx parent_dirscripts) not_warn_dirsr:r< sz5message_about_scripts_not_on_PATH..rsz script {} isrzscripts {} arez, z and z.The {} installed in '{}' which is not on PATH.zeConsider adding {} to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.zthis directoryzthese directoriescss|]}|r|ddkVqdS)r~Nr:)rxrr:r:r<rzsz4message_about_scripts_not_on_PATH..ziNOTE: The current PATH contains path(s) starting with `~`, which may not be expanded by all applications. ) collections defaultdictsetrYrKdirnamebasenameaddenvironrlrtpathsepappendrr_r`itemssortedlenrTjoinany) rgrouped_by_dirdestfiler script_namewarn_for msg_lines dir_scriptssorted_scripts start_text last_line_fmtwarn_for_tildetilde_warning_msgr:)rr<!message_about_scripts_not_on_PATHsD        " rcCstdd|DS)aNormalize the given rows of a RECORD file. Items in each row are converted into str. Rows are then sorted to make the value more predictable for tests. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. css*|]"\}}}t|dd|t|fVqdS)zutf-8)rSN)r rJ)rx record_pathhash_sizer:r:r<rz sz&_normalized_outrows..)r)outrowsr:r:r<_normalized_outrowssrcCs|S)Nr:)rr:r:r<_record_to_fs_pathsrcCsX|dk r>tj|dtj|dkr>tj||}|tjjd}td|S)Nr/r8)rYrK splitdrivermrelpathrrr$)rK relative_tor:r:r<_fs_to_record_paths rcCst|dd}td|S)Nzutf-8)rSr8)r r$) record_columnpr:r:r<_parse_record_path#s rcCsg}x|D]}t|dkr&td|t|d}|||}||krXtt|\} } n0t|dkrl|dnd} t|dkr|dnd} ||| | fq Wx2|D]*} t| |} t| \} } || | | fqWx t |D]} || ddfqW|S)z_ :param installed: A map from archive RECORD path to installation RECORD path. z,RECORD line has more than three elements: %srrsrQ) rloggerwarningrpoprOrrrr ) old_csv_rows installedrC generatedlib_dirinstalled_rowsrowold_record_pathnew_record_pathrGrNfrKinstalled_record_pathr:r:r<get_csv_rows_for_installed)s$         rcCs |}g}|dd}|rdtjkr4|d|tjdddkr^|dtjd||dt |d d |D}x|D] }||=qW|d d}|rdtjkr|d ||d t |dd |D}x|D] }||=qW| t dj| |S)zk Given the mapping from entrypoint name to callable, return the relevant console script specs. pipNENSUREPIP_OPTIONSzpip = rQ altinstallz pip{} = {}rcSsg|]}td|r|qS)zpip(\d(\.\d)?)?$)rematch)rxkr:r:r<rsz,get_console_script_specs.. easy_installzeasy_install = zeasy_install-{} = {}cSsg|]}td|r|qS)zeasy_install(-\d\.\d)?$)rr)rxrr:r:r<rsz{} = {}) copyrrYrrrlrTr_ version_inforextendrr)rscripts_to_generate pip_scriptpip_epreasy_install_scripteasy_install_epr:r:r<get_console_script_specsJs6#          rc@s$eZdZddZddZddZdS) ZipBackedFilecCs||_||_||_d|_dS)NF)rArB _zip_filerC)r;rArBzip_filer:r:r<__init__szZipBackedFile.__init__cCs&ts|j|jS|j|jdS)Nzutf-8)r rgetinforAra)r;r:r:r<_getinfoszZipBackedFile._getinfoc Cstj|j}t|tj|jr0t|j|}|j |*}t |jd}t ||WdQRXWdQRXt |rt |jdS)NrX)rYrKrrBrexistsunlinkrrr\shutil copyfileobjr!r )r;rzipinfordestr:r:r<r=s   zZipBackedFile.saveN)r>r?r@rrr=r:r:r:r<rs rc@seZdZddZddZdS) ScriptFilecCs$||_|jj|_|jj|_d|_dS)NF)_filerArBrC)r;filer:r:r<rs  zScriptFile.__init__cCs|jt|j|_dS)N)rr=rjrBrC)r;r:r:r<r=s zScriptFile.saveN)r>r?r@rr=r:r:r:r<rsrcseZdZfddZZS)MissingCallableSuffixcstt|d|dS)NzInvalid script entry point: {} - A callable suffix is required. Cf https://packaging.python.org/specifications/entry-points/#use-for-scripts for more information.)superrrrT)r; entry_point) __class__r:r<rs zMissingCallableSuffix.__init__)r>r?r@r __classcell__r:r:)rr<rsrcCs*t|}|dk r&|jdkr&tt|dS)N)r suffixrrJ) specificationentryr:r:r<_raise_for_invalid_entrypointsrcseZdZdfdd ZZS)PipScriptMakerNcst|tt|||S)N)rrrmake)r;roptions)rr:r<rszPipScriptMaker.make)N)r>r?r@rrr:r:)rr<rsrTFc: st|\}} t| r|jn|jitg} d-fdd } fdd} dd} fdd fd d }fd d }dd}| }t| |}t||\}}|tt d}t ||}dd}t||\}}||}t ||}t ||}t |}t |\fdd}t ||}t||}t t|}t ||}x(|D] }|| |j|j|jqLWfdd} dd}!|r|4?}5t@|5| d+}6tj5|.d*}7|-|7ftAd)$}8t=Btd,|8}9|9CtD|6WdQRXdS).aInstall a wheel. :param name: Name of the project to install :param wheel_zip: open ZipFile for wheel being installed :param scheme: Distutils scheme dictating the install directories :param req_description: String used in place of the requirement, for logging :param pycompile: Whether to byte-compile installed Python files :param warn_script_location: Whether to check that scripts are installed into a directory on PATH :raises UnsupportedWheel: * when the directory holds an unpacked wheel with incompatible Wheel-Version * when the .dist-info dir does not match the wheel Fcs(t|}||<|r$t|dS)z6Map archive RECORD paths to installation RECORD paths.N)rr)srcfilermodifiednewpath)rCrrr:r<record_installeds z(_install_wheel..record_installedc3s0}tt|}x|D]}td|VqWdS)Nr8)namelistrr r$)names decoded_namesname) wheel_zipr:r< all_paths&s  z!_install_wheel..all_pathscSs |dS)Nr)endswith)rKr:r:r< is_dir_path/sz#_install_wheel..is_dir_pathcs$t||s d}t|||dS)NzRThe wheel {!r} has a file {!r} trying to install outside the target directory {!r})rrrT) dest_dir_path target_pathmessage) wheel_pathr:r<assert_no_path_traversal3s z0_install_wheel..assert_no_path_traversalcsfdd}|S)Ncs0tj|}tj|}|t||S)N)rYrKnormpathrr)r normed_pathrB)rrrr:r<make_root_scheme_file@s  zM_install_wheel..root_scheme_file_maker..make_root_scheme_filer:)rrr)r)rrr<root_scheme_file_maker>sz._install_wheel..root_scheme_file_makercsJix.tD]&}t|}tt||td|<q Wfdd}|S)N)rSc stj|}y|tjjd\}}}Wn(tk rNd|}t|YnXy |}Wn:tk rd t }d|||}t|YnXtj ||}||t ||S)NrzbUnexpected file in {}: {!r}. .data directory contents should be named like: '/'.z, zUnknown scheme key used in {}: {} (for file {!r}). .data directory contents should be in subdirectories named with a valid scheme key ({})) rYrKrrtr ValueErrorrTrr|rrr) rr_ scheme_key dest_subpathr scheme_pathvalid_scheme_keysrB)r scheme_pathsrrr:r<make_data_scheme_fileRs"    zM_install_wheel..data_scheme_file_maker..make_data_scheme_file)rr getattrr_rb)rschemekey encoded_keyr)rr)r rr<data_scheme_file_makerIs z._install_wheel..data_scheme_file_makercSs|ddddS)Nrrsrz.data)rtr)rKr:r:r<is_data_scheme_pathqsz+_install_wheel..is_data_scheme_path)rScSs2|dd}t|dko0|ddo0|ddkS)Nrrrz.datarsr)rtrr)rKpartsr:r:r<is_script_scheme_paths  z-_install_wheel..is_script_scheme_pathcsz|j}tj|}|dr.|dd}n<|drJ|dd}n |drf|dd}n|}|kpx|kS)Nz.exez -script.pyiz.pya)rBrYrKrrmr)rrKr matchname)rrr:r<is_entrypoint_wrappers z-_install_wheel..is_entrypoint_wrapperc3sLxFttD]2}tj|}tj|s2q|ds>q|VqWdS)Nz.py)rrr~rYrKrrZr)installed_pathfull_installed_path)rrr:r<pyc_source_file_pathss  z-_install_wheel..pyc_source_file_pathscSs.trtjjr|dS|dSn tj|SdS)zAReturn the path the pyc file would have been written to. ocN)r r_flagsoptimize importlibutilcache_from_source)rKr:r:r<pyc_output_paths  z'_install_wheel..pyc_output_pathignoreT)forcequietr8rNrQz{} = {}ric ;s<t|f| }|VWdQRXt|jt|j|dS)N)rrYchmodrr)rKkwargsr)generated_file_moder:r<_generate_filesz&_install_wheel.._generate_file INSTALLERspip zutf-8 REQUESTEDwRECORD)rrCrrzIO[str])F)Er"ropurelibplatlibrrrr r_rbrrr#rrr=rArBrCrwarningscatch_warningsfilterwarningsr compileall compile_filerYrKrr[r$rrrdebuggetvaluerrclobbervariantsset_moderlistrrTr make_multiplerrrr contextlibcontextmanagerrrerrto_jsonrar\ get_metadatacsvreader splitlinesrrUwriter writerowsr):rrrr pycompilewarn_script_location direct_url requestedinfo_dirrnrrrrrrrpaths file_pathsroot_scheme_pathsdata_scheme_pathsrfilesrother_scheme_pathsscript_scheme_pathsrother_scheme_filesrrscript_scheme_filesrrr$stdoutrKpath_argsuccesspyc_pathpyc_record_pathmakerrgui_scripts_to_generategenerated_console_scriptsmsgr+ dest_info_dirinstaller_pathinstaller_filedirect_url_pathdirect_url_filerequested_path record_text record_rowsrowsr record_filerEr:) rrCrr*rrrrrr<_install_wheels  (                   $               rhc cs\y dVWnLtk rV}z.d||jd}ttt|tdWdd}~XYnXdS)NzFor req: {}. {}rr)rrTargsrr_exc_info)req_descriptionerr:r:r<req_error_context;s  rmc CsHt|dd2}t|t||||||||dWdQRXWdQRXdS)NT) allowZip64)rrrrrGrHrIrJ)rrmrh) rrrrkrGrHrIrJzr:r:r< install_wheelGs  rp)rD)N)TTNF)TTNF)v__doc__ __future__rrr5r>rBr!loggingos.pathrYrrr_r2base64r itertoolsrrzipfiler pip._vendorrpip._vendor.distlib.scriptsrZpip._vendor.distlib.utilr Zpip._vendor.sixr r r r rrpip._vendor.six.movesrrpip._internal.exceptionsrpip._internal.locationsrpip._internal.models.direct_urlrrpip._internal.models.schemerpip._internal.utils.filesystemrrpip._internal.utils.miscrrrrpip._internal.utils.typingrpip._internal.utils.unpackingrrr r!pip._internal.utils.wheelr"r#r$ email.messager%typingr&r'r(r)r*r+r,r-r.r/r0r1r2r3r4Zpip._vendor.pkg_resourcesr5r6r7r8rJintZInstalledCSVRowr9 getLoggerr>rrOrUrjrorrrrrrrrobjectrrrrrrhr?rmrpr:r:r:r<s            D        G !V.   @operations/install/__pycache__/editable_legacy.cpython-37.pyc000064400000002525152352421750020343 0ustar00B Re@svdZddlZddlmZddlmZddlmZddlm Z e r`ddl m Z m Z m Z ddlmZeeZd d ZdS) z?Legacy editable installation process, i.e. `setup.py develop`. N) indent_log)make_setuptools_develop_args)call_subprocess)MYPY_CHECK_RUNNING)ListOptionalSequence)BuildEnvironmentc CsTtd|t|||||||d} t"|t| | dWdQRXWdQRXdS)z[Install a package in editable mode. Most arguments are pass-through to setuptools. zRunning setup.py develop for %s)global_optionsinstall_optionsno_user_configprefixhome use_user_site)cwdN)loggerinforrr) r r r rrname setup_py_pathisolated build_envunpacked_source_directoryargsr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/install/editable_legacy.pyinstall_editables r)__doc__loggingpip._internal.utils.loggingr$pip._internal.utils.setuptools_buildrpip._internal.utils.subprocessrpip._internal.utils.typingrtypingrrrpip._internal.build_envr getLogger__name__rrrrrrs      operations/install/__pycache__/legacy.cpython-37.pyc000064400000006123152352421750016510 0ustar00B Re@sdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZerdd lmZmZmZdd lmZdd lmZeeZGdddeZ ddZ!dS)z6Legacy installation process, i.e. `setup.py install`. N) change_root)InstallationError) indent_log) ensure_dir)make_setuptools_install_args)runner_with_spinner_message) TempDirectory)MYPY_CHECK_RUNNING)ListOptionalSequence)BuildEnvironment)Schemec@seZdZddZdS)LegacyInstallFailurecCst|_dS)N)sysexc_infoparent)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/install/legacy.py__init__szLegacyInstallFailure.__init__N)__name__ __module__ __qualname__rrrrrrsrcs|j}tdd}ytj|jd}t||||||||| |d }td| }t"| ||| dWdQRXWdQRXtj |st d|dSWnt k rt YnXt|}|}WdQRXWdQRXfd d }x>|D]$}tj|}|d r||}PqWd | }t|g}xH|D]@}|}tj|r\|tjj7}|tj|||q6W|t|tj|d }t|d}|d|dWdQRXdS)Nrecord)kindzinstall-record.txt) global_optionsinstall_optionsrecord_filenamerootprefix header_dirhome use_user_siteno_user_config pycompilezRunning setup.py install for {})cmdcwdzRecord file %s not foundFcs&dkstj|s|St|SdS)N)ospathisabsr)r))rrr prepend_root`szinstall..prepend_rootz .egg-infoz{} did not indicate that it installed an .egg-info directory. Only setup.py projects generating .egg-info directories are supported.zinstalled-files.txtw T)headersrr(r)joinrrformatrexistsloggerdebug Exceptionropenread splitlinesdirnameendswithrstripisdirsepappendrelpathsortrwrite)rrrr"r r#r%scheme setup_py_pathisolatedreq_name build_envunpacked_source_directoryreq_descriptionr!temp_dirr install_argsrunnerf record_linesr+line directory egg_info_dirmessage new_linesfilenameinst_files_pathr)rrinstall!sf              rT)"__doc__loggingr(rdistutils.utilrpip._internal.exceptionsrpip._internal.utils.loggingrpip._internal.utils.miscr$pip._internal.utils.setuptools_buildrpip._internal.utils.subprocessrpip._internal.utils.temp_dirrpip._internal.utils.typingr typingr r r pip._internal.build_envr pip._internal.models.schemer getLoggerrr2r4rrTrrrrs$           operations/install/__pycache__/__init__.cpython-37.pyc000064400000000447152352421750017006 0ustar00B Re3@sdZdS)z,For modules related to installing packages. N)__doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/operations/install/__init__.pyoperations/install/legacy.py000064400000010271152352421750012222 0ustar00"""Legacy installation process, i.e. `setup.py install`. """ import logging import os import sys from distutils.util import change_root from pip._internal.exceptions import InstallationError from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ensure_dir from pip._internal.utils.setuptools_build import make_setuptools_install_args from pip._internal.utils.subprocess import runner_with_spinner_message from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Sequence from pip._internal.build_env import BuildEnvironment from pip._internal.models.scheme import Scheme logger = logging.getLogger(__name__) class LegacyInstallFailure(Exception): def __init__(self): # type: () -> None self.parent = sys.exc_info() def install( install_options, # type: List[str] global_options, # type: Sequence[str] root, # type: Optional[str] home, # type: Optional[str] prefix, # type: Optional[str] use_user_site, # type: bool pycompile, # type: bool scheme, # type: Scheme setup_py_path, # type: str isolated, # type: bool req_name, # type: str build_env, # type: BuildEnvironment unpacked_source_directory, # type: str req_description, # type: str ): # type: (...) -> bool header_dir = scheme.headers with TempDirectory(kind="record") as temp_dir: try: record_filename = os.path.join(temp_dir.path, 'install-record.txt') install_args = make_setuptools_install_args( setup_py_path, global_options=global_options, install_options=install_options, record_filename=record_filename, root=root, prefix=prefix, header_dir=header_dir, home=home, use_user_site=use_user_site, no_user_config=isolated, pycompile=pycompile, ) runner = runner_with_spinner_message( "Running setup.py install for {}".format(req_name) ) with indent_log(), build_env: runner( cmd=install_args, cwd=unpacked_source_directory, ) if not os.path.exists(record_filename): logger.debug('Record file %s not found', record_filename) # Signal to the caller that we didn't install the new package return False except Exception: # Signal to the caller that we didn't install the new package raise LegacyInstallFailure # At this point, we have successfully installed the requirement. # We intentionally do not use any encoding to read the file because # setuptools writes the file using distutils.file_util.write_file, # which does not specify an encoding. with open(record_filename) as f: record_lines = f.read().splitlines() def prepend_root(path): # type: (str) -> str if root is None or not os.path.isabs(path): return path else: return change_root(root, path) for line in record_lines: directory = os.path.dirname(line) if directory.endswith('.egg-info'): egg_info_dir = prepend_root(directory) break else: message = ( "{} did not indicate that it installed an " ".egg-info directory. Only setup.py projects " "generating .egg-info directories are supported." ).format(req_description) raise InstallationError(message) new_lines = [] for line in record_lines: filename = line.strip() if os.path.isdir(filename): filename += os.path.sep new_lines.append( os.path.relpath(prepend_root(filename), egg_info_dir) ) new_lines.sort() ensure_dir(egg_info_dir) inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt') with open(inst_files_path, 'w') as f: f.write('\n'.join(new_lines) + '\n') return True operations/install/editable_legacy.py000064400000002720152352421750014053 0ustar00"""Legacy editable installation process, i.e. `setup.py develop`. """ import logging from pip._internal.utils.logging import indent_log from pip._internal.utils.setuptools_build import make_setuptools_develop_args from pip._internal.utils.subprocess import call_subprocess from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Sequence from pip._internal.build_env import BuildEnvironment logger = logging.getLogger(__name__) def install_editable( install_options, # type: List[str] global_options, # type: Sequence[str] prefix, # type: Optional[str] home, # type: Optional[str] use_user_site, # type: bool name, # type: str setup_py_path, # type: str isolated, # type: bool build_env, # type: BuildEnvironment unpacked_source_directory, # type: str ): # type: (...) -> None """Install a package in editable mode. Most arguments are pass-through to setuptools. """ logger.info('Running setup.py develop for %s', name) args = make_setuptools_develop_args( setup_py_path, global_options=global_options, install_options=install_options, no_user_config=isolated, prefix=prefix, home=home, use_user_site=use_user_site, ) with indent_log(): with build_env: call_subprocess( args, cwd=unpacked_source_directory, ) operations/install/wheel.py000064400000075116152352421750012073 0ustar00"""Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import collections import compileall import contextlib import csv import importlib import logging import os.path import re import shutil import sys import warnings from base64 import urlsafe_b64encode from itertools import chain, starmap from zipfile import ZipFile from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry from pip._vendor.six import ( PY2, ensure_str, ensure_text, itervalues, reraise, text_type, ) from pip._vendor.six.moves import filterfalse, map from pip._internal.exceptions import InstallationError from pip._internal.locations import get_major_minor_version from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl from pip._internal.models.scheme import SCHEME_KEYS from pip._internal.utils.filesystem import adjacent_tmp_file, replace from pip._internal.utils.misc import ( captured_stdout, ensure_dir, hash_file, partition, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import ( current_umask, is_within_directory, set_extracted_file_to_default_mode_plus_executable, zip_item_is_executable, ) from pip._internal.utils.wheel import ( parse_wheel, pkg_resources_distribution_for_wheel, ) # Use the custom cast function at runtime to make cast work, # and import typing.cast when performing pre-commit and type # checks if not MYPY_CHECK_RUNNING: from pip._internal.utils.typing import cast else: from email.message import Message from typing import ( Any, Callable, Dict, IO, Iterable, Iterator, List, NewType, Optional, Protocol, Sequence, Set, Tuple, Union, cast, ) from zipfile import ZipInfo from pip._vendor.pkg_resources import Distribution from pip._internal.models.scheme import Scheme from pip._internal.utils.filesystem import NamedTemporaryFileResult RecordPath = NewType('RecordPath', text_type) InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]] class File(Protocol): src_record_path = None # type: RecordPath dest_path = None # type: text_type changed = None # type: bool def save(self): # type: () -> None pass logger = logging.getLogger(__name__) def rehash(path, blocksize=1 << 20): # type: (text_type, int) -> Tuple[str, str] """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') # unicode/str python2 issues return (digest, str(length)) # type: ignore def csv_io_kwargs(mode): # type: (str) -> Dict[str, Any] """Return keyword arguments to properly open a CSV file in the given mode. """ if PY2: return {'mode': '{}b'.format(mode)} else: return {'mode': mode, 'newline': '', 'encoding': 'utf-8'} def fix_script(path): # type: (text_type) -> bool """Replace #!python with #!/path/to/python Return True if file was changed. """ # XXX RECORD hashes will need to be updated assert os.path.isfile(path) with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True def wheel_root_is_purelib(metadata): # type: (Message) -> bool return metadata.get("Root-Is-Purelib", "").lower() == "true" def get_entrypoints(distribution): # type: (Distribution) -> Tuple[Dict[str, str], Dict[str, str]] # get the entry points and then the script names try: console = distribution.get_entry_map('console_scripts') gui = distribution.get_entry_map('gui_scripts') except KeyError: # Our dict-based Distribution raises KeyError if entry_points.txt # doesn't exist. return {}, {} def _split_ep(s): # type: (pkg_resources.EntryPoint) -> Tuple[str, str] """get the string representation of EntryPoint, remove space and split on '=' """ split_parts = str(s).replace(" ", "").split("=") return split_parts[0], split_parts[1] # convert the EntryPoint objects into strings with module:function console = dict(_split_ep(v) for v in console.values()) gui = dict(_split_ep(v) for v in gui.values()) return console, gui def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scripts by the path they were installed in grouped_by_dir = collections.defaultdict(set) # type: Dict[str, Set[str]] for destfile in scripts: parent_dir = os.path.dirname(destfile) script_name = os.path.basename(destfile) grouped_by_dir[parent_dir].add(script_name) # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable))) warn_for = { parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items() if os.path.normcase(parent_dir) not in not_warn_dirs } # type: Dict[str, Set[str]] if not warn_for: return None # Format a message msg_lines = [] for parent_dir, dir_scripts in warn_for.items(): sorted_scripts = sorted(dir_scripts) # type: List[str] if len(sorted_scripts) == 1: start_text = "script {} is".format(sorted_scripts[0]) else: start_text = "scripts {} are".format( ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1] ) msg_lines.append( "The {} installed in '{}' which is not on PATH." .format(start_text, parent_dir) ) last_line_fmt = ( "Consider adding {} to PATH or, if you prefer " "to suppress this warning, use --no-warn-script-location." ) if len(msg_lines) == 1: msg_lines.append(last_line_fmt.format("this directory")) else: msg_lines.append(last_line_fmt.format("these directories")) # Add a note if any directory starts with ~ warn_for_tilde = any( i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i ) if warn_for_tilde: tilde_warning_msg = ( "NOTE: The current PATH contains path(s) starting with `~`, " "which may not be expanded by all applications." ) msg_lines.append(tilde_warning_msg) # Returns the formatted multiline message return "\n".join(msg_lines) def _normalized_outrows(outrows): # type: (Iterable[InstalledCSVRow]) -> List[Tuple[str, str, str]] """Normalize the given rows of a RECORD file. Items in each row are converted into str. Rows are then sorted to make the value more predictable for tests. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. """ # Normally, there should only be one row per path, in which case the # second and third elements don't come into play when sorting. # However, in cases in the wild where a path might happen to occur twice, # we don't want the sort operation to trigger an error (but still want # determinism). Since the third element can be an int or string, we # coerce each element to a string to avoid a TypeError in this case. # For additional background, see-- # https://github.com/pypa/pip/issues/5868 return sorted( (ensure_str(record_path, encoding='utf-8'), hash_, str(size)) for record_path, hash_, size in outrows ) def _record_to_fs_path(record_path): # type: (RecordPath) -> text_type return record_path def _fs_to_record_path(path, relative_to=None): # type: (text_type, Optional[text_type]) -> RecordPath if relative_to is not None: # On Windows, do not handle relative paths if they belong to different # logical disks if os.path.splitdrive(path)[0].lower() == \ os.path.splitdrive(relative_to)[0].lower(): path = os.path.relpath(path, relative_to) path = path.replace(os.path.sep, '/') return cast('RecordPath', path) def _parse_record_path(record_column): # type: (str) -> RecordPath p = ensure_text(record_column, encoding='utf-8') return cast('RecordPath', p) def get_csv_rows_for_installed( old_csv_rows, # type: List[List[str]] installed, # type: Dict[RecordPath, RecordPath] changed, # type: Set[RecordPath] generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to installation RECORD path. """ installed_rows = [] # type: List[InstalledCSVRow] for row in old_csv_rows: if len(row) > 3: logger.warning('RECORD line has more than three elements: %s', row) old_record_path = _parse_record_path(row[0]) new_record_path = installed.pop(old_record_path, old_record_path) if new_record_path in changed: digest, length = rehash(_record_to_fs_path(new_record_path)) else: digest = row[1] if len(row) > 1 else '' length = row[2] if len(row) > 2 else '' installed_rows.append((new_record_path, digest, length)) for f in generated: path = _fs_to_record_path(f, lib_dir) digest, length = rehash(f) installed_rows.append((path, digest, length)) for installed_record_path in itervalues(installed): installed_rows.append((installed_record_path, '', '')) return installed_rows def get_console_script_specs(console): # type: (Dict[str, str]) -> List[str] """ Given the mapping from entrypoint name to callable, return the relevant console script specs. """ # Don't mutate caller's version console = console.copy() scripts_to_generate = [] # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadata 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append('pip = ' + pip_script) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": scripts_to_generate.append( 'pip{} = {}'.format(sys.version_info[0], pip_script) ) scripts_to_generate.append( 'pip{} = {}'.format(get_major_minor_version(), pip_script) ) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append( 'easy_install = ' + easy_install_script ) scripts_to_generate.append( 'easy_install-{} = {}'.format( get_major_minor_version(), easy_install_script ) ) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console entry points specified in the wheel scripts_to_generate.extend(starmap('{} = {}'.format, console.items())) return scripts_to_generate class ZipBackedFile(object): def __init__(self, src_record_path, dest_path, zip_file): # type: (RecordPath, text_type, ZipFile) -> None self.src_record_path = src_record_path self.dest_path = dest_path self._zip_file = zip_file self.changed = False def _getinfo(self): # type: () -> ZipInfo if not PY2: return self._zip_file.getinfo(self.src_record_path) # Python 2 does not expose a way to detect a ZIP's encoding, but the # wheel specification (PEP 427) explicitly mandates that paths should # use UTF-8, so we assume it is true. return self._zip_file.getinfo(self.src_record_path.encode("utf-8")) def save(self): # type: () -> None # directory creation is lazy and after file filtering # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. parent_dir = os.path.dirname(self.dest_path) ensure_dir(parent_dir) # When we open the output file below, any existing file is truncated # before we start writing the new contents. This is fine in most # cases, but can cause a segfault if pip has loaded a shared # object (e.g. from pyopenssl through its vendored urllib3) # Since the shared object is mmap'd an attempt to call a # symbol in it will then cause a segfault. Unlinking the file # allows writing of new contents while allowing the process to # continue to use the old copy. if os.path.exists(self.dest_path): os.unlink(self.dest_path) zipinfo = self._getinfo() with self._zip_file.open(zipinfo) as f: with open(self.dest_path, "wb") as dest: shutil.copyfileobj(f, dest) if zip_item_is_executable(zipinfo): set_extracted_file_to_default_mode_plus_executable(self.dest_path) class ScriptFile(object): def __init__(self, file): # type: (File) -> None self._file = file self.src_record_path = self._file.src_record_path self.dest_path = self._file.dest_path self.changed = False def save(self): # type: () -> None self._file.save() self.changed = fix_script(self.dest_path) class MissingCallableSuffix(InstallationError): def __init__(self, entry_point): # type: (str) -> None super(MissingCallableSuffix, self).__init__( "Invalid script entry point: {} - A callable " "suffix is required. Cf https://packaging.python.org/" "specifications/entry-points/#use-for-scripts for more " "information.".format(entry_point) ) def _raise_for_invalid_entrypoint(specification): # type: (str) -> None entry = get_export_entry(specification) if entry is not None and entry.suffix is None: raise MissingCallableSuffix(str(entry)) class PipScriptMaker(ScriptMaker): def make(self, specification, options=None): # type: (str, Dict[str, Any]) -> List[str] _raise_for_invalid_entrypoint(specification) return super(PipScriptMaker, self).make(specification, options) def _install_wheel( name, # type: str wheel_zip, # type: ZipFile wheel_path, # type: str scheme, # type: Scheme pycompile=True, # type: bool warn_script_location=True, # type: bool direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool ): # type: (...) -> None """Install a wheel. :param name: Name of the project to install :param wheel_zip: open ZipFile for wheel being installed :param scheme: Distutils scheme dictating the install directories :param req_description: String used in place of the requirement, for logging :param pycompile: Whether to byte-compile installed Python files :param warn_script_location: Whether to check that scripts are installed into a directory on PATH :raises UnsupportedWheel: * when the directory holds an unpacked wheel with incompatible Wheel-Version * when the .dist-info dir does not match the wheel """ info_dir, metadata = parse_wheel(wheel_zip, name) if wheel_root_is_purelib(metadata): lib_dir = scheme.purelib else: lib_dir = scheme.platlib # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} # type: Dict[RecordPath, RecordPath] changed = set() # type: Set[RecordPath] generated = [] # type: List[str] def record_installed(srcfile, destfile, modified=False): # type: (RecordPath, text_type, bool) -> None """Map archive RECORD paths to installation RECORD paths.""" newpath = _fs_to_record_path(destfile, lib_dir) installed[srcfile] = newpath if modified: changed.add(_fs_to_record_path(destfile)) def all_paths(): # type: () -> Iterable[RecordPath] names = wheel_zip.namelist() # If a flag is set, names may be unicode in Python 2. We convert to # text explicitly so these are valid for lookup in RECORD. decoded_names = map(ensure_text, names) for name in decoded_names: yield cast("RecordPath", name) def is_dir_path(path): # type: (RecordPath) -> bool return path.endswith("/") def assert_no_path_traversal(dest_dir_path, target_path): # type: (text_type, text_type) -> None if not is_within_directory(dest_dir_path, target_path): message = ( "The wheel {!r} has a file {!r} trying to install" " outside the target directory {!r}" ) raise InstallationError( message.format(wheel_path, target_path, dest_dir_path) ) def root_scheme_file_maker(zip_file, dest): # type: (ZipFile, text_type) -> Callable[[RecordPath], File] def make_root_scheme_file(record_path): # type: (RecordPath) -> File normed_path = os.path.normpath(record_path) dest_path = os.path.join(dest, normed_path) assert_no_path_traversal(dest, dest_path) return ZipBackedFile(record_path, dest_path, zip_file) return make_root_scheme_file def data_scheme_file_maker(zip_file, scheme): # type: (ZipFile, Scheme) -> Callable[[RecordPath], File] scheme_paths = {} for key in SCHEME_KEYS: encoded_key = ensure_text(key) scheme_paths[encoded_key] = ensure_text( getattr(scheme, key), encoding=sys.getfilesystemencoding() ) def make_data_scheme_file(record_path): # type: (RecordPath) -> File normed_path = os.path.normpath(record_path) try: _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) except ValueError: message = ( "Unexpected file in {}: {!r}. .data directory contents" " should be named like: '/'." ).format(wheel_path, record_path) raise InstallationError(message) try: scheme_path = scheme_paths[scheme_key] except KeyError: valid_scheme_keys = ", ".join(sorted(scheme_paths)) message = ( "Unknown scheme key used in {}: {} (for file {!r}). .data" " directory contents should be in subdirectories named" " with a valid scheme key ({})" ).format( wheel_path, scheme_key, record_path, valid_scheme_keys ) raise InstallationError(message) dest_path = os.path.join(scheme_path, dest_subpath) assert_no_path_traversal(scheme_path, dest_path) return ZipBackedFile(record_path, dest_path, zip_file) return make_data_scheme_file def is_data_scheme_path(path): # type: (RecordPath) -> bool return path.split("/", 1)[0].endswith(".data") paths = all_paths() file_paths = filterfalse(is_dir_path, paths) root_scheme_paths, data_scheme_paths = partition( is_data_scheme_path, file_paths ) make_root_scheme_file = root_scheme_file_maker( wheel_zip, ensure_text(lib_dir, encoding=sys.getfilesystemencoding()), ) files = map(make_root_scheme_file, root_scheme_paths) def is_script_scheme_path(path): # type: (RecordPath) -> bool parts = path.split("/", 2) return ( len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts" ) other_scheme_paths, script_scheme_paths = partition( is_script_scheme_path, data_scheme_paths ) make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme) other_scheme_files = map(make_data_scheme_file, other_scheme_paths) files = chain(files, other_scheme_files) # Get the defined entry points distribution = pkg_resources_distribution_for_wheel( wheel_zip, name, wheel_path ) console, gui = get_entrypoints(distribution) def is_entrypoint_wrapper(file): # type: (File) -> bool # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools path = file.dest_path name = os.path.basename(path) if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) script_scheme_files = map(make_data_scheme_file, script_scheme_paths) script_scheme_files = filterfalse( is_entrypoint_wrapper, script_scheme_files ) script_scheme_files = map(ScriptFile, script_scheme_files) files = chain(files, script_scheme_files) for file in files: file.save() record_installed(file.src_record_path, file.dest_path, file.changed) def pyc_source_file_paths(): # type: () -> Iterator[text_type] # We de-duplicate installation paths, since there can be overlap (e.g. # file in .data maps to same location as file in wheel root). # Sorting installation paths makes it easier to reproduce and debug # issues related to permissions on existing files. for installed_path in sorted(set(installed.values())): full_installed_path = os.path.join(lib_dir, installed_path) if not os.path.isfile(full_installed_path): continue if not full_installed_path.endswith('.py'): continue yield full_installed_path def pyc_output_path(path): # type: (text_type) -> text_type """Return the path the pyc file would have been written to. """ if PY2: if sys.flags.optimize: return path + 'o' else: return path + 'c' else: return importlib.util.cache_from_source(path) # Compile all of the pyc files for the installed files if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') for path in pyc_source_file_paths(): # Python 2's `compileall.compile_file` requires a str in # error cases, so we must convert to the native type. path_arg = ensure_str( path, encoding=sys.getfilesystemencoding() ) success = compileall.compile_file( path_arg, force=True, quiet=True ) if success: pyc_path = pyc_output_path(path) assert os.path.exists(pyc_path) pyc_record_path = cast( "RecordPath", pyc_path.replace(os.path.sep, "/") ) record_installed(pyc_record_path, pyc_path) logger.debug(stdout.getvalue()) maker = PipScriptMaker(None, scheme.scripts) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = {''} # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Generate the console and GUI entry points specified in the wheel scripts_to_generate = get_console_script_specs(console) gui_scripts_to_generate = list(starmap('{} = {}'.format, gui.items())) generated_console_scripts = maker.make_multiple(scripts_to_generate) generated.extend(generated_console_scripts) generated.extend( maker.make_multiple(gui_scripts_to_generate, {'gui': True}) ) if warn_script_location: msg = message_about_scripts_not_on_PATH(generated_console_scripts) if msg is not None: logger.warning(msg) generated_file_mode = 0o666 & ~current_umask() @contextlib.contextmanager def _generate_file(path, **kwargs): # type: (str, **Any) -> Iterator[NamedTemporaryFileResult] with adjacent_tmp_file(path, **kwargs) as f: yield f os.chmod(f.name, generated_file_mode) replace(f.name, path) dest_info_dir = os.path.join(lib_dir, info_dir) # Record pip as the installer installer_path = os.path.join(dest_info_dir, 'INSTALLER') with _generate_file(installer_path) as installer_file: installer_file.write(b'pip\n') generated.append(installer_path) # Record the PEP 610 direct URL reference if direct_url is not None: direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME) with _generate_file(direct_url_path) as direct_url_file: direct_url_file.write(direct_url.to_json().encode("utf-8")) generated.append(direct_url_path) # Record the REQUESTED file if requested: requested_path = os.path.join(dest_info_dir, 'REQUESTED') with open(requested_path, "w"): pass generated.append(requested_path) record_text = distribution.get_metadata('RECORD') record_rows = list(csv.reader(record_text.splitlines())) rows = get_csv_rows_for_installed( record_rows, installed=installed, changed=changed, generated=generated, lib_dir=lib_dir) # Record details of all files installed record_path = os.path.join(dest_info_dir, 'RECORD') with _generate_file(record_path, **csv_io_kwargs('w')) as record_file: # The type mypy infers for record_file is different for Python 3 # (typing.IO[Any]) and Python 2 (typing.BinaryIO). We explicitly # cast to typing.IO[str] as a workaround. writer = csv.writer(cast('IO[str]', record_file)) writer.writerows(_normalized_outrows(rows)) @contextlib.contextmanager def req_error_context(req_description): # type: (str) -> Iterator[None] try: yield except InstallationError as e: message = "For req: {}. {}".format(req_description, e.args[0]) reraise( InstallationError, InstallationError(message), sys.exc_info()[2] ) def install_wheel( name, # type: str wheel_path, # type: str scheme, # type: Scheme req_description, # type: str pycompile=True, # type: bool warn_script_location=True, # type: bool direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool ): # type: (...) -> None with ZipFile(wheel_path, allowZip64=True) as z: with req_error_context(req_description): _install_wheel( name=name, wheel_zip=z, wheel_path=wheel_path, scheme=scheme, pycompile=pycompile, warn_script_location=warn_script_location, direct_url=direct_url, requested=requested, ) operations/install/__init__.py000064400000000063152352421750012513 0ustar00"""For modules related to installing packages. """ network/__pycache__/xmlrpc.cpython-37.pyc000064400000003546152352421750014417 0ustar00B ReZ@sdZddlZddlmZddlmZddlmZddl m Z ddl m Z e rdddl mZdd lmZeeZGd d d ejZdS) z#xmlrpclib.Transport implementation N) xmlrpc_client)parse)NetworkConnectionError)raise_for_status)MYPY_CHECK_RUNNING)Dict) PipSessionc@s$eZdZdZdddZd ddZdS) PipXmlrpcTransportzRProvide a `xmlrpclib.Transport` implementation via a `PipSession` object. FcCs*tj||t|}|j|_||_dS)N)r Transport__init__ urllib_parseurlparsescheme_scheme_session)self index_urlsession use_datetimeZ index_partsr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/xmlrpc.pyr s zPipXmlrpcTransport.__init__c Cs|j||dddf}t|}y6ddi}|jj|||dd}t|||_||jSt k r} z"| j snt t d| j j|Wdd} ~ XYnXdS)Nz Content-Typeztext/xmlT)dataheadersstreamzHTTP error %s while getting %s)rr urlunparserpostrverboseparse_responserawrresponseAssertionErrorloggercritical status_code) rhosthandler request_bodyrpartsurlrrexcrrrrequest#s      zPipXmlrpcTransport.requestN)F)F)__name__ __module__ __qualname____doc__r r*rrrrr s r )r.loggingpip._vendor.six.movesrZpip._vendor.six.moves.urllibrr pip._internal.exceptionsrpip._internal.network.utilsrpip._internal.utils.typingrtypingrpip._internal.network.sessionr getLoggerr+r!r r rrrrs        network/__pycache__/session.cpython-37.pyc000064400000022014152352421750014564 0ustar00B Reh;@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z m Z ddlmZddlmZmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd l m!Z!dd l"m#Z#m$Z$ddl%m&Z&ddl'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.e,rXddl/m0Z0m1Z1m2Z2m3Z3m4Z4ddl5m6Z6e3e7e7e2e4e8e7ffZ9e:e;ZdZ?ddZ@dd ZAGd!d"d"eZBGd#d$d$eZCGd%d&d&eZDGd'd(d(e jEZFdS))zhPipSession and supporting code, containing all pip-specific network request configuration and behavior. N)requestssixurllib3)CacheControlAdapter) BaseAdapter HTTPAdapter)Response)CaseInsensitiveDict)parse)InsecureRequestWarning) __version__)MultiDomainBasicAuth) SafeFileCache)has_tls ipaddress)libc_ver)build_url_from_netlocget_installed_version parse_netloc)MYPY_CHECK_RUNNING) url_to_path)IteratorListOptionalTupleUnion)Linkignore)category)https*r )r localhostr )r z 127.0.0.0/8r )r z::1/128r )filer N)sshr r ) BUILD_BUILDIDBUILD_IDCI PIP_IS_CIcCstddtDS)z? Return whether it looks like pip is running under CI. css|]}|tjkVqdS)N)osenviron).0namer,/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/session.py `sz looks_like_ci..)anyCI_ENVIRONMENT_VARIABLESr,r,r,r- looks_like_ciXsr1cCsLdtdtdtid}|dddkr@t|dd<n|dddkrtjjd krltjd d }ntj}d d d|D|dd<nB|dddkrt|dd<n |dddkrt|dd<tjdrHddl m }t t ddt dddg|}t t ddt ddgt}|r:||d<|rH||d<tjdrztdrzdtdd|d<trt|did<trt|did<trt|d<trdd l}|j|d <td!}|d k r||d"<tr d#nd |d$<tjd%}|d k r2||d&<d'j|tj|d(d#d)d*S)+z6 Return a string representing the user agent. pip)r+versionr+) installerpythonimplementationr6CPythonr3PyPyfinalN.cSsg|] }t|qSr,)str)r*xr,r,r- wszuser_agent..Jython IronPythonlinuxr)distrocSs|dS)Nr,)r=r,r,r-zuser_agent..idcSs|dS)NrCr,)r=r,r,r-rDrEliblibcrBdarwinmacOSsystemreleasecpuopenssl_version setuptoolssetuptools_versionTciPIP_USER_AGENT_USER_DATA user_dataz9{data[installer][name]}/{data[installer][version]} {json}),:) separators sort_keys)datajson) r platformpython_versionpython_implementationsyspypy_version_info releaseleveljoin startswith pip._vendorrBdictfilterziplinux_distributionrmac_verrK setdefaultrLmachiner_sslOPENSSL_VERSIONrr1r(r)getformatrYdumps)rXr^rB distro_infosrHsslrPrSr,r,r- user_agentcs`          rqc@seZdZdddZddZdS)LocalFSAdapterNc Cst|j}t}d|_|j|_yt|} Wn.tk rZ} zd|_| |_Wdd} ~ XYnPXtj j | j dd} t |dp~d} t| | j| d|_t|d|_|jj|_|S) NiT)usegmtrz text/plain)z Content-TypezContent-Lengthz Last-Modifiedrb)rurlr status_coder(statOSErrorrawemailutils formatdatest_mtime mimetypes guess_typer st_sizeheadersopenclose) selfrequeststreamtimeoutverifycertproxiespathnamerespstatsexcmodified content_typer,r,r-sends$    zLocalFSAdapter.sendcCsdS)Nr,)rr,r,r-rszLocalFSAdapter.close)NNNNN)__name__ __module__ __qualname__rrr,r,r,r-rrs rrcseZdZfddZZS)InsecureHTTPAdaptercstt|j||d|ddS)NF)connrvrr)superr cert_verify)rrrvrr) __class__r,r-rs zInsecureHTTPAdapter.cert_verify)rrrr __classcell__r,r,)rr-rsrcseZdZfddZZS)InsecureCacheControlAdaptercstt|j||d|ddS)NF)rrvrr)rrr)rrrvrr)rr,r-rs z'InsecureCacheControlAdapter.cert_verify)rrrrrr,r,)rr-rsrcsFeZdZdZfddZd ddZddZd d Zfd d ZZ S) PipSessionNc s|dd}|dd}|dg}|dd}tt|j||g|_t|jd<t|d|_t j |d d d d gd d}t |d}|rt t ||d}tt ||d|_nt|d}||_|d||d||dtx|D]} |j| ddqWdS)zj :param trusted_hosts: Domains not to emit warnings for when not using HTTPS. retriesrcacheN trusted_hosts index_urlsz User-Agent)riiiig?)totalstatus_forcelistbackoff_factor) max_retries)rrzhttps://zhttp://zfile://T)suppress_logging)poprr__init__pip_trusted_originsrqrr authrRetryrrrr_trusted_host_adapterrmountrradd_trusted_host) rargskwargsrrrrinsecure_adaptersecure_adapterhost)rr,r-rs6             zPipSession.__init__FcCs|s.d|}|dk r$|d|7}t|t|}||jkrL|j||t|d|j|ds|t|d|jdS)z :param host: It is okay to provide a host that has previously been added. :param source: An optional source string, for logging where the host string came from. zadding trusted host: {!r}Nz (from {})/rCrU) rmloggerinforrappendrrr)rrsourcermsg host_portr,r,r-r4s      zPipSession.add_trusted_hostccsDxtD] }|VqWx*|jD] \}}d||dkr4dn|fVqWdS)Nr )SECURE_ORIGINSr)r secure_originrportr,r,r-iter_secure_originsQs  zPipSession.iter_secure_originsc Cstt|}|j|j|j}}}|ddd}x|D]}|\}}} ||kr^|dkr^q>y0t |dkrpdnt |} t t |} Wn2t k r|r||kr|dkrw>Yn X| | krq>|| kr| dkr| dk rq>dSWtd||dS)N+rCr TzThe repository located at %s is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host %s'.F) urllib_parseurlparser<schemehostnamerrsplitrr ip_addressr ensure_text ip_network ValueErrorlowerrwarning) rlocationparsedorigin_protocol origin_host origin_portrsecure_protocol secure_host secure_portaddrnetworkr,r,r-is_secure_originXs<   zPipSession.is_secure_origincs(|d|jtt|j||f||S)Nr)rhrrrr)rmethodrvrr)rr,r-rszPipSession.request)NF) rrrrrrrrrrr,r,)rr-rs  L Hr)G__doc__ email.utilsr{rYloggingrr(rZr]warningsrbrrrZpip._vendor.cachecontrolrZpip._vendor.requests.adaptersrrZpip._vendor.requests.modelsrZpip._vendor.requests.structuresr Zpip._vendor.six.moves.urllibr rZpip._vendor.urllib3.exceptionsr r2r pip._internal.network.authr pip._internal.network.cacherpip._internal.utils.compatrrpip._internal.utils.glibcrpip._internal.utils.miscrrrpip._internal.utils.typingrpip._internal.utils.urlsrtypingrrrrrpip._internal.models.linkrr<intZ SecureOrigin getLoggerrrfilterwarningsrr0r1rqrrrrSessionrr,r,r,r-sT                P!network/__pycache__/auth.cpython-37.pyc000064400000015711152352421750014050 0ustar00B Re- @s(dZddlZddlmZmZddlmZddlmZ ddl m Z m Z m Z mZmZddlmZerddlmZmZmZmZmZdd lmZdd lmZmZeeeefZee Z!y ddl"a"WnNe#k rda"Yn8e$k r Z%ze!&d ee%da"WddZ%[%XYnXd d Z'GdddeZ(dS)zNetwork Authentication Helpers Contains interface (MultiDomainBasicAuth) and associated glue code for providing credentials in the context of network requests. N)AuthBase HTTPBasicAuth)get_netrc_auth)parse)ask ask_input ask_passwordremove_auth_from_urlsplit_auth_netloc_from_url)MYPY_CHECK_RUNNING)DictOptionalTupleListAny)AuthInfo)ResponseRequestz*Keyring is skipped due to an exception: %sc Cs|rts dSyzy tj}Wntk r,Yn0Xtd||||}|dk rX|j|jfSdS|rtd|t||}|r||fSWn6tk r}zt dt |daWdd}~XYnXdS)z3Return the tuple auth for a given url from keyring.Nz'Getting credentials from keyring for %sz$Getting password from keyring for %sz*Keyring is skipped due to an exception: %s) keyringget_credentialAttributeErrorloggerdebugusernamepassword get_password Exceptionwarningstr)urlrrcredrexcr"/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/auth.pyget_keyring_auth,s,        r$c@s`eZdZdddZddZdddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS)MultiDomainBasicAuthTNcCs||_||_i|_d|_dS)N) prompting index_urls passwords_credentials_to_save)selfr&r'r"r"r#__init__OszMultiDomainBasicAuth.__init__cCsB|r |jsdSx.|jD]$}t|dd}||r|SqWdS)aReturn the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentials then they will be included in the return value. Returns None if no matching index was found, or if --no-index was specified by the user. N/)r'r rstrip startswith)r*ruprefixr"r"r#_get_index_url[s   z#MultiDomainBasicAuth._get_index_urlcCst|\}}}|\}}|dk r6|dk r6td||S||} | rft| } | rf| \} } } td| | r| ddk r| \}}|dk r|dk rtd|| S|rt|} | rtd|| S|rt| |pt||}|rtd||S||fS)z2Find and return credentials for the specified URL.NzFound credentials in url for %szFound index url %srz%Found credentials in index url for %sz!Found credentials in netrc for %sz#Found credentials in keyring for %s)r rrr1rr$)r* original_url allow_netrc allow_keyringrnetlocurl_user_passwordrr index_url index_info_index_url_user_password netrc_authkr_authr"r"r#_get_new_credentialsrs:          z)MultiDomainBasicAuth._get_new_credentialscCst|\}}}|j|d\}}|dkr>|dkr>||\}}|dk sN|dk rl|pTd}|p\d}||f|j|<|dk r||dk s|dkr|dkstd||||fS)a_Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different username and password. )NNNz'Could not load credentials from url: {})r r(getr=AssertionErrorformat)r*r2rr5r9rrr"r"r#_get_url_and_credentialss  z-MultiDomainBasicAuth._get_url_and_credentialscCsH||j\}}}||_|dk r6|dk r6t|||}|d|j|S)Nresponse)rBrr register_hook handle_401)r*reqrrrr"r"r#__call__s zMultiDomainBasicAuth.__call__cCs`td|}|sdSt||}|rN|ddk rN|ddk rN|d|ddfStd}||dfS)Nz User for {}: )NNFrFz Password: T)rrAr$r)r*r5rauthrr"r"r#_prompt_for_passwords z)MultiDomainBasicAuth._prompt_for_passwordcCstsdStdddgdkS)NFz#Save credentials to keyring [y/N]: yn)rr)r*r"r"r# _should_save_password_to_keyringsz5MultiDomainBasicAuth._should_save_password_to_keyringc Ks|jdkr|S|js|St|j}||j\}}}d|_|dk rv|dk rv||f|j|j<|rv| rv|j||f|_|j |j t |pd|pd|j}|d|j|jr|d|j|jj|f|}|j||S)Nir>rC) status_coder& urllib_parseurlparserrJr5r)r(rMcontentraw release_connrrequestrD warn_on_401save_credentials connectionsendhistoryappend) r*respkwargsparsedrrsaverFnew_respr"r"r#rEs(     zMultiDomainBasicAuth.handle_401cKs|jdkrtd|jjdS)z6Response callback to warn about incorrect credentials.iz)401 Error, Credentials not correct for %sN)rNrrrTr)r*r[r\r"r"r#rU s z MultiDomainBasicAuth.warn_on_401cKsntdk stdtsdS|j}d|_|rj|jdkrjytdtj|Wntk rhtdYnXdS)z1Response callback to save credentials on success.Nz'should never reach here without keyringizSaving credentials to keyringzFailed to save credentials) rr@r)rNrinfo set_passwordr exception)r*r[r\credsr"r"r#rV(s z%MultiDomainBasicAuth.save_credentials)TN)TT) __name__ __module__ __qualname__r+r1r=rBrGrJrMrErUrVr"r"r"r#r%Ms  2) .r%))__doc__loggingZpip._vendor.requests.authrrZpip._vendor.requests.utilsrZpip._vendor.six.moves.urllibrrOpip._internal.utils.miscrrrr r pip._internal.utils.typingr typingr r rrr pip._internal.vcs.versioncontrolrZpip._vendor.requests.modelsrrrZ Credentials getLoggerrdrr ImportErrorrr!rr$r%r"r"r"r#s,       !network/__pycache__/utils.cpython-37.pyc000064400000002634152352421750014247 0ustar00B ReL@s\ddlmZmZddlmZddlmZers  network/__pycache__/__init__.cpython-37.pyc000064400000000433152352421750014641 0ustar00B Re2@sdZdS)z+Contains purely network-related utilities. N)__doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/__init__.pynetwork/__pycache__/lazy_wheel.cpython-37.pyc000064400000017433152352421750015255 0ustar00B Re@sdZddgZddlmZmZddlmZddlmZddl m Z m Z ddl m Z dd lmZdd lmZmZmZdd lmZdd lmZerdd lmZmZmZmZmZmZddlm Z ddl m!Z!ddl"m#Z#Gddde$Z%ddZ&Gddde'Z(dS)zLazy ZIP over HTTPHTTPRangeRequestUnsupporteddist_from_wheel_url) bisect_left bisect_right)contextmanager)NamedTemporaryFile) BadZipfileZipFile)CONTENT_CHUNK_SIZE)range)HEADERSraise_for_statusresponse_chunks)MYPY_CHECK_RUNNING)$pkg_resources_distribution_for_wheel)AnyDictIteratorListOptionalTuple) Distribution)Response) PipSessionc@s eZdZdS)rN)__name__ __module__ __qualname__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.pyrsc Cs,t||}t|}t|||jSQRXdS)a%Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised. N)LazyZipOverHTTPr rname)r urlsessionwheelzip_filerrrr"s c@seZdZdZefddZeddZeddZdd Z d d Z ed d Z d+ddZ ddZ d,ddZddZd-ddZddZddZdd Zed!d"Zd#d$Zefd%d&Zd'd(Zd)d*ZdS).raFile-like object mapped to a ZIP file over HTTP. This uses HTTP range requests to lazily fetch the file's content, which is supposed to be fed to ZipFile. If such requests are not supported by the server, raise HTTPRangeRequestUnsupported during initialization. cCs|j|td}t||jdks$t||||_|_|_t|j d|_ t |_ | |j g|_g|_d|j ddkrtd|dS)N)headerszContent-Lengthbytesz Accept-Rangesnonezrange request is not supported)headr r status_codeAssertionError_session_url _chunk_sizeintr%_lengthr_filetruncate_left_rightgetr _check_zip)selfr!r" chunk_sizer)rrr__init__=s zLazyZipOverHTTP.__init__cCsdS)z!Opening mode, which is always rb.rbr)r7rrrmodeLszLazyZipOverHTTP.modecCs|jjS)zPath to the underlying file.)r1r )r7rrrr RszLazyZipOverHTTP.namecCsdS)z9Return whether random access is supported, which is True.Tr)r7rrrseekableXszLazyZipOverHTTP.seekablecCs|jdS)zClose the file.N)r1close)r7rrrr=]szLazyZipOverHTTP.closecCs|jjS)zWhether the file is closed.)r1closed)r7rrrr>bszLazyZipOverHTTP.closedcCs`t||j}||j}}|dkr(|n t|||}td||}|||d|j|S)zRead up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached. r)maxr.tellr0min _downloadr1read)r7sizeZ download_sizestartlengthstoprrrrEhs  zLazyZipOverHTTP.readcCsdS)z3Return whether the file is readable, which is True.Tr)r7rrrreadablewszLazyZipOverHTTP.readablercCs|j||S)a-Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative; * 2: End of stream - pos usually negative. )r1seek)r7offsetwhencerrrrK|s zLazyZipOverHTTP.seekcCs |jS)zReturn the current possition.)r1rB)r7rrrrBszLazyZipOverHTTP.tellNcCs |j|S)zResize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size. )r1r2)r7rFrrrr2s zLazyZipOverHTTP.truncatecCsdS)z Return False.Fr)r7rrrwritableszLazyZipOverHTTP.writablecCs|j|S)N)r1 __enter__)r7rrrrOs zLazyZipOverHTTP.__enter__cGs |jj|S)N)r1__exit__)r7excrrrrPszLazyZipOverHTTP.__exit__c cs$|}z dVWd||XdS)zyReturn a context manager keeping the position. At the end of the block, seek back to original position. N)rBrK)r7posrrr_stays zLazyZipOverHTTP._stayc Csn|jd}x^ttd||jD]H}||||*y t|Wntk rXYnXPWdQRXqWdS)z1Check and download until the file is a valid ZIP.r@rN)r0reversedr r.rDrSr r)r7endrGrrrr6s    zLazyZipOverHTTP._check_zipcCs4|}d|||d<d|d<|jj|j|ddS)z:Return HTTP response to a range request from start to end.z bytes={}-{}ZRangezno-cachez Cache-ControlT)r%stream)copyformatr,r5r-)r7rGrUZ base_headersr%rrr_stream_responsesz LazyZipOverHTTP._stream_responsec cs|j|||j||}}t|g|dd}}t|g|dd}x4t||D]&\}} ||krx||dfV| d}qZW||kr||fV|g|g|j||<|j||<dS)a/Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data Nr@r?)r3r4rCrAzip) r7rGrUleftrightZlsliceZrsliceijkrrr_merges   zLazyZipOverHTTP._mergec Cs||t|j|}t|j|}x\|||||D]H\}}|||}|||x t ||j D]}|j |qhWq4WWdQRXdS)z-Download bytes from start to end inclusively.N) rSrr4rr3r`rYr rKrr.r1write)r7rGrUr[r\responsechunkrrrrDs     zLazyZipOverHTTP._download)r?)r)N)rrr__doc__r r9propertyr;r r<r=r>rErJrKrBr2rNrOrPrrSr6r rYr`rDrrrrr4s(         rN))rd__all__bisectrr contextlibrtempfilerzipfilerr Zpip._vendor.requests.modelsr pip._vendor.six.movesr pip._internal.network.utilsr r rpip._internal.utils.typingrpip._internal.utils.wheelrtypingrrrrrrZpip._vendor.pkg_resourcesrrpip._internal.network.sessionr Exceptionrrobjectrrrrrs$          network/__pycache__/download.cpython-37.pyc000064400000010514152352421750014712 0ustar00B Re@s*dZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlmZmZmZdd lmZmZmZdd lmZerdd lmZmZdd lmZdd lmZddlm Z e!e"Z#ddZ$ddZ%ddZ&ddZ'ddZ(ddZ)Gddde*Z+Gddde*Z,dS)z)Download files with progress indicators. N)CONTENT_CHUNK_SIZE)DownloadProgressProvider)NetworkConnectionError)PyPI) is_from_cache)HEADERSraise_for_statusresponse_chunks) format_sizeredact_auth_from_urlsplitext)MYPY_CHECK_RUNNING)IterableOptional)Response)Link) PipSessionc Cs.yt|jdStttfk r(dSXdS)Nzcontent-length)intheaders ValueErrorKeyError TypeError)respr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/download.py_get_http_response_size%srcCst|}|jtjkr|j}n|j}t|}|r>d|t|}t |rTt d|n t d|t t jkrtd}n*t |rd}n|sd}n|dkrd}nd}t|t}|s|St||d|S)Nz{} ({})zUsing cached %szDownloading %sFTi@)max)rnetlocrfile_storage_domainshow_urlurl_without_fragmentr formatr rloggerinfogetEffectiveLevelloggingINFOr rr)rlink progress_bar total_lengthurl logged_url show_progresschunksrrr_prepare_download-s2   r.cCs tj|S)zJ Sanitize the "filename" value from a Content-Disposition header. )ospathbasename)filenamerrrsanitize_content_filenameYsr3cCs,t|\}}|d}|r$t|}|p*|S)z Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. r2)cgi parse_headergetr3)content_dispositiondefault_filename_typeparamsr2rrrparse_content_dispositionas  r;cCs|j}|jd}|r t||}t|d}|sPt|jdd}|rP||7}|s~|j|jkr~tj |jd}|r~||7}|S)zoGet an ideal filename from the given HTTP response, falling back to the link filename if not provided. zcontent-dispositionz content-type) r2rr6r;r mimetypesguess_extensionr*r/r0)rr'r2r7extrrr_get_http_response_filenameps   rAcCs.|jddd}|j|tdd}t||S)N#r<rT)rstream)r*splitr6rr)sessionr' target_urlrrrr_http_get_downloadsrGc@seZdZddZdS)DownloadcCs||_||_||_dS)N)responser2r-)selfrIr2r-rrr__init__szDownload.__init__N)__name__ __module__ __qualname__rKrrrrrHsrHc@seZdZddZddZdS) DownloadercCs||_||_dS)N)_session _progress_bar)rJrEr(rrrrKszDownloader.__init__c Csryt|j|}WnDtk rT}z&|jdk s0ttd|jj|Wdd}~XYnXt|t ||t |||j S)NzHTTP error %s while getting %s) rGrPrrIAssertionErrorr"critical status_coderHrAr.rQ)rJr'rerrr__call__szDownloader.__call__N)rLrMrNrKrVrrrrrOs rO)-__doc__r4r%r>r/Zpip._vendor.requests.modelsrpip._internal.cli.progress_barsrpip._internal.exceptionsrpip._internal.models.indexrpip._internal.network.cacherpip._internal.network.utilsrrr pip._internal.utils.miscr r r pip._internal.utils.typingr typingrrrpip._internal.models.linkrpip._internal.network.sessionr getLoggerrLr"rr.r3r;rArGobjectrHrOrrrrs4          , network/__pycache__/cache.cpython-37.pyc000064400000005243152352421750014151 0ustar00B Re @sdZddlZddlmZddlmZddlmZddlm Z ddl m Z m Z ddl mZdd lmZerxdd lmZmZd d Zed dZGdddeZdS)zHTTP cache implementation. N)contextmanager) BaseCache) FileCache)Response)adjacent_tmp_filereplace) ensure_dir)MYPY_CHECK_RUNNING)OptionalIteratorcCs t|ddS)N from_cacheF)getattr)responser/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/network/cache.py is_from_cachesrc cs(y dVWnttfk r"YnXdS)zvIf we can't access the cache then we can just skip caching and process requests as if caching wasn't enabled. N)OSErrorIOErrorrrrrsuppressed_cache_errorss rcs@eZdZdZfddZddZddZdd Zd d ZZ S) SafeFileCachezw A file based cache which is safe to use even when the target directory may not be accessible or writable. cs(|dk stdtt|||_dS)Nz!Cache directory must not be None.)AssertionErrorsuperr__init__ directory)selfr) __class__rrr*szSafeFileCache.__init__cCs4t|}t|dd|g}tjj|jf|S)N)rencodelistospathjoinr)rnamehashedpartsrrr_get_cache_path0s zSafeFileCache._get_cache_pathc Cs:||}t t|d }|SQRXWdQRXdS)Nrb)r%ropenread)rkeyr frrrget9s  zSafeFileCache.getc CsZ||}t@ttj|t|}||WdQRXt|j |WdQRXdS)N) r%rrrr dirnamerwriterr")rr)valuer r*rrrset@s   zSafeFileCache.setc Cs*||}tt|WdQRXdS)N)r%rrremove)rr)r rrrdeleteKs zSafeFileCache.delete) __name__ __module__ __qualname____doc__rr%r+r/r1 __classcell__rr)rrr$s    r)r5r contextlibrZpip._vendor.cachecontrol.cacherpip._vendor.cachecontrol.cachesrZpip._vendor.requests.modelsrpip._internal.utils.filesystemrrpip._internal.utils.miscrpip._internal.utils.typingr typingr r rrrrrrrs       network/download.py000064400000012037152352421750010427 0ustar00"""Download files with progress indicators. """ import cgi import logging import mimetypes import os from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._internal.cli.progress_bars import DownloadProgressProvider from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.index import PyPI from pip._internal.network.cache import is_from_cache from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.misc import ( format_size, redact_auth_from_url, splitext, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Iterable, Optional from pip._vendor.requests.models import Response from pip._internal.models.link import Link from pip._internal.network.session import PipSession logger = logging.getLogger(__name__) def _get_http_response_size(resp): # type: (Response) -> Optional[int] try: return int(resp.headers['content-length']) except (ValueError, KeyError, TypeError): return None def _prepare_download( resp, # type: Response link, # type: Link progress_bar # type: str ): # type: (...) -> Iterable[bytes] total_length = _get_http_response_size(resp) if link.netloc == PyPI.file_storage_domain: url = link.show_url else: url = link.url_without_fragment logged_url = redact_auth_from_url(url) if total_length: logged_url = '{} ({})'.format(logged_url, format_size(total_length)) if is_from_cache(resp): logger.info("Using cached %s", logged_url) else: logger.info("Downloading %s", logged_url) if logger.getEffectiveLevel() > logging.INFO: show_progress = False elif is_from_cache(resp): show_progress = False elif not total_length: show_progress = True elif total_length > (40 * 1000): show_progress = True else: show_progress = False chunks = response_chunks(resp, CONTENT_CHUNK_SIZE) if not show_progress: return chunks return DownloadProgressProvider( progress_bar, max=total_length )(chunks) def sanitize_content_filename(filename): # type: (str) -> str """ Sanitize the "filename" value from a Content-Disposition header. """ return os.path.basename(filename) def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = params.get('filename') if filename: # We need to sanitize the filename to prevent directory traversal # in case the filename contains ".." path parts. filename = sanitize_content_filename(filename) return filename or default_filename def _get_http_response_filename(resp, link): # type: (Response, Link) -> str """Get an ideal filename from the given HTTP response, falling back to the link filename if not provided. """ filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] # type: Optional[str] if not ext: ext = mimetypes.guess_extension( resp.headers.get('content-type', '') ) if ext: filename += ext if not ext and link.url != resp.url: ext = os.path.splitext(resp.url)[1] if ext: filename += ext return filename def _http_get_download(session, link): # type: (PipSession, Link) -> Response target_url = link.url.split('#', 1)[0] resp = session.get(target_url, headers=HEADERS, stream=True) raise_for_status(resp) return resp class Download(object): def __init__( self, response, # type: Response filename, # type: str chunks, # type: Iterable[bytes] ): # type: (...) -> None self.response = response self.filename = filename self.chunks = chunks class Downloader(object): def __init__( self, session, # type: PipSession progress_bar, # type: str ): # type: (...) -> None self._session = session self._progress_bar = progress_bar def __call__(self, link): # type: (Link) -> Download try: resp = _http_get_download(self._session, link) except NetworkConnectionError as e: assert e.response is not None logger.critical( "HTTP error %s while getting %s", e.response.status_code, link ) raise return Download( resp, _get_http_response_filename(resp, link), _prepare_download(resp, link, self._progress_bar), ) network/utils.py000064400000010114152352421750007752 0ustar00from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response from pip._internal.exceptions import NetworkConnectionError from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict, Iterator # The following comments and HTTP headers were originally added by # Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03. # # We use Accept-Encoding: identity here because requests defaults to # accepting compressed responses. This breaks in a variety of ways # depending on how the server is configured. # - Some servers will notice that the file isn't a compressible file # and will leave the file alone and with an empty Content-Encoding # - Some servers will notice that the file is already compressed and # will leave the file alone, adding a Content-Encoding: gzip header # - Some servers won't notice anything at all and will take a file # that's already been compressed and compress it again, and set # the Content-Encoding: gzip header # By setting this to request only the identity encoding we're hoping # to eliminate the third case. Hopefully there does not exist a server # which when given a file will notice it is already compressed and that # you're not asking for a compressed file and will then decompress it # before sending because if that's the case I don't think it'll ever be # possible to make this work. HEADERS = {'Accept-Encoding': 'identity'} # type: Dict[str, str] def raise_for_status(resp): # type: (Response) -> None http_error_msg = u'' if isinstance(resp.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. try: reason = resp.reason.decode('utf-8') except UnicodeDecodeError: reason = resp.reason.decode('iso-8859-1') else: reason = resp.reason if 400 <= resp.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % ( resp.status_code, reason, resp.url) elif 500 <= resp.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % ( resp.status_code, reason, resp.url) if http_error_msg: raise NetworkConnectionError(http_error_msg, response=resp) def response_chunks(response, chunk_size=CONTENT_CHUNK_SIZE): # type: (Response, int) -> Iterator[bytes] """Given a requests Response, provide the data chunks. """ try: # Special case for urllib3. for chunk in response.raw.stream( chunk_size, # We use decode_content=False here because we don't # want urllib3 to mess with the raw bytes we get # from the server. If we decompress inside of # urllib3 then we cannot verify the checksum # because the checksum will be of the compressed # file. This breakage will only occur if the # server adds a Content-Encoding header, which # depends on how the server was configured: # - Some servers will notice that the file isn't a # compressible file and will leave the file alone # and with an empty Content-Encoding # - Some servers will notice that the file is # already compressed and will leave the file # alone and will add a Content-Encoding: gzip # header # - Some servers won't notice anything at all and # will take a file that's already been compressed # and compress it again and set the # Content-Encoding: gzip header # # By setting this not to decode automatically we # hope to eliminate problems with the second case. decode_content=False, ): yield chunk except AttributeError: # Standard file-like object. while True: chunk = response.raw.read(chunk_size) if not chunk: break yield chunk network/lazy_wheel.py000064400000017712152352421750010770 0ustar00"""Lazy ZIP over HTTP""" __all__ = ['HTTPRangeRequestUnsupported', 'dist_from_wheel_url'] from bisect import bisect_left, bisect_right from contextlib import contextmanager from tempfile import NamedTemporaryFile from zipfile import BadZipfile, ZipFile from pip._vendor.requests.models import CONTENT_CHUNK_SIZE from pip._vendor.six.moves import range from pip._internal.network.utils import ( HEADERS, raise_for_status, response_chunks, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel if MYPY_CHECK_RUNNING: from typing import Any, Dict, Iterator, List, Optional, Tuple from pip._vendor.pkg_resources import Distribution from pip._vendor.requests.models import Response from pip._internal.network.session import PipSession class HTTPRangeRequestUnsupported(Exception): pass def dist_from_wheel_url(name, url, session): # type: (str, str, PipSession) -> Distribution """Return a pkg_resources.Distribution from the given wheel URL. This uses HTTP range requests to only fetch the potion of the wheel containing metadata, just enough for the object to be constructed. If such requests are not supported, HTTPRangeRequestUnsupported is raised. """ with LazyZipOverHTTP(url, session) as wheel: # For read-only ZIP files, ZipFile only needs methods read, # seek, seekable and tell, not the whole IO protocol. zip_file = ZipFile(wheel) # type: ignore # After context manager exit, wheel.name # is an invalid file by intention. return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name) class LazyZipOverHTTP(object): """File-like object mapped to a ZIP file over HTTP. This uses HTTP range requests to lazily fetch the file's content, which is supposed to be fed to ZipFile. If such requests are not supported by the server, raise HTTPRangeRequestUnsupported during initialization. """ def __init__(self, url, session, chunk_size=CONTENT_CHUNK_SIZE): # type: (str, PipSession, int) -> None head = session.head(url, headers=HEADERS) raise_for_status(head) assert head.status_code == 200 self._session, self._url, self._chunk_size = session, url, chunk_size self._length = int(head.headers['Content-Length']) self._file = NamedTemporaryFile() self.truncate(self._length) self._left = [] # type: List[int] self._right = [] # type: List[int] if 'bytes' not in head.headers.get('Accept-Ranges', 'none'): raise HTTPRangeRequestUnsupported('range request is not supported') self._check_zip() @property def mode(self): # type: () -> str """Opening mode, which is always rb.""" return 'rb' @property def name(self): # type: () -> str """Path to the underlying file.""" return self._file.name def seekable(self): # type: () -> bool """Return whether random access is supported, which is True.""" return True def close(self): # type: () -> None """Close the file.""" self._file.close() @property def closed(self): # type: () -> bool """Whether the file is closed.""" return self._file.closed def read(self, size=-1): # type: (int) -> bytes """Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached. """ download_size = max(size, self._chunk_size) start, length = self.tell(), self._length stop = length if size < 0 else min(start+download_size, length) start = max(0, stop-download_size) self._download(start, stop-1) return self._file.read(size) def readable(self): # type: () -> bool """Return whether the file is readable, which is True.""" return True def seek(self, offset, whence=0): # type: (int, int) -> int """Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative; * 2: End of stream - pos usually negative. """ return self._file.seek(offset, whence) def tell(self): # type: () -> int """Return the current possition.""" return self._file.tell() def truncate(self, size=None): # type: (Optional[int]) -> int """Resize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size. """ return self._file.truncate(size) def writable(self): # type: () -> bool """Return False.""" return False def __enter__(self): # type: () -> LazyZipOverHTTP self._file.__enter__() return self def __exit__(self, *exc): # type: (*Any) -> Optional[bool] return self._file.__exit__(*exc) @contextmanager def _stay(self): # type: ()-> Iterator[None] """Return a context manager keeping the position. At the end of the block, seek back to original position. """ pos = self.tell() try: yield finally: self.seek(pos) def _check_zip(self): # type: () -> None """Check and download until the file is a valid ZIP.""" end = self._length - 1 for start in reversed(range(0, end, self._chunk_size)): self._download(start, end) with self._stay(): try: # For read-only ZIP files, ZipFile only needs # methods read, seek, seekable and tell. ZipFile(self) # type: ignore except BadZipfile: pass else: break def _stream_response(self, start, end, base_headers=HEADERS): # type: (int, int, Dict[str, str]) -> Response """Return HTTP response to a range request from start to end.""" headers = base_headers.copy() headers['Range'] = 'bytes={}-{}'.format(start, end) # TODO: Get range requests to be correctly cached headers['Cache-Control'] = 'no-cache' return self._session.get(self._url, headers=headers, stream=True) def _merge(self, start, end, left, right): # type: (int, int, int, int) -> Iterator[Tuple[int, int]] """Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data """ lslice, rslice = self._left[left:right], self._right[left:right] i = start = min([start]+lslice[:1]) end = max([end]+rslice[-1:]) for j, k in zip(lslice, rslice): if j > i: yield i, j-1 i = k + 1 if i <= end: yield i, end self._left[left:right], self._right[left:right] = [start], [end] def _download(self, start, end): # type: (int, int) -> None """Download bytes from start to end inclusively.""" with self._stay(): left = bisect_left(self._right, start) right = bisect_right(self._left, end) for start, end in self._merge(start, end, left, right): response = self._stream_response(start, end) response.raise_for_status() self.seek(start) for chunk in response_chunks(response, self._chunk_size): self._file.write(chunk) cli/__pycache__/main.cpython-37.pyc000064400000002713152352421750013107 0ustar00B Re8 @sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZerdd lmZmZeeZd d d ZdS)z Primary application entrypoint. )absolute_importN) autocomplete) parse_command)create_command)PipError) deprecation)MYPY_CHECK_RUNNING)ListOptionalc Cs|dkrtjdd}ttyt|\}}WnLtk r}z.tjd |tjt j t dWdd}~XYnXyt t jdWn0t jk r}ztd|Wdd}~XYnXt|d|kd}||S)Nz ERROR: {}z%Ignoring error %s when setting localez --isolated)isolated)sysargvrinstall_warning_loggerrrrstderrwriteformatoslinesepexitlocale setlocaleLC_ALLErrorloggerdebugrmain)argscmd_namecmd_argsexcecommandr$/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/main.pyr1s r)N)__doc__ __future__rrloggingrr pip._internal.cli.autocompletionrpip._internal.cli.main_parserrpip._internal.commandsrpip._internal.exceptionsrZpip._internal.utilsrpip._internal.utils.typingrtypingr r getLogger__name__rrr$r$r$r%s        cli/__pycache__/command_context.cpython-37.pyc000064400000002530152352421750015342 0ustar00B Re@s\ddlmZddlmZddlmZerHddlmZmZm Z e dddZ Gdd d e Z d S) )contextmanager) ExitStack)MYPY_CHECK_RUNNING)IteratorContextManagerTypeVar_TT) covariantcs0eZdZfddZeddZddZZS)CommandContextMixIncs tt|d|_t|_dS)NF)superr __init___in_main_contextr _main_context)self) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/command_context.pyr szCommandContextMixIn.__init__c cs:|jr td|_z|j dVWdQRXWdd|_XdS)NTF)r AssertionErrorr)rrrr main_contexts  z CommandContextMixIn.main_contextcCs|js t|j|S)N)r rr enter_context)rcontext_providerrrrr s z!CommandContextMixIn.enter_context)__name__ __module__ __qualname__r rrr __classcell__rr)rrr s  r N) contextlibrpip._vendor.contextlib2rpip._internal.utils.typingrtypingrrrrobjectr rrrrs    cli/__pycache__/req_command.cpython-37.pyc000064400000023210152352421750014443 0ustar00B Re;@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z m Z ddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZmZmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&e&rZddl'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddl4m5Z5ddl6m7Z7ddl#m8Z8m9Z9e:e;Ze$j?e$j@e$jAgZBdd ZCGd!d"d"e>ZDdS)#aContains the Command base classes that depend on PipSession. The classes in this module are in a separate module so the commands not needing download / PackageFinder capability don't unnecessarily import the PackageFinder machinery and all its vendored dependencies, etc. N)partial) cmdoptions)Command)CommandContextMixIn) CommandErrorPreviousBuildDirError) LinkCollector) PackageFinder)SelectionPreferences) Downloader) PipSession)RequirementPreparer)install_req_from_editableinstall_req_from_line#install_req_from_parsed_requirementinstall_req_from_req_string)parse_requirements)pip_self_version_check) tempdir_kinds)MYPY_CHECK_RUNNING)Values)AnyListOptionalTuple) WheelCache) TargetPython)InstallRequirement)RequirementTracker) BaseResolver) TempDirectoryTempDirectoryTypeRegistrycs>eZdZdZfddZeddZddZd d d ZZ S) SessionCommandMixinzE A class mixin for command classes needing _build_session(). cstt|d|_dS)N)superr"__init___session)self) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/req_command.pyr$8szSessionCommandMixin.__init__cCsLg}t|dds*t|dd}|r*||t|dd}|rD|||pJdS)z7Return a list of index urls from user-provided options.no_indexF index_urlNextra_index_urls)getattrappendextend)clsoptions index_urlsurlurlsr(r(r)_get_index_urls=s     z#SessionCommandMixin._get_index_urlscCs0|jdkr*||||_|jdk s*t|jS)zGet a default-managed session.N)r% enter_context_build_sessionAssertionError)r&r1r(r(r)get_default_sessionLs z'SessionCommandMixin.get_default_sessionNcCs|jrtj|jstt|jr0tj|jdnd|dk r>|n|j|j| |d}|j rb|j |_ |j rp|j |_ |j sz|r|dk r|n|j |_ |jr|j|jd|_|j |j_|S)Nhttp)cacheretries trusted_hostsr2)r:https) cache_dirospathisabsr8r joinr<r=r5certverify client_certtimeoutproxyproxiesno_inputauth prompting)r&r1r<rGsessionr(r(r)r7Ws"   z"SessionCommandMixin._build_session)NN) __name__ __module__ __qualname____doc__r$ classmethodr5r9r7 __classcell__r(r()r'r)r"3s    r"c@seZdZdZddZdS)IndexGroupCommandz Abstract base class for commands with the index_group options. This also corresponds to the commands that permit the pip version check. c CsTt|dst|js|jrdS|j|dtd|jd}|t||WdQRXdS)z Do the pip version check if not disabled. This overrides the default behavior of not doing the check. r*Nr)r<rG)hasattrr8disable_pip_version_checkr*r7minrGr)r&r1rMr(r(r)handle_pip_version_checks z*IndexGroupCommand.handle_pip_version_checkN)rNrOrPrQrYr(r(r(r)rTsrTcsddfdd}|S)zNDecorator for common logic related to managing temporary directories. cSsxtD]}||dqWdS)NF)KEEPABLE_TEMPDIR_TYPES set_delete)registrytr(r(r)configure_tempdir_registrys z0with_cleanup..configure_tempdir_registrycsP|jdk st|jr|jy |||Stk rJ|jYnXdS)N)tempdir_registryr8no_cleanr)r&r1args)r^funcr(r)wrappers   zwith_cleanup..wrapperr()rbrcr()r^rbr) with_cleanupsrdc sVeZdZfddZedddZedd d Zd d Zed dZdddZ Z S)RequirementCommandcs&tt|j|||jtdS)N)r#rer$cmd_opts add_optionrr`)r&rakw)r'r(r)r$szRequirementCommand.__init__Nc CsBt||jd}|j} | dk s tt| |j|||j||||j|d S)zQ Create a RequirementPreparer instance for the given parameters. ) progress_barN) build_dirsrc_dir download_dirwheel_download_dirbuild_isolation req_tracker downloaderfinderrequire_hashes use_user_site)r rirAr8r rkrnrr) temp_build_dirr1rorMrqrsrlrmrptemp_build_dir_pathr(r(r)make_requirement_preparers z,RequirementCommand.make_requirement_preparerFTto-satisfy-onlyc Cstt|j| d} d|jkrTddl} | jjjjj |||| ||j ||||| d|jkd Sddl } | jjj jj |||| ||j ||||| d S)zF Create a Resolver instance for the given parameters. )isolated use_pep517z 2020-resolverrNz fast-deps) preparerrq wheel_cachemake_install_reqrsignore_dependenciesignore_installedignore_requires_pythonforce_reinstallupgrade_strategypy_version_info lazy_wheel) rzrqr{r|rsr}r~rrrr) rr isolated_modefeatures_enabled,pip._internal.resolution.resolvelib.resolver _internal resolution resolvelibresolverResolverr}(pip._internal.resolution.legacy.resolverlegacy) rzrqr1r{rsr~rrrryrr|pipr(r(r) make_resolvers@   z RequirementCommand.make_resolverc Csfg}xD|jD]:}x4t|d|||dD]}t||jdd}||q$Wq Wx,|D]$} t| d|j|jdd}||qPWx,|jD]"} t| d|j|jd}||qWxF|j D]<}x6t||||dD]"}t||j|jdd}||qWqWt d d |Drd|_ |sb|jsb|j sbd |j i} |j rRtd jft| d |j dntdjf| |S)zS Parse command-line arguments into the corresponding requirements. T) constraintrqr1rMF)rx user_suppliedN)rxryr)rrxry)rqr1rMcss|] }|jVqdS)N)has_hash_options).0reqr(r(r) Zsz6RequirementCommand.get_requirements..namezXYou must give at least one requirement to {name} (maybe you meant "pip {name} {links}"?) )linkszHYou must give at least one requirement to {name} (see "pip help {name}")) constraintsrrrr.rry editablesr requirementsanyrrr find_linksrformatdictrC) r&rar1rqrMrfilename parsed_req req_to_addroptsr(r(r)get_requirements#s\        z#RequirementCommand.get_requirementscCs |j}|}|rt|dS)zE Trace basic information about the provided objects. N) search_scopeget_formatted_locationsloggerinfo)rqr locationsr(r(r)trace_basic_infoksz#RequirementCommand.trace_basic_infocCs6tj||d}td|j|j|j|d}tj|||dS)z Create a package finder appropriate to this requirement command. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. )r1T) allow_yankedformat_controlallow_all_prereleases prefer_binaryr)link_collectorselection_prefs target_python)rcreater rprerr )r&r1rMrrrrr(r(r)_build_package_finderwsz(RequirementCommand._build_package_finder)NN)NFTFFrwNN)NN) rNrOrPr$ staticmethodrvrrrrrSr(r()r'r)res"   -H re)ErQloggingr@ functoolsrZpip._internal.clirpip._internal.cli.base_commandr!pip._internal.cli.command_contextrpip._internal.exceptionsrrpip._internal.index.collectorr"pip._internal.index.package_finderr $pip._internal.models.selection_prefsr pip._internal.network.downloadr pip._internal.network.sessionr pip._internal.operations.preparer pip._internal.req.constructorsrrrrZpip._internal.req.req_filer!pip._internal.self_outdated_checkrpip._internal.utils.temp_dirrpip._internal.utils.typingroptparsertypingrrrrpip._internal.cacher"pip._internal.models.target_pythonrZpip._internal.req.req_installrpip._internal.req.req_trackerrpip._internal.resolution.baserr r! getLoggerrNrr"rT BUILD_ENVEPHEM_WHEEL_CACHE REQ_BUILDrZrdrer(r(r(r)sF                     L cli/__pycache__/parser.cpython-37.pyc000064400000021373152352421750013462 0ustar00B Re%@sdZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZmZddlmZeeZGd d d ejZGd d d eZGd ddejZGdddeZddZdS)zBase option parser setup)absolute_importN) strtobool) string_types) UNKNOWN_ERROR) ConfigurationConfigurationError)get_terminal_sizec@sReZdZdZddZddZddd Zd d Zd d ZddZ ddZ ddZ dS)PrettyHelpFormatterz4A prettier/less verbose help formatter for optparse.cOs:d|d<d|d<tdd|d<tjj|f||dS)Nmax_help_positionindent_incrementrwidth)roptparseIndentedHelpFormatter__init__)selfargskwargsr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/parser.pyrszPrettyHelpFormatter.__init__cCs ||S)N)_format_option_strings)roptionrrrformat_option_strings!sz)PrettyHelpFormatter.format_option_strings <{}>, cCs~g}|jr||jd|jr0||jdt|dkrH|d||rt|jp^|j}|| |d |S)z 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 :param optsep: separator rr ) _short_optsappend _long_optsleninsert takes_valuemetavardestlowerformatjoin)rrmvarfmtoptsepoptsr$rrrr$s  z*PrettyHelpFormatter._format_option_stringscCs|dkr dS|dS)NOptionsrz: r)rheadingrrrformat_heading;sz"PrettyHelpFormatter.format_headingcCsd|t|d}|S)zz Ensure there is only one newline between usage and the first heading if there is no description. z Usage: {} z )r' indent_linestextwrapdedent)rusagemsgrrr format_usage@sz PrettyHelpFormatter.format_usagecCsV|rNt|jdrd}nd}|d}|}|t|d}d||}|SdSdS)NmainCommands Description z z{}: {} r)hasattrparserlstriprstripr/r0r1r')r descriptionlabelrrrformat_descriptionIs   z&PrettyHelpFormatter.format_descriptioncCs|r|SdSdS)Nrr)repilogrrr format_epilog[sz!PrettyHelpFormatter.format_epilogcs"fdd|dD}d|S)Ncsg|] }|qSrr).0line)indentrr csz4PrettyHelpFormatter.indent_lines..r8)splitr()rtextrD new_linesr)rDrr/bsz PrettyHelpFormatter.indent_linesN)rr) __name__ __module__ __qualname____doc__rrrr.r4r?rAr/rrrrr s  r c@seZdZdZddZdS)UpdatingDefaultsHelpFormatterzCustom help formatter for use in ConfigOptionParser. This is updates the defaults before expanding them, allowing them to show up correctly in the help listing. cCs(|jdk r|j|jjtj||S)N)r:_update_defaultsdefaultsrrexpand_default)rrrrrrPns z,UpdatingDefaultsHelpFormatter.expand_defaultN)rIrJrKrLrPrrrrrMgsrMc@s eZdZddZeddZdS)CustomOptionParsercOs(|j||}|j|j|||S)z*Insert an OptionGroup at a given position.)add_option_group option_groupspopr")ridxrrgrouprrrinsert_option_groupvs  z&CustomOptionParser.insert_option_groupcCs.|jdd}x|jD]}||jqW|S)zszGConfigOptionParser._get_ordered_configuration_items..z7Ignoring configuration key '%s' as it's value is empty..r )r_raitemsloggerdebugrFr)roverride_order section_items section_keyrksectionrjrrr _get_ordered_configuration_itemss  z3ConfigOptionParser._get_ordered_configuration_itemsc sRtj_t}xD]\}ddkrBq jdkry t|}Wn,t k rt j|} |YnXnjdkr| }fdd|D}nhjdkr | j}||}jpd}jpi}j||f||n|}||j<q Wx|D]tj|<q.Wd_|S) zUpdates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).z--N) store_true store_falsecountrcsg|]}|qSr)rm)rBv)rjrrrrrEsz7ConfigOptionParser._update_defaults..callbackr)rValuesrOvaluessetrx get_optionactionr ValueErrorinvalid_config_error_messageerrorrFaddr%get_opt_string convert_value callback_argscallback_kwargsr}rmgetattr)rrO late_evalrk error_msgopt_strrrr)rjrrrrNs:          z#ConfigOptionParser._update_defaultsc Cs|jst|jSy|jWn2tk rR}z|tt |Wdd}~XYnX| |j }x@| D]4}| |j}t|trn|}|||||j<qnWt|S)zOverriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.N)process_default_valuesrr~rOraloadrrirstrrNcopy_get_all_optionsgetr% isinstancerrre)rerrrOrdefaultrrrrget_default_valuess "  z%ConfigOptionParser.get_default_valuescCs"|tj|td|dS)Nz{} ) print_usagerhstderrrirr')rr3rrrrs zConfigOptionParser.errorN) rIrJrKrLrrmrxrNrrrrrrr^s 1r^cCs |dkrd||Sd||S)zQReturns a better error message when invalid configuration option is provided.)ryrzzo{0} is not a valid value for {1} option, please specify a boolean value like yes/no, true/false or 1/0 instead.z[{0} is not a valid value for {1} option, please specify a numerical value like 1/0 instead.)r')rrjrkrrrrs r)rL __future__rloggingrrhr0distutils.utilrZpip._vendor.sixrpip._internal.cli.status_codesrpip._internal.configurationrrpip._internal.utils.compatr getLoggerrIrrrr rMrcrQr^rrrrrs       P wcli/__pycache__/autocompletion.cpython-37.pyc000064400000011613152352421750015224 0ustar00B Re@sdZddlZddlZddlZddlmZddlmZddlm Z m Z ddl m Z ddl mZerxddlmZmZmZmZd d Zd d Zd dZdS)zBLogic that powers autocompletion installed by ``pip completion``. N)chain)create_main_parser) commands_dictcreate_command)get_installed_distributions)MYPY_CHECK_RUNNING)AnyIterableListOptionalcsdtjkrdStjddd}ttjd}y||dWntk rZdYnXt}tt}g}d}x|D]}||krx|}PqxW|dk r>|dkrt d|dko d  }|r6g} } x}|d}|dr.|ddddkr.|d7}t|qWndd |jD}||jt|} d rxN|D]$} | jtjkrv|| j| j7}qvWn t|||}|rtt|}tdfdd |Dt ddS)z?Entry Point for completion of main and subcommand options. PIP_AUTO_COMPLETEN COMP_WORDS COMP_CWORDhelp)show uninstall-T) local_onlycSsg|]}|ddqS)=r)split).0xr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/autocompletion.py Hsz autocomplete..cs g|]\}}|kr||fqSrr)rrv) prev_optsrrrIscs"g|]\}}|r||fqSr) startswith)rkr)currentrrrKscSsg|] }|dfqS)rr)rpathrrrrTsrz--rcSsg|] }|jqSr) option_list)rirrrr^s csg|]}|r|qSr)r)rr)r!rrrms) osenvironrint IndexErrorrlistrsysexitrlowerrkeyappendprintrparseroption_list_allroptparse SUPPRESS_HELP _long_opts _short_optsnargsget_path_completion_typeauto_complete_paths option_groupsr$r from_iterablejoin)cwordscwordr2 subcommandsoptionssubcommand_namewordshould_list_installed installedlcdist subcommandoptopt_strcompletion_typepathsoption opt_labeloptsflattened_optsr)r!rr autocompletes~               rQcCs|dks||ddsdSxr|D]j}|jtjkr6q$xVt|dD]D}||ddd|krF|jrtdd|jdDrF|jSqFWq$WdS) aLGet the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) r#rN/rrcss|]}|dkVqdS))r"filedirNr)rrrrr sz+get_path_completion_type..)rrr4r5strrmetavarany)r>r?rOrIorrrr9qs   r9c#stj|\}tj|}t|tjs.dStjfddt|D}xh|D]`}tj||}tjtj||}|dkrtj |r|VqXtj |rXtj|dVqXWdS)aoIf ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A generator of regular files and/or directories Nc3s$|]}tj|r|VqdS)N)r'r"normcaser)rr)filenamerrrUsz&auto_complete_paths..rTr) r'r"rabspathaccessR_OKrZlistdirr=isfileisdir)r!rK directory current_path file_listfrI comp_filer)r[rr:s     r:)__doc__r4r'r, itertoolsrpip._internal.cli.main_parserrpip._internal.commandsrrpip._internal.utils.miscrpip._internal.utils.typingrtypingrr r r rQr9r:rrrrs    _cli/__pycache__/cmdoptions.cpython-37.pyc000064400000050423152352421750014343 0ustar00B Renp@sdZddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z m Z ddlmZddlmZdd lmZdd lmZmZdd lmZdd lmZdd lmZddlmZddlmZerddl m!Z!m"Z"m#Z#m$Z$m%Z%ddl m&Z&m'Z'ddl(m)Z)ddZ*ddZ+dddZ,dddZ-ddZ.Gddde Z/e e d d!d"d"d#d$Z0e e d%d&d'dd(d)Z1e e d*d+d,d'de d)Z2e e d-d.d/d0dd1d)Z3e e d2d3d'dd4d)Z4e e d5d6d7d'd8d$Z5e e d9d:d;d0ddd?e7e8d@dAdB9e8dCdDZ:e e/dEdFdGdHdIdIdJdKZ;e e dLdMd'ddNd)Ze e dZd[d\d]d^d_d`daZ?dbdcZ@e e/dddedIdIdfdgZAe e/dhdidIddIdjdkZBe e dldmdndodpejCdqdrZDdsdtZEe e dudvd'ddwd)ZFdxdyZGdzd{ZHd|d}ZId~dZJddZKddZLe e/ddddddIdedeLdd ZMddZNddZOddZPddZQddZRe e ddddddrZSddZTddZUe e ddddeUdQdedd ZVe e ddddddrZWe e ddddddrZXddZYddZZddZ[e e/ddeddIddZ\ddZ]e e ddde]ddZ^e e dddd'ddd)Z_ddZ`e e/ddddddIdde`ddÍ Zae e ddd'dd$Zbe e dddddd)Zcdd̈́Zde e ddd'ddd)Zee e dddedde dҍZfe e dddddd؍Zge e dddddd؍Zhe e dd'dddލZie e dd'dddލZje e ddd'ddd)ZkddZle e dddeldddZme e ddd'ddd)Zne e/ddIdIdddZoddZpe e ddd'ddd)Zqe e ddddgdge dZre e ddddgddgddZse e ddddggddZtde0e1e2e3e5e6e;ee?e@eHeAeBe\e^eke4eqeresetgdZudeDeEeFeGgdZvdS(aC shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parses general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this design. )absolute_importN) strtobool)partial) SUPPRESS_HELPOption OptionGroup)dedent) BAR_TYPES) CommandError)USER_CACHE_DIRget_src_prefix) FormatControl)PyPI) TargetPython) STRONG_HASHES)MYPY_CHECK_RUNNING)AnyCallableDictOptionalTuple) OptionParserValues)ConfigOptionParsercCs.d||}td|}||dS)z Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. z {} error: {} N)formattextwrapfilljoinspliterror)parseroptionmsgr$/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/cmdoptions.pyraise_option_error&s r&cCs0t||d}x|dD]}||qW|S)z Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser nameoptions)r add_option)groupr! option_groupr"r$r$r%make_option_group5sr,csPdkr |fdd}dddg}tt||rL|j}|tjddd dS) zDisable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. Ncs t|dS)N)getattr)n) check_optionsr$r%getnameMsz+check_install_build_global..getname build_optionsglobal_optionsinstall_optionszbDisabling all use of wheels due to the use of --build-option / --global-option / --install-option.) stacklevel)anymapformat_controldisallow_binarieswarningswarn)r(r/r0namescontrolr$)r/r%check_install_build_globalBs  r>FcCsbt|j|j|j|jg}ttdh}|j|ko6|j }|rH|rHt d|r^|r^|j s^t ddS)zFunction for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. z:all:zWhen restricting platform and interpreter constraints using --python-version, --platform, --abi, or --implementation, either --no-deps must be set, or --only-binary=:all: must be set and --no-binary must not be set (or must be set to :none:).zQCan not use any platform or abi specific options unless installing via '--target'N) r6python_versionplatformabiimplementationr setr8ignore_dependenciesr target_dir)r( check_targetdist_restriction_set binary_onlysdist_dependencies_allowedr$r$r%check_dist_restrictionZs   rJcCs tj|S)N)ospath expanduser)r"optvaluer$r$r%_path_option_checksrPc@s(eZdZejdZejZeed<dS) PipOption)rLrLN)__name__ __module__ __qualname__rTYPES TYPE_CHECKERcopyrPr$r$r$r%rQs  rQz-hz--helphelpz Show help.)destactionrXz --isolated isolated_mode store_truezSRun pip in an isolated mode, ignoring environment variables and user configuration.)rYrZdefaultrXz--require-virtualenvz--require-venv require_venvz-vz --verboseverbosecountzDGive more output. Option is additive, and can be used up to 3 times.z --no-colorno_colorzSuppress colored outputz-Vz --versionversionzShow version and exit.z-qz--quietquietzGive less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels).z--progress-bar progress_barchoiceonz*Specify type of progress to be displayed [|z] (default: %default))rYtypechoicesr]rXz--logz --log-filez --local-loglogrLz Path to a verbose appending log.)rYmetavarrhrXz --no-inputno_inputzDisable prompting for input.z--proxyproxystrz/src". The default for global installs is "/src".)rYrhrkr]rZrrXcCs t||jS)zGet a format_control object.)r-rY)rr"r$r$r%_get_format_controlsrcCs"t|j|}t||j|jdS)N)rrr handle_mutual_excludes no_binary only_binary)r"rrOr!existingr$r$r%_handle_no_binarys rcCs"t|j|}t||j|jdS)N)rrr rrr)r"rrOr!rr$r$r%_handle_only_binarys rc Cs$ttt}tdddtd|ddS)Nz --no-binaryr8rrnavDo not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all binary packages, ":none:" to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.)rYrZrrhr]rX)r rCrr)r8r$r$r%rs rc Cs$ttt}tdddtd|ddS)Nz --only-binaryr8rrnaKDo not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either ":all:" to disable all source packages, ":none:" to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.)rYrZrrhr]rX)r rCrr)r8r$r$r%rs rz --platformr@z[Only use wheels compatible with . Defaults to the platform of the running system.cCs|sdS|d}t|dkr"dSt|dkrV|d}t|dkrV|d|ddg}ytdd |D}Wntk rd SX|dfS) z Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. :return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. )NN.)r$z'at most three version parts are allowedrNcss|]}t|VqdS)N)rq).0partr$r$r% sz*_convert_python_version..)r$z$each version part must be an integer)rlentuple ValueError)rOparts version_infor$r$r%_convert_python_versions    rcCs:t|\}}|dk r.d||}t|||d||j_dS)z3 Handle a provided --python-version value. Nz(invalid --python-version value: {!r}: {})r"r#)rrr&rr?)r"rrOr!r error_msgr#r$r$r%_handle_python_versions  rz--python-versionr?a The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). )rYrkrZrrhr]rXz--implementationrBzOnly use wheels compatible with Python implementation , e.g. 'pp', 'jy', 'cp', or 'ip'. If not specified, then the current interpreter implementation is used. Use 'py' to force implementation-agnostic wheels.z--abirAzOnly use wheels compatible with Python abi , e.g. 'pypy_41'. If not specified, then the current interpreter abi tag is used. Generally you will need to specify --implementation, --platform, and --python-version when using this option.cCs4|t|t|t|tdS)N)r)r@r?rBrA)cmd_optsr$r$r%add_target_python_optionsVs   rcCst|j|j|j|jd}|S)N)r@py_version_inforArB)rr@r?rArB)r( target_pythonr$r$r%make_target_python^s  rcCstddddddS)Nz--prefer-binary prefer_binaryr\Fz8Prefer older binary packages over newer source packages.)rYrZr]rX)rr$r$r$r%rjs rz --cache-dir cache_dirzStore the cache data in .)rYr]rkrhrXc CsV|dk rJy t|Wn4tk rH}zt||t|dWdd}~XYnXd|j_dS)z Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. N)r"r#F)rrr&rnrr)r"rNrOr!excr$r$r%_handle_no_cache_dirs  $ rz--no-cache-dirzDisable the cache.)rYrZrrXz --no-depsz--no-dependenciesrDz#Don't install package dependencies.cCs$|rtj|}t|j|j|dS)N)rKrLrrrrY)r"rNrOr!r$r$r%_handle_build_dirs rz-bz--buildz --build-dirz--build-directory build_diraK(DEPRECATED) Directory to unpack packages into and build in. Note that an initial build still takes place in a temporary directory. The location of temporary directories can be controlled by setting the TMPDIR environment variable (TEMP on Windows) appropriately. When passed, build directories are not cleaned in case of failures.)rYrhrkrZrrXz--ignore-requires-pythonignore_requires_pythonz'Ignore the Requires-Python information.z--no-build-isolationbuild_isolation store_falseTzDisable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.cCs&|dk rd}t|||dd|j_dS)z Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. Na0A value was passed for --no-use-pep517, probably using either the PIP_NO_USE_PEP517 environment variable or the "no-use-pep517" config file option. Use an appropriate value of the PIP_USE_PEP517 environment variable or the "use-pep517" config file option instead. )r"r#F)r&r use_pep517)r"rNrOr!r#r$r$r%_handle_no_use_pep517s rz --use-pep517rz^Use PEP 517 for building source distributions (use --no-use-pep517 to force legacy behaviour).z--no-use-pep517)rYrZrr]rXz--install-optionr3r}r(a"Extra arguments to be supplied to the setup.py install command (use like --install-option="--install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.)rYrZrkrXz--global-optionr2zTExtra global options to be supplied to the setup.py call before the install command.z --no-cleanz!Don't clean up build directories.)rZr]rXz--prezYInclude pre-release and development versions. By default, pip only finds stable versions.z--disable-pip-version-checkdisable_pip_version_checkz{Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.cCs|jjsi|j_y|dd\}}Wn$tk rH|d|YnX|tkrj|d|dt|jj|g |dS)zkGiven a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.:rzTArguments to {} must be a hash name followed by a value, like --hash=sha256:abcde...z&Allowed hash algorithms for {} are {}.z, N) rhashesrrr rrr setdefaultr})r"rrOr!algodigestr$r$r%_handle_merge_hash9srz--hashrstringzgVerify that the package's archive matches this hash before installing. Example: --hash=sha256:abcdef...)rYrZrrhrXz--require-hashesrequire_hasheszRequire a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a --hash option.z--pathz^Restrict to the specified installation path for listing packages (can be used multiple times).)rYrhrZrXcCs|jr|js|jrtddS)Nz2Cannot combine '--path' with '--user' or '--local')rLuserlocalr )r(r$r$r%check_list_path_optionpsrz--no-python-version-warningno_python_version_warningz>Silence deprecation warnings for upcoming unsupported Pythons.z--unstable-featureunstable_featuresfeatureresolver)rYrkrZr]rirXz --use-featurefeatures_enabledz 2020-resolverz fast-depszrJrPrQhelp_r[require_virtualenvr_rarbrclistkeysrrdrjrlrmrprtrwr~r simple_urlrrrrrrrrrsrcrrrrrr@rrr?rBrArrrrrno_cacheno_depsrrrno_build_isolationrr no_use_pep517r3r2no_cleanprerrhashr list_pathrrunstable_featureuse_new_featureuse_deprecated_feature general_group index_groupr$r$r$r%s              (            cli/__pycache__/spinners.cpython-37.pyc000064400000011223152352421750014020 0ustar00B Re@sddlmZmZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddl mZddlmZerddlmZmZeeZGdd d eZGd d d eZGd d d eZGdddeZejddZejddZdS))absolute_importdivisionN) HIDE_CURSOR SHOW_CURSOR)WINDOWS)get_indentation)MYPY_CHECK_RUNNING)IteratorIOc@seZdZddZddZdS)SpinnerInterfacecCs tdS)N)NotImplementedError)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/spinners.pyspinszSpinnerInterface.spincCs tdS)N)r )r final_statusrrrfinishszSpinnerInterface.finishN)__name__ __module__ __qualname__rrrrrrr sr c@s.eZdZd ddZddZdd Zd d ZdS) InteractiveSpinnerN-\|/?cCs\||_|dkrtj}||_t||_d|_t||_ |j dt |jdd|_ dS)NF z ... r) _messagesysstdout_file RateLimiter _rate_limiter _finished itertoolscycle _spin_cyclewriter_width)r messagefile spin_charsmin_update_interval_secondsrrr__init__ s  zInteractiveSpinner.__init__cCs\|jr td|j}|j|d|j||j|t||_|j|jdS)Nr) r AssertionErrorr%rr$lenflushrreset)r statusbackuprrr_write0s     zInteractiveSpinner._writecCs,|jr dS|jsdS|t|jdS)N)r rreadyr2nextr#)r rrrr=s  zInteractiveSpinner.spincCs4|jr dS|||jd|jd|_dS)N T)r r2rr$r.)r rrrrrEs    zInteractiveSpinner.finish)Nrr)rrrr*r2rrrrrrrs   rc@s.eZdZd ddZddZddZdd Zd S) NonInteractiveSpinner<cCs$||_d|_t||_|ddS)NFstarted)rr rr_update)r r&r)rrrr*Ts zNonInteractiveSpinner.__init__cCs(|jr t|jtd|j|dS)Nz%s: %s)r r,rr/loggerinfor)r r0rrrr9[s  zNonInteractiveSpinner._updatecCs&|jr dS|jsdS|ddS)Nzstill running...)r rr3r9)r rrrras  zNonInteractiveSpinner.spincCs(|jr dS|djftd|_dS)Nz%finished with status '{final_status}'T)r r9formatlocals)r rrrrris zNonInteractiveSpinner.finishN)r7)rrrr*r9rrrrrrr6Ss r6c@s$eZdZddZddZddZdS)rcCs||_d|_dS)Nr)_min_update_interval_seconds _last_update)r r)rrrr*sszRateLimiter.__init__cCst}||j}||jkS)N)timer?r>)r nowdeltarrrr3xs zRateLimiter.readycCst|_dS)N)r@r?)r rrrr/~szRateLimiter.resetN)rrrr*r3r/rrrrrrsrc cstjr"ttjkr"t|}nt|}y t tj |VWdQRXWn>t k rj| dYn*t k r| dYn X| ddS)Ncancelederrordone) rrisattyr:getEffectiveLevelloggingINFOrr6 hidden_cursorKeyboardInterruptr Exception)r&spinnerrrr open_spinners    rNc csPtr dVn@|r"ttjkr*dVn"|tz dVWd|tXdS)N) rrFr:rGrHrIr$rr)r'rrrrJs  rJ) __future__rr contextlibr!rHrr@Zpip._vendor.progressrrpip._internal.utils.compatrpip._internal.utils.loggingrpip._internal.utils.typingrtypingr r getLoggerrr:objectr rr6rcontextmanagerrNrJrrrrs$     4cli/__pycache__/main_parser.cpython-37.pyc000064400000004316152352421750014464 0ustar00B Re @sdZddlZddlZddlmZddlmZmZddlm Z m Z ddl m Z ddl mZmZddlmZer|dd lmZmZd d gZd d Zd d ZdS)z=A single place for constructing and exposing the main parser N) cmdoptions)ConfigOptionParserUpdatingDefaultsHelpFormatter) commands_dictget_similar_commands) CommandError)get_pip_versionget_prog)MYPY_CHECK_RUNNING)TupleListcreate_main_parser parse_commandcCstddtdtd}tf|}|t|_ttj|}| |d|_ dgddt D}d ||_|S) z6Creates and returns the main parser for pip's CLI z %prog [options]Fglobal)usageadd_help_option formatternameprogTcSsg|]\}}djftqS)z {name:27} {command_info.summary})formatlocals).0r command_infor/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/main_parser.py 3sz&create_main_parser.. )rr rdisable_interspersed_argsrversionrmake_option_group general_groupadd_option_groupmainritemsjoin description) parser_kwparsergen_optsr&rrrr s     cCst}||\}}|jr>tj|jtjtjt|rZ|ddkrjt |dkrj| t|d}|t krt |}d |g}|r|d |td||dd}||||fS)Nrhelpzunknown command "{}"zmaybe you meant "{}"z - )r parse_argsrsysstdoutwriteoslinesepexitlen print_helprrrappendrr%remove)argsr(general_options args_elsecmd_nameguessmsgcmd_argsrrrr;s&    )__doc__r0r-Zpip._internal.clirpip._internal.cli.parserrrpip._internal.commandsrrpip._internal.exceptionsrpip._internal.utils.miscrr pip._internal.utils.typingr typingr r __all__r rrrrrs   #cli/__pycache__/status_codes.cpython-37.pyc000064400000000664152352421750014666 0ustar00B Re@s(ddlmZdZdZdZdZdZdZdS))absolute_importN) __future__rSUCCESSERROR UNKNOWN_ERRORVIRTUALENV_NOT_FOUNDPREVIOUS_BUILD_DIR_ERRORNO_MATCHES_FOUNDrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/status_codes.pys cli/__pycache__/progress_bars.cpython-37.pyc000064400000017010152352421750015032 0ustar00B Re#@sddlmZddlZddlZddlmZmZmZddlmZddl m Z m Z m Z ddl mZddlmZddlmZdd lmZdd lmZerdd lmZmZmZydd lmZWnek rdZYnXd dZee e ZGdddeZ Gddde Z!Gddde Z"GdddeZ#GdddeZ$Gddde$e e#Z%Gddde%eZ&Gddde%e!Z'Gdd d e%e Z(Gd!d"d"e%e Z)Gd#d$d$e%e"Z*Gd%d&d&e$e e#eZ+e'e'fe&e+fe(e+fe)e+fe*e+fd'Z,d*d(d)Z-dS)+)divisionN)SIGINTdefault_int_handlersignal)six)BarFillingCirclesBarIncrementalBar)Spinner)WINDOWS)get_indentation) format_size)MYPY_CHECK_RUNNING)AnyDictList)coloramacCst|jdd}|s|St|dtt|dtg}|tt|dg7}yt||Wntk rv|SX|SdS)Nencoding empty_fillfillphases)getattrfiler text_typelistjoinencodeUnicodeEncodeError) preferredfallbackr charactersr!/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/progress_bars.py_select_progress_classsr#cs4eZdZdZfddZfddZddZZS)InterruptibleMixina Helper to ensure that self.finish() gets called on keyboard interrupt. This allows downloads to be interrupted without leaving temporary state (like hidden cursors) behind. This class is similar to the progress library's existing SigIntMixin helper, but as of version 1.2, that helper has the following problems: 1. It calls sys.exit(). 2. It discards the existing SIGINT handler completely. 3. It leaves its own handler in place even after an uninterrupted finish, which will have unexpected delayed effects if the user triggers an unrelated keyboard interrupt some time after a progress-displaying download has already completed, for example. cs4tt|j||tt|j|_|jdkr0t|_dS)z= Save the original SIGINT handler for later. N)superr$__init__rr handle_sigintoriginal_handlerr)selfargskwargs) __class__r!r"r&Ls   zInterruptibleMixin.__init__cstt|tt|jdS)z Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. N)r%r$finishrrr()r))r,r!r"r-aszInterruptibleMixin.finishcCs||||dS)z Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. N)r-r()r)signumframer!r!r"r'lsz InterruptibleMixin.handle_sigint)__name__ __module__ __qualname____doc__r&r-r' __classcell__r!r!)r,r"r$:s  r$c@seZdZddZdS) SilentBarcCsdS)Nr!)r)r!r!r"updateyszSilentBar.updateN)r0r1r2r6r!r!r!r"r5wsr5c@seZdZdZdZdZdZdS) BlueEmojiBarz %(percent)d%% )u🔹u🔷u🔵N)r0r1r2suffix bar_prefix bar_suffixrr!r!r!r"r7~sr7csHeZdZfddZeddZeddZeddZd d ZZ S) DownloadProgressMixincs,tt|j||dtd|j|_dS)Nr8)r%r<r&r message)r)r*r+)r,r!r"r&s   zDownloadProgressMixin.__init__cCs t|jS)N)r index)r)r!r!r" downloadedsz DownloadProgressMixin.downloadedcCs |jdkrdStd|jdS)Ngz...z/s)avgr )r)r!r!r"download_speeds z$DownloadProgressMixin.download_speedcCs|jrd|jSdS)Nzeta {})etaformateta_td)r)r!r!r" pretty_etas z DownloadProgressMixin.pretty_etaccs.x |D]}|V|t|qW|dS)N)nextlenr-)r)itxr!r!r"iters zDownloadProgressMixin.iter) r0r1r2r&propertyr@rCrHrMr4r!r!)r,r"r<s    r<cseZdZfddZZS) WindowsMixincs\trjrd_ttj||trXtrXtj_fddj_fddj_ dS)NFcs jjS)N)rwrappedisattyr!)r)r!r"z'WindowsMixin.__init__..cs jjS)N)rrPflushr!)r)r!r"rRrS) r hide_cursorr%rOr&r AnsiToWin32rrQrT)r)r*r+)r,)r)r"r&s zWindowsMixin.__init__)r0r1r2r&r4r!r!)r,r"rOsrOc@seZdZejZdZdZdS)BaseDownloadProgressBarz %(percent)d%%z0%(downloaded)s %(download_speed)s %(pretty_eta)sN)r0r1r2sysstdoutrr>r9r!r!r!r"rWsrWc@s eZdZdS)DefaultDownloadProgressBarN)r0r1r2r!r!r!r"rZsrZc@s eZdZdS)DownloadSilentBarN)r0r1r2r!r!r!r"r[sr[c@s eZdZdS) DownloadBarN)r0r1r2r!r!r!r"r\sr\c@s eZdZdS)DownloadFillingCirclesBarN)r0r1r2r!r!r!r"r]sr]c@s eZdZdS)DownloadBlueEmojiProgressBarN)r0r1r2r!r!r!r"r^sr^c@s&eZdZejZdZddZddZdS)DownloadProgressSpinnerz!%(downloaded)s %(download_speed)scCs"t|dst|j|_t|jS)N_phaser)hasattr itertoolscyclerr`rI)r)r!r!r" next_phases z"DownloadProgressSpinner.next_phasecCsN|j|}|}|j|}d||r*dnd||r6dnd|g}||dS)NrDr8)r>rdr9rwriteln)r)r>phaser9liner!r!r"r6s    zDownloadProgressSpinner.updateN) r0r1r2rXrYrr9rdr6r!r!r!r"r_sr_)offonasciiprettyemojicCs8|dks|dkr t|djSt|d|djSdS)NrrA)max) BAR_TYPESrM) progress_barrmr!r!r"DownloadProgressProvidersrp)N). __future__rrbrXrrr pip._vendorrpip._vendor.progress.barrrr pip._vendor.progress.spinnerr pip._internal.utils.compatr pip._internal.utils.loggingr pip._internal.utils.miscr pip._internal.utils.typingrtypingrrrr Exceptionr#_BaseBarobjectr$r5r7r<rOrWrZr[r\r]r^r_rnrpr!r!r!r"sT         =*     cli/__pycache__/__init__.cpython-37.pyc000064400000000463152352421750013722 0ustar00B Re@sdZdS)zGSubpackage containing all of pip's command line interface related code N)__doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/cli/__init__.pycli/__pycache__/base_command.cpython-37.pyc000064400000014674152352421750014604 0ustar00B ReV$@sjdZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZddlmZmZddlmZmZmZmZddlmZmZmZmZmZmZmZdd lm Z dd l!m"Z"dd l#m$Z$m%Z%dd l&m'Z'm(Z(dd l)m*Z*m+Z+ddl,m-Z-ddl.m/Z/e-rFddl0m1Z1m2Z2m3Z3m4Z4ddlm5Z5ddl)m6Z7dgZ8e9e:Z;GdddeZs&   zCommand.__init__cCsdS)Nr>)r9r>r>r?r8^szCommand.add_optionscCst|drtdS)zf This is a no-op so that commands by default do not do the pip version check. no_indexN)hasattrAssertionError)r9optionsr>r>r?handle_pip_version_checkbsz Command.handle_pip_version_checkcCstdS)N)NotImplementedError)r9rCargsr>r>r?runlsz Command.runcCs |j|S)N)r0 parse_args)r9rFr>r>r?rHpszCommand.parse_argsc Cs.z| ||SQRXWdtXdS)N) main_context_mainloggingshutdown)r9rFr>r>r?mainus z Command.mainc Cs|t|_|t||\}}|j|j|_t|j|j|j d}t j dddkr|j sd}t dkrzd|}t|dddt j ddd kr|j sd }t|ddd|jrd tjd <|jrd |jtjd<|jr|jststdt t|jr:t|j|_t|js:td|jd|_t |ddrXtdddddd|j!krxtdt t"zvy |#||}t$|t%st&|St'k r}z tt(|tj)dddt*Sd}~XYnt+t,t-t.t/fk r&}z tt(|tj)dddt"Sd}~XYnt0k rb}ztd|tj)dddt"Sd}~XYnt1k rt2dt j3d|t4j5krt6j7t j3dt"St8k rtdtj)dddt"St9k rtjd ddt:SXWd|;|XdS)!N) verbosityno_color user_log_file)rQzpip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-supportCPythonzPython 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. z21.0) replacementgone_in)zPython 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021.1 PIP_NO_INPUT PIP_EXISTS_ACTIONz2Could not find an activated virtualenv (required).zThe directory '%s' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. build_dirzBThe -b/--build/--build-dir/--build-directory option is deprecated.zOuse the TMPDIR/TEMP/TMP environment variable, possibly combined with --no-cleanz20.3i )reasonrTrUissueresolverzs--unstable-feature=resolver is no longer supported, and has been replaced with --use-feature=2020-resolver instead.zException information:T)exc_infoz%sz ERROR: Pipe to stdout was broken)filezOperation cancelled by userz Exception:)< enter_contextrrrHverbosequietrNrrOlogsys version_infono_python_version_warningplatformpython_implementationrno_inputosenviron exists_actionjoin require_venvignore_require_venvrloggercriticalexitr cache_dirrrwarninggetattrunstable_featuresrrG isinstanceintrBrstrdebugr rrr rrr rprintstderrrKDEBUG traceback print_excKeyboardInterrupt BaseExceptionr rD)r9rFrC level_numbermessagestatusexcr>r>r?rJ}s              z Command._main)F) __name__ __module__ __qualname__r$rqr,r8rDrGrHrMrJ __classcell__r>r>)r=r?r#:s  )=r. __future__rrrKlogging.configr2rlrirfrZpip._internal.clir!pip._internal.cli.command_contextrpip._internal.cli.parserrrpip._internal.cli.status_codesrr r r pip._internal.exceptionsr r rrrrrpip._internal.utils.deprecationrpip._internal.utils.filesystemrpip._internal.utils.loggingrrpip._internal.utils.miscrrpip._internal.utils.temp_dirrrpip._internal.utils.typingrpip._internal.utils.virtualenvrtypingrrrr r!r"ZTempDirRegistry__all__ getLoggerrrrr#r>r>r>r?s6  $       cli/spinners.py000064400000012605152352421750007540 0ustar00from __future__ import absolute_import, division import contextlib import itertools import logging import sys import time from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR from pip._internal.utils.compat import WINDOWS from pip._internal.utils.logging import get_indentation from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Iterator, IO logger = logging.getLogger(__name__) class SpinnerInterface(object): def spin(self): # type: () -> None raise NotImplementedError() def finish(self, final_status): # type: (str) -> None raise NotImplementedError() class InteractiveSpinner(SpinnerInterface): def __init__(self, message, file=None, spin_chars="-\\|/", # Empirically, 8 updates/second looks nice min_update_interval_seconds=0.125): # type: (str, IO[str], str, float) -> None self._message = message if file is None: file = sys.stdout self._file = file self._rate_limiter = RateLimiter(min_update_interval_seconds) self._finished = False self._spin_cycle = itertools.cycle(spin_chars) self._file.write(" " * get_indentation() + self._message + " ... ") self._width = 0 def _write(self, status): # type: (str) -> None assert not self._finished # Erase what we wrote before by backspacing to the beginning, writing # spaces to overwrite the old text, and then backspacing again backup = "\b" * self._width self._file.write(backup + " " * self._width + backup) # Now we have a blank slate to add our status self._file.write(status) self._width = len(status) self._file.flush() self._rate_limiter.reset() def spin(self): # type: () -> None if self._finished: return if not self._rate_limiter.ready(): return self._write(next(self._spin_cycle)) def finish(self, final_status): # type: (str) -> None if self._finished: return self._write(final_status) self._file.write("\n") self._file.flush() self._finished = True # Used for dumb terminals, non-interactive installs (no tty), etc. # We still print updates occasionally (once every 60 seconds by default) to # act as a keep-alive for systems like Travis-CI that take lack-of-output as # an indication that a task has frozen. class NonInteractiveSpinner(SpinnerInterface): def __init__(self, message, min_update_interval_seconds=60): # type: (str, float) -> None self._message = message self._finished = False self._rate_limiter = RateLimiter(min_update_interval_seconds) self._update("started") def _update(self, status): # type: (str) -> None assert not self._finished self._rate_limiter.reset() logger.info("%s: %s", self._message, status) def spin(self): # type: () -> None if self._finished: return if not self._rate_limiter.ready(): return self._update("still running...") def finish(self, final_status): # type: (str) -> None if self._finished: return self._update( "finished with status '{final_status}'".format(**locals())) self._finished = True class RateLimiter(object): def __init__(self, min_update_interval_seconds): # type: (float) -> None self._min_update_interval_seconds = min_update_interval_seconds self._last_update = 0 # type: float def ready(self): # type: () -> bool now = time.time() delta = now - self._last_update return delta >= self._min_update_interval_seconds def reset(self): # type: () -> None self._last_update = time.time() @contextlib.contextmanager def open_spinner(message): # type: (str) -> Iterator[SpinnerInterface] # Interactive spinner goes directly to sys.stdout rather than being routed # through the logging system, but it acts like it has level INFO, # i.e. it's only displayed if we're at level INFO or better. # Non-interactive spinner goes through the logging system, so it is always # in sync with logging configuration. if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO: spinner = InteractiveSpinner(message) # type: SpinnerInterface else: spinner = NonInteractiveSpinner(message) try: with hidden_cursor(sys.stdout): yield spinner except KeyboardInterrupt: spinner.finish("canceled") raise except Exception: spinner.finish("error") raise else: spinner.finish("done") @contextlib.contextmanager def hidden_cursor(file): # type: (IO[str]) -> Iterator[None] # The Windows terminal does not support the hide/show cursor ANSI codes, # even via colorama. So don't even try. if WINDOWS: yield # We don't want to clutter the output with control characters if we're # writing to a file, or if the user is running with --quiet. # See https://github.com/pypa/pip/issues/3418 elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO: yield else: file.write(HIDE_CURSOR) try: yield finally: file.write(SHOW_CURSOR) cli/main.py000064400000005070152352421750006621 0ustar00"""Primary application entrypoint. """ from __future__ import absolute_import import locale import logging import os import sys from pip._internal.cli.autocompletion import autocomplete from pip._internal.cli.main_parser import parse_command from pip._internal.commands import create_command from pip._internal.exceptions import PipError from pip._internal.utils import deprecation from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional logger = logging.getLogger(__name__) # Do not import and use main() directly! Using it directly is actively # discouraged by pip's maintainers. The name, location and behavior of # this function is subject to change, so calling it directly is not # portable across different pip versions. # In addition, running pip in-process is unsupported and unsafe. This is # elaborated in detail at # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program. # That document also provides suggestions that should work for nearly # all users that are considering importing and using main() directly. # However, we know that certain users will still want to invoke pip # in-process. If you understand and accept the implications of using pip # in an unsupported manner, the best approach is to use runpy to avoid # depending on the exact location of this entry point. # The following example shows how to use runpy to invoke pip in that # case: # # sys.argv = ["pip", your, args, here] # runpy.run_module("pip", run_name="__main__") # # Note that this will exit the process after running, unlike a direct # call to main. As it is not safe to do any processing after calling # main, this should not be an issue in practice. def main(args=None): # type: (Optional[List[str]]) -> int if args is None: args = sys.argv[1:] # Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger() autocomplete() try: cmd_name, cmd_args = parse_command(args) except PipError as exc: sys.stderr.write("ERROR: {}".format(exc)) sys.stderr.write(os.linesep) sys.exit(1) # Needed for locale.getpreferredencoding(False) to work # in pip._internal.utils.encoding.auto_decode try: locale.setlocale(locale.LC_ALL, '') except locale.Error as e: # setlocale can apparently crash if locale are uninitialized logger.debug("Ignoring error %s when setting locale", e) command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) return command.main(cmd_args) cli/progress_bars.py000064400000021641152352421750010552 0ustar00from __future__ import division import itertools import sys from signal import SIGINT, default_int_handler, signal from pip._vendor import six from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar from pip._vendor.progress.spinner import Spinner from pip._internal.utils.compat import WINDOWS from pip._internal.utils.logging import get_indentation from pip._internal.utils.misc import format_size from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Any, Dict, List try: from pip._vendor import colorama # Lots of different errors can come from this, including SystemError and # ImportError. except Exception: colorama = None def _select_progress_class(preferred, fallback): # type: (Bar, Bar) -> Bar encoding = getattr(preferred.file, "encoding", None) # If we don't know what encoding this file is in, then we'll just assume # that it doesn't support unicode and use the ASCII bar. if not encoding: return fallback # Collect all of the possible characters we want to use with the preferred # bar. characters = [ getattr(preferred, "empty_fill", six.text_type()), getattr(preferred, "fill", six.text_type()), ] characters += list(getattr(preferred, "phases", [])) # Try to decode the characters we're using for the bar using the encoding # of the given file, if this works then we'll assume that we can use the # fancier bar and if not we'll fall back to the plaintext bar. try: six.text_type().join(characters).encode(encoding) except UnicodeEncodeError: return fallback else: return preferred _BaseBar = _select_progress_class(IncrementalBar, Bar) # type: Any class InterruptibleMixin(object): """ Helper to ensure that self.finish() gets called on keyboard interrupt. This allows downloads to be interrupted without leaving temporary state (like hidden cursors) behind. This class is similar to the progress library's existing SigIntMixin helper, but as of version 1.2, that helper has the following problems: 1. It calls sys.exit(). 2. It discards the existing SIGINT handler completely. 3. It leaves its own handler in place even after an uninterrupted finish, which will have unexpected delayed effects if the user triggers an unrelated keyboard interrupt some time after a progress-displaying download has already completed, for example. """ def __init__(self, *args, **kwargs): # type: (List[Any], Dict[Any, Any]) -> None """ Save the original SIGINT handler for later. """ # https://github.com/python/mypy/issues/5887 super(InterruptibleMixin, self).__init__( # type: ignore *args, **kwargs ) self.original_handler = signal(SIGINT, self.handle_sigint) # If signal() returns None, the previous handler was not installed from # Python, and we cannot restore it. This probably should not happen, # but if it does, we must restore something sensible instead, at least. # The least bad option should be Python's default SIGINT handler, which # just raises KeyboardInterrupt. if self.original_handler is None: self.original_handler = default_int_handler def finish(self): # type: () -> None """ Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. """ super(InterruptibleMixin, self).finish() # type: ignore signal(SIGINT, self.original_handler) def handle_sigint(self, signum, frame): # type: ignore """ Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. """ self.finish() self.original_handler(signum, frame) class SilentBar(Bar): def update(self): # type: () -> None pass class BlueEmojiBar(IncrementalBar): suffix = "%(percent)d%%" bar_prefix = " " bar_suffix = " " phases = (u"\U0001F539", u"\U0001F537", u"\U0001F535") # type: Any class DownloadProgressMixin(object): def __init__(self, *args, **kwargs): # type: (List[Any], Dict[Any, Any]) -> None # https://github.com/python/mypy/issues/5887 super(DownloadProgressMixin, self).__init__( # type: ignore *args, **kwargs ) self.message = (" " * ( get_indentation() + 2 )) + self.message # type: str @property def downloaded(self): # type: () -> str return format_size(self.index) # type: ignore @property def download_speed(self): # type: () -> str # Avoid zero division errors... if self.avg == 0.0: # type: ignore return "..." return format_size(1 / self.avg) + "/s" # type: ignore @property def pretty_eta(self): # type: () -> str if self.eta: # type: ignore return "eta {}".format(self.eta_td) # type: ignore return "" def iter(self, it): # type: ignore for x in it: yield x # B305 is incorrectly raised here # https://github.com/PyCQA/flake8-bugbear/issues/59 self.next(len(x)) # noqa: B305 self.finish() class WindowsMixin(object): def __init__(self, *args, **kwargs): # type: (List[Any], Dict[Any, Any]) -> None # The Windows terminal does not support the hide/show cursor ANSI codes # even with colorama. So we'll ensure that hide_cursor is False on # Windows. # This call needs to go before the super() call, so that hide_cursor # is set in time. The base progress bar class writes the "hide cursor" # code to the terminal in its init, so if we don't set this soon # enough, we get a "hide" with no corresponding "show"... if WINDOWS and self.hide_cursor: # type: ignore self.hide_cursor = False # https://github.com/python/mypy/issues/5887 super(WindowsMixin, self).__init__(*args, **kwargs) # type: ignore # Check if we are running on Windows and we have the colorama module, # if we do then wrap our file with it. if WINDOWS and colorama: self.file = colorama.AnsiToWin32(self.file) # type: ignore # The progress code expects to be able to call self.file.isatty() # but the colorama.AnsiToWin32() object doesn't have that, so we'll # add it. self.file.isatty = lambda: self.file.wrapped.isatty() # The progress code expects to be able to call self.file.flush() # but the colorama.AnsiToWin32() object doesn't have that, so we'll # add it. self.file.flush = lambda: self.file.wrapped.flush() class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin): file = sys.stdout message = "%(percent)d%%" suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar): pass class DownloadSilentBar(BaseDownloadProgressBar, SilentBar): pass class DownloadBar(BaseDownloadProgressBar, Bar): pass class DownloadFillingCirclesBar(BaseDownloadProgressBar, FillingCirclesBar): pass class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, BlueEmojiBar): pass class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner): file = sys.stdout suffix = "%(downloaded)s %(download_speed)s" def next_phase(self): # type: () -> str if not hasattr(self, "_phaser"): self._phaser = itertools.cycle(self.phases) return next(self._phaser) def update(self): # type: () -> None message = self.message % self phase = self.next_phase() suffix = self.suffix % self line = ''.join([ message, " " if message else "", phase, " " if suffix else "", suffix, ]) self.writeln(line) BAR_TYPES = { "off": (DownloadSilentBar, DownloadSilentBar), "on": (DefaultDownloadProgressBar, DownloadProgressSpinner), "ascii": (DownloadBar, DownloadProgressSpinner), "pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner), "emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner) } def DownloadProgressProvider(progress_bar, max=None): # type: ignore if max is None or max == 0: return BAR_TYPES[progress_bar][1]().iter else: return BAR_TYPES[progress_bar][0](max=max).iter models/__pycache__/wheel.cpython-37.pyc000064400000006235152352421750014006 0ustar00B Re @sTdZddlZddlmZddlmZddlmZer@ddlm Z Gddde Z dS) z`Represents a wheel file and provides access to the various parts of the name that have meaning. N)Tag)InvalidWheelFilename)MYPY_CHECK_RUNNING)Listc@s>eZdZdZedejZddZddZ ddZ d d Z d S) Wheelz A wheel filez^(?P(?P.+?)-(?P.*?)) ((-(?P\d[^-]*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$csj|}|std||_|ddd_|ddd_|d_ |d d_ |d  d_ |d  d_ fd d j D_d S)zX :raises InvalidWheelFilename: when the filename is invalid for a wheel z!{} is not a valid wheel filename.name_-verbuildpyver.abiplatcs0h|](}jD]}jD]}t|||qqqS)abisplatsr).0xyz)selfr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/wheel.py .sz!Wheel.__init__..N) wheel_file_rematchrformatfilenamegroupreplacerversion build_tagsplit pyversionsrr file_tags)rr wheel_infor)rr__init__s    zWheel.__init__cCstdd|jDS)z4Return the wheel's tags as a sorted list of strings.css|]}t|VqdS)N)str)rtagrrr 6sz0Wheel.get_formatted_file_tags..)sortedr$)rrrrget_formatted_file_tags3szWheel.get_formatted_file_tagscstfdd|jDS)aReturn the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. c3s |]}|kr|VqdS)N)index)rr()tagsrrr)Fsz*Wheel.support_index_min..)minr$)rr-r)r-rsupport_index_min8szWheel.support_index_mincCs|j| S)zReturn whether the wheel is compatible with one of the given tags. :param tags: the PEP 425 tags to check the wheel against. )r$ isdisjoint)rr-rrr supportedHszWheel.supportedN) __name__ __module__ __qualname____doc__recompileVERBOSErr&r+r/r1rrrrrsr) r5r6pip._vendor.packaging.tagsrpip._internal.exceptionsrpip._internal.utils.typingrtypingrobjectrrrrrs    models/__pycache__/scheme.cpython-37.pyc000064400000001751152352421750014144 0ustar00B Re @s&dZdddddgZGdddeZdS) z For types associated with installation schemes. For a general overview of available schemes and their context, see https://docs.python.org/3/install/index.html#alternate-installation. platlibpurelibheadersscriptsdatac@seZdZdZeZddZdS)SchemeztA Scheme holds paths which are used as the base directories for artifacts associated with a Python package. cCs"||_||_||_||_||_dS)N)rrrrr)selfrrrrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/scheme.py__init__s zScheme.__init__N)__name__ __module__ __qualname____doc__ SCHEME_KEYS __slots__r rrrr r srN)rrobjectrrrrr smodels/__pycache__/index.cpython-37.pyc000064400000002345152352421750014007 0ustar00B Re@s8ddlmZGdddeZedddZedddZd S) )parsecs6eZdZdZdddddgZfddZd d ZZS) PackageIndexzGRepresents a Package Index and provides easier access to endpoints urlnetloc simple_urlpypi_urlfile_storage_domaincsDtt|||_t|j|_|d|_|d|_ ||_ dS)Nsimplepypi) superr__init__r urllib_parseurlsplitr _url_for_pathrrr)selfrr) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/index.pyr s   zPackageIndex.__init__cCst|j|S)N)r urljoinr)rpathrrrrszPackageIndex._url_for_path)__name__ __module__ __qualname____doc__ __slots__r r __classcell__rr)rrrs  rzhttps://pypi.org/zfiles.pythonhosted.org)rzhttps://test.pypi.org/ztest-files.pythonhosted.orgN)Zpip._vendor.six.moves.urllibrr objectrPyPITestPyPIrrrrs  models/__pycache__/candidate.cpython-37.pyc000064400000002761152352421750014616 0ustar00B Re@sTddlmZddlmZddlmZer@ddlmZddlm Z GdddeZ dS) )parse)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) _BaseVersion)Linkcs:eZdZdZdddgZfddZddZd d ZZS) InstallationCandidatez9Represents a potential "candidate" for installation. nameversionlinkcs:||_t||_||_tt|j|j|j|jftddS)N)keydefining_class)r parse_versionr r superr__init__)selfrr r ) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/candidate.pyrs   zInstallationCandidate.__init__cCsd|j|j|jS)Nz))formatrr r )rrrr__repr__szInstallationCandidate.__repr__cCsd|j|j|jS)Nz!{!r} candidate (version {} at {}))rrr r )rrrr__str__"szInstallationCandidate.__str__) __name__ __module__ __qualname____doc__ __slots__rrr __classcell__rr)rrr s   rN) pip._vendor.packaging.versionrr pip._internal.utils.modelsrpip._internal.utils.typingrrpip._internal.models.linkrrrrrrs     models/__pycache__/target_python.cpython-37.pyc000064400000006440152352421750015567 0ustar00B Re@shddlZddlmZmZddlmZddlmZerTddlm Z m Z m Z ddl m Z GdddeZdS) N) get_supportedversion_info_to_nodot)normalize_version_info)MYPY_CHECK_RUNNING)ListOptionalTuple)Tagc@s<eZdZdZdddddddgZdd d Zd d ZddZd S) TargetPythonzx Encapsulates the properties of a Python interpreter one is targeting for a package install, download, etc. _given_py_version_infoabiimplementationplatform py_versionpy_version_info _valid_tagsNcCsf||_|dkrtjdd}nt|}dtt|dd}||_||_||_ ||_ ||_ d|_ dS)a' :param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built locally. :param py_version_info: An optional tuple of ints representing the Python version information to use (e.g. `sys.version_info[:3]`). This can have length 1, 2, or 3 when provided. :param abi: A string or None. This is passed to compatibility_tags.py's get_supported() function as is. :param implementation: A string or None. This is passed to compatibility_tags.py's get_supported() function as is. N.) r sys version_inforjoinmapstrr r rrrr)selfrrr r rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/target_python.py__init__!szTargetPython.__init__cCsZd}|jdk r$ddd|jD}d|jfd|fd|jfd|jfg}d d d|DS) zD Format the given, non-None attributes for display. Nrcss|]}t|VqdS)N)r).0partrrr Rsz,TargetPython.format_given..rrr r  css&|]\}}|dk rd||VqdS)Nz{}={!r})format)rkeyvaluerrrr \s)r rrr r )rdisplay_version key_valuesrrr format_givenJs  zTargetPython.format_givencCsH|jdkrB|j}|dkrd}nt|}t||j|j|jd}||_|jS)z Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). N)versionrr impl)rr rrrr r )rrr(tagsrrrget_tags`s  zTargetPython.get_tags)NNNN)__name__ __module__ __qualname____doc__ __slots__rr'r+rrrrr s $r )r&pip._internal.utils.compatibility_tagsrrpip._internal.utils.miscrpip._internal.utils.typingrtypingrrrpip._vendor.packaging.tagsr objectr rrrrs   models/__pycache__/search_scope.cpython-37.pyc000064400000006574152352421750015346 0ustar00B Re@sddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZmZddlmZer|ddlmZeeZGd d d eZdS) N)canonicalize_name)parse)PyPI)has_tls)normalize_pathredact_auth_from_url)MYPY_CHECK_RUNNING)Listc@s<eZdZdZddgZeddZddZdd Zd d Z d S) SearchScopezF Encapsulates the locations that pip is configured to search. find_links index_urlscCsg}x8|D]0}|dr0t|}tj|r0|}||q Wtszx4t||D]$}t |}|j dkrRt dPqRW|||dS)zQ Create a SearchScope object after normalizing the `find_links`. ~httpszipip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.)r r ) startswithrospathexistsappendr itertoolschain urllib_parseurlparseschemeloggerwarning)clsr r built_find_linkslinknew_linkparsedr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/search_scope.pycreates"     zSearchScope.createcCs||_||_dS)N)r r )selfr r r r r!__init__FszSearchScope.__init__cCsg}g}|jrv|jtjgkrvxB|jD]8}t|}t|}|jsR|jsRt d|| |q$W| d d ||j r| d d dd|j Dd |S)Nz:The index url "%s" seems invalid, please provide a scheme.zLooking in indexes: {}z, zLooking in links: {}css|]}t|VqdS)N)r).0urlr r r! msz6SearchScope.get_formatted_locations.. )r r simple_urlrrurlsplitrnetlocrrrformatjoinr )r#linesredacted_index_urlsr&redacted_index_urlpurlr r r!get_formatted_locationsOs$   z#SearchScope.get_formatted_locationscs fddfdd|jDS)zReturns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations cs,t|tt}|ds(|d}|S)N/) posixpathr-rquoterendswith)r&loc) project_namer r!mkurl_pypi_urlys  z.mkurl_pypi_urlcsg|] }|qSr r )r%r&)r9r r! sz8SearchScope.get_index_urls_locations..)r )r#r8r )r9r8r!get_index_urls_locationsqs z$SearchScope.get_index_urls_locationsN) __name__ __module__ __qualname____doc__ __slots__ classmethodr"r$r2r;r r r r!r s  ) "r )rloggingrr4Zpip._vendor.packaging.utilsrZpip._vendor.six.moves.urllibrrpip._internal.models.indexrpip._internal.utils.compatrpip._internal.utils.miscrrpip._internal.utils.typingrtypingr getLoggerr<robjectr r r r r!s       models/__pycache__/link.cpython-37.pyc000064400000015743152352421750013643 0ustar00B Re.@sddlZddlZddlZddlmZddlmZddlm Z m Z m Z ddl m Z ddlmZddlmZmZerddlmZmZmZmZdd lmZdd lmZGd d d e ZdS) N)parse)WHEEL_EXTENSION)redact_auth_from_urlsplit_auth_from_netlocsplitext)KeyBasedCompareMixin)MYPY_CHECK_RUNNING) path_to_url url_to_path)OptionalTextTupleUnion)HTMLPage)HashescsPeZdZdZddddddgZd=fd d Zd d ZddZeddZ eddZ eddZ eddZ eddZ eddZddZeddZed d!Zed"Zed#d$Zed%Zed&d'Zed(Zed)d*Zed+d,Zed-d.Zed/d0Zd1d2Zed3d4Zed5d6Zed7d8Z ed9d:Z!d;d<Z"Z#S)>Linkz?Represents a parsed link from a Package Index's simple URL _parsed_url_url comes_fromrequires_python yanked_reasoncache_link_parsingNTcs\|drt|}t||_||_||_|r2|nd|_||_t t |j |t d||_ dS)a :param url: url of the resource pointed to (href of the link) :param comes_from: instance of HTMLPage where the link was found, or string. :param requires_python: String containing the `Requires-Python` metadata field, specified in PEP 345. This may be specified by a data-requires-python attribute in the HTML link tag, as described in PEP 503. :param yanked_reason: the reason the file has been yanked, if the file has been yanked, or None if the file hasn't been yanked. This is the value of the "data-yanked" attribute, if present, in a simple repository HTML link. If the file has been yanked but no reason was provided, this should be the empty string. See PEP 592 for more information and the specification. :param cache_link_parsing: A flag that is used elsewhere to determine whether resources retrieved from this link should be cached. PyPI index urls should generally have this set to False, for example. z\\N)keydefining_class) startswithr urllib_parseurlsplitrrrrrsuperr__init__r)selfurlrrrr) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/link.pyr$s  z Link.__init__cCsF|jrd|j}nd}|jr4dt|j|j|Stt|jSdS)Nz (requires-python:{})z{} (from {}){})rformatrrrstr)rrpr"r"r#__str__Ssz Link.__str__cCs d|S)Nz )r%)rr"r"r#__repr___sz Link.__repr__cCs|jS)N)r)rr"r"r#r cszLink.urlcCsP|jd}t|}|s,t|j\}}|St|}|sLtdj ft |S)N/z&URL {self._url!r} produced no filename) pathrstrip posixpathbasenamernetlocrunquoteAssertionErrorr%locals)rr+namer/ user_passr"r"r#filenamehs   z Link.filenamecCs t|jS)N)r r )rr"r"r# file_pathxszLink.file_pathcCs|jjS)N)rscheme)rr"r"r#r7}sz Link.schemecCs|jjS)z4 This can contain auth information. )rr/)rr"r"r#r/sz Link.netloccCst|jjS)N)rr0rr+)rr"r"r#r+sz Link.pathcCstt|jdS)Nr*)rr-r.r+r,)rr"r"r#rsz Link.splitextcCs |dS)N)r)rr"r"r#extszLink.extcCs$|j\}}}}}t||||dfS)N)rr urlunsplit)rr7r/r+queryfragmentr"r"r#url_without_fragmentszLink.url_without_fragmentz[#&]egg=([^&]*)cCs |j|j}|sdS|dS)Nr8)_egg_fragment_researchrgroup)rmatchr"r"r# egg_fragmentszLink.egg_fragmentz[#&]subdirectory=([^&]*)cCs |j|j}|sdS|dS)Nr8)_subdirectory_fragment_rer?rr@)rrAr"r"r#subdirectory_fragmentszLink.subdirectory_fragmentz2(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)cCs |j|j}|r|dSdS)N)_hash_rer?rr@)rrAr"r"r#hashs z Link.hashcCs |j|j}|r|dSdS)Nr8)rFr?rr@)rrAr"r"r# hash_names zLink.hash_namecCs$t|jddddddS)N#r8r?)r-r.rsplit)rr"r"r#show_urlsz Link.show_urlcCs |jdkS)Nfile)r7)rr"r"r#is_filesz Link.is_filecCs|jotj|jS)N)rNosr+isdirr6)rr"r"r#is_existing_dirszLink.is_existing_dircCs |jtkS)N)r9r)rr"r"r#is_wheelsz Link.is_wheelcCsddlm}|j|jkS)Nr)vcs)pip._internal.vcsrSr7 all_schemes)rrSr"r"r#is_vcss z Link.is_vcscCs |jdk S)N)r)rr"r"r# is_yankedszLink.is_yankedcCs |jdk S)N)rH)rr"r"r#has_hashsz Link.has_hashcCs@|dks|jsdS|jdk s t|jdk s.t|j|j|jdS)zG Return True if the link has a hash and it is allowed. NF) hex_digest)rXrHr1rGis_hash_allowed)rhashesr"r"r#rZs zLink.is_hash_allowed)NNNT)$__name__ __module__ __qualname____doc__ __slots__rr(r)propertyr r5r6r7r/r+rr9r=recompiler>rBrCrDrFrGrHrLrNrQrRrVrWrXrZ __classcell__r"r")r!r#rsL)                     r)rOr-rbZpip._vendor.six.moves.urllibrrpip._internal.utils.filetypesrpip._internal.utils.miscrrrpip._internal.utils.modelsrpip._internal.utils.typingrpip._internal.utils.urlsr r typingr r r rpip._internal.index.collectorrpip._internal.utils.hashesrrr"r"r"r#s      models/__pycache__/selection_prefs.cpython-37.pyc000064400000003257152352421750016067 0ustar00B Re@s<ddlmZer(ddlmZddlmZGdddeZdS))MYPY_CHECK_RUNNING)Optional) FormatControlc@s(eZdZdZdddddgZd d d ZdS) SelectionPreferenceszd Encapsulates the candidate selection preferences for downloading and installing files. allow_yankedallow_all_prereleasesformat_control prefer_binaryignore_requires_pythonFNcCs.|dkr d}||_||_||_||_||_dS)awCreate a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links. :param prefer_binary: Whether to prefer an old, but valid, binary dist over a new source dist. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. NF)rrrr r )selfrrrr r r /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/selection_prefs.py__init__szSelectionPreferences.__init__)FNFN)__name__ __module__ __qualname____doc__ __slots__rr r r r rs rN)pip._internal.utils.typingrtypingr#pip._internal.models.format_controlrobjectrr r r r s   models/__pycache__/format_control.cpython-37.pyc000064400000005306152352421750015730 0ustar00B Re @sPddlmZddlmZddlmZer#sz'FormatControl.__eq__..) isinstance __class__NotImplemented __slots__all)r rr )rr r__eq__s   zFormatControl.__eq__cCs || S)N)r)r rr r r__ne__'szFormatControl.__ne__cCsd|jj|j|jS)Nz {}({}, {}))formatr__name__r r )r r r r__repr__+szFormatControl.__repr__cCs|drtd|d}xFd|krb|||d|d|dd=d|krdSqWx:|D]2}|dkr|qjt|}||||qjWdS)N-z7--no-binary / --only-binary option requires 1 argument.,z:all:z:none:) startswithrsplitclearaddindexrdiscard)valuetargetrnewnamer r rhandle_mutual_excludes3s$      z$FormatControl.handle_mutual_excludescCsfddh}||jkr|dn@||jkr4|dn*d|jkrJ|dnd|jkr^|dt|S)Nbinarysourcez:all:)r r'r frozenset)r canonical_nameresultr r rget_allowed_formatsKs        z!FormatControl.get_allowed_formatscCs|d|j|jdS)Nz:all:)r,r r )r r r rdisallow_binariesXszFormatControl.disallow_binaries)NN) r __module__ __qualname____doc__rrrrr staticmethodr,r2r3r r r rr s    rN) Zpip._vendor.packaging.utilsrpip._internal.exceptionsrpip._internal.utils.typingrtypingrrrobjectrr r r rs   models/__pycache__/__init__.cpython-37.pyc000064400000000447152352421750014440 0ustar00B Re?@sdZdS)z8A package that contains models that represent entities. N)__doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/__init__.pymodels/__pycache__/direct_url.cpython-37.pyc000064400000014604152352421750015035 0ustar00B Re@sdZddlZddlZddlmZddlmZddlm Z e rhddl m Z m Z m Z mZmZmZmZedZdZed Zd d d d dgZGdd d eZdddZdddZddZddZGdddeZGdd d eZGdd d eZ e reee efZ!Gdd d eZ"dS)z PEP 610 N)six)parse)MYPY_CHECK_RUNNING)AnyDictIterableOptionalTypeTypeVarUnionTzdirect_url.jsonz.^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$ DirectUrlDirectUrlValidationErrorDirInfo ArchiveInfoVcsInfoc@s eZdZdS)rN)__name__ __module__ __qualname__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/models/direct_url.pyrscCsH||kr |S||}tjr(|tkr(tj}t||sDtd||||S)z3Get value from dictionary and verify expected type.z-{!r} has unexpected type for {} (expected {}))rPY2str string_types isinstancerformat)d expected_typekeydefaultvaluerrr_get"s  r!cCs(t||||}|dkr$td||S)Nz{} must have a value)r!rr)rrrrr rrr _get_required3sr"cCsFdd|D}|stdt|dkr.td|ddk s>t|dS)NcSsg|]}|dk r|qS)Nr).0inforrr =sz#_exactly_one_of..z/missing one of archive_info, dir_info, vcs_infoz1more than one of archive_info, dir_info, vcs_infor)rlenAssertionError)infosrrr_exactly_one_of;s r*cKsdd|DS)z Make dict excluding None values.cSsi|]\}}|dk r||qS)Nr)r#kvrrr Msz _filter_none..)items)kwargsrrr _filter_noneJsr0c@s.eZdZdZd ddZeddZddZdS) rvcs_infoNcCs"||_||_||_||_||_dS)N)vcsrequested_revision commit_idresolved_revisionresolved_revision_type)selfr2r4r3r5r6rrr__init__Ss zVcsInfo.__init__c CsF|dkr dS|t|tdt|tdt|tdt|tdt|tddS)Nr2r4r3r5r6)r2r4r3r5r6)r"rr!)clsrrrr _from_dictas    zVcsInfo._from_dictcCst|j|j|j|j|jdS)N)r2r3r4r5r6)r0r2r3r4r5r6)r7rrr_to_dictns zVcsInfo._to_dict)NNN)rrrnamer8 classmethodr:r;rrrrrPs   c@s.eZdZdZd ddZeddZddZdS) r archive_infoNcCs ||_dS)N)hash)r7r?rrrr8|szArchiveInfo.__init__cCs|dkr dS|t|tddS)Nr?)r?)r!r)r9rrrrr:szArchiveInfo._from_dictcCs t|jdS)N)r?)r0r?)r7rrrr;szArchiveInfo._to_dict)N)rrrr<r8r=r:r;rrrrrys  c@s.eZdZdZd ddZeddZddZd S) rdir_infoFcCs ||_dS)N)editable)r7rArrrr8szDirInfo.__init__cCs"|dkr dS|t|tddddS)NrAF)r)rA)r"bool)r9rrrrr:szDirInfo._from_dictcCst|jp ddS)N)rA)r0rA)r7rrrr;szDirInfo._to_dictN)F)rrrr<r8r=r:r;rrrrrs  c@sZeZdZdddZddZeddZdd Zed d Z d d Z eddZ ddZ dS)r NcCs||_||_||_dS)N)urlr$ subdirectory)r7rCr$rDrrrr8szDirectUrl.__init__cCsRd|kr |S|dd\}}t|jtr@|jjdkr@|dkr@|St|rN|S|S)N@r&git)splitrr$rr2 ENV_VAR_REmatch)r7netloc user_passnetloc_no_user_passrrr_remove_auth_from_netlocs   z"DirectUrl._remove_auth_from_netloccCs8t|j}||j}t|j||j|j|j f}|S)zurl with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is ``git`` in the case of a git URL. ) urllib_parseurlsplitrCrMrJ urlunsplitschemepathqueryfragment)r7purlrJsurlrrr redacted_urls   zDirectUrl.redacted_urlcCs||dS)N) from_dictto_dict)r7rrrvalidateszDirectUrl.validatec CsRtt|tdt|tdttt|tdtt|tdt t|tdgdS)NrCrDr>r@r1)rCrDr$) r r"rr!r*rr:dictrr)r9rrrrrXs  zDirectUrl.from_dictcCs&t|j|jd}|j||jj<|S)N)rCrD)r0rWrDr$r;r<)r7resrrrrYs  zDirectUrl.to_dictcCs|t|S)N)rXjsonloads)r9srrr from_jsonszDirectUrl.from_jsoncCstj|ddS)NT) sort_keys)r]dumpsrY)r7rrrto_jsonszDirectUrl.to_json)N) rrrr8rMpropertyrWrZr=rXrYr`rcrrrrr s    )N)N)#__doc__r]re pip._vendorrZpip._vendor.six.moves.urllibrrNpip._internal.utils.typingrtypingrrrrr r r r DIRECT_URL_METADATA_NAMEcompilerH__all__ Exceptionrr!r"r*r0objectrrrZInfoTyper rrrrs4   $   )models/scheme.py000064400000001412152352421750007651 0ustar00""" For types associated with installation schemes. For a general overview of available schemes and their context, see https://docs.python.org/3/install/index.html#alternate-installation. """ SCHEME_KEYS = ['platlib', 'purelib', 'headers', 'scripts', 'data'] class Scheme(object): """A Scheme holds paths which are used as the base directories for artifacts associated with a Python package. """ __slots__ = SCHEME_KEYS def __init__( self, platlib, # type: str purelib, # type: str headers, # type: str scripts, # type: str data, # type: str ): self.platlib = platlib self.purelib = purelib self.headers = headers self.scripts = scripts self.data = data models/wheel.py000064400000005324152352421750007517 0ustar00"""Represents a wheel file and provides access to the various parts of the name that have meaning. """ import re from pip._vendor.packaging.tags import Tag from pip._internal.exceptions import InvalidWheelFilename from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List class Wheel(object): """A wheel file""" wheel_file_re = re.compile( r"""^(?P(?P.+?)-(?P.*?)) ((-(?P\d[^-]*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): # type: (str) -> None """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ wheel_info = self.wheel_file_re.match(filename) if not wheel_info: raise InvalidWheelFilename( "{} is not a valid wheel filename.".format(filename) ) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.build_tag = wheel_info.group('build') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = { Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats } def get_formatted_file_tags(self): # type: () -> List[str] """Return the wheel's tags as a sorted list of strings.""" return sorted(str(tag) for tag in self.file_tags) def support_index_min(self, tags): # type: (List[Tag]) -> int """Return the lowest index that one of the wheel's file_tag combinations achieves in the given list of supported tags. For example, if there are 8 supported tags and one of the file tags is first in the list, then return 0. :param tags: the PEP 425 tags to check the wheel against, in order with most preferred first. :raises ValueError: If none of the wheel's file tags match one of the supported tags. """ return min(tags.index(tag) for tag in self.file_tags if tag in tags) def supported(self, tags): # type: (List[Tag]) -> bool """Return whether the wheel is compatible with one of the given tags. :param tags: the PEP 425 tags to check the wheel against. """ return not self.file_tags.isdisjoint(tags) models/direct_url.py000064400000015364152352421750010554 0ustar00""" PEP 610 """ import json import re from pip._vendor import six from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ( Any, Dict, Iterable, Optional, Type, TypeVar, Union ) T = TypeVar("T") DIRECT_URL_METADATA_NAME = "direct_url.json" ENV_VAR_RE = re.compile(r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$") __all__ = [ "DirectUrl", "DirectUrlValidationError", "DirInfo", "ArchiveInfo", "VcsInfo", ] class DirectUrlValidationError(Exception): pass def _get(d, expected_type, key, default=None): # type: (Dict[str, Any], Type[T], str, Optional[T]) -> Optional[T] """Get value from dictionary and verify expected type.""" if key not in d: return default value = d[key] if six.PY2 and expected_type is str: expected_type = six.string_types # type: ignore if not isinstance(value, expected_type): raise DirectUrlValidationError( "{!r} has unexpected type for {} (expected {})".format( value, key, expected_type ) ) return value def _get_required(d, expected_type, key, default=None): # type: (Dict[str, Any], Type[T], str, Optional[T]) -> T value = _get(d, expected_type, key, default) if value is None: raise DirectUrlValidationError("{} must have a value".format(key)) return value def _exactly_one_of(infos): # type: (Iterable[Optional[InfoType]]) -> InfoType infos = [info for info in infos if info is not None] if not infos: raise DirectUrlValidationError( "missing one of archive_info, dir_info, vcs_info" ) if len(infos) > 1: raise DirectUrlValidationError( "more than one of archive_info, dir_info, vcs_info" ) assert infos[0] is not None return infos[0] def _filter_none(**kwargs): # type: (Any) -> Dict[str, Any] """Make dict excluding None values.""" return {k: v for k, v in kwargs.items() if v is not None} class VcsInfo(object): name = "vcs_info" def __init__( self, vcs, # type: str commit_id, # type: str requested_revision=None, # type: Optional[str] resolved_revision=None, # type: Optional[str] resolved_revision_type=None, # type: Optional[str] ): self.vcs = vcs self.requested_revision = requested_revision self.commit_id = commit_id self.resolved_revision = resolved_revision self.resolved_revision_type = resolved_revision_type @classmethod def _from_dict(cls, d): # type: (Optional[Dict[str, Any]]) -> Optional[VcsInfo] if d is None: return None return cls( vcs=_get_required(d, str, "vcs"), commit_id=_get_required(d, str, "commit_id"), requested_revision=_get(d, str, "requested_revision"), resolved_revision=_get(d, str, "resolved_revision"), resolved_revision_type=_get(d, str, "resolved_revision_type"), ) def _to_dict(self): # type: () -> Dict[str, Any] return _filter_none( vcs=self.vcs, requested_revision=self.requested_revision, commit_id=self.commit_id, resolved_revision=self.resolved_revision, resolved_revision_type=self.resolved_revision_type, ) class ArchiveInfo(object): name = "archive_info" def __init__( self, hash=None, # type: Optional[str] ): self.hash = hash @classmethod def _from_dict(cls, d): # type: (Optional[Dict[str, Any]]) -> Optional[ArchiveInfo] if d is None: return None return cls(hash=_get(d, str, "hash")) def _to_dict(self): # type: () -> Dict[str, Any] return _filter_none(hash=self.hash) class DirInfo(object): name = "dir_info" def __init__( self, editable=False, # type: bool ): self.editable = editable @classmethod def _from_dict(cls, d): # type: (Optional[Dict[str, Any]]) -> Optional[DirInfo] if d is None: return None return cls( editable=_get_required(d, bool, "editable", default=False) ) def _to_dict(self): # type: () -> Dict[str, Any] return _filter_none(editable=self.editable or None) if MYPY_CHECK_RUNNING: InfoType = Union[ArchiveInfo, DirInfo, VcsInfo] class DirectUrl(object): def __init__( self, url, # type: str info, # type: InfoType subdirectory=None, # type: Optional[str] ): self.url = url self.info = info self.subdirectory = subdirectory def _remove_auth_from_netloc(self, netloc): # type: (str) -> str if "@" not in netloc: return netloc user_pass, netloc_no_user_pass = netloc.split("@", 1) if ( isinstance(self.info, VcsInfo) and self.info.vcs == "git" and user_pass == "git" ): return netloc if ENV_VAR_RE.match(user_pass): return netloc return netloc_no_user_pass @property def redacted_url(self): # type: () -> str """url with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is ``git`` in the case of a git URL. """ purl = urllib_parse.urlsplit(self.url) netloc = self._remove_auth_from_netloc(purl.netloc) surl = urllib_parse.urlunsplit( (purl.scheme, netloc, purl.path, purl.query, purl.fragment) ) return surl def validate(self): # type: () -> None self.from_dict(self.to_dict()) @classmethod def from_dict(cls, d): # type: (Dict[str, Any]) -> DirectUrl return DirectUrl( url=_get_required(d, str, "url"), subdirectory=_get(d, str, "subdirectory"), info=_exactly_one_of( [ ArchiveInfo._from_dict(_get(d, dict, "archive_info")), DirInfo._from_dict(_get(d, dict, "dir_info")), VcsInfo._from_dict(_get(d, dict, "vcs_info")), ] ), ) def to_dict(self): # type: () -> Dict[str, Any] res = _filter_none( url=self.redacted_url, subdirectory=self.subdirectory, ) res[self.info.name] = self.info._to_dict() return res @classmethod def from_json(cls, s): # type: (str) -> DirectUrl return cls.from_dict(json.loads(s)) def to_json(self): # type: () -> str return json.dumps(self.to_dict(), sort_keys=True) resolution/__pycache__/base.cpython-37.pyc000064400000002031152352421750014522 0ustar00B Re@s\ddlmZerHddlmZmZddlmZddlmZee egefZ Gddde Z dS))MYPY_CHECK_RUNNING)CallableList)InstallRequirement)RequirementSetc@seZdZddZddZdS) BaseResolvercCs tdS)N)NotImplementedError)self root_reqscheck_supported_wheelsr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/base.pyresolveszBaseResolver.resolvecCs tdS)N)r)r req_setr r r get_installation_ordersz#BaseResolver.get_installation_orderN)__name__ __module__ __qualname__rrr r r r r srN) pip._internal.utils.typingrtypingrrZpip._internal.req.req_installrZpip._internal.req.req_setrstrZInstallRequirementProviderobjectrr r r r s   resolution/__pycache__/__init__.cpython-37.pyc000064400000000347152352421750015357 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/__init__.pyresolution/resolvelib/__pycache__/factory.cpython-37.pyc000064400000025300152352421750017431 0ustar00B ReA@sddlZddlmZddlmZmZmZmZddlm Z ddl m Z ddl m Z ddlmZddlmZmZmZdd lmZdd lmZd d lmZd d lmZmZmZmZmZd dl m!Z!d dl"m#Z#m$Z$m%Z%erddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:m;Z;ddlm?Z?ddl@mAZAddlBmCZCd dlmDZDmEZEd dlmFZFe0dZGe(e?eGfZHe(e4eDfZIeJeKZLGdddeMZNdS)N)canonicalize_name)DistributionNotFoundInstallationErrorUnsupportedPythonVersionUnsupportedWheel)Wheel)InstallRequirement) get_supported)Hashes)dist_in_site_packagesdist_in_usersiteget_installed_distributions)MYPY_CHECK_RUNNING)running_under_virtualenv) Constraint)AlreadyInstalledCandidateEditableCandidateExtrasCandidate LinkCandidateRequiresPythonCandidate)FoundCandidates)ExplicitRequirementRequiresPythonRequirementSpecifierRequirement) FrozenSetDictIterableIteratorListOptionalSequenceSetTupleTypeVar) SpecifierSet) _BaseVersion) Distribution)ResolutionImpossible) CacheEntry WheelCache) PackageFinder)Link)RequirementPreparer)InstallRequirementProvider) Candidate Requirement) BaseCandidateCc@seZdZd ddZeddZddZd d Zd d Zd dZ ddZ ddZ d!ddZ ddZ ddZddZddZddZdS)"FactoryNFc Csl||_||_||_t| |_||_||_||_||_| |_ i|_ i|_ |sbddt ddD|_ ni|_ dS)NcSsi|]}|t|jqS)r project_name).0distr4r4/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/factory.py gsz$Factory.__init__..F) local_only)_finderpreparer _wheel_cacher_python_candidate_make_install_req_from_spec_use_user_site_force_reinstall_ignore_requires_pythonZuse_lazy_wheel_link_candidate_cache_editable_candidate_cacher _installed_dists) selffinderr<make_install_req wheel_cache use_user_siteforce_reinstallignore_installedignore_requires_pythonpy_version_info lazy_wheelr4r4r8__init__Ks zFactory.__init__cCs|jS)N)rA)rFr4r4r8rKnszFactory.force_reinstallcCs t|||d}|rt||S|S)N)factory)rr)rFr7extrastemplatebaser4r4r8_make_candidate_from_distss z!Factory._make_candidate_from_distcCsr|jr4||jkr(t|||||d|j|<|j|}n,||jkrVt|||||d|j|<|j|}|rnt||S|S)N)rQnameversion)editablerDrrCrr)rFlinkrRrSrVrWrTr4r4r8_make_candidate_from_links      z!Factory._make_candidate_from_linkc s|sdS|dtjjtx6|D].}|jjM|jddMt|jOq(Wd}jsjkrj}j |j ddrj |d}fdd }t |||S) Nr4rF)trust_internetT) prereleases)r7rRrSc3sJjjd}x2tt|D]}j|j|jdVq$WdS)N)r5 specifierhashes)rYrRrSrVrW)r;find_best_candidatereversedlistiter_applicablerZrYrW)resultZican)rRr^rVrFr]rSr4r8iter_index_candidatessz=Factory._iter_found_candidates..iter_index_candidates) rreqrV frozensetr]r^rRrArEcontainsrWrUr) rFireqsr]r^prefers_installedireqZinstalled_candidateZinstalled_distrdr4)rRr^rVrFr]rSr8_iter_found_candidatess,    zFactory._iter_found_candidatesc st}g}x<D]4}|\}}|dk r2|||dk r||qW|s`|||j|j|S|r||j} t d | fdd|DS)NzhCould not satisfy constraints for {!r}: installation from path or url cannot be constrained to a versionc3s(|] tfddDrVqdS)c3s|]}|VqdS)N)Zis_satisfied_by)r6re)cr4r8 sz4Factory.find_candidates...N)all)r6) requirements)rlr8rmsz*Factory.find_candidates..) setZget_candidate_lookupaddappendrkr]r^poprVrformat) rFro constraintriZexplicit_candidatesrhrecandrjrVr4)ror8find_candidatess(    zFactory.find_candidatescCs||s td|j|jdS|js.t|S|jjrht|jj }| |j j shd|j }t||j|jt|j||jrt|jnddd}||S)Nz6Ignoring %s: markers '%s' don't match your environmentz-{} is not a supported wheel on this platform.)rRrSrVrW) match_markersloggerinforVmarkersrYris_wheelrfilename supportedr; target_pythonget_tagsrtrrZrfrRrmake_requirement_from_candidate)rFrjrequested_extraswheelmsgrvr4r4r8!make_requirement_from_install_reqs(   z)Factory.make_requirement_from_install_reqcCst|S)N)r)rF candidater4r4r8rsz'Factory.make_requirement_from_candidater4cCs|||}|||S)N)r?r)rFr] comes_fromrrjr4r4r8make_requirement_from_specs z"Factory.make_requirement_from_speccCs|js|dkrdSt||jS)N)rBrr>)rFr]r4r4r8 make_requires_python_requirement$sz(Factory.make_requires_python_requirementcCs*|jdks|jjrdS|jj||tdS)aLook up the link in the wheel cache. If ``preparer.require_hashes`` is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have nondeterministic contents due to file modification times. N)rY package_namesupported_tags)r=r<require_hashesget_cache_entryr )rFrYrVr4r4r8get_wheel_cache_entry*s zFactory.get_wheel_cache_entrycCsV|j|j}|dkrdS|js$|St|r0|StrRt|rRtd|j |j dS)NzVWill not install to the user site because it will lack sys.path precedence to {} in {}) rEgetrVr@r rr rrtr5location)rFrr7r4r4r8get_dist_to_uninstall<szFactory.get_dist_to_uninstallcCs(d}|j|j|jjt|jd}t|S)NzOPackage {package!r} requires a different Python: {version} not in {specifier!r})packagerWr])rtrVr>rWstrr]r)rF requirementrSZmessage_formatmessager4r4r8_report_requires_python_errorZs z%Factory._report_requires_python_errorc Cs|jstdx*|jD] }t|jtr||j|jSqWt|jdkr|jd\}}|dkrht|}nd ||j }t d|t d |Sdd}d d }d d }g} x6|jD],\}}|dkr|} n||} | | qW| r|| } nd } d | } t | d} xL|jD]B\}}| d} |rB| d |j |j} n| d} | |} qW| ddddd} t | t dS)Nz)Installation error reported with no causerrz {} (from {})z:Could not find a version that satisfies the requirement %sz%No matching distribution found for {}cSs2t|dkr|dSd|ddd|dS)Nrrz, z and )lenjoin)partsr4r4r8 text_joins z1Factory.get_installation_error..text_joincSsd|j|jS)Nz{} {})rtrVrW)rvr4r4r8 readable_formsz5Factory.get_installation_error..readable_formcSsD|}|r|js"d|j|jSt|jtr:t|jjSt|jS)Nz{} {})Zget_install_requirementrrtrVrW isinstancerr)parentrjr4r4r8describe_triggers    z8Factory.get_installation_error..describe_triggerzthe requested packageszOCannot install {} because these package versions have conflicting dependencies.z The conflict is caused by:z z{} {} depends on zThe user requested z zTo fix this you could try to: z91. loosen the range of package versions you've specified z92. remove package versions to allow pip attempt to solve zthe dependency conflict znResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies)ZcausesAssertionErrorrrrrrrrrtrVrycriticalrZformat_for_errorrrrWrz) rFecausererZreq_disprrrZtriggersZtriggerrzrr4r4r8get_installation_errorksZ           zFactory.get_installation_error)NF)r4)__name__ __module__ __qualname__rPpropertyrKrUrZrkrwrrrrrrrrr4r4r4r8r3Js    <& r3)OloggingZpip._vendor.packaging.utilsrpip._internal.exceptionsrrrrpip._internal.models.wheelrZpip._internal.req.req_installr&pip._internal.utils.compatibility_tagsr pip._internal.utils.hashesr pip._internal.utils.miscr r r pip._internal.utils.typingrpip._internal.utils.virtualenvrrTr candidatesrrrrrZfound_candidatesrrorrrtypingrrrrrr r!r"r#r$Z pip._vendor.packaging.specifiersr%pip._vendor.packaging.versionr&Zpip._vendor.pkg_resourcesr'Zpip._vendor.resolvelibr(pip._internal.cacher)r*"pip._internal.index.package_finderr+pip._internal.models.linkr, pip._internal.operations.preparer-pip._internal.resolution.baser.r/r0r1r2CacheZVersionCandidates getLoggerrryobjectr3r4r4r4r8s>         0            resolution/resolvelib/__pycache__/resolver.cpython-37.pyc000064400000015724152352421750017634 0ustar00B Req'@sTddlZddlZddlmZddlmZddlmZmZddlm Z ddl m Z ddl mZddlmZdd lmZdd lmZdd lmZdd lmZd dlmZd dlmZer&ddlmZmZm Z m!Z!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddl m-Z-ddlm.Z.e/e0Z1GdddeZ ddZ2ddZ3dS)N)six)canonicalize_name) BaseReporterResolutionImpossible)Resolver)InstallationError)check_invalid_constraint_type)RequirementSet) BaseResolver) PipProvider)dist_is_editable)MYPY_CHECK_RUNNING) Constraint)Factory)DictListOptionalSetTuple)Result)Graph) WheelCache) PackageFinder)RequirementPreparer)InstallRequirement)InstallRequirementProvidercs8eZdZdddhZd fdd Zdd Zd d ZZS) reagerzonly-if-neededzto-satisfy-onlyNFc s^tt|| rtd| |jks*tt|||||| ||| | d |_||_ | |_ d|_ dS)Nzpip is using lazily downloaded wheels using HTTP range requests to obtain dependency information. This experimental feature is enabled through --use-feature=fast-deps and it is not ready for production.) finderpreparermake_install_req wheel_cache use_user_siteforce_reinstallignore_installedignore_requires_pythonpy_version_info lazy_wheel) superr__init__loggerwarning_allowed_strategiesAssertionErrorrfactoryignore_dependenciesupgrade_strategy_result) selfrrr!r r"r/r$r%r#r0r&r') __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/resolver.pyr)'s& zResolver.__init__c Csi}t}g}x|D]}|jrpt|}|r2t||s)nameversionlinkreason)+set constraintrr match_markersrr9rZ from_ireq user_suppliedaddr.Z!make_requirement_from_install_reqappendr r/r0r RLResolverresolver1rZget_installation_errorr raise_fromr mappingvaluesZget_install_requirementZget_dist_to_uninstallshould_reinstallr#parsed_versionr:r is_editableZ source_link is_yankedformat yanked_reasonr*r+add_named_requirement)r2 root_reqsr8r6r7 requirementsreqproblemr9rZproviderZreporterresolverZ try_to_avoid_resolution_too_deepeerrorreq_set candidateireqZinstalled_distr;msgr4r4r5rDQsx            zResolver.resolvecCsN|jdk std|jj}t|}t|jtjt |ddd}dd|DS)aGet order for installation of requirements in RequirementSet. The returned list contains a requirement before another that depends on it. This helps ensure that the environment is kept consistent as they get installed one-by-one. The current implementation creates a topological ordering of the dependency graph, while breaking any cycles in the graph at arbitrary points. We make no guarantees about where the cycle would be broken, other than they would be broken. Nzmust call resolve() first)weightsT)keyreversecSsg|] \}}|qSr4r4).0_rYr4r4r5 sz3Resolver.get_installation_order..) r1r-graphget_topological_weightssortedrPitems functoolspartial_req_set_item_sorter)r2rWrar[Z sorted_itemsr4r4r5get_installation_orders  zResolver.get_installation_order)NF)__name__ __module__ __qualname__r,r)rDrh __classcell__r4r4)r3r5r$s  ^rcsLtifdddddks4tttksHtS)aAssign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior notice. We take the length for the longest path to any node from root, ignoring any paths that contain a single node twice (i.e. cycles). This is done through a depth-first search through the graph, while keeping track of the path to the node. Cycles in the graph result would result in node being revisited while also being it's own path. In this case, take no action. This helps ensure we don't get stuck in a cycle. When assigning weight, the longer path (i.e. larger length) is preferred. cs^|kr dS|x|D] }|q"W||d}t|t|<dS)Nr)rAZ iter_childrenremovegetmaxlen)nodechildZlast_known_parent_count)rapathvisitr[r4r5rts    z&get_topological_weights..visitNr)r=r-rp)rar4)rarsrtr[r5rbsrbcCst|d}|||fS)a)Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests. r)r)itemr[r9r4r4r5rgs rg)4relogging pip._vendorrZpip._vendor.packaging.utilsrZpip._vendor.resolvelibrrrrCpip._internal.exceptionsrZpip._internal.req.req_installrZpip._internal.req.req_setr pip._internal.resolution.baser Z,pip._internal.resolution.resolvelib.providerr pip._internal.utils.miscr pip._internal.utils.typingr baserr.rtypingrrrrrZ pip._vendor.resolvelib.resolversrZpip._vendor.resolvelib.structsrpip._internal.cacher"pip._internal.index.package_finderr pip._internal.operations.preparerrr getLoggerrir*rbrgr4r4r4r5s8                    &.resolution/resolvelib/__pycache__/requirements.cpython-37.pyc000064400000011640152352421750020507 0ustar00B Re@sddlmZddlmZddlmZmZerTddlmZddl m Z ddlm Z m Z Gdd d eZ Gd d d eZGd d d eZdS))canonicalize_name)MYPY_CHECK_RUNNING) Requirement format_name) SpecifierSet)InstallRequirement) CandidateCandidateLookupc@s@eZdZddZddZeddZddZd d Zd d Z d S)ExplicitRequirementcCs ||_dS)N) candidate)selfr r/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/requirements.py__init__szExplicitRequirement.__init__cCsdj|jj|jdS)Nz{class_name}({candidate!r})) class_namer )format __class____name__r )r rrr__repr__szExplicitRequirement.__repr__cCs|jjS)N)r name)r rrrrszExplicitRequirement.namecCs |jS)N)r format_for_error)r rrrr!sz$ExplicitRequirement.format_for_errorcCs |jdfS)N)r )r rrrget_candidate_lookup%sz(ExplicitRequirement.get_candidate_lookupcCs ||jkS)N)r )r r rrris_satisfied_by)sz#ExplicitRequirement.is_satisfied_byN) r __module__ __qualname__rrpropertyrrrrrrrrr s  r c@sHeZdZddZddZddZeddZd d Zd d Z d dZ dS)SpecifierRequirementcCs(|jdkstd||_t|j|_dS)NzThis is a link, not a specifier)linkAssertionError_ireq frozensetextras_extras)r ireqrrrr/szSpecifierRequirement.__init__cCs t|jjS)N)strr req)r rrr__str__5szSpecifierRequirement.__str__cCsdj|jjt|jjdS)Nz{class_name}({requirement!r}))r requirement)rrrr%r r&)r rrrr9szSpecifierRequirement.__repr__cCst|jjj}t||jS)N)rr r&rrr#)r canonical_namerrrr@szSpecifierRequirement.namecCsZddt|dD}t|dkr(dSt|dkr<|dSd|ddd |dS) NcSsg|] }|qSr)strip).0srrr Msz9SpecifierRequirement.format_for_error..,rrz, z and )r%splitlenjoin)r partsrrrrFs   z%SpecifierRequirement.format_for_errorcCs d|jfS)N)r )r rrrrUsz)SpecifierRequirement.get_candidate_lookupcCs:|j|jks td|j|j|jjj}|j|jddS)Nz?Internal issue: Candidate is not for this requirement {} vs {}T) prereleases)rrrr r& specifiercontainsversion)r r specrrrrYs  z$SpecifierRequirement.is_satisfied_byN) rrrrr'rrrrrrrrrrr.s rc@sDeZdZdZddZddZeddZdd Zd d Z d d Z dS)RequiresPythonRequirementz9A requirement representing Requires-Python metadata. cCs||_||_dS)N)r6 _candidate)r r6matchrrrrhsz"RequiresPythonRequirement.__init__cCsdj|jjt|jdS)Nz{class_name}({specifier!r}))rr6)rrrr%r6)r rrrrmsz"RequiresPythonRequirement.__repr__cCs|jjS)N)r;r)r rrrrtszRequiresPythonRequirement.namecCsdt|jS)NzPython )r%r6)r rrrrysz*RequiresPythonRequirement.format_for_errorcCs"|jj|jjddr|jdfSdS)NT)r5)NN)r6r7r;r8)r rrrr}s z.RequiresPythonRequirement.get_candidate_lookupcCs(|j|jjkstd|jj|jddS)NzNot Python candidateT)r5)rr;rr6r7r8)r r rrrrsz)RequiresPythonRequirement.is_satisfied_byN) rrr__doc__rrrrrrrrrrrr:es r:N)Zpip._vendor.packaging.utilsrpip._internal.utils.typingrbaserrZ pip._vendor.packaging.specifiersrZpip._internal.req.req_installrr r r rr:rrrrs    7resolution/resolvelib/__pycache__/base.cpython-37.pyc000064400000010726152352421750016702 0ustar00B Re @sddlmZddlmZddlmZddlmZddlm Z e rddl m Z m Z m Z mZddlmZddlmZee d e efZd d ZGd d d eZGdddeZGdd d eZdS)) SpecifierSet)canonicalize_name)InstallRequirement)Hashes)MYPY_CHECK_RUNNING) FrozenSetIterableOptionalTuple) _BaseVersion)Link CandidatecCs,|s|Stdd|D}d|d|S)Ncss|]}t|VqdS)N)r).0er/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/base.py szformat_name..z{}[{}],)sortedformatjoin)projectextrasZcanonical_extrasrrr format_namesrc@sDeZdZddZeddZeddZddZd d Zd d Z d S) ConstraintcCs||_||_dS)N) specifierhashes)selfrrrrr__init__szConstraint.__init__cCstttS)N)rrr)clsrrrempty#szConstraint.emptycCst|j|jddS)NF)trust_internet)rrr)rireqrrr from_ireq(szConstraint.from_ireqcCst|jpt|jS)N)boolrr)rrrr __nonzero__-szConstraint.__nonzero__cCs|S)N)r%)rrrr__bool__1szConstraint.__bool__cCs6t|tstS|j|j@}|j|jdd@}t||S)NF)r!) isinstancerNotImplementedrrr)rotherrrrrr__and__5s   zConstraint.__and__N) __name__ __module__ __qualname__r classmethodr r#r%r&r*rrrrrs   rc@s0eZdZeddZddZddZddZd S) RequirementcCs tddS)NzSubclass should override)NotImplementedError)rrrrname?szRequirement.namecCsdS)NFr)r candidaterrris_satisfied_byDszRequirement.is_satisfied_bycCs tddS)NzSubclass should override)r0)rrrrget_candidate_lookupHsz Requirement.get_candidate_lookupcCs tddS)NzSubclass should override)r0)rrrrformat_for_errorLszRequirement.format_for_errorN)r+r,r-propertyr1r3r4r5rrrrr/>s r/c@s`eZdZeddZeddZeddZeddZed d Zd d Z d dZ ddZ dS)r cCs tddS)NzOverride in subclass)r0)rrrrr1RszCandidate.namecCs tddS)NzOverride in subclass)r0)rrrrversionWszCandidate.versioncCs tddS)NzOverride in subclass)r0)rrrr is_installed\szCandidate.is_installedcCs tddS)NzOverride in subclass)r0)rrrr is_editableaszCandidate.is_editablecCs tddS)NzOverride in subclass)r0)rrrr source_linkfszCandidate.source_linkcCs tddS)NzOverride in subclass)r0)rZ with_requiresrrriter_dependencieskszCandidate.iter_dependenciescCs tddS)NzOverride in subclass)r0)rrrrget_install_requirementosz!Candidate.get_install_requirementcCs tddS)NzSubclass should override)r0)rrrrr5sszCandidate.format_for_errorN) r+r,r-r6r1r7r8r9r:r;r<r5rrrrr Qs     N)Z pip._vendor.packaging.specifiersrZpip._vendor.packaging.utilsrZpip._internal.req.req_installrpip._internal.utils.hashesrpip._internal.utils.typingrtypingrrr r pip._vendor.packaging.versionr pip._internal.models.linkr ZCandidateLookuprobjectrr/r rrrrs        !resolution/resolvelib/__pycache__/candidates.cpython-37.pyc000064400000042557152352421750020076 0ustar00B Re%O@sddlZddlZddlmZddlmZmZddlmZddl m Z ddl m Z m Z ddlmZmZddlmZmZdd lmZdd lmZdd lmZmZdd lmZdd lmZddlm Z m!Z!er:ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ddlm0Z0ddl1m2Z2e(dZ3e4e5Z6ddZ7ddZ8ddZ9Gddde Z:Gd d!d!e:Z;Gd"d#d#e:ZGd(d)d)e Z?dS)*N)suppress)InvalidSpecifier SpecifierSet)canonicalize_name)Version) HashErrorMetadataInconsistent)HTTPRangeRequestUnsupporteddist_from_wheel_url)install_req_from_editableinstall_req_from_line)InstallRequirement) indent_log)dist_is_editablenormalize_version_info)get_requires_python)MYPY_CHECK_RUNNING) Candidate format_name)Any FrozenSetIterableOptionalTupleUnion) _BaseVersion) Distribution)AbstractDistribution)Link) Requirement)Factory)AlreadyInstalledCandidateEditableCandidate LinkCandidatec Csh|jrtd|jr t|j}n|j}t||j|j|j|j |j t |j |j |jdd}|j|_||_|S)Nztemplate is editable)install_optionsglobal_optionshashes) user_supplied comes_from use_pep517isolated constraintoptions)editableAssertionErrorreqstrurlr r(r)r*r+r,dictr%r& hash_options original_linklink)r6templatelineireqr:/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.pymake_install_req_from_link0s$ r<c Cs@|jstdt|j|j|j|j|j|jt |j |j |j ddS)Nztemplate not editable)r%r&r')r(r)r*r+r,r-) r.r/r r2r(r)r*r+r,r3r%r&r4)r6r7r:r:r;make_install_req_from_editableIsr=c Cs|t|j}|jrt|j}n&|jr4d||jj}nd||j}t||j |j |j |j |j t|j|j|jdd}||_|S)Nz{} @ {}z{}=={})r%r&r')r(r)r*r+r,r-)r project_namer0r1r6formatr2parsed_versionr r(r)r*r+r,r3r%r&r4 satisfied_by)distr7r>r8r9r:r:r;make_install_req_from_dist[s&  rCc@seZdZdZdZd&ddZddZdd Zd d Zd d Z e ddZ e ddZ e ddZ ddZddZddZddZddZe ddZd d!Zd"d#Zd$d%ZdS)'"_InstallRequirementBackedCandidateaA candidate backed by an ``InstallRequirement``. This represents a package request with the target not being already in the environment, and needs to be fetched and installed. The backing ``InstallRequirement`` is responsible for most of the leg work; this class exposes appropriate information to the resolver. :param link: The link passed to the ``InstallRequirement``. The backing ``InstallRequirement`` will use this link to fetch the distribution. :param source_link: The link this candidate "originates" from. This is different from ``link`` when the link is found in the wheel cache. ``link`` would point to the wheel cache, while this points to the found remote link (e.g. from pypi.org). FNcCs4||_||_||_||_||_||_d|_d|_dS)NF)_link _source_link_factory_ireq_name_version_dist _prepared)selfr6 source_linkr9factorynameversionr:r:r;__init__s z+_InstallRequirementBackedCandidate.__init__cCsdj|jjt|jdS)Nz{class_name}({link!r})) class_namer6)r? __class____name__r1rE)rMr:r:r;__repr__sz+_InstallRequirementBackedCandidate.__repr__cCst|j|jfS)N)hashrTrE)rMr:r:r;__hash__sz+_InstallRequirementBackedCandidate.__hash__cCst||jr|j|jkSdS)NF) isinstancerTrE)rMotherr:r:r;__eq__s  z)_InstallRequirementBackedCandidate.__eq__cCs || S)N)r[)rMrZr:r:r;__ne__sz)_InstallRequirementBackedCandidate.__ne__cCs|jS)N)rF)rMr:r:r;rNsz._InstallRequirementBackedCandidate.source_linkcCs|jdkrt|jj|_|jS)z:The normalised name of the project the candidate refers toN)rIrrBr>)rMr:r:r;rPs z'_InstallRequirementBackedCandidate.namecCs|jdkr|jj|_|jS)N)rJrBr@)rMr:r:r;rQs  z*_InstallRequirementBackedCandidate.versioncCs$d|j|j|jjr|jjn|jS)Nz{} {} (from {}))r?rPrQrEis_file file_path)rMr:r:r;format_for_errorsz3_InstallRequirementBackedCandidate.format_for_errorcCs tddS)NzOverride in subclass)NotImplementedError)rMr:r:r;_prepare_abstract_distributionszA_InstallRequirementBackedCandidate._prepare_abstract_distributioncCsb|j}t|j}|jdk r4|j|kr4t|jd|j|j}|jdk r^|j|kr^t|jd|jdS)z:Check for consistency of project name and version of dist.NrPrQ) rKrr>rIrrHr@rJrQ)rMrBrPrQr:r:r;_check_metadata_consistencys z>_InstallRequirementBackedCandidate._check_metadata_consistencyc Csr|jr dSy |}Wn,tk rB}z|j|_Wdd}~XYnX||_|jdk s`td|d|_dS)NzDistribution already installedT) rLrarrHr0get_pkg_resources_distributionrKr/rb)rM abstract_dister:r:r;_prepares  z+_InstallRequirementBackedCandidate._preparec Cs|jj}|jj}|jjo |jj }|r|r|js|jdk s>tt d|j j pP|j t `ttLt d|j|j|jjddd}|jj}t|j|||_|WdQRXWdQRX|jdkr|dS)z-Fetch metadata, using lazy wheel if possible.Nz Collecting %sz+Obtaining dependency information from %s %s#rr)rGprepareruse_lazy_wheelrEis_wheelr]require_hashesrIr/loggerinforHr0rrr rJr2split downloader_sessionr rKrbrf)rMrhriZ remote_wheelr2sessionr:r:r;_fetch_metadatas   z2_InstallRequirementBackedCandidate._fetch_metadatacCs|jdkr||jS)N)rKrr)rMr:r:r;rBs z'_InstallRequirementBackedCandidate.distc Csft|j}|dkrdSy t|}Wn6tk rX}zd}t||j|dSd}~XYnX|j|S)Nz-Package %r has an invalid Requires-Python: %s) rrBrrrlwarningrPrGZ make_requires_python_requirement)rMrequires_pythonspecremessager:r:r;_get_requires_python_dependencys  zB_InstallRequirementBackedCandidate._get_requires_python_dependencyccsD|r|jnd}x"|D]}|jt||jVqW|VdS)Nr:)rBrequiresrGmake_requirement_from_specr1rHrw)rM with_requiresrxrr:r:r;iter_dependenciess z4_InstallRequirementBackedCandidate.iter_dependenciescCs||jS)N)rfrH)rMr:r:r;get_install_requirementsz:_InstallRequirementBackedCandidate.get_install_requirement)NN)rU __module__ __qualname____doc__ is_installedrRrVrXr[r\propertyrNrPrQr_rarbrfrrrBrwr|r}r:r:r:r;rDus(       rDcs*eZdZdZdfdd ZddZZS)r$FNc sv|}|||}|dk r,td|j|j}t||}|dk rV|jrV|j|jkrVd|_tt |j ||||||ddS)NzUsing cached wheel link: %sT)r6rNr9rOrPrQ) Zget_wheel_cache_entryrldebugr6r< persistentr5original_link_is_in_wheel_cachesuperr$rR) rMr6r7rOrPrQrN cache_entryr9)rTr:r;rR%s"     zLinkCandidate.__init__cCs|jjj|jddS)NT)parallel_builds)rGrhprepare_linked_requirementrH)rMr:r:r;raCsz,LinkCandidate._prepare_abstract_distribution)NN)rUr~r is_editablerRra __classcell__r:r:)rTr;r$"sr$cs*eZdZdZdfdd ZddZZS)r#TNcs&tt|j||t|||||ddS)N)r6rNr9rOrPrQ)rr#rRr=)rMr6r7rOrPrQ)rTr:r;rRMs zEditableCandidate.__init__cCs|jj|jS)N)rGrhprepare_editable_requirementrH)rMr:r:r;ra_sz0EditableCandidate._prepare_abstract_distribution)NN)rUr~rrrRrarr:r:)rTr;r#Js r#c@sxeZdZdZdZddZddZddZd d Zd d Z e d dZ e ddZ e ddZ ddZddZddZdS)r"TNcCs0||_t|||_||_d}|j|j|dS)Nzalready satisfied)rBrCrHrGrhprepare_installed_requirement)rMrBr7rO skip_reasonr:r:r;rRhs  z"AlreadyInstalledCandidate.__init__cCsdj|jj|jdS)Nz{class_name}({distribution!r}))rS distribution)r?rTrUrB)rMr:r:r;rVzsz"AlreadyInstalledCandidate.__repr__cCst|j|j|jfS)N)rWrTrPrQ)rMr:r:r;rXsz"AlreadyInstalledCandidate.__hash__cCs(t||jr$|j|jko"|j|jkSdS)NF)rYrTrPrQ)rMrZr:r:r;r[s z AlreadyInstalledCandidate.__eq__cCs || S)N)r[)rMrZr:r:r;r\sz AlreadyInstalledCandidate.__ne__cCs t|jjS)N)rrBr>)rMr:r:r;rPszAlreadyInstalledCandidate.namecCs|jjS)N)rBr@)rMr:r:r;rQsz!AlreadyInstalledCandidate.versioncCs t|jS)N)rrB)rMr:r:r;rsz%AlreadyInstalledCandidate.is_editablecCsd|j|jS)Nz{} {} (Installed))r?rPrQ)rMr:r:r;r_sz*AlreadyInstalledCandidate.format_for_errorccs6|sdSx(|jD]}|jt||jVqWdS)N)rBrxrGryr1rH)rMrzr{r:r:r;r|sz+AlreadyInstalledCandidate.iter_dependenciescCsdS)Nr:)rMr:r:r;r}sz1AlreadyInstalledCandidate.get_install_requirement)rUr~rrrNrRrVrXr[r\rrPrQrr_r|r}r:r:r:r;r"ds   r"c@seZdZdZddZddZddZdd Zd d Ze d d Z e ddZ ddZ e ddZ e ddZe ddZddZddZdS)ExtrasCandidateaA candidate that has 'extras', indicating additional dependencies. Requirements can be for a project with dependencies, something like foo[extra]. The extras don't affect the project/version being installed directly, but indicate that we need additional dependencies. We model that by having an artificial ExtrasCandidate that wraps the "base" candidate. The ExtrasCandidate differs from the base in the following ways: 1. It has a unique name, of the form foo[extra]. This causes the resolver to treat it as a separate node in the dependency graph. 2. When we're getting the candidate's dependencies, a) We specify that we want the extra dependencies as well. b) We add a dependency on the base candidate. See below for why this is needed. 3. We return None for the underlying InstallRequirement, as the base candidate will provide it, and we don't want to end up with duplicates. The dependency on the base candidate is needed so that the resolver can't decide that it should recommend foo[extra1] version 1.0 and foo[extra2] version 2.0. Having those candidates depend on foo=1.0 and foo=2.0 respectively forces the resolver to recognise that this is a conflict. cCs||_||_dS)N)baseextras)rMrrr:r:r;rRszExtrasCandidate.__init__cCsdj|jj|j|jdS)Nz.{class_name}(base={base!r}, extras={extras!r}))rSrr)r?rTrUrr)rMr:r:r;rVszExtrasCandidate.__repr__cCst|j|jfS)N)rWrr)rMr:r:r;rXszExtrasCandidate.__hash__cCs(t||jr$|j|jko"|j|jkSdS)NF)rYrTrr)rMrZr:r:r;r[s zExtrasCandidate.__eq__cCs || S)N)r[)rMrZr:r:r;r\szExtrasCandidate.__ne__cCst|jj|jS)z:The normalised name of the project the candidate refers to)rrrPr)rMr:r:r;rPszExtrasCandidate.namecCs|jjS)N)rrQ)rMr:r:r;rQszExtrasCandidate.versioncCsd|jdt|jS)Nz{} [{}]z, )r?rr_joinsortedr)rMr:r:r;r_sz ExtrasCandidate.format_for_errorcCs|jjS)N)rr)rMr:r:r;rszExtrasCandidate.is_installedcCs|jjS)N)rr)rMr:r:r;rszExtrasCandidate.is_editablecCs|jjS)N)rrN)rMr:r:r;rNszExtrasCandidate.source_linkccs|jj}||jV|sdS|j|jjj}|j|jjj}x&t|D]}t d|jj |j |qLWx6|jj |D]$}| t||jj|}|rz|VqzWdS)Nz%%s %s does not provide the extra '%s')rrGZmake_requirement_from_candidater intersectionrB differencerrlrsrPrQrxryr1rH)rMrzrOZ valid_extrasZinvalid_extrasextrar{ requirementr:r:r;r|s" z!ExtrasCandidate.iter_dependenciescCsdS)Nr:)rMr:r:r;r}%sz'ExtrasCandidate.get_install_requirementN)rUr~rrrRrVrXr[r\rrPrQr_rrrNr|r}r:r:r:r;rs      rc@sLeZdZdZdZddZeddZeddZd d Z d d Z d dZ dS)RequiresPythonCandidateFNcCs>|dk rt|}ntjdd}tddd|D|_dS)N.css|]}t|VqdS)N)r1).0cr:r:r; 7sz3RequiresPythonCandidate.__init__..)rsys version_inforrrJ)rMpy_version_inforr:r:r;rR1s z RequiresPythonCandidate.__init__cCsdS)Nzr:)rMr:r:r;rP=szRequiresPythonCandidate.namecCs|jS)N)rJ)rMr:r:r;rQCszRequiresPythonCandidate.versioncCs d|jS)Nz Python {})r?rQ)rMr:r:r;r_Hsz(RequiresPythonCandidate.format_for_errorcCsdS)Nr:r:)rMrzr:r:r;r|Lsz)RequiresPythonCandidate.iter_dependenciescCsdS)Nr:)rMr:r:r;r}Psz/RequiresPythonCandidate.get_install_requirement) rUr~rrrNrRrrPrQr_r|r}r:r:r:r;r-s  r)@loggingrpip._vendor.contextlib2rZ pip._vendor.packaging.specifiersrrZpip._vendor.packaging.utilsrpip._vendor.packaging.versionrpip._internal.exceptionsrrZ pip._internal.network.lazy_wheelr r pip._internal.req.constructorsr r Zpip._internal.req.req_installr pip._internal.utils.loggingrpip._internal.utils.miscrrpip._internal.utils.packagingrpip._internal.utils.typingrrrrtypingrrrrrrrZpip._vendor.pkg_resourcesrpip._internal.distributionsrpip._internal.models.linkrr rOr!Z BaseCandidate getLoggerrUrlr<r=rCrDr$r#r"rrr:r:r:r;sF               .(K~resolution/resolvelib/__pycache__/found_candidates.cpython-37.pyc000064400000006356152352421750021266 0ustar00B Re @sddlZddlZddlmZddlmZddlmZerhddlm Z m Z m Z m Z ddl mZddlmZd d Zd d ZGd ddejZdS)N)collections_abc) lru_cache)MYPY_CHECK_RUNNING)CallableIteratorOptionalSet) _BaseVersion) Candidateccs6t}x*|D]"}|j|krq ||j|Vq WdS)N)setversionadd) candidatesZreturned candidater/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py_deduplicated_by_versions    rcCs&tt|g|tddd}t|S)azIterator for ``FoundCandidates``. This iterator is used when the resolver prefers to upgrade an already-installed package. Candidates from index are returned in their normal ordering, except replaced when the version is already installed. Since candidates from index are already sorted by reverse version order, `sorted()` here would keep the ordering mostly intact, only shuffling the already-installed candidate into the correct position. We put the already- installed candidate in front of those from the index, so it's put in front after sorting due to Python sorting's stableness guarentee. r T)keyreverse)sorted itertoolschainoperator attrgetteriter) installedZothersrrrr_insert_installeds  rc@sFeZdZdZddZddZddZdd Zed d d d Z e Z dS)FoundCandidatesacA lazy sequence to provide candidates to the resolver. The intended usage is to return this from `find_matches()` so the resolver can iterate through the sequence multiple times, but only access the index page when remote packages are actually needed. This improve performances when suitable candidates are already installed on disk. cCs||_||_||_dS)N) _get_others _installed_prefers_installed)selfZ get_othersrZprefers_installedrrr__init__9szFoundCandidates.__init__cCs tddS)Nz don't do this)NotImplementedError)r"indexrrr __getitem__CszFoundCandidates.__getitem__cCsD|js|}n,|jr,t|jg|}nt|j|}t|S)N)r rr!rrrr)r"rrrr__iter__Js  zFoundCandidates.__iter__cCs tddS)Nz don't do this)r$)r"rrr__len__TszFoundCandidates.__len__r )maxsizecCs|jr|jrdSt|S)NT)r!r any)r"rrr__bool__[s zFoundCandidates.__bool__N) __name__ __module__ __qualname____doc__r#r&r'r(rr+ __nonzero__rrrrr1s  r)rrpip._vendor.six.movesrpip._internal.utils.compatrpip._internal.utils.typingrtypingrrrrpip._vendor.packaging.versionr baser rrSequencerrrrrs      resolution/resolvelib/__pycache__/__init__.cpython-37.pyc000064400000000362152352421750017522 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/__init__.pyresolution/resolvelib/__pycache__/provider.cpython-37.pyc000064400000006167152352421750017626 0ustar00B Re@sddlmZddlmZddlmZerlddlmZmZm Z m Z m Z m Z m Z mZddlmZmZddlmZGdd d eZd S) )AbstractProvider)MYPY_CHECK_RUNNING) Constraint)AnyDictIterableOptionalSequenceSetTupleUnion) Requirement Candidate)Factoryc@s<eZdZddZddZddZddZd d Zd d Zd S) PipProvidercCs"||_||_||_||_||_dS)N)_factory _constraints_ignore_dependencies_upgrade_strategy_user_requested)selffactory constraintsignore_dependenciesupgrade_strategyZuser_requestedr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/provider.py__init__*s zPipProvider.__init__cCs|jS)N)name)r dependencyrrridentify9szPipProvider.identifycCstdd|D}|t|fS)Ncss|]\}}|dk VqdS)Nr).0_parentrrr Dsz-PipProvider.get_preference..)allbool)r resolution candidatesZ informationZ transitiverrrget_preference=szPipProvider.get_preferencecsD|sgS|dj}fdd}jj|j|t|| dS)Nrcs&jdkrdSjdkr"|jkSdS)aAre upgrades allowed for this project? This checks the upgrade strategy, and whether the project was one that the user specified in the command line, in order to decide whether we should upgrade if there's a newer version available. (Note that we don't need access to the `--upgrade` flag, because an upgrade strategy of "to-satisfy-only" means that `--upgrade` was not specified). eagerTzonly-if-neededF)rr)r)rrr_eligible_for_upgradeMs   z7PipProvider.find_matches.._eligible_for_upgrade) constraintZprefers_installed)rrZfind_candidatesrgetrempty)r requirementsrr,r)rr find_matchesGs  zPipProvider.find_matchescCs ||S)N)is_satisfied_by)r requirement candidaterrrr2eszPipProvider.is_satisfied_bycCs|j }dd||DS)NcSsg|]}|dk r|qS)Nr)r"rrrr msz0PipProvider.get_dependencies..)rZiter_dependencies)rr4Z with_requiresrrrget_dependenciesiszPipProvider.get_dependenciesN) __name__ __module__ __qualname__rr!r*r1r2r7rrrrr)s  rN)Z pip._vendor.resolvelib.providersrpip._internal.utils.typingrbasertypingrrrr r r r r rrrrrrrrrs   (  resolution/resolvelib/candidates.py000064400000047445152352421750013612 0ustar00import logging import sys from pip._vendor.contextlib2 import suppress from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import Version from pip._internal.exceptions import HashError, MetadataInconsistent from pip._internal.network.lazy_wheel import ( HTTPRangeRequestUnsupported, dist_from_wheel_url, ) from pip._internal.req.constructors import ( install_req_from_editable, install_req_from_line, ) from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_is_editable, normalize_version_info from pip._internal.utils.packaging import get_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Candidate, format_name if MYPY_CHECK_RUNNING: from typing import Any, FrozenSet, Iterable, Optional, Tuple, Union from pip._vendor.packaging.version import _BaseVersion from pip._vendor.pkg_resources import Distribution from pip._internal.distributions import AbstractDistribution from pip._internal.models.link import Link from .base import Requirement from .factory import Factory BaseCandidate = Union[ "AlreadyInstalledCandidate", "EditableCandidate", "LinkCandidate", ] logger = logging.getLogger(__name__) def make_install_req_from_link(link, template): # type: (Link, InstallRequirement) -> InstallRequirement assert not template.editable, "template is editable" if template.req: line = str(template.req) else: line = link.url ireq = install_req_from_line( line, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), ) ireq.original_link = template.original_link ireq.link = link return ireq def make_install_req_from_editable(link, template): # type: (Link, InstallRequirement) -> InstallRequirement assert template.editable, "template not editable" return install_req_from_editable( link.url, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), ) def make_install_req_from_dist(dist, template): # type: (Distribution, InstallRequirement) -> InstallRequirement project_name = canonicalize_name(dist.project_name) if template.req: line = str(template.req) elif template.link: line = "{} @ {}".format(project_name, template.link.url) else: line = "{}=={}".format(project_name, dist.parsed_version) ireq = install_req_from_line( line, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=template.use_pep517, isolated=template.isolated, constraint=template.constraint, options=dict( install_options=template.install_options, global_options=template.global_options, hashes=template.hash_options ), ) ireq.satisfied_by = dist return ireq class _InstallRequirementBackedCandidate(Candidate): """A candidate backed by an ``InstallRequirement``. This represents a package request with the target not being already in the environment, and needs to be fetched and installed. The backing ``InstallRequirement`` is responsible for most of the leg work; this class exposes appropriate information to the resolver. :param link: The link passed to the ``InstallRequirement``. The backing ``InstallRequirement`` will use this link to fetch the distribution. :param source_link: The link this candidate "originates" from. This is different from ``link`` when the link is found in the wheel cache. ``link`` would point to the wheel cache, while this points to the found remote link (e.g. from pypi.org). """ is_installed = False def __init__( self, link, # type: Link source_link, # type: Link ireq, # type: InstallRequirement factory, # type: Factory name=None, # type: Optional[str] version=None, # type: Optional[_BaseVersion] ): # type: (...) -> None self._link = link self._source_link = source_link self._factory = factory self._ireq = ireq self._name = name self._version = version self._dist = None # type: Optional[Distribution] self._prepared = False def __repr__(self): # type: () -> str return "{class_name}({link!r})".format( class_name=self.__class__.__name__, link=str(self._link), ) def __hash__(self): # type: () -> int return hash((self.__class__, self._link)) def __eq__(self, other): # type: (Any) -> bool if isinstance(other, self.__class__): return self._link == other._link return False # Needed for Python 2, which does not implement this by default def __ne__(self, other): # type: (Any) -> bool return not self.__eq__(other) @property def source_link(self): # type: () -> Optional[Link] return self._source_link @property def name(self): # type: () -> str """The normalised name of the project the candidate refers to""" if self._name is None: self._name = canonicalize_name(self.dist.project_name) return self._name @property def version(self): # type: () -> _BaseVersion if self._version is None: self._version = self.dist.parsed_version return self._version def format_for_error(self): # type: () -> str return "{} {} (from {})".format( self.name, self.version, self._link.file_path if self._link.is_file else self._link ) def _prepare_abstract_distribution(self): # type: () -> AbstractDistribution raise NotImplementedError("Override in subclass") def _check_metadata_consistency(self): # type: () -> None """Check for consistency of project name and version of dist.""" # TODO: (Longer term) Rather than abort, reject this candidate # and backtrack. This would need resolvelib support. dist = self._dist # type: Distribution name = canonicalize_name(dist.project_name) if self._name is not None and self._name != name: raise MetadataInconsistent(self._ireq, "name", dist.project_name) version = dist.parsed_version if self._version is not None and self._version != version: raise MetadataInconsistent(self._ireq, "version", dist.version) def _prepare(self): # type: () -> None if self._prepared: return try: abstract_dist = self._prepare_abstract_distribution() except HashError as e: e.req = self._ireq raise self._dist = abstract_dist.get_pkg_resources_distribution() assert self._dist is not None, "Distribution already installed" self._check_metadata_consistency() self._prepared = True def _fetch_metadata(self): # type: () -> None """Fetch metadata, using lazy wheel if possible.""" preparer = self._factory.preparer use_lazy_wheel = self._factory.use_lazy_wheel remote_wheel = self._link.is_wheel and not self._link.is_file if use_lazy_wheel and remote_wheel and not preparer.require_hashes: assert self._name is not None logger.info('Collecting %s', self._ireq.req or self._ireq) # If HTTPRangeRequestUnsupported is raised, fallback silently. with indent_log(), suppress(HTTPRangeRequestUnsupported): logger.info( 'Obtaining dependency information from %s %s', self._name, self._version, ) url = self._link.url.split('#', 1)[0] session = preparer.downloader._session self._dist = dist_from_wheel_url(self._name, url, session) self._check_metadata_consistency() if self._dist is None: self._prepare() @property def dist(self): # type: () -> Distribution if self._dist is None: self._fetch_metadata() return self._dist def _get_requires_python_dependency(self): # type: () -> Optional[Requirement] requires_python = get_requires_python(self.dist) if requires_python is None: return None try: spec = SpecifierSet(requires_python) except InvalidSpecifier as e: message = "Package %r has an invalid Requires-Python: %s" logger.warning(message, self.name, e) return None return self._factory.make_requires_python_requirement(spec) def iter_dependencies(self, with_requires): # type: (bool) -> Iterable[Optional[Requirement]] requires = self.dist.requires() if with_requires else () for r in requires: yield self._factory.make_requirement_from_spec(str(r), self._ireq) yield self._get_requires_python_dependency() def get_install_requirement(self): # type: () -> Optional[InstallRequirement] self._prepare() return self._ireq class LinkCandidate(_InstallRequirementBackedCandidate): is_editable = False def __init__( self, link, # type: Link template, # type: InstallRequirement factory, # type: Factory name=None, # type: Optional[str] version=None, # type: Optional[_BaseVersion] ): # type: (...) -> None source_link = link cache_entry = factory.get_wheel_cache_entry(link, name) if cache_entry is not None: logger.debug("Using cached wheel link: %s", cache_entry.link) link = cache_entry.link ireq = make_install_req_from_link(link, template) if (cache_entry is not None and cache_entry.persistent and template.link is template.original_link): ireq.original_link_is_in_wheel_cache = True super(LinkCandidate, self).__init__( link=link, source_link=source_link, ireq=ireq, factory=factory, name=name, version=version, ) def _prepare_abstract_distribution(self): # type: () -> AbstractDistribution return self._factory.preparer.prepare_linked_requirement( self._ireq, parallel_builds=True, ) class EditableCandidate(_InstallRequirementBackedCandidate): is_editable = True def __init__( self, link, # type: Link template, # type: InstallRequirement factory, # type: Factory name=None, # type: Optional[str] version=None, # type: Optional[_BaseVersion] ): # type: (...) -> None super(EditableCandidate, self).__init__( link=link, source_link=link, ireq=make_install_req_from_editable(link, template), factory=factory, name=name, version=version, ) def _prepare_abstract_distribution(self): # type: () -> AbstractDistribution return self._factory.preparer.prepare_editable_requirement(self._ireq) class AlreadyInstalledCandidate(Candidate): is_installed = True source_link = None def __init__( self, dist, # type: Distribution template, # type: InstallRequirement factory, # type: Factory ): # type: (...) -> None self.dist = dist self._ireq = make_install_req_from_dist(dist, template) self._factory = factory # This is just logging some messages, so we can do it eagerly. # The returned dist would be exactly the same as self.dist because we # set satisfied_by in make_install_req_from_dist. # TODO: Supply reason based on force_reinstall and upgrade_strategy. skip_reason = "already satisfied" factory.preparer.prepare_installed_requirement(self._ireq, skip_reason) def __repr__(self): # type: () -> str return "{class_name}({distribution!r})".format( class_name=self.__class__.__name__, distribution=self.dist, ) def __hash__(self): # type: () -> int return hash((self.__class__, self.name, self.version)) def __eq__(self, other): # type: (Any) -> bool if isinstance(other, self.__class__): return self.name == other.name and self.version == other.version return False # Needed for Python 2, which does not implement this by default def __ne__(self, other): # type: (Any) -> bool return not self.__eq__(other) @property def name(self): # type: () -> str return canonicalize_name(self.dist.project_name) @property def version(self): # type: () -> _BaseVersion return self.dist.parsed_version @property def is_editable(self): # type: () -> bool return dist_is_editable(self.dist) def format_for_error(self): # type: () -> str return "{} {} (Installed)".format(self.name, self.version) def iter_dependencies(self, with_requires): # type: (bool) -> Iterable[Optional[Requirement]] if not with_requires: return for r in self.dist.requires(): yield self._factory.make_requirement_from_spec(str(r), self._ireq) def get_install_requirement(self): # type: () -> Optional[InstallRequirement] return None class ExtrasCandidate(Candidate): """A candidate that has 'extras', indicating additional dependencies. Requirements can be for a project with dependencies, something like foo[extra]. The extras don't affect the project/version being installed directly, but indicate that we need additional dependencies. We model that by having an artificial ExtrasCandidate that wraps the "base" candidate. The ExtrasCandidate differs from the base in the following ways: 1. It has a unique name, of the form foo[extra]. This causes the resolver to treat it as a separate node in the dependency graph. 2. When we're getting the candidate's dependencies, a) We specify that we want the extra dependencies as well. b) We add a dependency on the base candidate. See below for why this is needed. 3. We return None for the underlying InstallRequirement, as the base candidate will provide it, and we don't want to end up with duplicates. The dependency on the base candidate is needed so that the resolver can't decide that it should recommend foo[extra1] version 1.0 and foo[extra2] version 2.0. Having those candidates depend on foo=1.0 and foo=2.0 respectively forces the resolver to recognise that this is a conflict. """ def __init__( self, base, # type: BaseCandidate extras, # type: FrozenSet[str] ): # type: (...) -> None self.base = base self.extras = extras def __repr__(self): # type: () -> str return "{class_name}(base={base!r}, extras={extras!r})".format( class_name=self.__class__.__name__, base=self.base, extras=self.extras, ) def __hash__(self): # type: () -> int return hash((self.base, self.extras)) def __eq__(self, other): # type: (Any) -> bool if isinstance(other, self.__class__): return self.base == other.base and self.extras == other.extras return False # Needed for Python 2, which does not implement this by default def __ne__(self, other): # type: (Any) -> bool return not self.__eq__(other) @property def name(self): # type: () -> str """The normalised name of the project the candidate refers to""" return format_name(self.base.name, self.extras) @property def version(self): # type: () -> _BaseVersion return self.base.version def format_for_error(self): # type: () -> str return "{} [{}]".format( self.base.format_for_error(), ", ".join(sorted(self.extras)) ) @property def is_installed(self): # type: () -> bool return self.base.is_installed @property def is_editable(self): # type: () -> bool return self.base.is_editable @property def source_link(self): # type: () -> Optional[Link] return self.base.source_link def iter_dependencies(self, with_requires): # type: (bool) -> Iterable[Optional[Requirement]] factory = self.base._factory # Add a dependency on the exact base # (See note 2b in the class docstring) yield factory.make_requirement_from_candidate(self.base) if not with_requires: return # The user may have specified extras that the candidate doesn't # support. We ignore any unsupported extras here. valid_extras = self.extras.intersection(self.base.dist.extras) invalid_extras = self.extras.difference(self.base.dist.extras) for extra in sorted(invalid_extras): logger.warning( "%s %s does not provide the extra '%s'", self.base.name, self.version, extra ) for r in self.base.dist.requires(valid_extras): requirement = factory.make_requirement_from_spec( str(r), self.base._ireq, valid_extras, ) if requirement: yield requirement def get_install_requirement(self): # type: () -> Optional[InstallRequirement] # We don't return anything here, because we always # depend on the base candidate, and we'll get the # install requirement from that. return None class RequiresPythonCandidate(Candidate): is_installed = False source_link = None def __init__(self, py_version_info): # type: (Optional[Tuple[int, ...]]) -> None if py_version_info is not None: version_info = normalize_version_info(py_version_info) else: version_info = sys.version_info[:3] self._version = Version(".".join(str(c) for c in version_info)) # We don't need to implement __eq__() and __ne__() since there is always # only one RequiresPythonCandidate in a resolution, i.e. the host Python. # The built-in object.__eq__() and object.__ne__() do exactly what we want. @property def name(self): # type: () -> str # Avoid conflicting with the PyPI package "Python". return "" @property def version(self): # type: () -> _BaseVersion return self._version def format_for_error(self): # type: () -> str return "Python {}".format(self.version) def iter_dependencies(self, with_requires): # type: (bool) -> Iterable[Optional[Requirement]] return () def get_install_requirement(self): # type: () -> Optional[InstallRequirement] return None resolution/resolvelib/factory.py000064400000040770152352421750013154 0ustar00import logging from pip._vendor.packaging.utils import canonicalize_name from pip._internal.exceptions import ( DistributionNotFound, InstallationError, UnsupportedPythonVersion, UnsupportedWheel, ) from pip._internal.models.wheel import Wheel from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.compatibility_tags import get_supported from pip._internal.utils.hashes import Hashes from pip._internal.utils.misc import ( dist_in_site_packages, dist_in_usersite, get_installed_distributions, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.virtualenv import running_under_virtualenv from .base import Constraint from .candidates import ( AlreadyInstalledCandidate, EditableCandidate, ExtrasCandidate, LinkCandidate, RequiresPythonCandidate, ) from .found_candidates import FoundCandidates from .requirements import ( ExplicitRequirement, RequiresPythonRequirement, SpecifierRequirement, ) if MYPY_CHECK_RUNNING: from typing import ( FrozenSet, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, TypeVar, ) from pip._vendor.packaging.specifiers import SpecifierSet from pip._vendor.packaging.version import _BaseVersion from pip._vendor.pkg_resources import Distribution from pip._vendor.resolvelib import ResolutionImpossible from pip._internal.cache import CacheEntry, WheelCache from pip._internal.index.package_finder import PackageFinder from pip._internal.models.link import Link from pip._internal.operations.prepare import RequirementPreparer from pip._internal.resolution.base import InstallRequirementProvider from .base import Candidate, Requirement from .candidates import BaseCandidate C = TypeVar("C") Cache = Dict[Link, C] VersionCandidates = Dict[_BaseVersion, Candidate] logger = logging.getLogger(__name__) class Factory(object): def __init__( self, finder, # type: PackageFinder preparer, # type: RequirementPreparer make_install_req, # type: InstallRequirementProvider wheel_cache, # type: Optional[WheelCache] use_user_site, # type: bool force_reinstall, # type: bool ignore_installed, # type: bool ignore_requires_python, # type: bool py_version_info=None, # type: Optional[Tuple[int, ...]] lazy_wheel=False, # type: bool ): # type: (...) -> None self._finder = finder self.preparer = preparer self._wheel_cache = wheel_cache self._python_candidate = RequiresPythonCandidate(py_version_info) self._make_install_req_from_spec = make_install_req self._use_user_site = use_user_site self._force_reinstall = force_reinstall self._ignore_requires_python = ignore_requires_python self.use_lazy_wheel = lazy_wheel self._link_candidate_cache = {} # type: Cache[LinkCandidate] self._editable_candidate_cache = {} # type: Cache[EditableCandidate] if not ignore_installed: self._installed_dists = { canonicalize_name(dist.project_name): dist for dist in get_installed_distributions(local_only=False) } else: self._installed_dists = {} @property def force_reinstall(self): # type: () -> bool return self._force_reinstall def _make_candidate_from_dist( self, dist, # type: Distribution extras, # type: FrozenSet[str] template, # type: InstallRequirement ): # type: (...) -> Candidate base = AlreadyInstalledCandidate(dist, template, factory=self) if extras: return ExtrasCandidate(base, extras) return base def _make_candidate_from_link( self, link, # type: Link extras, # type: FrozenSet[str] template, # type: InstallRequirement name, # type: Optional[str] version, # type: Optional[_BaseVersion] ): # type: (...) -> Candidate # TODO: Check already installed candidate, and use it if the link and # editable flag match. if template.editable: if link not in self._editable_candidate_cache: self._editable_candidate_cache[link] = EditableCandidate( link, template, factory=self, name=name, version=version, ) base = self._editable_candidate_cache[link] # type: BaseCandidate else: if link not in self._link_candidate_cache: self._link_candidate_cache[link] = LinkCandidate( link, template, factory=self, name=name, version=version, ) base = self._link_candidate_cache[link] if extras: return ExtrasCandidate(base, extras) return base def _iter_found_candidates( self, ireqs, # type: Sequence[InstallRequirement] specifier, # type: SpecifierSet hashes, # type: Hashes prefers_installed, # type: bool ): # type: (...) -> Iterable[Candidate] if not ireqs: return () # The InstallRequirement implementation requires us to give it a # "template". Here we just choose the first requirement to represent # all of them. # Hopefully the Project model can correct this mismatch in the future. template = ireqs[0] name = canonicalize_name(template.req.name) extras = frozenset() # type: FrozenSet[str] for ireq in ireqs: specifier &= ireq.req.specifier hashes &= ireq.hashes(trust_internet=False) extras |= frozenset(ireq.extras) # Get the installed version, if it matches, unless the user # specified `--force-reinstall`, when we want the version from # the index instead. installed_candidate = None if not self._force_reinstall and name in self._installed_dists: installed_dist = self._installed_dists[name] if specifier.contains(installed_dist.version, prereleases=True): installed_candidate = self._make_candidate_from_dist( dist=installed_dist, extras=extras, template=template, ) def iter_index_candidates(): # type: () -> Iterator[Candidate] result = self._finder.find_best_candidate( project_name=name, specifier=specifier, hashes=hashes, ) # PackageFinder returns earlier versions first, so we reverse. for ican in reversed(list(result.iter_applicable())): yield self._make_candidate_from_link( link=ican.link, extras=extras, template=template, name=name, version=ican.version, ) return FoundCandidates( iter_index_candidates, installed_candidate, prefers_installed, ) def find_candidates( self, requirements, # type: Sequence[Requirement] constraint, # type: Constraint prefers_installed, # type: bool ): # type: (...) -> Iterable[Candidate] explicit_candidates = set() # type: Set[Candidate] ireqs = [] # type: List[InstallRequirement] for req in requirements: cand, ireq = req.get_candidate_lookup() if cand is not None: explicit_candidates.add(cand) if ireq is not None: ireqs.append(ireq) # If none of the requirements want an explicit candidate, we can ask # the finder for candidates. if not explicit_candidates: return self._iter_found_candidates( ireqs, constraint.specifier, constraint.hashes, prefers_installed, ) if constraint: name = explicit_candidates.pop().name raise InstallationError( "Could not satisfy constraints for {!r}: installation from " "path or url cannot be constrained to a version".format(name) ) return ( c for c in explicit_candidates if all(req.is_satisfied_by(c) for req in requirements) ) def make_requirement_from_install_req(self, ireq, requested_extras): # type: (InstallRequirement, Iterable[str]) -> Optional[Requirement] if not ireq.match_markers(requested_extras): logger.info( "Ignoring %s: markers '%s' don't match your environment", ireq.name, ireq.markers, ) return None if not ireq.link: return SpecifierRequirement(ireq) if ireq.link.is_wheel: wheel = Wheel(ireq.link.filename) if not wheel.supported(self._finder.target_python.get_tags()): msg = "{} is not a supported wheel on this platform.".format( wheel.filename, ) raise UnsupportedWheel(msg) cand = self._make_candidate_from_link( ireq.link, extras=frozenset(ireq.extras), template=ireq, name=canonicalize_name(ireq.name) if ireq.name else None, version=None, ) return self.make_requirement_from_candidate(cand) def make_requirement_from_candidate(self, candidate): # type: (Candidate) -> ExplicitRequirement return ExplicitRequirement(candidate) def make_requirement_from_spec( self, specifier, # type: str comes_from, # type: InstallRequirement requested_extras=(), # type: Iterable[str] ): # type: (...) -> Optional[Requirement] ireq = self._make_install_req_from_spec(specifier, comes_from) return self.make_requirement_from_install_req(ireq, requested_extras) def make_requires_python_requirement(self, specifier): # type: (Optional[SpecifierSet]) -> Optional[Requirement] if self._ignore_requires_python or specifier is None: return None return RequiresPythonRequirement(specifier, self._python_candidate) def get_wheel_cache_entry(self, link, name): # type: (Link, Optional[str]) -> Optional[CacheEntry] """Look up the link in the wheel cache. If ``preparer.require_hashes`` is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have nondeterministic contents due to file modification times. """ if self._wheel_cache is None or self.preparer.require_hashes: return None return self._wheel_cache.get_cache_entry( link=link, package_name=name, supported_tags=get_supported(), ) def get_dist_to_uninstall(self, candidate): # type: (Candidate) -> Optional[Distribution] # TODO: Are there more cases this needs to return True? Editable? dist = self._installed_dists.get(candidate.name) if dist is None: # Not installed, no uninstallation required. return None # We're installing into global site. The current installation must # be uninstalled, no matter it's in global or user site, because the # user site installation has precedence over global. if not self._use_user_site: return dist # We're installing into user site. Remove the user site installation. if dist_in_usersite(dist): return dist # We're installing into user site, but the installed incompatible # package is in global site. We can't uninstall that, and would let # the new user installation to "shadow" it. But shadowing won't work # in virtual environments, so we error out. if running_under_virtualenv() and dist_in_site_packages(dist): raise InstallationError( "Will not install to the user site because it will " "lack sys.path precedence to {} in {}".format( dist.project_name, dist.location, ) ) return None def _report_requires_python_error( self, requirement, # type: RequiresPythonRequirement template, # type: Candidate ): # type: (...) -> UnsupportedPythonVersion message_format = ( "Package {package!r} requires a different Python: " "{version} not in {specifier!r}" ) message = message_format.format( package=template.name, version=self._python_candidate.version, specifier=str(requirement.specifier), ) return UnsupportedPythonVersion(message) def get_installation_error(self, e): # type: (ResolutionImpossible) -> InstallationError assert e.causes, "Installation error reported with no cause" # If one of the things we can't solve is "we need Python X.Y", # that is what we report. for cause in e.causes: if isinstance(cause.requirement, RequiresPythonRequirement): return self._report_requires_python_error( cause.requirement, cause.parent, ) # Otherwise, we have a set of causes which can't all be satisfied # at once. # The simplest case is when we have *one* cause that can't be # satisfied. We just report that case. if len(e.causes) == 1: req, parent = e.causes[0] if parent is None: req_disp = str(req) else: req_disp = '{} (from {})'.format(req, parent.name) logger.critical( "Could not find a version that satisfies the requirement %s", req_disp, ) return DistributionNotFound( 'No matching distribution found for {}'.format(req) ) # OK, we now have a list of requirements that can't all be # satisfied at once. # A couple of formatting helpers def text_join(parts): # type: (List[str]) -> str if len(parts) == 1: return parts[0] return ", ".join(parts[:-1]) + " and " + parts[-1] def readable_form(cand): # type: (Candidate) -> str return "{} {}".format(cand.name, cand.version) def describe_trigger(parent): # type: (Candidate) -> str ireq = parent.get_install_requirement() if not ireq or not ireq.comes_from: return "{} {}".format(parent.name, parent.version) if isinstance(ireq.comes_from, InstallRequirement): return str(ireq.comes_from.name) return str(ireq.comes_from) triggers = [] for req, parent in e.causes: if parent is None: # This is a root requirement, so we can report it directly trigger = req.format_for_error() else: trigger = describe_trigger(parent) triggers.append(trigger) if triggers: info = text_join(triggers) else: info = "the requested packages" msg = "Cannot install {} because these package versions " \ "have conflicting dependencies.".format(info) logger.critical(msg) msg = "\nThe conflict is caused by:" for req, parent in e.causes: msg = msg + "\n " if parent: msg = msg + "{} {} depends on ".format( parent.name, parent.version ) else: msg = msg + "The user requested " msg = msg + req.format_for_error() msg = msg + "\n\n" + \ "To fix this you could try to:\n" + \ "1. loosen the range of package versions you've specified\n" + \ "2. remove package versions to allow pip attempt to solve " + \ "the dependency conflict\n" logger.info(msg) return DistributionNotFound( "ResolutionImpossible: for help visit " "https://pip.pypa.io/en/latest/user_guide/" "#fixing-conflicting-dependencies" ) resolution/resolvelib/provider.py000064400000007726152352421750013343 0ustar00from pip._vendor.resolvelib.providers import AbstractProvider from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Constraint if MYPY_CHECK_RUNNING: from typing import ( Any, Dict, Iterable, Optional, Sequence, Set, Tuple, Union, ) from .base import Requirement, Candidate from .factory import Factory # Notes on the relationship between the provider, the factory, and the # candidate and requirement classes. # # The provider is a direct implementation of the resolvelib class. Its role # is to deliver the API that resolvelib expects. # # Rather than work with completely abstract "requirement" and "candidate" # concepts as resolvelib does, pip has concrete classes implementing these two # ideas. The API of Requirement and Candidate objects are defined in the base # classes, but essentially map fairly directly to the equivalent provider # methods. In particular, `find_matches` and `is_satisfied_by` are # requirement methods, and `get_dependencies` is a candidate method. # # The factory is the interface to pip's internal mechanisms. It is stateless, # and is created by the resolver and held as a property of the provider. It is # responsible for creating Requirement and Candidate objects, and provides # services to those objects (access to pip's finder and preparer). class PipProvider(AbstractProvider): def __init__( self, factory, # type: Factory constraints, # type: Dict[str, Constraint] ignore_dependencies, # type: bool upgrade_strategy, # type: str user_requested, # type: Set[str] ): # type: (...) -> None self._factory = factory self._constraints = constraints self._ignore_dependencies = ignore_dependencies self._upgrade_strategy = upgrade_strategy self._user_requested = user_requested def identify(self, dependency): # type: (Union[Requirement, Candidate]) -> str return dependency.name def get_preference( self, resolution, # type: Optional[Candidate] candidates, # type: Sequence[Candidate] information # type: Sequence[Tuple[Requirement, Candidate]] ): # type: (...) -> Any transitive = all(parent is not None for _, parent in information) return (transitive, bool(candidates)) def find_matches(self, requirements): # type: (Sequence[Requirement]) -> Iterable[Candidate] if not requirements: return [] name = requirements[0].name def _eligible_for_upgrade(name): # type: (str) -> bool """Are upgrades allowed for this project? This checks the upgrade strategy, and whether the project was one that the user specified in the command line, in order to decide whether we should upgrade if there's a newer version available. (Note that we don't need access to the `--upgrade` flag, because an upgrade strategy of "to-satisfy-only" means that `--upgrade` was not specified). """ if self._upgrade_strategy == "eager": return True elif self._upgrade_strategy == "only-if-needed": return (name in self._user_requested) return False return self._factory.find_candidates( requirements, constraint=self._constraints.get(name, Constraint.empty()), prefers_installed=(not _eligible_for_upgrade(name)), ) def is_satisfied_by(self, requirement, candidate): # type: (Requirement, Candidate) -> bool return requirement.is_satisfied_by(candidate) def get_dependencies(self, candidate): # type: (Candidate) -> Sequence[Requirement] with_requires = not self._ignore_dependencies return [ r for r in candidate.iter_dependencies(with_requires) if r is not None ] resolution/resolvelib/found_candidates.py000064400000006755152352421750015004 0ustar00import itertools import operator from pip._vendor.six.moves import collections_abc # type: ignore from pip._internal.utils.compat import lru_cache from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Callable, Iterator, Optional, Set from pip._vendor.packaging.version import _BaseVersion from .base import Candidate def _deduplicated_by_version(candidates): # type: (Iterator[Candidate]) -> Iterator[Candidate] returned = set() # type: Set[_BaseVersion] for candidate in candidates: if candidate.version in returned: continue returned.add(candidate.version) yield candidate def _insert_installed(installed, others): # type: (Candidate, Iterator[Candidate]) -> Iterator[Candidate] """Iterator for ``FoundCandidates``. This iterator is used when the resolver prefers to upgrade an already-installed package. Candidates from index are returned in their normal ordering, except replaced when the version is already installed. Since candidates from index are already sorted by reverse version order, `sorted()` here would keep the ordering mostly intact, only shuffling the already-installed candidate into the correct position. We put the already- installed candidate in front of those from the index, so it's put in front after sorting due to Python sorting's stableness guarentee. """ candidates = sorted( itertools.chain([installed], others), key=operator.attrgetter("version"), reverse=True, ) return iter(candidates) class FoundCandidates(collections_abc.Sequence): """A lazy sequence to provide candidates to the resolver. The intended usage is to return this from `find_matches()` so the resolver can iterate through the sequence multiple times, but only access the index page when remote packages are actually needed. This improve performances when suitable candidates are already installed on disk. """ def __init__( self, get_others, # type: Callable[[], Iterator[Candidate]] installed, # type: Optional[Candidate] prefers_installed, # type: bool ): self._get_others = get_others self._installed = installed self._prefers_installed = prefers_installed def __getitem__(self, index): # type: (int) -> Candidate # Implemented to satisfy the ABC check. This is not needed by the # resolver, and should not be used by the provider either (for # performance reasons). raise NotImplementedError("don't do this") def __iter__(self): # type: () -> Iterator[Candidate] if not self._installed: candidates = self._get_others() elif self._prefers_installed: candidates = itertools.chain([self._installed], self._get_others()) else: candidates = _insert_installed(self._installed, self._get_others()) return _deduplicated_by_version(candidates) def __len__(self): # type: () -> int # Implemented to satisfy the ABC check. This is not needed by the # resolver, and should not be used by the provider either (for # performance reasons). raise NotImplementedError("don't do this") @lru_cache(maxsize=1) def __bool__(self): # type: () -> bool if self._prefers_installed and self._installed: return True return any(self) __nonzero__ = __bool__ # XXX: Python 2. resolution/resolvelib/requirements.py000064400000010637152352421750014227 0ustar00from pip._vendor.packaging.utils import canonicalize_name from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Requirement, format_name if MYPY_CHECK_RUNNING: from pip._vendor.packaging.specifiers import SpecifierSet from pip._internal.req.req_install import InstallRequirement from .base import Candidate, CandidateLookup class ExplicitRequirement(Requirement): def __init__(self, candidate): # type: (Candidate) -> None self.candidate = candidate def __repr__(self): # type: () -> str return "{class_name}({candidate!r})".format( class_name=self.__class__.__name__, candidate=self.candidate, ) @property def name(self): # type: () -> str # No need to canonicalise - the candidate did this return self.candidate.name def format_for_error(self): # type: () -> str return self.candidate.format_for_error() def get_candidate_lookup(self): # type: () -> CandidateLookup return self.candidate, None def is_satisfied_by(self, candidate): # type: (Candidate) -> bool return candidate == self.candidate class SpecifierRequirement(Requirement): def __init__(self, ireq): # type: (InstallRequirement) -> None assert ireq.link is None, "This is a link, not a specifier" self._ireq = ireq self._extras = frozenset(ireq.extras) def __str__(self): # type: () -> str return str(self._ireq.req) def __repr__(self): # type: () -> str return "{class_name}({requirement!r})".format( class_name=self.__class__.__name__, requirement=str(self._ireq.req), ) @property def name(self): # type: () -> str canonical_name = canonicalize_name(self._ireq.req.name) return format_name(canonical_name, self._extras) def format_for_error(self): # type: () -> str # Convert comma-separated specifiers into "A, B, ..., F and G" # This makes the specifier a bit more "human readable", without # risking a change in meaning. (Hopefully! Not all edge cases have # been checked) parts = [s.strip() for s in str(self).split(",")] if len(parts) == 0: return "" elif len(parts) == 1: return parts[0] return ", ".join(parts[:-1]) + " and " + parts[-1] def get_candidate_lookup(self): # type: () -> CandidateLookup return None, self._ireq def is_satisfied_by(self, candidate): # type: (Candidate) -> bool assert candidate.name == self.name, \ "Internal issue: Candidate is not for this requirement " \ " {} vs {}".format(candidate.name, self.name) # We can safely always allow prereleases here since PackageFinder # already implements the prerelease logic, and would have filtered out # prerelease candidates if the user does not expect them. spec = self._ireq.req.specifier return spec.contains(candidate.version, prereleases=True) class RequiresPythonRequirement(Requirement): """A requirement representing Requires-Python metadata. """ def __init__(self, specifier, match): # type: (SpecifierSet, Candidate) -> None self.specifier = specifier self._candidate = match def __repr__(self): # type: () -> str return "{class_name}({specifier!r})".format( class_name=self.__class__.__name__, specifier=str(self.specifier), ) @property def name(self): # type: () -> str return self._candidate.name def format_for_error(self): # type: () -> str return "Python " + str(self.specifier) def get_candidate_lookup(self): # type: () -> CandidateLookup if self.specifier.contains(self._candidate.version, prereleases=True): return self._candidate, None return None, None def is_satisfied_by(self, candidate): # type: (Candidate) -> bool assert candidate.name == self._candidate.name, "Not Python candidate" # We can safely always allow prereleases here since PackageFinder # already implements the prerelease logic, and would have filtered out # prerelease candidates if the user does not expect them. return self.specifier.contains(candidate.version, prereleases=True) resolution/resolvelib/base.py000064400000006577152352421750012426 0ustar00from pip._vendor.packaging.specifiers import SpecifierSet from pip._vendor.packaging.utils import canonicalize_name from pip._internal.req.req_install import InstallRequirement from pip._internal.utils.hashes import Hashes from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import FrozenSet, Iterable, Optional, Tuple from pip._vendor.packaging.version import _BaseVersion from pip._internal.models.link import Link CandidateLookup = Tuple[ Optional["Candidate"], Optional[InstallRequirement], ] def format_name(project, extras): # type: (str, FrozenSet[str]) -> str if not extras: return project canonical_extras = sorted(canonicalize_name(e) for e in extras) return "{}[{}]".format(project, ",".join(canonical_extras)) class Constraint(object): def __init__(self, specifier, hashes): # type: (SpecifierSet, Hashes) -> None self.specifier = specifier self.hashes = hashes @classmethod def empty(cls): # type: () -> Constraint return Constraint(SpecifierSet(), Hashes()) @classmethod def from_ireq(cls, ireq): # type: (InstallRequirement) -> Constraint return Constraint(ireq.specifier, ireq.hashes(trust_internet=False)) def __nonzero__(self): # type: () -> bool return bool(self.specifier) or bool(self.hashes) def __bool__(self): # type: () -> bool return self.__nonzero__() def __and__(self, other): # type: (InstallRequirement) -> Constraint if not isinstance(other, InstallRequirement): return NotImplemented specifier = self.specifier & other.specifier hashes = self.hashes & other.hashes(trust_internet=False) return Constraint(specifier, hashes) class Requirement(object): @property def name(self): # type: () -> str raise NotImplementedError("Subclass should override") def is_satisfied_by(self, candidate): # type: (Candidate) -> bool return False def get_candidate_lookup(self): # type: () -> CandidateLookup raise NotImplementedError("Subclass should override") def format_for_error(self): # type: () -> str raise NotImplementedError("Subclass should override") class Candidate(object): @property def name(self): # type: () -> str raise NotImplementedError("Override in subclass") @property def version(self): # type: () -> _BaseVersion raise NotImplementedError("Override in subclass") @property def is_installed(self): # type: () -> bool raise NotImplementedError("Override in subclass") @property def is_editable(self): # type: () -> bool raise NotImplementedError("Override in subclass") @property def source_link(self): # type: () -> Optional[Link] raise NotImplementedError("Override in subclass") def iter_dependencies(self, with_requires): # type: (bool) -> Iterable[Optional[Requirement]] raise NotImplementedError("Override in subclass") def get_install_requirement(self): # type: () -> Optional[InstallRequirement] raise NotImplementedError("Override in subclass") def format_for_error(self): # type: () -> str raise NotImplementedError("Subclass should override") resolution/resolvelib/resolver.py000064400000023561152352421750013345 0ustar00import functools import logging from pip._vendor import six from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible from pip._vendor.resolvelib import Resolver as RLResolver from pip._internal.exceptions import InstallationError from pip._internal.req.req_install import check_invalid_constraint_type from pip._internal.req.req_set import RequirementSet from pip._internal.resolution.base import BaseResolver from pip._internal.resolution.resolvelib.provider import PipProvider from pip._internal.utils.misc import dist_is_editable from pip._internal.utils.typing import MYPY_CHECK_RUNNING from .base import Constraint from .factory import Factory if MYPY_CHECK_RUNNING: from typing import Dict, List, Optional, Set, Tuple from pip._vendor.resolvelib.resolvers import Result from pip._vendor.resolvelib.structs import Graph from pip._internal.cache import WheelCache from pip._internal.index.package_finder import PackageFinder from pip._internal.operations.prepare import RequirementPreparer from pip._internal.req.req_install import InstallRequirement from pip._internal.resolution.base import InstallRequirementProvider logger = logging.getLogger(__name__) class Resolver(BaseResolver): _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} def __init__( self, preparer, # type: RequirementPreparer finder, # type: PackageFinder wheel_cache, # type: Optional[WheelCache] make_install_req, # type: InstallRequirementProvider use_user_site, # type: bool ignore_dependencies, # type: bool ignore_installed, # type: bool ignore_requires_python, # type: bool force_reinstall, # type: bool upgrade_strategy, # type: str py_version_info=None, # type: Optional[Tuple[int, ...]] lazy_wheel=False, # type: bool ): super(Resolver, self).__init__() if lazy_wheel: logger.warning( 'pip is using lazily downloaded wheels using HTTP ' 'range requests to obtain dependency information. ' 'This experimental feature is enabled through ' '--use-feature=fast-deps and it is not ready for production.' ) assert upgrade_strategy in self._allowed_strategies self.factory = Factory( finder=finder, preparer=preparer, make_install_req=make_install_req, wheel_cache=wheel_cache, use_user_site=use_user_site, force_reinstall=force_reinstall, ignore_installed=ignore_installed, ignore_requires_python=ignore_requires_python, py_version_info=py_version_info, lazy_wheel=lazy_wheel, ) self.ignore_dependencies = ignore_dependencies self.upgrade_strategy = upgrade_strategy self._result = None # type: Optional[Result] def resolve(self, root_reqs, check_supported_wheels): # type: (List[InstallRequirement], bool) -> RequirementSet constraints = {} # type: Dict[str, Constraint] user_requested = set() # type: Set[str] requirements = [] for req in root_reqs: if req.constraint: # Ensure we only accept valid constraints problem = check_invalid_constraint_type(req) if problem: raise InstallationError(problem) if not req.match_markers(): continue name = canonicalize_name(req.name) if name in constraints: constraints[name] &= req else: constraints[name] = Constraint.from_ireq(req) else: if req.user_supplied and req.name: user_requested.add(canonicalize_name(req.name)) r = self.factory.make_requirement_from_install_req( req, requested_extras=(), ) if r is not None: requirements.append(r) provider = PipProvider( factory=self.factory, constraints=constraints, ignore_dependencies=self.ignore_dependencies, upgrade_strategy=self.upgrade_strategy, user_requested=user_requested, ) reporter = BaseReporter() resolver = RLResolver(provider, reporter) try: try_to_avoid_resolution_too_deep = 2000000 self._result = resolver.resolve( requirements, max_rounds=try_to_avoid_resolution_too_deep, ) except ResolutionImpossible as e: error = self.factory.get_installation_error(e) six.raise_from(error, e) req_set = RequirementSet(check_supported_wheels=check_supported_wheels) for candidate in self._result.mapping.values(): ireq = candidate.get_install_requirement() if ireq is None: continue # Check if there is already an installation under the same name, # and set a flag for later stages to uninstall it, if needed. # * There isn't, good -- no uninstalltion needed. # * The --force-reinstall flag is set. Always reinstall. # * The installation is different in version or editable-ness, so # we need to uninstall it to install the new distribution. # * The installed version is the same as the pending distribution. # Skip this distrubiton altogether to save work. installed_dist = self.factory.get_dist_to_uninstall(candidate) if installed_dist is None: ireq.should_reinstall = False elif self.factory.force_reinstall: ireq.should_reinstall = True elif installed_dist.parsed_version != candidate.version: ireq.should_reinstall = True elif dist_is_editable(installed_dist) != candidate.is_editable: ireq.should_reinstall = True else: continue link = candidate.source_link if link and link.is_yanked: # The reason can contain non-ASCII characters, Unicode # is required for Python 2. msg = ( u'The candidate selected for download or install is a ' u'yanked version: {name!r} candidate (version {version} ' u'at {link})\nReason for being yanked: {reason}' ).format( name=candidate.name, version=candidate.version, link=link, reason=link.yanked_reason or u'', ) logger.warning(msg) req_set.add_named_requirement(ireq) return req_set def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Get order for installation of requirements in RequirementSet. The returned list contains a requirement before another that depends on it. This helps ensure that the environment is kept consistent as they get installed one-by-one. The current implementation creates a topological ordering of the dependency graph, while breaking any cycles in the graph at arbitrary points. We make no guarantees about where the cycle would be broken, other than they would be broken. """ assert self._result is not None, "must call resolve() first" graph = self._result.graph weights = get_topological_weights(graph) sorted_items = sorted( req_set.requirements.items(), key=functools.partial(_req_set_item_sorter, weights=weights), reverse=True, ) return [ireq for _, ireq in sorted_items] def get_topological_weights(graph): # type: (Graph) -> Dict[Optional[str], int] """Assign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior notice. We take the length for the longest path to any node from root, ignoring any paths that contain a single node twice (i.e. cycles). This is done through a depth-first search through the graph, while keeping track of the path to the node. Cycles in the graph result would result in node being revisited while also being it's own path. In this case, take no action. This helps ensure we don't get stuck in a cycle. When assigning weight, the longer path (i.e. larger length) is preferred. """ path = set() # type: Set[Optional[str]] weights = {} # type: Dict[Optional[str], int] def visit(node): # type: (Optional[str]) -> None if node in path: # We hit a cycle, so we'll break it here. return # Time to visit the children! path.add(node) for child in graph.iter_children(node): visit(child) path.remove(node) last_known_parent_count = weights.get(node, 0) weights[node] = max(last_known_parent_count, len(path)) # `None` is guaranteed to be the root node by resolvelib. visit(None) # Sanity checks assert weights[None] == 0 assert len(weights) == len(graph) return weights def _req_set_item_sorter( item, # type: Tuple[str, InstallRequirement] weights, # type: Dict[Optional[str], int] ): # type: (...) -> Tuple[int, str] """Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests. """ name = canonicalize_name(item[0]) return weights[name], name resolution/resolvelib/__init__.py000064400000000000152352421750013222 0ustar00resolution/legacy/__pycache__/resolver.cpython-37.pyc000064400000027154152352421750016732 0ustar00B ReI@sdZddlZddlZddlmZddlmZddlmZddl m Z m Z m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZdd lmZddlmZmZddl m!Z!e!rZddl"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/ddl0m1Z1ddl2m3Z3ddlm4Z4ddlm5Z5e#e6e$e4fZ7e8e9Z:dddZ;GdddeZzqThe candidate selected for download or install is a yanked version: {candidate} Reason for being yanked: {reason}) candidatereason) r\r@rcrb is_yanked yanked_reasonr,r%r&)rJrTr`best_candidaterbrgmsgr3r3r4_find_requirement_links    zResolver._find_requirement_linkcCs~|jdkr|||_|jdks(|jjr,dS|jj|j|jtd}|dk rzt d|j|j|j krr|j rrd|_ |j|_dS)afEnsure that if a link can be found for this, that it is found. Note that req.link may still be None - if the requirement is already installed and not needed to be upgraded based on the return value of _is_upgrade_allowed(). If preparer.require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. N)rb package_namesupported_tagszUsing cached wheel link: %sT) rbrlrAr?require_hashesget_cache_entrynamer r%r+ original_link persistentoriginal_link_is_in_wheel_cache)rJrT cache_entryr3r3r4_populate_link%s   zResolver._populate_linkcCs|jr|j|S|jdks t||}|jr>|j||S|||j|}|j sf| |j |jr|j dkp|j p|j p|jjdk}|r||n td||S)zzTakes a InstallRequirement and returns a single AbstractDist representing a prepared variant of the same. Nzto-satisfy-onlyfilez.add_reqN)rz!Installing extra requirements: %r,z"%s does not provide the extra '%s')r)rOpreparedrget_pkg_resources_distributionr5r>r.rhas_requirementrqr[r<rPrDextrasr%r+r(sortedsetr&requiresrxr]successfully_downloaded) rJrWrdrr-rmissing_requestedmissingavailable_requestedrr3)rrdrWrJr4rSusB        zResolver._resolve_onecs<gtfddx|jD] }|q(WS)zCreate the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. csR|js|krdS|jrdS|xj|jD] }|q4W|dS)N)r]rOaddrIrqrU)rTdep)order ordered_reqsschedulerJr3r4rs  z1Resolver.get_installation_order..schedule)r requirementsvalues)rJreq_set install_reqr3)rrrrJr4get_installation_orders   zResolver.get_installation_order)N)__name__ __module__ __qualname____doc__r;r:rZr\r_rerlrvrrSr __classcell__r3r3)rMr4r6ms &  52Yr6)F)=rloggingr= collectionsr itertoolsrZpip._vendor.packagingrpip._internal.exceptionsrrrrr Zpip._internal.req.req_installr Zpip._internal.req.req_setr pip._internal.resolution.baser &pip._internal.utils.compatibility_tagsr pip._internal.utils.loggingrpip._internal.utils.miscrrrpip._internal.utils.packagingrrpip._internal.utils.typingrtypingrrrrr pip._vendorrpip._internal.cacherpip._internal.distributionsr"pip._internal.index.package_finderrpip._internal.models.linkr pip._internal.operations.preparerr r!r*ZDiscoveredDependencies getLoggerrr%r5r6r3r3r3r4 s:                    -resolution/legacy/__pycache__/__init__.cpython-37.pyc000064400000000356152352421750016623 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/resolution/legacy/__init__.pyresolution/legacy/resolver.py000064400000044714152352421750012446 0ustar00"""Dependency Resolution The dependency resolution in pip is performed as follows: for top-level requirements: a. only one spec allowed per project, regardless of conflicts or not. otherwise a "double requirement" exception is raised b. they override sub-dependency requirements. for sub-dependencies a. "first found, wins" (where the order is breadth first) """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False import logging import sys from collections import defaultdict from itertools import chain from pip._vendor.packaging import specifiers from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, HashError, HashErrors, UnsupportedPythonVersion, ) from pip._internal.req.req_install import check_invalid_constraint_type from pip._internal.req.req_set import RequirementSet from pip._internal.resolution.base import BaseResolver from pip._internal.utils.compatibility_tags import get_supported from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import dist_in_usersite, normalize_version_info from pip._internal.utils.misc import dist_in_install_path from pip._internal.utils.packaging import ( check_requires_python, get_requires_python, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import DefaultDict, List, Optional, Set, Tuple from pip._vendor import pkg_resources from pip._internal.cache import WheelCache from pip._internal.distributions import AbstractDistribution from pip._internal.index.package_finder import PackageFinder from pip._internal.models.link import Link from pip._internal.operations.prepare import RequirementPreparer from pip._internal.req.req_install import InstallRequirement from pip._internal.resolution.base import InstallRequirementProvider DiscoveredDependencies = DefaultDict[str, List[InstallRequirement]] logger = logging.getLogger(__name__) def _check_dist_requires_python( dist, # type: pkg_resources.Distribution version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> None """ Check whether the given Python version is compatible with a distribution's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. :raises UnsupportedPythonVersion: When the given Python version isn't compatible. """ requires_python = get_requires_python(dist) try: is_compatible = check_requires_python( requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier as exc: logger.warning( "Package %r has an invalid Requires-Python: %s", dist.project_name, exc, ) return if is_compatible: return version = '.'.join(map(str, version_info)) if ignore_requires_python: logger.debug( 'Ignoring failed Requires-Python check for package %r: ' '%s not in %r', dist.project_name, version, requires_python, ) return raise UnsupportedPythonVersion( 'Package {!r} requires a different Python: {} not in {!r}'.format( dist.project_name, version, requires_python, )) class Resolver(BaseResolver): """Resolves which packages need to be installed/uninstalled to perform \ the requested operation without breaking the requirements of any package. """ _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} def __init__( self, preparer, # type: RequirementPreparer finder, # type: PackageFinder wheel_cache, # type: Optional[WheelCache] make_install_req, # type: InstallRequirementProvider use_user_site, # type: bool ignore_dependencies, # type: bool ignore_installed, # type: bool ignore_requires_python, # type: bool force_reinstall, # type: bool upgrade_strategy, # type: str py_version_info=None, # type: Optional[Tuple[int, ...]] ): # type: (...) -> None super(Resolver, self).__init__() assert upgrade_strategy in self._allowed_strategies if py_version_info is None: py_version_info = sys.version_info[:3] else: py_version_info = normalize_version_info(py_version_info) self._py_version_info = py_version_info self.preparer = preparer self.finder = finder self.wheel_cache = wheel_cache self.upgrade_strategy = upgrade_strategy self.force_reinstall = force_reinstall self.ignore_dependencies = ignore_dependencies self.ignore_installed = ignore_installed self.ignore_requires_python = ignore_requires_python self.use_user_site = use_user_site self._make_install_req = make_install_req self._discovered_dependencies = \ defaultdict(list) # type: DiscoveredDependencies def resolve(self, root_reqs, check_supported_wheels): # type: (List[InstallRequirement], bool) -> RequirementSet """Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be possible to move the preparation to become a step separated from dependency resolution. """ requirement_set = RequirementSet( check_supported_wheels=check_supported_wheels ) for req in root_reqs: if req.constraint: check_invalid_constraint_type(req) requirement_set.add_requirement(req) # Actually prepare the files, and collect any exceptions. Most hash # exceptions cannot be checked ahead of time, because # _populate_link() needs to be called before we can make decisions # based on link type. discovered_reqs = [] # type: List[InstallRequirement] hash_errors = HashErrors() for req in chain(requirement_set.all_requirements, discovered_reqs): try: discovered_reqs.extend(self._resolve_one(requirement_set, req)) except HashError as exc: exc.req = req hash_errors.append(exc) if hash_errors: raise hash_errors return requirement_set def _is_upgrade_allowed(self, req): # type: (InstallRequirement) -> bool if self.upgrade_strategy == "to-satisfy-only": return False elif self.upgrade_strategy == "eager": return True else: assert self.upgrade_strategy == "only-if-needed" return req.user_supplied or req.constraint def _set_req_to_reinstall(self, req): # type: (InstallRequirement) -> None """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. if ((not self.use_user_site or dist_in_usersite(req.satisfied_by)) and dist_in_install_path(req.satisfied_by)): req.should_reinstall = True req.satisfied_by = None def _check_skip_installed(self, req_to_install): # type: (InstallRequirement) -> Optional[str] """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. """ if self.ignore_installed: return None req_to_install.check_if_exists(self.use_user_site) if not req_to_install.satisfied_by: return None if self.force_reinstall: self._set_req_to_reinstall(req_to_install) return None if not self._is_upgrade_allowed(req_to_install): if self.upgrade_strategy == "only-if-needed": return 'already satisfied, skipping upgrade' return 'already satisfied' # Check for the possibility of an upgrade. For link-based # requirements we have to pull the tree down and inspect to assess # the version #, so it's handled way down. if not req_to_install.link: try: self.finder.find_requirement(req_to_install, upgrade=True) except BestVersionAlreadyInstalled: # Then the best version is installed. return 'already up-to-date' except DistributionNotFound: # No distribution found, so we squash the error. It will # be raised later when we re-try later to do the install. # Why don't we just raise here? pass self._set_req_to_reinstall(req_to_install) return None def _find_requirement_link(self, req): # type: (InstallRequirement) -> Optional[Link] upgrade = self._is_upgrade_allowed(req) best_candidate = self.finder.find_requirement(req, upgrade) if not best_candidate: return None # Log a warning per PEP 592 if necessary before returning. link = best_candidate.link if link.is_yanked: reason = link.yanked_reason or '' msg = ( # Mark this as a unicode string to prevent # "UnicodeEncodeError: 'ascii' codec can't encode character" # in Python 2 when the reason contains non-ascii characters. u'The candidate selected for download or install is a ' 'yanked version: {candidate}\n' 'Reason for being yanked: {reason}' ).format(candidate=best_candidate, reason=reason) logger.warning(msg) return link def _populate_link(self, req): # type: (InstallRequirement) -> None """Ensure that if a link can be found for this, that it is found. Note that req.link may still be None - if the requirement is already installed and not needed to be upgraded based on the return value of _is_upgrade_allowed(). If preparer.require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. """ if req.link is None: req.link = self._find_requirement_link(req) if self.wheel_cache is None or self.preparer.require_hashes: return cache_entry = self.wheel_cache.get_cache_entry( link=req.link, package_name=req.name, supported_tags=get_supported(), ) if cache_entry is not None: logger.debug('Using cached wheel link: %s', cache_entry.link) if req.link is req.original_link and cache_entry.persistent: req.original_link_is_in_wheel_cache = True req.link = cache_entry.link def _get_abstract_dist_for(self, req): # type: (InstallRequirement) -> AbstractDistribution """Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same. """ if req.editable: return self.preparer.prepare_editable_requirement(req) # satisfied_by is only evaluated by calling _check_skip_installed, # so it must be None here. assert req.satisfied_by is None skip_reason = self._check_skip_installed(req) if req.satisfied_by: return self.preparer.prepare_installed_requirement( req, skip_reason ) # We eagerly populate the link, since that's our "legacy" behavior. self._populate_link(req) abstract_dist = self.preparer.prepare_linked_requirement(req) # NOTE # The following portion is for determining if a certain package is # going to be re-installed/upgraded or not and reporting to the user. # This should probably get cleaned up in a future refactor. # req.req is only avail after unpack for URL # pkgs repeat check_if_exists to uninstall-on-upgrade # (#14) if not self.ignore_installed: req.check_if_exists(self.use_user_site) if req.satisfied_by: should_modify = ( self.upgrade_strategy != "to-satisfy-only" or self.force_reinstall or self.ignore_installed or req.link.scheme == 'file' ) if should_modify: self._set_req_to_reinstall(req) else: logger.info( 'Requirement already satisfied (use --upgrade to upgrade):' ' %s', req, ) return abstract_dist def _resolve_one( self, requirement_set, # type: RequirementSet req_to_install, # type: InstallRequirement ): # type: (...) -> List[InstallRequirement] """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting # (remote url or package name) if req_to_install.constraint or req_to_install.prepared: return [] req_to_install.prepared = True abstract_dist = self._get_abstract_dist_for(req_to_install) # Parse and return dependencies dist = abstract_dist.get_pkg_resources_distribution() # This will raise UnsupportedPythonVersion if the given Python # version isn't compatible with the distribution's Requires-Python. _check_dist_requires_python( dist, version_info=self._py_version_info, ignore_requires_python=self.ignore_requires_python, ) more_reqs = [] # type: List[InstallRequirement] def add_req(subreq, extras_requested): sub_install_req = self._make_install_req( str(subreq), req_to_install, ) parent_req_name = req_to_install.name to_scan_again, add_to_parent = requirement_set.add_requirement( sub_install_req, parent_req_name=parent_req_name, extras_requested=extras_requested, ) if parent_req_name and add_to_parent: self._discovered_dependencies[parent_req_name].append( add_to_parent ) more_reqs.extend(to_scan_again) with indent_log(): # We add req_to_install before its dependencies, so that we # can refer to it when adding dependencies. if not requirement_set.has_requirement(req_to_install.name): # 'unnamed' requirements will get added here # 'unnamed' requirements can only come from being directly # provided by the user. assert req_to_install.user_supplied requirement_set.add_requirement( req_to_install, parent_req_name=None, ) if not self.ignore_dependencies: if req_to_install.extras: logger.debug( "Installing extra requirements: %r", ','.join(req_to_install.extras), ) missing_requested = sorted( set(req_to_install.extras) - set(dist.extras) ) for missing in missing_requested: logger.warning( "%s does not provide the extra '%s'", dist, missing ) available_requested = sorted( set(dist.extras) & set(req_to_install.extras) ) for subreq in dist.requires(available_requested): add_req(subreq, extras_requested=available_requested) if not req_to_install.editable and not req_to_install.satisfied_by: # XXX: --no-install leads this to report 'Successfully # downloaded' for only non-editable reqs, even though we took # action on them. req_to_install.successfully_downloaded = True return more_reqs def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # dependencies must come earlier to achieve topological order. order = [] ordered_reqs = set() # type: Set[InstallRequirement] def schedule(req): if req.satisfied_by or req in ordered_reqs: return if req.constraint: return ordered_reqs.add(req) for dep in self._discovered_dependencies[req.name]: schedule(dep) order.append(req) for install_req in req_set.requirements.values(): schedule(install_req) return order resolution/legacy/__init__.py000064400000000000152352421750012320 0ustar00resolution/base.py000064400000001252152352421750010241 0ustar00from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Callable, List from pip._internal.req.req_install import InstallRequirement from pip._internal.req.req_set import RequirementSet InstallRequirementProvider = Callable[ [str, InstallRequirement], InstallRequirement ] class BaseResolver(object): def resolve(self, root_reqs, check_supported_wheels): # type: (List[InstallRequirement], bool) -> RequirementSet raise NotImplementedError() def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] raise NotImplementedError() resolution/__init__.py000064400000000000152352421750011054 0ustar00index/collector.py000064400000053500152352421750010224 0ustar00""" The main purpose of this module is to expose LinkCollector.collect_links(). """ import cgi import functools import itertools import logging import mimetypes import os import re from collections import OrderedDict from pip._vendor import html5lib, requests from pip._vendor.distlib.compat import unescape from pip._vendor.requests.exceptions import RetryError, SSLError from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.exceptions import NetworkConnectionError from pip._internal.models.link import Link from pip._internal.models.search_scope import SearchScope from pip._internal.network.utils import raise_for_status from pip._internal.utils.compat import lru_cache from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS from pip._internal.utils.misc import pairwise, redact_auth_from_url from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.urls import path_to_url, url_to_path from pip._internal.vcs import is_url, vcs if MYPY_CHECK_RUNNING: from optparse import Values from typing import ( Callable, Iterable, List, MutableMapping, Optional, Sequence, Tuple, Union, ) import xml.etree.ElementTree from pip._vendor.requests import Response from pip._internal.network.session import PipSession HTMLElement = xml.etree.ElementTree.Element ResponseHeaders = MutableMapping[str, str] logger = logging.getLogger(__name__) def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return None def _is_url_like_archive(url): # type: (str) -> bool """Return whether the URL looks like an archive. """ filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False class _NotHTML(Exception): def __init__(self, content_type, request_desc): # type: (str, str) -> None super(_NotHTML, self).__init__(content_type, request_desc) self.content_type = content_type self.request_desc = request_desc def _ensure_html_header(response): # type: (Response) -> None """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/html"): raise _NotHTML(content_type, response.request.method) class _NotHTTP(Exception): pass def _ensure_html_response(url, session): # type: (str, PipSession) -> None """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) raise_for_status(resp) _ensure_html_header(resp) def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if _is_url_like_archive(url): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) raise_for_status(resp) # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp def _get_encoding_from_headers(headers): # type: (ResponseHeaders) -> Optional[str] """Determine if we have any encoding information in our headers. """ if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: return params['charset'] return None def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str """Determine the HTML document's base URL. This looks for a ```` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. """ for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url def _clean_url_path_part(part): # type: (str) -> str """ Clean a "part" of a URL path (i.e. after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. return urllib_parse.quote(urllib_parse.unquote(part)) def _clean_file_url_path(part): # type: (str) -> str """ Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. # Also, on Windows the path part might contain a drive letter which # should not be quoted. On Linux where drive letters do not # exist, the colon should be quoted. We rely on urllib.request # to do the right thing here. return urllib_request.pathname2url(urllib_request.url2pathname(part)) # percent-encoded: / _reserved_chars_re = re.compile('(@|%2F)', re.IGNORECASE) def _clean_url_path(path, is_local_path): # type: (str, bool) -> str """ Clean the path portion of a URL. """ if is_local_path: clean_func = _clean_file_url_path else: clean_func = _clean_url_path_part # Split on the reserved characters prior to cleaning so that # revision strings in VCS URLs are properly preserved. parts = _reserved_chars_re.split(path) cleaned_parts = [] for to_clean, reserved in pairwise(itertools.chain(parts, [''])): cleaned_parts.append(clean_func(to_clean)) # Normalize %xx escapes (e.g. %2f -> %2F) cleaned_parts.append(reserved.upper()) return ''.join(cleaned_parts) def _clean_link(url): # type: (str) -> str """ Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters. """ # Split the URL into parts according to the general structure # `scheme://netloc/path;parameters?query#fragment`. result = urllib_parse.urlparse(url) # If the netloc is empty, then the URL refers to a local filesystem path. is_local_path = not result.netloc path = _clean_url_path(result.path, is_local_path=is_local_path) return urllib_parse.urlunparse(result._replace(path=path)) def _create_link_from_element( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str ): # type: (...) -> Optional[Link] """ Convert an anchor element in a simple repository page to a Link. """ href = anchor.get("href") if not href: return None url = _clean_link(urllib_parse.urljoin(base_url, href)) pyrequire = anchor.get('data-requires-python') pyrequire = unescape(pyrequire) if pyrequire else None yanked_reason = anchor.get('data-yanked') if yanked_reason: # This is a unicode string in Python 2 (and 3). yanked_reason = unescape(yanked_reason) link = Link( url, comes_from=page_url, requires_python=pyrequire, yanked_reason=yanked_reason, ) return link class CacheablePageContent(object): def __init__(self, page): # type: (HTMLPage) -> None assert page.cache_link_parsing self.page = page def __eq__(self, other): # type: (object) -> bool return (isinstance(other, type(self)) and self.page.url == other.page.url) def __hash__(self): # type: () -> int return hash(self.page.url) def with_cached_html_pages( fn, # type: Callable[[HTMLPage], Iterable[Link]] ): # type: (...) -> Callable[[HTMLPage], List[Link]] """ Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`. """ @lru_cache(maxsize=None) def wrapper(cacheable_page): # type: (CacheablePageContent) -> List[Link] return list(fn(cacheable_page.page)) @functools.wraps(fn) def wrapper_wrapper(page): # type: (HTMLPage) -> List[Link] if page.cache_link_parsing: return wrapper(CacheablePageContent(page)) return list(fn(page)) return wrapper_wrapper @with_cached_html_pages def parse_links(page): # type: (HTMLPage) -> Iterable[Link] """ Parse an HTML document, and yield its anchor elements as Link objects. """ document = html5lib.parse( page.content, transport_encoding=page.encoding, namespaceHTMLElements=False, ) url = page.url base_url = _determine_base_url(document, url) for anchor in document.findall(".//a"): link = _create_link_from_element( anchor, page_url=url, base_url=base_url, ) if link is None: continue yield link class HTMLPage(object): """Represents one page, along with its URL""" def __init__( self, content, # type: bytes encoding, # type: Optional[str] url, # type: str cache_link_parsing=True, # type: bool ): # type: (...) -> None """ :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. :param cache_link_parsing: whether links parsed from this page's url should be cached. PyPI index urls should have this set to False, for example. """ self.content = content self.encoding = encoding self.url = url self.cache_link_parsing = cache_link_parsing def __str__(self): # type: () -> str return redact_auth_from_url(self.url) def _handle_get_page_fail( link, # type: Link reason, # type: Union[str, Exception] meth=None # type: Optional[Callable[..., None]] ): # type: (...) -> None if meth is None: meth = logger.debug meth("Could not fetch URL %s: %s - skipping", link, reason) def _make_html_page(response, cache_link_parsing=True): # type: (Response, bool) -> HTMLPage encoding = _get_encoding_from_headers(response.headers) return HTMLPage( response.content, encoding=encoding, url=response.url, cache_link_parsing=cache_link_parsing) def _get_html_page(link, session=None): # type: (Link, Optional[PipSession]) -> Optional[HTMLPage] if session is None: raise TypeError( "_get_html_page() missing 1 required keyword argument: 'session'" ) url = link.url.split('#', 1)[0] # Check for VCS schemes that do not support lookup as web pages. vcs_scheme = _match_vcs_scheme(url) if vcs_scheme: logger.warning('Cannot look at %s URL %s because it does not support ' 'lookup as web pages.', vcs_scheme, link) return None # Tack index.html onto file:// URLs that point to directories scheme, _, path, _, _, _ = urllib_parse.urlparse(url) if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))): # add trailing slash if not present so urljoin doesn't trim # final segment if not url.endswith('/'): url += '/' url = urllib_parse.urljoin(url, 'index.html') logger.debug(' file: URL is directory, getting %s', url) try: resp = _get_html_response(url, session=session) except _NotHTTP: logger.warning( 'Skipping page %s because it looks like an archive, and cannot ' 'be checked by a HTTP HEAD request.', link, ) except _NotHTML as exc: logger.warning( 'Skipping page %s because the %s request got Content-Type: %s.' 'The only supported Content-Type is text/html', link, exc.request_desc, exc.content_type, ) except NetworkConnectionError as exc: _handle_get_page_fail(link, exc) except RetryError as exc: _handle_get_page_fail(link, exc) except SSLError as exc: reason = "There was a problem confirming the ssl certificate: " reason += str(exc) _handle_get_page_fail(link, reason, meth=logger.info) except requests.ConnectionError as exc: _handle_get_page_fail(link, "connection error: {}".format(exc)) except requests.Timeout: _handle_get_page_fail(link, "timed out") else: return _make_html_page(resp, cache_link_parsing=link.cache_link_parsing) return None def _remove_duplicate_links(links): # type: (Iterable[Link]) -> List[Link] """ Return a list of links, with duplicates removed and ordering preserved. """ # We preserve the ordering when removing duplicates because we can. return list(OrderedDict.fromkeys(links)) def group_locations(locations, expand_dir=False): # type: (Sequence[str], bool) -> Tuple[List[str], List[str]] """ Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): # type: (str) -> None url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) else: logger.warning( "Path '%s' is ignored: it is a directory.", path, ) elif os.path.isfile(path): sort_path(path) else: logger.warning( "Url '%s' is ignored: it is neither a file " "nor a directory.", url, ) elif is_url(url): # Only add url with clear scheme urls.append(url) else: logger.warning( "Url '%s' is ignored. It is either a non-existing " "path or lacks a specific scheme.", url, ) return files, urls class CollectedLinks(object): """ Encapsulates the return value of a call to LinkCollector.collect_links(). The return value includes both URLs to project pages containing package links, as well as individual package Link objects collected from other sources. This info is stored separately as: (1) links from the configured file locations, (2) links from the configured find_links, and (3) urls to HTML project pages, as described by the PEP 503 simple repository API. """ def __init__( self, files, # type: List[Link] find_links, # type: List[Link] project_urls, # type: List[Link] ): # type: (...) -> None """ :param files: Links from file locations. :param find_links: Links from find_links. :param project_urls: URLs to HTML project pages, as described by the PEP 503 simple repository API. """ self.files = files self.find_links = find_links self.project_urls = project_urls class LinkCollector(object): """ Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. """ def __init__( self, session, # type: PipSession search_scope, # type: SearchScope ): # type: (...) -> None self.search_scope = search_scope self.session = session @classmethod def create(cls, session, options, suppress_no_index=False): # type: (PipSession, Values, bool) -> LinkCollector """ :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. """ index_urls = [options.index_url] + options.extra_index_urls if options.no_index and not suppress_no_index: logger.debug( 'Ignoring indexes: %s', ','.join(redact_auth_from_url(url) for url in index_urls), ) index_urls = [] # Make sure find_links is a list before passing to create(). find_links = options.find_links or [] search_scope = SearchScope.create( find_links=find_links, index_urls=index_urls, ) link_collector = LinkCollector( session=session, search_scope=search_scope, ) return link_collector @property def find_links(self): # type: () -> List[str] return self.search_scope.find_links def fetch_page(self, location): # type: (Link) -> Optional[HTMLPage] """ Fetch an HTML page containing package links. """ return _get_html_page(location, session=self.session) def collect_links(self, project_name): # type: (str) -> CollectedLinks """Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. """ search_scope = self.search_scope index_locations = search_scope.get_index_urls_locations(project_name) index_file_loc, index_url_loc = group_locations(index_locations) fl_file_loc, fl_url_loc = group_locations( self.find_links, expand_dir=True, ) file_links = [ Link(url) for url in itertools.chain(index_file_loc, fl_file_loc) ] # We trust every directly linked archive in find_links find_link_links = [Link(url, '-f') for url in self.find_links] # We trust every url that the user has given us whether it was given # via --index-url or --find-links. # We want to filter out anything that does not have a secure origin. url_locations = [ link for link in itertools.chain( # Mark PyPI indices as "cache_link_parsing == False" -- this # will avoid caching the result of parsing the page for links. (Link(url, cache_link_parsing=False) for url in index_url_loc), (Link(url) for url in fl_url_loc), ) if self.session.is_secure_origin(link) ] url_locations = _remove_duplicate_links(url_locations) lines = [ '{} location(s) to search for versions of {}:'.format( len(url_locations), project_name, ), ] for link in url_locations: lines.append('* {}'.format(link)) logger.debug('\n'.join(lines)) return CollectedLinks( files=file_links, find_links=find_link_links, project_urls=url_locations, ) index/__pycache__/package_finder.cpython-37.pyc000064400000062404152352421750015450 0ustar00B ReB@s@dZddlmZddlZddlZddlmZddlmZddl m Z ddl m Z mZmZmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddl-m.Z.e*rddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7ddl8m9Z9ddl m:Z:ddlm;Z;ddlm?Z?ddl@mAZAe7e6de6eBeCffZDe6eBeBeBe:eDe3eBfZEdd d!gZFeGeHZId3d#d$ZJGd%d&d&eKZLd'd(ZMGd)d*d*eKZNGd+d d eKZOGd,d-d-eKZPGd.d!d!eKZQd/d0ZRd1d2ZSdS)4z!Routines related to PyPI, indexes)absolute_importN) specifiers)canonicalize_name)parse)BestVersionAlreadyInstalledDistributionNotFoundInvalidWheelFilenameUnsupportedWheel) parse_links)InstallationCandidate) FormatControl)Link)SelectionPreferences) TargetPython)Wheel) lru_cache)WHEEL_EXTENSION) indent_log) build_netloc)check_requires_python)MYPY_CHECK_RUNNING)SUPPORTED_EXTENSIONS) url_to_path) FrozenSetIterableListOptionalSetTextTupleUnion)Tag) _BaseVersion) LinkCollector) SearchScope)InstallRequirement)Hashesr BestCandidateResult PackageFinderFcCs~yt|j|d}Wn&tjk r8td|j|YnBX|szdtt|}|shtd||j|dStd||j|dS)aa Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. ) version_infoz2Ignoring invalid Requires-Python (%r) for link: %s.z4Link requires a different Python (%s not in: %r): %sFzBIgnoring failed Requires-Python check (%s not in: %r) for link: %sT) rrequires_pythonrInvalidSpecifierloggerdebugjoinmapstr)linkr*ignore_requires_python is_compatibleversionr'r'/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/index/package_finder.py_check_link_requires_python>s$  r8c@s,eZdZdZedZdddZddZdS) LinkEvaluatorzD Responsible for evaluating links for a particular project. z-py([123]\.?[0-9]?)$NcCs4|dkr d}||_||_||_||_||_||_dS)a :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. NF) _allow_yanked_canonical_name_ignore_requires_python_formats_target_python project_name)selfr?canonical_nameformats target_python allow_yankedr4r'r'r7__init__uszLinkEvaluator.__init__c Csd}|jr(|js(|jpd}dd|fS|jr<|j}|j}n|\}}|sPdS|tkrfdd|fSd|jkr|t krd|j }d|fSd |j kr|d krd S|t kr0yt |j }Wntk rd SXt|j|jkrd |j }d|fS|j}||s*|}dd|}d|fS|j}d|jkrZ|t krZd|j }d|fS|slt||j}|sd|j }d|fS|j|} | r|d| }| d} | |jjkrdSt||jj|j d} | sdSt!"d||d|fS)aG Determine whether a link is a candidate for installation. :return: A tuple (is_candidate, result), where `result` is (1) a version string if `is_candidate` is True, and (2) if `is_candidate` is False, an optional string to log the reason the link fails to qualify. Nz Fzyanked for reason: {})Fz not a filezunsupported archive format: {}binaryzNo binaries permitted for {}macosx10z.zip)Fz macosx10 one)Fzinvalid wheel filenamezwrong project name (not {})z"none of the wheel's tags match: {}z, sourcezNo sources permitted for {}zMissing project version for {})FzPython version is incorrect)r*r4)FNzFound link %s, version: %sT)# is_yankedr: yanked_reasonformat egg_fragmentextsplitextrr=rr?pathrfilenamerrnamer;r>get_tags supportedget_formatted_file_tagsr0r6_extract_version_from_fragment_py_version_researchstartgroup py_versionr8py_version_infor<r.r/) r@r3r6reasonegg_inforNwheelsupported_tags file_tagsmatchr[supports_pythonr'r'r7 evaluate_linksp              zLinkEvaluator.evaluate_link)N) __name__ __module__ __qualname____doc__recompilerWrErdr'r'r'r7r9is r9c Cs|stdt||t|Sg}g}d}xF|D]>}|j}|jsBn"|j|drX|d7}n ||q0||q0W|r||}nt|}t|t|krd} n dt|d dd |D} td t|||j |t||| |S) a Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). zJGiven no hashes to check %s links for project %r: discarding no candidatesr)hashesrIzdiscarding no candidateszdiscarding {} non-matches: {}z css|]}t|jVqdS)N)r2r3).0 candidater'r'r7 0sz*filter_unallowed_hashes..zPChecked %s links for project %r against %s hashes (%s matches, %s no digest): %s) r.r/lenlistr3has_hashis_hash_allowedappendrLr0 digest_count) candidatesrkr?matches_or_no_digest non_matches match_countrmr3filtereddiscard_messager'r'r7filter_unallowed_hashessF     r{c@seZdZdZdddZdS)CandidatePreferenceszk Encapsulates some of the preferences for filtering and sorting InstallationCandidate objects. FcCs||_||_dS)zR :param allow_all_prereleases: Whether to allow all pre-releases. N)allow_all_prereleases prefer_binary)r@r~r}r'r'r7rEHs zCandidatePreferences.__init__N)FF)rerfrgrhrEr'r'r'r7r|Asr|c@s(eZdZdZddZddZddZdS) r(zA collection of candidates, returned by `PackageFinder.find_best_candidate`. This class is only intended to be instantiated by CandidateEvaluator's `compute_best_candidate()` method. cCsHt|t|kst|dkr&|r2tn ||ks2t||_||_||_dS)a :param candidates: A sequence of all available candidates found. :param applicable_candidates: The applicable candidates. :param best_candidate: The most preferred candidate found, or None if no applicable candidates were found. N)setAssertionError_applicable_candidates _candidatesbest_candidate)r@ruapplicable_candidatesrr'r'r7rE\s   zBestCandidateResult.__init__cCs t|jS)z(Iterate through all candidates. )iterr)r@r'r'r7iter_alluszBestCandidateResult.iter_allcCs t|jS)z3Iterate through the applicable candidates. )rr)r@r'r'r7iter_applicable{sz#BestCandidateResult.iter_applicableN)rerfrgrhrErrr'r'r'r7r(Usc@sHeZdZdZedddZdddZdd Zd d Zd d Z ddZ dS)CandidateEvaluatorzm Responsible for filtering and sorting candidates for installation based on what tags are valid. NFcCs:|dkrt}|dkrt}|}|||||||dS)aCreate a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :param hashes: An optional collection of allowed hashes. N)r?r` specifierr~r}rk)rr SpecifierSetrS)clsr?rCr~r}rrkr`r'r'r7createszCandidateEvaluator.createcCs(||_||_||_||_||_||_dS)z :param supported_tags: The PEP 425 tags supported by the target Python in order of preference (most preferred first). N)_allow_all_prereleases_hashes_prefer_binary _project_name _specifier_supported_tags)r@r?r`rr~r}rkr'r'r7rEs zCandidateEvaluator.__init__csd|jpd}|j}dd|jdd|D|dDfdd|D}t||j|jd }t||jd S) zM Return the applicable candidates from a list of candidates. NcSsh|] }t|qSr')r2)rlvr'r'r7 sz?CandidateEvaluator.get_applicable_candidates..css|]}t|jVqdS)N)r2r6)rlcr'r'r7rnsz?CandidateEvaluator.get_applicable_candidates..) prereleasescsg|]}t|jkr|qSr')r2r6)rlr)versionsr'r7 sz@CandidateEvaluator.get_applicable_candidates..)rurkr?)key)rrfilterr{rrsorted _sort_key)r@ruallow_prereleasesrrfiltered_applicable_candidatesr')rr7get_applicable_candidatess    z,CandidateEvaluator.get_applicable_candidatesc Cs|j}t|}d}d}|j}|jrt|j}||sFtd|j|j rPd}| | }|j dk rt d|j } | } t| d| df}n| }t||j} dt|j} | | ||j||fS)a) Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal r'rzB{} is not a supported wheel for this platform. It can't be sorted.rINz ^(\d+)(.*)$)rror3is_wheelrrQrTr rLrsupport_index_min build_tagrirbgroupsintrrrrJr6) r@rm valid_tags support_numrbinary_preferencer3r_prirbbuild_tag_groupshas_allowed_hash yank_valuer'r'r7rs.      zCandidateEvaluator._sort_keycCs|sdSt||jd}|S)zy Return the best candidate per the instance's sort order, or None if no candidate is acceptable. N)r)maxr)r@rurr'r'r7sort_best_candidate%s z&CandidateEvaluator.sort_best_candidatecCs"||}||}t|||dS)zF Compute and return a `BestCandidateResult` instance. )rr)rrr()r@rurrr'r'r7compute_best_candidate3s   z)CandidateEvaluator.compute_best_candidate)NFFNN)FFN) rerfrgrh classmethodrrErrrrr'r'r'r7rs " &<rc@seZdZdZd/ddZed0ddZeddZed d Z e j d d Z ed d Z eddZ eddZ eddZddZeddZddZddZddZddZd d!Zd"d#Zd$d%Zedd&d'd(Zd1d)d*Zd2d+d,Zd-d.ZdS)3r)zThis finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. NcCsP|dkrt}|pttt}||_||_||_||_||_||_t|_ dS)a This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. N) r|r rr:_candidate_prefsr<_link_collectorr>format_control _logged_links)r@link_collectorrCrDrcandidate_prefsr4r'r'r7rEMszPackageFinder.__init__cCs8|dkrt}t|j|jd}|||||j|j|jdS)afCreate a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. N)r~r})rrrCrDrr4)rr|r~r}rDrr4)rrselection_prefsrCrr'r'r7rus zPackageFinder.createcCs|jS)N)r>)r@r'r'r7rCszPackageFinder.target_pythoncCs|jjS)N)r search_scope)r@r'r'r7rszPackageFinder.search_scopecCs ||j_dS)N)rr)r@rr'r'r7rscCs|jjS)N)r find_links)r@r'r'r7rszPackageFinder.find_linkscCs|jjS)N)r index_urls)r@r'r'r7rszPackageFinder.index_urlsccs"x|jjjD]}t|Vq WdS)N)rsessionpip_trusted_originsr)r@ host_portr'r'r7 trusted_hostsszPackageFinder.trusted_hostscCs|jjS)N)rr})r@r'r'r7r}sz#PackageFinder.allow_all_prereleasescCs d|j_dS)NT)rr})r@r'r'r7set_allow_all_prereleasessz'PackageFinder.set_allow_all_prereleasescCs|jjS)N)rr~)r@r'r'r7r~szPackageFinder.prefer_binarycCs d|j_dS)NT)rr~)r@r'r'r7set_prefer_binaryszPackageFinder.set_prefer_binarycCs.t|}|j|}t||||j|j|jdS)N)r?rArBrCrDr4)rrget_allowed_formatsr9r>r:r<)r@r?rArBr'r'r7make_link_evaluators z!PackageFinder.make_link_evaluatorcCsTgg}}t}x:|D]2}||kr|||jr>||q||qW||S)z Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates )raddrMrs)r@linkseggsno_eggsseenr3r'r'r7 _sort_linkss    zPackageFinder._sort_linkscCs(||jkr$td|||j|dS)NzSkipping link: %s: %s)rr.r/r)r@r3r]r'r'r7_log_skipped_links zPackageFinder._log_skipped_linkcCs<||\}}|s(|r$|j||ddSt|j|t|dS)z If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. )r]N)rRr3r6)rdrr r?r2)r@link_evaluatorr3 is_candidateresultr'r'r7get_install_candidatesz#PackageFinder.get_install_candidatecCs:g}x0||D]"}|||}|dk r||qW|S)zU Convert links that are candidates to InstallationCandidate objects. N)rrrs)r@rrrur3rmr'r'r7evaluate_linkss  zPackageFinder.evaluate_linksc CsTtd||j|}|dkr$gStt|}t|j||d}WdQRX|S)Nz-Fetching project page and analyzing links: %s)r)r.r/r fetch_pagerpr rr)r@ project_urlr html_page page_links package_linksr'r'r7process_project_urls  z!PackageFinder.process_project_url)maxsizec Cs|j|}||}|j||jd}g}x&|jD]}|j||d}||q2W|j||jd}|r|j ddt dd dd|D|||S) aFind all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. )r)rT)reversezLocal files found: %sz, cSsg|]}t|jjqSr')rr3url)rlrmr'r'r7rIsz5PackageFinder.find_all_candidates..) r collect_linksrrr project_urlsrextendfilessortr.r/r0) r@r?collected_linksrfind_links_versions page_versionsrr file_versionsr'r'r7find_all_candidates%s*        z!PackageFinder.find_all_candidatescCs"|j}tj||j|j|j||dS)z3Create a CandidateEvaluator object to use. )r?rCr~r}rrk)rrrr>r~r})r@r?rrkrr'r'r7make_candidate_evaluatorQs z&PackageFinder.make_candidate_evaluatorcCs$||}|j|||d}||S)aFind matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. )r?rrk)rrr)r@r?rrkrucandidate_evaluatorr'r'r7find_best_candidateds  z!PackageFinder.find_best_candidatec Cs|jdd}|j|j|j|d}|j}d}|jdk r@t|jj}dd}|dkr||dkr|t d||| t d |d}|r|dks|j|krd }|s|dk r|rt d |nt d ||jdS|rt d |||tt d |j|||S)zTry to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise F)trust_internet)rrkNcSs dtdd|DtdpdS)Nz, cSsh|]}t|jqSr')r2r6)rlrr'r'r7rszKPackageFinder.find_requirement.._format_versions..)rnone)r0r parse_version) cand_iterr'r'r7_format_versionss  z8PackageFinder.find_requirement.._format_versionszNCould not find a version that satisfies the requirement %s (from versions: %s)z%No matching distribution found for {}TzLExisting installed version (%s) is most up-to-date and satisfies requirementzUExisting installed version (%s) satisfies requirement (most up-to-date version is %s)z=Installed version (%s) is most up-to-date (past versions: %s)z)Using version %s (newest of versions: %s))rkrrRrr satisfied_byrr6r.criticalrrrLr/rr) r@requpgraderkbest_candidate_resultrinstalled_versionrbest_installedr'r'r7find_requirement{sT      zPackageFinder.find_requirement)NNN)N)NN)NN)rerfrgrhrErrpropertyrCrsetterrrrr}rr~rrrrrrrrrrrrr'r'r'r7r)Fs8 !          /  cCsLx6t|D]*\}}|dkrq t|d||kr |Sq Wtd||dS)aFind the separator's index based on the package's canonical name. :param fragment: A + filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 -Nz{} does not match {}) enumerater ValueErrorrL)fragmentrAirr'r'r7_find_name_version_seps rcCs@yt||d}Wntk r&dSX||d}|s+ filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. rIN)rr)rrA version_startr6r'r'r7rVs  rV)F)Trh __future__rloggingriZpip._vendor.packagingrZpip._vendor.packaging.utilsrpip._vendor.packaging.versionrrpip._internal.exceptionsrrrr pip._internal.index.collectorr pip._internal.models.candidater #pip._internal.models.format_controlr pip._internal.models.linkr $pip._internal.models.selection_prefsr"pip._internal.models.target_pythonrpip._internal.models.wheelrpip._internal.utils.compatrpip._internal.utils.filetypesrpip._internal.utils.loggingrpip._internal.utils.miscrpip._internal.utils.packagingrpip._internal.utils.typingrpip._internal.utils.unpackingrpip._internal.utils.urlsrtypingrrrrrrrr pip._vendor.packaging.tagsr!r"r#!pip._internal.models.search_scoper$Zpip._internal.reqr%pip._internal.utils.hashesr&rr2ZBuildTagZCandidateSortingKey__all__ getLoggerrer.r8objectr9r{r|r(rr)rrVr'r'r'r7s`                   (         (K-E index/__pycache__/collector.cpython-37.pyc000064400000042735152352421750014521 0ustar00B Re@W@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z ddl mZddlmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lm Z ddl!m"Z"ddl#m$Z$m%Z%ddl&m'Z'ddl(m)Z)m*Z*ddl+m,Z,m-Z-e'rddl.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9Z:ddl;mZ>e:j?j@jAZBe4eCeCfZDeEeFZGddZHddZIGdddeJZKddZLGdd d eJZMd!d"ZNd#d$ZOd%d&ZPd'd(ZQd)d*ZRd+d,ZSeTd-ejUZVd.d/ZWd0d1ZXd2d3ZYGd4d5d5eZZ[d6d7Z\e\d8d9Z]Gd:d;d;eZZ^dLdhttpshttpT)allow_redirectsN) urllib_parseurlsplitr@headr r?)r&sessionr'netlocpathqueryfragmentrespr(r(r)_ensure_html_responsefs rMcCsLt|rt||dtdt||j|dddd}t|t||S)aAccess an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. )rGzGetting page %sz text/htmlz max-age=0)Acceptz Cache-Control)r;)r.rMloggerdebugrr<r r?)r&rGrLr(r(r)_get_html_responsews  rQcCs2|r.d|kr.t|d\}}d|kr.|dSdS)zBDetermine if we have any encoding information in our headers. z Content-TypecharsetN)cgi parse_header)r;r2paramsr(r(r)_get_encoding_from_headerss  rVcCs.x(|dD]}|d}|dk r |Sq W|S)aDetermine the HTML document's base URL. This looks for a ```` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :param document: An HTML document representation. The current implementation expects the result of ``html5lib.parse()``. :param page_url: The URL of the HTML document. z.//basehrefN)findallr<)documentpage_urlbaserWr(r(r)_determine_base_urls  r\cCstt|S)zP Clean a "part" of a URL path (i.e. after splitting on "@" characters). )rDquoteunquote)partr(r(r)_clean_url_path_partsr`cCstt|S)z Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "@" characters). )urllib_request pathname2url url2pathname)r_r(r(r)_clean_file_url_paths rdz(@|%2F)cCsb|r t}nt}t|}g}x:tt|dgD]$\}}|||||q0Wd |S)z* Clean the path portion of a URL. r:) rdr`_reserved_chars_resplitr itertoolschainappendupperjoin)rI is_local_path clean_funcparts cleaned_partsto_cleanreservedr(r(r)_clean_url_paths rrcCs2t|}|j }t|j|d}t|j|dS)z Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters. )rl)rI)rDurlparserHrrrI urlunparse_replace)r&resultrlrIr(r(r) _clean_links rwcCsf|d}|sdStt||}|d}|r8t|nd}|d}|rRt|}t||||d}|S)zJ Convert an anchor element in a simple repository page to a Link. rWNzdata-requires-pythonz data-yanked) comes_fromrequires_python yanked_reason)r<rwrDurljoinrr )anchorrZbase_urlrWr& pyrequirerzlinkr(r(r)_create_link_from_element s   rc@s$eZdZddZddZddZdS)CacheablePageContentcCs|js t||_dS)N)cache_link_parsingAssertionErrorpage)r4rr(r(r)r1,s zCacheablePageContent.__init__cCst|t|o|jj|jjkS)N) isinstancetyperr&)r4otherr(r(r)__eq__1szCacheablePageContent.__eq__cCs t|jjS)N)hashrr&)r4r(r(r)__hash__6szCacheablePageContent.__hash__N)r6r7r8r1rrr(r(r(r)r+srcs2tddfddtfdd}|S)z Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`. N)maxsizecst|jS)N)listr)cacheable_page)fnr(r)wrapperEsz'with_cached_html_pages..wrappercs|jrt|St|S)N)rrr)r)rrr(r)wrapper_wrapperJs z/with_cached_html_pages..wrapper_wrapper)r functoolswraps)rrr()rrr)with_cached_html_pages;s rccsZtj|j|jdd}|j}t||}x0|dD]"}t|||d}|dkrLq0|Vq0WdS)zP Parse an HTML document, and yield its anchor elements as Link objects. F)transport_encodingnamespaceHTMLElementsz.//a)rZr}N)rrcontentencodingr&r\rXr)rrYr&r}r|rr(r(r) parse_linksTs rc@s"eZdZdZdddZddZdS) HTMLPagez'Represents one page, along with its URLTcCs||_||_||_||_dS)am :param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. :param cache_link_parsing: whether links parsed from this page's url should be cached. PyPI index urls should have this set to False, for example. N)rrr&r)r4rrr&rr(r(r)r1pszHTMLPage.__init__cCs t|jS)N)rr&)r4r(r(r)__str__szHTMLPage.__str__N)T)r6r7r8__doc__r1rr(r(r(r)rms rcCs|dkrtj}|d||dS)Nz%Could not fetch URL %s: %s - skipping)rOrP)rreasonmethr(r(r)_handle_get_page_failsrTcCst|j}t|j||j|dS)N)rr&r)rVr;rrr&)r>rrr(r(r)_make_html_pages  rc Cs|dkrtd|jddd}t|}|r@td||dSt|\}}}}}}|dkrtj t |r| ds|d7}t|d}td |yt||d }WnFtk rtd |Yn4tk r}ztd ||j|jWdd}~XYntk r0}zt||Wdd}~XYntk r\}zt||Wdd}~XYntk r}z$d } | t|7} t|| tjdWdd}~XYndtjk r}zt|d|Wdd}~XYn0tjk rt|dYnXt||j dSdS)Nz?_get_html_page() missing 1 required keyword argument: 'session'#rzICannot look at %s URL %s because it does not support lookup as web pages.file/z index.htmlz# file: URL is directory, getting %s)rGz`Skipping page %s because it looks like an archive, and cannot be checked by a HTTP HEAD request.ziSkipping page %s because the %s request got Content-Type: %s.The only supported Content-Type is text/htmlz4There was a problem confirming the ssl certificate: )rzconnection error: {}z timed out)r)! TypeErrorr&rfr*rOwarningrDrsosrIisdirrarcr,r{rPrQr@r/r3r2r rrrstrinforConnectionErrorformatTimeoutrr) rrGr& vcs_schemer'_rIrLexcrr(r(r)_get_html_pagesP        rcCstt|S)zQ Return a list of links, with duplicates removed and ordering preserved. )rrfromkeys)linksr(r(r)_remove_duplicate_linkssrFcsggfdd}x|D]}tj|}|d}|s>|r|rH|}nt|}tj|r|rtj|}xBt|D]}|tj||qxWq|r |qt d|qtj |r||qt d|qt |r |qt d|qWfS)z Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). cs8t|}tj|ddddkr*|n |dS)NF)strictrz text/html)r mimetypes guess_typeri)rIr&)filesurlsr(r) sort_paths z"group_locations..sort_pathzfile:z(Path '%s' is ignored: it is a directory.z:Url '%s' is ignored: it is neither a file nor a directory.zQUrl '%s' is ignored. It is either a non-existing path or lacks a specific scheme.)rrIexistsr$rrrealpathlistdirrkrirOrisfiler) locations expand_dirrr&rl is_file_urlrIitemr()rrr)group_locationss<           rc@seZdZdZddZdS)CollectedLinksa Encapsulates the return value of a call to LinkCollector.collect_links(). The return value includes both URLs to project pages containing package links, as well as individual package Link objects collected from other sources. This info is stored separately as: (1) links from the configured file locations, (2) links from the configured find_links, and (3) urls to HTML project pages, as described by the PEP 503 simple repository API. cCs||_||_||_dS)z :param files: Links from file locations. :param find_links: Links from find_links. :param project_urls: URLs to HTML project pages, as described by the PEP 503 simple repository API. N)r find_links project_urls)r4rrrr(r(r)r1,s zCollectedLinks.__init__N)r6r7r8rr1r(r(r(r)rsrc@sBeZdZdZddZedddZeddZd d Z d d Z d S) LinkCollectorz Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_links() method. cCs||_||_dS)N) search_scoperG)r4rGrr(r(r)r1GszLinkCollector.__init__FcCs`|jg|j}|jr8|s8tdddd|Dg}|jp@g}tj||d}t ||d}|S)z :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object. zIgnoring indexes: %s,css|]}t|VqdS)N)r).0r&r(r(r) \sz'LinkCollector.create..)r index_urls)rGr) index_urlextra_index_urlsno_indexrOrPrkrr creater)clsrGoptionssuppress_no_indexrrrlink_collectorr(r(r)rPs    zLinkCollector.createcCs|jjS)N)rr)r4r(r(r)rkszLinkCollector.find_linkscCst||jdS)z> Fetch an HTML page containing package links. )rG)rrG)r4locationr(r(r) fetch_pagepszLinkCollector.fetch_pagec sj}||}t|\}}tjdd\}}ddt||D}ddjD} fddtdd|Dd d|DD} t| } d t| |g} x| D]} | d | qWt d | t || | d S)zFind all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. T)rcSsg|] }t|qSr()r )rr&r(r(r) sz/LinkCollector.collect_links..cSsg|]}t|dqS)z-f)r )rr&r(r(r)rscsg|]}j|r|qSr()rGis_secure_origin)rr)r4r(r)rscss|]}t|ddVqdS)F)rN)r )rr&r(r(r)rsz.LinkCollector.collect_links..css|]}t|VqdS)N)r )rr&r(r(r)rsz,{} location(s) to search for versions of {}:z* {} )rrr)rget_index_urls_locationsrrrgrhrrr%rirOrPrkr) r4 project_namerindex_locationsindex_file_loc index_url_loc fl_file_loc fl_url_loc file_linksfind_link_links url_locationslinesrr()r4r) collect_linksws(    zLinkCollector.collect_linksN)F) r6r7r8rr1 classmethodrpropertyrrrr(r(r(r)r>s   r)N)T)N)F)frrSrrgloggingrrre collectionsr pip._vendorrrpip._vendor.distlib.compatrZpip._vendor.requests.exceptionsrrZpip._vendor.six.moves.urllibrrDr rapip._internal.exceptionsr pip._internal.models.linkr !pip._internal.models.search_scoper pip._internal.network.utilsr pip._internal.utils.compatrpip._internal.utils.filetypesrpip._internal.utils.miscrrpip._internal.utils.typingrpip._internal.utils.urlsrrpip._internal.vcsrroptparsertypingrrrrrrrrxml.etree.ElementTreexmlZpip._vendor.requestsr pip._internal.network.sessionr!etree ElementTreeElementZ HTMLElementrZResponseHeaders getLoggerr6rOr*r. Exceptionr/r?r@rMrQrVr\r`rdcompile IGNORECASErerrrwrobjectrrrrrrrrrrrr(r(r(r)st            (         3      9 ;#index/__pycache__/__init__.cpython-37.pyc000064400000000405152352421750014256 0ustar00B Re@sdZdS)zIndex interaction code N)__doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/index/__init__.pyindex/package_finder.py000064400000111102152352421750011151 0ustar00"""Routines related to PyPI, indexes""" # The following comment should be removed at some point in the future. # mypy: strict-optional=False from __future__ import absolute_import import logging import re from pip._vendor.packaging import specifiers from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.packaging.version import parse as parse_version from pip._internal.exceptions import ( BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.index.collector import parse_links from pip._internal.models.candidate import InstallationCandidate from pip._internal.models.format_control import FormatControl from pip._internal.models.link import Link from pip._internal.models.selection_prefs import SelectionPreferences from pip._internal.models.target_python import TargetPython from pip._internal.models.wheel import Wheel from pip._internal.utils.compat import lru_cache from pip._internal.utils.filetypes import WHEEL_EXTENSION from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import build_netloc from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS from pip._internal.utils.urls import url_to_path if MYPY_CHECK_RUNNING: from typing import ( FrozenSet, Iterable, List, Optional, Set, Text, Tuple, Union, ) from pip._vendor.packaging.tags import Tag from pip._vendor.packaging.version import _BaseVersion from pip._internal.index.collector import LinkCollector from pip._internal.models.search_scope import SearchScope from pip._internal.req import InstallRequirement from pip._internal.utils.hashes import Hashes BuildTag = Union[Tuple[()], Tuple[int, str]] CandidateSortingKey = ( Tuple[int, int, int, _BaseVersion, BuildTag, Optional[int]] ) __all__ = ['FormatControl', 'BestCandidateResult', 'PackageFinder'] logger = logging.getLogger(__name__) def _check_link_requires_python( link, # type: Link version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> bool """ Return whether the given Python version is compatible with a link's "Requires-Python" value. :param version_info: A 3-tuple of ints representing the Python major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. """ try: is_compatible = check_requires_python( link.requires_python, version_info=version_info, ) except specifiers.InvalidSpecifier: logger.debug( "Ignoring invalid Requires-Python (%r) for link: %s", link.requires_python, link, ) else: if not is_compatible: version = '.'.join(map(str, version_info)) if not ignore_requires_python: logger.debug( 'Link requires a different Python (%s not in: %r): %s', version, link.requires_python, link, ) return False logger.debug( 'Ignoring failed Requires-Python check (%s not in: %r) ' 'for link: %s', version, link.requires_python, link, ) return True class LinkEvaluator(object): """ Responsible for evaluating links for a particular project. """ _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$') # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def __init__( self, project_name, # type: str canonical_name, # type: str formats, # type: FrozenSet[str] target_python, # type: TargetPython allow_yanked, # type: bool ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. """ if ignore_requires_python is None: ignore_requires_python = False self._allow_yanked = allow_yanked self._canonical_name = canonical_name self._ignore_requires_python = ignore_requires_python self._formats = formats self._target_python = target_python self.project_name = project_name def evaluate_link(self, link): # type: (Link) -> Tuple[bool, Optional[Text]] """ Determine whether a link is a candidate for installation. :return: A tuple (is_candidate, result), where `result` is (1) a version string if `is_candidate` is True, and (2) if `is_candidate` is False, an optional string to log the reason the link fails to qualify. """ version = None if link.is_yanked and not self._allow_yanked: reason = link.yanked_reason or '' # Mark this as a unicode string to prevent "UnicodeEncodeError: # 'ascii' codec can't encode character" in Python 2 when # the reason contains non-ascii characters. return (False, u'yanked for reason: {}'.format(reason)) if link.egg_fragment: egg_info = link.egg_fragment ext = link.ext else: egg_info, ext = link.splitext() if not ext: return (False, 'not a file') if ext not in SUPPORTED_EXTENSIONS: return (False, 'unsupported archive format: {}'.format(ext)) if "binary" not in self._formats and ext == WHEEL_EXTENSION: reason = 'No binaries permitted for {}'.format( self.project_name) return (False, reason) if "macosx10" in link.path and ext == '.zip': return (False, 'macosx10 one') if ext == WHEEL_EXTENSION: try: wheel = Wheel(link.filename) except InvalidWheelFilename: return (False, 'invalid wheel filename') if canonicalize_name(wheel.name) != self._canonical_name: reason = 'wrong project name (not {})'.format( self.project_name) return (False, reason) supported_tags = self._target_python.get_tags() if not wheel.supported(supported_tags): # Include the wheel's tags in the reason string to # simplify troubleshooting compatibility issues. file_tags = wheel.get_formatted_file_tags() reason = ( "none of the wheel's tags match: {}".format( ', '.join(file_tags) ) ) return (False, reason) version = wheel.version # This should be up by the self.ok_binary check, but see issue 2700. if "source" not in self._formats and ext != WHEEL_EXTENSION: reason = 'No sources permitted for {}'.format(self.project_name) return (False, reason) if not version: version = _extract_version_from_fragment( egg_info, self._canonical_name, ) if not version: reason = 'Missing project version for {}'.format(self.project_name) return (False, reason) match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != self._target_python.py_version: return (False, 'Python version is incorrect') supports_python = _check_link_requires_python( link, version_info=self._target_python.py_version_info, ignore_requires_python=self._ignore_requires_python, ) if not supports_python: # Return None for the reason text to suppress calling # _log_skipped_link(). return (False, None) logger.debug('Found link %s, version: %s', link, version) return (True, version) def filter_unallowed_hashes( candidates, # type: List[InstallationCandidate] hashes, # type: Hashes project_name, # type: str ): # type: (...) -> List[InstallationCandidate] """ Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). """ if not hashes: logger.debug( 'Given no hashes to check %s links for project %r: ' 'discarding no candidates', len(candidates), project_name, ) # Make sure we're not returning back the given value. return list(candidates) matches_or_no_digest = [] # Collect the non-matches for logging purposes. non_matches = [] match_count = 0 for candidate in candidates: link = candidate.link if not link.has_hash: pass elif link.is_hash_allowed(hashes=hashes): match_count += 1 else: non_matches.append(candidate) continue matches_or_no_digest.append(candidate) if match_count: filtered = matches_or_no_digest else: # Make sure we're not returning back the given value. filtered = list(candidates) if len(filtered) == len(candidates): discard_message = 'discarding no candidates' else: discard_message = 'discarding {} non-matches:\n {}'.format( len(non_matches), '\n '.join(str(candidate.link) for candidate in non_matches) ) logger.debug( 'Checked %s links for project %r against %s hashes ' '(%s matches, %s no digest): %s', len(candidates), project_name, hashes.digest_count, match_count, len(matches_or_no_digest) - match_count, discard_message ) return filtered class CandidatePreferences(object): """ Encapsulates some of the preferences for filtering and sorting InstallationCandidate objects. """ def __init__( self, prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool ): # type: (...) -> None """ :param allow_all_prereleases: Whether to allow all pre-releases. """ self.allow_all_prereleases = allow_all_prereleases self.prefer_binary = prefer_binary class BestCandidateResult(object): """A collection of candidates, returned by `PackageFinder.find_best_candidate`. This class is only intended to be instantiated by CandidateEvaluator's `compute_best_candidate()` method. """ def __init__( self, candidates, # type: List[InstallationCandidate] applicable_candidates, # type: List[InstallationCandidate] best_candidate, # type: Optional[InstallationCandidate] ): # type: (...) -> None """ :param candidates: A sequence of all available candidates found. :param applicable_candidates: The applicable candidates. :param best_candidate: The most preferred candidate found, or None if no applicable candidates were found. """ assert set(applicable_candidates) <= set(candidates) if best_candidate is None: assert not applicable_candidates else: assert best_candidate in applicable_candidates self._applicable_candidates = applicable_candidates self._candidates = candidates self.best_candidate = best_candidate def iter_all(self): # type: () -> Iterable[InstallationCandidate] """Iterate through all candidates. """ return iter(self._candidates) def iter_applicable(self): # type: () -> Iterable[InstallationCandidate] """Iterate through the applicable candidates. """ return iter(self._applicable_candidates) class CandidateEvaluator(object): """ Responsible for filtering and sorting candidates for installation based on what tags are valid. """ @classmethod def create( cls, project_name, # type: str target_python=None, # type: Optional[TargetPython] prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> CandidateEvaluator """Create a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :param hashes: An optional collection of allowed hashes. """ if target_python is None: target_python = TargetPython() if specifier is None: specifier = specifiers.SpecifierSet() supported_tags = target_python.get_tags() return cls( project_name=project_name, supported_tags=supported_tags, specifier=specifier, prefer_binary=prefer_binary, allow_all_prereleases=allow_all_prereleases, hashes=hashes, ) def __init__( self, project_name, # type: str supported_tags, # type: List[Tag] specifier, # type: specifiers.BaseSpecifier prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool hashes=None, # type: Optional[Hashes] ): # type: (...) -> None """ :param supported_tags: The PEP 425 tags supported by the target Python in order of preference (most preferred first). """ self._allow_all_prereleases = allow_all_prereleases self._hashes = hashes self._prefer_binary = prefer_binary self._project_name = project_name self._specifier = specifier self._supported_tags = supported_tags def get_applicable_candidates( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> List[InstallationCandidate] """ Return the applicable candidates from a list of candidates. """ # Using None infers from the specifier instead. allow_prereleases = self._allow_all_prereleases or None specifier = self._specifier versions = { str(v) for v in specifier.filter( # We turn the version object into a str here because otherwise # when we're debundled but setuptools isn't, Python will see # packaging.version.Version and # pkg_resources._vendor.packaging.version.Version as different # types. This way we'll use a str as a common data interchange # format. If we stop using the pkg_resources provided specifier # and start using our own, we can drop the cast to str(). (str(c.version) for c in candidates), prereleases=allow_prereleases, ) } # Again, converting version to str to deal with debundling. applicable_candidates = [ c for c in candidates if str(c.version) in versions ] filtered_applicable_candidates = filter_unallowed_hashes( candidates=applicable_candidates, hashes=self._hashes, project_name=self._project_name, ) return sorted(filtered_applicable_candidates, key=self._sort_key) def _sort_key(self, candidate): # type: (InstallationCandidate) -> CandidateSortingKey """ Function to pass as the `key` argument to a call to sorted() to sort InstallationCandidates by preference. Returns a tuple such that tuples sorting as greater using Python's default comparison operator are more preferred. The preference is as follows: First and foremost, candidates with allowed (matching) hashes are always preferred over candidates without matching hashes. This is because e.g. if the only candidate with an allowed hash is yanked, we still want to use that candidate. Second, excepting hash considerations, candidates that have been yanked (in the sense of PEP 592) are always less preferred than candidates that haven't been yanked. Then: If not finding wheels, they are sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min(self._supported_tags) 3. source archives If prefer_binary was set, then all wheels are sorted above sources. Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal """ valid_tags = self._supported_tags support_num = len(valid_tags) build_tag = () # type: BuildTag binary_preference = 0 link = candidate.link if link.is_wheel: # can raise InvalidWheelFilename wheel = Wheel(link.filename) if not wheel.supported(valid_tags): raise UnsupportedWheel( "{} is not a supported wheel for this platform. It " "can't be sorted.".format(wheel.filename) ) if self._prefer_binary: binary_preference = 1 pri = -(wheel.support_index_min(valid_tags)) if wheel.build_tag is not None: match = re.match(r'^(\d+)(.*)$', wheel.build_tag) build_tag_groups = match.groups() build_tag = (int(build_tag_groups[0]), build_tag_groups[1]) else: # sdist pri = -(support_num) has_allowed_hash = int(link.is_hash_allowed(self._hashes)) yank_value = -1 * int(link.is_yanked) # -1 for yanked. return ( has_allowed_hash, yank_value, binary_preference, candidate.version, build_tag, pri, ) def sort_best_candidate( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> Optional[InstallationCandidate] """ Return the best candidate per the instance's sort order, or None if no candidate is acceptable. """ if not candidates: return None best_candidate = max(candidates, key=self._sort_key) return best_candidate def compute_best_candidate( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> BestCandidateResult """ Compute and return a `BestCandidateResult` instance. """ applicable_candidates = self.get_applicable_candidates(candidates) best_candidate = self.sort_best_candidate(applicable_candidates) return BestCandidateResult( candidates, applicable_candidates=applicable_candidates, best_candidate=best_candidate, ) class PackageFinder(object): """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector, # type: LinkCollector target_python, # type: TargetPython allow_yanked, # type: bool format_control=None, # type: Optional[FormatControl] candidate_prefs=None, # type: CandidatePreferences ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. """ if candidate_prefs is None: candidate_prefs = CandidatePreferences() format_control = format_control or FormatControl(set(), set()) self._allow_yanked = allow_yanked self._candidate_prefs = candidate_prefs self._ignore_requires_python = ignore_requires_python self._link_collector = link_collector self._target_python = target_python self.format_control = format_control # These are boring links that have already been logged somehow. self._logged_links = set() # type: Set[Link] # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. @classmethod def create( cls, link_collector, # type: LinkCollector selection_prefs, # type: SelectionPreferences target_python=None, # type: Optional[TargetPython] ): # type: (...) -> PackageFinder """Create a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. """ if target_python is None: target_python = TargetPython() candidate_prefs = CandidatePreferences( prefer_binary=selection_prefs.prefer_binary, allow_all_prereleases=selection_prefs.allow_all_prereleases, ) return cls( candidate_prefs=candidate_prefs, link_collector=link_collector, target_python=target_python, allow_yanked=selection_prefs.allow_yanked, format_control=selection_prefs.format_control, ignore_requires_python=selection_prefs.ignore_requires_python, ) @property def target_python(self): # type: () -> TargetPython return self._target_python @property def search_scope(self): # type: () -> SearchScope return self._link_collector.search_scope @search_scope.setter def search_scope(self, search_scope): # type: (SearchScope) -> None self._link_collector.search_scope = search_scope @property def find_links(self): # type: () -> List[str] return self._link_collector.find_links @property def index_urls(self): # type: () -> List[str] return self.search_scope.index_urls @property def trusted_hosts(self): # type: () -> Iterable[str] for host_port in self._link_collector.session.pip_trusted_origins: yield build_netloc(*host_port) @property def allow_all_prereleases(self): # type: () -> bool return self._candidate_prefs.allow_all_prereleases def set_allow_all_prereleases(self): # type: () -> None self._candidate_prefs.allow_all_prereleases = True @property def prefer_binary(self): # type: () -> bool return self._candidate_prefs.prefer_binary def set_prefer_binary(self): # type: () -> None self._candidate_prefs.prefer_binary = True def make_link_evaluator(self, project_name): # type: (str) -> LinkEvaluator canonical_name = canonicalize_name(project_name) formats = self.format_control.get_allowed_formats(canonical_name) return LinkEvaluator( project_name=project_name, canonical_name=canonical_name, formats=formats, target_python=self._target_python, allow_yanked=self._allow_yanked, ignore_requires_python=self._ignore_requires_python, ) def _sort_links(self, links): # type: (Iterable[Link]) -> List[Link] """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() # type: Set[Link] for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs def _log_skipped_link(self, link, reason): # type: (Link, Text) -> None if link not in self._logged_links: # Mark this as a unicode string to prevent "UnicodeEncodeError: # 'ascii' codec can't encode character" in Python 2 when # the reason contains non-ascii characters. # Also, put the link at the end so the reason is more visible # and because the link string is usually very long. logger.debug(u'Skipping link: %s: %s', reason, link) self._logged_links.add(link) def get_install_candidate(self, link_evaluator, link): # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate] """ If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. """ is_candidate, result = link_evaluator.evaluate_link(link) if not is_candidate: if result: self._log_skipped_link(link, reason=result) return None return InstallationCandidate( name=link_evaluator.project_name, link=link, # Convert the Text result to str since InstallationCandidate # accepts str. version=str(result), ) def evaluate_links(self, link_evaluator, links): # type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate] """ Convert links that are candidates to InstallationCandidate objects. """ candidates = [] for link in self._sort_links(links): candidate = self.get_install_candidate(link_evaluator, link) if candidate is not None: candidates.append(candidate) return candidates def process_project_url(self, project_url, link_evaluator): # type: (Link, LinkEvaluator) -> List[InstallationCandidate] logger.debug( 'Fetching project page and analyzing links: %s', project_url, ) html_page = self._link_collector.fetch_page(project_url) if html_page is None: return [] page_links = list(parse_links(html_page)) with indent_log(): package_links = self.evaluate_links( link_evaluator, links=page_links, ) return package_links @lru_cache(maxsize=None) def find_all_candidates(self, project_name): # type: (str) -> List[InstallationCandidate] """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. """ collected_links = self._link_collector.collect_links(project_name) link_evaluator = self.make_link_evaluator(project_name) find_links_versions = self.evaluate_links( link_evaluator, links=collected_links.find_links, ) page_versions = [] for project_url in collected_links.project_urls: package_links = self.process_project_url( project_url, link_evaluator=link_evaluator, ) page_versions.extend(package_links) file_versions = self.evaluate_links( link_evaluator, links=collected_links.files, ) if file_versions: file_versions.sort(reverse=True) logger.debug( 'Local files found: %s', ', '.join([ url_to_path(candidate.link.url) for candidate in file_versions ]) ) # This is an intentional priority ordering return file_versions + find_links_versions + page_versions def make_candidate_evaluator( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> CandidateEvaluator """Create a CandidateEvaluator object to use. """ candidate_prefs = self._candidate_prefs return CandidateEvaluator.create( project_name=project_name, target_python=self._target_python, prefer_binary=candidate_prefs.prefer_binary, allow_all_prereleases=candidate_prefs.allow_all_prereleases, specifier=specifier, hashes=hashes, ) def find_best_candidate( self, project_name, # type: str specifier=None, # type: Optional[specifiers.BaseSpecifier] hashes=None, # type: Optional[Hashes] ): # type: (...) -> BestCandidateResult """Find matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. """ candidates = self.find_all_candidates(project_name) candidate_evaluator = self.make_candidate_evaluator( project_name=project_name, specifier=specifier, hashes=hashes, ) return candidate_evaluator.compute_best_candidate(candidates) def find_requirement(self, req, upgrade): # type: (InstallRequirement, bool) -> Optional[InstallationCandidate] """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise """ hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( req.name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version = None # type: Optional[_BaseVersion] if req.satisfied_by is not None: installed_version = parse_version(req.satisfied_by.version) def _format_versions(cand_iter): # type: (Iterable[InstallationCandidate]) -> str # This repeated parse_version and str() conversion is needed to # handle different vendoring sources from pip and pkg_resources. # If we stop using the pkg_resources provided specifier and start # using our own, we can drop the cast to str(). return ", ".join(sorted( {str(c.version) for c in cand_iter}, key=parse_version, )) or "none" if installed_version is None and best_candidate is None: logger.critical( 'Could not find a version that satisfies the requirement %s ' '(from versions: %s)', req, _format_versions(best_candidate_result.iter_all()), ) raise DistributionNotFound( 'No matching distribution found for {}'.format( req) ) best_installed = False if installed_version and ( best_candidate is None or best_candidate.version <= installed_version): best_installed = True if not upgrade and installed_version is not None: if best_installed: logger.debug( 'Existing installed version (%s) is most up-to-date and ' 'satisfies requirement', installed_version, ) else: logger.debug( 'Existing installed version (%s) satisfies requirement ' '(most up-to-date version is %s)', installed_version, best_candidate.version, ) return None if best_installed: # We have an existing version, and its the best version logger.debug( 'Installed version (%s) is most up-to-date (past versions: ' '%s)', installed_version, _format_versions(best_candidate_result.iter_applicable()), ) raise BestVersionAlreadyInstalled logger.debug( 'Using version %s (newest of versions: %s)', best_candidate.version, _format_versions(best_candidate_result.iter_applicable()), ) return best_candidate def _find_name_version_sep(fragment, canonical_name): # type: (str, str) -> int """Find the separator's index based on the package's canonical name. :param fragment: A + filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 """ # Project name and version must be separated by one single dash. Find all # occurrences of dashes; if the string in front of it matches the canonical # name, this is the one separating the name and version parts. for i, c in enumerate(fragment): if c != "-": continue if canonicalize_name(fragment[:i]) == canonical_name: return i raise ValueError("{} does not match {}".format(fragment, canonical_name)) def _extract_version_from_fragment(fragment, canonical_name): # type: (str, str) -> Optional[str] """Parse the version string from a + filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. """ try: version_start = _find_name_version_sep(fragment, canonical_name) + 1 except ValueError: return None version = fragment[version_start:] if not version: return None return version index/__init__.py000064400000000036152352421750007771 0ustar00"""Index interaction code """ vcs/__pycache__/mercurial.cpython-37.pyc000064400000011574152352421750014177 0ustar00B Re*@sddlmZddlZddlZddlmZddlmZmZddl m Z ddl m Z ddl mZddlmZdd lmZdd lmZmZmZerdd l mZdd lmZeeZGd ddeZeedS))absolute_importN) configparser) BadCommandSubProcessError) display_path) make_command) TempDirectory)MYPY_CHECK_RUNNING) path_to_url)VersionControl!find_path_to_setup_from_repo_rootvcs) HiddenText) RevOptionscseZdZdZdZdZdZeddZddZ d d Z d d Z d dZ e ddZe ddZe ddZe ddZe ddZe fddZZS) Mercurialhgz.hgclone)rzhg+filezhg+httpzhg+httpszhg+sshzhg+static-httpcCs|gS)N)revrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/mercurial.pyget_base_rev_args'szMercurial.get_base_rev_argsc Cs>tdd*}|j|j|d|jd|g|jdWdQRXdS)z?Export the Hg repository at the url to the destination locationexport)kind)urlarchive)cwdN)runpackpath run_command)selflocationrtemp_dirrrrr+s zMercurial.exportcCsP|}td||t||tddd|||jtdd||ddS)NzCloning hg %s%s to %srz --noupdatez-qupdate)r) to_displayloggerinforrrto_args)rdestr rev_options rev_displayrrr fetch_new5s zMercurial.fetch_newc Cstj||jd}t}y>|||dd|jt |d}| |WdQRXWn6t tj fk r}zt d||Wdd}~XYn Xtdd|}|j||ddS) Nhgrcpathsdefaultwz/Could not switch Mercurial repository to %s: %sr"z-q)r)osrjoindirnamerRawConfigParserreadsetsecretopenwriteOSErrorNoSectionErrorr$warningrr&r) rr'rr( repo_configconfig config_fileexccmd_argsrrrswitchDs  zMercurial.switchcCs4|jddg|dtdd|}|j||ddS)Npullz-q)rr")rrr&)rr'rr(r?rrrr"UszMercurial.updatecCs0|jddg|d}||r(t|}|S)N showconfigz paths.default)r)rstrip_is_local_repositoryr )clsr rrrrget_remote_url[s   zMercurial.get_remote_urlcCs|jddg|d}|S)zW Return the repository-local changeset revision number, as an integer. parentsz--template={rev})r)rrC)rEr current_revisionrrr get_revisiondszMercurial.get_revisioncCs|jddg|d}|S)zh Return the changeset identification hash, as a 40-character hexadecimal string rGz--template={node})r)rrC)rEr current_rev_hashrrrget_requirement_revisionms z"Mercurial.get_requirement_revisioncCsdS)z&Always assume the versions don't matchFr)rEr'namerrris_commit_id_equalxszMercurial.is_commit_id_equalcCs@|jdg|d}tj|s6tjtj||}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. root)r)rrCr/risabsabspathr0r )rEr repo_rootrrrget_subdirectory}s  zMercurial.get_subdirectorycsttt||}|r|Sy|jdg|dd}Wn2tk rNtd|dStk r`dSXtj | dS)NrNF)rlog_failed_cmdzIcould not determine if %s is under hg control because hg is not availablez ) superrget_repository_rootrrr$debugrr/rnormpathrstrip)rEr locr) __class__rrrUs zMercurial.get_repository_root)__name__ __module__ __qualname__rLr1 repo_nameschemes staticmethodrrr*r@r" classmethodrFrIrKrMrRrU __classcell__rr)r[rrs    r) __future__rloggingr/pip._vendor.six.movesrpip._internal.exceptionsrrpip._internal.utils.miscrpip._internal.utils.subprocessrpip._internal.utils.temp_dirrpip._internal.utils.typingr pip._internal.utils.urlsr pip._internal.vcs.versioncontrolr r r rr getLoggerr\r$rregisterrrrrs          vcs/__pycache__/bazaar.cpython-37.pyc000064400000007206152352421750013451 0ustar00B Re/@sddlmZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z ddlmZddlmZmZe rdd lmZmZdd lmZdd lmZmZeeZGd d d eZeedS))absolute_importN)parse) display_pathrmtree) make_command)MYPY_CHECK_RUNNING) path_to_url)VersionControlvcs)OptionalTuple) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZfddZeddZ d d Z d d Z d dZ ddZ efddZeddZeddZeddZZS)Bazaarbzrz.bzrbranch)rzbzr+httpz bzr+httpszbzr+sshzbzr+sftpzbzr+ftpzbzr+lpcs0tt|j||ttddr,tjdgdS)N uses_fragmentlp)superr__init__getattr urllib_parserextend)selfargskwargs) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/bazaar.pyr#s zBazaar.__init__cCsd|gS)Nz-rr)revrrrget_base_rev_args*szBazaar.get_base_rev_argscCs>tj|rt|||\}}|td|||dS)zU Export the Bazaar repository at the url to the destination location exportN)ospathexistsrget_url_rev_options run_commandrto_args)rlocationurl rev_optionsrrrr".s  z Bazaar.exportcCs>|}td||t|tdd|||}||dS)NzChecking out %s%s to %srz-q) to_displayloggerinforrr(r')rdestr*r+ rev_displaycmd_argsrrr fetch_new<s zBazaar.fetch_newcCs|jtd||ddS)Nswitch)cwd)r'r)rr/r*r+rrrr3Jsz Bazaar.switchcCs"tdd|}|j||ddS)Npullz-q)r4)rr(r')rr/r*r+r1rrrupdateNsz Bazaar.updatecs2tt||\}}}|dr(d|}|||fS)Nzssh://zbzr+)rrget_url_rev_and_auth startswith)clsr*r user_pass)rrrr7Ss zBazaar.get_url_rev_and_authcCsj|jdg|d}xT|D]H}|}x:dD]2}||r,||d}||rZt|S|Sq,WqWdS)Nr.)r4)zcheckout of branch: zparent branch: )r' splitlinesstripr8split_is_local_repositoryr)r9r)urlslinexreporrrget_remote_url\s    zBazaar.get_remote_urlcCs|jdg|d}|dS)Nrevno)r4)r'r<)r9r)revisionrrr get_revisionjs zBazaar.get_revisioncCsdS)z&Always assume the versions don't matchFr)r9r/namerrris_commit_id_equalqszBazaar.is_commit_id_equal)__name__ __module__ __qualname__rIdirname repo_nameschemesr staticmethodr!r"r2r3r6 classmethodr7rDrHrJ __classcell__rr)rrrs    r) __future__rloggingr#Zpip._vendor.six.moves.urllibrrpip._internal.utils.miscrrpip._internal.utils.subprocessrpip._internal.utils.typingrpip._internal.utils.urlsr pip._internal.vcs.versioncontrolr r typingr r r rr getLoggerrKr-rregisterrrrrs       ]vcs/__pycache__/subversion.cpython-37.pyc000064400000020431152352421750014403 0ustar00B Reo0@sddlmZddlZddlZddlZddlmZddlmZm Z m Z m Z ddl m Z ddlmZddlmZmZedZed Zed Zed Zerdd lmZmZdd l mZddlmZddlmZmZee Z!GdddeZ"e#e"dS))absolute_importN) indent_log) display_pathis_console_interactivermtreesplit_auth_from_netloc) make_command)MYPY_CHECK_RUNNING)VersionControlvcsz url="([^"]+)"zcommitted-rev="(\d+)"z\s*revision="(\d+)"z(.*))OptionalTuple) CommandArgs) HiddenText)AuthInfo RevOptionscseZdZdZdZdZdZeddZe ddZ ed d Z efd d Z efd dZ e ddZeddZeddZeddZd(fdd ZddZddZddZd d!Zd"d#Zd$d%Zd&d'ZZS)) Subversionsvnz.svncheckout)rzsvn+sshzsvn+httpz svn+httpszsvn+svncCsdS)NT)cls remote_urlrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/subversion.pyshould_add_vcs_url_prefix+sz$Subversion.should_add_vcs_url_prefixcCsd|gS)Nz-rr)revrrrget_base_rev_args/szSubversion.get_base_rev_argsc Csd}xt|D]\}}}|j|kr2g|dd<q||jtj||jd}tj|s^q||\}}||kr~|d}n|r||sg|dd<qt ||}qW|S)zR Return the maximum revision for all files under a given location rNentries/) oswalkdirnameremovepathjoinexists_get_svn_url_rev startswithmax) rlocationrevisionbasedirs_ entries_fndirurllocalrevrrr get_revision3s"      zSubversion.get_revisioncs"|dkrtt|||St|S)z This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. ssh)superrget_netloc_and_authr)rnetlocscheme) __class__rrr3OszSubversion.get_netloc_and_authcs2tt||\}}}|dr(d|}|||fS)Nzssh://zsvn+)r2rget_url_rev_and_authr&)rurlr user_pass)r6rrr7\s zSubversion.get_url_rev_and_authcCs(g}|r|d|g7}|r$|d|g7}|S)Nz --usernamez --passwordr)usernamepassword extra_argsrrr make_rev_argses   zSubversion.make_rev_argscCsV|}xBtjtj|dsF|}tj|}||krtd|dSqW||dS)Nzsetup.pyzGCould not find setup.py for directory %s (tried all parent directories)r)rr"r$r#r loggerwarningr%)rr( orig_location last_locationrrrget_remote_urlps zSubversion.get_remote_urlc Csrddlm}tj||jd}tj|rHt|}|}WdQRXnd}| dsj| dsj| drt t t j |d}|dd=|dd }d d |Ddg}n| d rt|}|std jft|d}dd t|Ddg}nZy8|dd|g} t| d}dd t| D}Wn |k rTdg}}YnX|rft|} nd} || fS)Nr)SubProcessErrorr8910z cSs,g|]$}t|dkr|drt|dqS) )lenint).0drrr sz/Subversion._get_svn_url_rev..z             zSubversion._get_svn_url_revcCsdS)z&Always assume the versions don't matchFr)rdestnamerrris_commit_id_equalszSubversion.is_commit_id_equalNcs,|dkrt}||_d|_tt|dS)N)ruse_interactive _vcs_versionr2r__init__)selfrn)r6rrrps zSubversion.__init__cCsvd}|dg}||sdS|t|dd}|ddd}yttt|}Wntk rpdSX|S)aQuery the version of the currently installed Subversion client. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. z svn, version z --versionrNr-.) rbr&rJrZ partitiontuplerWrKr])rqversion_prefixversion version_listparsed_versionrrrcall_vcs_versions  zSubversion.call_vcs_versioncCs"|jdk r|jS|}||_|S)aReturn the version of the currently installed Subversion client. If the version of the Subversion client has already been queried, a cached value will be used. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. N)rorz)rq vcs_versionrrrget_vcs_versions zSubversion.get_vcs_versioncCs&|js dgS|}|dkr"dgSgS)aXReturn options to be used on calls to Subversion that contact the server. These options are applicable for the following ``svn`` subcommands used in this class. - checkout - export - switch - update :return: A list of command line arguments to pass to ``svn``. z--non-interactive)rOz--force-interactive)rnr|)rq svn_versionrrrget_remote_call_optionss  z"Subversion.get_remote_call_optionsc Csh||\}}td||t<tj|r8t|td| | ||}| |WdQRXdS)z@Export the svn repository at the url to the destination locationz!Exporting svn repository %s to %sexportN) get_url_rev_optionsr>rRrrr"r$rrrto_argsrb)rqr(r8 rev_optionscmd_argsrrrrs zSubversion.exportcCsD|}td||t|tdd||||}||dS)NzChecking out %s%s to %srz-q) to_displayr>rRrrrrrb)rqrkr8r rev_displayrrrr fetch_new0s  zSubversion.fetch_newcCs&td||||}||dS)Nswitch)rrrrb)rqrkr8rrrrrr?szSubversion.switchcCs$td|||}||dS)Nupdate)rrrrb)rqrkr8rrrrrrGszSubversion.update)N)__name__ __module__ __qualname__rlr repo_nameschemes classmethodr staticmethodrr0r3r7r=rBr%rmrprzr|rrrrr __classcell__rr)r6rr%s*      2 !r)$ __future__rloggingrrepip._internal.utils.loggingrpip._internal.utils.miscrrrrpip._internal.utils.subprocessrpip._internal.utils.typingr pip._internal.vcs.versioncontrolr r compiler[r`rdrctypingr r rrrr getLoggerrr>rregisterrrrrs,           -vcs/__pycache__/versioncontrol.cpython-37.pyc000064400000050670152352421750015302 0ustar00B Rene@sdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddlmZmZmZddlmZmZddlmZdd lmZmZmZmZmZmZdd lmZm Z m!Z!m"Z"dd l#m$Z$dd l%m&Z&e$r>dd l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2ddlm3Z3ddlm4Z4e.e,e5e,e5fZ6dgZ7e8e9Z:ddZ;d"ddZGddde?Z@GdddeAZBGdddeAZCeCZDGd d!d!eAZEdS)$z)Handles all VCS (version control) support)absolute_importN) pkg_resources)parse) BadCommandInstallationErrorSubProcessError)console_to_strsamefile)subprocess_logger)ask_path_exists backup_dir display_pathhide_url hide_valuermtree)format_command_args make_commandmake_subprocess_output_errorreveal_command_args)MYPY_CHECK_RUNNING)get_url_scheme) DictIterableIteratorListOptionalTextTupleTypeUnionMappingAny) HiddenText) CommandArgsvcscCs*t|}|dkrdS|ddddgtjkS)z3 Return true if the name looks like a URL. NFhttphttpsfileftp)rr$ all_schemes)nameschemer,/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.pyis_url8sr.cCs.t|}d|||}|r*|d|7}|S)z Return the URL for a VCS requirement. Args: repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+"). project_name: the (unescaped) project name. z {}@{}#egg={}z&subdirectory={})r to_filenameformat)repo_urlrev project_namesubdiregg_project_namereqr,r,r-make_vcs_requirement_urlCs r7Tc Csd|dkr g}tj}tj}|r*||d}t|}y.tjt |tj tj |d} | j rb| j Wn6t k r} z|rtd| |Wdd} ~ XYnXg} x@d} | jrt| j} | sP| } | | d|| qWz | Wd| jr| j X| jo| j|k} | rZ|sD|rDt||| | jd}t|d| j|}t|d| S) z Args: extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. log_failed_cmd: if false, failed commands are not logged, only raised. NT)stdoutstderrcwdz#Error %s while executing command %s )cmd_argsr:lines exit_statuszSCommand errored out with exit status {}: {} Check the logs for full command output.)r debugosenvironcopyupdater subprocessPopenrPIPEstdinclose Exceptioncriticalr8rreadlinerstripappendwait returncodererrorr0rjoin)cmdr: extra_environextra_ok_returncodeslog_failed_cmdlog_subprocessenvshowing_subprocess command_descprocexc all_outputlineproc_had_errormsgexc_msgr,r,r-call_subprocessTs`          rbcCsd|}xBtjtj|dsF|}tj|}||krtd|dSqWt||rVdStj||S)z Find the path to `setup.py` by searching up the filesystem from `location`. Return the path to `setup.py` relative to `repo_root`. Return None if `setup.py` is in `repo_root` or cannot be found. zsetup.pyzGCould not find setup.py for directory %s (tried all parent directories)N) rApathexistsrRdirnameloggerwarningr relpath)location repo_root orig_location last_locationr,r,r-!find_path_to_setup_from_repo_roots  rmc@s eZdZdS)RemoteNotFoundErrorN)__name__ __module__ __qualname__r,r,r,r-rnsrnc@sFeZdZdZdddZddZeddZd d Zd d Z d dZ dS) RevOptionsz Encapsulates a VCS-specific revision to install, along with any VCS install options. Instances of this class should be treated as if immutable. NcCs(|dkr g}||_||_||_d|_dS)z Args: vc_class: a VersionControl subclass. rev: the name of the revision to install. extra_args: a list of extra options. N) extra_argsr2vc_class branch_name)selfrtr2rsr,r,r-__init__s zRevOptions.__init__cCsd|jj|jS)Nz)r0rtr*r2)rvr,r,r-__repr__szRevOptions.__repr__cCs|jdkr|jjS|jS)N)r2rtdefault_arg_rev)rvr,r,r-arg_revs zRevOptions.arg_revcCs0g}|j}|dk r"||j|7}||j7}|S)z< Return the VCS-specific command arguments. N)rzrtget_base_rev_argsrs)rvargsr2r,r,r-to_argss  zRevOptions.to_argscCs|js dSd|jS)Nr?z (to revision {}))r2r0)rvr,r,r- to_displayszRevOptions.to_displaycCs|jj||jdS)z Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. )rs)rtmake_rev_optionsrs)rvr2r,r,r-make_newszRevOptions.make_new)NN) rorprq__doc__rwrxpropertyrzr}r~rr,r,r,r-rrs   rrcseZdZiZddddddgZfddZd d Zed d Zed dZ eddZ ddZ ddZ ddZ ddZddZZS) VcsSupportsshgithgbzrsftpsvncs:tj|jttddr(tj|jtt|dS)N uses_fragment) urllib_parse uses_netlocextendschemesgetattrrsuperrrw)rv) __class__r,r-rws zVcsSupport.__init__cCs |jS)N) _registry__iter__)rvr,r,r-r!szVcsSupport.__iter__cCst|jS)N)listrvalues)rvr,r,r-backends%szVcsSupport.backendscCsdd|jDS)NcSsg|] }|jqSr,)re).0backendr,r,r- -sz'VcsSupport.dirnames..)r)rvr,r,r-dirnames*szVcsSupport.dirnamescCs$g}x|jD]}||jq W|S)N)rrr)rvrrr,r,r-r)/s zVcsSupport.all_schemescCsHt|dstd|jdS|j|jkrD||j|j<td|jdS)Nr*zCannot register VCS %szRegistered VCS backend: %s)hasattrrfrgror*rr@)rvclsr,r,r-register7s   zVcsSupport.registercCs||jkr|j|=dS)N)r)rvr*r,r,r- unregister@s zVcsSupport.unregistercCs\i}x:|jD],}||}|s$qtd||j|||<qW|sHdSt|td}||S)zv Return a VersionControl object if a repository of that type is found at the given directory. zDetermine that %s uses VCS: %sN)key)rrget_repository_rootrfr@r*maxlen)rvri vcs_backends vcs_backend repo_pathinner_most_repo_pathr,r,r-get_backend_for_dirEs    zVcsSupport.get_backend_for_dircCs&x |jD]}||jkr |Sq WdS)z9 Return a VersionControl object or None. N)rrr)rvr+rr,r,r-get_backend_for_scheme^s z!VcsSupport.get_backend_for_schemecCs|}|j|S)z9 Return a VersionControl object or None. )lowerrget)rvr*r,r,r- get_backendhszVcsSupport.get_backend)rorprqrrrwrrrrr)rrrrr __classcell__r,r,)rr-rs      rc@s@eZdZdZdZdZdZdZdZe ddZ e ddZ e dd Z e d d Z ed d ZddZe d9ddZe ddZddZe ddZe ddZeddZddZeddZe d d!Zd"d#Zd$d%Zd&d'Ze d(d)Zd*d+Zd,d-Ze d.d/Z e d0d1Z!e d:d3d4Z"e d5d6Z#e d7d8Z$dS);VersionControlr?r,NcCs|d|j S)z Return whether the vcs prefix (e.g. "git+") should be added to a repository's remote url when used in a requirement. z{}:)r startswithr0r*)r remote_urlr,r,r-should_add_vcs_url_prefix~sz(VersionControl.should_add_vcs_url_prefixcCsdS)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. Nr,)rrir,r,r-get_subdirectoryszVersionControl.get_subdirectorycCs ||S)zR Return the revision string that should be used in a requirement. ) get_revision)rrepo_dirr,r,r-get_requirement_revisionsz'VersionControl.get_requirement_revisioncCsV||}|dkrdS||r.d|j|}||}||}t||||d}|S)aC Return the requirement string to use to redownload the files currently at the given repository directory. Args: project_name: the (unescaped) project name. The return value has a form similar to the following: {repository_url}@{revision}#egg={project_name} Nz{}+{})r4)get_remote_urlrr0r*rrr7)rrr3r1revisionr4r6r,r,r-get_src_requirements    z"VersionControl.get_src_requirementcCstdS)z Return the base revision arguments for a vcs command. Args: rev: the name of a revision to install. Cannot be None. N)NotImplementedError)r2r,r,r-r{s z VersionControl.get_base_rev_argscCsdS)aZ Return true if the commit hash checked out at dest matches the revision in url. Always return False, if the VCS does not support immutable commit hashes. This method does not check if there are local uncommitted changes in dest after checkout, as pip currently has no use case for that. Fr,)rvurldestr,r,r-is_immutable_rev_checkouts z(VersionControl.is_immutable_rev_checkoutcCst|||dS)z Return a RevOptions object. Args: rev: the name of a revision to install. extra_args: a list of extra options. )rs)rr)rr2rsr,r,r-rs zVersionControl.make_rev_optionscCs&tj|\}}|tjjp$t|S)zy posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\folder) )rArc splitdriversepbool)rrepodrivetailr,r,r-_is_local_repositorysz#VersionControl._is_local_repositorycCstdS)z Export the repository at the url to the destination location i.e. only download the files, without vcs informations :param url: the repository URL starting with a vcs prefix. N)r)rvrirr,r,r-exportszVersionControl.exportcCs|dfS)aZ Parse the repository URL's netloc, and return the new netloc to use along with auth information. Args: netloc: the original repository URL netloc. scheme: the repository URL's scheme without the vcs prefix. This is mainly for the Subversion class to override, so that auth information can be provided via the --username and --password options instead of through the URL. For other subclasses like Git without such an option, auth information must stay in the URL. Returns: (netloc, (username, password)). )NNr,)rnetlocr+r,r,r-get_netloc_and_authsz"VersionControl.get_netloc_and_authc Cst|\}}}}}d|kr*td||ddd}|||\}}d}d|krx|dd\}}|sxtd|t||||df}|||fS)z Parse the repository URL to use, and return the URL, revision, and auth info to use. Returns: (url, rev, (username, password)). +zvSorry, {!r} is a malformed VCS url. The format is +://, e.g. svn+http://myrepo/svn/MyApp#egg=MyAppN@zyThe URL {!r} has an empty revision (after @) which is not supported. Include a revision after @ or remove @ from the URL.r?) rurlsplit ValueErrorr0splitrrsplitr urlunsplit) rrr+rrcqueryfrag user_passr2r,r,r-get_url_rev_and_auths z#VersionControl.get_url_rev_and_authcCsgS)zM Return the RevOptions "extra arguments" to use in obtain(). r,)usernamepasswordr,r,r- make_rev_args szVersionControl.make_rev_argsc CsT||j\}}}|\}}d}|dk r.t|}|||}|j||d} t|| fS)z Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). N)rs)rsecretrrrr) rvr secret_urlr2rrsecret_passwordrrs rev_optionsr,r,r-get_url_rev_options(s z"VersionControl.get_url_rev_optionscCst|dS)zi Normalize a URL for comparison by unquoting it and removing any trailing slash. /)runquoterM)rr,r,r- normalize_url8szVersionControl.normalize_urlcCs||||kS)zV Compare two repo URLs for identity, ignoring incidental differences. )r)rurl1url2r,r,r- compare_urlsAszVersionControl.compare_urlscCstdS)z Fetch a revision from a repository, in the case that this is the first fetch from the repository. Args: dest: the directory to fetch the repository to. rev_options: a RevOptions object. N)r)rvrrrr,r,r- fetch_newIs zVersionControl.fetch_newcCstdS)z} Switch the repo at ``dest`` to point to ``URL``. Args: rev_options: a RevOptions object. N)r)rvrrrr,r,r-switchUszVersionControl.switchcCstdS)z Update an already-existing repo to the given ``rev_options``. Args: rev_options: a RevOptions object. N)r)rvrrrr,r,r-rD_szVersionControl.updatecCstdS)z Return whether the id of the current commit equals the given name. Args: dest: the repository directory. name: a string name. N)r)rrr*r,r,r-is_commit_id_equalis z!VersionControl.is_commit_id_equalc Cs||\}}tj|s,||||dS|}||r||}|||j rt d|j t|||||jst dt||j |||||n t ddSt d|j|j t||d}nt d||j|j d}t d |j|td |d |d }|d kr&td|dkrZt dt|t|||||dS|dkrt|}t dt||t||||||dS|dkrt d|j t|||||||dS)a Install or update in editable mode the package represented by this VersionControl object. :param dest: the repository directory in which to install or update. :param url: the repository URL starting with a vcs prefix. Nz)%s in %s exists, and has correct URL (%s)zUpdating %s %s%sz$Skipping because already up-to-date.z%s %s in %s exists with URL %s)z%(s)witch, (i)gnore, (w)ipe, (b)ackup )siwbz0Directory %s already exists, and is not a %s %s.)z(i)gnore, (w)ipe, (b)ackup )rrrz+The plan is to install the %s repository %szWhat to do? {}rrarz Deleting %srzBacking up %s to %srzSwitching %s %s to %s%s)rrArcrdrr~is_repository_directoryrrrrfr@ repo_nametitler rr2inforDrgr*r r0sysexitrr shutilmover) rvrrr rev_display existing_urlpromptresponsedest_dirr,r,r-obtainus~           zVersionControl.obtaincCs&tj|rt||j||ddS)z Clean up current location and download the url repository (and vcs infos) into location :param url: the repository URL starting with a vcs prefix. )rN)rArcrdrr)rvrirr,r,r-unpacks zVersionControl.unpackcCstdS)z Return the url used at location Raises RemoteNotFoundError if the repository does not have a remote url configured. N)r)rrir,r,r-rs zVersionControl.get_remote_urlcCstdS)zR Return the current commit id of the files at the given location. N)r)rrir,r,r-rszVersionControl.get_revisionTc Cslt|jf|}yt|||||dStk rf}z&|jtjkrTtdjftnWdd}~XYnXdS)z Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available )rTrUrVzWCannot find command {cls.name!r} - do you have {cls.name!r} installed and in your PATH?N) rr*rbOSErrorerrnoENOENTrr0locals)rrSr:rTrUrVer,r,r- run_commands  zVersionControl.run_commandcCs,td||j|jtjtj||jS)zL Return whether a directory path is a repository directory. zChecking in %s for %s (%s)...)rfr@rer*rArcrdrR)rrcr,r,r-rsz&VersionControl.is_repository_directorycCs||r|SdS)ay Return the "root" (top-level) directory controlled by the vcs, or `None` if the directory is not in any. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. This can do more than is_repository_directory() alone. For example, the Git override checks that Git is actually available. N)r)rrir,r,r-rs z"VersionControl.get_repository_root)NN)NNNT)%rorprqr*rerr unset_environry classmethodrrrr staticmethodr{rrrrrrrrrrrrrDrrrrrrrrr,r,r,r-rtsJ           ^   r)N)NNNT)Fr __future__rrloggingrArrEr pip._vendorrZpip._vendor.six.moves.urllibrrpip._internal.exceptionsrrrpip._internal.utils.compatrr pip._internal.utils.loggingr pip._internal.utils.miscr r r rrrpip._internal.utils.subprocessrrrrpip._internal.utils.typingrpip._internal.utils.urlsrtypingrrrrrrrrrr r!r"r#strZAuthInfo__all__ getLoggerrorfr.r7rbrmrJrnobjectrrrr$rr,r,r,r-sF       4     QI^vcs/__pycache__/git.cpython-37.pyc000064400000022473152352421750012777 0ustar00B Re6@sddlmZddlZddlZddlZddlmZddl mZ ddl m Z ddl mZmZddlmZmZddlmZddlmZdd lmZdd lmZmZmZmZerdd lmZm Z dd lm!Z!dd lm"Z"m#Z#e j$Z$e j%Z%e&e'Z(e)dZ*ddZ+GdddeZ,e-e,dS))absolute_importN)parse)request) BadCommandSubProcessError) display_pathhide_url) make_command) TempDirectory)MYPY_CHECK_RUNNING)RemoteNotFoundErrorVersionControl!find_path_to_setup_from_repo_rootvcs)OptionalTuple) HiddenText)AuthInfo RevOptionsz^[a-fA-F0-9]{40}$cCstt|S)N)bool HASH_REGEXmatch)shar/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/git.pylooks_like_hash*srcseZdZdZdZdZdZdZdZe ddZ d d Z d d Z e d dZddZe ddZe ddZe ddZddZddZddZe ddZe d*d d!Ze d"d#Ze fd$d%Ze d&d'Ze fd(d)ZZS)+Gitgitz.gitclone)rzgit+httpz git+httpszgit+sshzgit+gitzgit+file)GIT_DIR GIT_WORK_TREEHEADcCs|gS)Nr)revrrrget_base_rev_args:szGit.get_base_rev_argscCsJ|t|\}}|jsdS|||js.dSt|||jd}| S)NFr)get_url_rev_optionsrr"is_commit_id_equalrget_revision_sha)selfurldest_ rev_optionsis_tag_or_branchrrris_immutable_rev_checkout>szGit.is_immutable_rev_checkoutcCsXd}|dg}||r4|t|dd}nd}d|ddd}t|S)Nz git version versionr.) run_command startswithlensplitjoin parse_version)r' VERSION_PFXr.rrrget_git_versionOs  zGit.get_git_versioncCs@dddg}|j|d|d}|}|dr<|tddSdS)zl Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). z symbolic-refz-qr!))extra_ok_returncodescwdz refs/heads/N)r2stripr3r4)clslocationargsoutputrefrrrget_current_branch\s   zGit.get_current_branchc CsV|ds|d}tdd0}|j|j|d|jdddd|g|jd Wd QRXd S) z@Export the Git repository at the url to the destination location/export)kind)r(zcheckout-indexz-az-fz--prefix)r<N)endswithr unpackpathr2)r'r?r(temp_dirrrrrEqs   z Git.exportc Csd}y|jd|g|d}Wntk r.YnXi}xP|D]@}y|\}}Wn"tk rxtd|YnX|||<qBWd|}d|} ||}|dk r|dfS|| }|d fS) z Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. r/zshow-ref)r<zunexpected show-ref line: {!r}zrefs/remotes/origin/{}z refs/tags/{}NTF)r2rr= splitlinesr5 ValueErrorformatget) r>r)r"rArefslinerrB branch_reftag_refrrrr&~s&      zGit.get_revision_shacCs|j}|dk st|||\}}|dk rF||}|r<|nd|_|St|sZtd||dsh|S|j t dd|| |d|j |dd}||}|S) z Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. Nz:Did not find branch or tag '%s', assuming revision or ref.zrefs/fetchz-q)r< FETCH_HEAD)r") arg_revAssertionErrorr&make_new branch_namerloggerwarningr3r2r to_args get_revision)r>r)r(r+r"r is_branchrrrresolve_revisions&     zGit.resolve_revisioncCs|sdS|||kS)z Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name. F)r\)r>r)namerrrr%s zGit.is_commit_id_equalcCs|}td||t||tdd|||jr||||}t|dd}|dkr| ||jstdd| }|j||dn4| ||krd |}dd|d |g}|j||d| |dS) NzCloning %s%s to %srz-qrXcheckout)r<z origin/{}z-bz--track) to_displayrYinforr2r r"r^getattrr%r[rCrMupdate_submodules)r'r)r(r+ rev_displayrXcmd_args track_branchrrr fetch_news   z Git.fetch_newcCsB|jtdd||dtdd|}|j||d||dS)Nconfigzremote.origin.url)r<r`z-q)r2r r[rd)r'r)r(r+rfrrrswitchs  z Git.switchcCst|tdkr&|jdddg|dn|jddg|d||||}tddd|}|j||d||dS)Nz1.9.0rSz-qz--tags)r<resetz--hard)r9r7r2r^r r[rd)r'r)r(r+rfrrrupdate sz Git.updatecCsx|jdddgd|d}|}y |d}Wntk rBtYnXx|D]}|drJ|}PqJW|dd }|S) z Return URL of the first remote encountered. Raises RemoteNotFoundError if the repository does not have a remote url configured. riz --get-regexpzremote\..*\.url)r:)r;r<rzremote.origin.url  r:)r2rK IndexErrorr r3r5r=)r>r?stdoutremotes found_remoteremoter(rrrget_remote_urls      zGit.get_remote_urlNcCs&|dkr d}|jd|g|d}|S)Nr!z rev-parse)r<)r2r=)r>r?r" current_revrrrr\5s zGit.get_revisioncCsP|jddg|d}tj|s0tj||}tjtj|d}t||S)z~ Return the path to setup.py, relative to the repo root. Return None if setup.py is in the repo root. z rev-parsez --git-dir)r<z..)r2r=osrIisabsr6abspathr)r>r?git_dir repo_rootrrrget_subdirectory>s  zGit.get_subdirectoryc st|\}}}}}|dr|dt|d }|t|ddd}t|||||f}|dd} |d| t|| d||||f}d|krd|kst |d d }t t | |\}} } |d d }nt t | |\}} } || | fS) a9 Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. fileNrD\+r:z://zfile:zgit+z git+ssh://zssh://r/) urlsplitrGr4lstripurllib_request url2pathnamereplace urlunsplitfindrVsuperrget_url_rev_and_auth) r>r(schemenetlocrIqueryfragmentinitial_slashesnewpath after_plusr" user_pass) __class__rrrMs"      zGit.get_url_rev_and_authcCs6tjtj|dsdS|jdddddg|ddS)Nz .gitmodules submodulerlz--initz --recursivez-q)r<)rurIexistsr6r2)r>r?rrrrdps  zGit.update_submodulescsvtt||}|r|Sy|jddg|dd}Wn2tk rPtd|dStk rbdSXtj | dS)Nz rev-parsez--show-toplevelF)r<log_failed_cmdzKcould not determine if %s is under git control because git is not availablez ) rrget_repository_rootr2rrYdebugrrurInormpathrstrip)r>r?locr)rrrrys zGit.get_repository_root)N)__name__ __module__ __qualname__r_dirname repo_nameschemes unset_environdefault_arg_rev staticmethodr#r-r9 classmethodrCrEr&r^r%rhrjrlrsr\rzrrdr __classcell__rr)rrr.s0   ( -     # r). __future__rloggingos.pathrurepip._vendor.packaging.versionrr7Zpip._vendor.six.moves.urllib urllib_parserrpip._internal.exceptionsrrpip._internal.utils.miscrrpip._internal.utils.subprocessr pip._internal.utils.temp_dirr pip._internal.utils.typingr pip._internal.vcs.versioncontrolr r rrtypingrrrrrr~r getLoggerrrYcompilerrrregisterrrrrs2          avcs/__pycache__/__init__.cpython-37.pyc000064400000001007152352421750013741 0ustar00B Rei@s<ddlZddlZddlZddlZddlmZmZmZm Z dS)N)RemoteNotFoundErroris_urlmake_vcs_requirement_urlvcs) pip._internal.vcs.bazaarpippip._internal.vcs.gitpip._internal.vcs.mercurialpip._internal.vcs.subversion pip._internal.vcs.versioncontrolrrrrr r /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/vcs/__init__.pysutils/__pycache__/wheel.cpython-37.pyc000064400000014271152352421750013662 0ustar00B Re@s dZddlmZddlZddlmZddlmZddlm Z ddl m Z ddl m Z mZdd lmZdd lmZdd lmZerdd lmZdd lmZmZddl mZe rddlmZn ddlmZdZeeZ GdddeZ!ddZ"ddZ#ddZ$ddZ%ddZ&ddZ'd d!Z(dS)"z0Support functions for working with wheel files. )absolute_importN)Parser)ZipFile)canonicalize_name)DistInfoDistribution)PY2 ensure_str)UnsupportedWheel) DictMetadata)MYPY_CHECK_RUNNING)Message)DictTuple) Distribution) BadZipfile) BadZipFile)rcs,eZdZdZfddZfddZZS) WheelMetadatazaMetadata provider that maps metadata decoding exceptions to our internal exception type. cstt||||_dS)N)superr__init__ _wheel_name)selfmetadata wheel_name) __class__/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/wheel.pyr(szWheelMetadata.__init__c sJytt||Stk rD}ztd|j|Wdd}~XYnXdS)Nz"Error decoding metadata for {}: {})rr get_metadataUnicodeDecodeErrorr formatr)rnamee)rrrr-s zWheelMetadata.get_metadata)__name__ __module__ __qualname____doc__rr __classcell__rr)rrr$s rc st||\}fdd|D}i}xn|D]f}t|}|dd\}}yt||||<Wq.tk r} ztd|t| Wdd} ~ XYq.Xq.Wt||} t || |dS)zaGet a pkg_resources distribution given a wheel. :raises UnsupportedWheel: on any errors cs g|]}|dr|qS)z{}/) startswithr).0p)info_dirrr Csz8pkg_resources_distribution_for_wheel../rz{} has an invalid wheel, {}N)locationr project_name) parse_wheelnamelistrsplitread_wheel_metadata_filer rstrrr) wheel_zipr r-_metadata_files metadata_textpath full_path metadata_namer!rr)r*r$pkg_resources_distribution_for_wheel:s ( r;c Csjy t||}t||}t|}Wn6tk rV}ztd|t|Wdd}~XYnXt||||fS)zExtract information from the provided wheel, ensuring it meets basic standards. Returns the name of the .dist-info directory and the parsed WHEEL metadata. z{} has an invalid wheel, {}N)wheel_dist_info_dirwheel_metadata wheel_versionr rr3check_compatibility)r4r r*rversionr!rrrr/_s   $ r/cCstdd|D}dd|D}|s0tdt|dkrPtdd||d }t|}t|}||std ||t|S) zReturns the name of the contained .dist-info directory. Raises AssertionError or UnsupportedWheel if not found, >1 found, or it doesn't match the provided name. css|]}|dddVqdS)r,rrN)r1)r(r)rrr |sz&wheel_dist_info_dir..cSsg|]}|dr|qS)z .dist-info)endswith)r(srrrr+~sz'wheel_dist_info_dir..z.dist-info directory not foundrz)multiple .dist-info directories found: {}z, rz2.dist-info directory {!r} does not start with {!r}) setr0r lenrjoinrr'r)sourcer subdirs info_dirsr* info_dir_namecanonical_namerrrr<ts    r<c CsHy ||Stttfk rB}ztd||Wdd}~XYnXdS)Nzcould not read {!r} file: {!r})readrKeyError RuntimeErrorr r)rGr8r!rrrr2s  r2c Cs`d|}t||}y t|}Wn2tk rR}ztd||Wdd}~XYnXt|S)ziReturn the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel. z{}/WHEELzerror decoding {!r}: {!r}N)rr2rrr rparsestr)rG dist_info_dirr8wheel_contents wheel_textr!rrrr=s   "r=cCs\|d}|dkrtd|}yttt|dStk rVtd|YnXdS)zbGiven WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel. z Wheel-VersionNzWHEEL is missing Wheel-Version.zinvalid Wheel-Version: {!r})r striptuplemapintr1 ValueErrorr) wheel_data version_textr@rrrr>sr>c CsR|dtdkr.td|dtt|n |tkrNtddtt|dS)aRaises errors or warns if called with an incompatible Wheel-Version. pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given rzB{}'s Wheel-Version ({}) is not compatible with this version of piprSz*Installing from a newer Wheel-Version (%s)N)VERSION_COMPATIBLEr rrFrVr3loggerwarning)r@r rrrr?s r?))r% __future__rlogging email.parserrzipfilerZpip._vendor.packaging.utilsrZpip._vendor.pkg_resourcesrZpip._vendor.sixrrpip._internal.exceptionsr !pip._internal.utils.pkg_resourcesr pip._internal.utils.typingr email.messager typingr rrrrr[ getLoggerr"r\rr;r/r<r2r=r>r?rrrrs6            %& utils/__pycache__/packaging.cpython-37.pyc000064400000005145152352421750014502 0ustar00B Re @sddlmZddlZddlmZddlmZddlmZm Z ddl m Z ddl m Z ddlmZerdd lmZmZdd lmZdd lmZeeZd d ZddZddZddZdS))absolute_importN) FeedParser) pkg_resources) specifiersversion)NoneMetadataError) display_path)MYPY_CHECK_RUNNING)OptionalTuple)Message) DistributioncCs4|dkr dSt|}tdtt|}||kS)a Check if the given Python version matches a "Requires-Python" specifier. :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). :return: `True` if the given Python version satisfies the requirement. Otherwise, return `False`. :raises InvalidSpecifier: If `requires_python` has an invalid format. NT.)r SpecifierSetrparsejoinmapstr)requires_python version_inforequires_python_specifierpython_versionr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/packaging.pycheck_requires_pythons  rcCsd}t|tjr&||r&||}n0|dr@d}||}ntdt|jd}|dkrht ||t }| || S)z :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. METADATAzPKG-INFOzNo metadata found in %sN) isinstancerDistInfoDistribution has_metadata get_metadataloggerwarningrlocationrrfeedclose)dist metadata_namemetadata feed_parserrrrr ,s       r cCs&t|}|d}|dk r"t|}|S)z_ Return the "Requires-Python" metadata for a distribution, or None if not present. zRequires-PythonN)r getr)r& pkg_info_dictrrrrget_requires_pythonGs  r,cCs2|dr.x"|dD]}|r|SqWdS)N INSTALLERr)rget_metadata_linesstrip)r&linerrr get_installerXs   r1) __future__rlogging email.parserr pip._vendorrZpip._vendor.packagingrrpip._internal.exceptionsrpip._internal.utils.miscrpip._internal.utils.typingr typingr r email.messager Zpip._vendor.pkg_resourcesr getLogger__name__r!rr r,r1rrrrs         utils/__pycache__/inject_securetransport.cpython-37.pyc000064400000001743152352421750017355 0ustar00B Re*@sdZddlZddZedS)a-A helper module that injects SecureTransport, on import. The import should be done as early as possible, to ensure all requests and sessions (or whatever) are created after injecting SecureTransport. Note that we only do the injection on macOS, when the linked OpenSSL is too old to handle TLSv1.2. Nc CsttjdkrdSy ddl}Wntk r.dSX|jdkr>dSyddlm}Wnttfk rfdSX|dS)Ndarwinri)securetransport) sysplatformssl ImportErrorOPENSSL_VERSION_NUMBERpip._vendor.urllib3.contribrOSErrorinject_into_urllib3)rrr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/inject_securetransport.pyinject_securetransport s   r)__doc__rrr r r r sutils/__pycache__/appdirs.cpython-37.pyc000064400000002574152352421750014223 0ustar00B ReE@s^dZddlmZddlZddlmZddlmZer@ddl m Z ddZ dd d Z d d Z dS)z This code wraps the vendored appdirs module to so the return values are compatible for the current pip code base. The intention is to rewrite current usages gradually, keeping the tests pass, and eventually drop this after all usages are changed. )absolute_importN)appdirs)MYPY_CHECK_RUNNING)ListcCstj|ddS)NF) appauthor)_appdirsuser_cache_dir)appnamer /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/appdirs.pyrsrTcCsHtj|d|d}tjdkrDtj|sDtjd}|rDtj||}|S)NF)rroamingdarwinz ~/.config/)ruser_config_dirsystemospathisdir expanduserjoin)r r rr r r rs  rcCs2tj|ddd}tjdkr,|tjdgS|gS)NFT)r multipath)win32r z/etc)rsite_config_dirrsplitrpathsep)r dirvalr r r site_config_dirs&s r)T)__doc__ __future__rr pip._vendorrrpip._internal.utils.typingrtypingrrrrr r r r s     utils/__pycache__/temp_dir.cpython-37.pyc000064400000015722152352421750014363 0ustar00B Re @s&ddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZmZddlmZerddlmZmZmZmZmZmZed d d ZeeZed d ddZdae ddZ Gddde!Z"da#e ddZ$Gddde!Z%e%Z&Gdd d e!Z'Gddde'Z(dS))absolute_importN)contextmanager) ExitStack) ensure_text)enumrmtree)MYPY_CHECK_RUNNING)AnyDictIteratorOptionalTypeVarUnion_T TempDirectory)boundz build-envzephem-wheel-cachez req-build) BUILD_ENVEPHEM_WHEEL_CACHE REQ_BUILDc cs2t"}t|}az dVWd|aXWdQRXdS)N)r_tempdir_manager)stackold_tempdir_managerr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/temp_dir.pyglobal_tempdir_manager%s   rc@s(eZdZdZddZddZddZdS) TempDirectoryTypeRegistryz$Manages temp directory behavior cCs i|_dS)N)_should_delete)selfrrr__init__5sz"TempDirectoryTypeRegistry.__init__cCs||j|<dS)z[Indicate whether a TempDirectory of the given kind should be auto-deleted. N)r)rkindvaluerrr set_delete9sz$TempDirectoryTypeRegistry.set_deletecCs|j|dS)z^Get configured auto-delete flag for a given TempDirectory type, default True. T)rget)rrrrr get_delete@sz$TempDirectoryTypeRegistry.get_deleteN)__name__ __module__ __qualname____doc__rr!r#rrrrr1srccs t}taz tVWd|aXdS)zuProvides a scoped global tempdir registry that can be used to dictate whether directories should be deleted. N)_tempdir_registryr)old_tempdir_registryrrrtempdir_registryKs  r*c@s eZdZdS)_DefaultN)r$r%r&rrrrr+Zsr+cs^eZdZdZdeddffdd ZeddZd d Zd d Z d dZ ddZ ddZ Z S)raMHelper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory should be deleted when exiting (when used as a contextmanager) Methods: cleanup() Deletes the temporary directory When used as a context manager, if the delete attribute is True, on exiting the context the temporary directory is deleted. NtempFcsptt||tkr(|dk r$d}nd}|dkr:||}||_d|_||_||_|rlt dk sbt t |dS)NF) superrr_default_create_path_deleteddeleterrAssertionError enter_context)rpathr2rglobally_managed) __class__rrrvs  zTempDirectory.__init__cCs|jrtd|j|jS)Nz$Attempted to access deleted path: {})r1r3formatr0)rrrrr5szTempDirectory.pathcCsd|jj|jS)Nz <{} {!r}>)r8r7r$r5)rrrr__repr__szTempDirectory.__repr__cCs|S)Nr)rrrr __enter__szTempDirectory.__enter__cCs8|jdk r|j}ntr$t|j}nd}|r4|dS)NT)r2r(r#rcleanup)rexcr tbr2rrr__exit__s zTempDirectory.__exit__cCs*tjtjd|d}td||S)zECreate a temporary directory and store its path in self.path zpip-{}-)prefixzCreated temporary directory: %s)osr5realpathtempfilemkdtempr8loggerdebug)rrr5rrrr/s zTempDirectory._createcCs&d|_tj|jr"tt|jdS)z?Remove the temporary directory created and reset state TN)r1r@r5existsr0rr)rrrrr;szTempDirectory.cleanup)r$r%r&r'r.rpropertyr5r9r:r>r/r; __classcell__rr)r7rras  cs:eZdZdZdZd fdd ZeddZdd ZZ S) AdjacentTempDirectoryaHelper class that creates a temporary directory adjacent to a real one. Attributes: original The original directory to create a temp directory for. path After calling create() or entering, contains the full path to the temporary directory. delete Whether the directory should be deleted when exiting (when used as a contextmanager) z-~.=%0123456789Ncs"|d|_tt|j|ddS)Nz/\)r2)rstriporiginalr-rIr)rrKr2)r7rrrs zAdjacentTempDirectory.__init__ccsxZtdt|D]H}xBt|j|dD],}dd|||d}||kr(|Vq(WqWxNtt|jD]<}x6t|j|D]$}dd||}||kr|VqWqlWdS)a Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). ~N)rangelen itertoolscombinations_with_replacement LEADING_CHARSjoin)clsnamei candidatenew_namerrr_generate_namess z%AdjacentTempDirectory._generate_namesc Cstj|j\}}x||D]`}tj||}yt|Wn0tk rn}z|jtj kr^Wdd}~XYqXtj |}PqWtj t j d |d}td||S)Nzpip-{}-)r?zCreated temporary directory: %s)r@r5splitrKrZrTmkdirOSErrorerrnoEEXISTrArBrCr8rDrE)rrrootrVrXr5exrrrr/s   zAdjacentTempDirectory._create)N) r$r%r&r'rSr classmethodrZr/rHrr)r7rrIs   rI)) __future__rr^rQloggingos.pathr@rB contextlibrpip._vendor.contextlib2rZpip._vendor.sixrpip._internal.utils.miscrrpip._internal.utils.typingrtypingr r r r r rr getLoggerr$rD tempdir_kindsrrobjectrr(r*r+r.rrIrrrrs6          iutils/__pycache__/urls.cpython-37.pyc000064400000003030152352421750013532 0ustar00B Re@shddlZddlZddlmZddlmZddlmZerLddl m Z m Z m Z ddZ dd Zd d ZdS) N)parse)request)MYPY_CHECK_RUNNING)OptionalTextUnioncCs d|kr dS|dddS)N:r)splitlower)urlr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/urls.pyget_url_scheme srcCs*tjtj|}tdt|}|S)zh Convert a path to a file: URL. The path will be made absolute and have quoted path parts. zfile:)ospathnormpathabspath urllib_parseurljoinurllib_request pathname2url)rr r r r path_to_urlsrcCsz|dstdjftt|\}}}}}|r<|dkrBd}n&tjdkrVd|}ntdjftt ||}|S)z( Convert a file: URL to a path. zfile:z9You can only turn file: urls into filenames (not {url!r}) localhostwin32z\\z?non-local file URIs are not supported on this platform: {url!r}) startswithAssertionErrorformatlocalsrurlsplitsysplatform ValueErrorr url2pathname)r _netlocrr r r url_to_paths      r')rr!Zpip._vendor.six.moves.urllibrrrrpip._internal.utils.typingrtypingrrrrrr'r r r rs    utils/__pycache__/filesystem.cpython-37.pyc000064400000012741152352421750014742 0ustar00B Re@sRddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZddlmZddlmZmZerdd lmZmZmZmZmZGd d d eZd d ZddZddZ e ddZ!e dddZ"er e"ddZ#n e"ej#Z#ddZ$ddZ%ddZ&dd Z'd!d"Z(d#d$Z)d%d&Z*dS)'N)contextmanager)NamedTemporaryFile)retry)PY2) get_path_uid) format_size)MYPY_CHECK_RUNNINGcast)AnyBinaryIOIteratorListUnionc@seZdZeddZdS)NamedTemporaryFileResultcCsdS)N)selfrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/filesystem.pyfileszNamedTemporaryFileResult.fileN)__name__ __module__ __qualname__propertyrrrrrrsrcCstjdksttdsdStj|s(td}xp||krtj|rtdkrxy t |}Wnt k rndSX|dkSt |tj Sq.|tj |}}q.WdS)Nwin32geteuidTrF)sysplatformhasattrospathisabsAssertionErrorlexistsrrOSErroraccessW_OKdirname)rpreviouspath_uidrrrcheck_path_owners    r(c Cs|yt||Wnfttfk rvxJ||gD]>}y t|}Wntk rRYq.X|r.tdjftq.WYnXdS)zWrap shutil.copy2() but map errors copying socket files to SpecialFileError as expected. See also https://bugs.python.org/issue37700. z`{f}` is a socketN)shutilcopy2r"IOError is_socketSpecialFileErrorformatlocals)srcdestfis_socket_filerrr copy2_fixed;s r4cCstt|jS)N)statS_ISSOCKrlstatst_mode)rrrrr,Tsr,c ksjtfdtj|tj|dd|8}td|}z |VWd|jt|j XWdQRXdS)a%Return a file-like object pointing to a tmp file next to path. The file is created securely and is ensured to be written to disk after the context reaches its end. kwargs will be passed to tempfile.NamedTemporaryFile to control the way the temporary file will be opened. Fz.tmp)deletedirprefixsuffixrN) rrrr%basenamer rflushfsyncfileno)rkwargsr2resultrrradjacent_tmp_fileYs      rCi)stop_max_delay wait_fixedcCs@yt||Wn*tk r:t|t||YnXdS)N)rrenamer"remove)r0r1rrrreplacevs  rIcCsLx*tj|s*tj|}||kr$P|}qWtjdkrDt|tjSt|S)zgCheck if a directory is writable. Uses os.access() on POSIX, tries creating files on Windows. posix)rrisdirr%namer#r$_test_writable_dir_win)rparentrrrtest_writable_dirs  rOc sd}dxtdD]}|dfddtdD}tj||}yt|tjtjBtjB}WnNtk r}z0|j t j krw|j t j ks|j t j krdSWdd}~XYqXt |t|d SqWtd dS) N(accesstest_deleteme_fishfingers_custard_$abcdefghijklmnopqrstuvwxyz0123456789 c3s|]}tVqdS)N)randomchoice).0_)alphabetrr sz)_test_writable_dir_win..FTz3Unexpected condition testing for writable directory)rangejoinrropenO_RDWRO_CREATO_EXCLr"errnoEEXISTEPERMEACCEScloseunlinkEnvironmentError)rr=rWrLrfder)rXrrMs$    rMcsFg}x.)rwalkfnmatchfilterextend)rpatternrBrWfilesmatchesr)rjr find_filess  rrcCstj|rdStj|S)Nr)rrislinkgetsize)rrrr file_sizes rucCs tt|S)N)rru)rrrrformat_file_sizesrvcCsJd}x@t|D]2\}}}x&|D]}tj||}|t|7}q WqW|S)Ng)rrkrr\ru)rsizerj_dirsrpfilename file_pathrrrdirectory_sizes  r{cCs tt|S)N)rr{)rrrrformat_directory_sizesr|)+rarlros.pathrTr)r5r contextlibrtempfilerpip._vendor.retryingrZpip._vendor.sixrpip._internal.utils.compatrpip._internal.utils.miscrpip._internal.utils.typingrr typingr r r r rrr(r4r,rC_replace_retryrIrOrMrrrurvr{r|rrrrs@         $  utils/__pycache__/datetime.cpython-37.pyc000064400000001037152352421750014346 0ustar00B Re'@s$dZddlmZddlZddZdS)z.For when pip wants to check the date or time. )absolute_importNcCs tj}t|||}||kS)N)datetimedatetoday)yearmonthdayrgivenr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/datetime.pytoday_is_later_than s r )__doc__ __future__rrr r r r r s utils/__pycache__/encoding.cpython-37.pyc000064400000002512152352421750014337 0ustar00B Re@sddlZddlZddlZddlZddlmZerDddlmZmZm Z ej dfej dfej dfej dfejdfejd fejd fgZed Zd d ZdS)N)MYPY_CHECK_RUNNING)ListTupleTextzutf-8zutf-16z utf-16-bez utf-16-lezutf-32z utf-32-bez utf-32-lescoding[:=]\s*([-\w.]+)cCsx0tD](\}}||r|t|d|SqWxf|dddD]P}|dddkrFt|rFt|}|dk szt|dd}||SqFW|t dpt S) zCheck a bytes string for a BOM to correctly detect the encoding Fallback to locale.getpreferredencoding(False) like open() on Python3N r#asciiF) BOMS startswithlendecodesplit ENCODING_REsearchAssertionErrorgroupslocalegetpreferredencodingsysgetdefaultencoding)databomencodinglineresultr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/encoding.py auto_decodes   r)codecsrrerpip._internal.utils.typingrtypingrrrBOM_UTF8 BOM_UTF16 BOM_UTF16_BE BOM_UTF16_LE BOM_UTF32 BOM_UTF32_BE BOM_UTF32_LEr compilerrrrrrs   utils/__pycache__/hashes.cpython-37.pyc000064400000011030152352421750014017 0ustar00B ReF@sddlmZddlZddlmZmZmZddlmZm Z m Z ddl m Z ddl mZerddlmZmZmZmZmZddlmZerdd lmZn dd lmZd Zd d d gZGdddeZGdddeZdS))absolute_importN) iteritemsiterkeys itervalues) HashMismatch HashMissingInstallationError) read_chunks)MYPY_CHECK_RUNNING)DictListBinaryIONoReturnIterator)PY3)_Hash)_hashsha256sha384sha512c@sfeZdZdZdddZddZeddZd d Zd d Z d dZ ddZ ddZ ddZ ddZdS)HasheszaA wrapper that builds multiple hashes at once and checks them against known-good values NcCs|dkr in||_dS)zo :param hashes: A dict of algorithm names pointing to lists of allowed hex digests N)_allowed)selfhashesr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/hashes.py__init__)szHashes.__init__csft|tstS|sSs|Si}x:t|jD],\}jkrBq.fdd|D|<q.Wt|S)Ncsg|]}|jkr|qSr)r).0v)algrrr Bsz"Hashes.__and__..) isinstancerNotImplementedrr)rothernewvaluesr)rrr__and__1s  zHashes.__and__cCstdd|jDS)Ncss|]}t|VqdS)N)len)rdigestsrrr Hsz&Hashes.digest_count..)sumrr%)rrrr digest_countEszHashes.digest_countcCs||j|gkS)z/Return whether the given hex digest is allowed.)rget)r hash_name hex_digestrrris_hash_allowedJszHashes.is_hash_allowedc Csi}xLt|jD]>}yt|||<Wqttfk rLtd|YqXqWx(|D] }xt|D]}| |qfWqXWx*t |D]\}}| |j|krdSqW| |dS)zCheck good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. zUnknown hash name: {}N) rrhashlibr$ ValueError TypeErrorrformatrupdater hexdigest_raise)rchunksgotsr-chunkhashgotrrrcheck_against_chunksSs zHashes.check_against_chunkscCst|j|dS)N)rr)rr8rrrr6msz Hashes._raisecCs|t|S)zaCheck good hashes against a file-like object Raise HashMismatch if none match. )r<r )rfilerrrcheck_against_fileqszHashes.check_against_filec Cs t|d }||SQRXdS)Nrb)openr>)rpathr=rrrcheck_against_pathzs zHashes.check_against_pathcCs t|jS)z,Return whether I know any known-good hashes.)boolr)rrrr __nonzero__szHashes.__nonzero__cCs|S)N)rD)rrrr__bool__szHashes.__bool__)N)__name__ __module__ __qualname____doc__rr&propertyr+r/r<r6r>rBrDrErrrrr$s    rcs(eZdZdZfddZddZZS) MissingHasheszA workalike for Hashes used when we're missing a hash for a requirement It computes the actual hash of the requirement and raises a HashMissing exception showing it to the user. cstt|jtgiddS)z!Don't offer the ``hashes`` kwarg.)rN)superrKr FAVORITE_HASH)r) __class__rrrszMissingHashes.__init__cCst|tdS)N)rrMr5)rr8rrrr6szMissingHashes._raise)rFrGrHrIrr6 __classcell__rr)rNrrKs rK) __future__rr0Zpip._vendor.sixrrrpip._internal.exceptionsrrrpip._internal.utils.miscr pip._internal.utils.typingr typingr r r rrrrrrM STRONG_HASHESobjectrrKrrrrs      eutils/__pycache__/pkg_resources.cpython-37.pyc000064400000003522152352421750015426 0ustar00B Re@sPddlmZddlmZddlmZers   utils/__pycache__/glibc.cpython-37.pyc000064400000003335152352421750013635 0ustar00B Re @s`ddlmZddlZddlZddlmZerdSX|S)z@Primary implementation of glibc_version_string using os.confstr.win32NCS_GNU_LIBC_VERSION)sysplatformosconfstrsplitAttributeErrorOSError ValueError)_versionrrr rs rcCsry ddl}Wntk r dSX|d}y |j}Wntk rJdSX|j|_|}t|tsn| d}|S)z=Fallback implementation of glibc_version_string using ctypes.rNascii) ctypes ImportErrorCDLLgnu_get_libc_versionrc_char_prestype isinstancestrdecode)rprocess_namespacer version_strrrr r's     rcCst}|dkrdSd|fSdS)zTry to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails. N)r#glibc)r ) glibc_versionrrr libc_verWsr&) __future__rrr pip._internal.utils.typingrtypingrrr rrr&rrrr s  0utils/__pycache__/direct_url_helpers.cpython-37.pyc000064400000005223152352421750016431 0ustar00B Re@sddlZddlmZmZmZmZmZmZddlm Z ddl m Z yddl m Z Wnek rheZ YnXe rddlmZddlmZddlmZeeZd d Zdd d ZddZdS)N)DIRECT_URL_METADATA_NAME ArchiveInfo DirectUrlDirectUrlValidationErrorDirInfoVcsInfo)MYPY_CHECK_RUNNING)vcs)JSONDecodeError)Optional)Link) DistributioncCs||d}g}t|jtr>|d|jj|j|jj7}nTt|jtrl||j7}|jj r| |jj n&t|jt s|t |jj rt ||j7}|jr| d|j|r|dd|7}|S)z0Convert a DirectUrl to a pip requirement string.z @ z{}+{}@{}z subdirectory=#&)validate isinstanceinforformatr url commit_idrhashappendrAssertionErroreditable subdirectoryjoin) direct_urlname requirement fragmentsr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/direct_url_helpers.py%direct_url_as_pep440_direct_references$     r"Fc Cs|jrlt|j}|st||j\}}}|r>|s8t|}n|sFt||}t|t |j ||d|j dS| rt|jt |j dSd}|j} | rd| |j}t|jt|d|j dSdS)N)r rrequested_revision)rrrz{}={})r)is_vcsr get_backend_for_schemeschemerget_url_rev_and_authurl_without_fragment get_revisionrrrsubdirectory_fragmentis_existing_dirr hash_namerrr) link source_dirlink_is_in_wheel_cache vcs_backendrr#_rrr,r r r!direct_url_from_link:s:    r2c Cs^|tsdSyt|tStttfk rX}zt dt|j |dSd}~XYnXdS)zObtain a DirectUrl from a pkg_resource.Distribution. Returns None if the distribution has no `direct_url.json` metadata, or if `direct_url.json` is invalid. NzError parsing %s for %s: %s) has_metadatarr from_json get_metadatarr UnicodeDecodeErrorloggerwarning project_name)dister r r!dist_get_direct_urlls r<)NF)loggingpip._internal.models.direct_urlrrrrrrpip._internal.utils.typingrpip._internal.vcsr jsonr ImportError ValueErrortypingr pip._internal.models.linkr Zpip._vendor.pkg_resourcesr getLogger__name__r7r"r2r<r r r r!s         2utils/__pycache__/misc.cpython-37.pyc000064400000061003152352421750013504 0ustar00B Ren@s,ddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZddlmZddlmZddlmZddlmZmZdd lmZmZmZmZmZdd l m!Z"dd l#m$Z%dd l&m'Z'dd l(m)Z)ddl*m+Z+m,Z,m-Z-m.Z.ddl/m0Z0m1Z1m2Z2m3Z3ddl4m5Z5m6Z6ddl7m8Z8m9Z9er`ddlm:Z;n ddlm;Z;e5rddlZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHddlImJZJeFeKeKeKfZLeGdZMdddddddddd d!d"d#d$gZNeOePZQd%d&ZRd'd(ZSd)d"ZTd*d ZUed+d,d-dd/dZVd0d1ZWd2d3ZXd4dZYdd6dZZd7d8Z[d9d:Z\d;dZ]dd?Z_d@dZ`dAdBZadCdZbejcfdDdEZdddGdZedHdZfdIdZgdJdKZhdLdMZidNdOZjdPdQZkdRdSZldTdUZmdFe2dFd.d.dfdVdWZndXdYZodZd[Zpd\d]Zqd^d_Zrd`daZsGdbdcdcetZuGdddedee;ZvejwdfdgZxdhd!ZydidjZzddkd#Z{dldmZ|dndoZ}dpdqZ~ddsdtZdudvZdwdxZdydzZd{d|Zd}d~ZddZddZdd$ZddZGdddetZddZddZddZddZdddZddZddZddZdS))absolute_importN)deque)tee) pkg_resources)canonicalize_name)retry)PY2 text_type)filter filterfalseinputmap zip_longest)parse)unquote) __version__) CommandError)distutils_schemeget_major_minor_version site_packages user_site)WINDOWS expanduser stdlib_pkgsstr_to_display)MYPY_CHECK_RUNNINGcast)running_under_virtualenvvirtualenv_no_global)BytesIO)StringIO) AnyAnyStrCallable ContainerIterableIteratorListOptionalTextTupleTypeVarUnion) DistributionTrmtree display_path backup_dirasksplitext format_sizeis_installable_dirnormalize_pathrenamesget_progcaptured_stdout ensure_dirget_installed_versionremove_auth_from_urlcCs4tjtjtdd}tj|}dt|tS)Nz..zpip {} from {} (python {})) ospathjoindirname__file__abspathformatrr) pip_pkg_dirrE/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/misc.pyget_pip_versionOs rGcCsDt|dkr"|dt|d7}nt|dkr:|dd}td|S)ax Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple can have any length. :return: a tuple of length three if `py_version_info` is non-None. Otherwise, return `py_version_info` unchanged (i.e. None). )rN VersionInfo)lenr)py_version_inforErErFnormalize_version_info[s   rLc CsPyt|Wn<tk rJ}z|jtjkr:|jtjkr:Wdd}~XYnXdS)z os.path.makedirs without EEXIST.N)r=makedirsOSErrorerrnoEEXIST ENOTEMPTY)r>erErErFr:os c CsNy.tjtjd}|dkr(dtjS|SWnttt fk rHYnXdS)Nr)z __main__.pyz-cz {} -m pippip) r=r>basenamesysargvrC executableAttributeError TypeError IndexError)progrErErFr8zs i i)stop_max_delay wait_fixedFcCstj||tddS)N) ignore_errorsonerror)shutilr/rmtree_errorhandler)dirr^rErErFr/sc CsVyt|jtj@ }Wnttfk r0dSX|rPt|tj||dSdS)zOn Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.N)r=statst_modeS_IWRITEIOErrorrNchmod)funcr>exc_infohas_attr_readonlyrErErFrasracCsd|dkr dSt|tr|Sy|td}Wn0tk r^trRtd|}nt |}YnX|S)z Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str paths are already text. Nstrictzb{!r}) isinstancer decoderUgetfilesystemencodingUnicodeDecodeErrorrrrCascii)r>r0rErErFpath_to_displays  rqcCsttjtj|}tjddkrB|td}|t d}| t tjj rpd|t t d}|S)zTGives the display value for a given path, making it relative to cwd if possible.rreplace.N)r=r>normcaserBrU version_informrnencodegetdefaultencoding startswithgetcwdseprJ)r>rErErFr0s.bakcCs:d}|}x(tj||r0|d7}|t|}q W||S)z\Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc))r=r>existsstr)rbextn extensionrErErFr1s cCs2x&tjddD]}||kr|SqWt||S)NPIP_EXISTS_ACTION)r=environgetsplitr2)messageoptionsactionrErErFask_path_existssrcCstjdrtd|dS)z&Raise an error if no input is allowed. PIP_NO_INPUTz7No input was expected ($PIP_NO_INPUT set); question: {}N)r=rr ExceptionrC)rrErErF_check_no_inputs rcCsJxDt|t|}|}||kr>td|d|q|SqWdS)z@Ask the message interactively, with the given possible responsesz>Your response ({!r}) was not one of the expected responses: {}z, N)rr striplowerprintrCr?)rrresponserErErFr2s cCst|t|S)zAsk for input interactively.)rr )rrErErF ask_inputsrcCst|t|S)z!Ask for a password interactively.)rgetpass)rrErErF ask_passwordsrcCs\|dkrd|ddS|dkr4dt|dS|dkrJd|dSdt|SdS) Ni@Bz {:.1f} MBg@@ii'z{} kBz {:.1f} kBz{} bytes)rCint)bytesrErErFr4scs@dd|D}ddt|ddiDfdd|D}|fS)zReturn a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4]) cSsg|]}ttt|qSrE)tupler r).0rowrErErF #sztabulate..cSsg|]}ttt|qSrE)maxr rJ)rcolrErErFr$s fillvaluercs$g|]}dttj|qS) )r?r rljustrstrip)rr)sizesrErFr%s)r)rowstablerE)rrFtabulates rcCsPtj|sdStj|d}tj|r.dStj|d}tj|rLdSdS)zBIs path is a directory containing setup.py or pyproject.toml? Fzsetup.pyTzpyproject.toml)r=r>isdirr?isfile)r>setup_pypyproject_tomlrErErFr5)s   ccs x||}|sP|VqWdS)z7Yield pieces of data from a file-like object until EOF.N)read)filesizechunkrErErF read_chunks8s  rTcCs2t|}|rtj|}n tj|}tj|S)zN Convert a path to its canonical, case-normalized, absolute version. )rr=r>realpathrBru)r>resolve_symlinksrErErFr6As  cCs@t|\}}|dr8|dd|}|dd}||fS)z,Like os.path.splitext, but take off .tar tooz.tarN) posixpathr3rendswith)r>baserrErErFr3Os  cCsztj|\}}|r.|r.tj|s.t|t||tj|\}}|rv|rvyt|Wntk rtYnXdS)z7Like os.renames(), but handles renaming across devices.N) r=r>rr~rMr`move removedirsrN)oldnewheadtailrErErFr7Ys  cCsts dS|ttjS)z Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. T)rryr6rUprefix)r>rErErFis_localks rcCs tt|S)z Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. )r dist_location)distrErErF dist_is_localzs rcCst|ttS)zF Return True if given Distribution is installed in user site. )rryr6r)rrErErFdist_in_usersitesrcCst|ttS)z[ Return True if given Distribution is installed in sysconfig.get_python_lib(). )rryr6r)rrErErFdist_in_site_packagessrcCs,tt|}|ttddddS)zf Return True if given Distribution is installed in path matching distutils_scheme layout. rpurelibpythonr)r6rryrr)r norm_pathrErErFdist_in_install_paths rcCs8x2tjD](}tj||jd}tj|rdSqWdS)zC Return True if given Distribution is an editable install. z .egg-linkTF)rUr>r=r? project_namer)r path_itemegg_linkrErErFdist_is_editables   rcs|rt|}ntj}|r tndd|r6ddndd|rLddndd|r^tnd d fd d |DS) a^ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. If ``user_only`` is True , only report installations in the user site directory. If ``paths`` is set, only report the distributions present at the specified list of locations. cSsdS)NTrE)drErErF local_testsz/get_installed_distributions..local_testcSsdS)NTrE)rrErErF editable_testsz2get_installed_distributions..editable_testcSs t| S)N)r)rrErErFrscSst|S)N)r)rrErErFeditables_only_testsz8get_installed_distributions..editables_only_testcSsdS)NTrE)rrErErFrscSsdS)NTrE)rrErErF user_testsz.get_installed_distributions..user_testcs:g|]2}|r|jkr|r|r|r|qSrE)key)rr)rrrskiprrErFrs  z/get_installed_distributions..)r WorkingSet working_setrr) local_onlyrinclude_editableseditables_only user_onlypathsrrE)rrrrrrFget_installed_distributionss    rcCs4t|}tddddddd}dd|D}||S)zFind a distribution matching the ``req_name`` in the environment. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. FrETN)rrrrrrcSsi|]}|t|jqSrE)rr)rprErErF sz(_search_distribution..)rrr)req_namepackagespkg_dictrErErF_search_distributions rcCs<t|}|s4ytj|Wntjk r2dSXt|S)zGiven a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. N)rrrrequireDistributionNotFound)rrrErErFget_distributions  rcCsxg}tr*|ttsBtrB|tntr8|t|tx0|D](}tj||jd}tj |rH|SqHWdS)a Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packages, then site.USER_SITE (don't look in global location) For #1 and #3, there could be odd cases, where there's an egg-link in 2 locations. This method will just return the first one found. z .egg-linkN) rappendrrrr=r>r?rr)rsitessiteegglinkrErErF egg_link_path$s       rcCst|}|rt|St|jS)aO Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks removed). )rr6location)rrrErErFrHs rcGstj|f|dS)N)loggerinfo)msgargsrErErF write_outputXsrc@s(eZdZdZddZddZddZdS) FakeFilezQWrap a list of lines in an object with readline() to make ConfigParser happy.cCst||_dS)N)iter_gen)selflinesrErErF__init__`szFakeFile.__init__cCs$y t|jStk rdSXdS)Nr)nextr StopIteration)rrErErFreadlinecs zFakeFile.readlinecCs|jS)N)r)rrErErF__iter__iszFakeFile.__iter__N)__name__ __module__ __qualname____doc__rrrrErErErFr]src@s$eZdZeddZeddZdS) StreamWrappercCs ||_|S)N) orig_stream)clsrrErErF from_streamoszStreamWrapper.from_streamcCs|jjS)N)rencoding)rrErErFruszStreamWrapper.encodingN)rrr classmethodrpropertyrrErErErFrms rc cs@tt|}tt|t|ztt|VWdtt||XdS)zReturn a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. N)getattrrUsetattrrr) stream_name orig_stdoutrErErFcaptured_outputzs  rcCstdS)zCapture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello ') Taken from Lib/support/__init__.py in the CPython repo. stdout)rrErErErFr9s cCstdS)z See captured_stdout(). stderr)rrErErErFcaptured_stderrsr cCs4tj|}|dkrt}||}|r0|jSdS)zCGet the installed version of dist_name avoiding pkg_resources cacheN)r Requirementrrfindversion) dist_namerreqrrErErFr;s   cCst|dddS)zConsume an iterable at C speed.r)maxlenN)r)iteratorrErErFconsumesrcOs@tt|tt|f|}dd|D}||d<tdd|S)NcSsi|]\}}||qSrErE)rrvaluerErErFrszenum..reverse_mappingEnumrE)dictziprangerJitemstype) sequentialnamedenumsreverserErErFenumsrcCs*|dkr |Sd|krd|}d||S)z. Build a netloc from a host-port pair N:z[{}]z{}:{})rC)hostportrErErF build_netlocs  r"httpscCs4|ddkr(d|kr(d|kr(d|}d||S)z) Build a full URL from a netloc. rrr@[z[{}]z{}://{})countrC)netlocschemerErErFbuild_url_from_netlocs r)cCst|}t|}|j|jfS)z2 Return the host-port pair from a netloc. )r) urllib_parseurlparsehostnamer!)r'urlparsedrErErF parse_netlocs r/cCsXd|kr|dfS|dd\}}d|kr6|dd}n|df}tdd|D}||fS)zp Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). r$)NNr}rNcss"|]}|dkrdnt|VqdS)N)urllib_unquote)rxrErErF sz)split_auth_from_netloc..)rsplitrr)r'auth user_passrErErFsplit_auth_from_netlocsr6cCsLt|\}\}}|dkr|S|dkr.d}d}nt|}d}dj|||dS)z Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" Nz****rz:****z{user}{password}@{netloc})userpasswordr')r6r*quoterC)r'r7r8rErErF redact_netlocs  r:cCs@t|}||j}|j|d|j|j|jf}t|}||fS)aRTransform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netloc as item 1. r)r*urlsplitr'r(r>queryfragment urlunsplit)r-transform_netlocpurl netloc_tuple url_piecessurlrErErF_transform_urls   rDcCst|S)N)r6)r'rErErF _get_netloc$srEcCs t|fS)N)r:)r'rErErF_redact_netloc(srFcCst|t\}\}}|||fS)z Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) )rDrE)r-url_without_authr'r4rErErFsplit_auth_netloc_from_url,srHcCst|tdS)z7Return a copy of url with 'username:password@' removed.r)rDrE)r-rErErFr<7scCst|tdS)z.Replace the password in a given url with ****.r)rDrF)r-rErErFredact_auth_from_url?srIc@s4eZdZddZddZddZddZd d Zd S) HiddenTextcCs||_||_dS)N)secretredacted)rrKrLrErErFrFszHiddenText.__init__cCsdt|S)Nz)rCr)rrErErF__repr__OszHiddenText.__repr__cCs|jS)N)rL)rrErErF__str__SszHiddenText.__str__cCs t|t|krdS|j|jkS)NF)rrK)rotherrErErF__eq__XszHiddenText.__eq__cCs ||k S)NrE)rrOrErErF__ne__cszHiddenText.__ne__N)rrrrrMrNrPrQrErErErFrJEs   rJcCs t|ddS)Nz****)rL)rJ)rrErErF hide_valuehsrRcCst|}t||dS)N)rL)rIrJ)r-rLrErErFhide_urlmsrScCszddtjddjtjddg}|oBtoBtjtjd|k}|rvtjddgtjd d}t d d |dS) zProtection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... zpip.exez pip{}.exerz pip{}.{}.exeNrrz-mrSr}z3To modify pip, please run the following command: {}r) rCrUrvrr=r>rTrVrWrr?) modifying_pip pip_namesshould_show_use_python_msg new_commandrErErF(protect_pip_from_modification_on_windowsss rXcCstjdk otjS)z!Is this console interactive? N)rUstdinisattyrErErErFis_console_interactivesr[c CsVt}d}t|d2}x*t||dD]}|t|7}||q&WWdQRX||fS)z:Return (hash, length) for path using hashlib.sha256() rrb)rN)hashlibsha256openrrJupdate)r> blocksizehlengthfblockrErErF hash_files  rgcCs&y ddl}Wntk r dSXdS)z8 Return whether the wheel package is installed. rNFT)wheel ImportError)rhrErErFis_wheel_installeds  rjcCst|}t||S)zb Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ... )rr)iterablerErErFpairwisesrlcCs t|\}}t||t||fS)z Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 )rr r )predrkt1t2rErErF partitions rp)F)r|)T)N)r#)r\) __future__r contextlibrOrr^iologgingr=rr`rcrU collectionsr itertoolsr pip._vendorrZpip._vendor.packaging.utilsrpip._vendor.retryingrZpip._vendor.sixrr pip._vendor.six.movesr r r r rZpip._vendor.six.moves.urllibrr*"pip._vendor.six.moves.urllib.parserr0rSrpip._internal.exceptionsrpip._internal.locationsrrrrpip._internal.utils.compatrrrrpip._internal.utils.typingrrpip._internal.utils.virtualenvrrrr typingr!r"r#r$r%r&r'r(r)r*r+r,Zpip._vendor.pkg_resourcesr-rrIr.__all__ getLoggerrrrGrLr:r8r/rarqr0r1rrr2rrr4rr5DEFAULT_BUFFER_SIZErr6r3r7rrrrrrrrrrrrobjectrrcontextmanagerrr9r r;rrr"r)r/r6r:rDrErFrHr<rIrJrRrSrXr[rgrjrlrprErErErFs           8      "          >$      #   utils/__pycache__/models.cpython-37.pyc000064400000003725152352421750014043 0ustar00B Re@s dZddlZGdddeZdS)zUtilities for defining models Nc@s`eZdZdZddgZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ dS)KeyBasedCompareMixinzsutils/__pycache__/distutils_args.cpython-37.pyc000064400000002270152352421750015612 0ustar00B ReF @shddlmZddlmZddlmZer8ddlmZmZddddd d d d d dddg Z ee Z ddZ dS))DistutilsArgError) FancyGetopt)MYPY_CHECK_RUNNING)DictList)z exec-prefix=N)zhome=Nr)z install-base=Nr)z install-data=Nr)zinstall-headers=Nr)z install-lib=Nr)zinstall-platlib=Nr)zinstall-purelib=Nr)zinstall-scripts=Nr)zprefix=Nr)zroot=Nr)userNrc CsNi}xD|D]<}ytj|gd\}}Wntk r8Yq X||jq W|S)z~Parse provided arguments, returning an object that has the matched arguments. Any unknown arguments are ignored. )args)_distutils_getoptgetoptrupdate__dict__)r resultarg_matchr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/distutils_args.pyparse_distutils_argss rN) distutils.errorsrdistutils.fancy_getoptrpip._internal.utils.typingrtypingrr_optionsr rrrrrs$   utils/__pycache__/setuptools_build.cpython-37.pyc000064400000005653152352421750016162 0ustar00B Re@sfddlZddlmZer,ddlmZmZmZdZdddZdd Z d d Z d d Z ddZ ddZ dS)N)MYPY_CHECK_RUNNING)ListOptionalSequencezimport sys, setuptools, tokenize; sys.argv[0] = {0!r}; __file__={0!r};f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))FcCsFtjg}|r|dg7}|dt|g7}|r4||7}|rB|dg7}|S)ao Get setuptools command arguments with shim wrapped setup file invocation. :param setup_py_path: The path to setup.py to be wrapped. :param global_options: Additional global options. :param no_user_config: If True, disables personal user configuration. :param unbuffered_output: If True, adds the unbuffered switch to the argument list. z-uz-cz --no-user-cfg)sys executable_SETUPTOOLS_SHIMformat) setup_py_pathglobal_optionsno_user_configunbuffered_outputargsr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/setuptools_build.pymake_setuptools_shim_argss  rcCs(t||dd}|dd|g7}||7}|S)NT)r r bdist_wheelz-d)r)r r build_optionsdestination_dirrrrr make_setuptools_bdist_wheel_args2s rcCst||dd}|ddg7}|S)NT)r r cleanz--all)r)r r rrrrmake_setuptools_clean_argsGs  rcCsf|r |r tt|||d}|ddg7}||7}|r>|d|g7}|dk rR|d|g7}|rb|ddg7}|S)N)r r developz --no-depsz--prefixz--homez--userz --prefix=)AssertionErrorr)r r install_optionsr prefixhome use_user_siterrrrmake_setuptools_develop_argsUs     rcCs*t||d}|dg7}|r&|d|g7}|S)N)r egg_infoz --egg-base)r)r egg_info_dirr rrrrmake_setuptools_egg_info_argsvs    r!c Cs|r |r t|r|rtt||| dd} | dd|g7} | dg7} |dk rT| d|g7} |dk rh| d|g7} |dk r|| d|g7} |r| d d g7} | r| d g7} n | d g7} |r| d |g7} | |7} | S)NT)r r r installz--recordz#--single-version-externally-managedz--rootz--prefixz--homez--userz --prefix=z --compilez --no-compilez--install-headers)rr) r r rrecord_filenamerootr header_dirrrr pycompilerrrrmake_setuptools_install_argss0          r')NFF)rpip._internal.utils.typingrtypingrrrrrrrrr!r'rrrrs    !utils/__pycache__/parallel.cpython-37.pyc000064400000006143152352421750014351 0ustar00B ReL @s&dZddgZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZerdd lmZmZmZmZmZdd lmZeejejfZed Zed Zy ddlZWnek rdZYnXdZdZeddZdddZdddZ dddZ!ese reZ"Z#ne Z"e!Z#dS)abConvenient parallelization of higher order functions. This module provides two helper functions, with appropriate fallbacks on Python 2 and on systems lacking support for synchronization mechanisms: - map_multiprocess - map_multithread These helpers work like Python 3's map, with two differences: - They don't guarantee the order of processing of the elements of the iterable. - The underlying process/thread pools chop the iterable into a number of chunks, so that for very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. map_multiprocessmap_multithread)contextmanager)Pool)DEFAULT_POOLSIZE)PY2)map)MYPY_CHECK_RUNNING)CallableIterableIteratorUnionTypeVar)poolSTNTFiccs*z |VWd|||XdS)z>Return a context manager making sure the pool closes properly.N)closejoin terminate)rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/parallel.pyclosing4s  rcCs t||S)zMake an iterator applying func to each element in iterable. This function is the sequential fallback either on Python 2 where Pool.imap* doesn't react to KeyboardInterrupt or when sem_open is unavailable. )r)funciterable chunksizerrr _map_fallbackBsrc Cs$tt}||||SQRXdS)zChop iterable into chunks and submit them to a process pool. For very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. Return an unordered iterator of the results. N)r ProcessPoolimap_unordered)rrrrrrr_map_multiprocessMs rc Cs&ttt}||||SQRXdS)zChop iterable into chunks and submit them to a thread pool. For very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. Return an unordered iterator of the results. N)r ThreadPoolrr)rrrrrrr_map_multithreadZs r!)r)r)r)$__doc____all__ contextlibrmultiprocessingrrZmultiprocessing.dummyr Zpip._vendor.requests.adaptersrZpip._vendor.sixrpip._vendor.six.movesrpip._internal.utils.typingr typingr r r r rrrrZmultiprocessing.synchronize ImportErrorZ LACK_SEM_OPENTIMEOUTrrrr!rrrrrrs8             utils/__pycache__/entrypoints.cpython-37.pyc000064400000002545152352421750015155 0ustar00B Re@sBddlZddlmZddlmZer4ddlmZmZdddZdS) N)main)MYPY_CHECK_RUNNING)OptionalListFcCs|stjdt|S)aCentral wrapper for all old entrypoints. Historically pip has had several entrypoints defined. Because of issues arising from PATH, sys.path, multiple Pythons, their interactions, and most of them having a pip installed, users suffer every time an entrypoint gets moved. To alleviate this pain, and provide a mechanism for warning users and directing them to an appropriate place for help, we now define all of our old entrypoints as wrappers for the current one. aWARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. )sysstderrwriter)args_nowarnr /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/entrypoints.py_wrapper s r )NF) rpip._internal.cli.mainrpip._internal.utils.typingrtypingrrr r r r r s   utils/__pycache__/virtualenv.cpython-37.pyc000064400000006421152352421750014753 0ustar00B Rez@sddlmZddlZddlZddlZddlZddlZddlZddlm Z e r\ddl m Z m Z e eZedZddZdd Zd d Zd d ZddZddZddZdS))absolute_importN)MYPY_CHECK_RUNNING)ListOptionalz8include-system-site-packages\s*=\s*(?Ptrue|false)cCstjttdtjkS)znChecks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments. base_prefix)sysprefixgetattrr r /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/virtualenv.py_running_under_venvsr cCs ttdS)zmChecks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv. real_prefix)hasattrrr r r r !_running_under_regular_virtualenvsrcCs tp tS)zGReturn True if we're running inside a virtualenv, False otherwise. )r rr r r r running_under_virtualenv(src CsPtjtjd}y&tj|dd}|SQRXWnt k rJdSXdS)zReads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file. z pyvenv.cfgzutf-8)encodingN) ospathjoinrrioopenread splitlinesIOError)pyvenv_cfg_filefr r r _get_pyvenv_cfg_lines/s rcCsRt}|dkrtddSx0|D](}t|}|dk r"|ddkr"dSq"WdS)aZCheck `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-site-packages = false Additionally, log a warning if accessing the file fails. NzCould not access 'pyvenv.cfg' despite a virtual environment being active. Assuming global site-packages is not accessible in this environment.TvaluefalseF)rloggerwarning#_INCLUDE_SYSTEM_SITE_PACKAGES_REGEXmatchgroup) cfg_linesliner"r r r _no_global_under_venv?s   r&cCs0tjtjtj}tj|d}tj|S)zCheck if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment. zno-global-site-packages.txt)rrdirnameabspathsite__file__rexists) site_mod_dirno_global_site_packages_filer r r #_no_global_under_regular_virtualenv]sr.cCstr tStrtSdS)zMReturns a boolean, whether running in venv with no system site-packages. F)r r&rr.r r r r virtualenv_no_globalks r/) __future__rrloggingrrer)rpip._internal.utils.typingrtypingrr getLogger__name__rcompiler!r rrrr&r.r/r r r r s&     utils/__pycache__/deprecation.cpython-37.pyc000064400000005433152352421750015053 0ustar00B Re @sdZddlmZddlZddlZddlmZddlmZ ddl m Z e rXddl m Z mZdZGd d d eZdadd d Zd dZdddZdS)zN A module that implements tooling to enable easy warnings about deprecations. )absolute_importN)parse) __version__)MYPY_CHECK_RUNNING)AnyOptionalz DEPRECATION: c@s eZdZdS)PipDeprecationWarningN)__name__ __module__ __qualname__r r /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/deprecation.pyrsrcCsZ|dk r$tdk rVt||||||n2t|trDtd}||nt||||||dS)Nzpip._internal.deprecations)_original_showwarning issubclassrlogging getLoggerwarning)messagecategoryfilenamelinenofilelineloggerr r r _showwarning!s   rcCs(tjdtddtdkr$tjatt_dS)NdefaultT)append)warnings simplefilterrr showwarningrr r r r install_warning_logger2sr cCsh|tdf|df|df|dfg}ddd|D}|dk rTttt|krTt|tj|td d dS) aHelper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. z{}z2pip {} will remove support for this functionality.zA possible replacement is {}.zPYou can find discussion regarding this at https://github.com/pypa/pip/issues/{}. css$|]\}}|dk r||VqdS)N)format).0valtemplater r r aszdeprecated..N)r stacklevel)DEPRECATION_MSG_PREFIXjoinrcurrent_versionrrwarn)reason replacementgone_inissue sentencesrr r r deprecated>s r2)NN)N)__doc__ __future__rrrpip._vendor.packaging.versionrpiprr+pip._internal.utils.typingrtypingrrr)Warningrrrr r2r r r r s      utils/__pycache__/subprocess.cpython-37.pyc000064400000013036152352421750014744 0ustar00B Re& @sddlmZddlZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z mZddlmZddlmZmZdd lmZerdd lmZmZmZmZmZmZmZmZeeeefZ d Z!d d Z"ddZ#ddZ$ddZ%dddZ&ddZ'dS))absolute_importN) shlex_quote)SpinnerInterface open_spinner)InstallationError)console_to_strstr_to_display)subprocess_logger) HiddenTextpath_to_display)MYPY_CHECK_RUNNING)AnyCallableIterableListMappingOptionalTextUnionz(----------------------------------------cGs6g}x,|D]$}t|tr$||q ||q W|S)z& Create a CommandArgs object. ) isinstancelistextendappend)args command_argsargr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/subprocess.py make_commands    rcCsddd|DS)z/ Format command arguments for display.  css,|]$}t|trtt|nt|VqdS)N)rr rstr).0rrrr 8sz&format_command_args..)join)rrrrformat_command_args-s r$cCsdd|DS)z= Return the arguments in their raw, unredacted form. cSs g|]}t|tr|jn|qSr)rr secret)r!rrrr Csz'reveal_command_args..r)rrrrreveal_command_args=sr'c CsDt|}t|dd}t|}d|}dj|||t||td}|S)z Create and return the error message to use to log a subprocess error with command output. :param lines: A list of lines, each ending with a newline. z command bytes)desczCommand errored out with exit status {exit_status}: command: {command_display} cwd: {cwd_display} Complete output ({line_count} lines): {output}{divider}) exit_statuscommand_display cwd_display line_countoutputdivider)r$rr r#formatlen LOG_DIVIDER) cmd_argscwdlinesr*commandr+r,r.msgrrrmake_subprocess_output_errorGs   r8FraiseTc  Csd|dkr g}|dkrg}|r*tj} tj} n tj} tj} t| k} | oN|dk } |dkr`t|}| d|tj }|r| |x|D]}| |dqWyBt jt|t jt jt j||d}|jst|jst|jWn:tk r}z| rtd||Wdd}~XYnXg}xRt|j}|s6P|}||d| || r |sdt|q Wz |Wd|jr|jX|jo|j|k}| r|st|r|dn |d|rZ|dkr"| s | r t ||||jd }t!|d "|j|}t#|n8|d kr@t$d ||j|n|d krLnt%d"|d&|S)a Args: show_stdout: if true, use INFO to log the subprocess's stderr and stdout streams. Otherwise, use DEBUG. Defaults to False. extra_ok_returncodes: an iterable of integer return codes that are acceptable, in addition to 0. Defaults to None, which means []. unset_environ: an iterable of environment variable names to unset prior to calling subprocess.Popen(). log_failed_cmd: if false, failed commands are not logged, only raised. NzRunning command %s)stderrstdinstdoutr4envz#Error %s while executing command %s errordoner9)r3r4r5r*zSCommand errored out with exit status {}: {} Check the logs for full command output.warnz$Command "%s" had error code %s in %signorez!Invalid value: on_returncode={!r}r))'r infologgingINFOdebugDEBUGgetEffectiveLevelr$osenvironcopyupdatepop subprocessPopenr'STDOUTPIPEr;AssertionErrorr<close Exceptioncriticalrreadlinerstriprspinwait returncodefinishr8r?r0rwarning ValueErrorr#)cmd show_stdoutr4 on_returncodeextra_ok_returncodes command_desc extra_environ unset_environspinnerlog_failed_cmdlog_subprocess used_levelshowing_subprocess use_spinnerr=nameprocexc all_outputlineproc_had_errorr7exc_msgrrrcall_subprocessqs                      rrcsdfdd }|S)zProvide a subprocess_runner that shows a spinner message. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has an API that matches what's expected by Pep517HookCaller.subprocess_runner. Nc s(t}t||||dWdQRXdS)N)r4rcre)rrr)r^r4rcre)messagerrrunner s  z+runner_with_spinner_message..runner)NNr)rsrtr)rsrrunner_with_spinner_messages  ru) FNr9NNNNNT)( __future__rrDrIrNpip._vendor.six.movesrpip._internal.cli.spinnersrrpip._internal.exceptionsrpip._internal.utils.compatrrpip._internal.utils.loggingr pip._internal.utils.miscr r pip._internal.utils.typingr typingr rrrrrrrr Z CommandArgsr2rr$r'r8rrrurrrrs:     ( , utils/__pycache__/__init__.cpython-37.pyc000064400000000342152352421750014307 0ustar00B Re@sdS)Nrrr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/__init__.pyutils/__pycache__/logging.cpython-37.pyc000064400000022001152352421750014172 0ustar00B Re%3@sddlmZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z ddl m Z ddlmZddlmZy ddlZWnek rddlZYnXyddlmZWnek rdZYnXdd lmZeZeZe d ZGd d d eZe r e rd dZnddZne r0ddZnddZej d%ddZ!ddZ"Gdddej#Z$ddZ%Gdddej&Z'Gdddej(j)Z*Gdd d eZ+Gd!d"d"eZ,d#d$Z-dS)&)absolute_importN)Filter getLogger)PY2)WINDOWS)DEPRECATION_MSG_PREFIX) ensure_dir)colorama)Forezpip.subprocessorc@seZdZdZdS)BrokenStdoutLoggingErrorzO Raised if BrokenPipeError occurs for the stdout stream while logging. N)__name__ __module__ __qualname____doc__rr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/logging.pyr :sr cCs|tko|jtjtjfkS)z1See the docstring for non-Windows Python 3 below.)IOErrorerrnoEINVALEPIPE) exc_classexcrrr_is_broken_pipe_errorHsrcCs"|tkp |tko |jtjtjfkS)z1See the docstring for non-Windows Python 3 below.)BrokenPipeErrorOSErrorrrr)rrrrrrNscCs|tko|jtjkS)z1See the docstring for non-Windows Python 3 below.)rrr)rrrrrrTscCs|tkS)z Return whether an exception is a broken pipe error. Args: exc_class: an exception class. exc: an exception instance. )r)rrrrrrYsc cs6tt_tj|7_z dVWdtj|8_XdS)zv A context manager which will cause the log output to be indented for any log messages emitted inside it. N)get_indentation _log_state indentation)numrrr indent_logds  r cCs ttddS)Nrr)getattrrrrrrrssrcs0eZdZfddZddZfddZZS)IndentingFormattercs$|dd|_tt|j||dS)z A logging.Formatter that obeys the indent_log() context manager. :param add_timestamp: A bool indicating output lines should be prefixed with their record's timestamp. add_timestampFN)popr#superr"__init__)selfargskwargs) __class__rrr&yszIndentingFormatter.__init__cCs.|tjkrdS|trdS|tjkr*dSdS)zv Return the start of the formatted log message (not counting the prefix to add to each line). z WARNING: zERROR: )loggingWARNING startswithrERROR)r' formattedlevelnorrrget_message_starts   z$IndentingFormatter.get_message_startcsztt||}|||j}||}d|jrJ||d}djftdt7d fdd| dD}|S)z Calls the standard formatter, but will indent all of the log message lines by our current indentation level. r+z%Y-%m-%dT%H:%M:%Sz{t},{record.msecs:03.0f}  csg|] }|qSrr).0line)prefixrr sz-IndentingFormatter.format..T) r%r"formatr2r1r# formatTimelocalsrjoin splitlines)r'recordr0 message_startt)r*)r6rr8s  zIndentingFormatter.format)r r rr&r2r8 __classcell__rr)r*rr"ws r"csfdd}|S)Ncsdt|tjjgS)Nr+)r;listr Style RESET_ALL)inp)colorsrrwrappedsz_color_wrap..wrappedr)rErFr)rEr _color_wraps rGcsheZdZer.ejeejfej eej fgZ ngZ d ddZ ddZ ddZdd Zfd d ZZS) ColorizedStreamHandlerNcCs.tj||||_tr*tr*t|j|_dS)N)r, StreamHandlerr& _no_colorrr AnsiToWin32stream)r'rLno_colorrrrr&szColorizedStreamHandler.__init__cCs"trtr|jjtjkS|jtjkS)zA Return whether the handler is using sys.stdout. )rr rLrFsysstdout)r'rrr _using_stdoutsz$ColorizedStreamHandler._using_stdoutcCsXtr |jrdSt|jtjs"|jn|jj}t|dr@|r@dStj ddkrTdSdS)NFisattyTTERMANSI) r rJ isinstancerLrKrFhasattrrQosenvironget)r' real_streamrrr should_colors z#ColorizedStreamHandler.should_colorcCsBtj||}|r>x&|jD]\}}|j|kr||}PqW|S)N)r,rIr8rZCOLORSr1)r'r=msglevelcolorrrrr8s zColorizedStreamHandler.formatcs@tdd\}}|r0|r0t||r0ttt||S)Nr)rNexc_inforPrr r%rH handleError)r'r=rr)r*rrr`s   z"ColorizedStreamHandler.handleError)NN)r r rr r,r/rGr REDr-YELLOWr[r&rPrZr8r`r@rr)r*rrHs   rHc@seZdZddZdS)BetterRotatingFileHandlercCs ttj|jtjj|S)N) rrVpathdirname baseFilenamer,handlersRotatingFileHandler_open)r'rrrriszBetterRotatingFileHandler._openN)r r rrirrrrrcsrcc@seZdZddZddZdS)MaxLevelFiltercCs ||_dS)N)r])r'r]rrrr&szMaxLevelFilter.__init__cCs |j|jkS)N)r1r])r'r=rrrfilterszMaxLevelFilter.filterN)r r rr&rkrrrrrjsrjcs eZdZdZfddZZS)ExcludeLoggerFilterzQ A logging Filter that excludes records from a logger (or its children). cstt|| S)N)r%rlrk)r'r=)r*rrrkszExcludeLoggerFilter.filter)r r rrrkr@rr)r*rrl srlc Csf|dkrd}n.|dkrd}n |dkr*d}n|dkr8d}nd }tt|}|d k }|r\|}d}nd }|}|d krpdnd}d dd} ddd} dddg|rdgng} tjdddtjddtjddtjddtddtdd d!d"|| d#|| d$d%d&gd'd(d| d#|| d)d%gd'd(|| d#|| d)d*gd'd(d| d+|d d,d-d.|| d/d0d1|iid2|S)3znConfigures and sets up all of the logging Returns the requested logging level, as its integer value. DEBUGr-r/CRITICALINFONz /dev/null)rsr/zext://sys.stdoutzext://sys.stderr)rOstderrz2pip._internal.utils.logging.ColorizedStreamHandlerz5pip._internal.utils.logging.BetterRotatingFileHandler)rLfileconsoleconsole_errorsconsole_subprocessuser_logFz*pip._internal.utils.logging.MaxLevelFilter)z()r]zlogging.Filter)z()namez/pip._internal.utils.logging.ExcludeLoggerFilter)exclude_warningsrestrict_to_subprocessexclude_subprocessz %(message)s)z()r8T)z()r8r#)indentindent_with_timestamprLrOr}r{r~)r]classrMrLfilters formatterrtr|rur)r]rfilenamedelayr)rvrwrxry)r]rgz pip._vendorr])versiondisable_existing_loggersr formattersrgrootloggers)r!r,config dictConfigr-subprocess_loggerrzr") verbosityrM user_log_filer] level_numberinclude_user_logadditional_log_file root_levelvendored_log_level log_streamshandler_classesrgrrr setup_loggings    r)r). __future__r contextlibrr,logging.handlersrVrNrrZpip._vendor.sixrpip._internal.utils.compatrpip._internal.utils.deprecationrpip._internal.utils.miscr threading ImportErrorZdummy_threading pip._vendorr _colorama ExceptionZpip._vendor.coloramar localrrr rcontextmanagerr r Formatterr"rGrIrHrgrhrcrjrlrrrrrsR              2K  utils/__pycache__/unpacking.cpython-37.pyc000064400000014544152352421750014540 0ustar00B Re%@stdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z mZmZddlmZddlmZerddlmZmZmZmZmZdd lmZeeZee ZyddlZee 7ZWne k re!d YnXyddl"Z"ee7ZWn e k r"e!d YnXd d Z#ddZ$ddZ%ddZ&ddZ'ddZ(dddZ)ddZ*d ddZ+dS)!zUtilities related archives. )absolute_importN)InstallationError)BZ2_EXTENSIONSTAR_EXTENSIONS XZ_EXTENSIONSZIP_EXTENSIONS) ensure_dir)MYPY_CHECK_RUNNING)IterableListOptionalTextUnion)ZipInfozbz2 module is not availablezlzma module is not availablecCstd}t||S)zBGet the current umask which involves having to set it temporarily.r)osumask)maskr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/unpacking.py current_umask/s  rcCsh|dd}d|krHd|kr4|d|dkslocationflattenzipfpzipleadingr3namefndirmessagefpdestfprrr unzip_filets4         rQc Cs$t||ds$|dr*d}nL|tr>d}n8|trRd}n$|drfd}ntd|d }t||}zt d d | D}xr| D]d}|j }|rt |d }t j||}t||sd }t|||||rt|q|r\y|||Wn8tk rX} ztd||j | wWdd} ~ XYnXqy||} Wn<ttfk r} ztd||j | wWdd} ~ XYnXtt j|| dk stt|d} t| | WdQRX| ||||j d@rt!|qWWd|XdS)a Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. z.gzz.tgzzr:gzzr:bz2zr:xzz.tarrz-Cannot determine compression type for file %szr:*cSsg|] }|jqSr)rK).0memberrrr szuntar_file..rzQThe tar file ({}) has a file ({}) trying to install outside target directory ({})z/In the tar file %s the member %s is invalid: %sNr8r+)"rlowerrBrrloggerwarningtarfiler9r# getmembersrKrrrr?r*rrAisdirissym_extract_member Exception extractfileKeyErrorAttributeErrorr@AssertionErrorrCrDrEutimer4r-) r>rFr4tarrJrTrLrrNexcrOrPrrr untar_filesf            rfcCstj|}|dks,|ts,t|rDt|||d dnR|dkslt |sl|t t t rxt||ntd|||td|dS)Nzapplication/zipz.whl)rGzapplication/x-gzipzZCannot unpack file %s (downloaded from %s, content-type: %s); cannot detect archive formatz%Cannot determine archive format of {})rrrealpathrVrBrr: is_zipfilerQrY is_tarfilerrrrfrWcriticalrrA)r>rF content_typerrr unpack_files$     rl)T)N),__doc__ __future__rloggingrrCr1rYr:pip._internal.exceptionsrpip._internal.utils.filetypesrrrrpip._internal.utils.miscrpip._internal.utils.typingr typingr r r r rr getLogger__name__rWSUPPORTED_EXTENSIONSbz2 ImportErrordebuglzmarrr#r*r-r5rQrfrlrrrrsF           /Vutils/__pycache__/compatibility_tags.cpython-37.pyc000064400000006752152352421750016452 0ustar00B Re?@sdZddlmZddlZddlmZmZmZmZm Z m Z m Z ddl m Z e rlddlmZmZmZddlmZedZd d Zd d Zd dZddZddZdddZdddZdS)z3Generate and work with PEP 425 Compatibility Tags. )absolute_importN)Tagcompatible_tags cpython_tags generic_tagsinterpreter_nameinterpreter_version mac_platforms)MYPY_CHECK_RUNNING)ListOptionalTuple) PythonVersionz(.+)_(\d+)_(\d+)_(.+)cCsdtt|ddS)N)joinmapstr) version_infor/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/compatibility_tags.pyversion_info_to_nodotsrcsRt|}|rH|\}}}t|t|f}fddt||D}n|g}|S)Ncs$g|]}d|tddqS)z{}_{}macosx_N)formatlen).0arch)namerr .sz"_mac_platforms..) _osx_arch_patmatchgroupsintr )rr majorminor actual_arch mac_versionarchesr)rr_mac_platforms"s  r(cCsj|g}|d\}}}|dkrL|dkrf|d|||d||n|dkrf|d|||S)N_ manylinux2014>i686x86_64 manylinux2010 manylinux1) partitionappend)rr' arch_prefixarch_sep arch_suffixrrr_custom_manylinux_platforms7sr4cCs@|d\}}}|dr$t|}n|dkr6t|}n|g}|S)Nr)macosx)r*r-)r/ startswithr(r4)rr1r2r3r'rrr_get_custom_platformsMs   r7cCs:t|dkr(t|dt|ddfSt|dfSdS)Nr)rr")versionrrr_get_python_versionYs r:cCs(|dkrt}|dkrt}d||S)Nz{}{})rrr)implementationr9rrr_get_custom_interpreteras r<c Csg}d}|dk rt|}t||}d}|dk r4|g}d}|dk rHt|}|pPtdk} | rp|t|||dn|t|||d|t|||d|S)aSReturn a list of supported tags for each version specified in `versions`. :param version: a string version, of the form "33" or "32", or None. The version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. Ncp)python_versionabis platforms) interpreterr?r@)r>rAr@)r:r<r7rextendrrr) r9platformimplabi supportedr>rAr?r@ is_cpythonrrr get_supportedjs:    rH)NN)NNNN)__doc__ __future__rrepip._vendor.packaging.tagsrrrrrrr pip._internal.utils.typingr typingr r r rcompilerrr(r4r7r:r<rHrrrrs$ $     utils/__pycache__/filetypes.cpython-37.pyc000064400000001161152352421750014554 0ustar00B Re;@sLdZddlmZer ddlmZdZdZdZdefZdZ eee eZ d S) zFiletype information. )MYPY_CHECK_RUNNING)Tuplez.whl)z.tar.bz2z.tbz)z.tar.xzz.txzz.tlzz.tar.lzz .tar.lzmaz.zip)z.tar.gzz.tgzz.tarN) __doc__pip._internal.utils.typingrtypingrWHEEL_EXTENSIONBZ2_EXTENSIONS XZ_EXTENSIONSZIP_EXTENSIONSTAR_EXTENSIONSARCHIVE_EXTENSIONSr r /builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/filetypes.pys  utils/__pycache__/typing.cpython-37.pyc000064400000002740152352421750014066 0ustar00B Rey@s&dZdZerddlmZnddZdS)aBFor neatly implementing static typing in pip. `mypy` - the static type analysis tool we use - uses the `typing` module, which provides core functionality fundamental to mypy's functioning. Generally, `typing` would be imported at runtime and used in that fashion - it acts as a no-op at runtime and does not have any run-time overhead by design. As it turns out, `typing` is not vendorable - it uses separate sources for Python 2/Python 3. Thus, this codebase can not expect it to be present. To work around this, mypy allows the typing import to be behind a False-y optional to prevent it from running at runtime and type-comments can be used to remove the need for the types to be accessible directly during runtime. This module provides the False-y guard in a nicely named fashion so that a curious maintainer can reach here to read this. In pip, all static-typing related imports should be guarded as follows: from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import ... Ref: https://github.com/python/mypy/issues/3216 F)castcCs|S)N)type_valuerr/builddir/build/BUILDROOT/alt-python37-pip-20.2.4-6.el8.x86_64/opt/alt/python37/lib/python3.7/site-packages/pip/_internal/utils/typing.pyr%srN)__doc__MYPY_CHECK_RUNNINGtypingrrrrrsutils/__pycache__/compat.cpython-37.pyc000064400000015205152352421750014037 0ustar00B Re% @s4dZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z m Z ddlmZerddlmZmZmZmZmZmZmZedZGdd d eZy ddlZWnVek r ydd lmZWn.ek rddlZeje_ej e_!YnXYnXd d d dddddgZ"e#e$Z%e rhddl&Z&y e&j'Z'Wne(k r\dZ'YnXe'dk Z)ndZ)ddl*m'Z'e rddZ+e,de+dZ-ndZ-ddZ.d-ddZ/dd Z0ddZ1dd Z2d!d"d#hZ3e j45d$pe j4d%koej6d&kZ7d'dZ8e9e drd(dZ:nd)dZ:d.d*d+Z;eIsz-backslashreplace_decode_fn..css|]}t|VqdS)N)ord)r#brrrr&Ksz\x{:x})rangestartendjoinmapformat)r%Z raw_bytesr)r%rbackslashreplace_decode_fnHsr0backslashreplace_decodebackslashreplacecCs2y ddl}dStk r YnXddlm}|S)NrT) IS_PYOPENSSL)_ssl ImportErrorpip._vendor.urllib3.utilr3)r4r3rrrhas_tlsVs r7cCst|tr|St}|r*t|jdkr.d}y||}Wn4tk rpt d|pXd||j|t d}YnXt t t dddd}|r|j|d d}||}|S) a For display or logging purposes, convert a bytes object (or text) to text (e.g. unicode in Python 2) safe for output. :param desc: An optional phrase describing the input data, for use in the log message if a warning is logged. Defaults to "Bytes object". This function should never error out and so can take a best effort approach. It is okay to be lossy if needed since the return value is just for display. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. asciizutf-8z&%s does not appear to be encoded as %sz Bytes object)errors __stderr__Nencodingr2) isinstancerlocalegetpreferredencodingcodecslookupnamedecodeUnicodeDecodeErrorloggerwarningr1getattrsysencode)datadescr; decoded_dataoutput_encodingoutput_encodedrrrstr_to_displaybs*   rNcCs t|ddS)zProvide an alternative for os.path.samefile on Windows/Python2rN)rPrQrWrnormcaseabspath)file1file2path1path2rrrrs  cCs ttS)z Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. )tupleshutilr rrrrr scCsdd}|dp|dp|d}|sltjdkrly(tttj}||}t|Wntk rjYnX|stj ddtj d d f}t |dt |dfS) z Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. cSsZy4ddl}ddl}ddl}|d|||jd}Wntk rHdSX|dkrVdS|S)NrhhZ12345678)rr)fcntltermiosstruct unpack_fromZioctl TIOCGWINSZ Exception)r[rprqrrcrrrr ioctl_GWINSZsz'get_terminal_size..ioctl_GWINSZrr]win32LINESCOLUMNSP) rGplatformrQrRctermidrSrVruenvirongetint)rwrvr[rrrr s cCs dd}|S)NcSs|S)Nr)frrr_wrappersz noop_lru_cache.._wrapperr)rrrrrnoop_lru_cachesr lru_cache)N)N)>__doc__ __future__rrr? functoolsr=loggingrQrnrGZpip._vendor.sixrrpip._internal.utils.typingrtypingrrr r r r r rrrr5 pip._vendoripaddrZ IPAddress ip_addressZ IPNetwork ip_network__all__ getLoggerrrDimpr!AttributeErrorrimportlib.utilr0register_errorr1r7rNrrr^rr~r_rArrrPr rrFrrrrrsp $       C   $ utils/compatibility_tags.py000064400000012477152352421750012166 0ustar00"""Generate and work with PEP 425 Compatibility Tags. """ from __future__ import absolute_import import re from pip._vendor.packaging.tags import ( Tag, compatible_tags, cpython_tags, generic_tags, interpreter_name, interpreter_version, mac_platforms, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import List, Optional, Tuple from pip._vendor.packaging.tags import PythonVersion _osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)') def version_info_to_nodot(version_info): # type: (Tuple[int, ...]) -> str # Only use up to the first two numbers. return ''.join(map(str, version_info[:2])) def _mac_platforms(arch): # type: (str) -> List[str] match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() mac_version = (int(major), int(minor)) arches = [ # Since we have always only checked that the platform starts # with "macosx", for backwards-compatibility we extract the # actual prefix provided by the user in case they provided # something like "macosxcustom_". It may be good to remove # this as undocumented or deprecate it in the future. '{}_{}'.format(name, arch[len('macosx_'):]) for arch in mac_platforms(mac_version, actual_arch) ] else: # arch pattern didn't match (?!) arches = [arch] return arches def _custom_manylinux_platforms(arch): # type: (str) -> List[str] arches = [arch] arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch_prefix == 'manylinux2014': # manylinux1/manylinux2010 wheels run on most manylinux2014 systems # with the exception of wheels depending on ncurses. PEP 599 states # manylinux1/manylinux2010 wheels should be considered # manylinux2014 wheels: # https://www.python.org/dev/peps/pep-0599/#backwards-compatibility-with-manylinux2010-wheels if arch_suffix in {'i686', 'x86_64'}: arches.append('manylinux2010' + arch_sep + arch_suffix) arches.append('manylinux1' + arch_sep + arch_suffix) elif arch_prefix == 'manylinux2010': # manylinux1 wheels run on most manylinux2010 systems with the # exception of wheels depending on ncurses. PEP 571 states # manylinux1 wheels should be considered manylinux2010 wheels: # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels arches.append('manylinux1' + arch_sep + arch_suffix) return arches def _get_custom_platforms(arch): # type: (str) -> List[str] arch_prefix, arch_sep, arch_suffix = arch.partition('_') if arch.startswith('macosx'): arches = _mac_platforms(arch) elif arch_prefix in ['manylinux2014', 'manylinux2010']: arches = _custom_manylinux_platforms(arch) else: arches = [arch] return arches def _get_python_version(version): # type: (str) -> PythonVersion if len(version) > 1: return int(version[0]), int(version[1:]) else: return (int(version[0]),) def _get_custom_interpreter(implementation=None, version=None): # type: (Optional[str], Optional[str]) -> str if implementation is None: implementation = interpreter_name() if version is None: version = interpreter_version() return "{}{}".format(implementation, version) def get_supported( version=None, # type: Optional[str] platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Tag] """Return a list of supported tags for each version specified in `versions`. :param version: a string version, of the form "33" or "32", or None. The version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # type: List[Tag] python_version = None # type: Optional[PythonVersion] if version is not None: python_version = _get_python_version(version) interpreter = _get_custom_interpreter(impl, version) abis = None # type: Optional[List[str]] if abi is not None: abis = [abi] platforms = None # type: Optional[List[str]] if platform is not None: platforms = _get_custom_platforms(platform) is_cpython = (impl or interpreter_name()) == "cp" if is_cpython: supported.extend( cpython_tags( python_version=python_version, abis=abis, platforms=platforms, ) ) else: supported.extend( generic_tags( interpreter=interpreter, abis=abis, platforms=platforms, ) ) supported.extend( compatible_tags( python_version=python_version, interpreter=interpreter, platforms=platforms, ) ) return supported utils/entrypoints.py000064400000002303152352421750010660 0ustar00import sys from pip._internal.cli.main import main from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Optional, List def _wrapper(args=None, _nowarn=False): # type: (Optional[List[str]]) -> int """Central wrapper for all old entrypoints. Historically pip has had several entrypoints defined. Because of issues arising from PATH, sys.path, multiple Pythons, their interactions, and most of them having a pip installed, users suffer every time an entrypoint gets moved. To alleviate this pain, and provide a mechanism for warning users and directing them to an appropriate place for help, we now define all of our old entrypoints as wrappers for the current one. """ if not _nowarn: sys.stderr.write( "WARNING: pip is being invoked by an old script wrapper. This will " "fail in a future version of pip.\n" "Please see https://github.com/pypa/pip/issues/5599 for advice on " "fixing the underlying issue.\n" "To avoid this problem you can invoke Python with '-m pip' instead of " "running pip directly.\n" ) return main(args) utils/datetime.py000064400000000447152352421750010065 0ustar00"""For when pip wants to check the date or time. """ from __future__ import absolute_import import datetime def today_is_later_than(year, month, day): # type: (int, int, int) -> bool today = datetime.date.today() given = datetime.date(year, month, day) return today > given utils/pkg_resources.py000064400000002346152352421750011144 0ustar00from pip._vendor.pkg_resources import yield_lines from pip._vendor.six import ensure_str from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict, Iterable, List class DictMetadata(object): """IMetadataProvider that reads metadata files from a dictionary. """ def __init__(self, metadata): # type: (Dict[str, bytes]) -> None self._metadata = metadata def has_metadata(self, name): # type: (str) -> bool return name in self._metadata def get_metadata(self, name): # type: (str) -> str try: return ensure_str(self._metadata[name]) except UnicodeDecodeError as e: # Mirrors handling done in pkg_resources.NullProvider. e.reason += " in {} file".format(name) raise def get_metadata_lines(self, name): # type: (str) -> Iterable[str] return yield_lines(self.get_metadata(name)) def metadata_isdir(self, name): # type: (str) -> bool return False def metadata_listdir(self, name): # type: (str) -> List[str] return [] def run_script(self, script_name, namespace): # type: (str, str) -> None pass utils/wheel.py000064400000016207152352421750007376 0ustar00"""Support functions for working with wheel files. """ from __future__ import absolute_import import logging from email.parser import Parser from zipfile import ZipFile from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import DistInfoDistribution from pip._vendor.six import PY2, ensure_str from pip._internal.exceptions import UnsupportedWheel from pip._internal.utils.pkg_resources import DictMetadata from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from email.message import Message from typing import Dict, Tuple from pip._vendor.pkg_resources import Distribution if PY2: from zipfile import BadZipfile as BadZipFile else: from zipfile import BadZipFile VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) class WheelMetadata(DictMetadata): """Metadata provider that maps metadata decoding exceptions to our internal exception type. """ def __init__(self, metadata, wheel_name): # type: (Dict[str, bytes], str) -> None super(WheelMetadata, self).__init__(metadata) self._wheel_name = wheel_name def get_metadata(self, name): # type: (str) -> str try: return super(WheelMetadata, self).get_metadata(name) except UnicodeDecodeError as e: # Augment the default error with the origin of the file. raise UnsupportedWheel( "Error decoding metadata for {}: {}".format( self._wheel_name, e ) ) def pkg_resources_distribution_for_wheel(wheel_zip, name, location): # type: (ZipFile, str, str) -> Distribution """Get a pkg_resources distribution given a wheel. :raises UnsupportedWheel: on any errors """ info_dir, _ = parse_wheel(wheel_zip, name) metadata_files = [ p for p in wheel_zip.namelist() if p.startswith("{}/".format(info_dir)) ] metadata_text = {} # type: Dict[str, bytes] for path in metadata_files: # If a flag is set, namelist entries may be unicode in Python 2. # We coerce them to native str type to match the types used in the rest # of the code. This cannot fail because unicode can always be encoded # with UTF-8. full_path = ensure_str(path) _, metadata_name = full_path.split("/", 1) try: metadata_text[metadata_name] = read_wheel_metadata_file( wheel_zip, full_path ) except UnsupportedWheel as e: raise UnsupportedWheel( "{} has an invalid wheel, {}".format(name, str(e)) ) metadata = WheelMetadata(metadata_text, location) return DistInfoDistribution( location=location, metadata=metadata, project_name=name ) def parse_wheel(wheel_zip, name): # type: (ZipFile, str) -> Tuple[str, Message] """Extract information from the provided wheel, ensuring it meets basic standards. Returns the name of the .dist-info directory and the parsed WHEEL metadata. """ try: info_dir = wheel_dist_info_dir(wheel_zip, name) metadata = wheel_metadata(wheel_zip, info_dir) version = wheel_version(metadata) except UnsupportedWheel as e: raise UnsupportedWheel( "{} has an invalid wheel, {}".format(name, str(e)) ) check_compatibility(version, name) return info_dir, metadata def wheel_dist_info_dir(source, name): # type: (ZipFile, str) -> str """Returns the name of the contained .dist-info directory. Raises AssertionError or UnsupportedWheel if not found, >1 found, or it doesn't match the provided name. """ # Zip file path separators must be / subdirs = set(p.split("/", 1)[0] for p in source.namelist()) info_dirs = [s for s in subdirs if s.endswith('.dist-info')] if not info_dirs: raise UnsupportedWheel(".dist-info directory not found") if len(info_dirs) > 1: raise UnsupportedWheel( "multiple .dist-info directories found: {}".format( ", ".join(info_dirs) ) ) info_dir = info_dirs[0] info_dir_name = canonicalize_name(info_dir) canonical_name = canonicalize_name(name) if not info_dir_name.startswith(canonical_name): raise UnsupportedWheel( ".dist-info directory {!r} does not start with {!r}".format( info_dir, canonical_name ) ) # Zip file paths can be unicode or str depending on the zip entry flags, # so normalize it. return ensure_str(info_dir) def read_wheel_metadata_file(source, path): # type: (ZipFile, str) -> bytes try: return source.read(path) # BadZipFile for general corruption, KeyError for missing entry, # and RuntimeError for password-protected files except (BadZipFile, KeyError, RuntimeError) as e: raise UnsupportedWheel( "could not read {!r} file: {!r}".format(path, e) ) def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message """Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel. """ path = "{}/WHEEL".format(dist_info_dir) # Zip file path separators must be / wheel_contents = read_wheel_metadata_file(source, path) try: wheel_text = ensure_str(wheel_contents) except UnicodeDecodeError as e: raise UnsupportedWheel("error decoding {!r}: {!r}".format(path, e)) # FeedParser (used by Parser) does not raise any exceptions. The returned # message may have .defects populated, but for backwards-compatibility we # currently ignore them. return Parser().parsestr(wheel_text) def wheel_version(wheel_data): # type: (Message) -> Tuple[int, ...] """Given WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel. """ version_text = wheel_data["Wheel-Version"] if version_text is None: raise UnsupportedWheel("WHEEL is missing Wheel-Version") version = version_text.strip() try: return tuple(map(int, version.split('.'))) except ValueError: raise UnsupportedWheel("invalid Wheel-Version: {!r}".format(version)) def check_compatibility(version, name): # type: (Tuple[int, ...], str) -> None """Raises errors or warns if called with an incompatible Wheel-Version. pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "{}'s Wheel-Version ({}) is not compatible with this version " "of pip".format(name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) utils/distutils_args.py000064400000002506152352421750011327 0ustar00from distutils.errors import DistutilsArgError from distutils.fancy_getopt import FancyGetopt from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Dict, List _options = [ ("exec-prefix=", None, ""), ("home=", None, ""), ("install-base=", None, ""), ("install-data=", None, ""), ("install-headers=", None, ""), ("install-lib=", None, ""), ("install-platlib=", None, ""), ("install-purelib=", None, ""), ("install-scripts=", None, ""), ("prefix=", None, ""), ("root=", None, ""), ("user", None, ""), ] # typeshed doesn't permit Tuple[str, None, str], see python/typeshed#3469. _distutils_getopt = FancyGetopt(_options) # type: ignore def parse_distutils_args(args): # type: (List[str]) -> Dict[str, str] """Parse provided arguments, returning an object that has the matched arguments. Any unknown arguments are ignored. """ result = {} for arg in args: try: _, match = _distutils_getopt.getopt(args=[arg]) except DistutilsArgError: # We don't care about any other options, which here may be # considered unrecognized since our option list is not # exhaustive. pass else: result.update(match.__dict__) return result utils/parallel.py000064400000006514152352421750010066 0ustar00"""Convenient parallelization of higher order functions. This module provides two helper functions, with appropriate fallbacks on Python 2 and on systems lacking support for synchronization mechanisms: - map_multiprocess - map_multithread These helpers work like Python 3's map, with two differences: - They don't guarantee the order of processing of the elements of the iterable. - The underlying process/thread pools chop the iterable into a number of chunks, so that for very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. """ __all__ = ['map_multiprocess', 'map_multithread'] from contextlib import contextmanager from multiprocessing import Pool as ProcessPool from multiprocessing.dummy import Pool as ThreadPool from pip._vendor.requests.adapters import DEFAULT_POOLSIZE from pip._vendor.six import PY2 from pip._vendor.six.moves import map from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import Callable, Iterable, Iterator, Union, TypeVar from multiprocessing import pool Pool = Union[pool.Pool, pool.ThreadPool] S = TypeVar('S') T = TypeVar('T') # On platforms without sem_open, multiprocessing[.dummy] Pool # cannot be created. try: import multiprocessing.synchronize # noqa except ImportError: LACK_SEM_OPEN = True else: LACK_SEM_OPEN = False # Incredibly large timeout to work around bpo-8296 on Python 2. TIMEOUT = 2000000 @contextmanager def closing(pool): # type: (Pool) -> Iterator[Pool] """Return a context manager making sure the pool closes properly.""" try: yield pool finally: # For Pool.imap*, close and join are needed # for the returned iterator to begin yielding. pool.close() pool.join() pool.terminate() def _map_fallback(func, iterable, chunksize=1): # type: (Callable[[S], T], Iterable[S], int) -> Iterator[T] """Make an iterator applying func to each element in iterable. This function is the sequential fallback either on Python 2 where Pool.imap* doesn't react to KeyboardInterrupt or when sem_open is unavailable. """ return map(func, iterable) def _map_multiprocess(func, iterable, chunksize=1): # type: (Callable[[S], T], Iterable[S], int) -> Iterator[T] """Chop iterable into chunks and submit them to a process pool. For very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. Return an unordered iterator of the results. """ with closing(ProcessPool()) as pool: return pool.imap_unordered(func, iterable, chunksize) def _map_multithread(func, iterable, chunksize=1): # type: (Callable[[S], T], Iterable[S], int) -> Iterator[T] """Chop iterable into chunks and submit them to a thread pool. For very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1. Return an unordered iterator of the results. """ with closing(ThreadPool(DEFAULT_POOLSIZE)) as pool: return pool.imap_unordered(func, iterable, chunksize) if LACK_SEM_OPEN or PY2: map_multiprocess = map_multithread = _map_fallback else: map_multiprocess = _map_multiprocess map_multithread = _map_multithread utils/direct_url_helpers.py000064400000010407152352421750012144 0ustar00import logging from pip._internal.models.direct_url import ( DIRECT_URL_METADATA_NAME, ArchiveInfo, DirectUrl, DirectUrlValidationError, DirInfo, VcsInfo, ) from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.vcs import vcs try: from json import JSONDecodeError except ImportError: # PY2 JSONDecodeError = ValueError # type: ignore if MYPY_CHECK_RUNNING: from typing import Optional from pip._internal.models.link import Link from pip._vendor.pkg_resources import Distribution logger = logging.getLogger(__name__) def direct_url_as_pep440_direct_reference(direct_url, name): # type: (DirectUrl, str) -> str """Convert a DirectUrl to a pip requirement string.""" direct_url.validate() # if invalid, this is a pip bug requirement = name + " @ " fragments = [] if isinstance(direct_url.info, VcsInfo): requirement += "{}+{}@{}".format( direct_url.info.vcs, direct_url.url, direct_url.info.commit_id ) elif isinstance(direct_url.info, ArchiveInfo): requirement += direct_url.url if direct_url.info.hash: fragments.append(direct_url.info.hash) else: assert isinstance(direct_url.info, DirInfo) # pip should never reach this point for editables, since # pip freeze inspects the editable project location to produce # the requirement string assert not direct_url.info.editable requirement += direct_url.url if direct_url.subdirectory: fragments.append("subdirectory=" + direct_url.subdirectory) if fragments: requirement += "#" + "&".join(fragments) return requirement def direct_url_from_link(link, source_dir=None, link_is_in_wheel_cache=False): # type: (Link, Optional[str], bool) -> DirectUrl if link.is_vcs: vcs_backend = vcs.get_backend_for_scheme(link.scheme) assert vcs_backend url, requested_revision, _ = ( vcs_backend.get_url_rev_and_auth(link.url_without_fragment) ) # For VCS links, we need to find out and add commit_id. if link_is_in_wheel_cache: # If the requested VCS link corresponds to a cached # wheel, it means the requested revision was an # immutable commit hash, otherwise it would not have # been cached. In that case we don't have a source_dir # with the VCS checkout. assert requested_revision commit_id = requested_revision else: # If the wheel was not in cache, it means we have # had to checkout from VCS to build and we have a source_dir # which we can inspect to find out the commit id. assert source_dir commit_id = vcs_backend.get_revision(source_dir) return DirectUrl( url=url, info=VcsInfo( vcs=vcs_backend.name, commit_id=commit_id, requested_revision=requested_revision, ), subdirectory=link.subdirectory_fragment, ) elif link.is_existing_dir(): return DirectUrl( url=link.url_without_fragment, info=DirInfo(), subdirectory=link.subdirectory_fragment, ) else: hash = None hash_name = link.hash_name if hash_name: hash = "{}={}".format(hash_name, link.hash) return DirectUrl( url=link.url_without_fragment, info=ArchiveInfo(hash=hash), subdirectory=link.subdirectory_fragment, ) def dist_get_direct_url(dist): # type: (Distribution) -> Optional[DirectUrl] """Obtain a DirectUrl from a pkg_resource.Distribution. Returns None if the distribution has no `direct_url.json` metadata, or if `direct_url.json` is invalid. """ if not dist.has_metadata(DIRECT_URL_METADATA_NAME): return None try: return DirectUrl.from_json(dist.get_metadata(DIRECT_URL_METADATA_NAME)) except ( DirectUrlValidationError, JSONDecodeError, UnicodeDecodeError ) as e: logger.warning( "Error parsing %s for %s: %s", DIRECT_URL_METADATA_NAME, dist.project_name, e, ) return None