U
    楡cV                     @   s  d Z ddlmZmZ ddlZddlmZmZmZ ddl	Z	ddl
mZ ddlmZ ddlZddlZddlmZmZm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! dd	l"m#Z#m$Z$m%Z% er<dd
l&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl"m6Z6m7Z7 neZ6dd Z7G dd deZ8edddZ9e ee d df df Z:dZ;edZ<e e=e>f e?ddd Z@e=e ed! ed" ed# ed$ f d%d&d'ZAe>e?d(d)d*ZBeCe>d+d,d-ZDe>e>d.d/d0ZEG d1d2 d2eZFeFdd3ZGeCeCed4d5d6ZHe e>ef ee?e?f d7d8d9ZIe	Jd:ZKe	Jd;ZLe>eee?e?f d<d=d>ZMG d?d@ d@eNZOe7G dAd de6ZPe7G dBdC dCe6ZQG dDd deePZRdS )Ez$Module for general utility functions    )ABCabstractmethodN)IterableListIterableObjActor)deque)digits)datetime	timedeltatzinfo)AnyCallableDequeIteratorGeneric
NamedTupleoverloadSequenceTYPE_CHECKINGTupleTypeTypeVarUnioncast)Has_id_attributeLiteral_T)BytesIOStringIO   )Commit)Blob)	TagObject)TreeTraversedTreeTup)Popen)	Submodule)Protocolruntime_checkablec                 C   s   | S N )fr*   r*   4/tmp/pip-unpacked-wheel-_pbxsds5/git/objects/util.pyr(   7   s    r(   c                   @   s.   e Zd ZU eed< ed ed< ed ed< dS )
TraverseNTdepthTraversabler!   itemr0   NsrcN)__name__
__module____qualname__int__annotations__r   r*   r*   r*   r,   r-   ;   s   
r-   T_TIobjTraversableIterableObj)boundr2   r0   r$   )get_object_type_by_name
parse_dateparse_actor_and_dateProcessStreamAdapterr0   altz_to_utctz_strutctz_to_altzverify_utctzr   tzoffsetutc)modestrreturnc                 C   sL   d}t t| dd D ].\}}ttttf |}|t||d > 7 }q|S )a_  
    :param modestr: string like 755 or 644 or 100644 - only the last 6 chars will be used
    :return:
        String identifying a mode compatible to the mode methods ids of the
        stat module regarding the rwx permissions for user, group and other,
        special flags and file system flags, i.e. whether it is a symlink
        for example.r   N   )	enumeratereversedr   r   strr7   )rE   mode	iterationcharr*   r*   r,   mode_str_to_int]   s
    rO   r    r"   r#   r!   )object_type_namerF   c                 C   s|   | dkrddl m} |jS | dkr4ddl m} |jS | dkrNddl m} |jS | dkrhdd	l m} |jS t	d
| 
  dS )z
    :return: type suitable to handle the given object type name.
        Use the type to create new instances.

    :param object_type_name: Member of TYPES

    :raise ValueError: In case object_type_name is unknowns   commitr   )commits   tag)tags   blob)blobs   tree)treez%Cannot handle unknown object type: %sN) rQ   r    rR   r"   rS   r!   rT   r#   
