Repository

Everything starts either by creating a new repository, or by opening an existing one.

Functions

pygit2.init_repository(path: str | bytes | ~os.PathLike | None, bare: bool = False, flags: ~pygit2.enums.RepositoryInitFlag = <RepositoryInitFlag.MKPATH: 16>, mode: int | ~pygit2.enums.RepositoryInitMode = RepositoryInitMode.SHARED_UMASK, workdir_path: str | None = None, description: str | None = None, template_path: str | None = None, initial_head: str | None = None, origin_url: str | None = None) Repository

Creates a new Git repository in the given path.

If bare is True the repository will be bare, i.e. it will not have a working copy.

The flags may be a combination of enums.RepositoryInitFlag constants:

  • BARE (overriden by the bare parameter)

  • NO_REINIT

  • NO_DOTGIT_DIR

  • MKDIR

  • MKPATH (set by default)

  • EXTERNAL_TEMPLATE

The mode parameter may be any of the predefined modes in enums.RepositoryInitMode (SHARED_UMASK being the default), or a custom int.

The workdir_path, description, template_path, initial_head and origin_url are all strings.

See libgit2’s documentation on git_repository_init_ext for further details.

Example:

>>> from pygit2 import init_repository
>>> repo = init_repository('test')            # Creates a non-bare repository
>>> repo = init_repository('test', bare=True) # Creates a bare repository
pygit2.clone_repository(url, path, bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None, depth=0)

Clones a new Git repository from url in the given path.

Returns: a Repository class pointing to the newly cloned repository.

Parameters:

urlstr

URL of the repository to clone.

pathstr

Local path to clone into.

barebool

Whether the local repository should be bare.

remotecallable

Callback for the remote to use.

The remote callback has (Repository, name, url) -> Remote as a signature. The Remote it returns will be used instead of the default one.

repositorycallable

Callback for the repository to use.

The repository callback has (path, bare) -> Repository as a signature. The Repository it returns will be used instead of creating a new one.

checkout_branchstr

Branch to checkout after the clone. The default is to use the remote’s default branch.

callbacksRemoteCallbacks

Object which implements the callbacks as methods.

The callbacks should be an object which inherits from pyclass:RemoteCallbacks.

depthint

Number of commits to clone.

If greater than 0, creates a shallow clone with a history truncated to the specified number of commits. The default is 0 (full commit history).

Example:

>>> from pygit2 import clone_repository
>>> repo_url = 'git://github.com/libgit2/pygit2.git'
>>> repo_path = '/path/to/create/repository'
>>> repo = clone_repository(repo_url, repo_path) # Clones a non-bare repository
>>> repo = clone_repository(repo_url, repo_path, bare=True) # Clones a bare repository
pygit2.discover_repository(path: str, across_fs: bool = False[, ceiling_dirs: str]) str

Look for a git repository and return its path. If not found returns None.

Example:

>>> current_working_directory = os.getcwd()
>>> repository_path = discover_repository(current_working_directory)
>>> repo = Repository(repository_path)
pygit2.tree_entry_cmp(object, other)

tree_entry_cmp(a: Object, b: Object) -> int

Rich comparison for objects, only available when the objects have been obtained through a tree. The sort criteria is the one Git uses to sort tree entries in a tree object. This function wraps git_tree_entry_cmp.

Returns < 0 if a is before b, > 0 if a is after b, and 0 if a and b are the same.

The Repository class

The API of the Repository class is quite large. Since this documentation is organized by features, the related bits are explained in the related chapters, for instance the pygit2.Repository.checkout() method is explained in the Checkout section.

Below there are some general attributes and methods:

class pygit2.Repository(path: str | None = None, flags: ~pygit2.enums.RepositoryOpenFlag = <RepositoryOpenFlag.DEFAULT: 0>)

The Repository constructor will most commonly be called with one argument, the path of the repository to open.

Alternatively, constructing a repository with no arguments will create a repository with no backends. You can use this path to create repositories with custom backends. Note that most operations on the repository are considered invalid and may lead to undefined behavior if attempted before providing an odb and refdb via set_odb() and set_refdb().

Parameters:

path

The path to open — if not provided, the repository will have no backend.

flags

Flags controlling how to open the repository can optionally be provided — any combination of:

  • enums.RepositoryOpenFlag.NO_SEARCH

  • enums.RepositoryOpenFlag.CROSS_FS

  • enums.RepositoryOpenFlag.BARE

  • enums.RepositoryOpenFlag.NO_DOTGIT

  • enums.RepositoryOpenFlag.FROM_ENV

Example:

>>> from pygit2 import Repository
>>> repo = Repository('pygit2/.git')
ahead_behind(local, upstream)

Calculate how many different commits are in the non-common parts of the history between the two given ids.

Ahead is how many commits are in the ancestry of the local commit which are not in the upstream commit. Behind is the opposite.

Returns: a tuple of two integers with the number of commits ahead and behind respectively.

Parameters:

local

The commit which is considered the local or current state.

upstream

The commit which is considered the upstream.

amend_commit(commit, refname, author=None, committer=None, message=None, tree=None, encoding='UTF-8')

Amend an existing commit by replacing only explicitly passed values, return the rewritten commit’s oid.

This creates a new commit that is exactly the same as the old commit, except that any explicitly passed values will be updated. The new commit has the same parents as the old commit.

You may omit the author, committer, message, tree, and encoding parameters, in which case this will use the values from the original commit.

Parameters:

commitCommit, Oid, or str

The commit to amend.

refnameReference or str

If not None, name of the reference that will be updated to point to the newly rewritten commit. Use “HEAD” to update the HEAD of the current branch and make it point to the rewritten commit. If you want to amend a commit that is not currently the tip of the branch and then rewrite the following commits to reach a ref, pass this as None and update the rest of the commit chain and ref separately.

authorSignature

If not None, replace the old commit’s author signature with this one.

committerSignature

If not None, replace the old commit’s committer signature with this one.

messagestr

If not None, replace the old commit’s message with this one.

treeTree, Oid, or str

If not None, replace the old commit’s tree with this one.

encodingstr

Optional encoding for message.

applies(diff: Diff, location: int = GIT_APPLY_LOCATION_INDEX, raise_error: bool = False) bool

Tests if the given patch will apply to HEAD, without writing it.

Parameters:

diff

The Diff to apply.

location

The location to apply: GIT_APPLY_LOCATION_WORKDIR, GIT_APPLY_LOCATION_INDEX (default), or GIT_APPLY_LOCATION_BOTH.

raise_error

If the patch doesn’t apply, raise an exception containing more details about the failure instead of returning False.

apply(diff: Diff, location: ApplyLocation = ApplyLocation.WORKDIR)

Applies the given Diff object to HEAD, writing the results into the working directory, the index, or both.

Parameters:

diff

The Diff to apply.

location

The location to apply: ApplyLocation.WORKDIR (default), ApplyLocation.INDEX, or ApplyLocation.BOTH.

create_reference(name, target, force=False, message=None)

Create a new reference “name” which points to an object or to another reference.

Based on the type and value of the target parameter, this method tries to guess whether it is a direct or a symbolic reference.

Keyword arguments:

force: bool

If True references will be overridden, otherwise (the default) an exception is raised.

message: str

Optional message to use for the reflog.

Examples:

repo.create_reference('refs/heads/foo', repo.head.target)
repo.create_reference('refs/tags/foo', 'refs/heads/master')
repo.create_reference('refs/tags/foo', 'bbb78a9cec580')
default_signature

Return the signature according to the repository’s configuration

descendant_of(oid1: Oid, oid2: Oid) bool

Determine if the first commit is a descendant of the second commit. Note that a commit is not considered a descendant of itself.

describe(committish=None, max_candidates_tags=None, describe_strategy: DescribeStrategy = DescribeStrategy.DEFAULT, pattern=None, only_follow_first_parent=None, show_commit_oid_as_fallback=None, abbreviated_size=None, always_use_long_format=None, dirty_suffix=None)

Describe a commit-ish or the current working tree.

Returns: The description (str).

Parameters:

committishstr, Reference, or Commit

Commit-ish object or object name to describe, or None to describe the current working tree.

max_candidates_tagsint

The number of candidate tags to consider. Increasing above 10 will take slightly longer but may produce a more accurate result. A value of 0 will cause only exact matches to be output.

describe_strategyDescribeStrategy

Can be one of:

  • DescribeStrategy.DEFAULT - Only match annotated tags.

  • DescribeStrategy.TAGS - Match everything under refs/tags/ (includes lightweight tags).

  • DescribeStrategy.ALL - Match everything under refs/ (includes branches).

patternstr

Only consider tags matching the given glob(7) pattern, excluding the “refs/tags/” prefix.

only_follow_first_parentbool

Follow only the first parent commit upon seeing a merge commit.

show_commit_oid_as_fallbackbool

Show uniquely abbreviated commit object as fallback.

abbreviated_sizeint

The minimum number of hexadecimal digits to show for abbreviated object names. A value of 0 will suppress long format, only showing the closest tag.

always_use_long_formatbool

Always output the long format (the nearest tag, the number of commits, and the abbrevated commit name) even when the committish matches a tag.

