U
    楡c                     @  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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mZ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'm(Z( d dl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0m1Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8 d dl9Z9d dl:Z:d dl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA d dlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR d dl;mSZSmTZT eRrd dl)mUZU d dlVmWZW d dlmXZX d dlYmZZZ d dl%m[Z[ e\e]Z^dZ_G dd dePZ`G dd deaZbdS )    )annotationsN)LooseObjectDB)	BadObject)Githandle_process_output)defencsafe_decodeis_win)GitConfigParser)GitCmdObjectDB)InvalidGitRepositoryErrorNoSuchPathErrorGitCommandError	IndexFile)	Submodule
RootModuleCommit)HEADHead	ReferenceTagReference)Remoteadd_progressto_progress_instance)Actorfinalize_processcygpath
hex_to_binexpand_pathremove_password_if_present   )	rev_parse
is_git_dirfind_submodule_git_dirtouchfind_worktree_git_dir)TBDPathLikeLit_config_levels
Commit_ishTree_ishassert_never)AnyBinaryIOCallableDictIteratorListMappingOptionalSequenceTextIOTupleTypeUnion
NamedTuplecastTYPE_CHECKING)ConfigLevels_Tup	TypedDict)IterableList)SymbolicReference)Tree)UpdateProgress)RemoteProgress)Repoc                   @  s.   e Zd ZU ded< ded< ded< ded< dS )	
BlameEntryzDict[str, 'Commit']commitrangeZlinenosOptional[str]	orig_pathZorig_linenosN__name__
__module____qualname____annotations__ rO   rO   1/tmp/pip-unpacked-wheel-_pbxsds5/git/repo/base.pyrE   ^   s   
rE   c                   @  sl  e Zd ZU dZdZeddZdZded< dZ	ded< dZ
d	ed
< dZd	ed< edZedZedZedZedZedZdZded< eZdeddfddddddddZdddd Zd!dd"d#d$Zddd%d&Zddd'd(Zd)dd*d+d,Zd)dd*d-d.Zd/dd0d1Zd2dd3d4Z d2dd5d6d7Z!e"e e!d8d9Z#[ [!e"ddd:d;Z$e"d	dd<d=Z%e"ddd>d?Z&e"d@ddAdBZ'e"dCddDdEZ(e(Z)e'Z*e"dFddGdHZ+e"dIddJdKZ,e"dLddMdNZ-dd2dPdQdRdSZ.e"dTddUdVZ/d2dWdQdXdYZ0d!d!dZd[d\d]Z1d!d!d^d[d_d`Z2d!d!d^d[dadbZ3e"dcddddeZ4d	dfdgdhdiZ5e6d	d2dgdjdkZ7dd	dmddndodpdqdrZ8dsd!ddtdudvZ9dd	d2dndd!dfdwdxdyZ:dfddzd{d|Z;d2d2d!d}d~ddZ<dPd2dddZ=dd2dddZ>ddddddZ?ddddddZ@ddddddZAd!d!dd[ddZBddddddZCdddd!ddddZDdd!ddddZEddddddZFdd2dddddZGddddZHd)ddddZIe"eHeIdd9ZJ[H[IddddZKdddddZLe"eKeLdd9ZMddddddddddZNe"ddddZOd!d!dd[ddZPd	ddddĄZQe"ddddǄZRdd2d!ddʜdd̄ZSddd2ddd!ddМdd҄ZTeUddedfddddd!dd՜ddׄZVeUddd	d	dddd!ddڜdd܄ZWdd	ddd!ddޜddZXeUdd	d	dddd!ddddZYdddndnd!d dddZZddddZ[e\Z\d2dddZ]ddddZ^dS )rD   a2  Represents a git repository and allows you to query references,
    gather commit information, generate diffs, create and clone repositories query
    the log.

    The following attributes are worth using:

    'working_dir' is the working directory of the git command, which is the working tree
    directory if available or the .git directory in case of bare repositories

    'working_tree_dir' is the working tree directory, but will raise AssertionError
    if we are a bare repository.

    'git_dir' is the .git repository directory, which is always set.zgit-daemon-export-okr   NzOptional[PathLike]working_dir_working_tree_dir r(   git_dir_common_dirz\s+z^[0-9A-Fa-f]{40}$z^[0-9A-Fa-f]{4,40}$z5(\$(\{\s?)?[a-zA-Z_]\w*(\}\s?)?|%\s?[a-zA-Z_]\w*\s?%)z^(author|committer)z^\t(.*)$)systemuserglobal
