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=[])

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, flags=0, context_lines=3, interhunk_lines=0)

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 GIT_DIFF_* constant.

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=0, context_lines=3, interhunk_lines=0)

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

Parameters:

flags

A GIT_DIFF_* constant.

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, mode)
__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

The id of the referenced object

mode

The mode of this entry, a GIT_FILEMODE_* value

path

The path of this entry

Status

class pygit2.Repository(path=None, flags=0)
status() {str: int}

Reads the status of the repository and returns a dictionary with file paths as keys and status flags as values. See pygit2.GIT_STATUS_*.

Example, inspect the status of the repository:

from pygit2 import GIT_STATUS_CURRENT
status = repo.status()
for filepath, flags in status.items():
    if flags != GIT_STATUS_CURRENT:
        print("Filepath %s isn't clean" % filepath)
status_file(path) int

Returns the status of the given file path.

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

GIT_STATUS_CURRENT
GIT_STATUS_INDEX_NEW
GIT_STATUS_INDEX_MODIFIED
GIT_STATUS_INDEX_DELETED
GIT_STATUS_INDEX_RENAMED
GIT_STATUS_INDEX_TYPECHANGE
GIT_STATUS_WT_NEW
GIT_STATUS_WT_MODIFIED
GIT_STATUS_WT_DELETED
GIT_STATUS_WT_TYPECHANGE
GIT_STATUS_WT_RENAMED
GIT_STATUS_WT_UNREADABLE
GIT_STATUS_IGNORED
GIT_STATUS_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 GIT_STATUS_INDEX set of flags represents the status of file in the index relative to the HEAD, and the GIT_STATUS_WT set of flags represent 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 GIT_CHECKOUT_SAFE | GIT_CHECKOUT_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.

strategyint

A GIT_CHECKOUT_ value. The default is GIT_CHECKOUT_SAFE.

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.

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, message=None, keep_index=False, include_untracked=False, include_ignored=False)

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.

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.

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=GIT_CHECKOUT_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().