dirty_suffixstr

A string to append if the working tree is dirty.

Example:

repo.describe(pattern='public/*', dirty_suffix='-dirty')
free()

Releases handles to the Git database without deallocating the repository.

get_attr(path: str | bytes | ~os.PathLike, name: str | bytes, flags: ~pygit2.enums.AttrCheck = <AttrCheck.FILE_THEN_INDEX: 0>, commit: ~_pygit2.Oid | str | None = None) bool | None | str

Retrieve an attribute for a file by path.

Returns: a boolean, None if the value is unspecified, or string with the value of the attribute.

Parameters:

path

The path of the file to look up attributes for, relative to the workdir root.

name

The name of the attribute to look up.

flags

A combination of enums.AttrCheck flags which determine the lookup order.

commit

Optional id of commit to load attributes from when the INCLUDE_COMMIT flag is specified.

Examples:

>>> print(repo.get_attr('splash.bmp', 'binary'))
True
>>> print(repo.get_attr('splash.bmp', 'unknown-attr'))
None
>>> repo.get_attr('test.h', 'whitespace')
'tab-in-indent,trailing-space'
is_bare

Check if a repository is a bare repository.

is_empty

Check if a repository is empty.

is_shallow

Check if a repository is a shallow repository.

odb

Return the object database for this repository

path

The normalized path to the git repository.

path_is_ignored(path: str) bool

Check if a path is ignored in the repository.

reset(oid: Oid, reset_mode: enums.ResetMode)

Resets the current head.

Parameters:

oid

The oid of the commit to reset to.

reset_mode
  • SOFT: resets head to point to oid, but does not modify working copy, and leaves the changes in the index.

  • MIXED: resets head to point to oid, but does not modify working copy. It empties the index too.

  • HARD: resets head to point to oid, and resets too the working copy and the content of the index.

revert_commit(revert_commit, our_commit, mainline=0)

Revert the given Commit against the given “our” Commit, producing an Index that reflects the result of the revert.

Returns: an Index with the result of the revert.

Parameters:

revert_commit

The Commit to revert.

our_commit

The Commit to revert against (eg, HEAD).

mainline

The parent of the revert Commit, if it is a merge (i.e. 1, 2).

set_odb(odb: Odb)

Sets the object database for this repository. This is a low-level function, most users won’t need it.

set_refdb(refdb: Refdb)

Sets the reference database for this repository. This is a low-level function, most users won’t need it.

state_cleanup()

Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc. For example: MERGE_HEAD, MERGE_MSG, etc.

workdir

The normalized path to the working directory of the repository. If the repository is bare, None will be returned.

write(type, data) Oid

Write raw object data into the repository. First arg is the object type, the second one a buffer with data. Return the Oid of the created object.

write_archive(treeish, archive, timestamp=None, prefix='')

Write treeish into an archive.

If no timestamp is provided and ‘treeish’ is a commit, its committer timestamp will be used. Otherwise the current time will be used.

All path names in the archive are added to ‘prefix’, which defaults to an empty string.

Parameters:

treeish

The treeish to write.

archive

An archive from the ‘tarfile’ module.

timestamp

Timestamp to use for the files in the archive.

prefix

Extra prefix to add to the path names in the archive.

Example:

>>> import tarfile, pygit2
>>> with tarfile.open('foo.tar', 'w') as archive:
>>>     repo = pygit2.Repository('.')
>>>     repo.write_archive(repo.head.target, archive)

The Odb class

class pygit2.Odb

Object database.

add_backend(backend: OdbBackend, priority: int)

Adds an OdbBackend to the list of backends for this object database.

add_disk_alternate(path: str)

Adds a path on disk as an alternate backend for objects. Alternate backends are checked for objects only after the main backends are checked. Writing is disabled on alternate backends.

backends

Return an iterable of backends for this object database.

exists(oid: Oid) bool

Returns true if the given oid can be found in this odb.

read(oid) type, data, size

Read raw object data from the object db.

write(type: int, data: bytes) Oid

Write raw object data into the object db. First arg is the object type, the second one a buffer with data. Return the Oid of the created object.

The Refdb class

class pygit2.Refdb

Reference database.

compress()

Suggests that the given refdb compress or optimize its references. This mechanism is implementation specific. For on-disk reference databases, for example, this may pack all loose references.

static new(repo: Repository) Refdb

Creates a new refdb with no backend.

static open(repo: Repository) Refdb

Create a new reference database and automatically add the default backends, assuming the repository dir as the folder.

set_backend(backend: RefdbBackend)

Sets a custom RefdbBackend for this Refdb.