B
    `dSf                 @   s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
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 d dl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%m&Z&m'Z' d dl(m)Z)m*Z*m+Z+m,Z, d dl-m.Z.m/Z/ d dl0m1Z1m2Z2 er<d dlm3Z4 nd dlm4Z4 e.rd dl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? d dl@mAZA e>eBeBeBf ZCddddddddddddd d!gZDeEeFZGd"d# ZHd$d% ZId&d ZJd'd ZKed(d)d*dd,dZLd-d. ZMd/d0 ZNd1d ZOdd3dZPd4d5 ZQd6d7 ZRd8d ZSd9d: ZTd;d< ZUd=d ZVd>d? ZWd@d ZXejYfdAdBZZddDdZ[dEd Z\dFd Z]dGdH Z^dIdJ Z_dKdL Z`dMdN ZadOdP ZbdCe+dCd+d+dfdQdRZcdSdT ZddUdV ZedWdX ZfG dYdZ dZegZhG d[d\ d\e4Ziejjd]d^ Zkd_d Zld`da ZmG dbdc dcegZndddd Zodedf Zpdgdh Zqdidj ZrddldmZsdndo Ztdpdq Zudrds Zvdtdu Zwdvdw Zxdxdy Zydzd{ Zzd|d! Z{d}d~ Z|G dd degZ}dd Z~dd Zdd Zdd ZdddZdd Zdd ZdS )    )absolute_importN)deque)pkg_resources)retry)PY2	text_type)inputmapzip_longest)parse)unquote)__version__)CommandError)get_major_minor_versionsite_packages	user_site)WINDOWS
expanduserstdlib_pkgsstr_to_display)MYPY_CHECK_RUNNINGcast)running_under_virtualenvvirtualenv_no_global)BytesIO)StringIO)
AnyAnyStr	ContainerIterableIteratorListOptionalTextTupleUnion)Distribution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_urlc              C   s4   t jt jtdd} t j| } dt| t S )Nz..zpip {} from {} (python {}))	ospathjoindirname__file__abspathformatr   r   )pip_pkg_dir r=   </tmp/pip-unpacked-wheel-hu9qqap1/pip/_internal/utils/misc.pyget_pip_versionK   s    r?   c             C   sD   t | dk r"| dt |  d 7 } nt | dkr:| dd } td| 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).
       )r   NVersionInfo)lenr   )py_version_infor=   r=   r>   normalize_version_infoW   s
    rD   c          
   C   sP   yt |  W n< tk
rJ } z|jtjkr:|jtjkr: W dd}~X Y nX dS )z os.path.makedirs without EEXIST.N)r5   makedirsOSErrorerrnoEEXIST	ENOTEMPTY)r6   er=   r=   r>   r2   k   s
    c           
   C   sN   y.t jtjd } | dkr(dtjS | S W n ttt	fk
rH   Y nX dS )Nr   )z__main__.pyz-cz	{} -m pippip)
r5   r6   basenamesysargvr;   
executableAttributeError	TypeError
IndexError)progr=   r=   r>   r0   v   s    i  i  )stop_max_delay
wait_fixedFc             C   s   t j| |td d S )N)ignore_errorsonerror)shutilr'   rmtree_errorhandler)dirrV   r=   r=   r>   r'      s    c          	   C   sV   yt |jtj@  }W n ttfk
r0   dS X |rPt |tj | | dS  dS )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)r5   statst_modeS_IWRITEIOErrorrF   chmod)funcr6   exc_infohas_attr_readonlyr=   r=   r>   rY      s    rY   c             C   sd   | dkrdS t | tr| S y| t d}W n0 tk
r^   trRtd| }nt	| }Y nX |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.
    Nstrictzb{!r})

isinstancer   decoderM   getfilesystemencodingUnicodeDecodeErrorr   r   r;   ascii)r6   r(   r=   r=   r>   path_to_display   s    	
ri   c             C   st   t jt j| } tjd dkrB| t d} | t	 d} | 
t  t jj rpd| tt  d  } | S )zTGives the display value for a given path, making it relative to cwd
    if possible.r      replace.N)r5   r6   normcaser:   rM   version_infore   rf   encodegetdefaultencoding
startswithgetcwdseprB   )r6   r=   r=   r>   r(      s    .bakc             C   s:   d}|}x(t j| | r0|d7 }|t| }q
W | | S )z\Figure out the name of a directory to back up the given dir to
    (adding .bak, .bak2, etc)   )r5   r6   existsstr)rZ   extn	extensionr=   r=   r>   r)      s    c             C   s2   x&t jdd D ]}||kr|S qW t| |S )NPIP_EXISTS_ACTION )r5   environgetsplitr*   )messageoptionsactionr=   r=   r>   ask_path_exists   s    r   c             C   s   t jdrtd| dS )z&Raise an error if no input is allowed.PIP_NO_INPUTz7No input was expected ($PIP_NO_INPUT set); question: {}N)r5   r}   r~   	Exceptionr;   )r   r=   r=   r>   _check_no_input   s    r   c             C   sJ   xDt |  t| }|  }||kr>td|d| q|S qW dS )z@Ask the message interactively, with the given possible responsesz>Your response ({!r}) was not one of the expected responses: {}z, N)r   r   striplowerprintr;   r7   )r   r   responser=   r=   r>   r*      s    c             C   s   t |  t| S )zAsk for input interactively.)r   r   )r   r=   r=   r>   	ask_input   s    r   c             C   s   t |  t| S )z!Ask for a password interactively.)r   getpass)r   r=   r=   r>   ask_password  s    r   c             C   s\   | dkrd | d d S | dkr4d t| d S | dkrJd | d S d t| S d S )	Ni@B z	{:.1f} MBg     @@i  i'  z{} kBz	{:.1f} kBz{} bytes)r;   int)bytesr=   r=   r>   r,   
  s    c                s@   dd | D } dd t | ddiD   fdd| D }| fS )zReturn a list of formatted rows and a list of column sizes.

    For example::

    >>> tabulate([['foobar', 2000], [0xdeadbeef]])
    (['foobar     2000', '3735928559'], [10, 4])
    c             S   s   g | ]}t tt|qS r=   )tupler	   rw   ).0rowr=   r=   r>   
<listcomp>  s    ztabulate.<locals>.<listcomp>c             S   s   g | ]}t tt|qS r=   )maxr	   rB   )r   colr=   r=   r>   r      s    	fillvaluer|   c                s$   g | ]}d  ttj|  qS ) )r7   r	   rw   ljustrstrip)r   r   )sizesr=   r>   r   !  s    )r
   )rowstabler=   )r   r>   tabulate  s    	r   c             C   sP   t j| sdS t j| d}t j|r.dS t j| d}t j|rLdS dS )zBIs path is a directory containing setup.py or pyproject.toml?
    Fzsetup.pyTzpyproject.toml)r5   r6   isdirr7   isfile)r6   setup_pypyproject_tomlr=   r=   r>   r-   %  s    c             c   s    x|  |}|sP |V  qW dS )z7Yield pieces of data from a file-like object until EOF.N)read)filesizechunkr=   r=   r>   read_chunks4  s
    
r   Tc             C   s2   t | } |rtj| } ntj| } tj| S )zN
    Convert a path to its canonical, case-normalized, absolute version.

    )r   r5   r6   realpathr:   rm   )r6   resolve_symlinksr=   r=   r>   r.   =  s
    c             C   s@   t | \}}| dr8|dd | }|dd }||fS )z,Like os.path.splitext, but take off .tar tooz.tarN)	posixpathr+   r   endswith)r6   baserx   r=   r=   r>   r+   K  s
    c             C   sz   t j|\}}|r.|r.t j|s.t | t| | t j| \}}|rv|rvyt | W n tk
rt   Y nX dS )z7Like os.renames(), but handles renaming across devices.N)	r5   r6   r   rv   rE   rX   move
removedirsrF   )oldnewheadtailr=   r=   r>   r/   U  s    
c             C   s   t  s
dS | ttjS )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)r   rq   r.   rM   prefix)r6   r=   r=   r>   is_localg  s    
r   c             C   s   t t| 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)distr=   r=   r>   dist_is_localv  s    	r   c             C   s   t | ttS )zF
    Return True if given Distribution is installed in user site.
    )r   rq   r.   r   )r   r=   r=   r>   dist_in_usersite  s    r   c             C   s   t | ttS )z[
    Return True if given Distribution is installed in
    sysconfig.get_python_lib().
    )r   rq   r.   r   )r   r=   r=   r>   dist_in_site_packages  s    r   c             C   s8   x2t jD ](}tj|| jd }tj|rdS qW dS )zC
    Return True if given Distribution is an editable install.
    z	.egg-linkTF)rM   r6   r5   r7   project_namer   )r   	path_itemegg_linkr=   r=   r>   dist_is_editable  s
    r   c                s   |rt |}nt j}| r tndd |r6dd  ndd  |rLdd ndd |r^tnd	d
  fdd|D S )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.
    c             S   s   dS )NTr=   )dr=   r=   r>   
local_test  s    z/get_installed_distributions.<locals>.local_testc             S   s   dS )NTr=   )r   r=   r=   r>   editable_test  s    z2get_installed_distributions.<locals>.editable_testc             S   s
   t |  S )N)r   )r   r=   r=   r>   r     s    c             S   s   t | S )N)r   )r   r=   r=   r>   editables_only_test  s    z8get_installed_distributions.<locals>.editables_only_testc             S   s   dS )NTr=   )r   r=   r=   r>   r     s    c             S   s   dS )NTr=   )r   r=   r=   r>   	user_test  s    z.get_installed_distributions.<locals>.user_testc                s:   g | ]2}|r|j kr |r|r|r|qS r=   )key)r   r   )r   r   r   skipr   r=   r>   r     s    
z/get_installed_distributions.<locals>.<listcomp>)r   
WorkingSetworking_setr   r   )
local_onlyr   include_editableseditables_only	user_onlypathsr   r=   )r   r   r   r   r   r>   get_installed_distributions  s     

r   c             C   sx   g }t  r*|t t sBtrB|t ntr8|t |t x0|D ](}tj|| jd }tj	|rH|S qHW dS )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)
r   appendr   r   r   r5   r6   r7   r   r   )r   sitessiteegglinkr=   r=   r>   egg_link_path  s    




r   c             C   s   t | }|rt|S t| jS )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).
    )r   r.   location)r   r   r=   r=   r>   r     s    
r   c             G   s   t j| f|  d S )N)loggerinfo)msgargsr=   r=   r>   write_output  s    r   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	FakeFilezQWrap a list of lines in an object with readline() to make
    ConfigParser happy.c             C   s   dd |D | _ d S )Nc             s   s   | ]
}|V  qd S )Nr=   )r   lr=   r=   r>   	<genexpr>   s    z$FakeFile.__init__.<locals>.<genexpr>)_gen)selflinesr=   r=   r>   __init__  s    zFakeFile.__init__c             C   sD   y*y
t | jS  tk
r&   | j  S X W n tk
r>   dS X d S )Nr|   )nextr   	NameErrorStopIteration)r   r=   r=   r>   readline"  s    
zFakeFile.readlinec             C   s   | j S )N)r   )r   r=   r=   r>   __iter__+  s    zFakeFile.__iter__N)__name__
__module____qualname____doc__r   r   r   r=   r=   r=   r>   r     s   	r   c               @   s$   e Zd Zedd Zedd ZdS )StreamWrapperc             C   s   || _ |  S )N)orig_stream)clsr   r=   r=   r>   from_stream1  s    zStreamWrapper.from_streamc             C   s   | j jS )N)r   encoding)r   r=   r=   r>   r   7  s    zStreamWrapper.encodingN)r   r   r   classmethodr   propertyr   r=   r=   r=   r>   r   /  s   r   c          
   c   s@   t t| }tt| t| zt t| V  W dtt| | X dS )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)getattrrM   setattrr   r   )stream_nameorig_stdoutr=   r=   r>   captured_output<  s
    
r   c               C   s   t dS )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)r   r=   r=   r=   r>   r1   K  s    	c               C   s   t dS )z 
    See captured_stdout().
    stderr)r   r=   r=   r=   r>   captured_stderrW  s    r   c               @   s    e Zd ZdZdd Zdd ZdS )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
    c             C   s   t |d| _|| _d S )Nr   )r   r   r`   )r   r`   r=   r=   r>   r   f  s    zcached_property.__init__c             C   s(   |d kr| S |  | }|j| j j< |S )N)r`   __dict__r   )r   objr   valuer=   r=   r>   __get__j  s    zcached_property.__get__N)r   r   r   r   r   r   r=   r=   r=   r>   r   ^  s   r   c             C   s4   t j| }|dkrt  }||}|r0|jS dS )zCGet the installed version of dist_name avoiding pkg_resources cacheN)r   Requirementr   r   findversion)	dist_namer   reqr   r=   r=   r>   r3   r  s
    
