or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced.mdauth.mdconfig.mddiff.mdindex.mdobjects.mdreferences.mdremotes.mdrepository.mdstaging.md
tile.json

tessl/pypi-pygit2

Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pygit2@1.18.x

To install, run

npx @tessl/cli install tessl/pypi-pygit2@1.18.0

index.mddocs/

pygit2

Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality. pygit2 enables programmatic Git operations including repository management, object manipulation, branching, merging, remote operations, and configuration management through both high-level Python APIs and low-level libgit2 bindings.

Package Information

  • Package Name: pygit2
  • Language: Python
  • Installation: pip install pygit2
  • Documentation: https://www.pygit2.org/
  • Version: 1.18.2
  • libgit2 Version: Available via pygit2.LIBGIT2_VERSION
  • Features: Thread safety, HTTPS, SSH support - check via pygit2.features

Core Imports

import pygit2

Common specific imports:

from pygit2 import Repository, init_repository, clone_repository, discover_repository
from pygit2 import Commit, Tree, Blob, Tag, Reference, Branch, Walker
from pygit2 import Signature, Oid, Note, RevSpec, TreeBuilder
from pygit2 import Config, Index, Remote, Diff, settings

Basic Usage

import pygit2

# Initialize a new repository
repo = pygit2.init_repository('/path/to/repo')

# Open an existing repository
repo = pygit2.Repository('/path/to/existing/repo')

# Clone a repository
repo = pygit2.clone_repository('https://github.com/user/repo.git', '/local/path')

# Create a signature for commits
signature = pygit2.Signature('Author Name', 'author@example.com')

# Get repository status
status = repo.status()
for filepath, flags in status.items():
    print(f"{filepath}: {flags}")

# Stage files and create commit
repo.index.add_all()
repo.index.write()
tree = repo.index.write_tree()
commit = repo.create_commit(
    'HEAD',
    signature,
    signature, 
    'Commit message',
    tree,
    [repo.head.target]
)

Architecture

pygit2 provides a layered architecture:

  • High-level Python API: Pythonic wrappers for common Git operations
  • Low-level libgit2 bindings: Direct access to libgit2 C library functions via CFFI
  • Git Objects: Object-oriented representation of Git entities (Repository, Commit, Tree, Blob, etc.)
  • Collections: Iterator-based access to branches, references, remotes, and other collections
  • Callbacks: Event handling for remote operations, checkout, and other interactive processes

This design enables both simple high-level operations and fine-grained control over Git repository manipulation.

Capabilities

Repository Management

Core repository operations including initialization, opening, cloning, and basic repository information access. Provides the foundation for all Git operations.

def init_repository(path: str, bare: bool = False, **kwargs) -> Repository: ...
def clone_repository(url: str, path: str, **kwargs) -> Repository: ...
def discover_repository(path: str) -> str: ...

class Repository:
    def __init__(self, path: str): ...
    @property
    def workdir(self) -> str: ...
    @property
    def path(self) -> str: ...
    @property
    def is_bare(self) -> bool: ...
    @property
    def is_empty(self) -> bool: ...
    @property
    def head(self) -> Reference: ...

Repository Management

Git Objects

Core Git object types including commits, trees, blobs, and tags. These represent the fundamental data structures in Git repositories.

class Object:
    @property
    def oid(self) -> Oid: ...
    @property
    def type(self) -> int: ...

class Commit(Object):
    @property
    def message(self) -> str: ...
    @property
    def author(self) -> Signature: ...
    @property
    def committer(self) -> Signature: ...
    @property
    def tree(self) -> Tree: ...
    @property
    def parents(self) -> list[Commit]: ...

class Tree(Object):
    def __getitem__(self, key: str) -> Object: ...
    def __iter__(self): ...

class Blob(Object):
    @property
    def data(self) -> bytes: ...
    @property
    def size(self) -> int: ...

Git Objects

History and Navigation

Git history traversal and revision parsing operations.

