U
    @vg                     @   s4  d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	m
Z ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, e(rddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl	m8Z8 ddlm9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? e5e4d e4e@eAf f ZBe4e@e@e@e8eBe1e@ f ZCddd gZDeEeFZGd2d"d#ZHG d$d% d%eIZJd&d' ZKG d(d) d)eIZLG d*d deIZMG d+d, d,eIZNG d-d  d eIZOd.d/ ZPd0d1 ZQdS )3z!Routines related to PyPI, indexes    )absolute_importN)
specifiers)canonicalize_name)parse)BestVersionAlreadyInstalledDistributionNotFoundInvalidWheelFilenameUnsupportedWheel)parse_links)InstallationCandidate)FormatControl)Link)SelectionPreferences)TargetPython)Wheel)WHEEL_EXTENSION)
indent_log)build_netloc)check_requires_python)MYPY_CHECK_RUNNING)SUPPORTED_EXTENSIONS)url_to_path)	FrozenSetIterableListOptionalSetTextTupleUnion)Tag)_BaseVersion)LinkCollector)SearchScope)InstallRequirement)Hashes r   BestCandidateResultPackageFinderFc                 C   s~   zt | j|d}W n& tjk
r8   td| j|  Y nBX |szdtt|}|shtd|| j|  dS td|| j|  dS )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)	r   requires_pythonr   InvalidSpecifierloggerdebugjoinmapstr)linkr)   ignore_requires_pythonis_compatibleversionr&   r&   F/tmp/pip-unpacked-wheel-gw11q0wt/pip/_internal/index/package_finder.py_check_link_requires_python=   s8     
 
    r7   c                   @   s,   e Zd ZdZedZdddZdd ZdS )	LinkEvaluatorzD
    Responsible for evaluating links for a particular project.
    z-py([123]\.?[0-9]?)$Nc                 C   s4   |dkrd}|| _ || _|| _|| _|| _|| _dS )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_nameformatstarget_pythonallow_yankedr3   r&   r&   r6   __init__t   s    zLinkEvaluator.__init__c                 C   s  d}|j r(| js(|jpd}dd|fS |jr<|j}|j}n| \}}|sPdS |tkrddd| fS d| jkr|t	krd| j
 }d|fS d	|jkr|d
krdS |t	kr,zt|j}W n tk
r   Y dS X t|j| jkrd| j
 }d|fS | j }||s&| }dd|}d|fS |j}d| jkrP|t	krPdd| j
 fS |sbt|| j}|svdd| j
 fS | j|}	|	r|d|	  }|	d}
|
| jjkrdS t|| jj| j d}|sdS t!"d|| d|fS )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<none given>Fzyanked for reason: {})Fz
not a filezunsupported archive format: %sbinaryzNo binaries permitted for %smacosx10z.zip)Fzmacosx10 one)Fzinvalid wheel filenamezwrong project name (not %s)z"none of the wheel's tags match: {}, sourcezNo sources permitted for %szMissing project version for %s   )FzPython version is incorrect)r)   r3   )FNzFound link %s, version: %sT)#	is_yankedr9   yanked_reasonformategg_fragmentextsplitextr   r<   r   r>   pathr   filenamer   r   namer:   r=   get_tags	supportedget_formatted_file_tagsr/   r5   _extract_version_from_fragment_py_version_researchstartgroup
py_versionr7   py_version_infor;   r-   r.   )r?   r2   r5   reasonegg_inforO   wheelsupported_tags	file_tagsmatchr\   supports_pythonr&   r&   r6   evaluate_link   sx    





  
 zLinkEvaluator.evaluate_link)N)	__name__
__module____qualname____doc__recompilerX   rD   re   r&   r&   r&   r6   r8   h   s
   
 
&r8   c           
   	   C   s   |st dt| | t| S g }g }d}| D ]>}|j}|js@n"|j|drV|d7 }n|| q.|| q.|rx|}nt| }t|t| krd}	n dt|d	dd	 |D }	t d
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   )hashesrJ   zdiscarding no candidateszdiscarding {} non-matches:
  {}z
  c                 s   s   | ]}t |jV  qd S N)r1   r2   .0	candidater&   r&   r6   	<genexpr>-  s     z*filter_unallowed_hashes.<locals>.<genexpr>zPChecked %s links for project %r against %s hashes (%s matches, %s no digest): %s)r-   r.   lenlistr2   has_hashis_hash_allowedappendrM   r/   digest_count)

