Index file & Working copy

Repository.index

Index representing the repository’s index file.

Index read:

>>> index = repo.index
>>> index.read()
>>> id = index['path/to/file'].id    # from path to object id
>>> blob = repo[id]                  # from object id to object

Iterate over all entries of the index:

>>> for entry in index:
...     print(entry.path, entry.hex)

Index write:

>>> index.add('path/to/file')          # git add
>>> index.remove('path/to/file')       # git rm
>>> index.write()                      # don't forget to save the changes
Custom entries::
>>> entry = pygit2.IndexEntry('README.md', blob_id, blob_filemode)
>>> repo.index.add(entry)

The index fulfills a dual role as the in-memory representation of the index file and data structure which represents a flat list of a tree. You can use it independently of the index file, e.g.

>>> index = pygit2.Index()
>>> entry = pygit2.IndexEntry('README.md', blob_id, blob_filemode)
>>> index.add(entry)

The Index type

class pygit2.Index(path=None)
add(path_or_entry)

Add or update an entry in the Index.

If a path is given, that file will be added. The path must be relative to the root of the worktree and the Index must be associated with a repository.

If an IndexEntry is given, that entry will be added or update in the Index without checking for the existence of the path or id.

add_all(pathspecs=None)

Add or update index entries matching files in the working directory.

If pathspecs are specified, only files matching those pathspecs will be added.

property conflicts

A collection of conflict information

If there are no conflicts None is returned. Otherwise return an object that represents the conflicts in the index.

This object presents a mapping interface with the paths as keys. You can use the del operator to remove a conflict from the Index.

Each conflict is made up of three elements. Access or iteration of the conflicts returns a three-tuple of IndexEntry. The first is the common ancestor, the second is the “ours” side of the conflict, and the third is the “theirs” side.

These elements may be None depending on which sides exist for the particular conflict.

diff_to_tree(tree: Tree, flags: DiffOption = DiffOption.NORMAL, context_lines: int = 3, interhunk_lines: int = 0) Diff

Diff the index against a tree. Return a <Diff> object with the differences between the index and the given tree.

Parameters:

tree

The tree to diff.

flags

A combination of enums.DiffOption constants.

context_lines

The number of unchanged lines that define the boundary of a hunk (and to display before and after).

interhunk_lines

The maximum number of unchanged lines between hunk boundaries before the hunks will be merged into a one.

diff_to_workdir(flags: DiffOption = DiffOption.NORMAL, context_lines: int = 3, interhunk_lines: int = 0) Diff

Diff the index against the working directory. Return a <Diff> object with the differences between the index and the working copy.

Parameters:

flags

A combination of enums.DiffOption constants.

context_lines

The number of unchanged lines that define the boundary of a hunk (and to display before and after).

interhunk_lines

The maximum number of unchanged lines between hunk boundaries before the hunks will be merged into a one.

read(force=True)

Update the contents of the Index by reading from a file.

Parameters:

force

If True (the default) always reload. If False, only if the file has changed.

read_tree(tree)

Replace the contents of the Index with those of the given tree, expressed either as a <Tree> object or as an oid (string or <Oid>).

The tree will be read recursively and all its children will also be inserted into the Index.

remove(path, level=0)

Remove an entry from the Index.

remove_all(pathspecs)

Remove all index entries matching pathspecs.

write()

Write the contents of the Index to disk.

write_tree(repo=None)

Create a tree out of the Index. Return the <Oid> object of the written tree.

The contents of the index will be written out to the object database. If there is no associated repository, ‘repo’ must be passed. If there is an associated repository and ‘repo’ is passed, then that repository will be used instead.

It returns the id of the resulting tree.

The IndexEntry type

class pygit2.IndexEntry(path, object_id: Oid, mode: FileMode)
__eq__(other)

Return self==value.

__ne__(value, /)

Return self!=value.

__repr__()

Return repr(self).

__str__()

Return str(self).

property hex

The id of the referenced object as a hex string

id: Oid

The id of the referenced object

mode: FileMode

The mode of this entry, a FileMode value

path: str

The path of this entry

The Stash type

class pygit2.Stash

Stashed state.

commit_id

The commit id of the stashed state.

message

Stash message.

Status

class pygit2.Repository(path: str | None = None, flags: RepositoryOpenFlag = RepositoryOpenFlag.DEFAULT)
status(untracked_files: str = 'all', ignored: bool = False) dict[str, enums.FileStatus]

Reads the status of the repository and returns a dictionary with file paths as keys and FileStatus flags as values.

Parameters:

untracked_files

How to handle untracked files, defaults to “all”:

  • “no”: do not return untracked files

  • “normal”: include untracked files/directories but no dot recurse subdirectories

  • “all”: include all files in untracked directories

Using untracked_files=”no” or “normal”can be faster than “all” when the worktree contains many untracked files/directories.

ignored

