o
    ﯪg                    @  s  U d dl mZ ddg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mZmZ d dl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 d d	lmZmZm Z 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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9 e0rd dl:m;Z; d dl<m=Z= h dZ>e?e@ZA			dJdKddZBd eCd!< ejDd"krd#dd$dLd-d.ZEeEZFneZFdMd1d2ZGdNdOd9d:ZHdNdPd?d@ZIdAZJdBZKdQdDdEZLG dFdG dGeMZNeNZO	 G dHd deNdIZPdS )R    )annotationsGitMetaGitN)DEVNULLPIPEPopen)dedent)defencforce_bytessafe_decode)CommandErrorGitCommandErrorGitCommandNotFoundUnsafeOptionErrorUnsafeProtocolError)cygpathexpand_pathis_cygwin_git	patch_envremove_password_if_presentstream_copy)AnyAnyStrBinaryIOCallableDictIOIteratorListMappingOptionalSequenceTYPE_CHECKINGTextIOTupleUnioncastoverload)LiteralPathLikeTBD)	DiffIndex)Repo>   envshellistream
as_processwith_stdoutoutput_streammax_chunk_sizewith_exceptionsstdout_as_stringkill_after_timeoutuniversal_newlineswith_extended_outputstrip_newline_in_stdoutTprocess'Git.AutoInterrupt' | Popenstdout_handlersUnion[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None], Callable[[bytes, 'Repo', 'DiffIndex'], None]]stderr_handlerEUnion[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None]]	finalizer@Union[None, Callable[[Union[Popen, 'Git.AutoInterrupt']], None]]decode_streamsboolr6   Union[None, float]returnNonec                 C  s  ddd}t | dr)td| } t| jdd}| jr| jjnd}| jr&| jjnd}	ntt| } t| dd}| j}| j}	t|tt	fsE|
 }g }
|rQ|
d||f |	r[|
d|	|f g }|
D ]\}}}tj||||||fd}d|_|  || q_|D ];}|j|d | rt| tjr|   ntd| d|rd| d}|st|	trtt|}| }|| q|r||  dS dS )a  Register for notifications to learn that process output is ready to read, and
    dispatch lines to the respective line handlers.

    This function returns once the finalizer returns.

    :param process:
        :class:`subprocess.Popen` instance.

    :param stdout_handler:
        f(stdout_line_string), or ``None``.

    :param stderr_handler:
        f(stderr_line_string), or ``None``.

    :param finalizer:
        f(proc) - wait for proc to finish.

    :param decode_streams:
        Assume stdout/stderr streams are binary and decode them before pushing their
        contents to handlers.

        This defaults to ``True``. Set it to ``False`` if:

        - ``universal_newlines == True``, as then streams are in text mode, or
        - decoding must happen later, such as for :class:`~git.diff.Diff`\s.

    :param kill_after_timeout:
        :class:`float` or ``None``, Default = ``None``

        To specify a timeout in seconds for the git command, after which the process
        should be killed.
    cmdline	List[str]namestrstreamUnion[BinaryIO, TextIO]	is_decoderC   handler0Union[None, Callable[[Union[bytes, str]], None]]rE   rF   c                 S  s   zfz |D ]}|r|rt |tsJ |t}|| q|| qW n7 tyX } z+td|dt|  d| dt|vrNt	d| dgt|  ||W Y d }~nd }~ww W |
  d S W |
  d S |
  w )NzPumping z of cmd(z) failed due to: zI/O operation on closed file<z-pump>)