c             C   s   t | dd dS )zConsume an iterable at C speed.r   )maxlenN)r   )iteratorr=   r=   r>   consume  s    r  c              O   s@   t t| tt| f|}dd | D }||d< tdd|S )Nc             S   s   i | ]\}}||qS r=   r=   )r   r   r   r=   r=   r>   
<dictcomp>  s    zenum.<locals>.<dictcomp>reverse_mappingEnumr=   )dictziprangerB   itemstype)
sequentialnamedenumsreverser=   r=   r>   enum  s    r  c             C   s*   |dkr| S d| krd | } d | |S )z.
    Build a netloc from a host-port pair
    N:z[{}]z{}:{})r;   )hostportr=   r=   r>   build_netloc  s
    
r  httpsc             C   s4   |  ddkr(d| kr(d| kr(d| } d|| S )z)
    Build a full URL from a netloc.
    r  rj   @[z[{}]z{}://{})countr;   )netlocschemer=   r=   r>   build_url_from_netloc  s    
r  c             C   s   t | }t|}|j|jfS )z2
    Return the host-port pair from a netloc.
    )r  urllib_parseurlparsehostnamer  )r  urlparsedr=   r=   r>   parse_netloc  s    
r!  c             C   sX   d| kr| dfS |  dd\}} d|kr6|dd}n|df}tdd |D }| |fS )zp
    Parse out and remove the auth information from a netloc.

    Returns: (netloc, (username, password)).
    r  )NNru   r  Nc             s   s"   | ]}|d krd nt |V  qd S )N)urllib_unquote)r   xr=   r=   r>   r     s    z)split_auth_from_netloc.<locals>.<genexpr>)rsplitr   r   )r  auth	user_passr=   r=   r>   split_auth_from_netloc  s    r'  c             C   sL   t | \} \}}|dkr| S |dkr.d}d}nt|}d}dj||| dS )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****r|   z:****z{user}{password}@{netloc})userpasswordr  )r'  r  quoter;   )r  r(  r)  r=   r=   r>   redact_netloc  s    	
