o
     {g                     @   s  d Z g dZddlZddlZddlZddlmZ ddlZddlm	Z
 ddlm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 dd	lmZmZmZmZ dd
lm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZS eNrddlmTZT ddlUmVZV ddlWmXZX ePe$e!eYeZf Z[ej\deSdeGeYddf fddZ]G dd de)ej^e&Z_dS )zModule containing :class:`IndexFile`, an Index implementation facilitating all kinds
of index manipulations such as querying and merging.)	IndexFileCheckoutError	StageType    N)BytesIO)S_ISLNK)IStream)MemoryDB)defencforce_bytes)r   GitCommandErrorGitErrorInvalidGitRepositoryError)BlobCommitObject	SubmoduleTree)Serializable)Actor	LazyMixinLockedFDjoin_path_nativefile_contents_roto_native_path_linuxunbare_repo
to_bin_sha   )S_IFGITLINKaggressive_tree_merge	entry_key
read_cacherun_commit_hookstat_mode_to_index_modewrite_cachewrite_tree_from_cache)BaseIndexEntry
IndexEntryr   )TemporaryFileSwappost_clear_cachedefault_indexgit_working_dir)AnyBinaryIOCallableDict	GeneratorIOIterableIteratorListNoReturnSequenceTYPE_CHECKINGTupleUnion)LiteralPathLike)Popen)	Reference)Repo	directoryreturnc              	   c   s    t jdkr%tj| d\}}t| z|V  W t| dS t| w tj| d}|jV  W d   dS 1 s;w   Y  dS )a$  Create a named temporary file git subprocesses can open, deleting it afterward.

    :param directory:
        The directory in which the file is created.

    :return:
        A context manager object that creates the file and provides its name on entry,
        and deletes it on exit.
    win32)dirN)	sysplatformtempfilemkstemposcloseremoveNamedTemporaryFilename)r>   fdrJ   ctx rM   k/var/www/bot.gig.net.ua/public_html/telegram/P1/HellBot/venv/lib/python3.10/site-packages/git/index/base.py$_named_temporary_file_for_subprocessW   s   


"rO   c                       s  e Zd ZdZdZdZ	 eZ	 ddddeedf ddfd	d
Z	de
ddf fddZdefddZedefddZdddZdedd fddZdee fddZddededd fddZ		ddedef deddfddZeedded edef dd fd!d"Zeddd#ee
ef dd fd$d%Zeddd&ed'edd fd(d)Z e!d*d d+e"e de#e fd,d-Z$	.dd/d0d1ed2ed3e%d4e&f d5e%eeegdf d6edede
f fd7d8Z'd9d: fd;e%e(e)e*f gef de#e(e)e*f  fd<d=Z+de,eee(e)e*f  f fd>d?Z-ed@ee.ee)f de(ee)f fdAdBZ/dCe#e* dd fdDdEZ0ddFdGZ1defdHdIZ2dJeeedKf  deeedKf  fdLdMZ3dNedefdOdPZ4dQeee"eee*e.dRf  f de(ee ee. f fdSdTZ5d1ed5e%de.fdUdVZ6e!e7d+ee
 dWee%df d5e%dXee. dee. f
dYdZZ8d.d[d: dd.dfdQeee"eee*e.dRf  f d\ed5e%dWee%d4ef df d]ed^edee. fd_d`Z9dQeee"eee.e*e:f  f dee fdadbZ;ee	ddQeee"eee*e.dRf  f dced'edee
 fdddeZ<ee	ddQeee"eee*e.dRf  f dfed'edee(e
e
f  fdgdhZ=		.					ddie
djeee> df dkedlede?f dmede?f dnee@j@e
df doee@j@e
df dpede>fdqdrZAdie
ddfdsdtZBddudvZCde
fdwdxZDde
fdydzZEdd/d{d|edeFfd}d~ZGedddd: fd+edeHe f d\ed5e%d'edede#e e"e f f
ddZIe				ddee>de
f dced+edeHe f dked'edd fddZJeKjLddfdeeMeKjNjL dde
df d+eeee e(ed4f df ded'edeKjOeKjP f
 fddZQ  ZRS )r   a  An Index that can be manipulated using a native implementation in order to save
    git command function calls wherever possible.

    This provides custom merging facilities allowing to merge without actually changing
    your index or your working tree. This way you can perform your own test merges based
    on the index only without having to deal with the working copy. This is useful in
    case of partial working trees.

    Entries:

        The index contains an entries dict whose keys are tuples of type
        :class:`~git.index.typ.IndexEntry` to facilitate access.

        You may read the entries dict or manipulate it using IndexEntry instance, i.e.::

            index.entries[index.entry_key(index_entry_instance)] = index_entry_instance

    Make sure you use :meth:`index.write() <write>` once you are done manipulating the
    index directly before operating on it using the git command.
    )repoversionentries_extension_data
_file_path   NrP   r=   	file_pathr?   c                 C   s&   || _ | j| _d| _|p|  | _dS )a  Initialize this Index instance, optionally from the given `file_path`.

        If no `file_path` is given, we will be created from the current index file.

        If a stream is not given, the stream will be initialized from the current
        repository's index on demand.
            N)rP   _VERSIONrQ   rS   _index_pathrT   )selfrP   rV   rM   rM   rN   __init__   s   zIndexFile.__init__attrc              	      s   |dkr8z