isinstancebytesdecoder	   	Exception_loggererrorr   rJ   r   close)rG   rI   rK   rM   rN   lineline_strex r[   C/var/www/html/chatdoc2/venv/lib/python3.10/site-packages/git/cmd.pypump_stream   s*   

	 z*handle_process_output.<locals>.pump_streamprocGit.AutoInterruptargs Nstdoutstderr)targetr`   T)timeoutzKThread join() timed out in cmd.handle_process_output(). kill_after_timeout=z secondsz?error: process killed because it timed out. kill_after_timeout=)rG   rH   rI   rJ   rK   rL   rM   rC   rN   rO   rE   rF   )hasattrr&   getattrr^   rb   rc   r   rQ   tuplelistsplitappend	threadingThreaddaemonstartjoinis_aliver   AutoInterrupt
_terminateRuntimeErrorr   rJ   encode)r:   r<   r>   r@   rB   r6   r]   rG   p_stdoutp_stderrpumpsthreadsrI   rK   rN   t	error_strr[   r[   r\   handle_process_outputa   sX   
/





r|   zCallable[..., Popen]safer_popenwin32F)r.   r-   commandUnion[str, Sequence[Any]]r.   r-   Optional[Mapping[str, str]]kwargsr   r   c                K  sr   t jt jB }|r|du ri nt|}d|d< tdd t| f|||d|W  d   S 1 s2w   Y  dS )a  Call :class:`subprocess.Popen` on Windows but don't include a CWD in the
        search.

        This avoids an untrusted search path condition where a file like ``git.exe`` in
        a malicious repository would be run when GitPython operates on the repository.
        The process using GitPython may have an untrusted repository's working tree as
        its current working directory. Some operations may temporarily change to that
        directory before running a subprocess. In addition, while by default GitPython
        does not run external commands with a shell, it can be made to do so, in which
        case the CWD of the subprocess, which GitPython usually sets to a repository
        working tree, can itself be searched automatically by the shell. This wrapper
        covers all those cases.

        :note:
            This currently works by setting the
            :envvar:`NoDefaultCurrentDirectoryInExePath` environment variable during
            subprocess creation. It also takes care of passing Windows-specific process
            creation flags, but that is unrelated to path search.

        :note:
            The current implementation contains a race condition on :attr:`os.environ`.
            GitPython isn't thread-safe, but a program using it on one thread should
            ideally be able to mutate :attr:`os.environ` on another, without
            unpredictable results. See comments in:
            https://github.com/gitpython-developers/GitPython/pull/1650
        N1"NoDefaultCurrentDirectoryInExePath)r.   r-   creationflags)
subprocessCREATE_NO_WINDOWCREATE_NEW_PROCESS_GROUPdictr   r   )r   r.   r-   r   r   r[   r[   r\   _safer_popen_windows   s   $	$r   stringrJ   c                 C  s   |  ddS )N_-)replace)r   r[   r[   r\   dashify&     r   r[   self'Git'excludeSequence[str]Dict[str, Any]c                   s    fddj D S )Nc                   s    i | ]}| vr|t |qS r[   )rg   ).0sr   r   r[   r\   
<dictcomp>+  s     z!slots_to_dict.<locals>.<dictcomp>)	__slots__)r   r   r[   r   r\   slots_to_dict*  s   r   objectdMapping[str, Any]excludedc                 C  s8   |  D ]
\}}t| || q|D ]}t| |d  qd S N)itemssetattr)r   r   r   kvr[   r[   r\   $dict_to_slots_and__excluded_are_none.  s
   r   zuGit.USE_SHELL is deprecated, because only its default value of False is safe. It will be removed in a future release.a  Setting Git.USE_SHELL to True is unsafe and insecure, as the effect of special shell syntax cannot usually be accounted for. This can result in a command injection vulnerability and arbitrary code execution. Git.USE_SHELL is deprecated and will be removed in a future release.extra_dangerc                 C  s   t j| rtnttdd d S )N   )
stacklevel)warningswarn_USE_SHELL_DANGER_MESSAGE_USE_SHELL_DEFAULT_MESSAGEDeprecationWarning)r   r[   r[   r\   _warn_use_shellD  s
   

r   c                      sD   e Zd ZdZd fddZd fd	d
ZeseZeZ  Z	S   Z	S )_GitMetaztMetaclass for :class:`Git`.

    This helps issue :class:`DeprecationWarning` if :attr:`Git.USE_SHELL` is used.
    rI   rJ   rE   r   c                      |dkrt d t |S N	USE_SHELLFr   super__getattribute__)clsrI   	__class__r[   r\   __getattributeR     z_GitMeta.__getattributevaluec                   s"   |dkrt | t || d S )Nr   )r   r   __setattr__)r   rI   r   r   r[   r\   	__setattrW  s   z_GitMeta.__setattrrI   rJ   rE   r   )rI   rJ   r   r   rE   r   )
__name__
__module____qualname____doc___GitMeta__getattribute_GitMeta__setattrr"   r   r   __classcell__r[   r[   r   r\   r   L  s    r   c                      s  e Zd ZU dZdZdZedZdddZ	dddZ
dZ	 ejddZ	 dZded< 	 dZdZdZ	 e ZeddddZedddZeeddd d!Zeeddd#d!Zeddd%d!Zedd&d'Zedd+d,ZG d-d. d.ZG d/d0 d0Zdd fd2d3Z d fd6d7Z!d fd8d9Z"dd;d<Z#e$dd=d>Z%e$dd@dAZ&eddGdHZ'eddIddLdHZ'edddMddOdHZ'eddQdHZ'eddSdHZ'dddTdddTddTddde(j)dTfd fdedHZ'ddgdhZ*ddjdkZ+e,j-ddmdnZ.ddqdrZ/dddsdtZ0eddwdxZ1ddzd{Z2edd~dZ3edddZ3edddZ3dddZ3dddZ4dddZ5dddZ6dddZ7dddZ8dddZ9dddZ:dddZ;  Z<S )r   a  The Git class manages communication with the Git binary.

    It provides a convenient interface to calling the Git binary, such as in::

     g = Git( git_dir )
     g.init()                   # calls 'git init' program
     rval = g.ls_files()        # calls 'git ls-files' program

    Debugging:

    * Set the :envvar:`GIT_PYTHON_TRACE` environment variable to print each invocation
      of the command to stdout.
    * Set its value to ``full`` to see details about the returned values.
    )_working_dircat_file_allcat_file_header_version_info_version_info_token_git_options_persistent_git_options_environment)r   r   r   r   z(.+)::.+rE   r   c                 C  s   t | | jdS )N)r   )r   
_excluded_r   r[   r[   r\   __getstate__  s   zGit.__getstate__r   rF   c                 C  s   t | || jd d S )N)r   )r   r   )r   r   r[   r[   r\   __setstate__  s   zGit.__setstate__gitGIT_PYTHON_TRACEFrC   r   GIT_PYTHON_GIT_EXECUTABLEGIT_PYTHON_REFRESHNpathUnion[None, PathLike]c              	   C  s  |durt j|}t j|}n	t j| j| j}| j}| j	}|| _t
 | _	d}z	|    d}W n ttfy=   Y nw |std| j }|| _|| _	|du rt j| jd }g d}g d}	g d}
||v rlnH||	v st||
v rtd	|| jd
|d
|	d
|
| j|d f }||	v rt| nt|td| jd
|d
|	d
|
f }t|| j| _|S t|||S )a5	  Update information about the git executable :class:`Git` objects will use.

        Called by the :func:`git.refresh` function in the top level ``__init__``.

        :param path:
            Optional path to the git executable. If not absolute, it is resolved
            immediately, relative to the current directory. (See note below.)

        :note:
            The top-level :func:`git.refresh` should be preferred because it calls this
            method and may also update other state accordingly.

        :note:
            There are three different ways to specify the command that refreshing causes
            to be used for git:

            1. Pass no `path` argument and do not set the
               :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable. The command
               name ``git`` is used. It is looked up in a path search by the system, in
               each command run (roughly similar to how git is found when running
               ``git`` commands manually). This is usually the desired behavior.

            2. Pass no `path` argument but set the :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
               environment variable. The command given as the value of that variable is
               used. This may be a simple command or an arbitrary path. It is looked up
               in each command run. Setting :envvar:`GIT_PYTHON_GIT_EXECUTABLE` to
               ``git`` has the same effect as not setting it.

            3. Pass a `path` argument. This path, if not absolute, is immediately
               resolved, relative to the current directory. This resolution occurs at
               the time of the refresh. When git commands are run, they are run using
               that previously resolved path. If a `path` argument is passed, the
               :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not
               consulted.

        :note:
            Refreshing always sets the :attr:`Git.GIT_PYTHON_GIT_EXECUTABLE` class
            attribute, which can be read on the :class:`Git` class or any of its
            instances to check what command is used to run git. This attribute should
            not be confused with the related :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
            environment variable. The class attribute is set no matter how refreshing is
            performed.
        NFTa0                  Bad git executable.
                The git executable must be specified in one of the following ways:
                    - be included in your $PATH
                    - be set via $%s
                    - explicitly set via git.refresh(<full-path-to-git-executable>)
                raise)quietqsilencer   silentnonen0)r   wwarningloglr   )rV   e	exceptionr   r2ae                          %s
                        All git commands will error until this is rectified.

                        This initial message can be silenced or aggravated in the future by setting the
                        $%s environment variable. Use one of the following values:
                            - %s: for no message or exception
                            - %s: for a warning message (logging level CRITICAL, displayed by default)
                            - %s: for a raised exception

                        Example:
                            export %s=%s
                        |r   a                          %s environment variable has been set but it has been set with an invalid value.

                        Use only the following values:
                            - %s: for no message or exception
                            - %s: for a warning message (logging level CRITICAL, displayed by default)
                            - %s: for a raised exception
                        )osr   
expanduserabspathenvironget_git_exec_env_vargit_exec_namer   _refresh_tokenr   versionr   PermissionErrorr   _refresh_env_varlowerrp   rU   criticalImportError)r   r   new_gitold_gitold_refresh_tokenhas_giterrmoder   r   rV   r[   r[   r\   refresh  sz   .
	

zGit.refreshc                 C  s
   t | jS r   )r   r   )r   r[   r[   r\   	is_cygwin  s   
zGit.is_cygwin.urlrJ   r   Literal[False]c                 C     d S r   r[   r   r   r   r[   r[   r\   
polish_url     zGit.polish_urlUnion[None, bool]c                 C  r  r   r[   r  r[   r[   r\   r    r  r)   c                 C  sZ   |du r|   }|rt|}|S tj|}|dr!tj|}|dddd}|S )a  Remove any backslashes from URLs to be written in config files.

        Windows might create config files containing paths with backslashes, but git
        stops liking them as it will escape the backslashes. Hence we undo the escaping
        just to be sure.
        N~z\\\/)r   r   r   r   
expandvars
startswithr   r   r  r[   r[   r\   r    s   
c                 C  s.   | j |}|r|d}td| ddS )a}  Check for unsafe protocols.

        Apart from the usual protocols (http, git, ssh), Git allows "remote helpers"
        that have the form ``<transport>::<address>``. One of these helpers (``ext::``)
        can be used to invoke any arbitrary command.

        See:

        - https://git-scm.com/docs/gitremote-helpers
        - https://git-scm.com/docs/git-remote-ext
           zThe `zM::` protocol looks suspicious, use `allow_unsafe_protocols=True` to allow it.N)re_unsafe_protocolmatchgroupr   )r   r   r  protocolr[   r[   r\   check_unsafe_protocols  s   

zGit.check_unsafe_protocolsoptionsrH   unsafe_optionsc                 C  sP   dd |D }|D ]}t ||D ]\}}||s||kr$t| dqq	dS )zCheck for unsafe options.

        Some options that are passed to ``git <command>`` can be used to execute
        arbitrary commands. These are blocked by default.
        c                 S  s   g | ]}| d qS )r   )lstrip)r   optionr[   r[   r\   
<listcomp>  s    z,Git.check_unsafe_options.<locals>.<listcomp>z= is not allowed, use `allow_unsafe_options=True` to allow it.N)zipr
  r   )r   r  r  bare_unsafe_optionsr  unsafe_optionbare_optionr[   r[   r\   check_unsafe_options  s   	zGit.check_unsafe_optionsc                   @  sV   e Zd ZU dZdZdZded< dddZdddZdddZ	dddZ
dd ddZdS )!r_   a  Process wrapper that terminates the wrapped process on finalization.

        This kills/interrupts the stored process instance once this instance goes out of
        scope. It is used to prevent processes piling up in case iterators stop reading.

        All attributes are wired through to the contained process object.

        The wait method is overridden to perform automatic status code checking and
        possibly raise.
        r^   r`   statusr   int_status_code_if_terminater^   Union[None, subprocess.Popen]r`   r   rE   rF   c                 C  s   || _ || _d | _d S r   r  )r   r^   r`   r[   r[   r\   __init__  s   
zGit.AutoInterrupt.__init__c              
   C  s  | j du rdS | j }d| _ |jr|j  |jr|j  |jr%|j  z| dur7| jp2| | _W dS W n tyP } zt	