r+  c             C   s@   t | }||j}|j|d |j|j|jf}t |}||fS )aR  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.
    r   )r  urlsplitr  r  r6   queryfragment
urlunsplit)r  transform_netlocpurlnetloc_tuple
url_piecessurlr=   r=   r>   _transform_url  s
    



r5  c             C   s   t | S )N)r'  )r  r=   r=   r>   _get_netloc  s    r6  c             C   s
   t | fS )N)r+  )r  r=   r=   r>   _redact_netloc  s    r7  c             C   s   t | t\}\}}|||fS )z
    Parse a url into separate netloc, auth, and url with no auth.

    Returns: (url_without_auth, netloc, (username, password))
    )r5  r6  )r  url_without_authr  r%  r=   r=   r>   split_auth_netloc_from_url  s    r9  c             C   s   t | td S )z7Return a copy of url with 'username:password@' removed.r   )r5  r6  )r  r=   r=   r>   r4     s    c             C   s   t | td S )z.Replace the password in a given url with ****.r   )r5  r7  )r  r=   r=   r>   redact_auth_from_url  s    r:  c               @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )
HiddenTextc             C   s   || _ || _d S )N)secretredacted)r   r<  r=  r=   r=   r>   r     s    zHiddenText.__init__c             C   s   d t| S )Nz<HiddenText {!r}>)r;   rw   )r   r=   r=   r>   __repr__%  s    zHiddenText.__repr__c             C   s   | j S )N)r=  )r   r=   r=   r>   __str__)  s    zHiddenText.__str__c             C   s    t | t |krdS | j|jkS )NF)r  r<  )r   otherr=   r=   r>   __eq__.  s    zHiddenText.__eq__c             C   s
   | |k S )Nr=   )r   r@  r=   r=   r>   __ne__9  s    zHiddenText.__ne__N)r   r   r   r   r>  r?  rA  rB  r=   r=   r=   r>   r;    s
   	r;  c             C   s   t | ddS )Nz****)r=  )r;  )r   r=   r=   r>   
