Python bindings for libgit2 providing comprehensive Git repository operations and version control functionality.
—
Core repository operations including initialization, opening, cloning, and basic repository information access. Provides the foundation for all Git operations through the Repository class and related functions.
Initialize new repositories, clone existing repositories, or open local repositories. These functions provide the primary entry points for Git operations.
def init_repository(
path: str,
bare: bool = False,
flags: int = None,
mode: int = None,
workdir_path: str = None,
description: str = None,
template_path: str = None,
initial_head: str = None,
origin_url: str = None
) -> Repository:
"""
Create a new Git repository.
Parameters:
- path: Path where repository should be created
- bare: Create bare repository without working directory
- flags: Repository initialization flags
- mode: File permissions mode
- workdir_path: Path to working directory (bare repos only)
- description: Repository description
- template_path: Template directory path
- initial_head: Name of initial branch
- origin_url: URL of origin remote
Returns:
Repository object
"""
def clone_repository(
url: str,
path: str,
bare: bool = False,
repository: callable = None,
remote: callable = None,
checkout_branch: str = None,
callbacks: 'RemoteCallbacks' = None,
depth: int = 0,
proxy: bool | str = None
) -> Repository:
"""
Clone a remote repository.
Parameters:
- url: URL of repository to clone
- path: Local path for cloned repository
- bare: Create bare clone
- repository: Repository creation callback
- remote: Remote creation callback
- checkout_branch: Branch to checkout after clone
- callbacks: Remote operation callbacks
- depth: Shallow clone depth (0 = full history)
- proxy: Proxy configuration
Returns:
Repository object
"""
def discover_repository(path: str) -> str:
"""
Find the path of the Git repository containing the given path.
Parameters:
- path: Starting path for repository search
Returns:
Path to .git directory
"""The main interface for Git repository operations, providing access to all repository components and metadata.
class Repository:
def __init__(self, path: str):
"""
Open existing Git repository.
Parameters:
- path: Path to repository or .git directory
"""
# Repository Properties
@property
def path(self) -> str:
"""Path to .git directory"""
@property
def workdir(self) -> str:
"""Path to working directory (None for bare repos)"""
@property
def is_bare(self) -> bool:
"""True if repository is bare"""
@property
def is_empty(self) -> bool:
"""True if repository has no commits"""
@property
def is_shallow(self) -> bool:
"""True if repository is shallow clone"""
@property
def head(self) -> Reference:
"""Reference to current HEAD"""
@property
def head_is_unborn(self) -> bool:
"""True if HEAD points to unborn branch"""
@property
def head_is_detached(self) -> bool:
"""True if HEAD is detached"""
# Repository Collections
@property
def references(self) -> References:
"""Repository references collection"""
@property
def branches(self) -> Branches:
"""Repository branches collection"""
@property
def remotes(self) -> RemoteCollection:
"""Repository remotes collection"""
@property
def config(self) -> Config:
"""Repository configuration"""
@property
def index(self) -> Index:
"""Repository index (staging area)"""
@property
def odb(self) -> Odb:
"""Object database"""
# Repository State
@property
def state(self) -> int:
"""Current repository state (merge, rebase, etc.)"""
def state_cleanup(self):
"""Clean up repository state after operations"""
# Object Access
def __getitem__(self, oid: str | Oid) -> Object:
"""Get object by OID"""
def __contains__(self, oid: str | Oid) -> bool:
"""Check if object exists in repository"""
def get(self, oid: str | Oid, default=None) -> Object:
"""Get object by OID with default"""
def revparse_single(self, revision: str) -> Object:
"""Parse revision string to single object"""
def revparse(self, revision: str) -> RevSpec:
"""Parse revision string"""
# Object Creation
def create_blob(self, data: bytes) -> Oid:
"""Create blob object from data"""
def create_blob_fromworkdir(self, path: str) -> Oid:
"""Create blob from working directory file"""
def create_blob_fromdisk(self, path: str) -> Oid:
"""Create blob from disk file"""
def create_blob_fromiobase(self, file: 'IO') -> Oid:
"""Create blob from IO stream"""
def create_tree(self, tree_builder: TreeBuilder) -> Oid:
"""Create tree object"""
def create_commit(
self,
update_ref: str,
author: Signature,
committer: Signature,
message: str,
tree: Oid,
parents: list[Oid]
) -> Oid:
"""Create commit object"""
def create_tag(
self,
name: str,
target: Oid,
tagger: Signature,
message: str,
force: bool = False
) -> Oid:
"""Create tag object"""
def create_branch(
self,
name: str,
commit: Commit,
force: bool = False
) -> Branch:
"""Create new branch"""
def create_reference_direct(
self,
name: str,
target: Oid,
force: bool = False,
message: str = None
) -> Reference:
"""Create direct reference"""
def create_reference_symbolic(
self,
name: str,
target: str,
force: bool = False,
message: str = None
) -> Reference:
"""Create symbolic reference"""
# Working Directory Operations
def status(self) -> dict[str, int]:
"""Get working directory status"""
def status_file(self, path: str) -> int:
"""Get status of single file"""
def checkout_head(self, **kwargs):
"""Checkout HEAD to working directory"""
def checkout_tree(self, treeish: Object, **kwargs):
"""Checkout tree to working directory"""
def checkout_index(self, **kwargs):
"""Checkout index to working directory"""
def reset(self, oid: Oid, reset_type: int):
"""Reset repository to commit"""
# Diff Operations
def diff(
self,
a: Object | str = None,
b: Object | str = None,
cached: bool = False,
**kwargs
) -> Diff:
"""Create diff between objects/trees"""
# Merge Operations
def merge_analysis(self, their_heads: list[Oid]) -> tuple[int, int]:
"""Analyze merge possibility"""
def merge(self, oid: Oid, **kwargs):
"""Perform merge operation"""
def merge_commits(self, our_commit: Oid, their_commit: Oid) -> Index:
"""Merge two commits"""
def merge_trees(
self,
ancestor: Oid,
ours: Oid,
theirs: Oid
) -> Index:
"""Merge three trees"""
# Search and History
def walk(self, oid: Oid, sort: int = None) -> Walker:
"""Create commit walker"""
def ahead_behind(self, local: Oid, upstream: Oid) -> tuple[int, int]:
"""Count commits ahead/behind"""
def descendant_of(self, commit: Oid, ancestor: Oid) -> bool:
"""Check if commit is descendant of ancestor"""
# Advanced Operations
def blame(
self,
path: str,
flags: int = None,
min_match_characters: int = None,
newest_commit: Oid = None,
oldest_commit: Oid = None,
min_line: int = None,
max_line: int = None
) -> Blame:
"""Generate blame information for file"""
def cherry_pick(self, commit: Oid, **kwargs):
"""Cherry-pick commit"""
def revert(self, commit: Oid, **kwargs):
"""Revert commit"""
def apply(self, diff: Diff, location: int = None):
"""Apply diff/patch"""# Repository State Constants
GIT_REPOSITORY_STATE_NONE: int
GIT_REPOSITORY_STATE_MERGE: int
GIT_REPOSITORY_STATE_REVERT: int
GIT_REPOSITORY_STATE_REBASE: int
GIT_REPOSITORY_STATE_BISECT: int
GIT_REPOSITORY_STATE_CHERRYPICK: int
GIT_REPOSITORY_STATE_APPLY_MAILBOX: int
# Reset Types
GIT_RESET_SOFT: int # Move HEAD only
GIT_RESET_MIXED: int # Move HEAD and index
GIT_RESET_HARD: int # Move HEAD, index, and working dirimport pygit2
# Initialize new repository
repo = pygit2.init_repository('/path/to/new/repo')
# Open existing repository
repo = pygit2.Repository('/path/to/existing/repo')
# Clone repository
repo = pygit2.clone_repository(
'https://github.com/user/repo.git',
'/local/clone/path',
callbacks=pygit2.RemoteCallbacks()
)
# Check repository properties
print(f"Repository path: {repo.path}")
print(f"Working directory: {repo.workdir}")
print(f"Is bare: {repo.is_bare}")
print(f"Is empty: {repo.is_empty}")# Get objects by OID
commit = repo[repo.head.target]
tree = repo[commit.tree]
# Create new blob
blob_oid = repo.create_blob(b"Hello, World!")
# Create signature
signature = pygit2.Signature('Author', 'author@example.com')
# Create commit
tree_oid = repo.index.write_tree()
commit_oid = repo.create_commit(
'HEAD',
signature,
signature,
'Commit message',
tree_oid,
[] # No parents for initial commit
)# Get repository status
status = repo.status()
for filepath, flags in status.items():
if flags & pygit2.GIT_STATUS_WT_NEW:
print(f"New file: {filepath}")
elif flags & pygit2.GIT_STATUS_WT_MODIFIED:
print(f"Modified file: {filepath}")
elif flags & pygit2.GIT_STATUS_WT_DELETED:
print(f"Deleted file: {filepath}")
# Check single file status
file_status = repo.status_file('README.md')
if file_status & pygit2.GIT_STATUS_WT_MODIFIED:
print("README.md is modified")Install with Tessl CLI
npx tessl i tessl/pypi-pygit2