d| W Y d}~nd}~ww tdu s]ttdddu r_dS z|  | }| jpl|| _W dS  ty } zt	
d| W Y d}~dS d}~ww )z!Terminate the underlying process.Nz(Ignored error after process had died: %rkill)r^   stdinrW   rb   rc   pollr  r  OSErrorrU   infor   rg   	terminatewait)r   r^   rZ   r  r[   r[   r\   rs     s:   



zGit.AutoInterrupt._terminatec                 C  s   |    d S r   )rs   r   r[   r[   r\   __del__  r   zGit.AutoInterrupt.__del__attrrJ   c                 C  s   t | j|S r   )rg   r^   )r   r)  r[   r[   r\   __getattr__  r   zGit.AutoInterrupt.__getattr__    rc   Union[None, str, bytes]c                   s   |du rd t |dd | jdur| j }| jj}n| j}d}d fd	d
}|dkr@||}td|f  tt| j	|||S )a  Wait for the process and return its status code.

            :param stderr:
                Previously read value of stderr, in case stderr is already closed.

            :warn:
                May deadlock if output or error pipes are used and not handled
                separately.

            :raise git.exc.GitCommandError:
                If the return status is not 0.
            Nr+  zutf-8)dataencodingrK   Union[IO[bytes], None]rE   rR   c              	     s>   | rz	 t |   W S  ttfy    pd Y S w  pdS )Nr+  )r
   readr$  
