U
    楡c                     @   s  U d dl mZ d dlmZ ddlmZ d dlZ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mZ d dlZd dlmZmZ d dlZd dlmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,Z,e*r8d d	l-m.Z. d d
l/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? e'de(d ddZ@d dlAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJ dddddddddddddd d!d"d#d$gZKeLeMZNeoejOPd$dZQeoejOPd%dZRe'd&ZSed'eSf ed'eSf d(d)d#ZTejUe;ee;ddf d*d+d,ZVe;dd-d.d"ZWe;dd-d/d0ZXdyeeeYeYd2d3dZZe;e;e;d4d5dZ[ere;e;d-d6d7Z\e;e]d-d8dZ^eK_d7 e\Z`ne;e]d-d9dZ^e^Z`e;e;e;d4d:dZadze;ebebd<d=dZce%e] d>d?d@Zdd{e]e#e; e"e] dAdBdCZee#e] e]e]dDdEdFZfegdGdHdI d;fegdJefd;fegdKefd;fegdLejhdMdI dfegdNdOdI d;ffZie&e&e$e] eebf d'f ejdP< e]e]d-dQdRZkegdSZle;e]d-dTdUZmi Znee]e#eb f ejdV< e+de7d; dWdXdYZoe+e;ebdWdZdYZoe(de;f ebdWd[dYZoe]d>d\dZpe(ejqd]f edd^d_d`Zre+d|debddadbdcZse+d}e;ebe]dadddcZsd~e(de;f ebe#e; dadedcZse%e] e"e] dfdgdhZtG did  d euZvG djd! d!evZwG dkd deuZxG dld deuZyG dmd deuZzG dnd deuZ{G dod de{Z|G dpd de"e@ Z}G dqdr dre~ZG dsdt dteduZe:G dvd de9ZG dwdx dxejZdS )    )abstractmethodN   )is_win)wraps)maxsize)urlsplit
urlunsplit)AnyAnyStrBinaryIOCallableDict	GeneratorIOIteratorListOptionalPatternSequenceTupleTypeVarUnioncastTYPE_CHECKINGoverload)Remote)Repo)GitConfigParserSectionConstraint)Git)	LiteralSupportsIndexProtocolruntime_checkablePathLikeHSH_TDTotal_TDFiles_TDHas_id_attributeT_IterableObj)IterableObjr(   T)bound	covariant)	make_shaLockedFDfile_contents_rofile_contents_ro_filepath	LazyMixin
to_hex_sha
to_bin_sha
bin_to_hex
hex_to_binstream_copy	join_pathto_native_path_linuxjoin_path_nativeStatsIndexFileSHA1Writerr*   IterableListBlockingLockFileLockFileActorget_user_idassure_directory_existsRemoteProgressCallableRemoteProgressrmtreeunbare_repoHIDE_WINDOWS_KNOWN_ERRORSHIDE_WINDOWS_FREEZE_ERRORST.)funcreturnc                    s2   ddl m  tdtttd fdd}|S )zcMethods with this decorator raise InvalidGitRepositoryError if they
    encounter a bare repositoryr   )InvalidGitRepositoryErrorr   )selfargskwargsrJ   c                    s&   | j jr dj | f||S )Nz/Method '%s' cannot operate on bare repositories)repoZbare__name__rL   rM   rN   rK   rI    ,/tmp/pip-unpacked-wheel-_pbxsds5/git/util.pywrapper   s    zunbare_repo.<locals>.wrapper)excrK   r   r	   rH   )rI   rU   rS   rR   rT   rE      s    )new_dirrJ   c              	   c   s.   t  }t |  z
| V  W 5 t | X d S N)osgetcwdchdir)rW   Zold_dirrS   rS   rT   cwd   s
    

r\   )pathrJ   c                 C   s"   t ttdddd}t| d|S )zRemove the given recursively.

    :note: we use shutil rmtree but adjust its behaviour to see whether files that
        couldn't be deleted are read-only. Windows will not remove them in that caseN)rI   r]   exc_inforJ   c              
   S   sd   t |tj z| | W nD tk