ValueErrordecode)rP   rQ   rR   rS   rT   r*   r*   r,   r<   m   s    
r<   )utctzrF   c                 C   s   dt t| d d  S )a  we convert utctz to the timezone in seconds, it is the format time.altzone
    returns. Git stores it as UTC timezone which has the opposite sign as well,
    which explains the -1 * ( that was made explicit here )
    :param utctz: git utc timezone string, i.e. +0200d     )r7   float)rX   r*   r*   r,   rA      s    rA   )altzrF   c                 C   sP   dt t| d d  }tt|}ddt|  | }|dk rDdpFd}|| S )	z_As above, but inverses the operation, returning a string that can be used
    in commit objectsrY   r[   rZ   0   r   -+)r7   r\   rK   abslen)r]   ZutciZutcsprefixr*   r*   r,   r@      s
    r@   )offsetrF   c                 C   sd   t d|  }t| dkr|| d dkr,|| d tks\| d tks\| d tks\| d tkr`|| S )	z=:raise ValueError: if offset is incorrect
    :return: offsetz"Invalid timezone offset format: %s   r   z+-r      rH   r_   )rV   rc   r   )re   Zfmt_excr*   r*   r,   rB      s    0rB   c                   @   s   e Zd Zdeedef ddddZeed  eeef f dddZ	ee
df edd	d
Zee
df edddZee
df edddZdS )rC   N)secs_west_of_utcnamerF   c                 C   s   t | d| _|pd| _d S )N)secondsZfixed)r
   _offset_name)selfrh   ri   r*   r*   r,   __init__   s    ztzoffset.__init__)rF   c                 C   s   t | j  | jffS r)   )rC   rk   total_secondsrl   rm   r*   r*   r,   
__reduce__   s    ztzoffset.__reduce__)dtrF   c                 C   s   | j S r)   )rk   rm   rr   r*   r*   r,   	utcoffset   s    ztzoffset.utcoffsetc                 C   s   | j S r)   )rl   rs   r*   r*   r,   tzname   s    ztzoffset.tznamec                 C   s   t S r)   )ZEROrs   r*   r*   r,   dst   s    ztzoffset.dst)N)r4   r5   r6   r\   r   rK   rn   r   r   rq   r	   r
   rt   ru   rw   r*   r*   r*   r,   rC      s
   "rC   UTC)	timestamp	tz_offsetrF   c                 C   s>   t | t}z|t|}|W S  tk
r8   | Y S X dS )zAConverts a timestamp + tz_offset into an aware datetime instance.N)r	   fromtimestamprD   
astimezonerC   rV   )ry   rz   Zutc_dtZlocal_dtr*   r*   r,   from_timestamp   s    r}   )string_daterF   c                 C   sJ  t | trP| jrBtt|  }t|  }t| t	
 |fS td|  z| ddkr| ddkr|  \}}|dr|dd }t|}|tt|fW S d}| d	 d
krt| d	d }| dd } t|}g }d}d| kr|d | d}nF|d |d |d |d | d}|dkrN| d}|dks\t| |d d }| d| }	t|d}
|D ]r}zNt|	|}t|j|j|j|
j|
j|
j|j|j|
j f	}t||fW   W S  tk
r   Y qY nX qtdW n> t!k
rD } ztd|  dt"|  |W 5 d}~X Y nX dS )a  
    Parse the given date as one of the following

        * aware datetime instance
        * Git internal format: timestamp offset
        * RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
        * ISO 8601 2005-04-07T22:13:13
            The T can be a space as well

    :return: Tuple(int(timestamp_UTC), int(offset)), both in seconds since epoch
    :raise ValueError: If the format could not be understood
    :note: Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY.
    z,string_date datetime object without tzinfo,  r   :rY   @Nz+0000z-+rG   ,z%a, %d %b %Yz%Y-%m-%dz%Y.%m.%dz%m/%d/%Yz%d.%m.%YTz%H:%M:%Szno format matchedz!Unsupported date format or type: z, type=)#
isinstancer	   r   r   r
   rt   r7   ro   r|   rD   ry   rV   countrfindsplit
startswithrA   rB   appendAssertionErrortimestrptimecalendartimegmtm_yeartm_montm_mdaytm_hourtm_mintm_sectm_wdaytm_ydaytm_isdst	Exceptiontype)r~   rt   re   ry   Z
offset_strZtimestamp_intZdate_formatsZsplitterZ	time_partZ	date_partZtstructfmtZdtstructZutctimeer*   r*   r,   r=      sn    










r=   z^.+? (.*) (\d+) ([+-]\d+).*$z
^.+? (.*)$)linerF   c                 C   s`   d\}}}t | }|r(| \}}}n t| }|r@|dn| pFd}t|t|t|fS )zParse out the actor (author or committer) info from a line like::

        author Tom Preston-Werner <tom@mojombo.com> 1191999972 -0700

    :return: [Actor, int_seconds_since_epoch, int_timezone_offset])rU   r^   r^   r   rU   )	_re_actor_epochsearchgroups_re_only_actorgroupr   Z_from_stringr7   rA   )r   Zactorepochre   mr*   r*   r,   r>   /  s    