ValueError)rK   stderr_br[   r\   $read_all_from_possibly_closed_stream4  s   zDGit.AutoInterrupt.wait.<locals>.read_all_from_possibly_closed_streamr   zAutoInterrupt wait stderr: %r)rK   r/  rE   rR   )
r
   r^   r'  rc   r  rU   debugr   r   r`   )r   rc   r  rw   r4  errstrr[   r2  r\   r'    s   


zGit.AutoInterrupt.waitN)r^   r  r`   r   rE   rF   rE   rF   )r)  rJ   rE   r   )r+  )rc   r,  rE   r  )r   r   r   r   r   r  __annotations__r   rs   r(  r*  r'  r[   r[   r[   r\   rr     s   
 


#
rr   c                   @  sd   e Zd ZdZdZdd	d
ZddddZddddZddddZd ddZ	d!ddZ
e
Zd"ddZdS )#zGit.CatFileContentStreama  Object representing a sized read-only stream returning the contents of
        an object.

        This behaves like a stream, but counts the data read and simulates an empty
        stream once our sized content region is empty.

        If not all data are read to the end of the object's lifetime, we read the
        rest to ensure the underlying stream continues to work.
        )_stream_nbr_sizesizer  rK   	IO[bytes]rE   rF   c                 C  s,   || _ || _d| _|dkr|d d S d S )Nr   r  )r9  r;  r:  r0  )r   r<  rK   r[   r[   r\   r   T  s   z!Git.CatFileContentStream.__init__rR   c                 C  sn   | j | j }|dkrdS |dkrt||}n|}| j|}|  jt|7  _| j | j dkr5| jd |S )Nr   r+  r>  r  )r;  r:  minr9  r0  lenr   r<  
bytes_leftr-  r[   r[   r\   r0  _  s   zGit.CatFileContentStream.readc                 C  sr   | j | jkrdS | j| j  }|dkrt||}n|}| j|}|  j t|7  _ | j| j  dkr7| jd |S )Nr+  r>  r   r  )r:  r;  r?  r9  readliner@  r0  rA  r[   r[   r\   rC  t  s   z!Git.CatFileContentStream.readlineList[bytes]c                 C  sZ   | j | jkrg S g }d}	 |  }|s	 |S || |dkr,|t|7 }||kr,	 |S q)Nr   Tr>  )r:  r;  rC  rk   r@  )r   r<  outnbrrX   r[   r[   r\   	readlines  s    
z"Git.CatFileContentStream.readlines'Git.CatFileContentStream'c                 C  s   | S r   r[   r   r[   r[   r\   __iter__  s   z!Git.CatFileContentStream.__iter__c                 C  s   |   }|st|S r   )rC  StopIteration)r   rX   r[   r[   r\   __next__  s   z!Git.CatFileContentStream.__next__c                 C  s(   | j | j }|r| j|d  d S d S )Nr  )r;  r:  r9  r0  )r   rB  r[   r[   r\   r(    s   z Git.CatFileContentStream.__del__N)r<  r  rK   r=  rE   rF   )r>  )r<  r  rE   rR   )r<  r  rE   rD  )rE   rH  )rE   rR   r7  )r   r   r   r   r   r   r0  rC  rG  rI  rK  nextr(  r[   r[   r[   r\   CatFileContentStreamG  s    



rM  working_dirc                   sB   t    t|| _d| _g | _i | _d| _d| _d| _	d| _
dS )aa  Initialize this instance with:

        :param working_dir:
            Git directory we should work in. If ``None``, we always work in the current
            directory as returned by :func:`os.getcwd`.
            This is meant to be the working tree directory if available, or the
            ``.git`` directory in case of bare repositories.
        r[   N)r   r   r   r   r   r   r   r   r   r   r   )r   rN  r   r[   r\   r     s   
	

zGit.__init__rI   r   c                   r   r   r   r   rI   r   r[   r\   r     r   zGit.__getattribute__c                   s$     drt  S  fddS )zA convenience method as it allows to call the command as if it was an object.

        :return:
            Callable object that will execute call :meth:`_call_process` with your
            arguments.
        r   c                    s   j  g| R i |S r   )_call_process)r`   r   rI   r   r[   r\   <lambda>      z!Git.__getattr__.<locals>.<lambda>)r
  r   r   rO  r   rQ  r\   r*    s   