r^ } z&trLddlm} |d|| W 5 d }~X Y nX d S )Nr   )SkipTestz'FIXME: fails with: PermissionError
  {})	rY   chmodstatS_IWUSR	ExceptionrF   Zunittestr_   format)rI   r]   r^   exr_   rS   rS   rT   onerror   s    zrmtree.<locals>.onerrorF)r   r$   strshutilrD   )r]   rf   rS   rS   rT   rD      s    c                 C   s(   t | r$trt| d t|  dS )zSEnsure file deleted also on *Windows* where read-only files need special treatment.i  N)ospisfiler   rY   r`   remover]   rS   rS   rT   rmfile   s    
rm      )sourcedestination
chunk_sizerJ   c                 C   s8   d}|  |}|| |t|7 }t||k rq4q|S )zCopy all data from the source stream into the destination stream in chunks
    of size chunk_size

    :return: amount of bytes writtenr   )readwritelen)ro   rp   rq   brchunkrS   rS   rT   r6      s    

)aprJ   c                 G   sh   t | }|D ]V}t |}|sq|dr:||dd 7 }q|dksL|drV||7 }q|d| 7 }q|S )zhJoin path tokens together similar to osp.join, but always use
    '/' instead of possibly '' on windows./r   N )rg   
startswithendswith)rw   rx   r]   brS   rS   rT   r7      s    

c                 C   s   t | } | ddS )Nry   \rg   replacerl   rS   rS   rT   to_native_path_windows   s    r   c                 C   s   t | } | ddS )Nr~   ry   r   rl   rS   rS   rT   r8      s    c                 C   s   t | S rX   )rg   rl   rS   rS   rT   r8      s    c                 G   s   t t| f| S )z
    As join path, but makes sure an OS native path is returned. This is only
        needed to play it safe on my dear windows and to assure nice paths that only
        use '')to_native_pathr7   )rw   rx   rS   rS   rT   r9      s    F)r]   is_filerJ   c                 C   s.   |rt | } t | s*tj| dd dS dS )zAssure that the directory pointed to by path exists.

    :param is_file: If True, path is assumed to be a file and handled correctly.
        Otherwise it must be a directory
    :return: True if the directory was created, False if it already existedT)exist_okF)ri   dirnameisdirrY   makedirs)r]   r   rS   rS   rT   rA      s    

rJ   c                  C   s8   t jdd } | r,tdd | t jD S tr4dS dS )NPATHEXTc                 s   s   | ]}|  V  qd S rX   )upper).0rx   rS   rS   rT   	<genexpr>  s     z&_get_exe_extensions.<locals>.<genexpr>)z.BATZCOMz.EXErz   )rY   environgettuplesplitpathsepr   )r   rS   rS   rT   _get_exe_extensions  s    (r   )programr]   rJ   c                    s   t  ttdfdd}g }|s,tjd }t|tjD ]N}|d}|r<t	||   g fddD  D ]}||rr|
| qrq<|S )N)fpathrJ   c                    s>   t  o<t tjo<tjdkp< p<t fddD S )Nntc                 3   s   | ]}   |V  qd S rX   )r   r|   )r   extr   rS   rT   r     s     z,py_where.<locals>.is_exec.<locals>.<genexpr>)ri   rj   rY   accessX_OKnameanyr   )winprog_extsr   rT   is_exec  s
    
$zpy_where.<locals>.is_execPATH"c                    s   g | ]}d  |f qS )z%s%srS   )r   e)exe_pathrS   rT   
<listcomp>%  s     zpy_where.<locals>.<listcomp>)r   rg   boolrY   r   r   r   stripri   joinappend)r   r]   r   ZprogsfolderfrS   )r   r   rT   py_where  s    

r   )driver]   rJ   c                 C   st   t |r| s|}nL|o,t t t |}t |rL| rB|}q`t|}n| r`d|  |f }t|}|ddS )Nz/proc/cygdrive/%s/%sr~   ry   )	ri   isabsnormpath
expandvars
expandusercygpathlowerrg   r   )r   r]   rx   Zp_strrS   rS   rT   
_cygexpath+  s    

r   z*\\\\\?\\UNC\\([^\\]+)\\([^\\]+)(?:\\(.*))?c                 C   s   d| || ddf S )Nz
//%s/%s/%sr~   ry   )r   )serverZshare	rest_pathrS   rS   rT   <lambda>C      r   z\\\\\?\\(\w):[/\\](.*)z(\w):[/\\](.*)z	file:(.*)c                 C   s   | S rX   rS   )r   rS   rS   rT   r   H  r   z(\w{2,}:.*)c                 C   s   | S rX   rS   )urlrS   rS   rT   r   I  r   _cygpath_parsersc                 C   sZ   t | } | dsVtD ]4\}}}|| }|r||  } |rFt| }  qVqtd| } | S )zLUse :meth:`git.cmd.Git.polish_url()` instead, that works on any environment.)z	/cygdrivez//z/proc/cygdriveN)rg   r{   r   matchgroupsr   r   )r]   regexparserZrecurser   rS   rS   rT   r   M  s    


r   z(?:/proc)?/cygdrive/(\w)(/.*)?c                 C   sB   t | } t| }|r6| \}}d| |p0df } | ddS )Nz%s:%srz   ry   r~   )rg   _decygpath_regexr   r   r   r   )r]   mr   r   rS   rS   rT   	decygpathb  s    
r   _is_cygwin_cache)git_executablerJ   c                 C   s   d S rX   rS   r   rS   rS   rT   is_cygwin_gitq  s    r   c                 C   s   d S rX   rS   r   rS   rS   rT   r   v  s    c           	   
   C   s   t rdS | d krdS t| } t| }|d krd}zdt| }|s`t| }|r\t|d nd}t|d}tj	|gtj