Whether to show ignored files with untracked files. Ignored when untracked_files == “no” Defaults to False.

Example, inspect the status of the repository:

from pygit2.enums import FileStatus
status = repo.status()
for filepath, flags in status.items():
    if flags != FileStatus.CURRENT:
        print(f"Filepath {filepath} isn't clean")
status_file(path: str) enums.FileStatus

Returns the status of the given file path.

This is the list of status flags for a single file:

enums.FileStatus.CURRENT
enums.FileStatus.INDEX_NEW
enums.FileStatus.INDEX_MODIFIED
enums.FileStatus.INDEX_DELETED
enums.FileStatus.INDEX_RENAMED
enums.FileStatus.INDEX_TYPECHANGE
enums.FileStatus.WT_NEW
enums.FileStatus.WT_MODIFIED
enums.FileStatus.WT_DELETED
enums.FileStatus.WT_TYPECHANGE
enums.FileStatus.WT_RENAMED
enums.FileStatus.WT_UNREADABLE
enums.FileStatus.IGNORED
enums.FileStatus.CONFLICTED

A combination of these values will be returned to indicate the status of a file. Status compares the working directory, the index, and the current HEAD of the repository. The INDEX_… set of flags represents the status of file in the index relative to the HEAD, and the WT_… set of flags represents the status of the file in the working directory relative to the index.

Checkout

Repository.checkout(refname=None, **kwargs)

Checkout the given reference using the given strategy, and update the HEAD. The reference may be a reference name or a Reference object. The default strategy is SAFE | RECREATE_MISSING.

If no reference is given, checkout from the index.

Parameters:

refnamestr or Reference

The reference to checkout. After checkout, the current branch will be switched to this one.

strategyCheckoutStrategy

A CheckoutStrategy value. The default is SAFE | RECREATE_MISSING.

directorystr

Alternative checkout path to workdir.

pathslist[str]

A list of files to checkout from the given reference. If paths is provided, HEAD will not be set to the reference.

callbacksCheckoutCallbacks

Optional. Supply a callbacks object to get information about conflicted files, updated files, etc. as the checkout is being performed. The callbacks can also abort the checkout prematurely.

The callbacks should be an object which inherits from pyclass:CheckoutCallbacks. It should implement the callbacks as overridden methods.

Examples:

  • To checkout from the HEAD, just pass ‘HEAD’:

    >>> checkout('HEAD')
    

    This is identical to calling checkout_head().

Lower level API:

Repository.checkout_head(**kwargs)

Checkout HEAD

For arguments, see Repository.checkout().

Repository.checkout_tree(treeish, **kwargs)

Checkout the given treeish

For arguments, see Repository.checkout().

Repository.checkout_index(index=None, **kwargs)

Checkout the given index or the repository’s index

For arguments, see Repository.checkout().

Stash

Repository.stash(stasher: Signature, message: str | None = None, keep_index: bool = False, include_untracked: bool = False, include_ignored: bool = False, keep_all: bool = False, paths: List[str] | None = None)

Save changes to the working directory to the stash.

Returns: The Oid of the stash merge commit (Oid).

Parameters:

stasherSignature

The identity of the person doing the stashing.

messagestr

An optional description of stashed state.

keep_indexbool

Leave changes already added to the index in the working directory.

include_untrackedbool

Also stash untracked files.

include_ignoredbool

Also stash ignored files.

keep_allbool

All changes in the index and working directory are left intact.

pathslist[str]

An optional list of paths that control which files are stashed.

Example:

>>> repo = pygit2.Repository('.')
>>> repo.stash(repo.default_signature(), 'WIP: stashing')
Repository.stash_apply(index=0, **kwargs)

Apply a stashed state in the stash list to the working directory.

Parameters:

indexint

The position within the stash list of the stash to apply. 0 is the most recent stash.

reinstate_indexbool

Try to reinstate stashed changes to the index.

callbacksStashApplyCallbacks

Optional. Supply a callbacks object to get information about the progress of the stash application as it is being performed.

The callbacks should be an object which inherits from pyclass:StashApplyCallbacks. It should implement the callbacks as overridden methods.

Note that this class inherits from CheckoutCallbacks, so you can also get information from the checkout part of the unstashing process via the callbacks.

The checkout options may be customized using the same arguments taken by Repository.checkout().

Example:

>>> repo = pygit2.Repository('.')
>>> repo.stash(repo.default_signature(), 'WIP: stashing')
>>> repo.stash_apply(strategy=CheckoutStrategy.ALLOW_CONFLICTS)
Repository.stash_drop(index=0)

Remove a stashed state from the stash list.

Parameters:

indexint

The position within the stash list of the stash to remove. 0 is the most recent stash.

Repository.stash_pop(index=0, **kwargs)

Apply a stashed state and remove it from the stash list.

For arguments, see Repository.stash_apply().

Repository.listall_stashes() list[Stash]

Return a list with all stashed commits in the repository.