repositoryr=   config_levelFTzType[LooseObjectDB]boolNone)pathodbtsearch_parent_directoriesexpand_varsreturnc                 C  s  |pt d}|st  }t r*t|}|p8|p8t  }t|tsLt|}|rht	| j
|rhtd t||}|dk	rt j|st||}|rt|r|| _t j| j| _t jddkr| d}|ddr|dd| _dt jkrt d| _qt|d	}t|}	|	dk	r2t|	| _t|}	|	dkrLt|}	|	dk	rlt|	|| _|| _q|svqt|\}}
|
sqq| jdkrt|d
| _ z| d!dd| _ W n t"k
r   Y nX z4t#t| jdd$ d % }t| j|| _&W n t'k
r(   d| _&Y nX | j r8d| _| jpD| j(| _)| *| j)| _+t| j(d}t,|t-r||| j+| _.n
||| _.dS )a	  Create a new Repo instance

        :param path:
            the path to either the root git directory or the bare git repo::

                repo = Repo("/Users/mtrier/Development/git-python")
                repo = Repo("/Users/mtrier/Development/git-python.git")
                repo = Repo("~/Development/git-python.git")
                repo = Repo("$REPOSITORIES/Development/git-python.git")
                repo = Repo("C:\Users\mtrier\Development\git-python\.git")

            - In *Cygwin*, path may be a `'cygdrive/...'` prefixed path.
            - If it evaluates to false, :envvar:`GIT_DIR` is used, and if this also evals to false,
              the current-directory is used.
        :param odbt:
            Object DataBase type - a type which is constructed by providing
            the directory containing the database objects, i.e. .git/objects. It will
            be used to access all object data
        :param search_parent_directories:
            if True, all parent directories will be searched for a valid repo as well.

            Please note that this was the default behaviour in older versions of GitPython,
            which is considered a bug though.
        :raise InvalidGitRepositoryError:
        :raise NoSuchPathError:
        :return: git.RepoGIT_DIRzoThe use of environment variables in paths is deprecated