dd}| \}}d|k}W n. tk
r } ztd| W 5 d }~X Y nX |t| < |S )	NFr   rz   unameT)stdoutuniversal_newlinesZCYGWINz/Failed checking if running in CYGWIN due to: %r)r   rg   r   r   ri   r   r   r   
subprocessPopenPIPEcommunicaterc   logdebug)	r   Z	is_cygwingit_dirresZ	uname_cmdprocessZ	uname_out_re   rS   rS   rT   r   {  s*    

c                   C   s   dt  t f S )zI:return: string identifying the currently active system user as name@nodez%s@%s)getpassgetuserplatformnoderS   rS   rS   rT   r@     s    zGit.AutoInterrupt)procrN   rJ   c                 K   s   | j f | dS )zSWait for the process (clone, fetch, pull or push) and handle its errors accordinglyN)wait)r   rN   rS   rS   rT   finalize_process  s    r   )rx   expand_varsrJ   c                 C   s   d S rX   rS   rx   r   rS   rS   rT   expand_path  s    r   c                 C   s   d S rX   rS   r   rS   rS   rT   r     s    c                 C   sZ   t | tjr|  S z*t| } |r.t| } tt| W S  t	k
rT   Y d S X d S rX   )

isinstancepathlibPathresolveri   r   r   r   abspathrc   r   rS   rS   rT   r     s    

)cmdlinerJ   c              	   C   s   g }t | D ]\}}|| ztt|}|jdkr@|jdkr@W q|jdk	rb|j|j|jdd}|jdk	r|j|j|jdd}t|||< W q t	k
r   Y qY qX q|S )a8  
    Parse any command line argument and if on of the element is an URL with a
    username and/or password, replace them by stars (in-place).

    If nothing found just returns the command line as-is.

    This should be used for every log line that print a command line, as well as
    exception messages.
    Nz*****)netloc)
	enumerater   r   passwordusername_replacer   r   r   
ValueError)r   Znew_cmdlineindexZto_parser   rS   rS   rT   remove_password_if_present  s    