hide_value>  s    rC  c             C   s   t | }t| |dS )N)r=  )r:  r;  )r  r=  r=   r=   r>   hide_urlC  s    rD  c             C   sz   dd tjd dj tjdd  g}| oBtoBtjtjd |k}|rvtjddgtjd	d  }t	d
 d
|dS )zProtection of pip.exe from modification on Windows

    On Windows, any operation modifying pip should be run as:
        python -m pip ...
    zpip.exez	pip{}.exer   zpip{}.{}.exeNrj   z-mrK   ru   z3To modify pip, please run the following command:
{}r   )r;   rM   rn   r   r5   r6   rL   rN   rO   r   r7   )modifying_pip	pip_namesshould_show_use_python_msgnew_commandr=   r=   r>   (protect_pip_from_modification_on_windowsI  s    
rI  c               C   s   t jdk	ot j S )z!Is this console interactive?
    N)rM   stdinisattyr=   r=   r=   r>   is_console_interactiveg  s    rL     c          	   C   sV   t  }d}t| d2}x*t||dD ]}|t|7 }|| q&W W dQ R X ||fS )z:Return (hash, length) for path using hashlib.sha256()
    r   rb)r   N)hashlibsha256openr   rB   update)r6   	blocksizehlengthfblockr=   r=   r>   	hash_filen  s    rX  c              C   s&   yddl } W n tk