zGit.__getattr__r   c                 K  s   | j dddi|| _dS )a7  Specify command line options to the git executable for subsequent
        subcommand calls.

        :param kwargs:
            A dict of keyword arguments.
            These arguments are passed as in :meth:`_call_process`, but will be passed
            to the git command rather than the subcommand.
        split_single_char_optionsTNr[   )transform_kwargsr   r   r   r[   r[   r\   set_persistent_git_options  s   
zGit.set_persistent_git_optionsc                 C     | j S )z(:return: Git directory we are working on)r   r   r[   r[   r\   rN    s   zGit.working_dirTuple[int, ...]c                 C  s|   | j }| j|u r| jdusJ d| jS | d}|dd }|ddd }ttj|}t	t
t|| _|| _| jS )a  
        :return: Tuple with integers representing the major, minor and additional
            version numbers as parsed from :manpage:`git-version(1)`. Up to four fields
            are used.

            This value is generated on demand and is cached.
        Nz Bug: corrupted token-check stater       .   )r   r   r   rP  rj   	itertools	takewhilerJ   isdigitrh   mapr  )r   refresh_tokenprocess_versionversion_stringversion_fieldsleading_numeric_fieldsr[   r[   r\   version_info  s   


zGit.version_infor   r   r0   Literal[True]'AutoInterrupt'c                C  r  r   r[   )r   r   r0   r[   r[   r\   execute	  s   zGit.execute)r0   r5    Union[str, Tuple[int, str, str]]c                C  r  r   r[   r   r   r0   r5   r[   r[   r\   rj       )r0   r5   $Union[bytes, Tuple[int, bytes, str]]c                C  r  r   r[   rl  r[   r[   r\   rj    rm  r8   c                C  r  r   r[   r   r   r8   r0   r5   r[   r[   r\   rj  #     rR   c                C  r  r   r[   ro  r[   r[   r\   rj  -  rp  Tr/   Union[None, BinaryIO]r4   r2   r6   rD   r1   r7   r.   r-   Union[None, Mapping[str, str]]r3   r  r9   subprocess_kwargsDUnion[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]c                   s  t || jr| jdks|rtd z| jpt }tt	|tj
s)d}W n ty5   d}Y nw |}tj }d|d< d|d< || j |durT|| tjdkre|durbtdt}nt}|	rktnttd	dpvttjd
}|du rt d}td||rdnd| zt|f||d|ptt||rtndd	|W n |y } zt||d}~ww t t!j"_"t t!j#_#|r| $|S tjdkr|dur|d& fdd}d' fdd}t%&  t%j'|j(fdnj)}d}d}d}rdnd}zcdu r9| \}}|*|r)|r)|dd }|*|r5|dd }j+}n.|rC|dkrC|nt,j-}t.j"| j"/ }j#/ }|*|rc|dd }0 }W j"1  j#1  nj"1  j#1  w | jdkrd}d(fd!d"}|rtd#||||t2| n|rtd$|||| ntd%|| |r|dkrt|||t3|t4r|rt2|}|r||t2|fS |S ))a  Handle executing the command, and consume and return the returned
        information (stdout).

        :param command:
            The command argument list to execute.
            It should be a sequence of program arguments, or a string. The
            program to execute is the first item in the args sequence or string.

        :param istream:
            Standard input filehandle passed to :class:`subprocess.Popen`.

        :param with_extended_output:
            Whether to return a (status, stdout, stderr) tuple.

        :param with_exceptions:
            Whether to raise an exception when git returns a non-zero status.

        :param as_process:
            Whether to return the created process instance directly from which
            streams can be read on demand. This will render `with_extended_output`
            and `with_exceptions` ineffective - the caller will have to deal with
            the details. It is important to note that the process will be placed
            into an :class:`AutoInterrupt` wrapper that will interrupt the process
            once it goes out of scope. If you use the command in iterators, you
            should pass the whole process instance instead of a single stream.

        :param output_stream:
            If set to a file-like object, data produced by the git command will be
            copied to the given stream instead of being returned as a string.
            This feature only has any effect if `as_process` is ``False``.

        :param stdout_as_string:
            If ``False``, the command's standard output will be bytes. Otherwise, it
            will be decoded into a string using the default encoding (usually UTF-8).
            The latter can fail, if the output contains binary data.

        :param kill_after_timeout:
            Specifies a timeout in seconds for the git command, after which the process
            should be killed. This will have no effect if `as_process` is set to
            ``True``. It is set to ``None`` by default and will let the process run
            until the timeout is explicitly specified. Uses of this feature should be
            carefully considered, due to the following limitations:

            1. This feature is not supported at all on Windows.
            2. Effectiveness may vary by operating system. ``ps --ppid`` is used to
               enumerate child processes, which is available on most GNU/Linux systems
               but not most others.
            3. Deeper descendants do not receive signals, though they may sometimes
               terminate as a consequence of their parent processes being killed.
            4. `kill_after_timeout` uses ``SIGKILL``, which can have negative side
               effects on a repository. For example, stale locks in case of
               :manpage:`git-gc(1)` could render the repository incapable of accepting
               changes until the lock is manually removed.

        :param with_stdout:
            If ``True``, default ``True``, we open stdout on the created process.

        :param universal_newlines:
            If ``True``, pipes will be opened as text, and lines are split at all known
            line endings.

        :param shell:
            Whether to invoke commands through a shell
            (see :class:`Popen(..., shell=True) <subprocess.Popen>`).
            If this is not ``None``, it overrides :attr:`USE_SHELL`.

            Passing ``shell=True`` to this or any other GitPython function should be
            avoided, as it is unsafe under most circumstances. This is because it is
            typically not feasible to fully consider and account for the effect of shell
            expansions, especially when passing ``shell=True`` to other methods that
            forward it to :meth:`Git.execute`. Passing ``shell=True`` is also no longer
            needed (nor useful) to work around any known operating system specific
            issues.

        :param env:
            A dictionary of environment variables to be passed to
            :class:`subprocess.Popen`.

        :param max_chunk_size:
            Maximum number of bytes in one chunk of data passed to the `output_stream`
            in one invocation of its ``write()`` method. If the given number is not
            positive then the default value is used.

        :param strip_newline_in_stdout:
            Whether to strip the trailing ``\n`` of the command stdout.

        :param subprocess_kwargs:
            Keyword arguments to be passed to :class:`subprocess.Popen`. Please note
            that some of the valid kwargs are already set by this method; the ones you
            specify may not be the same ones.

        :return:
            * str(output), if `extended_output` is ``False`` (Default)
            * tuple(int(status), str(stdout), str(stderr)),
              if `extended_output` is ``True``

            If `output_stream` is ``True``, the stdout value will be your output stream:

            * output_stream, if `extended_output` is ``False``
            * tuple(int(status), output_stream, str(stderr)),
              if `extended_output` is ``True``

            Note that git is executed with ``LC_MESSAGES="C"`` to ensure consistent
            output regardless of system language.

        :raise git.exc.GitCommandError:

        :note:
            If you add additional keyword arguments to the signature of this method, you
            must update the ``execute_kwargs`` variable housed in this module.
        fullrZ  NCLANGUAGELC_ALLr~   z9"kill_after_timeout" feature is not supported on Windows.r   wbr   z<Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)z<valid stream>rF   r>  )	r-   cwdbufsizer"  rc   rb   r.   r7   r.  pidr  rE   c              	     s   t ddt| gtd}g }|jdur1|jD ]}t| dkr0| d }| r0|t| qz%t	
