Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality.
npx @tessl/cli install tessl/pypi-pygit2@1.18.0Python 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.
pip install pygit2pygit2.LIBGIT2_VERSIONpygit2.featuresimport pygit2Common 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, settingsimport 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]
)pygit2 provides a layered architecture:
This design enables both simple high-level operations and fine-grained control over Git repository manipulation.
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: ...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 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 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: ...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): ...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): ...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: ...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]: ...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): ...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: ...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 = ''): ...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): ...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"""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 instanceGlobal library configuration and settings management.
class Settings:
def __getitem__(self, key: str): ...
def __setitem__(self, key: str, value): ...
settings: Settings # Global settings instanceType-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...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"""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): ...