t | jt j}W n ty   i | _Y d S w zt|ddd}W t | nt | w | | d S t	 
| d S )NrR   T)stream
allow_mmap)rF   openrT   O_RDONLYOSErrorrR   r   rG   _deserializesuper_set_cache_)rZ   r\   rK   r]   	__class__rM   rN   rd      s   zIndexFile._set_cache_c                 C   s   | j jrt| j jdS td)Nindexz)No git directory given to join index path)rP   git_dirr   r   rZ   rM   rM   rN   rY      s   zIndexFile._index_pathc                 C   s   | j S )z3:return: Path to the index file we are representing)rT   ri   rM   rM   rN   path   s   zIndexFile.pathc                 C   s    z| ` W dS  ty   Y dS w )z6Safely clear the entries cache so it can be recreated.N)rR   AttributeErrorri   rM   rM   rN   _delete_entries_cache   s
   
zIndexFile._delete_entries_cacher]   c                 C   s   t |\| _| _| _}| S )zFInitialize this instance with index values read from the given stream.)r    rQ   rR   rS   )rZ   r]   _conten_sharM   rM   rN   rb      s   zIndexFile._deserializec                 C   s   t | j dd dS )zK:return: List of entries, in a sorted fashion, first by path, then by stagec                 S   s   | j | jfS Nrj   stageerM   rM   rN   <lambda>       z+IndexFile._entries_sorted.<locals>.<lambda>)key)sortedrR   valuesri   rM   rM   rN   _entries_sorted   s   zIndexFile._entries_sortedFignore_extension_datac                 C   s&   |   }| j}|rd }t||| | S rn   )rx   rS   r#   )rZ   r]   ry   rR   extension_datarM   rM   rN   
_serialize   s   zIndexFile._serializec                 C   sj   | j  t|p| j}|jddd}z| || W n ty%   |   w |  |dur3|| _dS dS )a  Write the current state to our file path or to the given one.

        :param file_path:
            If ``None``, we will write to our stored file path from which we have been
            initialized. Otherwise we write to the given file path. Please note that
            this will change the `file_path` of this index to the one you gave.

        :param ignore_extension_data:
            If ``True``, the TREE type extension data read in the index will not be
            written to disk. NOTE that no extension data is actually written. Use this
            if you have altered the index and would like to use
            :manpage:`git-write-tree(1)` afterwards to create a tree representing your
            written changes. If this data is present in the written index,
            :manpage:`git-write-tree(1)` will instead write the stored/cached tree.
            Alternatively, use :meth:`write_tree` to handle this case automatically.
        T)writer]   N)rR   r   rT   r_   r{   BaseExceptionrollbackcommit)rZ   rV   ry   lfdr]   rM   rM   rN   r|      s   
zIndexFile.writerhsbasec                 C   s6   g d}|dur| | | | | jj| | S )a  Merge the given `rhs` treeish into the current index, possibly taking
        a common base treeish into account.

        As opposed to the :func:`from_tree` method, this allows you to use an already
        existing tree as the left side of the merge.

        :param rhs:
            Treeish reference pointing to the 'other' side of the merge.

        :param base:
            Optional treeish reference pointing to the common base of `rhs` and this
            index which equals lhs.

        :return:
            self (containing the merge and possibly unmerged entries in case of
            conflicts)

        :raise git.exc.GitCommandError:
            If there is a merge conflict. The error will be raised at the first
            conflicting path. If you want to have proper merge resolution to be done by
            yourself, you have to commit the changed index (or make a valid tree from
            it) and retry with a three-way :meth:`index.from_tree <from_tree>` call.
        )--aggressivez-iz-mN)appendrP   git	read_tree)rZ   r   r   argsrM   rM   rN   
merge_tree   s   

zIndexFile.merge_treetree_shac                 G   sN   dd |D }t |j|}| |}ttdd |D dd |D }||_|S )a  Merge the given treeish revisions into a new index which is returned.

        This method behaves like ``git-read-tree --aggressive`` when doing the merge.

        :param repo:
            The repository treeish are located in.

        :param tree_sha:
            20 byte or 40 byte tree sha or tree objects.

        :return:
            New :class:`IndexFile` instance. Its path will be undefined.
            If you intend to write such a merged Index, supply an alternate
            ``file_path`` to its :meth:`write` method.
        c                 S   s   g | ]}t t|qS rM   )r   str).0trM   rM   rN   
<listcomp>4      z!IndexFile.new.<locals>.<listcomp>c                 s   s    | ]	}|j |jfV  qd S rn   ro   r   rr   rM   rM   rN   	<genexpr>;  s    z IndexFile.new.<locals>.<genexpr>c                 s   s    | ]}t |V  qd S rn   )r&   	from_baser   rM   rM   rN   r   <  s    )r   odbdictziprR   )clsrP   r   tree_sha_bytesbase_entriesinstrR   rM   rM   rN   new#  s   zIndexFile.newtreeishkwargsc              	   O   s   t |dkst |dkrtdt | g }t |dkr&|d |d t|jG}|d|  || tt|jd" |jj	|i | | ||}|j
 |W  d	   W  d	   S 1 sew   Y  W d	   d	S 1 suw   Y  d	S )
a  Merge the given treeish revisions into a new index which is returned.
        The original index will remain unaltered.

        :param repo:
            The repository treeish are located in.

        :param treeish:
            One, two or three :class:`~git.objects.tree.Tree` objects,
            :class:`~git.objects.commit.Commit`\s or 40 byte hexshas.

            The result changes according to the amount of trees:

            1. If 1 Tree is given, it will just be read into a new index.
            2. If 2 Trees are given, they will be merged into a new index using a two
               way merge algorithm. Tree 1 is the 'current' tree, tree 2 is the 'other'
               one. It behaves like a fast-forward.
            3. If 3 Trees are given, a 3-way merge will be performed with the first tree
               being the common ancestor of tree 2 and tree 3. Tree 2 is the 'current'
               tree, tree 3 is the 'other' one.

        :param kwargs:
            Additional arguments passed to :manpage:`git-read-tree(1)`.

        :return:
            New :class:`IndexFile` instance. It will point to a temporary index location
            which does not exist anymore. If you intend to write such a merged Index,
            supply an alternate ``file_path`` to its :meth:`write` method.

        :note:
            In the three-way merge case, ``--aggressive`` will be specified to
            automatically resolve more cases in a commonly correct manner. Specify
            ``trivial=True`` as a keyword argument to override that.

            As the underlying :manpage:`git-read-tree(1)` command takes into account the
            current index, it will be temporarily moved out of the way to prevent any
            unexpected interference.
        r      z.Please specify between 1 and 3 treeish, got %ir   z--resetr   z--index-output=%srg   N)len
ValueErrorr   rO   rh   extendr'   r   r   r   rR   )r   rP   r   r   arg_list	tmp_indexrg   rM   rM   rN   	from_treeC  s$   '



"zIndexFile.from_treerZ   pathsc              	   c   sP   dt dtfdd}t| jj}|tj }|D ]}t|}t|s(t	||}zt
|}W n	 ty8   Y nw t|jrF||dV  qtj|svd|v sXd|v sXd|v rvt|}||vrv| t|D ]}	t|	|dV  qiqztj||d	D ]\}
}}|D ]}t	|
|d|V  qq~W q ty   ||dV  Y qw d
S )a=  Expand the directories in list of paths to the corresponding paths
        accordingly.

        :note:
            git will add items multiple times even if a glob overlapped with manually
            specified paths or if paths where specified multiple times - we respect that
            and do not prune.
        rr   r?   c                 S   s   | rn   rM   rq   rM   rM   rN   	raise_exc  s   z/IndexFile._iter_expand_paths.<locals>.raise_exc ?*[)onerrorN)	Exceptionr4   r   rP   working_tree_dirrF   sepospisabsjoinlstatra   r   st_modereplacerj   existsglob_iter_expand_pathswalk)rZ   r   r   rrsrj   abs_pathstresolved_pathsfroot_dirsfiles	rela_filerM   rM   rN   r     s@   


$
zIndexFile._iter_expand_pathsTprocr;   filepathitemfmakeexc.	fprogressread_from_stdoutc           	   
   C   s   ||d| d}|j dur0z|j d| t W n ty* } z| |d}~ww |j   |r>|jdur>|j  }||d| |S )a  Write path to ``proc.stdin`` and make sure it processes the item, including
        progress.

        :return:
            stdout string

        :param read_from_stdout:
            If ``True``, ``proc.stdout`` will be read after the item was sent to stdin.
            In that case, it will return ``None``.

        :note:
            There is a bug in :manpage:`git-update-index(1)` that prevents it from
            sending reports just in time. This is why we have a version that tries to
            read stdout and one which doesn't. In fact, the stdout is not important as
            the piped-in files are processed anyway and just in time.

        :note:
            Newlines are essential here, git's behaviour is somewhat inconsistent on
            this depending on the version, hence we try our best to deal with newlines
            carefully. Usually the last newline will not be sent, instead we will close
            stdin to break the pipe.
        FNz%s
T)	stdinr|   encoder	   IOErrorflushstdoutreadlinestrip)	rZ   r   r   r   r   r   r   rvalrr   rM   rM   rN   _write_path_to_stdin  s   

zIndexFile._write_path_to_stdinc                 C   s   dS )NTrM   r   rM   rM   rN   rs         zIndexFile.<lambda>	predicatec                 c   sB    | j  D ]}|| j}|j|_|j|f}||r|V  qdS )a  
        :return:
            Iterator yielding tuples of :class:`~git.objects.blob.Blob` objects and
            stages, tuple(stage, Blob).

        :param predicate:
            Function(t) returning ``True`` if tuple(stage, Blob) should be yielded by
            the iterator. A default filter, the `~git.index.typ.BlobFilter`, allows you
            to yield blobs only if they match a given list of paths.
        N)rR   rw   to_blobrP   sizerp   )rZ   r   entrybloboutputrM   rM   rN   
iter_blobs  s   
zIndexFile.iter_blobsc                 C   sR   dd }i }|  |D ]\}}||jg ||f q| D ]}|  q |S )a  
        :return:
            Dict(path : list(tuple(stage, Blob, ...))), being a dictionary associating a
            path in the index with a list containing sorted stage/blob pairs.

        :note:
            Blobs that have been removed in one side simply do not exist in the given
            stage. That is, a file removed on the 'other' branch whose entries are at
            stage 3 will not have a stage 3 entry.
        c                 S   s   | d dkS )Nr   rM   r   rM   rM   rN   rs     rt   z*IndexFile.unmerged_blobs.<locals>.<lambda>)r   
setdefaultrj   r   rw   sort)rZ   is_unmerged_blobpath_maprp   r   linerM   rM   rN   unmerged_blobs
  s   
zIndexFile.unmerged_blobsr   c                 G   s   t | S rn   )r   )r   r   rM   rM   rN   r     s   zIndexFile.entry_keyr   c              
   C   sr   |D ]4}|j df}|| jv rtdt|j  dD ]}z	| j|j |f= W q ty-   Y qw t|| j|< q| S )am  Resolve the blobs given in blob iterator.

        This will effectively remove the index entries of the respective path at all
        non-null stages and add the given blob as new stage null blob.

        For each path there may only be one blob, otherwise a :exc:`ValueError` will be
        raised claiming the path is already at stage 0.

        :raise ValueError:
            If one of the blobs already existed at stage 0.

        :return:
            self

        :note:
            You will have to write the index manually once you are done, i.e.
            ``index.resolve_blobs(blobs).write()``.
        r   z!Path %r already exists at stage 0)r   rU   r   )rj   rR   r   r   KeyErrorr&   	from_blob)rZ   r   r   stage_null_keyrp   rM   rM   rN   resolve_blobs#  s   

zIndexFile.resolve_blobsc                 C   s   |    | S )a  Reread the contents of our index file, discarding all cached information
        we might have.

        :note:
            This is a possibly dangerous operations as it will discard your changes to
            :attr:`index.entries <entries>`.

        :return:
            self
        )rl   ri   rM   rM   rN   updateJ  s   zIndexFile.updatec                 C   sV   t  }|  }t||tdt|\}}|| | jj t	| j|dd}||_
|S )aO  Write this index to a corresponding :class:`~git.objects.tree.Tree` object
        into the repository's object database and return it.

        :return:
            :class:`~git.objects.tree.Tree` object representing this index.

        :note:
            The tree will be written even if one or more objects the tree refers to does
            not yet exist in the object database. This could happen if you added entries
            to the index directly.

        :raise ValueError:
            If there are no entries in the cache.

        :raise git.exc.UnmergedEntriesError:
        r   r   rj   )r   rx   r$   slicer   stream_copysha_iterrP   r   r   _cache)rZ   mdbrR   binsha
tree_items	root_treerM   rM   rN   
write_treeY  s   zIndexFile.write_treer   zgit_diff.Diffablec                 C   s,   z| ||  W |S  ty   Y |S w rn   )poprg   
IndexError)rZ   r   rM   rM   rN   _process_diff_argsy  s   zIndexFile._process_diff_argsrj   c                 C   s`   t |s|S | jjrtdt t|t| jjs't	d|| jjf t
j|| jjS )z
        :return:
            Version of path relative to our git directory or raise :exc:`ValueError` if
            it is not within our git directory.

        :raise ValueError:
        zrequire non-bare repositoryz/Absolute path %r is not in git repository at %r)r   r   rP   barer   normpathr   