candidatesrl   r>   matches_or_no_digestnon_matchesmatch_countrp   r2   filtereddiscard_messager&   r&   r6   filter_unallowed_hashes   sL    


r~   c                   @   s   e Zd ZdZdddZdS )CandidatePreferenceszk
    Encapsulates some of the preferences for filtering and sorting
    InstallationCandidate objects.
    Fc                 C   s   || _ || _dS )zR
        :param allow_all_prereleases: Whether to allow all pre-releases.
        N)allow_all_prereleasesprefer_binary)r?   r   r   r&   r&   r6   rD   E  s    	zCandidatePreferences.__init__N)FF)rf   rg   rh   ri   rD   r&   r&   r&   r6   r   >  s     r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	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.
    c                 C   sH   t |t |kst|dkr&|r2tn||ks2t|| _|| _|| _dS )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)setAssertionError_applicable_candidates_candidatesbest_candidater?   rx   applicable_candidatesr   r&   r&   r6   rD   Y  s    
zBestCandidateResult.__init__c                 C   s
   t | jS )z(Iterate through all candidates.
        )iterr   r?   r&   r&   r6   iter_allr  s    zBestCandidateResult.iter_allc                 C   s
   t | jS )z3Iterate through the applicable candidates.
        )r   r   r   r&   r&   r6   iter_applicablex  s    z#BestCandidateResult.iter_applicableN)rf   rg   rh   ri   rD   r   r   r&   r&   r&   r6   r'   R  s   c                   @   sH   e Zd ZdZedddZdddZdd	 Zd
d Zdd Z	dd Z
dS )CandidateEvaluatorzm
    Responsible for filtering and sorting candidates for installation based
    on what tags are valid.
    NFc                 C   s:   |dkrt  }|dkrt }| }| ||||||dS )a  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.
        N)r>   ra   	specifierr   r   rl   )r   r   SpecifierSetrT   )clsr>   rB   r   r   r   rl   ra   r&   r&   r6   create  s    zCandidateEvaluator.createc                 C   s(   || _ || _|| _|| _|| _|| _dS )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>   ra   r   r   r   rl   r&   r&   r6   rD     s    zCandidateEvaluator.__init__c                    sd   | j pd}| j}dd |jdd |D |dD   fdd|D }t|| j| jd	}t|| jd
S )zM
        Return the applicable candidates from a list of candidates.
        Nc                 S   s   h | ]}t |qS r&   )r1   )ro   vr&   r&   r6   	<setcomp>  s    z?CandidateEvaluator.get_applicable_candidates.<locals>.<setcomp>c                 s   s   | ]}t |jV  qd S rm   r1   r5   ro   cr&   r&   r6   rq     s     z?CandidateEvaluator.get_applicable_candidates.<locals>.<genexpr>)prereleasesc                    s   g | ]}t |j kr|qS r&   r   r   versionsr&   r6   
<listcomp>  s     z@CandidateEvaluator.get_applicable_candidates.<locals>.<listcomp>)rx   rl   r>   key)r   r   filterr~   r   r   sorted	_sort_key)r?   rx   allow_prereleasesr   r   filtered_applicable_candidatesr&   r   r6   get_applicable_candidates  s"    	