r   c                	   @   s   e Zd ZU dZdZeed< dd eeD \	ZZ	Z
ZZZZZZee	B Ze ZdZdZdZed	Zed
ZddddZeddddZeegdf dddZeddddZ dee!ee"f e!ee"df eddddZ#dS )rB   z
    Handler providing an interface to parse progress information emitted by git-push
    and git-fetch and to dispatch callbacks allowing subclasses to react to the progress.
    	   _num_op_codesc                 C   s   g | ]}d |> qS )r   rS   )r   xrS   rS   rT   r     s     zRemoteProgress.<listcomp>zdone.z, )	_cur_line	_seen_opserror_linesother_linesz%(remote: )?([\w\s]+):\s+()(\d+)()(.*)z2(remote: )?([\w\s]+):\s+(\d+)% \((\d+)/(\d+)\)(.*)Nr   c                 C   s   g | _ d | _g | _g | _d S rX   )r   r   r   r   rL   rS   rS   rT   __init__  s    zRemoteProgress.__init__linerJ   c                 C   s&  t |tr|d}n|}|| _| jdr>| j| j dS d}tt|D ]\}}t	|dk rN| d }qN|dk	r|d| }|
 }d\}}| j|}|dkr| j|}|s| | | j| dS d}	| \}
}}}}}|dkr|	| jO }	n|d	kr|	| jO }	n||d
kr(|	| jO }	nf|dkr>|	| jO }	nP|dkrT|	| jO }	n:|dkrj|	| jO }	n$|dkr|	| jO }	n| | dS |	| jkr| j|	 |	| jO }	|dkrd}| }|| jr|	| jO }	|dt| j  }|| j}|  |	|ot!||ot!|| dS )a3  Parse progress information from the given line as retrieved by git-push
        or git-fetch.

        - Lines that do not contain progress info are stored in :attr:`other_lines`.
        - Lines that seem to contain an error (i.e. start with error: or fatal:) are stored
            in :attr:`error_lines`.zutf-8)zerror:zfatal:N    r   )NNr   zCounting objectszCompressing objectszWriting objectszReceiving objectszResolving deltaszFinding sourceszChecking out filesrz   )"r   bytesdecoder   r{   r   r   r   reversedordrstripre_op_relativer   re_op_absoluteline_droppedr   r   COUNTINGCOMPRESSINGWRITING	RECEIVING	RESOLVINGFINDING_SOURCESCHECKING_OUTr   BEGINr   r|   
DONE_TOKENENDrt   TOKEN_SEPARATORupdatefloat)rL   r   line_strZlast_valid_indexic	cur_count	max_countr   op_codeZ_remoteZop_nameZ_percentmessagerS   rS   rT   _parse_progress_line  sp    











z#RemoteProgress._parse_progress_linec                    s   t dd fdd}|S )z
        :return:
            a progress handler suitable for handle_process_output(), passing lines on to this Progress
            handler in a suitable formatNr   c                    s     |  S rX   )r  r   )r   r   rS   rT   handlers  s    z3RemoteProgress.new_message_handler.<locals>.handler)r
   )rL   r  rS   r   rT   new_message_handlerm  s    z"RemoteProgress.new_message_handlerc                 C   s   dS )zICalled whenever a line could not be understood and was therefore dropped.NrS   )rL   r   rS   rS   rT   r   y  s    zRemoteProgress.line_droppedrz   )r  r  r  r  rJ   c                 C   s   dS )a2  Called whenever the progress changes

        :param op_code:
            Integer allowing to be compared against Operation IDs and stage IDs.

            Stage IDs are BEGIN and END. BEGIN will only be set once for each Operation
            ID as well as END. It may be that BEGIN and END are set at once in case only
            one progress message was emitted due to the speed of the operation.
            Between BEGIN and END, none of these flags will be set

            Operation IDs are all held within the OP_MASK. Only one Operation ID will
            be active per call.
        :param cur_count: Current absolute count of items

        :param max_count:
            The maximum count of items we expect. It may be None in case there is
            no maximum number of items or if it is (yet) unknown.

        :param message:
            In case of the 'WRITING' operation, it contains the amount of bytes
            transferred. It may possibly be used for other purposes as well.

        You may read the contents of the current line in self._cur_lineNrS   )rL   r  r  r  r  rS   rS   rT   r  }  s    zRemoteProgress.update)Nrz   )$rP   
__module____qualname____doc__r   int__annotations__ranger  r  r   r   r   r   r   r  r  Z
STAGE_MASKZOP_MASKr  r  	__slots__recompiler   r   r   r
   r  r   rg   r  r   r   r  r  rS   rS   rS   rT   rB     sB   


f  
c                       s>   e Zd ZdZdZedd fddZeedddd	Z  Z	S )
rC   z4An implementation forwarding updates to any callable	_callableN)fnrJ   c                    s   || _ tt|   d S rX   )r  superrC   r   )rL   r  	__class__rS   rT   r     s    zCallableRemoteProgress.__init__)rM   rN   rJ   c                 O   s   | j || d S rX   )r  rQ   rS   rS   rT   r    s    zCallableRemoteProgress.update)
rP   r  r  r  r  r   r   r	   r  __classcell__rS   rS   r  rT   rC     s   c                   @   s
  e Zd ZdZedZedZdZdZ	dZ