startswithr   r   rF   rj   relpath)rZ   rj   rM   rM   rN   _to_relative_path  s   
zIndexFile._to_relative_pathitemsr   c                 C   s   g }g }t |ttjfr|g}|D ]3}t |ttjfr$|| | qt |ttfr4|t	| qt |tr?|| qt
d| ||fS )z?Split the items into two lists of path strings and BaseEntries.zInvalid Type: %r)
isinstancer   rF   r:   r   r   r   r   r%   r   	TypeError)rZ   r   r   rR   r   rM   rM   rN   _preprocess_add_items  s   
zIndexFile._preprocess_add_itemsc                    s   t  }t|jr fdd}n fdd}| !}| d  | jjttj	|j
|}| d  W d   n1 s>w   Y  tt|j|jdt fS )zStore file at filepath in the database and return the base index entry.

        :note:
            This needs the :func:`~git.index.util.git_working_dir` decorator active!
            This must be ensured in the calling code.
        c                      s   t tt tdS )N)encoding)r   r
   rF   readlinkr	   rM   r   rM   rN   rs     s    z'IndexFile._store_path.<locals>.<lambda>c                      s
   t  dS Nrb)r_   rM   r   rM   rN   rs     s   
 FTNr   )rF   r   r   r   rP   r   storer   r   typest_sizer%   r"   r   r   )rZ   r   r   r   open_streamr]   istreamrM   r   rN   _store_path  s    