r    dS X dS )z8
    Return whether the wheel package is installed.
    r   NFT)wheelImportError)rY  r=   r=   r>   is_wheel_installed|  s
    r[  c             C   s   t | } t| | S )zb
    Return paired elements.

    For example:
        s -> (s0, s1), (s2, s3), (s4, s5), ...
    )iterr
   )iterabler=   r=   r>   pairwise  s    r^  )F)rt   )T)N)r  )rM  )
__future__r   
contextlibrG   r   rO  iologgingr5   r   rX   r[   rM   collectionsr   pip._vendorr   pip._vendor.retryingr   Zpip._vendor.sixr   r   pip._vendor.six.movesr   r	   r
   Zpip._vendor.six.moves.urllibr   r  "pip._vendor.six.moves.urllib.parser   r"  rK   r   pip._internal.exceptionsr   pip._internal.locationsr   r   r   pip._internal.utils.compatr   r   r   r   pip._internal.utils.typingr   r   pip._internal.utils.virtualenvr   r   r   r   typingr   r   r   r   r    r!   r"   r#   r$   r%   Zpip._vendor.pkg_resourcesr&   r   rA   __all__	getLoggerr   r   r?   rD   r2   r0   r'   rY   ri   r(   r)   r   r   r*   r   r   r,   r   r-   DEFAULT_BUFFER_SIZEr   r.   r+   r/   r   r   r   r   r   r   r   r   r   objectr   r   contextmanagerr   r1   r   r   r3   r  r  r  r  r!  r'  r+  r5  r6  r7  r9  r4   r:  r;  rC  rD  rI  rL  rX  r[  r^  r=   r=   r=   r>   <module>   s   0

"

	

	>$


#