class Walker:
    """Commit history walker"""
    def push(self, oid: Oid): ...
    def hide(self, oid: Oid): ...
    def sort(self, sort_mode: int): ...
    def __iter__(self): ...

class RevSpec:
    """Revision specification parsing result"""
    @property
    def from_object(self) -> Object: ...
    @property
    def to_object(self) -> Object: ...
    @property
    def flags(self) -> int: ...

Git Notes

Git notes operations for attaching metadata to objects.

class Note:
    """Git note object"""
    @property
    def oid(self) -> Oid: ...
    @property
    def annotated_id(self) -> Oid: ...
    @property
    def message(self) -> str: ...

Working Directory and Worktrees

Extended working directory and worktree management.

class Worktree:
    """Git worktree management"""
    @property
    def name(self) -> str: ...
    @property
    def path(self) -> str: ...
    @property
    def is_prunable(self) -> bool: ...
    def prune(self, **kwargs): ...

References and Branches

Git reference and branch management including creation, deletion, and iteration. Handles both local and remote references.

class Reference:
    @property
    def name(self) -> str: ...
    @property
    def target(self) -> Oid | str: ...
    @property
    def type(self) -> int: ...

class Branch(Reference):
    @property
    def branch_name(self) -> str: ...
    @property
    def upstream(self) -> Branch | None: ...
    @property
    def is_head(self) -> bool: ...

class References:
    def create(self, name: str, target: Oid | str) -> Reference: ...
    def delete(self, name: str): ...
    def __iter__(self): ...

References and Branches

Index and Staging

Git index (staging area) operations for preparing commits. Handles file staging, unstaging, and conflict resolution.

class Index:
    def add(self, path: str): ...
    def add_all(self, pathspecs: list[str] = None): ...
    def remove(self, path: str): ...
    def write(self): ...
    def write_tree(self) -> Oid: ...
    @property
    def conflicts(self) -> ConflictCollection: ...

class IndexEntry:
    @property
    def path(self) -> str: ...
    @property
    def oid(self) -> Oid: ...
    @property
    def mode(self) -> int: ...

Index and Staging

Diff and Patches

Difference analysis between Git objects, working directory, and index. Provides detailed change information and patch generation.

class Diff:
    @property
    def deltas(self) -> list[DiffDelta]: ...
    @property
    def stats(self) -> DiffStats: ...
    def patch(self) -> str: ...
    def find_similar(self, **kwargs): ...

class DiffDelta:
    @property
    def old_file(self) -> DiffFile: ...
    @property
    def new_file(self) -> DiffFile: ...
    @property
    def status(self) -> int: ...

class Patch:
    @property
    def delta(self) -> DiffDelta: ...
    @property
    def hunks(self) -> list[DiffHunk]: ...

Diff and Patches

Remote Operations

Git remote repository operations including fetching, pushing, and remote management. Handles authentication and transfer progress.

class Remote:
    @property
    def name(self) -> str: ...
    @property
    def url(self) -> str: ...
    def fetch(self, refspecs: list[str] = None, **kwargs): ...
    def push(self, refspecs: list[str], **kwargs): ...
    def ls_remotes(self) -> list[RemoteHead]: ...

class RemoteCallbacks:
    def credentials(self, url: str, username_from_url: str, allowed_types: int): ...
    def progress(self, stats: TransferProgress): ...
    def push_update_reference(self, refname: str, message: str): ...

Remote Operations

Configuration

Git configuration management for repository, global, and system settings. Provides type-safe access to Git configuration values.

class Config:
    def __getitem__(self, key: str): ...
    def __setitem__(self, key: str, value): ...
    def __delitem__(self, key: str): ...
    def get_bool(self, key: str) -> bool: ...
    def get_int(self, key: str) -> int: ...
    def get_multivar(self, key: str) -> list[str]: ...

class ConfigEntry:
    @property
    def name(self) -> str: ...
    @property
    def value(self) -> str: ...
    @property
    def level(self) -> int: ...