for security reasons and may be removed in the future!!NZGIT_COMMON_DIRrY   coreZworktreeGIT_WORK_TREE.gitFbareZ	commondirrtr   rS   objects)/osgetenvgetcwdr   	is_cygwinr   
isinstancestrresearch
re_envvarswarningswarnr   r]   existsr   r#   rT   dirnamerR   environgetconfig_reader
has_optionospjoinr$   normpathr&   splitr   _bare
getboolean	Exceptionopen	readlinesstriprU   OSError
common_dirrQ   GitCommandWrapperTypegit
issubclassr   odb)selfr]   r^   r_   r`   ZepathZcurpathZgitconfZdotgitZ
sm_gitpathtailr   ZrootpathrO   rO   rP   __init__   s    "


	



 zRepo.__init__z'Repo')ra   c                 C  s   | S NrO   r   rO   rO   rP   	__enter__  s    zRepo.__enter__r-   )argsra   c                 G  s   |    d S r   )close)r   r   rO   rO   rP   __exit__  s    zRepo.__exit__c                 C  s&   z|    W n tk
r    Y nX d S r   )r   r   r   rO   rO   rP   __del__  s    zRepo.__del__c                 C  s8   | j r4| j   trt  tjj  tr4t  d S r   )r   clear_cacher	   gcZcollectgitdbutilZmmanr   rO   rO   rP   r      s    
z
Repo.closeobject)rhsra   c                 C  s    t |tr| jr| j|jkS dS )NF)rm   rD   rT   r   r   rO   rO   rP   __eq__/  s    zRepo.__eq__c                 C  s   |  | S r   )r   r   rO   rO   rP   __ne__4  s    zRepo.__ne__intc                 C  s
   t | jS r   )hashrT   r   rO   rO   rP   __hash__7  s    zRepo.__hash__rn   c              
   C  sH   | j rt| j d}t|d }|  tW  5 Q R  S Q R X d S )Ndescriptionrb)rT   rz   r{   r   readrstripdecoder   )r   filenamefprO   rO   rP   _get_description;  s    zRepo._get_description)descrra   c              	   C  sB   | j rt| j d}t|d}||d t W 5 Q R X d S )Nr   wb
)rT   rz   r{   r   writeencoder   )r   r   r   r   rO   rO   rP   _set_descriptionA  s    zRepo._set_descriptionzthe project's description)docc                 C  s   | j S )zj:return: The working tree directory of our git repository. If this is a bare repository, None is returned.)rR   r   rO   rO   rP   working_tree_dirK  s    zRepo.working_tree_dirc                 C  s"   | j r| j S | jr| jS t dS )z
        :return: The git dir that holds everything except possibly HEAD,
            FETCH_HEAD, ORIG_HEAD, COMMIT_EDITMSG, index, and logs/.N)rU   rT   r   r   rO   rO   rP   r   P  s
    zRepo.common_dirc                 C  s   | j S )z':return: True if the repository is bare)r~   r   rO   rO   rP   rf   ]  s    z	Repo.barez'IterableList[Head]'c                 C  s
   t | S )zA list of ``Head`` objects representing the branch heads in
        this repo

        :return: ``git.IterableList(Head, ...)``)r   
list_itemsr   rO   rO   rP   headsb  s    z
Repo.headsz'IterableList[Reference]'c                 C  s
   t | S )zzA list of Reference objects representing tags, heads and remote references.

        :return: IterableList(Reference, ...))r   r   r   rO   rO   rP   
referencesj  s    zRepo.referencesz'IndexFile'c                 C  s   t | S )z:return: IndexFile representing this repository's index.
        :note: This property can be expensive, as the returned ``IndexFile`` will be
         reinitialized. It's recommended to re-use the object.r   r   rO   rO   rP   indexw  s    z
Repo.indexz'HEAD'c                 C  s
   t | dS )z;:return: HEAD Object pointing to the current head referencer   )r   r   rO   rO   rP   head~  s    z	Repo.headz'IterableList[Remote]'c                 C  s
   t | S )zuA list of Remote objects allowing to access and manipulate remotes
        :return: ``git.IterableList(Remote, ...)``)r   r   r   rO   rO   rP   remotes  s    zRepo.remotesoriginz'Remote')namera   c                 C  s"   t | |}| std| |S )zh:return: Remote with the specified name
        :raise ValueError:  if no remote with such a name existszRemote named '%s' didn't exist)r   rt   
ValueError)r   r   rrO   rO   rP   remote  s    
zRepo.remotez'IterableList[Submodule]'c                 C  s
   t | S )zs
        :return: git.IterableList(Submodule, ...) of direct submodules
            available from the current head)r   r   r   rO   rO   rP   
submodules  s    zRepo.submodulesz'Submodule'c              
   C  sB   z| j | W S  tk
r< } ztd| |W 5 d}~X Y nX dS )z]:return: Submodule with the given name
        :raise ValueError: If no such submodule existszDidn't find submodule named %rN)r   
IndexErrorr   )r   r   erO   rO   rP   	submodule  s    zRepo.submoduler   )r   kwargsra   c                 O  s   t j| f||S )zCreate a new submodule

        :note: See the documentation of Submodule.add for a description of the
            applicable parameters
        :return: created submodules)r   addr   r   r   rO   rO   rP   create_submodule  s    zRepo.create_submodulezIterator[Submodule]c                 O  s   t | j||S )zAn iterator yielding Submodule instances, see Traversable interface
        for a description of args and kwargs
        :return: Iterator)r   Ztraverser   rO   rO   rP   iter_submodules  s    zRepo.iter_submodulesc                 O  s   t | j||S )zUpdate the submodules, keeping the repository consistent as it will
        take the previous state into consideration. For more information, please
        see the documentation of RootModule.update)r   updater   rO   rO   rP   submodule_update  s    zRepo.submodule_updatez'IterableList[TagReference]'c                 C  s
   t | S )zrA list of ``Tag`` objects that are available in this repo
        :return: ``git.IterableList(TagReference, ...)``)r   r   r   rO   rO   rP   tags  s    z	Repo.tagsr   )r]   ra   c                 C  s   |  |}t| |S )z:return: TagReference Object, reference pointing to a Commit or Tag
        :param path: path to the tag reference, i.e. 0.1.5 or tags/0.1.5)_to_full_tag_pathr   )r   r]   	full_pathrO   rO   rP   tag  s    
zRepo.tagc                 C  sL   t | }|tjd r|S |tjd r:tjd | S tjd | S d S )N/)rn   
startswithr   Z_common_path_defaultZ_common_defaultr   )r]   Zpath_strrO   rO   rP   r     s    zRepo._to_full_tag_pathr   z#Union[('SymbolicReference', 'str')]rH   z'Head')r]   rF   forcelogmsgra   c                 C  s   t | ||||S )zCreate a new head within the repository.
        For more documentation, please see the Head.create method.

        :return: newly created Head Reference)r   create)r   r]   rF   r   r   rO   rO   rP   create_head  s    zRepo.create_headz'Union[str, Head]')r   r   ra   c                 O  s   t j| f||S )zfDelete the given heads

        :param kwargs: Additional keyword arguments to be passed to git-branch)r   delete)r   r   r   rO   rO   rP   delete_head  s    zRepo.delete_head)r]   refmessager   r   ra   c                 K  s   t j| ||||f|S )zCreate a new tag reference.
        For more documentation, please see the TagReference.create method.

        :return: TagReference object)r   r   )r   r]   r   r   r   r   rO   rO   rP   
create_tag  s    zRepo.create_tag)r   ra   c                 G  s   t j| f| S )zDelete the given tag references)r   r   )r   r   rO   rO   rP   
delete_tag  s    zRepo.delete_tagr   )r   urlr   ra   c                 K  s   t j| ||f|S )zCreate a new remote.

        For more information, please see the documentation of the Remote.create
        methods

        :return: Remote reference)r   r   )r   r   r   r   rO   rO   rP   create_remote  s    zRepo.create_remote)r   ra   c                 C  s   t | |S )zDelete the given remote.)r   remove)r   r   rO   rO   rP   delete_remote  s    zRepo.delete_remoter)   )rZ   ra   c              	   C  s   t r|dkrd}|dkrdS |dkr`tjdpDttjddd}ttt|d	d
