pygit2

1.19.2 · active · verified Thu Apr 09

pygit2 is a set of Python bindings for libgit2, a portable, pure C implementation of the Git core methods. It provides a low-level, plumbing-focused API for interacting with Git repositories. The library is actively maintained, with version 1.19.2 being the latest as of March 2026, and typically sees multiple minor releases per year, often in sync with libgit2 updates and bug fixes. It supports Python versions 3.11 through 3.14, and PyPy3 7.3+.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a new Git repository, create a file, add it to the index, and make the first commit using pygit2. It also includes cleanup of the temporary repository directory.

import pygit2
import os
import shutil
import tempfile
from pygit2 import enums

def create_and_commit_repo():
    # Create a temporary directory for the repository
    repo_path = tempfile.mkdtemp()
    print(f"Creating repository at: {repo_path}")

    try:
        # Initialize a new bare repository
        # For a non-bare repo with a working directory, use `bare=False`
        repo = pygit2.init_repository(repo_path, bare=False)

        # Configure author and committer details
        author = pygit2.Signature("Test User", "test@example.com")
        committer = pygit2.Signature("Test User", "test@example.com")

        # Create a file in the working directory
        file_path = os.path.join(repo_path, "README.md")
        with open(file_path, "w") as f:
            f.write("# My New Repository\n\nThis is a test repository.")

        # Add the file to the index
        repo.index.add("README.md")
        repo.index.write()

        # Create a tree from the index
        tree = repo.index.write_tree()

        # Create the initial commit
        # For an initial commit, the parents list is empty, and HEAD is used
        commit_id = repo.create_commit(
            'HEAD',              # Reference to update
            author,              # Author signature
            committer,           # Committer signature
            'Initial commit',    # Commit message
            tree,                # Tree object for the commit
            []                   # Parent commits (empty for initial commit)
        )

        print(f"Initial commit created with ID: {commit_id}")

        # Checkout the branch to populate the working directory
        repo.checkout('refs/heads/main') # Or 'refs/heads/master' depending on default branch
        print(f"Repository content in working directory: {os.listdir(repo_path)}")

    finally:
        # Clean up the temporary directory
        shutil.rmtree(repo_path)
        print(f"Cleaned up repository at: {repo_path}")

if __name__ == "__main__":
    create_and_commit_repo()

view raw JSON →