dZdZd	Zd
Zee ee ddddZeedddZeedddZedddZedddZedddZeed dddZed'eeed d dd d!Zed(ed d d"d#d$Zed)ed d d"d%d&ZdS )*r?   zActors hold information about a person acting on the repository. They
    can be committers and authors or anything with a name and an email as
    mentioned in the git log entries.z<(.*)>z(.*) <(.*?)>ZGIT_AUTHOR_NAMEZGIT_AUTHOR_EMAILZGIT_COMMITTER_NAMEZGIT_COMMITTER_EMAILr   emailr   r"  N)r   r"  rJ   c                 C   s   || _ || _d S rX   r#  )rL   r   r"  rS   rS   rT   r     s    zActor.__init__)otherrJ   c                 C   s   | j |j ko| j|jkS rX   r#  rL   r$  rS   rS   rT   __eq__  s    zActor.__eq__c                 C   s
   | |k S rX   rS   r%  rS   rS   rT   __ne__  s    zActor.__ne__r   c                 C   s   t | j| jfS rX   )hashr   r"  r   rS   rS   rT   __hash__  s    zActor.__hash__c                 C   s   | j r| j S dS )Nrz   )r   r   rS   rS   rT   __str__  s    zActor.__str__c                 C   s   d| j | jf S )Nz<git.Actor "%s <%s>">r#  r   rS   rS   rT   __repr__  s    zActor.__repr__)stringrJ   c                 C   sT   | j |}|r&| \}}t||S | j|}|rFt|ddS t|dS dS )zCreate an Actor from a string.
        :param string: is the string, which is expected to be in regular git format

                John Doe <jdoe@example.com>

        :return: Actorr   N)name_email_regexsearchr   r?   name_only_regexgroup)clsr,  r   r   r"  rS   rS   rT   _from_string  s    
zActor._from_string)Nr   r   )env_name	env_emailconfig_readerrJ   c                    s   t dd}d tdfdd td fdd}d|| j|fd|| j ffD ]\}}}}	ztj| }
t|||
 W qN tk
r   |d k	rz|d	|}
W n t	k
r   |	 }
Y nX t|||
 t
||st|||	  Y qNX qN|S )
Nrz   r   c                      s    s
t    S rX   )r@   rS   )user_idrS   rT   default_email  s    z(Actor._main_actor.<locals>.default_emailc                      s      dd S )N@r   )r   rS   )r7  rS   rT   default_name  s    z'Actor._main_actor.<locals>.default_namer   r"  user)r?   rg   	conf_name
conf_emailrY   r   setattrKeyErrorr   rc   getattr)r1  r3  r4  r5  Zactorr9  attrZevarZcvardefaultvalrS   )r7  r6  rT   _main_actor  s(    


zActor._main_actor)r5  rJ   c                 C   s   |  | j| j|S )a  
        :return: Actor instance corresponding to the configured committer. It behaves
            similar to the git implementation, such that the environment will override
            configuration values of config_reader. If no value is set at all, it will be
            generated
        :param config_reader: ConfigReader to use to retrieve the values from in case
            they are not set in the environment)rC  env_committer_nameenv_committer_emailr1  r5  rS   rS   rT   	committer  s    	zActor.committerc                 C   s   |  | j| j|S )zSame as committer(), but defines the main author. It may be specified in the environment,
        but defaults to the committer)rC  env_author_nameenv_author_emailrF  rS   rS   rT   author  s    zActor.author)N)N)N) rP   r  r  r  r  r  r/  r-  rH  rI  rD  rE  r;  r<  r  r   rg   r   r	   r   r&  r'  r  r)  r*  r+  classmethodr2  r   rC  rG  rJ  rS   rS   rS   rT   r?     s<   

 '
c                   @   sB   e Zd ZdZdZeeeef dddZ	e
ded dddZd	S )
r:   a  
    Represents stat information as presented by git at the end of a merge. It is
    created from the output of a diff operation.

    ``Example``::

     c = Commit( sha1 )
     s = c.stats
     s.total         # full-stat-dict
     s.files         # dict( filepath : stat-dict )

    ``stat-dict``

    A dictionary with the following keys and values::

      deletions = number of deleted lines as int
      insertions = number of inserted lines as int
      lines = total number of lines changed as int, or deletions + insertions

    ``full-stat-dict``

    In addition to the items in the stat-dict, it features additional information::

     files = number of changed files as inttotalfilesc                 C   s   || _ || _d S rX   rL  )rL   rM  rN  rS   rS   rT   r   @  s    zStats.__init__r   )rO   textrJ   c                 C   s   dddddi d}|  D ]}|d\}}}|dkr@t|pBd}|dkrTt|pVd}	|d d  |7  < |d d  |	7  < |d d	  ||	 7  < |d d
  d7  < ||	||	 d}