S |dkrxttdS |dkr| jp| j	}|st
qtt|d
S nt|td| d S )NrV   rX   z/etc/gitconfigrW   XDG_CONFIG_HOMEHOME~z.configr   configz~/.gitconfigrY   zInvalid configuration level: )r	   ri   rv   rw   rz   r{   r|   
expanduserrU   rT   NotADirectoryErrorr,   r   )r   rZ   Zconfig_homerepo_dirrO   rO   rP   _get_config_path  s$    "zRepo._get_config_pathzOptional[Lit_config_levels]r
   c                   s<   d}|dkr" fdd j D }n |g}t|d dS )aw  
        :return:
            GitConfigParser allowing to read the full git configuration, but not to write it

            The configuration will include values from the system, user and repository
            configuration files.

        :param config_level:
            For possible values, see config_writer method
            If None, all applicable levels will be used. Specify a level in case
            you know which file you wish to read to prevent reading multiple files.
        :note: On windows, system configuration cannot currently be read as the path is
            unknown, instead the global path will be used.Nc                   s&   g | ]}t t|r t t|qS rO   )r;   r)   r   ).0fr   rO   rP   
<listcomp>.  s   
z&Repo.config_reader.<locals>.<listcomp>TZ	read_onlyrepo)rZ   r   r
   )r   rZ   filesrO   r   rP   rx     s    
zRepo.config_readerrY   c                 C  s   t | |d| dS )a:  
        :return:
            GitConfigParser allowing to write values of the specified configuration file level.
            Config writers should be retrieved, used to change the configuration, and written
            right away as they will lock the configuration file in question and prevent other's
            to write it.

        :param config_level:
            One of the following values
            system = system wide configuration file
            global = user level configuration file
            repository = configuration file for this repository onlyFr   )r
   r   )r   rZ   rO   rO   rP   config_writer7  s    zRepo.config_writerzUnion[str, Commit_ish, None]r   )revra   c                 C  s"   |dkr| j jS | t|d S )zThe Commit object for the specified revision

        :param rev: revision specifier, see git-rev-parse for viable options.
        :return: ``git.Commit``
        Nz^0)r   rF   r"   rn   r   r   rO   rO   rP   rF   F  s    zRepo.commitzIterator['Tree']c                 O  s   dd | j ||D S )zg:return: Iterator yielding Tree objects
        :note: Takes all arguments known to iter_commits methodc                 s  s   | ]}|j V  qd S r   )tree)r   crO   rO   rP   	<genexpr>S  s     z"Repo.iter_trees.<locals>.<genexpr>)iter_commitsr   rO   rO   rP   
iter_treesP  s    zRepo.iter_treeszUnion[Tree_ish, str, None]z'Tree'c                 C  s$   |dkr| j jjS | t|d S )a  The Tree object for the given treeish revision
        Examples::

              repo.tree(repo.heads[0])

        :param rev: is a revision pointing to a Treeish ( being a commit or tree )
        :return: ``git.Tree``

        :note:
            If you need a non-root level tree, find it by iterating the root tree. Otherwise
            it cannot know about its path relative to the repository root and subsequent
            operations might have unexpected results.Nz^{tree})r   rF   r   r"   rn   r   rO   rO   rP   r   U  s    
z	Repo.treez-Union[str, Commit, 'SymbolicReference', None]z#Union[PathLike, Sequence[PathLike]]zIterator[Commit])r   pathsr   ra   c                 K  s"   |dkr| j j}tj| ||f|S )a  A list of Commit objects representing the history of a given ref/commit

        :param rev:
            revision specifier, see git-rev-parse for viable options.
            If None, the active branch will be used.

        :param paths:
            is an optional path or a list of paths; if set only commits that include the path
            or paths will be returned

        :param kwargs:
            Arguments to be passed to git-rev-list - common ones are
            max_count and skip

        :note: to receive only commits between two named revisions, use the
            "revA...revB" revision specifier

        :return: ``git.Commit[]``N)r   rF   r   Z