z,CandidateEvaluator.get_applicable_candidatesc                 C   s   | j }t|}d}d}|j}|jrt|j}||sDtd|j | jrNd}|	| }|j
dk	rtd|j
}	|	 }
t|
d |
d f}n| }t|| j}dt|j }||||j||fS )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&   r   zB%s is not a supported wheel for this platform. It can't be sorted.rJ   Nz^(\d+)(.*)$)r   rr   r2   is_wheelr   rR   rU   r	   r   support_index_min	build_tagrj   rc   groupsintru   r   rK   r5   )r?   rp   
valid_tagssupport_numr   binary_preferencer2   r`   prirc   build_tag_groupshas_allowed_hash
yank_valuer&   r&   r6   r     s<    


    zCandidateEvaluator._sort_keyc                 C   sH   |sdS t || jd}|j}|jrD|jp*d}dj||d}t| |S )zy
        Return the best candidate per the instance's sort order, or None if
        no candidate is acceptable.
        Nr   rE   zqThe candidate selected for download or install is a yanked version: {candidate}
Reason for being yanked: {reason})rp   r^   )maxr   r2   rK   rL   rM   r-   warning)r?   rx   r   r2   r^   msgr&   r&   r6   sort_best_candidate"  s    	
 
z&CandidateEvaluator.sort_best_candidatec                 C   s"   |  |}| |}t|||dS )zF
        Compute and return a `BestCandidateResult` instance.
        )r   r   )r   r   r'   r   r&   r&   r6   compute_best_candidate@  s    

z)CandidateEvaluator.compute_best_candidate)NFFNN)FFN)rf   rg   rh   ri   classmethodr   rD   r   r   r   r   r&   r&   r&   r6   r     s         )   
&<r   c                   @   s   e Zd ZdZd(ddZed)ddZedd Zej	d	d Zed
d Z
edd Zedd Zedd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd*d"d#Zd+d$d%Zd&d' ZdS ),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.
    Nc                 C   sP   |dkrt  }|ptt t }|| _|| _|| _|| _|| _|| _t | _	dS )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   r   r9   _candidate_prefsr;   _link_collectorr=   format_control_logged_links)r?   link_collectorrB   rC   r   candidate_prefsr3   r&   r&   r6   rD   Z  s    zPackageFinder.__init__c                 C   s8   |dkrt  }t|j|jd}| ||||j|j|jdS )af  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.
        N)r   r   )r   r   rB   rC   r   r3   )r   r   r   r   rC   r   r3   )r   r   selection_prefsrB   r   r&   r&   r6   r     s    zPackageFinder.createc                 C   s   | j jS rm   r   search_scoper   r&   r&   r6   r     s    zPackageFinder.search_scopec                 C   s   || j _d S rm   r   )r?   r   r&   r&   r6   r     s    c                 C   s   | j jS rm   )r   
find_linksr   r&   r&   r6   r     s    zPackageFinder.find_linksc                 C   s   | j jS rm   )r   
index_urlsr   r&   r&   r6   r     s    zPackageFinder.index_urlsc                 c   s   | j jjD ]}t| V  q
d S rm   )r   sessionpip_trusted_originsr   )r?   	host_portr&   r&   r6   trusted_hosts  s    zPackageFinder.trusted_hostsc                 C   s   | j jS rm   r   r   r   r&   r&   r6   r     s    z#PackageFinder.allow_all_prereleasesc                 C   s   d| j _d S )NTr   r   r&   r&   r6   set_allow_all_prereleases  s    z'PackageFinder.set_allow_all_prereleasesc                 C   s.   t |}| j|}t|||| j| j| jdS )N)r>   r@   rA   rB   rC   r3   )r   r   get_allowed_formatsr8   r=   r9   r;   )r?   r>   r@   rA   r&   r&   r6   make_link_evaluator  s    z!PackageFinder.make_link_evaluatorc                 C   sP   g g  }}t  }|D ]2}||kr|| |jr<|| q|| q|| S )z
        Returns elements of links in order, non-egg links first, egg links
        second, while eliminating duplicates
        )r   addrN   rv   )r?   linkseggsno_eggsseenr2   r&   r&   r6   _sort_links  s    

zPackageFinder._sort_linksc                 C   s(   || j kr$td|| | j | d S )NzSkipping link: %s: %s)r   r-   r.   r   )r?   r2   r^   r&   r&   r6   _log_skipped_link  s    
zPackageFinder._log_skipped_linkc                 C   s<   | |\}}|s(|r$| j||d dS t|j|t|dS )z
        If the link is a candidate for install, convert it to an
        InstallationCandidate and return it. Otherwise, return None.
        )r^   N)rS   r2   r5   )re   r   r   r>   r1   )r?   link_evaluatorr2   is_candidateresultr&   r&   r6   get_install_candidate  s    z#PackageFinder.get_install_candidatec                 C   s6   g }|  |D ]"}| ||}|dk	r|| q|S )zU
        Convert links that are candidates to InstallationCandidate objects.
        N)r   r   rv   )r?   r   r   rx   r2   rp   r&   r&   r6   evaluate_links  s    zPackageFinder.evaluate_linksc              	   C   sT   t d| | j|}|d kr$g S tt|}t  | j||d}W 5 Q R X |S )Nz-Fetching project page and analyzing links: %sr   )r-   r.   r   
fetch_pagers   r
   r   r   )r?   project_urlr   	html_page
page_linkspackage_linksr&   r&   r6   process_project_url  s     z!PackageFinder.process_project_urlc           	      C   s   | j |}| |}| j||jd}g }|jD ]}| j||d}|| q0| j||jd}|r|j	dd t
dddd |D  || | S )	a  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.
        r   )r   T)reversezLocal files found: %srH   c                 S   s   g | ]}t |jjqS r&   )r   r2   urlrn   r&   r&   r6   r   F  s   z5PackageFinder.find_all_candidates.<locals>.<listcomp>)r   collect_linksr   r   r   project_urlsr   extendfilessortr-   r.   r/   )	r?   r>   collected_linksr   find_links_versionspage_versionsr   r   file_versionsr&   r&   r6   find_all_candidates$  s4    


 
	z!PackageFinder.find_all_candidatesc                 C   s"   | j }tj|| j|j|j||dS )z3Create a CandidateEvaluator object to use.
        )r>   rB   r   r   r   rl   )r   r   r   r=   r   r   )r?   r>   r   rl   r   r&   r&   r6   make_candidate_evaluatorO  s    	z&PackageFinder.make_candidate_evaluatorc                 C   s$   |  |}| j|||d}||S )a  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.
        )r>   r   rl   )r   r   r   )r?   r>   r   rl   rx   candidate_evaluatorr&   r&   r6   find_best_candidateb  s    
z!PackageFinder.find_best_candidatec           	      C   s  |j dd}| j|j|j|d}|j}d}|jdk	r@t|jj}dd }|dkrz|dkrzt	d|||
  td| d}|r|dks|j|krd	}|s|dk	r|rtd
| ntd||j dS |rtd|||  ttd|j||  |jS )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)trust_internet)r   rl   Nc                 S   s    d tdd | D tdpdS )NrH   c                 S   s   h | ]}t |jqS r&   r   r   r&   r&   r6   r     s     zKPackageFinder.find_requirement.<locals>._format_versions.<locals>.<setcomp>r   none)r/   r   parse_version)	cand_iterr&   r&   r6   _format_versions  s    z8PackageFinder.find_requirement.<locals>._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))rl   r   rS   r   r   satisfied_byr   r5   r-   criticalr   r   r.   r   r   r2   )	r?   requpgraderl   best_candidate_resultr   installed_versionr   best_installedr&   r&   r6   find_requirementy  sh      



zPackageFinder.find_requirement)NNN)N)NN)NN)rf   rg   rh   ri   rD   r   r   propertyr   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r&   r&   r&   r6   r(   S  sF      
(  





.  
  
c                 C   sL   t | D ].\}}|dkrqt| d| |kr|  S qtd| |dS )a  Find the separator's index based on the package's canonical name.

    :param fragment: A <package>+<version> 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   
ValueErrorrM   )fragmentr@   ir   r&   r&   r6   _find_name_version_sep  s    
r  c                 C   sB   zt | |d }W n tk
r(   Y dS X | |d }|s>dS |S )zParse the version string from a <package>+<version> 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.
    rJ   N)r  r  )r  r@   version_startr5   r&   r&   r6   rW     s    	rW   )F)Rri   
__future__r   loggingrj   Zpip._vendor.packagingr   pip._vendor.packaging.utilsr   Zpip._vendor.packaging.versionr   r   pip._internal.exceptionsr   r   r   r	   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_pythonr   pip._internal.models.wheelr   pip._internal.utils.filetypesr   pip._internal.utils.loggingr   pip._internal.utils.miscr   pip._internal.utils.packagingr   pip._internal.utils.typingr   pip._internal.utils.unpackingr   pip._internal.utils.urlsr   typingr   r   r   r   r   r   r   r   pip._vendor.packaging.tagsr    r!   r"   !pip._internal.models.search_scoper#   Zpip._internal.reqr$   pip._internal.utils.hashesr%   r   r1   ZBuildTagZCandidateSortingKey__all__	getLoggerrf   r-   r7   objectr8   r~   r   r'   r   r(   r  rW   r&   r&   r&   r6   <module>   s`   (

 
+ K- U  y