| tj |D ]}z	t	
|tj W q; tyO   Y q;w    W dS  ty`   Y dS w )zCallback to kill a process.

                This callback implementation would be ineffective and unsafe on Windows.
                psz--ppid)rb   Nr   )r   rJ   r   rb   r@  rj   r`  rk   r  r   r!  signalSIGKILLr$  set)r|  p
child_pidsrX   	local_pid	child_pid)
kill_checkr[   r\   kill_process	  s.   


z!Git.execute.<locals>.kill_processTuple[AnyStr, AnyStr]c                    sL       \} }    r"ddf }s"|t}| |fS )Nz6Timeout: the command "%s" did not complete in %d secs.rZ  )ro   communicatecancelis_setrp   ru   r	   )rE  r   )r  r^   redacted_commandre   r7   watchdogr[   r\   r  %  s   
z Git.execute.<locals>.communicate)r`   r   r+  
   
stdout_valueUnion[bytes, str]rJ   c                   s     rt | pdS )Nz<OUTPUT_STREAM>)r   )r  )r2   r[   r\   as_textY  s   zGit.execute.<locals>.as_textz$%s -> %d; stdout: '%s'; stderr: '%s'z%s -> %d; stdout: '%s'z%s -> %d)r|  r  rE   rF   )rE   r  )r  r  rE   rJ   )5r   r   rU   r%  rp   r   r   getcwdaccessrJ   X_OKFileNotFoundErrorr   copyupdater   sysplatformr   r$  r   rg   r   opendevnullr   r   r5  r}   r   r	   r   r&   r   rb   rc   rr   rl   EventTimerr|  r  endswith
returncodeioDEFAULT_BUFFER_SIZEr   r0  r'  rW   r   rQ   rR   )r   r   r/   r8   r4   r0   r2   r5   r6   r1   r7   r.   r-   r3   r9   rs  rz  
inline_envcmd_not_found_exceptionstdout_sinkr   r  r  r  r  stderr_valuenewlinecmdstrr  r   )r  r2   r^   r  re   r7   r  r\   rj  7  s    


 









Dict[str, str]c                 C  rX  r   )r   r   r[   r[   r\   environmentx  s   zGit.environmentDict[str, Union[str, None]]c                 K  s^   i }|  D ]&\}}|dur| j|||< || j|< q|| jv r,| j| ||< | j|= q|S )a  Set environment variables for future git invocations. Return all changed
        values in a format that can be passed back into this function to revert the
        changes.

        Examples::

            old_env = self.update_environment(PWD='/tmp')
            self.update_environment(**old_env)

        :param kwargs:
            Environment variables to use for git processes.

        :return:
            Dict that maps environment variables to their old values
        N)r   r   r   )r   r   old_envkeyr   r[   r[   r\   update_environment{  s   
zGit.update_environmentIterator[None]c              
   k  sB    | j di |}zdV  W | j di | dS | j di | w )ag  A context manager around the above :meth:`update_environment` method to
        restore the environment back to its previous state after operation.

        Examples::

            with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
                repo.remotes.origin.fetch()

        :param kwargs:
            See :meth:`update_environment`.
        Nr[   )r  )r   r   r  r[   r[   r\   custom_environment  s
   &zGit.custom_environmentr   rT  c                 C  s   t |dkr&|du rd| gS |dvr$|rd| d| gS d||f gS g S |du r1dt| gS |durB|d urBd	t||f gS g S )
Nr  Tz-%s)FNz%sz-%s%sz--%sFz--%s=%s)r@  r   )r   rI   r   rT  r[   r[   r\   transform_kwarg  s   
zGit.transform_kwargc                 K  sX   g }|  D ]#\}}t|ttfr |D ]}|| |||7 }qq|| |||7 }q|S )z<Transform Python-style kwargs into git command line options.)r   rQ   ri   rh   r  )r   rT  r   r`   r   r   r   r[   r[   r\   rU    s   zGit.transform_kwargsarg_listr   c                 C  sB   g }t |ttfr|D ]
}|| | q|S |t| |S r   )rQ   ri   rh   extend_unpack_argsrk   rJ   )r   r  outlistargr[   r[   r\   r    s   zGit._unpack_argsr   c                 K  s   | j dddi|| _| S )ag  Specify command line options to the git executable for a subcommand call.

        :param kwargs:
            A dict of keyword arguments.
            These arguments are passed as in :meth:`_call_process`, but will be passed
            to the git command rather than the subcommand.

        Examples::

            git(work_tree='/tmp').difftool()
        rT  TNr[   )rU  r   rV  r[   r[   r\   __call__  s   zGit.__call__methodr`   c                 O  r  r   r[   r   r  r`   r   r[   r[   r\   rP       zGit._call_process'Git.AutoInterrupt'c                 O  r  r   r[   )r   r  r/   r0   r`   r   r[   r[   r\   rP    rp  JUnion[str, bytes, Tuple[int, Union[str, bytes], str], 'Git.AutoInterrupt']c                 O  r  r   r[   r  r[   r[   r\   rP    r  c              
   O  s  dd |  D }dd |  D }|dd}| jd
i |}| dd |D }|du r3|| }	n1z||}
W n tyQ } ztd|t|f |d}~ww |d|
d	  | ||
d	 d  }	| jg}|| j	 || j
 d
| _
|t| ||	 | j|fi |S )a  Run the given git command with the specified arguments and return the result
        as a string.

        :param method:
            The command. Contained ``_`` characters will be converted to hyphens, such
            as in ``ls_files`` to call ``ls-files``.

        :param args:
            The list of arguments. If ``None`` is included, it will be pruned.
            This allows your commands to call git more conveniently, as ``None`` is
            realized as non-existent.

        :param kwargs:
            Contains key-values for the following:

            - The :meth:`execute()` kwds, as listed in ``execute_kwargs``.
            - "Command options" to be converted by :meth:`transform_kwargs`.
            - The ``insert_kwargs_after`` key which its value must match one of
              ``*args``.

            It also contains any command options, to be appended after the matched arg.

        Examples::

            git.rev_list('master', max_count=10, header=True)

        turns into::

            git rev-list max-count 10 --header master

        :return:
            Same as :meth:`execute`. If no args are given, used :meth:`execute`'s
            default (especially ``as_process = False``, ``stdout_as_string = True``) and
            return :class:`str`.
        c                 S  s   i | ]\}}|t v r||qS r[   execute_kwargsr   r   r   r[   r[   r\   r         z%Git._call_process.<locals>.<dictcomp>c                 S  s   i | ]\}}|t vr||qS r[   r  r  r[   r[   r\   r     r  insert_kwargs_afterNc                 S  s   g | ]}|d ur|qS r   r[   )r   ar[   r[   r\   r  #  rS  z%Git._call_process.<locals>.<listcomp>zBCouldn't find argument '%s' in args %s to insert cmd options afterr  r[   )r   poprU  r  indexr1  rJ   r   r  r   r   rk   r   rj  )r   r  r`   r   exec_kwargsopts_kwargsinsert_after_this_argopt_argsext_args	args_listr  r   callr[   r[   r\   rP    s6   (

$
header_lineTuple[str, str, int]c                 C  s   |  }t|dkr'|sd| j d| j d}t|td|d | f t|d dkr5td| |d |d	 t|d
 fS )a.  
        :param header_line:
            A line of the form::

                <hex_sha> type_string size_as_int

        :return:
            (hex_sha, type_string, size_as_int)

        :raise ValueError:
            If the header contains indication for an error due to incorrect input sha.
        r   z>SHA is empty, possible dubious ownership in the repository at zj.
            If this is unintended run:

                      "git config --global --add safe.directory z" z.SHA %s could not be resolved, git returned: %rr   (   zFailed to parse header: %rr  r[  )rj   r@  r   r1  stripr  )r   r  tokenserr_msgr[   r[   r\   _parse_object_headerA  s   zGit._parse_object_headerrefr   c                 C  sJ   t |tr|d}nt |tst|}n|}|ds |d7 }|tS )Nasciir  )rQ   rR   rS   rJ   r  ru   r	   )r   r  refstrr[   r[   r\   _prepare_ref`  s   




zGit._prepare_ref	attr_namecmd_namec                 O  s\   t | |}|d ur|S tdd}|| | j|g|R i |}t| || td|}|S )NT)r/   r0   r_   )rg   r   r  rP  r   r&   )r   r  r  r`   r   cur_valr  cmdr[   r[   r\   _get_persistent_cmdn  s   



zGit._get_persistent_cmdr  c                 C  s@   |j r|jr|j | | |j   | |j S td)Nzcmd stdin was empty)r"  rb   writer  flushr  rC  r1  )r   r  r  r[   r[   r\   __get_object_header{  s
   
zGit.__get_object_headerc                 C  s   | j dddd}| ||S )aD  Use this method to quickly examine the type and size of the object behind the
        given ref.

        :note:
            The method will only suffer from the costs of command invocation once and
            reuses the command in subsequent calls.

        :return:
            (hexsha, type_string, size_as_int)
        r   cat_fileT)batch_check)r  _Git__get_object_header)r   r  r  r[   r[   r\   get_object_header  s   zGit.get_object_headerTuple[str, str, int, bytes]c                 C  s*   |  |\}}}}||}~||||fS )zSimilar to :meth:`get_object_header`, but returns object data as well.

        :return:
            (hexsha, type_string, size_as_int, data_string)

        :note:
            Not threadsafe.
        )stream_object_datar0  )r   r  hexshatypenamer<  rK   r-  r[   r[   r\   get_object_data  s   	
zGit.get_object_data0Tuple[str, str, int, 'Git.CatFileContentStream']c                 C  sN   | j dddd}| ||\}}}|jdur|jnt }|||| ||fS )a$  Similar to :meth:`get_object_data`, but returns the data as a stream.

        :return:
            (hexsha, type_string, size_as_int, stream)

        :note:
            This method is not threadsafe. You need one independent :class:`Git`
            instance per thread to be safe!
        r   r  T)batchN)r  r  rb   r  BytesIOrM  )r   r  r  r  r  r<  