iter_items)r   r   r   r   rO   rO   rP   r   f  s    zRepo.iter_commitsr'   zList[Union[Commit_ish, None]])r   r   ra   c              
   O  s   t |dk rtdt | g }z| jj|| }W n6 tk
rl } z|jdkrT | W Y S d}~X Y nX |D ]}|| | qr|S )a  Find the closest common ancestor for the given revision (e.g. Commits, Tags, References, etc)

        :param rev: At least two revs to find the common ancestor for.
        :param kwargs: Additional arguments to be passed to the repo.git.merge_base() command which does all the work.
        :return: A list of Commit objects. If --all was not specified as kwarg, the list will have at max one Commit,
            or is empty if no common merge base exists.
        :raises ValueError: If not at least two revs are provided
           z-Please specify at least two revs, got only %i   N)	lenr   r   
merge_base
splitlinesr   statusappendrF   )r   r   r   reslineserrlinerO   rO   rP   r     s    	
zRepo.merge_basez'Commit')ancestor_revr   ra   c              
   C  sT   z| j j||dd W n8 tk
rN } z|jdkr<W Y 
dS  W 5 d}~X Y nX dS )zCheck if a commit is an ancestor of another

        :param ancestor_rev: Rev which should be an ancestor
        :param rev: Rev to test against ancestor_rev
        :return: ``True``, ancestor_rev is an ancestor to rev.
        T)is_ancestorr!   FN)r   r   r   r   )r   r   r   r   rO   rO   rP   r     s    

zRepo.is_ancestorzUnion[str, None])shaobject_typera   c                 C  s|   zV| j |}| j |}|rN|j| kr2W dS td|j | W dS nW dS W n  tk
rv   td Y dS X d S )NTzQCommit hash points to an object of type '%s'. Requested were objects of type '%s'FzCommit hash is invalid.)	r   Zpartial_to_complete_sha_hexinfotyper   logdebugr   r   )r   r   r   Zcomplete_shaZobject_inforO   rO   rP   is_valid_object  s     

zRepo.is_valid_objectc                 C  s    | j rt| j | j}t|S r   )rT   rz   r{   DAEMON_EXPORT_FILErt   )r   r   rO   rO   rP   _get_daemon_export  s    zRepo._get_daemon_export)valuera   c                 C  sH   | j rt| j | j}t|}|r2|s2t| n|sD|rDt| d S r   )rT   rz   r{   r  rt   r%   ri   unlink)r   r  r   Z
fileexistsrO   rO   rP   _set_daemon_export  s    

zRepo._set_daemon_exportz.If True, git-daemon may export this repositoryz	List[str]c              	   C  sV   | j rt| j ddd}t|rRt|d}| t}W 5 Q R X | 	 S g S )zThe list of alternates for this repo from which objects can be retrieved

        :return: list of strings being pathnames of alternatesrh   r   
alternatesr   )
rT   rz   r{   rt   r   r   r   r   r   r   )r   alternates_pathr   altsrO   rO   rP   _get_alternates  s    
zRepo._get_alternates)r  ra   c              	   C  s\   t | jddd}|s,t |rXt| n,t|d}|d|t	 W 5 Q R X dS )ai  Sets the alternates

        :param alts:
            is the array of string paths representing the alternates at which
            git should look for objects, i.e. /home/user/repo/.git/objects

        :raise NoSuchPathError:
        :note:
            The method does not check for the existence of the paths in alts
            as the caller is responsible.rh   r   r
  r   r   N)
rz   r{   r   isfileri   r   r   r   r   r   )r   r  r  r   rO   rO   rP   _set_alternates  s    
zRepo._set_alternateszPRetrieve a list of alternates paths or set a list paths to be used as alternates)r   working_treeuntracked_filesr   r]   ra   c                 C  s   | j r
dS dddg}|s"|d |r8|dt|g |rbt| jjrbt| j	j
d
| rbdS |rzt| j	j
| rzdS |rt| j|| d	rdS dS )z
        :return:
            ``True``, the repository is considered dirty. By default it will react
            like a git-status without untracked files, hence it is dirty if the
            index or the working copy have changes.Fz--abbrev=40z--full-indexz--rawz--ignore-submodules----cachedT)Zignore_submodules)r  )r~   r   extendrn   rz   r  r   r]   r   r   Zdiff_get_untracked_files)r   r   r  r  r   r]   Zdefault_argsrO   rO   rP   is_dirty  s"    