zIndexFile._store_pathpath_rewriterrR   c                 C   s   g }|rK|D ]?}t |r|}|tt| jjd d  }n|}| jjr,t | jj|}t| jtjt	t
|jt|}	|t|	 q|d d = t|dksSJ | |D ]}
|| |
| qX|S )Nr   r   )r   r   r   r   rP   r   r   r   NULL_BIN_SHAr"   rF   statr   r   r   r%   r   r   r  )rZ   r   r  r   rR   entries_addedrj   abspathgitrelative_pathr   r   rM   rM   rN   _entries_for_paths  s*   	

zIndexFile._entries_for_pathsc                  G      d S rn   rM   r   rM   rM   rN   rs     r   forcer|   write_extension_datac                    s,  |  |\} g }|r|| ||   r{dd  D }	|	r%tddd t D r?td fd	d
}
|
|  |rYt D ]\}}t|j|j|j	||f |< qEt D ]\}}|v }|su|j
d| |j
d| q]|  |D ]}t|| j|j
df< q}|r| j| d |S )a  Add files from the working tree, specific blobs, or
        :class:`~git.index.typ.BaseIndexEntry`\s to the index.

        :param items:
            Multiple types of items are supported, types can be mixed within one call.
            Different types imply a different handling. File paths may generally be
            relative or absolute.

            - path string

                Strings denote a relative or absolute path into the repository pointing
                to an existing file, e.g., ``CHANGES``, `lib/myfile.ext``,
                ``/home/gitrepo/lib/myfile.ext``.

                Absolute paths must start with working tree directory of this index's
                repository to be considered valid. For example, if it was initialized
                with a non-normalized path, like ``/root/repo/../repo``, absolute paths
                to be added must start with ``/root/repo/../repo``.

                Paths provided like this must exist. When added, they will be written
                into the object database.

                PathStrings may contain globs, such as ``lib/__init__*``. Or they can be
                directories like ``lib``, which will add all the files within the
                directory and subdirectories.

                This equals a straight :manpage:`git-add(1)`.

                They are added at stage 0.

            - :class:~`git.objects.blob.Blob` or
              :class:`~git.objects.submodule.base.Submodule` object

                Blobs are added as they are assuming a valid mode is set.

                The file they refer to may or may not exist in the file system, but must
                be a path relative to our repository.

                If their sha is null (40*0), their path must exist in the file system
                relative to the git repository as an object will be created from the
                data at the path.

                The handling now very much equals the way string paths are processed,
                except that the mode you have set will be kept. This allows you to
                create symlinks by settings the mode respectively and writing the target
                of the symlink directly into the file. This equals a default Linux
                symlink which is not dereferenced automatically, except that it can be
                created on filesystems not supporting it as well.

                Please note that globs or directories are not allowed in
                :class:`~git.objects.blob.Blob` objects.

                They are added at stage 0.

            - :class:`~git.index.typ.BaseIndexEntry` or type

                Handling equals the one of :class:~`git.objects.blob.Blob` objects, but
                the stage may be explicitly set. Please note that Index Entries require
                binary sha's.

        :param force:
            **CURRENTLY INEFFECTIVE**
            If ``True``, otherwise ignored or excluded files will be added anyway. As
            opposed to the :manpage:`git-add(1)` command, we enable this flag by default
            as the API user usually wants the item to be added even though they might be
            excluded.

        :param fprogress:
            Function with signature ``f(path, done=False, item=item)`` called for each
            path to be added, one time once it is about to be added where ``done=False``
            and once after it was added where ``done=True``.

            ``item`` is set to the actual item we handle, either a path or a
            :class:`~git.index.typ.BaseIndexEntry`.

            Please note that the processed path is not guaranteed to be present in the
            index already as the index is currently being processed.

        :param path_rewriter:
            Function, with signature ``(string) func(BaseIndexEntry)``, returning a path
            for each passed entry which is the path to be actually recorded for the
            object created from :attr:`entry.path <git.index.typ.BaseIndexEntry.path>`.
            This allows you to write an index which is not identical to the layout of
            the actual files on your hard-disk. If not ``None`` and `items` contain
            plain paths, these paths will be converted to Entries beforehand and passed
            to the path_rewriter. Please note that ``entry.path`` is relative to the git
            repository.

        :param write:
            If ``True``, the index will be written once it was altered. Otherwise the
            changes only exist in memory and are not available to git commands.

        :param write_extension_data:
            If ``True``, extension data will be written back to the index. This can lead
            to issues in case it is containing the 'TREE' extension, which will cause
            the :manpage:`git-commit(1)` command to write an old tree, instead of a new
            one representing the now changed index.

            This doesn't matter if you use :meth:`IndexFile.commit`, which ignores the
            'TREE' extension altogether. You should set it to ``True`` if you intend to
            use :meth:`IndexFile.commit` exclusively while maintaining support for
            third-party extensions. Besides that, you can usually safely ignore the
            built-in extensions when using GitPython on repositories that are not
            handled manually at all.

            All current built-in extensions are listed here:
            https://git-scm.com/docs/index-format

        :return:
            List of :class:`~git.index.typ.BaseIndexEntry`\s representing the entries
            just actually added.

        :raise OSError:
            If a supplied path did not exist. Please note that
            :class:`~git.index.typ.BaseIndexEntry` objects that do not have a null sha
            will be added even if their paths do not exist.
        c                 S   s   g | ]	}|j d kr|qS )r   )moder   rM   rM   rN   r   y      z!IndexFile.add.<locals>.<listcomp>zXAt least one Entry has a null-mode - please use index.remove to remove files for clarityc                 S   s    g | ]\}}|j tjkr|qS rM   )r   r   r  )r   irr   rM   rM   rN   r     s     rZ   r   r?   Nc                    s@   D ]} | }|  |j}t|j|j|j|jf |< qd S rn   )r  rj   r%   r  r   rp   )rZ   ei
null_entry	new_entryrR   r   null_entries_indicesrM   rN   handle_null_entries  s   
z*IndexFile.add.<locals>.handle_null_entriesFTr   )ry   )rZ   r   r?   N)r   r   r  r   	enumerater*   r%   r  r   rp   rj   r&   r   rR   r|   )rZ   r   r  r   r  r|   r  r   r  null_mode_entriesr  r  rr   r   progress_sentrM   r  rN   add  s>     
zIndexFile.addc                 C   sz   g }t |ttjfr|g}|D ]+}t |tttffr$|| |j	 qt |ttjfr5|| | qt
d| |S )z}Returns a list of repo-relative paths from the given items which
        may be absolute or relative paths, entries or blobs.zInvalid item type: %r)r   r   rF   r:   r%   r   r   r   r   rj   r   )rZ   r   r   r   rM   rM   rN   _items_to_rela_paths  s   zIndexFile._items_to_rela_pathsworking_treec                 K   sP   g }|s	| d | d | |}| jjj||fi | }dd |D S )a&  Remove the given items from the index and optionally from the working tree
        as well.

        :param items:
            Multiple types of items are supported which may be be freely mixed.

            - path string

                Remove the given path at all stages. If it is a directory, you must
                specify the ``r=True`` keyword argument to remove all file entries below
                it. If absolute paths are given, they will be converted to a path
                relative to the git repository directory containing the working tree

                The path string may include globs, such as ``*.c``.

            - :class:~`git.objects.blob.Blob` object

                Only the path portion is used in this case.

            - :class:`~git.index.typ.BaseIndexEntry` or compatible type

                The only relevant information here is the path. The stage is ignored.

        :param working_tree:
            If ``True``, the entry will also be removed from the working tree,
            physically removing the respective file. This may fail if there are
            uncommitted changes in it.

        :param kwargs:
            Additional keyword arguments to be passed to :manpage:`git-rm(1)`, such as
            ``r`` to allow recursive removal.

        :return:
            List(path_string, ...) list of repository relative paths that have been
            removed effectively.

            This is interesting to know in case you have provided a directory or globs.
            Paths are relative to the repository.
        z--cachedz--c                 S   s   g | ]}|d d qS )   rM   )r   prM   rM   rN   r   	  r   z$IndexFile.remove.<locals>.<listcomp>)r   r  rP   r   rm
splitlines)rZ   r   r  r   r   r   removed_pathsrM   rM   rN   rH     s   /


zIndexFile.removeskip_errorsc                 K   s  g }|r	| d | |}t|dk rtd|d|dd}d|d< g }| jjj||fi | }t	t
t|d t|D ]&}	||	 d}
t|
dksZJ d	||	  | |
d
 dd |
d f qC|rn|S |d | jjj||fi | |S )a  Rename/move the items, whereas the last item is considered the destination of
        the move operation.

        If the destination is a file, the first item (of two) must be a file as well.

        If the destination is a directory, it may be preceded by one or more directories
        or files.

        The working tree will be affected in non-bare repositories.

        :param items:
            Multiple types of items are supported, please see the :meth:`remove` method
            for reference.

        :param skip_errors:
            If ``True``, errors such as ones resulting from missing source files will be
            skipped.

        :param kwargs:
            Additional arguments you would like to pass to :manpage:`git-mv(1)`, such as
            ``dry_run`` or ``force``.

        :return:
            List(tuple(source_path_string, destination_path_string), ...)

            A list of pairs, containing the source file moved as well as its actual
            destination. Relative to the repository root.

        :raise ValueError:
            If only one item was given.

        :raise git.exc.GitCommandError:
            If git could not handle your request.
        z-krU   zLPlease provide at least one source and one destination of the move operationdry_runnNTz to zToo many tokens in %sr   	   r   )r   r  r   r   r   rP   r   mvr#  rangeintsplit)rZ   r   r%  r   r   r   was_dry_runoutmvlineslntokensrM   rM   rN   move  s&   *

 
zIndexFile.movemessageparent_commitsheadauthor	committerauthor_datecommit_date
skip_hooksc	                 C   sp   |st d|  | | t d| |   |  }|   |  }	tj| j|	|||||||d	}
|s6t d|  |
S )a  Commit the current default index file, creating a
        :class:`~git.objects.commit.Commit` object.

        For more information on the arguments, see
        :meth:`Commit.create_from_tree <git.objects.commit.Commit.create_from_tree>`.

        :note:
            If you have manually altered the :attr:`entries` member of this instance,
            don't forget to :meth:`write` your changes to disk beforehand.

        :note:
            Passing ``skip_hooks=True`` is the equivalent of using ``-n`` or
            ``--no-verify`` on the command line.

        :return:
            :class:`~git.objects.commit.Commit` object representing the new commit
        z
pre-commitz
commit-msg)r6  r7  r8  r9  zpost-commit)	r!   _write_commit_editmsg_commit_editmsg_filepath_read_commit_editmsg_remove_commit_editmsgr   r   create_from_treerP   )rZ   r3  r4  r5  r6  r7  r8  r9  r:  treer   rM   rM   rN   r   [  s*   


zIndexFile.commitc                 C   sD   t |  d}||t W d    d S 1 sw   Y  d S )Nwb)r_   r<  r|   r   r	   )rZ   r3  commit_editmsg_filerM   rM   rN   r;    s   "zIndexFile._write_commit_editmsgc                 C   s   t |   d S rn   )rF   rH   r<  ri   rM   rM   rN   r>    s   z IndexFile._remove_commit_editmsgc                 C   s@   t |  d}| tW  d    S 1 sw   Y  d S r   )r_   r<  readdecoder	   )rZ   rB  rM   rM   rN   r=    s   $zIndexFile._read_commit_editmsgc                 C   s   t | jjdS )NCOMMIT_EDITMSG)r   r   rP   
common_dirri   rM   rM   rN   r<    s   z"IndexFile._commit_editmsg_filepathPopen[bytes]ignore_stdoutc                 C   sN   |j }|r|  |  d}|s|jr|j }|jr%|j  |  |S )NrW   )r   r   rG   r   rC  wait)r   r   rH  stdin_IOr   rM   rM   rN   _flush_stdin_and_wait  s   


zIndexFile._flush_stdin_and_waitc                  G   r  rn   rM   r  rM   rM   rN   rs     r   c                    s  dg |r
  d g g g dddtt ddffdd	}|du rY  d
 d|d< |ddd | jjj i |  |ddd dd | j D }|| |S t	|t
ra|g}| j   d d|d< tj|d< | jjj fi | fdd}g }|D ]b}	t| |	}
d}z	| j|
df  W n; ty   t
|
}|ds|d7 }| j D ]}t
|j|r|j}| j||||dd | | d}qY nw |s| j|
|	||dd | |
 qz	| jdd W n ty   tdg w || |S )a  Check out the given paths or all files from the version known to the index
        into the working tree.

        :note:
            Be sure you have written pending changes using the :meth:`write` method in
            case you have altered the entries dictionary directly.

        :param paths:
            If ``None``, all paths in the index will be checked out.
            Otherwise an iterable of relative or absolute paths or a single path
            pointing to files or directories in the index is expected.

        :param force:
            If ``True``, existing files will be overwritten even if they contain local
            modifications.
            If ``False``, these will trigger a :exc:`~git.exc.CheckoutError`.

        :param fprogress:
            See :meth:`IndexFile.add` for signature and explanation.

            The provided progress information will contain ``None`` as path and item if
            no explicit paths are given. Otherwise progress information will be send
            prior and after a file has been checked out.

        :param kwargs:
            Additional arguments to be passed to :manpage:`git-checkout-index(1)`.

        :return:
            Iterable yielding paths to files which have been checked out and are
            guaranteed to match the version stored in the index.

        :raise git.exc.CheckoutError:
            * If at least one file failed to be checked out. This is a summary, hence it
              will checkout as many files as it can anyway.
            * If one of files or directories do not exist in the index (as opposed to
              the original git command, which ignores them).

        :raise git.exc.GitCommandError:
            If error lines could not be parsed - this truly is an exceptional state.

        :note:
            The checkout is limited to checking out the files in the index. Files which
            are not in the index anymore and exist in the working tree will not be
            deleted. This behaviour is fundamentally different to ``head.checkout``,
            i.e. if you want :manpage:`git-checkout(1)`-like behaviour, use
            ``head.checkout`` instead of ``index.checkout``.
        z--indexz--forcer   rG  iter_checked_out_filesr?   Nc                    s`  | j }|sd S | }|t}d}| D ]|}|dsu|dsud}d}d}	||r? |d t|   | n5||rX |t||	d  | n||	ro |d t|	   |	 n| q|D ]}