cmd_stdoutr[   r[   r\   r    s   
zGit.stream_object_datac                 C  s.   | j | jfD ]}|r|  qd| _ d| _| S )zClear all kinds of internal caches to release resources.

        Currently persistent commands will be interrupted.

        :return:
            self
        N)r   r   r(  )r   r  r[   r[   r\   clear_cache  s   zGit.clear_cache)rE   r   )r   r   rE   rF   r   )r   r   rE   rC   )rE   rC   ).)r   rJ   r   r   rE   rJ   )r   rJ   r   r  rE   rJ   )r   rJ   r   r  rE   r)   )r   rJ   rE   rF   )r  rH   r  rH   rE   rF   )rN  r   rE   rF   r   )r   r   rE   rF   )rE   r   )rE   rY  )r   r   r0   rh  rE   ri  )r   r   r0   r   r5   rh  rE   rk  )r   r   r0   r   r5   r   rE   rn  )
r   r   r8   r   r0   r   r5   rh  rE   rJ   )
r   r   r8   r   r0   r   r5   r   rE   rR   ) r   r   r/   rq  r8   rC   r4   rC   r0   rC   r2   rq  r5   rC   r6   rD   r1   rC   r7   rC   r.   r  r-   rr  r3   r  r9   rC   rs  r   rE   rt  )rE   r  )r   r   rE   r  )r   r   rE   r  )rI   rJ   r   r   rT  rC   rE   rH   )T)rT  rC   r   r   rE   rH   )r  r   rE   rH   )r   r   rE   r   )r  rJ   r`   rF   r   rF   rE   rJ   )r  rJ   r/   r  r0   rh  r`   r   r   r   rE   r  )r  rJ   r`   r   r   r   rE   r  )r  rJ   rE   r  )r  r   rE   rR   )
r  rJ   r  rJ   r`   r   r   r   rE   r  )r  r  r  r   rE   r  )r  rJ   rE   r  )r  rJ   rE   r  )r  rJ   rE   r  )rE   r   )=r   r   r   r   r   r   recompiler  r   r   r   r   r   r   r   r   r8  r   r   r   r   r   classmethodr   r   r'   r  r  r  rr   rM  r   r   r*  rW  propertyrN  rg  rj  r  r  r  r  
contextlibcontextmanagerr  r  rU  r  r  rP  r  r  r  r  r  r  r  r  r   r[   r[   r   r\   r     s   
 


0 &ll
	  
C



	

N





)	metaclass)NTN)r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   r6   rD   rE   rF   )
r   r   r.   rC   r-   r   r   r   rE   r   )r   rJ   rE   rJ   )r[   )r   r   r   r   rE   r   )r   r   r   r   r   r   rE   rF   )r   rC   rE   rF   )Q
__future__r   __all__r  r  r^  loggingr   r  r~  r   r   r   r   r  textwrapr   rl   r   
git.compatr	   r
   r   git.excr   r   r   r   r   git.utilr   r   r   r   r   r   typingr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   	git.typesr(   r)   r*   git.diffr+   git.repo.baser,   r  	getLoggerr   rU   r|   r8  r  r   r}   r   r   r   r   r   r   typer   r   r   r[   r[   r[   r\   <module>   s`    L

=