"zRepo.is_dirtyc                 C  s   |   S )a  
        :return:
            list(str,...)

            Files currently untracked as they have not been staged yet. Paths
            are relative to the current working directory of the git command.

        :note:
            ignored files will not appear here, i.e. files mentioned in .gitignore
        :note:
            This property is expensive, as no cache is involved. To process the result, please
            consider caching it yourself.)r  r   rO   rO   rP   r  )  s    zRepo.untracked_filesc                 O  s   | j j|dddd|}d}g }|jD ]}|t}||sBq(|t|d  d}|d |d   krtdkrn n(|dd }|d	d
dt}|	| q(t
| |S )NT)Z	porcelainr  
as_processz?? r   r   "r!   asciiZunicode_escapelatin1)r   r   stdoutr   r   r   r   r   r   r   r   )r   r   r   procprefixr  r   r   rO   rO   rP   r  9  s    


 zRepo._get_untracked_files)r   ra   c                 G  sD   z| j j| }W n tk
r(   g  Y S X |dddddS )zChecks if paths are ignored via .gitignore
        Doing so using the "git check-ignore" method.

        :param paths: List of paths to check whether they are ignored or not
        :return: subset of those paths which are ignored
        z\\\r  rS   r   )r   Zcheck_ignorer   replacer}   )r   r   r  rO   rO   rP   ignoredM  s
    
zRepo.ignoredr   c                 C  s   | j jS )zThe name of the currently active branch.

        :raises	TypeError: If HEAD is detached
        :return: Head to the active branch)r   	referencer   rO   rO   rP   active_branchZ  s    zRepo.active_branchz
str | HEADzIterator['BlameEntry'])r   filer   ra   c                 k  s  | j j|d|fdddd|}i }dd |dD }zt|}W n tk
rZ   Y dS X | }|\}	}
}}t|}t|}t|
}|	|krbi }zt|}W n tk
r   Y dS X |d	krq|d
d\}}|||< |dkr|}qqt| t|	tt	|d t	|d 
ddt|d tt	|d t	|d 
ddt|d d}|||	< nLzt|}W n tk
r   Y dS X |d
d\}}|dkrb|}qqbt||	 t||| t	|t||| V  q8dS )a  Iterator for blame information for the given file at the given revision.

        Unlike .blame(), this does not return the actual file's contents, only
        a stream of BlameEntry tuples.

        :param rev: revision specifier, see git-rev-parse for viable options.
        :return: lazy iterator of BlameEntry tuples, where the commit
                 indicates the commit to blame for the line, and range
                 indicates a span of line numbers in the resulting file.

        If you combine all line number ranges outputted by this command, you
        should get a continuous range spanning all line numbers in the file.
        r  TF)pincrementalstdout_as_stringc                 s  s   | ]}|r|V  qd S r   rO   )r   r   rO   rO   rP   r   u  s      z)Repo.blame_incremental.<locals>.<genexpr>   
Ns   boundary    r!   s   filenames   authors   author-mail   <   >s   author-times	   committers   committer-mails   committer-timeauthorZauthored_date	committerZcommitted_date)r   blamer}   nextStopIterationr   r   r   r   r   lstripr   rE   rG   )r   r   r$  r   datacommitsstreamr   Z
split_lineZhexshaZorig_lineno_bZlineno_bZnum_lines_blinenoZ	num_linesZorig_linenopropsr   r  orig_filenamer   rO   rO   rP   blame_incrementalc  sl     






zRepo.blame_incrementalzUnion[str, HEAD]zOptional[List[str]]zKList[List[Commit | List[str | bytes] | None]] | Iterator[BlameEntry] | None)r   r$  r&  rev_optsr   ra   c                 K  s"  |r| j ||f|S |pg }| jj|f|d|fddd|}i }g }G dd dtdd}	i }
d}||D ]}z| t}W n  tk
r   d}g }d}Y nX | j	
|d	}|d
 }d}| j|r0|d 
d}t|dkrd|i}
|dg g n*|
d |krd|i}
|||g g qn| j|}|r |d
}|dkr|drp|d |
d< n4|drt|d |
d< n||kr|d |
d< nX|dkr|dr|d |
d< n4|drt|d |
d< n||kr|d |
d< qn|dr|d |
d< qn|dr4|d |
d< qn|dkrn|
rn|
d }||}|dkrt| t|t|
d  d|
d  |
d t|
d  d|
d  |
d d}|||< ||d d
< |d d	 dk	r|s|r|d
 dkr|d	d }|}n|}|d d	 | d|i}