|
|d
 | < qt|d |d
 S )zRCreate a Stat object from output retrieved by git-diff.

        :return: git.Statr   )
insertions	deletionslinesrN  rL  	-rM  rP  rQ  rR  rN  r   )rP  rQ  rR  )
splitlinesr   r  r   r:   )r1  rO   rO  Zhshr   Zraw_insertionsZraw_deletionsfilenamerP  rQ  Z
files_dictrS   rS   rT   _list_from_stringD  s"    zStats._list_from_stringN)rP   r  r  r  r  r&   r   r$   r'   r   rK  rg   rW  rS   rS   rS   rT   r:   #  s
   c                   @   s^   e Zd ZdZdZeddddZeeddd	Z	e
d
ddZe
d
ddZed
ddZdS )r;   a  Wrapper around a file-like object that remembers the SHA1 of
    the data written to it. It will write a sha when the stream is closed
    or if the asked for explicitly using write_sha.

    Only useful to the indexfile

    :note: Based on the dulwich project)r   sha1N)r   rJ   c                 C   s   || _ td| _d S )Nr   )r   r-   rX  )rL   r   rS   rS   rT   r   k  s    zIndexFileSHA1Writer.__init__)datarJ   c                 C   s   | j | | j|S rX   )rX  r  r   rs   )rL   rY  rS   rS   rT   rs   o  s    zIndexFileSHA1Writer.writer   c                 C   s   | j  }| j| |S rX   )rX  digestr   rs   rL   sharS   rS   rT   	write_shas  s    
zIndexFileSHA1Writer.write_shac                 C   s   |   }| j  |S rX   )r]  r   closer[  rS   rS   rT   r^  x  s    
zIndexFileSHA1Writer.closec                 C   s
   | j  S rX   )r   tellr   rS   rS   rT   r_  }  s    zIndexFileSHA1Writer.tell)rP   r  r  r  r  r   r   r
   r  rs   r   r]  r^  r_  rS   rS   rS   rT   r;   _  s   c                   @   sx   e Zd ZdZdZeddddZdddd	Zedd
dZ	e
dddZddddZddddZddddZdS )r>   a  Provides methods to obtain, check for, and release a file based lock which
    should be used to handle concurrent access to the same file.

    As we are a utility class to be derived from, we only use protected methods.

    Locks will automatically be released on destruction