r>   c                   @   s6   e Zd ZdZdZdeddddZeedd	d
ZdS )r?   a  Class wireing all calls to the contained Process instance.

    Use this type to hide the underlying process to provide access only to a specified
    stream. The process is usually wrapped into an AutoInterrupt class to kill
    it if the instance goes out of scope.)_proc_streamr%   N)processstream_namerF   c                 C   s   || _ t||| _d S r)   )r   getattrr   )rm   r   r   r*   r*   r,   rn   O  s    zProcessStreamAdapter.__init__)attrrF   c                 C   s   t | j|S r)   )r   r   )rm   r   r*   r*   r,   __getattr__S  s    z ProcessStreamAdapter.__getattr__)	r4   r5   r6   __doc__	__slots__rK   rn   r   r   r*   r*   r*   r,   r?   E  s   r?   c                   @   s   e Zd ZdZdZeeeed  dddZ	eeeedddZ
deeeeed
  dddZeeeedddZdd dd ddddd	feed def egef eed def egef eeeeeeeed  ee f dddZdS )r0   zSimple interface to perform depth-first or breadth-first traversals
    into one direction.
    Subclasses only need to implement one function.
    Instances of the Subclass must be hashable

    Defined subclasses = [Commit, Tree, SubModule]
    r*   )r1   rF   c                 C   s   t ddS )a@  
        Returns:
            Tuple of items connected to the given item.
            Must be implemented in subclass

        class Commit::     (cls, Commit) -> Tuple[Commit, ...]
        class Submodule::  (cls, Submodule) -> Iterablelist[Submodule]
        class Tree::       (cls, Tree) -> Tuple[Tree, ...]
        To be implemented in subclassNNotImplementedError)clsr1   r*   r*   r,   _get_intermediate_itemsd  s    z#Traversable._get_intermediate_items)argskwargsrF   c                 O   s   t jdtdd | j||S )r   zlist_traverse() method should only be called from subclasses.Calling from Traversable abstract class will raise NotImplementedError in 3.1.20Builtin sublclasses are 'Submodule', 'Tree' and 'Commitrg   
stacklevel)warningswarnDeprecationWarning_list_traverserm   r   r   r*   r*   r,   list_traverser  s    zTraversable.list_traverseF)r    r&   r#   r!   )as_edger   r   rF   c                 O   sX   t | tr| j}nd}|s@t|}|| j|d|i| |S t| j||}|S dS )a  
        :return: IterableList with the results of the traversal as produced by
            traverse()
            Commit -> IterableList['Commit']
            Submodule ->  IterableList['Submodule']
            Tree -> IterableList[Union['Submodule', 'Tree', 'Blob']]
        rU   r   N)r   r   Z_id_attribute_r   extendtraverse)rm   r   r   r   idoutZout_listr*   r*   r,   r   ~  s    
zTraversable._list_traversec                 O   s   t jdtdd | j||S )r   ztraverse() method should only be called from subclasses.Calling from Traversable abstract class will raise NotImplementedError in 3.1.20Builtin sublclasses are 'Submodule', 'Tree' and 'Commitrg   r   )r   r   r   	_traverser   r*   r*   r,   r     s    zTraversable.traversec                 C   s   dS NTr*   idr*   r*   r,   <lambda>      zTraversable.<lambda>c                 C   s   dS NFr*   r   r*   r*   r,   r     r   rY   Tr   r!   r/   )	predicatepruner.   branch_first
visit_onceignore_selfr   rF   c                 #   s   t  }t }	|	tdd tt dttdd fdd}
|	r|	 \} }|r^ |kr^q>|rl|  |rz| f}n }|||rq>|o k}|s|||r|V  |d }|dkr||krq>|
|	 || q>dS )	aF  :return: iterator yielding of items found when traversing self
        :param predicate: f(i,d) returns False if item i at depth d should not be included in the result

        :param prune:
            f(i,d) return True if the search should stop at item i at depth d.
            Item i will not be returned.

        :param depth:
            define at which level the iteration should not go deeper
            if -1, there is no limit
            if 0, you would effectively only get self, the root of the iteration
            i.e. if 1, you would only get the first level of predecessors/successors

        :param branch_first:
            if True, items will be returned branch first, otherwise depth first

        :param visit_once:
            if True, items will only be returned once, although they might be encountered
            several times. Loops are prevented that way.

        :param ignore_self:
            if True, self will be ignored and automatically pruned from
            the result. Otherwise it will be the first item to be returned.
            If as_edge is True, the source of the first edge is None

        :param as_edge:
            if True, return a pair of items, first being the source, second the
            destination, i.e. tuple(src, dest) with the edge spanning from
            source to destinationr   Nr0   )stacksrc_itemr   r.   rF   c                    sf    sd S |r2|  fddD  n0 fddttd ddD }| | d S )Nc                 3   s   | ]}t  |V  qd S r)   r-   .0r   )r.   r   r*   r,   	<genexpr>  s     z<Traversable._traverse.<locals>.addToStack.<locals>.<genexpr>c                 3   s   | ]}t  | V  qd S r)   r   r   r.   lstr   r*   r,   r     s     r   rY   )r   