qn|S )a  The blame information for the given file at the given revision.

        :param rev: revision specifier, see git-rev-parse for viable options.
        :return:
            list: [git.Commit, list: [<line>]]
            A list of lists associating a Commit object with a list of lines that
            changed within the given commit. The Commit objects will be given in order
            of appearance.r  TF)r%  r'  c                   @  s^   e Zd ZU ded< ded< ded< ded< ded< ded< ded	< ded
< ded< ded< dS )zRepo.blame.<locals>.InfoTDrn   r   idr   summaryr-  author_emailr   author_dater.  committer_emailcommitter_dateNrJ   rO   rO   rO   rP   InfoTD  s   
rA  )totalrS   r!   r   r      r;  Nr-  z-mailr=  z-timer>  r.  r?  r@  r   r<  r,  	)r9  r   r/  r>   r   r   r   r   UnicodeDecodeErrorre_whitespacer}   re_hexsha_onlyrp   r   r   rw   re_author_committer_startgroupendswithr   r   r   r   r   Z_from_string)r   r   r$  r&  r:  r   r3  r4  ZblamesrA  r   keependsZ
line_bytesline_strZ	firstpartpartsZ	is_binarydigitsmroler   r   r   rO   rO   rP   r/    s    $









z
Repo.blamezUnion[PathLike, None]zType[GitCmdObjectDB])r]   mkdirr^   r`   r   ra   c                 K  sN   |rt ||}|r,|r,t|s,t|d | |}|jf | | ||dS )a]  Initialize a git repository at the given path if specified

        :param path:
            is the full path to the repo (traditionally ends with /<name>.git)
            or None in which case the repository will be created in the current
            working directory

        :param mkdir:
            if specified will create the repository directory if it doesn't
            already exists. Creates the directory with a mode=0755.
            Only effective if a path is explicitly given

        :param odbt:
            Object DataBase type - a type which is constructed by providing
            the directory containing the database objects, i.e. .git/objects.
            It will be used to access all object data

        :param expand_vars:
            if specified, environment variables will not be escaped. This
            can lead to information disclosure, allowing attackers to
            access the contents of environment variables

        :param kwargs:
            keyword arguments serving as additional options to the git-init command

        :return: ``git.Repo`` (the newly created repo)i  r^   )r   rz   rt   ri   makedirsr   init)clsr]   rR  r^   r`   r   r   rO   rO   rP   rU  G  s    #

z	Repo.initz'Git'zWUnion['RemoteProgress', 'UpdateProgress', Callable[(Ellipsis, 'RemoteProgress')], None])r   r   r]   odb_default_typeprogressmulti_optionsr   ra   c              	   K  s  | d|}t|tst|}t r8d|kr8t|n|}	|d}
|
rXt|
|d< d }|rptd	|}|j
|tt||	fdddddt|||}|rt|d t| tdd n:| \}}t|d	d
}t|}td|| t||d t|s&|jd k	r"t	|j|n|}| ||d}|jjf |  |jr~|jd j }|dt|jd j W 5 Q R X |S )Nr^   rf   Zseparate_git_dirrC  T)Zwith_extended_outputr  vuniversal_newlinesF)Zdecode_streamsr   rS   zCmd(%s)'s unused stdout: %s)stderrrS  r   r   )poprm   rn   r   rl   Z
polish_urlrw   shlexr}   r{   cloner   r   r   Znew_message_handlerr   communicategetattrr    r  r  rz   isabsZ_working_dirr   update_environmentenvironmentr   r   	set_valuer   )rV  r   r   r]   rW  rX  rY  r   r^   Z
clone_pathZsep_dirZmultir  r  r\  Zcmdliner   writerrO   rO   rP   _clonet  sV    




$zRepo._clonezOptional[Callable])r]   rX  rY  r   ra   c                 K  s"   | j | j| j|t| j||f|S )aB  Create a clone from this repository.

        :param path: is the full path of the new repo (traditionally ends with ./<name>.git).
        :param progress: See 'git.remote.Remote.push'.
        :param multi_options: A list of Clone options that can be provided multiple times.  One
            option per list item which is passed exactly as specified to clone.
            For example ['--config core.filemode=false', '--config core.ignorecase',
            '--recurse-submodule=repo1_path', '--recurse-submodule=repo2_path']
        :param kwargs:
            * odbt = ObjectDatabase Type, allowing to determine the object database
              implementation used by the returned Repo instance
            * All remaining keyword arguments are given to the git-clone command

        :return: ``git.Repo`` (the newly cloned repo))rg  r   r   r  r   )r   r]   rX  rY  r   rO   rO   rP   r_    s    z