_file_path
_owns_lockN)	file_pathrJ   c                 C   s   || _ d| _d S )NFr`  )rL   rc  rS   rS   rT   r     s    zLockFile.__init__r   c                 C   s   |    d S rX   )_release_lockr   rS   rS   rT   __del__  s    zLockFile.__del__c                 C   s
   d| j  S )z:return: Path to lockfilez%s.lock)ra  r   rS   rS   rT   _lock_file_path  s    zLockFile._lock_file_pathc                 C   s   | j S )z:return: True if we have a lock and if the lockfile still exists
        :raise AssertionError: if our lock-file does not exist)rb  r   rS   rS   rT   	_has_lock  s    zLockFile._has_lockc              
   C   s   |   rdS |  }t|r0td| j|f z<tjtjB tj	B }t
rR|tjO }t||d}t| W n0 tk
r } ztt||W 5 d}~X Y nX d| _dS )zCreate a lock file as flag for other instances, mark our instance as lock-holder

        :raise IOError: if a lock was already present or a lock file could not be writtenNzILock for file %r did already exist, delete %r in case the lock is illegalr   T)rg  rf  ri   rj   IOErrorra  rY   O_WRONLYO_CREATO_EXCLr   ZO_SHORT_LIVEDopenr^  OSErrorrg   rb  )rL   Z	lock_fileflagsfdr   rS   rS   rT   _obtain_lock_or_raise  s$    

 zLockFile._obtain_lock_or_raisec                 C   s   |   S )zThe default implementation will raise if a lock cannot be obtained.
        Subclasses may override this method to provide a different implementation)rp  r   rS   rS   rT   _obtain_lock  s    zLockFile._obtain_lockc                 C   s@   |   sdS |  }zt| W n tk
r4   Y nX d| _dS )zRelease our lock if we have oneNF)rg  rf  rm   rm  rb  )rL   ZlfprS   rS   rT   rd    s    zLockFile._release_lock)rP   r  r  r  r  r$   r   re  rg   rf  r   rg  rp  rq  rd  rS   rS   rS   rT   r>     s   c                       sH   e Zd ZdZdZdefeeedd fddZ	dd fd	d
Z
  ZS )r=   a  The lock file will block until a lock could be obtained, or fail after
    a specified timeout.

    :note: If the directory containing the lock was removed, an exception will
        be raised during the blocking period, preventing hangs as the lock
        can never be obtained.)_check_interval_max_block_timeg333333?N)rc  check_interval_smax_block_time_srJ   c                    s    t t| | || _|| _dS )a  Configure the instance

        :param check_interval_s:
            Period of time to sleep until the lock is checked the next time.
            By default, it waits a nearly unlimited time

        :param max_block_time_s: Maximum amount of seconds we may lockN)r  r=   r   rr  rs  )rL   rc  rt  ru  r  rS   rT   r     s    zBlockingLockFile.__init__r   c              
      s   t   }|t| j }ztt|   W q tk
r } zpt   }tt	| 
 std| 
 || f }t||||krd|| | 
 f }t||t | j W 5 d}~X Y qX qqdS )zThis method blocks until it obtained the lock, or raises IOError if
        it ran out of time or if the parent directory was not available anymore.
        If this method returns, you are guaranteed to own the lockzVDirectory containing the lockfile %r was not readable anymore after waiting %g secondsz Waited %g seconds for lock at %rN)timer  rs  r  r=   rq  rh  ri   r   r   rf  sleeprr  )rL   Z	starttimeZmaxtimer   Zcurtimemsgr  rS   rT   rq    s(    

zBlockingLockFile._obtain_lock)rP   r  r  r  r  r   r$   r  r  r   rq  r!  rS   rS   r  rT   r=     s   c                       s   e Zd ZdZdZdeedd fddZdeeddd	d
Zee	dddZ
eedddZeeeeef edddZeeeeef ddddZ  ZS )r<   as  
    List of iterable objects allowing to query an object by id or by named index::

     heads = repo.heads
     heads.master
     heads['master']
     heads[0]

    Iterable parent objects = [Commit, SubModule, Reference, FetchInfo, PushInfo]
    Iterable via inheritance = [Head, TagReference, RemoteReference]
    ]
    It requires an id_attribute name to be set which will be queried from its
    contained items to have a means for comparison.

    A prefix can be specified which is to be used in case the id returned by the
    items always contains a prefix that does not matter to the user, so it
    can be left out._id_attr_prefixrz   zIterableList[IterableObj])id_attrprefixrJ   c                    s   t t| | S rX   )r  r<   __new__)r1  r|  r}  r  rS   rT   r~    s    zIterableList.__new__Nc                 C   s   || _ || _d S rX   ry  )rL   r|  r}  rS   rS   rT   r     s    zIterableList.__init__)r@  rJ   c              	   C   sj   zt | |}|r|W S W n ttfk
r2   Y nX zt| tt| W dS  ttfk
rd   Y dS X d S )NTF)list__contains__AttributeError	TypeErrorr?  r   rg   )rL   r@  rvalrS   rS   rT   r  #  s    
zIterableList.__contains__c                 C   s8   | j | }| D ]}t|| j|kr|  S qt| |S rX   )r{  r?  rz  r  __getattribute__)rL   r@  itemrS   rS   rT   __getattr__5  s
    

zIterableList.__getattr__)r   rJ   c              
   C   s   t |tttfstdt |tr.t| |S t |trBtdnDzt| |W S  t	k
r } zt
d| j|  |W 5 d }~X Y nX d S )N-Index of IterableList should be an int or strzIndex should be an int or strzNo item found with id %r)r   r  rg   sliceAssertionErrorr  __getitem__r   r?  r  
IndexErrorr{  )rL   r   r   rS   rS   rT   r  =  s    


zIterableList.__getitem__c                 C   s   t |ttfstdtt|}t |tsvd}| j| }t| D ] \}}t|| j|kr@|} qbq@|dkrvt	d| t
| | d S )Nr  zItem with name %s not found)r   r  rg   r  r   r{  r   r?  rz  r  r  __delitem__)rL   r   Zdelindexr   r
  r  rS   rS   rT   r  L  s    


zIterableList.__delitem__)rz   )rz   )rP   r  r  r  r  rg   r~  r   objectr   r  r)   r  r   r!   r  r  r  r  r!  rS   rS   r  rT   r<     s   c                   @   s$   e Zd ZdZeeeddddZdS )IterableClassWatcherzMetaclass that watchesN)r   basesclsdictrJ   c                 C   s2   |D ](}t |tkrtjd| dtdd qd S )Nz!GitPython Iterable subclassed by zs. Iterable is deprecated due to naming clash since v3.1.18 and will be removed in 3.1.20, Use IterableObj instead 
   )
stacklevel)typer  warningswarnDeprecationWarning)r1  r   r  r  baserS   rS   rT   r   d  s    
zIterableClassWatcher.__init__)rP   r  r  r  rg   r   r   r   rS   rS   rS   rT   r  a  s   r  c                   @   sH   e Zd ZdZdZdZedeeedddZedeeeddd	Z	d
S )IterablezDefines an interface for iterable items which is to assure a uniform
    way to retrieve and iterate items within the git repositoryrS   z5attribute that most suitably identifies your instancer   rO   rM   rN   rJ   c                 O   s&   t | j}|| j|f|| |S )al  
        Deprecated, use IterableObj instead.
        Find all items of this type - subclasses can specify args and kwargs differently.
        If no args are given, subclasses are obliged to return all items if no additional
        arguments arg given.

        :note: Favor the iter_items method as it will

        :return:list(Item,...) list of item instancesr<   _id_attribute_extend
iter_itemsr1  rO   rM   rN   Zout_listrS   rS   rT   
list_itemsy  s    
zIterable.list_itemsc                 O   s   t ddS zbFor more information about the arguments, see list_items
        :return:  iterator yielding ItemszTo be implemented by SubclassNNotImplementedErrorr1  rO   rM   rN   rS   rS   rT   r    s    zIterable.iter_itemsN)
rP   r  r  r  r  r  rK  r	   r  r  rS   rS   rS   rT   r  q  s   r  )	metaclassc                   @   sZ   e Zd ZU dZdZeed< edeee	e
 dddZeedeeee
 ddd	Zd
S )r*   zDefines an interface for iterable items which is to assure a uniform
    way to retrieve and iterate items within the git repository

    Subclasses = [Submodule, Commit, Reference, PushInfo, FetchInfo, Remote]rS   r  r   r  c                 O   s&   t | j}|| j|f|| |S )a?  
        Find all items of this type - subclasses can specify args and kwargs differently.
        If no args are given, subclasses are obliged to return all items if no additional
        arguments arg given.

        :note: Favor the iter_items method as it will

        :return:list(Item,...) list of item instancesr  r  rS   rS   rT   r    s    

zIterableObj.list_itemsc                 O   s   t ddS r  r  r  rS   rS   rT   r    s    zIterableObj.iter_itemsN)rP   r  r  r  r  rg   r  rK  r	   r<   r)   r  r   r   r  rS   rS   rS   rT   r*     s   
c                   @   s   e Zd ZeddddZdS )NullHandlerN)recordrJ   c                 C   s   d S rX   rS   )rL   r  rS   rS   rT   emit  s    zNullHandler.emit)rP   r  r  r  r  rS   rS   rS   rT   r    s   r  )rn   )F)N).).)T)abcr   os.pathr]   ri   compatr   
contextlib	functoolsr   r   loggingrY   r   r   r  rh   ra   sysr   rv  urllib.parser   r   r  typingr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z
git.remoter   Zgit.repo.baser   Z
git.configr   r   gitr   typesr    r!   r"   r#   r$   r%   r&   r'   r(   r)   Z
gitdb.utilr-   r.   r/   r0   r1   r2   r3   r4   r5   __all__	getLoggerrP   r   r   r   rF   rG   rH   rE   contextmanagerr\   rD   rm   r  r6   r7   r   rg   r8   r   r   r9   r   rA   r   r   r   r  Ir   r  r   r   r   r   r   r@   r   r   r   r   r  rB   rC   r?   r:   r;   r>   r=   r<   r  r  r  r*   Handlerr  rS   rS   rS   rT   <module>   s    P,,
 	
"
  # ?x<"G>[#