extendleftrangerc   r   )r   r   r   r.   Zreviterr1   rm   r   r,   
addToStack  s    
&z)Traversable._traverse.<locals>.addToStackr   rY   )	setr   r   r-   r   boolr7   popadd)rm   r   r   r.   r   r   r   r   visitedr   r   r   r3   rvalZskipStartItemZndr*   r   r,   r     s6    3


zTraversable._traverseN)F)r4   r5   r6   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   TraversedTupr7   r   r   r*   r*   r*   r,   r0   W  sB      
c                   @   s4   e Zd ZdZdZdd dddZdd dddZd	S )
SerializablezPDefines methods to serialize and deserialize objects from and into a data streamr*   r   )streamrF   c                 C   s   t ddS )zSerialize the data of this object into the given data stream
        :note: a serialized object would ``_deserialize`` into the same object
        :param stream: a file-like object
        :return: selfr   Nr   rm   r   r*   r*   r,   
_serialize  s    zSerializable._serializec                 C   s   t ddS )zDeserialize all information regarding this object from the stream
        :param stream: a file-like object
        :return: selfr   Nr   r   r*   r*   r,   _deserialize  s    zSerializable._deserializeN)r4   r5   r6   r   r   r   r   r*   r*   r*   r,   r     s   r   c                       s6  e Zd ZdZeeedf ef Zeeee	e d fddZ
eeee dddZeeeeeeeedf ef f egef eeeeeedf ef f egef eeeed	 ed
 ee d	ddZeeeeeeeedf ef f egef eeeeeedf ef f egef eeeed
 ed	 eeeedf ef  d	ddZeeeeeef egef eeeef egef eeeed	 ed	 eeeef  d	ddZdd dd dd	d	dd
feeeeef egef eeeef egef eeeeeeee eeeef  ee f d	 fddZ  ZS )r:   r*   N)rm   r   r   rF   c                    s   t t| j||S r)   )superr:   r   r   	__class__r*   r,   r   *  s    z$TraversableIterableObj.list_traverse)rm   rF   c                 C   s   d S r)   r*   rp   r*   r*   r,   r   -  s    zTraversableIterableObj.traverseTF)	rm   r   r   r.   r   r   r   r   rF   c                 C   s   d S r)   r*   rm   r   r   r.   r   r   r   r   r*   r*   r,   r   1  s    c                 C   s   d S r)   r*   r   r*   r*   r,   r   >  s    c                 C   s   d S r)   r*   r   r*   r*   r,   r   K  s    c                 C   s   dS r   r*   r   r*   r*   r,   r   Z  r   zTraversableIterableObj.<lambda>c                 C   s   dS r   r*   r   r*   r*   r,   r   [  r   rY   r   c                    sB   t ttt tttdtf tf  f tt| |||||||S )z3For documentation, see util.Traversable._traverse()N)r   r   r   r9   r   r   r:   r   r   r   r*   r,   r   X  s    "
      )r4   r5   r6   r   r   r   r9   ZTIobj_tupler   r   r   r   r   r   r   r7   r   r   __classcell__r*   r*   r   r,   r:   %  sp   &&&& )Sr   abcr   r   r   Zgit.utilr   r   r   recollectionsr   stringr   r   r   r	   r
   r   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   Z	git.typesr   r   r   ior   r   rQ   r    rS   r!   rR   r"   rT   r#   r$   
subprocessr%   Zsubmodule.baser&   r'   r(   r-   r9   r   __all__rv   bytesrK   r7   rO   r<   rA   r\   r@   rB   rC   rD   r}   r=   compiler   r   r>   objectr?   r0   r   r:   r*   r*   r*   r,   <module>   sh   @


 a

 7