Repo.clonezOptional[Mapping[str, str]])r   to_pathrX  envrY  r   ra   c                 K  s:   |  t }|dk	r"|jf | | j|||t||f|S )aZ  Create a clone from the given URL

        :param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
        :param to_path: Path to which the repository should be cloned to
        :param progress: See 'git.remote.Remote.push'.
        :param env: Optional dictionary containing the desired environment variables.
            Note: Provided variables will be used to update the execution
            environment for `git`. If some variable is not specified in `env`
            and is defined in `os.environ`, value from `os.environ` will be used.
            If you want to unset some variable, consider providing empty string
            as its value.
        :param multi_options: See ``clone`` method
        :param kwargs: see the ``clone`` method
        :return: Repo instance pointing to the cloned directoryN)r   ri   rk   rc  rg  r   )rV  r   rh  rX  ri  rY  r   r   rO   rO   rP   
clone_from  s    zRepo.clone_fromzUnion[TextIO, BinaryIO])ostreamtreeishr  r   ra   c                 K  s   |dkr| j j}|r$d|kr$||d< ||d< |dg }ttttt ttdf f |}t|t	t
fsl|g}| jj|f|| | S )a-  Archive the tree at the given revision.

        :param ostream: file compatible stream object to which the archive will be written as bytes
        :param treeish: is the treeish name/id, defaults to active branch
        :param prefix: is the optional prefix to prepend to each filename in the archive
        :param kwargs: Additional arguments passed to git-archive

            * Use the 'format' argument to define the kind of format. Use
              specialized ostreams to write any format supported by python.
            * You may specify the special **path** keyword, which may either be a repository-relative
              path to a directory or file to place into the archive, or a list or tuple of multiple paths.

        :raise GitCommandError: in case something went wrong
        :return: selfNr  Zoutput_streamr]   .)r   rF   r]  r;   r9   r(   r2   r7   rm   tuplelistr   archive)r   rk  rl  r  r   r]   rO   rO   rP   ro    s     zRepo.archivec                 C  s,   | j r
dS | jr$tt| jdS dS dS )a  
        :return: True if our git_dir is not at the root of our working_tree_dir, but a .git file with a
            platform agnositic symbolic link. Our git_dir will be wherever the .git file points to
        :note: bare repositories will always return False here
        Fre   N)rf   r   rz   r  r{   r   rO   rO   rP   has_separate_working_tree  s
    zRepo.has_separate_working_treec                 C  s   | j }d|j|j| jf S )Nz
<%s.%s %r>)	__class__rL   rK   rT   )r   ZclazzrO   rO   rP   __repr__.  s    zRepo.__repr__zCommit | Nonec                 C  s:   | j rt| j d}t|s"dS | t|d  S )z
        :return: The commit which is currently being replayed while rebasing.

        None if we are not currently rebasing.
        ZREBASE_HEADNrg   )rT   rz   r{   r  rF   r   readliner   )r   Zrebase_head_filerO   rO   rP   currently_rebasing_on2  s
    
zRepo.currently_rebasing_on)r   )r   FN)r   NF)N)rY   )N)N)NrS   )N)TTFTN)FN)NN)NN)NNN)NN)_rK   rL   rM   __doc__r  r;   r   rQ   rN   rR   rT   rU   ro   compilerG  rH  Zre_hexsha_shortenedrq   rI  Zre_tab_full_linerZ   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   rf   r   r   refsZbranchesr   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   rx   r   rF   r   r   r   r   r   r  r  r	  Zdaemon_exportr  r  r
  r  r  r  r!  r#  r9  r/  classmethodrU  rg  r_  rj  ro  rp  r"   rr  rt  rO   rO   rO   rP   rD   e   s$  







 	
	   	   	 
  	     (Y   ,   O       "rD   )c
__future__r   loggingri   ro   r^  rr   Zgitdb.db.looser   Z	gitdb.excr   Zgit.cmdr   r   Z
git.compatr   r   r	   Z
git.configr
   Zgit.dbr   Zgit.excr   r   r   Z	git.indexr   Zgit.objectsr   r   r   Zgit.refsr   r   r   r   Z
git.remoter   r   r   Zgit.utilr   r   r   r   r   r    os.pathr]   rz   Zfunr"   r#   r$   r%   r&   r   r   Z	git.typesr'   r(   r)   r*   r+   r,   typingr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   Zgit.refs.symbolicr@   rA   Zgit.objects.submodule.baserB   rC   	getLoggerrK   r  __all__rE   r   rD   rO   rO   rO   rP   <module>   sD     H
