The repository

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

Functions

  • pygit2.initrepository(_path, bare=False, flags=16, mode=0, workdir_path=None, description=None, template_path=None, initial_head=None, origin_url=None)
  • Creates a new Git repository in the given path.

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

The flags may be a combination of:

  • GITREPOSITORY_INIT_BARE (overriden by the _bare parameter)
  • GIT_REPOSITORY_INIT_NO_REINIT
  • GIT_REPOSITORY_INIT_NO_DOTGIT_DIR
  • GIT_REPOSITORY_INIT_MKDIR
  • GIT_REPOSITORY_INIT_MKPATH (set by default)
  • GITREPOSITORY_INIT_EXTERNAL_TEMPLATE
    The _mode
    parameter may be any of GIT_REPOSITORY_SHARED_UMASK (default),GIT_REPOSITORY_SHARED_GROUP or GIT_REPOSITORY_INIT_SHARED_ALL, or a customvalue.

The workdir_path, description, template_path, initial_head andorigin_url are all strings.

See libgit2’s documentation on git_repository_init_ext for further details.

Example:

  1. >>> from pygit2 import init_repository
  2. >>> repo = init_repository('test') # Creates a non-bare repository
  3. >>> repo = init_repository('test', bare=True) # Creates a bare repository
  • pygit2.clonerepository(_url, path, bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)
  • Clones a new Git repository from url in the given path.

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

Parameters:

  • url :str
  • URL of the repository to clone.
  • path :str
  • Local path to clone into.
  • bare :bool
  • Whether the local repository should be bare.
  • remote :callable
  • Callback for the remote to use.

The remote callback has (Repository, name, url) -> Remote as asignature. The Remote it returns will be used instead of the defaultone.

  • repository :callable
  • Callback for the repository to use.

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

  • checkout_branch :str
  • Branch to checkout after the clone. The default is to use the remote’sdefault branch.
  • callbacks :RemoteCallbacks
  • Object which implements the callbacks as methods.

The callbacks should be an object which inherits frompyclass:RemoteCallbacks.

Example:

  1. >>> from pygit2 import clone_repository
  2. >>> repo_url = 'git://github.com/libgit2/pygit2.git'
  3. >>> repo_path = '/path/to/create/repository'
  4. >>> repo = clone_repository(repo_url, repo_path) # Clones a non-bare repository
  5. >>> repo = clone_repository(repo_url, repo_path, bare=True) # Clones a bare repository
  • pygit2.discoverrepository(_path[, across_fs[, ceiling_dirs]]) → str
  • Look for a git repository and return its path. If not found returns None.

Example:

  1. >>> current_working_directory = os.getcwd()
  2. >>> repository_path = discover_repository(current_working_directory)
  3. >>> repo = Repository(repository_path)

The Repository class

  • class pygit2.Repository(path)
  • The Repository constructor only takes one argument, the path of therepository to open.

Example:

  1. >>> from pygit2 import Repository
  2. >>> repo = Repository('pygit2/.git')

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

Below there are some general attributes and methods:

  • Repository.path
  • The normalized path to the git repository.

  • Repository.workdir

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

  • Repository.is_bare

  • Check if a repository is a bare repository.

  • Repository.is_empty

  • Check if a repository is empty.

  • Repository.default_signature

  • Return the signature according to the repository’s configuration

  • Repository.apply(id)

  • Applies the given id into HEAD.

Applies a diff into HEAD, writing the results into theworking directory.

  • Repository.aheadbehind(_local, upstream)
  • Calculate how many different commits are in the non-common parts of thehistory between the two given ids.

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

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

Parameters:

  • local
  • The commit which is considered the local or current state.
  • upstream
  • The commit which is considered the upstream.
    • Repository.createreference(_name, target, force=False)
    • Create a new reference “name” which points to an object or toanother reference.

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

Keyword arguments:

  • force
  • If True references will be overridden, otherwise (the default) anexception is raised.
    Examples:
  1. repo.create_reference('refs/heads/foo', repo.head.target)
  2. repo.create_reference('refs/tags/foo', 'refs/heads/master')
  3. repo.create_reference('refs/tags/foo', 'bbb78a9cec580')
  • Repository.descendantof(_oid, 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.

  • Repository.describe(committish=None, max_candidates_tags=None, describe_strategy=None, 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:

  • committish :str, Reference, or Commit
  • Commit-ish object or object name to describe, or None to describethe current working tree.
  • max_candidates_tags :int
  • The number of candidate tags to consider. Increasing above 10 willtake slightly longer but may produce a more accurate result. Avalue of 0 will cause only exact matches to be output.
  • describe_strategy :int
  • Can be one of:

    • GIT_DESCRIBE_DEFAULT - Only match annotated tags. (This isequivalent to setting this parameter to None.)
    • GIT_DESCRIBE_TAGS - Match everything under refs/tags/(includes lightweight tags).
    • GIT_DESCRIBE_ALL - Match everything under refs/ (includesbranches).
  • pattern :str
  • Only consider tags matching the given glob(7) pattern, excludingthe “refs/tags/” prefix.
  • only_follow_first_parent :bool
  • Follow only the first parent commit upon seeing a merge commit.
  • show_commit_oid_as_fallback :bool
  • Show uniquely abbreviated commit object as fallback.
  • abbreviated_size :int
  • The minimum number of hexadecimal digits to show for abbreviatedobject names. A value of 0 will suppress long format, only showingthe closest tag.
  • always_use_long_format :bool
  • Always output the long format (the nearest tag, the number ofcommits, and the abbrevated commit name) even when the committishmatches a tag.
  • dirty_suffix :str
  • A string to append if the working tree is dirty.
    Example:
  1. repo.describe(pattern='public/*', dirty_suffix='-dirty')
  • Repository.free()
  • Releases handles to the Git database without deallocating the repository.

  • Repository.path_is_ignored()

  • Check if a path is ignored in the repository.

  • Repository.read(oid) → type, data, size

  • Read raw object data from the repository.

  • Repository.reset(oid, reset_type)

  • Resets the current head.

Parameters:

  • oid
  • The oid of the commit to reset to.
  • reset_type
    • GIT_RESET_SOFT: resets head to point to oid, but does not modifyworking copy, and leaves the changes in the index.
    • GIT_RESET_MIXED: resets head to point to oid, but does not modifyworking copy. It empties the index too.
    • GIT_RESET_HARD: resets head to point to oid, and resets too theworking copy and the content of the index.
    • Repository.revertcommit(_revert_commit, our_commit, mainline=0)
    • Reverts the given Commit against the given “our” Commit, producing anIndex 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).
    • Repository.state_cleanup()
    • Remove all the metadata associated with an ongoing command likemerge, revert, cherry-pick, etc. For example: MERGE_HEAD, MERGE_MSG,etc.
  • Repository.write(type, data) → Oid
  • Write raw object data into the repository. First arg is the objecttype, the second one a buffer with data. Return the Oid of the createdobject.

  • Repository.writearchive(_treeish, archive, timestamp=None, prefix='')

  • Write treeish into an archive.

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

All path names in the archive are added to ‘prefix’, which defaults toan 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:
  1. >>> import tarfile, pygit2
  2. >>>> with tarfile.open('foo.tar', 'w') as archive:
  3. >>>> repo = pygit2.Repository('.')
  4. >>>> repo.write_archive(repo.head.target, archive)