||
r |dt|
   |
  nqwqrt
d	d
| rtt|t  }td |d S )N)z already existsz is not in the cachez does not exist at stagez is unmergedzgit checkout-index: zgit-checkout-index: z is a directoryzunable to unlink old 'z already exists, no checkout'   zgit-checkout-index   zMSome files could not be checked out from the index due to local modifications)stderrrC  rD  r	   r#  r   endswithr   r   rfindr   listsetr   )r   rL  	stderr_IOstderr_bytesrQ  endingsr   is_a_dirunlink_issuealready_exists_issuerr   valid_files)failed_filesfailed_reasonsunknown_linesrM   rN   handle_stderr  sP   






z)IndexFile.checkout.<locals>.handle_stderrz--allr   
as_processFTc                 s   s    | ]}|j V  qd S rn   r   r   rM   rM   rN   r   (  s    z%IndexFile.checkout.<locals>.<genexpr>z--stdinr  c                      s   t dt  dj S )NrO  rP  )r   tuplerQ  rC  rM   )r   r   rM   rN   rs   9  r  z$IndexFile.checkout.<locals>.<lambda>r   /)r   )rH  zWSome files could not be checked out from the index, probably because they didn't exist.)r   r1   r:   rP   r   checkout_indexrI  rR   rw   r   r   
subprocessPIPEr   r   r   rR  rj   r   r   rK  r   r   )rZ   r   r  r   r   r`  	rval_itermake_excchecked_out_filesrj   co_pathpath_is_directoryfolderr   r!  rM   )r   r]  r^  r   r_  rN   checkout  sx   7
"7








	zIndexFile.checkoutHEADr   r<   c           
      K   s   t | | j|}|s|j| _n4|j}|D ].}| |}zt|d}	||	 | j|	< W q tyC   z| j|	= W n	 ty@   Y nw Y qw |   |rQ| j|dd |rb| jj	j
| j|d| d | S )a[  Reset the index to reflect the tree at the given commit. This will not adjust
        our HEAD reference by default, as opposed to
        :meth:`HEAD.reset <git.refs.head.HEAD.reset>`.

        :param commit:
            Revision, :class:`~git.refs.reference.Reference` or
            :class:`~git.objects.commit.Commit` specifying the commit we should
            represent.

            If you want to specify a tree only, use :meth:`IndexFile.from_tree` and
            overwrite the default index.

        :param working_tree:
            If ``True``, the files in the working tree will reflect the changed index.
            If ``False``, the working tree will not be touched.
            Please note that changes to the working copy will be discarded without
            warning!

        :param head:
            If ``True``, the head will be set to the given commit. This is ``False`` by
            default, but if ``True``, this method behaves like
            :meth:`HEAD.reset <git.refs.head.HEAD.reset>`.

        :param paths:
            If given as an iterable of absolute or repository-relative paths, only these
            will be reset to their state at the given commit-ish.
            The paths need to exist at the commit, otherwise an exception will be
            raised.

        :param kwargs:
            Additional keyword arguments passed to :manpage:`git-reset(1)`.

        :note:
            :meth:`IndexFile.reset`, as opposed to
            :meth:`HEAD.reset <git.refs.head.HEAD.reset>`, will not delete any files in
            order to maintain a consistent working tree. Instead, it will just check out
            the files according to their state in the index.
            If you want :manpage:`git-reset(1)`-like behaviour, use
            :meth:`HEAD.reset <git.refs.head.HEAD.reset>` instead.

        :return:
            self
        r   T)r   r  z%s: Updating HEAD)logmsg)r   r   rP   rR   r   r   r   r|   rm  r5  
set_commitr   )
rZ   r   r  r   r5  r   new_instnierj   ru   rM   rM   rN   resete  s.   6



zIndexFile.resetotherr   r   create_patchc                    s   | j |  krtd|   || ju rt S t|tr#| j	
|}t|tr?|dd}| |d< |j| j||fi |S |durItd| t j|||fi |S )a  Diff this index against the working copy or a :class:`~git.objects.tree.Tree`
        or :class:`~git.objects.commit.Commit` object.

        For documentation of the parameters and return values, see
        :meth:`Diffable.diff <git.diff.Diffable.diff>`.

        :note:
            Will only work with indices that represent the default git index as they
            have not been initialized with a stream.
        zECannot call %r on indices that do not represent the default git indexRFNz<other must be None, Diffable.INDEX, a Tree or Commit, was %r)rT   rY   AssertionErrordiffINDEXgit_diff	DiffIndexr   r   rP   	rev_parser   getr   rc   )rZ   rt  r   ru  r   cur_valre   rM   rN   rx    s   



zIndexFile.diffrn   )r?   N)F)NF)T)r?   r   )NTNNNNF)rn  FNF)S__name__
__module____qualname____doc__	__slots__rX   r   r8   r:   r[   r   rd   rY   propertyrj   rl   r0   rb   r3   r&   rx   boolr{   r|   r(   r)   Treeishr   classmethodr   r   r+   r   r   r5   r2   r   r-   r   r   r7   r   r   r   r.   r   r%   r   r   r   r   r   r   r   r  r*   r  r  r   r  rH   r2  r   r   datetimer   r;  r>  r=  r<  bytesrK  r1   rm  rs  rz  ry  r9   DiffConstantsr{  Diffrx  __classcell__rM   rM   re   rN   r   n   s    


($# E B


1
"&
' 


*
 M
:Q

	

3
 :_
	

r   )`r  __all__
contextlibr  r   ior   rF   os.pathrj   r   r  r   re  rB   rD   
gitdb.baser   gitdb.dbr   
git.compatr	   r
   git.diffrx  rz  git.excr   r   r   r   git.objectsr   r   r   r   r   git.objects.utilr   git.utilr   r   r   r   r   r   r   r   funr   r   r   r    r!   r"   r#   r$   typr%   r&   r   utilr'   r(   r)   r*   typingr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   	git.typesr9   r:   r;   git.refs.referencer<   git.repor=   r   r  r  contextmanagerrO   Diffabler   rM   rM   rM   rN   <module>   sB   ((
@