Configuration

Authentication

Credential management for Git operations supporting various authentication methods including SSH keys, username/password, and SSH agent.

class Username:
    def __init__(self, username: str): ...

class UserPass:
    def __init__(self, username: str, password: str): ...

class Keypair:
    def __init__(self, username: str, pubkey_path: str, privkey_path: str, passphrase: str = ''): ...

class KeypairFromAgent:
    def __init__(self, username: str): ...

class KeypairFromMemory:
    def __init__(self, username: str, pubkey_data: str, privkey_data: str, passphrase: str = ''): ...

Authentication

Advanced Operations

Advanced Git operations including blame, stashing, submodules, filtering, and object database access.

class Blame:
    @property
    def hunks(self) -> list[BlameHunk]: ...

class Stash:
    def save(self, message: str, **kwargs) -> Oid: ...
    def apply(self, index: int, **kwargs): ...
    def drop(self, index: int): ...

class Submodule:
    @property
    def name(self) -> str: ...
    @property
    def path(self) -> str: ...
    @property
    def url(self) -> str: ...
    def update(self, **kwargs): ...

Advanced Operations

Utility Functions

Core utility functions for repository discovery, hashing, and data conversion operations.

def discover_repository(path: str) -> str:
    """Find repository path containing the given path"""

def hash(data: bytes) -> Oid:
    """Calculate SHA-1 hash of data"""

def hashfile(path: str) -> Oid:
    """Calculate SHA-1 hash of file"""

def reference_is_valid_name(name: str) -> bool:
    """Check if reference name is valid"""

def to_bytes(text: str) -> bytes:
    """Convert string to bytes"""

def to_str(data: bytes) -> str:
    """Convert bytes to string"""

Version and Feature Information

Access to library version information and feature flags.

__version__: str  # pygit2 version
LIBGIT2_VERSION: str  # libgit2 version string
LIBGIT2_VER: tuple[int, int, int]  # libgit2 version tuple
LIBGIT2_VER_MAJOR: int
LIBGIT2_VER_MINOR: int
LIBGIT2_VER_REVISION: int

class Features:
    """Feature flags for compiled capabilities"""
    THREADS: int
    HTTPS: int
    SSH: int
    NSEC: int

features: Features  # Global features instance

Global Settings

Global library configuration and settings management.

class Settings:
    def __getitem__(self, key: str): ...
    def __setitem__(self, key: str, value): ...
    
settings: Settings  # Global settings instance

Modern Enums API

Type-safe enumeration values for Git operations (preferred over legacy constants).

from pygit2 import enums

# Repository operations
enums.RepositoryInitFlag
enums.RepositoryOpenFlag
enums.RepositoryState

# Object types
enums.ObjectType
enums.FileMode

# Diff operations
enums.DiffOption
enums.DiffFind
enums.DeltaStatus

# Merge operations  
enums.MergeAnalysis
enums.MergePreference

# Branch operations
enums.BranchType
enums.ReferenceType

# And many more...

Error Handling

pygit2 operations can raise various exceptions for error conditions. All Git-related errors inherit from GitError.

class GitError(Exception):
    """Base class for all Git-related errors"""

class AlreadyExistsError(GitError):
    """Raised when trying to create an object that already exists"""

class InvalidSpecError(GitError):
    """Raised when a revision specification is invalid"""

Types

class Oid:
    def __init__(self, raw_bytes: bytes | str): ...
    @property
    def hex(self) -> str: ...
    @property
    def raw(self) -> bytes: ...

class Signature:
    def __init__(self, name: str, email: str, time: int = None, offset: int = None): ...
    @property
    def name(self) -> str: ...
    @property
    def email(self) -> str: ...
    @property
    def time(self) -> int: ...
    @property
    def offset(self) -> int: ...

class Settings:
    def __getitem__(self, key: str): ...
    def __setitem__(self, key: str, value): ...