package documentation

Simple wrapper that provides porcelain-like functions on top of Dulwich.

Currently implemented:
  • am
  • apply_patch
  • archive
  • add
  • bisect{_start,_bad,_good,_skip,_reset,_log,_replay}
  • branch{_create,_delete,_list}
  • check_ignore
  • checkout
  • checkout_branch
  • clone
  • cone mode{_init, _set, _add}
  • commit
  • commit_tree
  • daemon
  • describe
  • diff_tree
  • fetch
  • filter_branch
  • for_each_ref
  • grep
  • init
  • interpret_trailers
  • ls_files
  • ls_remote
  • ls_tree
  • mailsplit
  • merge
  • merge_tree
  • mv/move
  • prune
  • pull
  • push
  • rm
  • remote{_add}
  • receive_pack
  • replace{_create,_delete,_list}
  • rerere{_status,_diff,_forget,_clear,_gc}
  • reset
  • revert
  • sparse_checkout
  • submodule_add
  • submodule_init
  • submodule_list
  • rev_list
  • tag{_create,_delete,_list}
  • upload_pack
  • update_server_info
  • var
  • write_commit_graph
  • status
  • shortlog
  • symbolic_ref
  • worktree{_add,_list,_remove,_prune,_lock,_unlock,_move}

These functions are meant to behave similarly to the git subcommands. Differences in behaviour are considered bugs.

Note: one of the consequences of this is that paths tend to be interpreted relative to the current working directory rather than relative to the repository root.

Functions should generally accept both unicode strings and bytestrings

Module lfs Porcelain functions for Git LFS support.
Module notes Porcelain-like interface for Git notes.
Module submodule Porcelain functions for working with submodules.
Module subtree Porcelain for git subtree operations.
Module tag Porcelain-like tag functions for Dulwich.
Module worktree Porcelain-like interface for Git worktrees.

From __init__.py:

Class CountObjectsResult Result of counting objects in a repository.
Class NoneStream Fallback if stdout or stderr are unavailable, does nothing.
Class TransportKwargs Keyword arguments accepted by get_transport_and_path.
Exception CheckoutError Indicates that a checkout cannot be performed.
Exception DivergedBranches Branches have diverged and fast-forward is not possible.
Exception Error Porcelain-based error.
Exception RemoteExists Raised when the remote already exists.
Exception TimezoneFormatError Raised when the timezone cannot be determined from a given string.
Function active_branch Return the active branch in the repository, if any.
Function add Add files to the staging area.
Function am Apply patches from mailbox-style email messages, creating commits.
Function am_abort Abort the current am and restore the original state.
Function am_continue Continue applying patches after resolving a conflict.
Function am_quit Quit the current am without reverting changes.
Function am_skip Skip the current patch and continue with remaining patches.
Function annotate Annotate the history of a file.
Function apply_patch Apply a patch to the working tree and/or index.
Function archive Create an archive.
Function bisect_bad Mark a commit as bad.
Function bisect_good Mark a commit as good.
Function bisect_log Get the bisect log.
Function bisect_replay Replay a bisect log.
Function bisect_reset Reset bisect state and return to original branch/commit.
Function bisect_skip Skip one or more commits.
Function bisect_start Start a new bisect session.
Function branch_create Create a branch.
Function branch_delete Delete a branch.
Function branch_list List all branches.
Function branch_remotes_list List the short names of all remote branches.
Function branches_containing List branches that contain the specified commit.
Function cat_file_content Get the raw content of a Git object.
Function cat_file_size Get the size of a Git object.
Function cat_file_type Get the type of a Git object.
Function check_diverged Check if updating to a sha can be done with fast forwarding.
Function check_ignore Debug gitignore files.
Function check_mailmap Check canonical name and email of contact.
Function checkout Switch to a branch or commit, updating both HEAD and the working tree.
Function cherry Find commits not merged upstream.
Function cherry_pick Cherry-pick a commit onto the current branch.
Function clean Remove any untracked files from the target directory recursively.
Function clone Clone a local or remote git repository.
Function commit Create a new commit.
Function commit_decode Decode commit contents using the commit's encoding or default.
Function commit_encode Encode commit contents using the commit's encoding or default.
Function commit_tree Create a new commit object.
Function cone_mode_add Add new directories to the existing 'cone-mode' sparse-checkout patterns.
Function cone_mode_disable Disable sparse checkout and restore all files.
Function cone_mode_init Initialize a repository to use sparse checkout in 'cone' mode.
Function cone_mode_list List current sparse-checkout patterns.
Function cone_mode_set Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
Function count_objects Count unpacked objects and their disk usage.
Function daemon Run a daemon serving Git requests over TCP/IP.
Function describe Describe the repository version.
Function diff Show diff.
Function diff_tree Compares the content and mode of blobs found via two tree objects.
Function fetch Fetch objects from a remote server.
Function filter_branch Rewrite branch history by creating new commits with filtered properties.
Function filter_branches_by_pattern Filter branches by fnmatch pattern.
Function find_unique_abbrev Find the shortest unique abbreviation for an object ID.
Function for_each_ref Iterate over all refs that match the (optional) pattern.
Function format_patch Generate patches suitable for git am.
Function fsck Check a repository.
Function gc Run garbage collection on a repository.
Function get_branch_merge Return the branch's merge reference (upstream branch), if any.
Function get_branch_remote Return the active branch's remote name, if any.
Function get_object_by_path Get an object by path.
Function get_remote_repo Get the remote repository information.
Function get_tree_changes Return add/delete/modify changes to tree by comparing index to HEAD.
Function get_untracked_paths Get untracked paths.
Function get_user_timezones Retrieve local timezone as described in git documentation.
Function grep Search for a pattern in tracked files.
Function hash_object Compute object ID and optionally write to object store.
Function independent_commits Filter commits to only those that are not reachable from others.
Function init Create a new git repository.
Function interpret_trailers Parse and manipulate trailers in a commit message.
Function is_ancestor Check if one commit is an ancestor of another.
Function is_interactive_rebase Check if an interactive rebase is in progress.
Function lfs_clean Clean a file by converting it to an LFS pointer.
Function lfs_fetch Fetch LFS objects from remote.
Function lfs_init Initialize Git LFS in a repository.
Function lfs_ls_files List files tracked by Git LFS.
Function lfs_migrate Migrate files to Git LFS.
Function lfs_pointer_check Check if files are valid LFS pointers.
Function lfs_pull Pull LFS objects for current checkout.
Function lfs_push Push LFS objects to remote.
Function lfs_smudge Smudge an LFS pointer by retrieving the actual content.
Function lfs_status Show status of LFS files.
Function lfs_track Track file patterns with Git LFS.
Function lfs_untrack Untrack file patterns from Git LFS.
Function log Write commit logs.
Function ls_files List all files in an index.
Function ls_remote List the refs in a remote.
Function ls_tree List contents of a tree.
Function mailinfo Extract patch information from an email message.
Function mailsplit Split an mbox file or Maildir into individual message files.
Function maintenance_register Register a repository for background maintenance.
Function maintenance_run Run maintenance tasks on a repository.
Function maintenance_unregister Unregister a repository from background maintenance.
Function merge Merge one or more commits into the current branch.
Function merge_base Find the best common ancestor(s) between commits.
Function merge_tree Perform a three-way tree merge without touching the working directory.
Function merged_branches List branches that have been merged into the current branch.
Function mktag Create a tag object from raw tag data.
Function mv Move or rename a file, directory, or symlink.
Function no_merged_branches List branches that have been merged into the current branch.
Function notes_add Add or update a note for an object.
Function notes_list List all notes in a notes ref.
Function notes_remove Remove a note for an object.
Function notes_show Show the note for an object.
Function open_repo Open an argument that can be a repository or a path for a repository.
Function open_repo_closing Open an argument that can be a repository or a path for a repository.
Function pack_objects Pack objects into a file.
Function pack_refs Pack loose references into packed-refs file.
Function parse_timezone_format Parse given string and attempt to return a timezone offset.
Function path_to_tree_path Convert a path to a path usable in an index, e.g. bytes and relative to the repository root.
Function print_commit Write a human-readable commit log entry.
Function print_name_only Print only the names of changed files.
Function print_name_status Print a simple status summary, listing changed files.
Function print_oneline Write a single-line commit log entry.
Function print_stat Write a diffstat summary for a commit.
Function print_tag Write a human-readable tag.
Function prune Prune/clean up a repository's object store.
Function pull Pull from remote via dulwich.client.
Function push Remote push with dulwich via dulwich.client.
Function rebase Rebase commits onto another branch.
Function receive_pack Receive a pack file after negotiating its contents using smart protocol.
Function reflog Show reflog entries for a reference or all references.
Function reflog_delete Delete a specific reflog entry.
Function reflog_expire Expire reflog entries based on age and reachability.
Function remote_add Add a remote.
Function remote_remove Remove a remote.
Function remove Remove files from the staging area.
Function repack Repack loose files in a repository.
Function replace_create Create a replacement ref to replace one object with another.
Function replace_delete Delete a replacement ref.
Function replace_list List all replacement refs.
Function rerere Record current conflict resolutions and apply known resolutions.
Function rerere_clear Clear all recorded rerere resolutions.
Function rerere_diff Show differences for recorded rerere conflicts.
Function rerere_forget Forget recorded rerere resolutions for a pathspec.
Function rerere_gc Garbage collect old rerere resolutions.
Function rerere_status Get the status of all conflicts in the rerere cache.
Function reset Reset current HEAD to the specified state.
Function reset_file Reset the file to specific commit or branch.
Function restore Restore working tree files.
Function rev_list Lists commit objects in reverse chronological order.
Function rev_parse Parse a revision string and return the object SHA.
Function revert Revert one or more commits.
Function set_branch_tracking Set up branch tracking configuration.
Function shortlog Summarize commits by author, like git shortlog.
Function show Print the changes in a commit.
Function show_blob Write a blob to a stream.
Function show_branch Display branches and their commits.
Function show_commit Show a commit to a stream.
Function show_index Show the contents of a pack index file.
Function show_object Show details of a git object.
Function show_ref List references in a local repository.
Function show_tag Print a tag to a stream.
Function show_tree Print a tree to a stream.
Function sparse_checkout Perform a sparse checkout in the repository (either 'full' or 'cone mode').
Function stash_drop Drop a stash from the stack.
Function stash_list List all stashes in a repository.
Function stash_pop Pop a stash from the stack.
Function stash_push Push a new stash onto the stack.
Function status Returns staged, unstaged, and untracked changes relative to the HEAD.
Function stripspace Strip unnecessary whitespace from text.
Function submodule_add Add a new submodule.
Function submodule_init Initialize submodules.
Function submodule_list List submodules.
Function submodule_update Update submodules.
Function switch Switch branches.
Function symbolic_ref Set git symbolic ref into HEAD.
Function tag_create Creates a tag in git via dulwich calls.
Function tag_delete Remove a tag.
Function tag_list List all tags.
Function tree_path_to_fs_path Convert a git tree path to a filesystem path (relative).
Function unpack_objects Unpack objects from a pack file into the repository.
Function update_head Update HEAD to point at a new branch/commit.
Function update_ref Update the object name stored in a ref safely.
Function update_server_info Update server info files for a repository.
Function upload_pack Upload a pack file after negotiating its contents using smart protocol.
Function var Get the value of a specific Git logical variable.
Function var_list List all Git logical variables.
Function verify_commit Verify signature on a commit.
Function verify_tag Verify signature on a tag.
Function web_daemon Run a daemon serving Git requests over HTTP.
Function worktree_add Add a new worktree.
Function worktree_list List all worktrees for a repository.
Function worktree_lock Lock a worktree to prevent it from being pruned.
Function worktree_move Move a worktree to a new location.
Function worktree_prune Prune worktree administrative files.
Function worktree_remove Remove a worktree.
Function worktree_repair Repair worktree administrative files.
Function worktree_unlock Unlock a worktree.
Function write_commit_graph Write a commit graph file for a repository.
Function write_tree Write a tree object from the index.
Constant DEFAULT_ENCODING Undocumented
Constant INFINITE_DEPTH Undocumented
Type Variable T Undocumented
Variable default_bytes_err_stream Undocumented
Variable default_bytes_out_stream Undocumented
Variable GitStatus Undocumented
Variable RepoPath Undocumented
Function _canonical_part Undocumented
Function _check_uncommitted_changes Check for uncommitted changes that would conflict with a checkout/switch.
Function _do_merge Internal merge implementation that operates on an open repository.
Function _do_octopus_merge Internal octopus merge implementation that operates on an open repository.
Function _filter_transport_kwargs Filter kwargs to only include parameters accepted by get_transport_and_path.
Function _find_reachable_tags Yield annotated tags whose targets are reachable from pushed commits.
Function _get_branch_merge_status Get merge status for all branches relative to current HEAD.
Function _get_current_head_tree Get the current HEAD tree ID.
Function _get_reflog_message Get reflog message, checking GIT_REFLOG_ACTION environment variable.
Function _get_variables Internal function to get all Git logical variables.
Function _get_worktree_update_config Get configuration for working tree updates.
Function _is_subdir Check whether subdir is parentdir or a subdir of parentdir.
Function _make_branch_ref Undocumented
Function _make_replace_ref Undocumented
Function _noop_context_manager Context manager that has the same api as closing but does nothing.
Function _perform_tree_switch Perform the actual working tree switch.
Function _precompose_unicode_path Normalize a filesystem path to NFC (precomposed) Unicode form.
Function _quote_path Quote a path using C-style quoting similar to git's core.quotePath.
Function _select_push_refs Select which refs to push based on mode flags or user refspecs.
Function _walk_working_dir_paths Get path, is_dir for files in working dir from frompath.
def active_branch(repo: RepoPath) -> bytes:

Return the active branch in the repository, if any.

Parameters
repo:RepoPathRepository to open
Returns
bytesbranch name
Raises
KeyErrorif the repository does not have a working tree
IndexErrorif HEAD is floating
def add(repo: str | os.PathLike[str] | Repo = '.', paths: Sequence[str | bytes | os.PathLike[str]] | str | bytes | os.PathLike[str] | None = None) -> tuple[list[str], set[str]]:

Add files to the staging area.

Returns: Tuple with set of added files and ignored files

If the repository contains ignored directories, the returned set will contain the path to an ignored directory (with trailing slash). Individual files within ignored directories will not be returned.

Note: When paths=None, this function adds all untracked and modified files from the entire repository, mimicking 'git add -A' behavior.

Parameters
repo:str | os.PathLike[str] | RepoRepository for the files
paths:Sequence[str | bytes | os.PathLike[str]] | str | bytes | os.PathLike[str] | NonePaths to add. If None, stages all untracked and modified files from the current working directory (mimicking 'git add .' behavior).
Returns
tuple[list[str], set[str]]Undocumented
def am(repo: RepoPath = '.', patches: str | bytes | BinaryIO | list[str | bytes | BinaryIO] | None = None, three_way: bool = False, keep_subject: bool = False, keep_non_patch: bool = False, scissors: bool = False, message_id: bool = False, strip: int = 1, committer: bytes | None = None, commit_timestamp: float | None = None, commit_timezone: int | None = None) -> list[ObjectID]:

Apply patches from mailbox-style email messages, creating commits.

Parameters
repo:RepoPathPath to the repository
patches:str | bytes | BinaryIO | list[str | bytes | BinaryIO] | NonePatch input(s) - file path(s), file-like object(s), or None for stdin. Can be a single mbox file containing multiple messages.
three_way:boolFall back to 3-way merge if patch does not apply cleanly
keep_subject:boolIf True, keep subject intact without munging
keep_non_patch:boolIf True, only strip [PATCH] from brackets
scissors:boolIf True, remove everything before scissors line
message_id:boolIf True, include Message-ID in commit message
strip:intNumber of leading path components to strip (default: 1)
committer:bytes | NoneOptional committer identity (bytes)
commit_timestamp:float | NoneOptional committer timestamp
commit_timezone:int | NoneOptional committer timezone offset
Returns
list[ObjectID]List of commit SHAs (bytes) created
def am_abort(repo: RepoPath = '.'):

Abort the current am and restore the original state.

Resets HEAD, index, and working tree to the state before am started.

Parameters
repo:RepoPathPath to the repository
def am_continue(repo: RepoPath = '.', committer: bytes | None = None, commit_timestamp: float | None = None, commit_timezone: int | None = None) -> list[ObjectID]:

Continue applying patches after resolving a conflict.

The user should have resolved conflicts and staged the result.

Parameters
repo:RepoPathPath to the repository
committer:bytes | NoneOptional committer identity
commit_timestamp:float | NoneOptional committer timestamp
commit_timezone:int | NoneOptional committer timezone offset
Returns
list[ObjectID]List of commit SHAs created
def am_quit(repo: RepoPath = '.'):

Quit the current am without reverting changes.

Removes am state but keeps HEAD, index, and working tree as-is.

Parameters
repo:RepoPathPath to the repository
def am_skip(repo: RepoPath = '.', committer: bytes | None = None, commit_timestamp: float | None = None, commit_timezone: int | None = None) -> list[ObjectID]:

Skip the current patch and continue with remaining patches.

Parameters
repo:RepoPathPath to the repository
committer:bytes | NoneOptional committer identity
commit_timestamp:float | NoneOptional committer timestamp
commit_timezone:int | NoneOptional committer timezone offset
Returns
list[ObjectID]List of commit SHAs created
def annotate(repo: RepoPath, path: str | bytes, committish: str | bytes | Commit | Tag | None = None) -> list[tuple[tuple[Commit, TreeEntry], bytes]]:

Annotate the history of a file.

Parameters
repo:RepoPathPath to the repository
path:str | bytesPath to annotate
committish:str | bytes | Commit | Tag | NoneCommit id to find path in
Returns
list[tuple[tuple[Commit, TreeEntry], bytes]]List of ((Commit, TreeChange), line) tuples
def apply_patch(repo: RepoPath = '.', patch_file: str | bytes | BinaryIO | None = None, cached: bool = False, reverse: bool = False, check: bool = False, strip: int = 1, three_way: bool = False):

Apply a patch to the working tree and/or index.

Parameters
repo:RepoPathPath to the repository
patch_file:str | bytes | BinaryIO | NonePath to patch file or file-like object (stdin if None)
cached:boolApply patch to index only, not working tree
reverse:boolApply patch in reverse
check:boolOnly check if patch can be applied, don't apply
strip:intNumber of leading path components to strip (default: 1)
three_way:boolFall back to 3-way merge if patch does not apply cleanly
Raises
ValueErrorIf patch cannot be applied
def archive(repo: str | BaseRepo, committish: str | bytes | Commit | Tag | None = None, outstream: BinaryIO | RawIOBase = default_bytes_out_stream, errstream: BinaryIO | RawIOBase = default_bytes_err_stream):

Create an archive.

Parameters
repo:str | BaseRepoPath of repository for which to generate an archive.
committish:str | bytes | Commit | Tag | NoneCommit SHA1 or ref to use
outstream:BinaryIO | RawIOBaseOutput stream (defaults to stdout)
errstream:BinaryIO | RawIOBaseError stream (defaults to stderr)
def bisect_bad(repo: str | os.PathLike[str] | Repo = '.', rev: str | bytes | Commit | Tag | None = None) -> bytes | None:

Mark a commit as bad.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
rev:str | bytes | Commit | Tag | NoneCommit to mark as bad (defaults to HEAD)
Returns
bytes | NoneThe SHA of the next commit to test, or None if bisect is complete
def bisect_good(repo: str | os.PathLike[str] | Repo = '.', rev: str | bytes | Commit | Tag | None = None) -> bytes | None:

Mark a commit as good.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
rev:str | bytes | Commit | Tag | NoneCommit to mark as good (defaults to HEAD)
Returns
bytes | NoneThe SHA of the next commit to test, or None if bisect is complete
def bisect_log(repo: str | os.PathLike[str] | Repo = '.') -> str:

Get the bisect log.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
Returns
strThe bisect log as a string
def bisect_replay(repo: str | os.PathLike[str] | Repo, log_file: str | os.PathLike[str] | BinaryIO):

Replay a bisect log.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
log_file:str | os.PathLike[str] | BinaryIOPath to the log file or file-like object
def bisect_reset(repo: str | os.PathLike[str] | Repo = '.', commit: str | bytes | Commit | Tag | None = None):

Reset bisect state and return to original branch/commit.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
commit:str | bytes | Commit | Tag | NoneOptional commit to reset to (defaults to original branch/commit)
def bisect_skip(repo: str | os.PathLike[str] | Repo = '.', revs: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag] | None = None) -> bytes | None:

Skip one or more commits.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
revs:str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag] | NoneList of commits to skip (defaults to [HEAD])
Returns
bytes | NoneThe SHA of the next commit to test, or None if bisect is complete
def bisect_start(repo: str | os.PathLike[str] | Repo = '.', bad: str | bytes | Commit | Tag | None = None, good: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag] | None = None, paths: Sequence[bytes] | None = None, no_checkout: bool = False, term_bad: str = 'bad', term_good: str = 'good') -> bytes | None:

Start a new bisect session.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or a Repo object
bad:str | bytes | Commit | Tag | NoneThe bad commit (defaults to HEAD)
good:str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag] | NoneList of good commits or a single good commit
paths:Sequence[bytes] | NoneOptional paths to limit bisect to
no_checkout:boolIf True, don't checkout commits during bisect
term_bad:strTerm to use for bad commits (default: "bad")
term_good:strTerm to use for good commits (default: "good")
Returns
bytes | NoneUndocumented
def branch_create(repo: str | os.PathLike[str] | Repo, name: str | bytes, objectish: str | bytes | None = None, force: bool = False):

Create a branch.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository
name:str | bytesName of the new branch
objectish:str | bytes | NoneTarget object to point new branch at (defaults to HEAD)
force:boolForce creation of branch, even if it already exists
def branch_delete(repo: RepoPath, name: str | bytes | Sequence[str | bytes]):

Delete a branch.

Parameters
repo:RepoPathPath to the repository
name:str | bytes | Sequence[str | bytes]Name of the branch
def branch_list(repo: RepoPath) -> list[Ref]:

List all branches.

Parameters
repo:RepoPathPath to the repository
Returns
list[Ref]List of branch names (without refs/heads/ prefix)
def branch_remotes_list(repo: RepoPath) -> list[bytes]:

List the short names of all remote branches.

Parameters
repo:RepoPathPath to the repository
Returns
list[bytes]List of branch names (without refs/remotes/ prefix, and without remote name; e.g. 'main' from 'origin/main')
def branches_containing(repo: RepoPath, commit: str) -> Iterator[bytes]:

List branches that contain the specified commit.

Parameters
repo:RepoPathPath to the repository
commit:strCommit-ish string (SHA, branch name, tag, etc.)
Returns
Iterator[bytes]Undocumented
Yields
Branch names (without refs/heads/ prefix) that contain the commit
Raises
ValueErrorIf the commit reference is malformed
KeyErrorIf the commit reference does not exist
def cat_file_content(repo: str | os.PathLike[str] | Repo, objectish: str | bytes) -> bytes:

Get the raw content of a Git object.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
objectish:str | bytesObject SHA, reference, or objectish (e.g., 'HEAD', 'main', 'abc123')
Returns
bytesRaw object content as bytes
def cat_file_size(repo: str | os.PathLike[str] | Repo, objectish: str | bytes) -> int:

Get the size of a Git object.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
objectish:str | bytesObject SHA, reference, or objectish (e.g., 'HEAD', 'main', 'abc123')
Returns
intObject size in bytes
def cat_file_type(repo: str | os.PathLike[str] | Repo, objectish: str | bytes) -> bytes:

Get the type of a Git object.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
objectish:str | bytesObject SHA, reference, or objectish (e.g., 'HEAD', 'main', 'abc123')
Returns
bytesObject type as bytes (b'blob', b'tree', b'commit', or b'tag')
def check_diverged(repo: BaseRepo, current_sha: ObjectID, new_sha: ObjectID):

Check if updating to a sha can be done with fast forwarding.

Parameters
repo:BaseRepoRepository object
current_sha:ObjectIDCurrent head sha
new_sha:ObjectIDNew head sha
def check_ignore(repo: RepoPath, paths: Sequence[str | bytes | os.PathLike[str]], no_index: bool = False, quote_path: bool = True) -> Iterator[str]:

Debug gitignore files.

Returns: List of ignored files

Parameters
repo:RepoPathPath to the repository
paths:Sequence[str | bytes | os.PathLike[str]]List of paths to check for
no_index:boolDon't check index
quote_path:boolIf True, quote non-ASCII characters in returned paths using C-style octal escapes (e.g. "тест.txt" becomes "\321\202\320\265\321\201\321\202.txt"). If False, return raw unicode paths.
Returns
Iterator[str]Undocumented
def check_mailmap(repo: RepoPath, contact: str | bytes) -> bytes:

Check canonical name and email of contact.

Returns: Canonical contact data

Parameters
repo:RepoPathPath to the repository
contact:str | bytesContact name and/or email
Returns
bytesUndocumented
def checkout(repo: str | os.PathLike[str] | Repo, target: str | bytes | Commit | Tag | None = None, force: bool = False, new_branch: bytes | str | None = None, paths: list[bytes | str] | None = None):

Switch to a branch or commit, updating both HEAD and the working tree.

This is similar to 'git checkout', allowing you to switch to a branch, tag, or specific commit. Unlike update_head, this function also updates the working tree to match the target.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or repository object
target:str | bytes | Commit | Tag | NoneBranch name, tag, or commit SHA to checkout. If None and paths is specified, restores files from HEAD
force:boolForce checkout even if there are local changes
new_branch:bytes | str | NoneCreate a new branch at target (like git checkout -b)
paths:list[bytes | str] | NoneList of specific paths to checkout. If specified, only these paths are updated and HEAD is not changed
Raises
CheckoutErrorIf checkout cannot be performed due to conflicts
KeyErrorIf the target reference cannot be found
def cherry(repo: str | os.PathLike[str] | Repo, upstream: str | bytes | None = None, head: str | bytes | None = None, limit: str | bytes | None = None, verbose: bool = False) -> list[tuple[str, bytes, bytes | None]]:

Find commits not merged upstream.

Parameters
repo:str | os.PathLike[str] | RepoRepository path or object
upstream:str | bytes | NoneUpstream branch (default: tracking branch or @{upstream})
head:str | bytes | NoneHead branch (default: HEAD)
limit:str | bytes | NoneLimit commits to those after this ref
verbose:boolInclude commit messages in output
Returns
list[tuple[str, bytes, bytes | None]]List of tuples (status, commit_sha, message) where status is '+' or '-' '+' means commit is not in upstream, '-' means equivalent patch exists upstream message is None unless verbose=True
def cherry_pick(repo: str | os.PathLike[str] | Repo, committish: str | bytes | Commit | Tag | None, no_commit: bool = False, continue_: bool = False, abort: bool = False) -> bytes | None:

Cherry-pick a commit onto the current branch.

Parameters
repo:str | os.PathLike[str] | RepoRepository to cherry-pick into
committish:str | bytes | Commit | Tag | NoneCommit to cherry-pick (can be None only when resuming or aborting)
no_commit:boolIf True, do not create a commit after applying changes
continue_:boolResume an in-progress cherry-pick after resolving conflicts if True
abort:boolAbort an in-progress cherry-pick
Returns
bytes | NoneThe SHA of the newly created commit, or None if no_commit=True or there were conflicts
Raises
ErrorIf there is no HEAD reference, commit cannot be found, or operation fails
def clean(repo: str | os.PathLike[str] | Repo = '.', target_dir: str | os.PathLike[str] | None = None):

Remove any untracked files from the target directory recursively.

Equivalent to running git clean -fd in target_dir.

Parameters
repo:str | os.PathLike[str] | RepoRepository where the files may be tracked
target_dir:str | os.PathLike[str] | NoneDirectory to clean - current directory if None
def clone(source: str | bytes | Repo, target: str | os.PathLike[str] | None = None, bare: bool = False, checkout: bool | None = None, errstream: BinaryIO | RawIOBase = default_bytes_err_stream, outstream: BinaryIO | None = None, origin: str | None = 'origin', depth: int | None = None, branch: str | bytes | None = None, config: Config | None = None, filter_spec: str | None = None, protocol_version: int | None = None, recurse_submodules: bool = False, ssh_command: str | None = None, **kwargs: str | bytes | Sequence[str | bytes]) -> Repo:

Clone a local or remote git repository.

Returns: The new repository

Parameters
source:str | bytes | RepoPath or URL for source repository
target:str | os.PathLike[str] | NonePath to target repository (optional)
bare:boolWhether or not to create a bare repository
checkout:bool | NoneWhether or not to check-out HEAD after cloning
errstream:BinaryIO | RawIOBaseOptional stream to write progress to
outstream:BinaryIO | NoneOptional stream to write progress to (deprecated)
origin:str | NoneName of remote from the repository used to clone
depth:int | NoneDepth to fetch at
branch:str | bytes | NoneOptional branch or tag to be used as HEAD in the new repository instead of the cloned repository's HEAD.
config:Config | NoneConfiguration to use
filter_spec:str | NoneA git-rev-list-style object filter spec, as an ASCII string. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise.
protocol_version:int | Nonedesired Git protocol version. By default the highest mutually supported protocol version will be used.
recurse_submodules:boolWhether to initialize and clone submodules
ssh_command:str | NoneOptional custom SSH command
**kwargs:str | bytes | Sequence[str | bytes]Additional keyword arguments including refspecs to fetch. Can be a bytestring, a string, or a list of bytestring/string.
Returns
RepoUndocumented
def commit(repo: RepoPath = '.', message: str | bytes | Callable[[Any, Commit], bytes] | None = None, author: bytes | None = None, author_timestamp: float | None = None, author_timezone: int | None = None, committer: bytes | None = None, commit_timestamp: float | None = None, commit_timezone: int | None = None, encoding: bytes | None = None, no_verify: bool = False, signoff: bool | None = None, all: bool = False, amend: bool = False, sign: bool | None = None) -> bytes:

Create a new commit.

Returns: SHA1 of the new commit

Parameters
repo:RepoPathPath to repository
message:str | bytes | Callable[[Any, Commit], bytes] | NoneOptional commit message (string/bytes or callable that takes (repo, commit) and returns bytes)
author:bytes | NoneOptional author name and email
author_timestamp:float | NoneAuthor timestamp (defaults to commit timestamp)
author_timezone:int | NoneAuthor timestamp timezone
committer:bytes | NoneOptional committer name and email
commit_timestamp:float | NoneCommit timestamp (defaults to now)
commit_timezone:int | NoneCommit timestamp timezone
encoding:bytes | NoneEncoding to use for commit message
no_verify:boolSkip pre-commit and commit-msg hooks
signoff:bool | NoneAdd Signed-off-by line to commit message. If None, uses format.signoff config.
all:boolAutomatically stage all tracked files that have been modified
amend:boolReplace the tip of the current branch by creating a new commit
sign:bool | NoneGPG sign the commit. If None, uses commit.gpgsign config. If True, signs with default GPG key. If False, does not sign.
Returns
bytesUndocumented
def commit_decode(commit: Commit, contents: bytes, default_encoding: str = DEFAULT_ENCODING) -> str:

Decode commit contents using the commit's encoding or default.

def commit_encode(commit: Commit, contents: str, default_encoding: str = DEFAULT_ENCODING) -> bytes:

Encode commit contents using the commit's encoding or default.

def commit_tree(repo: RepoPath, tree: ObjectID, message: str | bytes | None = None, author: bytes | None = None, committer: bytes | None = None) -> ObjectID:

Create a new commit object.

Parameters
repo:RepoPathPath to repository
tree:ObjectIDAn existing tree object
message:str | bytes | NoneCommit message
author:bytes | NoneOptional author name and email
committer:bytes | NoneOptional committer name and email
Returns
ObjectIDUndocumented
def cone_mode_add(repo: str | os.PathLike[str] | Repo, dirs: Sequence[str], force: bool = False):

Add new directories to the existing 'cone-mode' sparse-checkout patterns.

Reads the current patterns from .git/info/sparse-checkout, adds pattern lines to include the specified directories, and then performs a sparse checkout to update the working tree accordingly.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
dirs:Sequence[str]List of directory names to add to the sparse-checkout.
force:boolWhether to forcibly discard local modifications (default False).
Returns
None
def cone_mode_disable(repo: str | os.PathLike[str] | Repo, force: bool = False):

Disable sparse checkout and restore all files.

This function: 1. Unsets core.sparseCheckout and core.sparseCheckoutCone config 2. Removes the .git/info/sparse-checkout file 3. Restores all files to the working tree

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
force:boolWhether to forcibly discard local modifications (default False).
Returns
None
def cone_mode_init(repo: str | os.PathLike[str] | Repo):

Initialize a repository to use sparse checkout in 'cone' mode.

Sets core.sparseCheckout and core.sparseCheckoutCone in the config. Writes an initial .git/info/sparse-checkout file that includes only top-level files (and excludes all subdirectories), e.g. ["/*", "!/*/"]. Then performs a sparse checkout to update the working tree accordingly.

If no directories are specified, then only top-level files are included: https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
Returns
None
def cone_mode_list(repo: str | os.PathLike[str] | Repo) -> list[str]:

List current sparse-checkout patterns.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
Returns
list[str]List of sparse-checkout patterns
def cone_mode_set(repo: str | os.PathLike[str] | Repo, dirs: Sequence[str], force: bool = False):

Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.

Ensures core.sparseCheckout and core.sparseCheckoutCone are enabled. Writes new patterns so that only the specified directories (and top-level files) remain in the working tree, and applies the sparse checkout update.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
dirs:Sequence[str]List of directory names to include.
force:boolWhether to forcibly discard local modifications (default False).
Returns
None
def count_objects(repo: RepoPath = '.', verbose: bool = False) -> CountObjectsResult:

Count unpacked objects and their disk usage.

Parameters
repo:RepoPathPath to repository or repository object
verbose:boolWhether to return verbose information
Returns
CountObjectsResultCountObjectsResult object with detailed statistics
def daemon(path: str | os.PathLike[str] = '.', address: str | None = None, port: int | None = None):

Run a daemon serving Git requests over TCP/IP.

Parameters
path:str | os.PathLike[str]Path to the directory to serve.
address:str | NoneOptional address to listen on (defaults to ::)
port:int | NoneOptional port to listen on (defaults to TCP_GIT_PORT)
def describe(repo: str | os.PathLike[str] | Repo, abbrev: int | None = None) -> str:

Describe the repository version.

Returns: a string description of the current git revision

Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".

Parameters
repo:str | os.PathLike[str] | Repogit repository
abbrev:int | Nonenumber of characters of commit to take, default is 7
Returns
strUndocumented
def diff(repo: RepoPath = '.', commit: str | bytes | Commit | None = None, commit2: str | bytes | Commit | None = None, staged: bool = False, paths: Sequence[str | bytes] | None = None, outstream: BinaryIO = default_bytes_out_stream, diff_algorithm: str | None = None):

Show diff.

Parameters
repo:RepoPathPath to repository
commit:str | bytes | Commit | NoneFirst commit to compare. If staged is True, compare index to this commit. If staged is False, compare working tree to this commit. If None, defaults to HEAD for staged and index for unstaged.
commit2:str | bytes | Commit | NoneSecond commit to compare against first commit. If provided, show diff between commit and commit2 (ignoring staged flag).
staged:boolIf True, show staged changes (index vs commit). If False, show unstaged changes (working tree vs commit/index). Ignored if commit2 is provided.
paths:Sequence[str | bytes] | NoneOptional list of paths to limit diff
outstream:BinaryIOStream to write to
diff_algorithm:str | NoneAlgorithm to use for diffing ("myers" or "patience"), defaults to the underlying function's default if None
def diff_tree(repo: RepoPath, old_tree: str | bytes | Tree, new_tree: str | bytes | Tree, outstream: BinaryIO = default_bytes_out_stream):

Compares the content and mode of blobs found via two tree objects.

Parameters
repo:RepoPathPath to repository
old_tree:str | bytes | TreeId of old tree
new_tree:str | bytes | TreeId of new tree
outstream:BinaryIOStream to write to
def fetch(repo: RepoPath, remote_location: str | bytes | None = None, outstream: TextIO = sys.stdout, errstream: BinaryIO | RawIOBase = default_bytes_err_stream, message: bytes | None = None, depth: int | None = None, prune: bool = False, prune_tags: bool = False, force: bool = False, operation: str | None = None, thin_packs: bool = True, report_activity: Callable[[int, str], None] | None = None, quiet: bool = False, include_tags: bool = False, username: str | None = None, password: str | None = None, key_filename: str | None = None, ssh_command: str | None = None, shallow_since: str | None = None, shallow_exclude: list[str] | None = None, unshallow: bool = False) -> FetchPackResult:

Fetch objects from a remote server.

Parameters
repo:RepoPathPath to the repository
remote_location:str | bytes | NoneString identifying a remote server
outstream:TextIOOutput stream (defaults to stdout)
errstream:BinaryIO | RawIOBaseError stream (defaults to stderr)
message:bytes | NoneReflog message (defaults to b"fetch: from <remote_name>")
depth:int | NoneDepth to fetch at
prune:boolPrune remote removed refs
prune_tags:boolPrune remote removed tags
force:boolForce fetching even if it would overwrite local changes
operation:str | NoneGit operation for authentication (e.g., "fetch")
thin_packs:boolWhether to use thin packs
report_activity:Callable[[int, str], None] | NoneOptional callback for reporting transport activity
quiet:boolWhether to suppress progress output
include_tags:boolWhether to include tags
username:str | NoneUsername for authentication
password:str | NonePassword for authentication
key_filename:str | NoneSSH key filename
ssh_command:str | NoneSSH command to use
shallow_since:str | NoneDeepen or shorten the history to include commits after this date
shallow_exclude:list[str] | NoneDeepen or shorten the history to exclude commits reachable from these refs
unshallow:boolConvert a shallow repository to a complete one
Returns
FetchPackResultDictionary with refs on the remote
def filter_branch(repo: RepoPath = '.', branch: str | bytes = 'HEAD', *, filter_fn: Callable[[Commit], CommitData | None] | None = None, filter_author: Callable[[bytes], bytes | None] | None = None, filter_committer: Callable[[bytes], bytes | None] | None = None, filter_message: Callable[[bytes], bytes | None] | None = None, tree_filter: Callable[[ObjectID, str], ObjectID | None] | None = None, index_filter: Callable[[ObjectID, str], ObjectID | None] | None = None, parent_filter: Callable[[Sequence[ObjectID]], list[ObjectID]] | None = None, commit_filter: Callable[[Commit, ObjectID], ObjectID | None] | None = None, subdirectory_filter: str | bytes | None = None, prune_empty: bool = False, tag_name_filter: Callable[[bytes], bytes | None] | None = None, force: bool = False, keep_original: bool = True, refs: list[bytes] | None = None) -> dict[ObjectID, ObjectID]:

Rewrite branch history by creating new commits with filtered properties.

This is similar to git filter-branch, allowing you to rewrite commit history by modifying trees, parents, author, committer, or commit messages.

Parameters
repo:RepoPathPath to repository
branch:str | bytesBranch to rewrite (defaults to HEAD)
filter_fn:Callable[[Commit], CommitData | None] | NoneOptional callable that takes a Commit object and returns a dict of updated fields (author, committer, message, etc.)
filter_author:Callable[[bytes], bytes | None] | NoneOptional callable that takes author bytes and returns updated author bytes or None to keep unchanged
filter_committer:Callable[[bytes], bytes | None] | NoneOptional callable that takes committer bytes and returns updated committer bytes or None to keep unchanged
filter_message:Callable[[bytes], bytes | None] | NoneOptional callable that takes commit message bytes and returns updated message bytes
tree_filter:Callable[[ObjectID, str], ObjectID | None] | NoneOptional callable that takes (tree_sha, temp_dir) and returns new tree SHA after modifying working directory
index_filter:Callable[[ObjectID, str], ObjectID | None] | NoneOptional callable that takes (tree_sha, temp_index_path) and returns new tree SHA after modifying index
parent_filter:Callable[[Sequence[ObjectID]], list[ObjectID]] | NoneOptional callable that takes parent list and returns modified parent list
commit_filter:Callable[[Commit, ObjectID], ObjectID | None] | NoneOptional callable that takes (Commit, tree_sha) and returns new commit SHA or None to skip commit
subdirectory_filter:str | bytes | NoneOptional subdirectory path to extract as new root
prune_empty:boolWhether to prune commits that become empty
tag_name_filter:Callable[[bytes], bytes | None] | NoneOptional callable to rename tags
force:boolForce operation even if branch has been filtered before
keep_original:boolKeep original refs under refs/original/
refs:list[bytes] | NoneList of refs to rewrite (defaults to [branch])
Returns
dict[ObjectID, ObjectID]Dict mapping old commit SHAs to new commit SHAs
Raises
ErrorIf branch is already filtered and force is False
def filter_branches_by_pattern(branches: Iterable[bytes], pattern: str) -> list[bytes]:

Filter branches by fnmatch pattern.

Parameters
branches:Iterable[bytes]Iterable of branch names as bytes
pattern:strPattern to match against
Returns
list[bytes]List of filtered branch names
def find_unique_abbrev(object_store: BaseObjectStore, object_id: str | bytes, min_length: int = 7) -> str:

Find the shortest unique abbreviation for an object ID.

Parameters
object_store:BaseObjectStoreObject store to search in
object_id:str | bytesThe full object ID to abbreviate
min_length:intMinimum length of abbreviation (default 7)
Returns
strThe shortest unique prefix of the object ID (at least min_length chars)
def for_each_ref(repo: Repo | str = '.', pattern: str | bytes | None = None) -> list[tuple[bytes, bytes, bytes]]:

Iterate over all refs that match the (optional) pattern.

Returns: List of bytes tuples with: (sha, object_type, ref_name)

Parameters
repo:Repo | strPath to the repository
pattern:str | bytes | NoneOptional glob (7) patterns to filter the refs with
Returns
list[tuple[bytes, bytes, bytes]]Undocumented
def format_patch(repo: RepoPath = '.', committish: ObjectID | tuple[ObjectID, ObjectID] | None = None, outstream: TextIO = sys.stdout, outdir: str | os.PathLike[str] | None = None, n: int = 1, stdout: bool = False, version: str | None = None) -> list[str]:

Generate patches suitable for git am.

Parameters
repo:RepoPathPath to repository
committish:ObjectID | tuple[ObjectID, ObjectID] | NoneCommit-ish or commit range to generate patches for. Can be a single commit id, or a tuple of (start, end) commit ids for a range. If None, formats the last n commits from HEAD.
outstream:TextIOStream to write to if stdout=True
outdir:str | os.PathLike[str] | NoneDirectory to write patch files to (default: current directory)
n:intNumber of patches to generate if committish is None
stdout:boolWrite patches to stdout instead of files
version:str | NoneVersion string to include in patches (default: Dulwich version)
Returns
list[str]List of patch filenames that were created (empty if stdout=True)
def fsck(repo: RepoPath) -> Iterator[tuple[bytes, Exception]]:

Check a repository.

This function is shallow-aware and will not report errors for missing parent commits that are beyond the shallow boundary.

Returns: Iterator over errors/warnings

Parameters
repo:RepoPathA path to the repository
Returns
Iterator[tuple[bytes, Exception]]Undocumented
def gc(repo: RepoPath, auto: bool = False, aggressive: bool = False, prune: bool = True, grace_period: int | None = None, dry_run: bool = False, progress: Callable[[str], None] | None = None) -> GCStats:

Run garbage collection on a repository.

Parameters
repo:RepoPathPath to the repository or a Repo object
auto:boolIf True, only run gc if needed
aggressive:boolIf True, use more aggressive settings
prune:boolIf True, prune unreachable objects
grace_period:int | NoneGrace period in seconds for pruning. If None, reads gc.pruneExpire from config (default 2 weeks).
dry_run:boolIf True, only report what would be done
progress:Callable[[str], None] | NoneOptional progress callback
Returns
GCStatsGCStats object with garbage collection statistics
def get_branch_merge(repo: RepoPath, branch_name: bytes | None = None) -> bytes:

Return the branch's merge reference (upstream branch), if any.

Parameters
repo:RepoPathRepository to open
branch_name:bytes | NoneName of the branch (defaults to active branch)
Returns
bytesmerge reference name (e.g. b"refs/heads/main")
Raises
KeyErrorif the branch does not have a merge configuration
def get_branch_remote(repo: str | os.PathLike[str] | Repo) -> bytes:

Return the active branch's remote name, if any.

Parameters
repo:str | os.PathLike[str] | RepoRepository to open
Returns
bytesremote name
Raises
KeyErrorif the repository does not have a working tree
def get_object_by_path(repo: RepoPath, path: str | bytes, committish: str | bytes | Commit | Tag | None = None) -> Blob | Tree | Commit | Tag:

Get an object by path.

Returns: A ShaFile object

Parameters
repo:RepoPathA path to the repository
path:str | bytesPath to look up
committish:str | bytes | Commit | Tag | NoneCommit to look up path in
Returns
Blob | Tree | Commit | TagUndocumented
def get_remote_repo(repo: Repo, remote_location: str | bytes | None = None) -> tuple[str | None, str]:

Get the remote repository information.

Parameters
repo:RepoLocal repository object
remote_location:str | bytes | NoneOptional remote name or URL; defaults to branch remote
Returns
tuple[str | None, str]Tuple of (remote_name, remote_url) where remote_name may be None if remote_location is a URL rather than a configured remote
def get_tree_changes(repo: RepoPath, index: Index | None = None) -> dict[str, list[str | bytes]]:

Return add/delete/modify changes to tree by comparing index to HEAD.

Returns: dict with lists for each type of change

Parameters
repo:RepoPathrepo path or object
index:Index | Noneoptional Index object to reuse (avoids re-opening the index)
Returns
dict[str, list[str | bytes]]Undocumented
def get_untracked_paths(frompath: str | bytes | os.PathLike[str], basepath: str | bytes | os.PathLike[str], index: Index, exclude_ignored: bool = False, untracked_files: str = 'all', precompose_unicode: bool = False) -> Iterator[str]:

Get untracked paths.

Note: ignored directories will never be walked for performance reasons.
If exclude_ignored is False, only the path to an ignored directory will be yielded, no files inside the directory will be returned
Parameters
frompath:str | bytes | os.PathLike[str]Path to walk
basepath:str | bytes | os.PathLike[str]Path to compare to
index:IndexIndex to check against
exclude_ignored:boolWhether to exclude ignored paths
untracked_files:strHow to handle untracked files: - "no": return an empty list - "all": return all files in untracked directories - "normal": return untracked directories without listing their contents
precompose_unicode:boolIf True, normalize filesystem paths to NFC Unicode form. This is needed on macOS where the filesystem returns NFD paths.
Returns
Iterator[str]Undocumented
def get_user_timezones() -> tuple[int, int]:

Retrieve local timezone as described in git documentation.

https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt Returns: A tuple containing author timezone, committer timezone.

def grep(repo: RepoPath, pattern: str | bytes, *, outstream: TextIO = sys.stdout, rev: str | bytes | None = None, pathspecs: Sequence[str | bytes] | None = None, ignore_case: bool = False, line_number: bool = False, max_depth: int | None = None, respect_ignores: bool = True):

Search for a pattern in tracked files.

Parameters
repo:RepoPathPath to repository or Repo object
pattern:str | bytesRegular expression pattern to search for
outstream:TextIOStream to write results to
rev:str | bytes | NoneRevision to search in (defaults to HEAD)
pathspecs:Sequence[str | bytes] | NoneOptional list of path patterns to limit search
ignore_case:boolWhether to perform case-insensitive matching
line_number:boolWhether to output line numbers
max_depth:int | NoneMaximum directory depth to search
respect_ignores:boolWhether to respect .gitignore patterns
def hash_object(repo: str | os.PathLike[str] | Repo | None, path: str | os.PathLike[str] | None = None, data: bytes | None = None, object_type: bytes = b'blob', write: bool = False) -> bytes:

Compute object ID and optionally write to object store.

Parameters
repo:str | os.PathLike[str] | Repo | NonePath to the repository or a Repo object (required if write=True)
path:str | os.PathLike[str] | NonePath to file to hash (mutually exclusive with data)
data:bytes | NoneData to hash (mutually exclusive with path)
object_type:bytesType of object (default: b'blob')
write:boolWhether to write the object to the object store (default: False)
Returns
bytesObject SHA as bytes
Raises
ValueErrorIf neither path nor data is provided, or both are provided
ValueErrorIf write=True but repo is None
def independent_commits(repo: RepoPath = '.', committishes: Sequence[str | bytes] | None = None) -> list[ObjectID]:

Filter commits to only those that are not reachable from others.

Parameters
repo:RepoPathPath to repository
committishes:Sequence[str | bytes] | NoneList of commit references to filter
Returns
list[ObjectID]List of commit IDs that are not ancestors of any other commits in the list
def init(path: str | os.PathLike[str] = '.', *, bare: bool = False, symlinks: bool | None = None, object_format: str | None = None) -> Repo:

Create a new git repository.

Returns: A Repo instance

Parameters
path:str | os.PathLike[str]Path to repository.
bare:boolWhether to create a bare repository.
symlinks:bool | NoneWhether to create actual symlinks (defaults to autodetect)
object_format:str | NoneObject format to use ("sha1" or "sha256", defaults to "sha1")
Returns
RepoUndocumented
def interpret_trailers(message: str | bytes, *, trailers: list[tuple[str, str]] | None = None, trim_empty: bool = False, only_trailers: bool = False, only_input: bool = False, unfold: bool = False, parse: bool = False, where: str = 'end', if_exists: str = 'addIfDifferentNeighbor', if_missing: str = 'add', separators: str = ':') -> bytes:

Parse and manipulate trailers in a commit message.

This function implements the functionality of git interpret-trailers, allowing parsing and manipulation of structured metadata (trailers) in commit messages.

Trailers are key-value pairs at the end of commit messages, formatted like:
Signed-off-by: Alice <[email protected]> Reviewed-by: Bob <[email protected]>

Examples

>>> msg = b"Subject\\n\\nBody text\\n"
>>> interpret_trailers(msg, trailers=[("Signed-off-by", "Alice <[email protected]>")])
b'Subject\\n\\nBody text\\n\\nSigned-off-by: Alice <[email protected]>\\n'
>>> msg = b"Subject\\n\\nSigned-off-by: Alice\\n"
>>> interpret_trailers(msg, only_trailers=True)
b'Signed-off-by: Alice\\n'
Parameters
message:str | bytesThe commit message (string or bytes)
trailers:list[tuple[str, str]] | NoneList of (key, value) tuples to add as new trailers
trim_empty:boolRemove trailers with empty values
only_trailers:boolOutput only the trailers, not the message body
only_input:boolDon't add new trailers, only parse existing ones
unfold:boolJoin multiline trailer values into a single line
parse:boolShorthand for --only-trailers --only-input --unfold
where:strWhere to add new trailers ('end', 'start', 'after', 'before')
if_exists:strHow to handle duplicate keys - 'add': Always add - 'replace': Replace all existing - 'addIfDifferent': Add only if value differs from all existing - 'addIfDifferentNeighbor': Add only if value differs from neighbors - 'doNothing': Don't add if key exists
if_missing:strWhat to do if key doesn't exist ('add' or 'doNothing')
separators:strValid separator characters (default ':')
Returns
bytesThe processed message as bytes
def is_ancestor(repo: RepoPath = '.', ancestor: str | bytes | None = None, descendant: str | bytes | None = None) -> bool:

Check if one commit is an ancestor of another.

Parameters
repo:RepoPathPath to repository
ancestor:str | bytes | NoneCommit that might be the ancestor
descendant:str | bytes | NoneCommit that might be the descendant
Returns
boolTrue if ancestor is an ancestor of descendant, False otherwise
def is_interactive_rebase(repo: Repo | str) -> bool:

Check if an interactive rebase is in progress.

Parameters
repo:Repo | strRepository to check
Returns
boolTrue if interactive rebase is in progress, False otherwise
def lfs_clean(repo: str | os.PathLike[str] | Repo = '.', path: str | os.PathLike[str] | None = None) -> bytes:

Clean a file by converting it to an LFS pointer.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
path:str | os.PathLike[str] | NonePath to file to clean (relative to repo root)
Returns
bytesLFS pointer content as bytes
def lfs_fetch(repo: str | os.PathLike[str] | Repo = '.', remote: str = 'origin', refs: list[str | bytes] | None = None) -> int:

Fetch LFS objects from remote.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
remote:strRemote name (default: origin)
refs:list[str | bytes] | NoneSpecific refs to fetch LFS objects for (default: all refs)
Returns
intNumber of objects fetched
def lfs_init(repo: str | os.PathLike[str] | Repo = '.'):

Initialize Git LFS in a repository.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
Returns
None
def lfs_ls_files(repo: str | os.PathLike[str] | Repo = '.', ref: str | bytes | None = None) -> list[tuple[bytes, str, int]]:

List files tracked by Git LFS.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
ref:str | bytes | NoneGit ref to check (defaults to HEAD)
Returns
list[tuple[bytes, str, int]]List of (path, oid, size) tuples for LFS files
def lfs_migrate(repo: str | os.PathLike[str] | Repo = '.', include: list[str] | None = None, exclude: list[str] | None = None, everything: bool = False) -> int:

Migrate files to Git LFS.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
include:list[str] | NonePatterns of files to include
exclude:list[str] | NonePatterns of files to exclude
everything:boolMigrate all files above a certain size
Returns
intNumber of migrated files
def lfs_pointer_check(repo: str | os.PathLike[str] | Repo = '.', paths: Sequence[str] | None = None) -> dict[str, Any | None]:

Check if files are valid LFS pointers.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
paths:Sequence[str] | NoneList of file paths to check (if None, check all files)
Returns
dict[str, Any | None]Dict mapping paths to LFSPointer objects (or None if not a pointer)
def lfs_pull(repo: str | os.PathLike[str] | Repo = '.', remote: str = 'origin') -> int:

Pull LFS objects for current checkout.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
remote:strRemote name (default: origin)
Returns
intNumber of objects fetched
def lfs_push(repo: str | os.PathLike[str] | Repo = '.', remote: str = 'origin', refs: list[str | bytes] | None = None) -> int:

Push LFS objects to remote.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
remote:strRemote name (default: origin)
refs:list[str | bytes] | NoneSpecific refs to push LFS objects for (default: current branch)
Returns
intNumber of objects pushed
def lfs_smudge(repo: str | os.PathLike[str] | Repo = '.', pointer_content: bytes | None = None) -> bytes:

Smudge an LFS pointer by retrieving the actual content.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
pointer_content:bytes | NoneLFS pointer content as bytes
Returns
bytesActual file content as bytes
def lfs_status(repo: str | os.PathLike[str] | Repo = '.') -> dict[str, list[str]]:

Show status of LFS files.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
Returns
dict[str, list[str]]Dict with status information
def lfs_track(repo: str | os.PathLike[str] | Repo = '.', patterns: Sequence[str] | None = None) -> list[str]:

Track file patterns with Git LFS.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
patterns:Sequence[str] | NoneList of file patterns to track (e.g., [".bin", ".pdf"]) If None, returns current tracked patterns
Returns
list[str]List of tracked patterns
def lfs_untrack(repo: str | os.PathLike[str] | Repo = '.', patterns: Sequence[str] | None = None) -> list[str]:

Untrack file patterns from Git LFS.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
patterns:Sequence[str] | NoneList of file patterns to untrack
Returns
list[str]List of remaining tracked patterns
def log(repo: RepoPath = '.', paths: Sequence[str | bytes] | None = None, outstream: TextIO = sys.stdout, max_entries: int | None = None, reverse: bool = False, name_status: bool = False, name_only: bool = False, author: str | None = None, committer: str | None = None, grep: str | None = None, since: str | int | None = None, until: str | int | None = None, no_merges: bool = False, merges: bool = False, oneline: bool = False, abbrev_commit: bool = False, stat: bool = False, patch: bool = False, follow: bool = False):

Write commit logs.

Parameters
repo:RepoPathPath to repository
paths:Sequence[str | bytes] | NoneOptional set of specific paths to print entries for
outstream:TextIOStream to write log output to
max_entries:int | NoneOptional maximum number of entries to display
reverse:boolReverse order in which entries are printed
name_status:boolPrint name/status for each changed file
name_only:boolPrint only names of changed files
author:str | NoneFilter commits by author pattern
committer:str | NoneFilter commits by committer pattern
grep:str | NoneFilter commits by message pattern
since:str | int | NoneShow commits after this date (timestamp or date string)
until:str | int | NoneShow commits before this date (timestamp or date string)
no_merges:boolExclude merge commits
merges:boolOnly show merge commits
oneline:boolShow each commit on a single line
abbrev_commit:boolAbbreviate commit hashes
stat:boolShow diffstat for each commit
patch:boolShow patch (diff) for each commit
follow:boolFollow file renames
def ls_files(repo: RepoPath) -> list[bytes]:

List all files in an index.

def ls_remote(remote: str | bytes, config: Config | None = None, operation: str | None = None, thin_packs: bool = True, report_activity: Callable[[int, str], None] | None = None, quiet: bool = False, include_tags: bool = False, username: str | None = None, password: str | None = None, key_filename: str | None = None, ssh_command: str | None = None) -> LsRemoteResult:

List the refs in a remote.

Parameters
remote:str | bytesRemote repository location
config:Config | NoneConfiguration to use
operation:str | NoneOperation type
thin_packs:boolWhether to use thin packs
report_activity:Callable[[int, str], None] | NoneFunction to report activity
quiet:boolWhether to suppress output
include_tags:boolWhether to include tags
username:str | NoneUsername for authentication
password:str | NonePassword for authentication
key_filename:str | NoneSSH key filename
ssh_command:str | NoneSSH command to use
Returns
LsRemoteResultLsRemoteResult object with refs and symrefs
def ls_tree(repo: RepoPath, treeish: str | bytes | Commit | Tree | Tag = b'HEAD', outstream: TextIO | BinaryIO = sys.stdout, recursive: bool = False, name_only: bool = False):

List contents of a tree.

Parameters
repo:RepoPathPath to the repository
treeish:str | bytes | Commit | Tree | TagTree id to list
outstream:TextIO | BinaryIOOutput stream (defaults to stdout)
recursive:boolWhether to recursively list files
name_only:boolOnly print item name
def mailinfo(input_path: str | os.PathLike[str] | IO[bytes] | IO[str] | None = None, msg_file: str | os.PathLike[str] | None = None, patch_file: str | os.PathLike[str] | None = None, keep_subject: bool = False, keep_non_patch: bool = False, encoding: str | None = None, scissors: bool = False, message_id: bool = False) -> MailinfoResult:

Extract patch information from an email message.

This is similar to git mailinfo.

Example

>>> result = mailinfo("patch.eml", "msg", "patch")
>>> print(f"Author: {result.author_name} <{result.author_email}>")
>>> print(f"Subject: {result.subject}")
Parameters
input_path:str | os.PathLike[str] | IO[bytes] | IO[str] | NonePath to email file or file-like object. If None, reads from stdin.
msg_file:str | os.PathLike[str] | NonePath to write commit message. If None, message not written to file.
patch_file:str | os.PathLike[str] | NonePath to write patch content. If None, patch not written to file.
keep_subject:boolIf True, keep subject intact without munging (-k)
keep_non_patch:boolIf True, only strip [PATCH] from brackets (-b)
encoding:str | NoneCharacter encoding to use (default: detect from message)
scissors:boolIf True, remove everything before scissors line
message_id:boolIf True, include Message-ID in commit message (-m)
Returns
MailinfoResultMailinfoResult with parsed information
Raises
ValueErrorIf message is malformed or missing required fields
OSErrorIf there are issues reading/writing files
def mailsplit(input_path: str | os.PathLike[str] | IO[bytes] | None = None, output_dir: str | os.PathLike[str] = '.', start_number: int = 1, precision: int = 4, keep_cr: bool = False, mboxrd: bool = False, is_maildir: bool = False) -> list[str]:

Split an mbox file or Maildir into individual message files.

This is similar to git mailsplit.

Parameters
input_path:str | os.PathLike[str] | IO[bytes] | NonePath to mbox file, Maildir, or file-like object. If None, reads from stdin.
output_dir:str | os.PathLike[str]Directory where individual messages will be written
start_number:intStarting number for output files (default: 1)
precision:intNumber of digits for output filenames (default: 4)
keep_cr:boolIf True, preserve r in lines ending with rn (default: False)
mboxrd:boolIf True, treat input as mboxrd format and reverse escaping (default: False)
is_maildir:boolIf True, treat input_path as a Maildir (default: False)
Returns
list[str]List of output file paths that were created
Raises
ValueErrorIf output_dir doesn't exist or input is invalid
OSErrorIf there are issues reading/writing files
def maintenance_register(repo: RepoPath):

Register a repository for background maintenance.

This adds the repository to the global maintenance.repo config and sets up recommended configuration for scheduled maintenance.

Parameters
repo:RepoPathPath to the repository or repository object
def maintenance_run(repo: RepoPath, tasks: list[str] | None = None, auto: bool = False, progress: Callable[[str], None] | None = None) -> MaintenanceResult:

Run maintenance tasks on a repository.

Parameters
repo:RepoPathPath to the repository or a Repo object
tasks:list[str] | NoneOptional list of specific task names to run (e.g., ['gc', 'commit-graph', 'pack-refs'])
auto:boolIf True, only run tasks if needed
progress:Callable[[str], None] | NoneOptional progress callback
Returns
MaintenanceResultMaintenanceResult object with task execution results
def maintenance_unregister(repo: RepoPath, force: bool = False):

Unregister a repository from background maintenance.

This removes the repository from the global maintenance.repo config.

Parameters
repo:RepoPathPath to the repository or repository object
force:boolIf True, don't error if repository is not registered
def merge(repo: str | os.PathLike[str] | Repo, committish: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag], no_commit: bool = False, no_ff: bool = False, message: bytes | None = None, author: bytes | None = None, committer: bytes | None = None) -> tuple[bytes | None, list[bytes]]:

Merge one or more commits into the current branch.

Parameters
repo:str | os.PathLike[str] | RepoRepository to merge into
committish:str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag]Commit(s) to merge. Can be a single commit or a sequence of commits. When merging more than two heads, the octopus merge strategy is used.
no_commit:boolIf True, do not create a merge commit
no_ff:boolIf True, force creation of a merge commit
message:bytes | NoneOptional merge commit message
author:bytes | NoneOptional author for merge commit
committer:bytes | NoneOptional committer for merge commit
Returns
tuple[bytes | None, list[bytes]]Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None if no_commit=True or there were conflicts
Raises
ErrorIf there is no HEAD reference or commit cannot be found
def merge_base(repo: RepoPath = '.', committishes: Sequence[str | bytes] | None = None, all: bool = False, octopus: bool = False) -> list[ObjectID]:

Find the best common ancestor(s) between commits.

Parameters
repo:RepoPathPath to repository
committishes:Sequence[str | bytes] | NoneList of commit references (branches, tags, commit IDs)
all:boolIf True, return all merge bases, not just one
octopus:boolIf True, find merge base of all commits (n-way merge)
Returns
list[ObjectID]List of commit IDs that are merge bases
def merge_tree(repo: RepoPath, base_tree: str | bytes | Tree | Commit | Tag | None, our_tree: str | bytes | Tree | Commit | Tag, their_tree: str | bytes | Tree | Commit | Tag) -> tuple[bytes, list[bytes]]:

Perform a three-way tree merge without touching the working directory.

This is similar to git merge-tree, performing a merge at the tree level without creating commits or updating any references.

Parameters
repo:RepoPathRepository containing the trees
base_tree:str | bytes | Tree | Commit | Tag | NoneTree-ish of the common ancestor (or None for no common ancestor)
our_tree:str | bytes | Tree | Commit | TagTree-ish of our side of the merge
their_tree:str | bytes | Tree | Commit | TagTree-ish of their side of the merge
Returns
tuple
A tuple of (merged_tree_id, conflicts) where:
  • merged_tree_id is the SHA-1 of the merged tree
  • conflicts is a list of paths (as bytes) that had conflicts
Raises
KeyErrorIf any of the tree-ish arguments cannot be resolved
def merged_branches(repo: RepoPath) -> Iterator[bytes]:

List branches that have been merged into the current branch.

Parameters
repo:RepoPathPath to the repository
Returns
Iterator[bytes]Undocumented
Yields
Branch names (without refs/heads/ prefix) that are merged into the current HEAD
def mktag(repo: str | os.PathLike[str] | Repo, tag_data: bytes) -> bytes:

Create a tag object from raw tag data.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
tag_data:bytesRaw tag data in git tag format
Returns
bytesObject SHA of the created tag as bytes
Raises
ObjectFormatExceptionIf the tag data is invalid
def mv(repo: str | os.PathLike[str] | Repo, source: str | bytes | os.PathLike[str], destination: str | bytes | os.PathLike[str], force: bool = False):

Move or rename a file, directory, or symlink.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository
source:str | bytes | os.PathLike[str]Path to move from
destination:str | bytes | os.PathLike[str]Path to move to
force:boolForce move even if destination exists
Raises
ErrorIf source doesn't exist, is not tracked, or destination already exists (without force)
def no_merged_branches(repo: RepoPath) -> Iterator[bytes]:

List branches that have been merged into the current branch.

Parameters
repo:RepoPathPath to the repository
Returns
Iterator[bytes]Undocumented
Yields
Branch names (without refs/heads/ prefix) that are merged into the current HEAD
def notes_add(repo: RepoPath, object_sha: bytes, note: bytes, ref: bytes = b'commits', author: bytes | None = None, committer: bytes | None = None, message: bytes | None = None) -> bytes:

Add or update a note for an object.

Parameters
repo:RepoPathPath to repository
object_sha:bytesSHA of the object to annotate
note:bytesNote content
ref:bytesNotes ref to use (defaults to "commits" for refs/notes/commits)
author:bytes | NoneAuthor identity (defaults to committer)
committer:bytes | NoneCommitter identity (defaults to config)
message:bytes | NoneCommit message for the notes update
Returns
bytesSHA of the new notes commit
def notes_list(repo: RepoPath, ref: bytes = b'commits') -> list[tuple[ObjectID, bytes]]:

List all notes in a notes ref.

Parameters
repo:RepoPathPath to repository
ref:bytesNotes ref to use (defaults to "commits" for refs/notes/commits)
Returns
list[tuple[ObjectID, bytes]]List of tuples of (object_sha, note_content)
def notes_remove(repo: RepoPath, object_sha: bytes, ref: bytes = b'commits', author: bytes | None = None, committer: bytes | None = None, message: bytes | None = None) -> bytes | None:

Remove a note for an object.

Parameters
repo:RepoPathPath to repository
object_sha:bytesSHA of the object to remove notes from
ref:bytesNotes ref to use (defaults to "commits" for refs/notes/commits)
author:bytes | NoneAuthor identity (defaults to committer)
committer:bytes | NoneCommitter identity (defaults to config)
message:bytes | NoneCommit message for the notes removal
Returns
bytes | NoneSHA of the new notes commit, or None if no note existed
def notes_show(repo: RepoPath, object_sha: bytes, ref: bytes = b'commits') -> bytes | None:

Show the note for an object.

Parameters
repo:RepoPathPath to repository
object_sha:bytesSHA of the object
ref:bytesNotes ref to use (defaults to "commits" for refs/notes/commits)
Returns
bytes | NoneNote content as bytes, or None if no note exists
def open_repo(path_or_repo: T) -> AbstractContextManager[T]:
def open_repo(path_or_repo: str | os.PathLike[str]) -> AbstractContextManager[Repo]:

Open an argument that can be a repository or a path for a repository.

def open_repo_closing(path_or_repo: T) -> AbstractContextManager[T]:
def open_repo_closing(path_or_repo: str | bytes | os.PathLike[str]) -> AbstractContextManager[Repo]:

Open an argument that can be a repository or a path for a repository.

returns a context manager that will close the repo on exit if the argument is a path, else does nothing if the argument is a repo.

def pack_objects(repo: RepoPath, object_ids: Sequence[ObjectID], packf: BinaryIO, idxf: BinaryIO | None, delta_window_size: int | None = None, deltify: bool | None = None, reuse_deltas: bool = True, pack_index_version: int | None = None):

Pack objects into a file.

Parameters
repo:RepoPathPath to the repository
object_ids:Sequence[ObjectID]List of object ids to write
packf:BinaryIOFile-like object to write to
idxf:BinaryIO | NoneFile-like object to write to (can be None)
delta_window_size:int | NoneSliding window size for searching for deltas; Set to None for default window size.
deltify:bool | NoneWhether to deltify objects
reuse_deltas:boolAllow reuse of existing deltas while deltifying
pack_index_version:int | NonePack index version to use (1, 2, or 3). If None, uses default version.
def pack_refs(repo: RepoPath, all: bool = False):

Pack loose references into packed-refs file.

def parse_timezone_format(tz_str: str) -> int:

Parse given string and attempt to return a timezone offset.

Different formats are considered in the following order:

  • Git internal format: <unix timestamp> <timezone offset>
  • RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  • ISO 8601: e.g. 1995-11-20T19:12:08-0500

Returns: Timezone offset as integer

Parameters
tz_str:strdatetime string
Returns
intUndocumented
Raises
TimezoneFormatErrorif timezone information cannot be extracted
def path_to_tree_path(repopath: str | bytes | os.PathLike[str], path: str | bytes | os.PathLike[str], tree_encoding: str = DEFAULT_ENCODING) -> bytes:

Convert a path to a path usable in an index, e.g. bytes and relative to the repository root.

Returns: A path formatted for use in e.g. an index

Parameters
repopath:str | bytes | os.PathLike[str]Repository path, absolute or relative to the cwd
path:str | bytes | os.PathLike[str]A path, absolute or relative to the cwd
tree_encoding:strEncoding to use for tree paths
Returns
bytesUndocumented
def print_commit(commit: Commit, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout, abbrev_commit: bool = False):

Write a human-readable commit log entry.

Parameters
commit:CommitA Commit object
decode:Callable[[bytes], str]Function to decode commit data
outstream:TextIOA stream file to write to
abbrev_commit:boolIf True, abbreviate commit hashes
def print_name_only(changes: Iterator[TreeChange]) -> Iterator[str]:

Print only the names of changed files.

Parameters
changes:Iterator[TreeChange]Iterator of TreeChange objects
Returns
Iterator[str]Undocumented
Yields
Formatted name-only strings for each change
def print_name_status(changes: Iterator[TreeChange]) -> Iterator[str]:

Print a simple status summary, listing changed files.

def print_oneline(commit: Commit, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout, abbrev_commit: bool = True):

Write a single-line commit log entry.

Parameters
commit:CommitA Commit object
decode:Callable[[bytes], str]Function to decode commit data
outstream:TextIOA stream file to write to
abbrev_commit:boolIf True, abbreviate commit hashes
def print_stat(store: BaseObjectStore, commit: Commit, outstream: TextIO = sys.stdout):

Write a diffstat summary for a commit.

Parameters
store:BaseObjectStoreObjectStore for looking up objects
commit:CommitA Commit object
outstream:TextIOA stream file to write to
def print_tag(tag: Tag, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout):

Write a human-readable tag.

Parameters
tag:TagA Tag object
decode:Callable[[bytes], str]Function for decoding bytes to unicode string
outstream:TextIOA stream to write to
def prune(repo: RepoPath, grace_period: int | None = None, dry_run: bool = False, progress: Callable[[str], None] | None = None):

Prune/clean up a repository's object store.

This removes temporary files that were left behind by interrupted pack operations.

Parameters
repo:RepoPathPath to the repository or a Repo object
grace_period:int | NoneGrace period in seconds for removing temporary files (default 2 weeks)
dry_run:boolIf True, only report what would be done
progress:Callable[[str], None] | NoneOptional progress callback
def pull(repo: RepoPath, remote_location: str | bytes | None = None, refspecs: str | bytes | Sequence[str | bytes] | None = None, outstream: BinaryIO = default_bytes_out_stream, errstream: BinaryIO | RawIOBase = default_bytes_err_stream, fast_forward: bool = True, ff_only: bool = False, force: bool = False, filter_spec: str | None = None, protocol_version: int | None = None, **kwargs: object):

Pull from remote via dulwich.client.

Parameters
repo:RepoPathPath to repository
remote_location:str | bytes | NoneLocation of the remote
refspecs:str | bytes | Sequence[str | bytes] | Nonerefspecs to fetch. Can be a bytestring, a string, or a list of bytestring/string.
outstream:BinaryIOA stream file to write to output
errstream:BinaryIO | RawIOBaseA stream file to write to errors
fast_forward:boolIf True, raise an exception when fast-forward is not possible
ff_only:boolIf True, only allow fast-forward merges. Raises DivergedBranches when branches have diverged rather than performing a merge.
force:boolIf True, allow overwriting local changes in the working tree. If False, pull will abort if it would overwrite uncommitted changes.
filter_spec:str | NoneA git-rev-list-style object filter spec, as an ASCII string. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise.
protocol_version:int | Nonedesired Git protocol version. By default the highest mutually supported protocol version will be used
**kwargs:objectAdditional keyword arguments for the client
def push(repo: RepoPath, remote_location: str | bytes | None = None, refspecs: str | bytes | Sequence[str | bytes] | None = None, outstream: BinaryIO = default_bytes_out_stream, errstream: BinaryIO | RawIOBase = default_bytes_err_stream, force: bool = False, push_options: list[str] | None = None, atomic: bool = False, all: bool = False, tags: bool = False, delete: bool = False, dry_run: bool = False, prune: bool = False, set_upstream: bool = False, follow_tags: bool = False, mirror: bool = False, **kwargs: object) -> SendPackResult:

Remote push with dulwich via dulwich.client.

Parameters
repo:RepoPathPath to repository
remote_location:str | bytes | NoneLocation of the remote
refspecs:str | bytes | Sequence[str | bytes] | NoneRefs to push to remote
outstream:BinaryIOA stream file to write output
errstream:BinaryIO | RawIOBaseA stream file to write errors
force:boolForce overwriting refs
push_options:list[str] | NoneOptional list of push options to send to the server (e.g. for AGit flow: ["topic=my-branch", "title=My PR"])
atomic:boolIf True, request atomic push (all refs update or none do)
all:boolIf True, push all branches
tags:boolIf True, push all tags
delete:boolIf True, delete the specified remote refs
dry_run:boolIf True, do everything except actually send the updates
prune:boolIf True, remove remote refs that don't exist locally
set_upstream:boolIf True, set upstream tracking info for pushed branches
follow_tags:boolIf True, push annotated tags reachable from pushed commits
mirror:boolIf True, mirror all refs (implies force, push all refs and delete remote refs not present locally)
**kwargs:objectAdditional keyword arguments for the client
Returns
SendPackResultUndocumented
def rebase(repo: Repo | str, upstream: bytes | str, onto: bytes | str | None = None, branch: bytes | str | None = None, abort: bool = False, continue_rebase: bool = False, skip: bool = False, interactive: bool = False, edit_todo: bool = False) -> list[bytes]:

Rebase commits onto another branch.

Parameters
repo:Repo | strRepository to rebase in
upstream:bytes | strUpstream branch/commit to rebase onto
onto:bytes | str | NoneSpecific commit to rebase onto (defaults to upstream)
branch:bytes | str | NoneBranch to rebase (defaults to current branch)
abort:boolAbort an in-progress rebase
continue_rebase:boolContinue an in-progress rebase
skip:boolSkip current commit and continue rebase
interactive:boolStart an interactive rebase
edit_todo:boolEdit the todo list of an interactive rebase
Returns
list[bytes]List of new commit SHAs created by rebase
Raises
ErrorIf rebase fails or conflicts occur
def receive_pack(path: str | os.PathLike[str] = '.', inf: BinaryIO | None = None, outf: BinaryIO | None = None) -> int:

Receive a pack file after negotiating its contents using smart protocol.

Parameters
path:str | os.PathLike[str]Path to the repository
inf:BinaryIO | NoneInput stream to communicate with client
outf:BinaryIO | NoneOutput stream to communicate with client
Returns
intUndocumented
def reflog(repo: RepoPath = '.', ref: str | bytes = b'HEAD', all: bool = False) -> Iterator[Any | tuple[bytes, Any]]:

Show reflog entries for a reference or all references.

Parameters
repo:RepoPathPath to repository or a Repo object
ref:str | bytesReference name (defaults to HEAD)
all:boolIf True, show reflogs for all refs (ignores ref parameter)
Returns
Iterator[Any | tuple[bytes, Any]]Undocumented
Yields
If all=FalseReflogEntry objects If all=True: Tuples of (ref_name, ReflogEntry) for all refs with reflogs
def reflog_delete(repo: RepoPath = '.', ref: str | bytes = b'HEAD', index: int = 0, rewrite: bool = False):

Delete a specific reflog entry.

Parameters
repo:RepoPathPath to repository or a Repo object
ref:str | bytesReference name
index:intReflog entry index (0 = newest, in Git reflog order)
rewrite:boolIf True, rewrite old_sha of subsequent entries to maintain consistency
def reflog_expire(repo: RepoPath = '.', ref: str | bytes | None = None, all: bool = False, expire_time: int | None = None, expire_unreachable_time: int | None = None, dry_run: bool = False) -> dict[bytes, int]:

Expire reflog entries based on age and reachability.

Parameters
repo:RepoPathPath to repository or a Repo object
ref:str | bytes | NoneReference name (if not using --all)
all:boolIf True, expire reflogs for all refs
expire_time:int | NoneExpire entries older than this timestamp (seconds since epoch)
expire_unreachable_time:int | NoneExpire unreachable entries older than this timestamp
dry_run:boolIf True, show what would be expired without making changes
Returns
dict[bytes, int]Dictionary mapping ref names to number of expired entries
def remote_add(repo: RepoPath, name: bytes | str, url: bytes | str):

Add a remote.

Parameters
repo:RepoPathPath to the repository
name:bytes | strRemote name
url:bytes | strRemote URL
def remote_remove(repo: Repo, name: bytes | str):

Remove a remote.

Parameters
repo:RepoPath to the repository
name:bytes | strRemote name
def remove(repo: str | os.PathLike[str] | Repo = '.', paths: Sequence[str | bytes | os.PathLike[str]] = [], cached: bool = False):

Remove files from the staging area.

Parameters
repo:str | os.PathLike[str] | RepoRepository for the files
paths:Sequence[str | bytes | os.PathLike[str]]Paths to remove. Can be absolute or relative to the repository root.
cached:boolOnly remove from index, not from working directory
def repack(repo: RepoPath, write_bitmaps: bool = False):

Repack loose files in a repository.

Currently this only packs loose objects.

Parameters
repo:RepoPathPath to the repository
write_bitmaps:boolWhether to write bitmap indexes for packs
def replace_create(repo: RepoPath, object_sha: str | ObjectID, replacement_sha: str | ObjectID):

Create a replacement ref to replace one object with another.

Parameters
repo:RepoPathPath to repository
object_sha:str | ObjectIDSHA of the object to replace
replacement_sha:str | ObjectIDSHA of the replacement object
def replace_delete(repo: RepoPath, object_sha: ObjectID | str):

Delete a replacement ref.

Parameters
repo:RepoPathPath to repository
object_sha:ObjectID | strSHA of the object whose replacement should be removed
def replace_list(repo: RepoPath) -> list[tuple[ObjectID, ObjectID]]:

List all replacement refs.

Parameters
repo:RepoPathPath to repository
Returns
list[tuple[ObjectID, ObjectID]]List of tuples of (object_sha, replacement_sha) where object_sha is the object being replaced and replacement_sha is what it's replaced with
def rerere(repo: RepoPath = '.') -> tuple[list[tuple[bytes, str]], list[bytes]]:

Record current conflict resolutions and apply known resolutions.

This reads conflicted files from the working tree and records them in the rerere cache. If rerere.autoupdate is enabled and a known resolution exists, it will be automatically applied.

Parameters
repo:RepoPathPath to the repository
Returns
Tuple of
  • List of tuples (path, conflict_id) for recorded conflicts
  • List of paths where resolutions were automatically applied
def rerere_clear(repo: RepoPath = '.'):

Clear all recorded rerere resolutions.

Parameters
repo:RepoPathPath to the repository
def rerere_diff(repo: RepoPath = '.', conflict_id: str | None = None) -> list[tuple[str, bytes, bytes | None]]:

Show differences for recorded rerere conflicts.

Parameters
repo:RepoPathPath to the repository
conflict_id:str | NoneOptional specific conflict ID to show
Returns
list[tuple[str, bytes, bytes | None]]List of tuples (conflict_id, preimage, postimage)
def rerere_forget(repo: RepoPath = '.', pathspec: str | bytes | None = None):

Forget recorded rerere resolutions for a pathspec.

Parameters
repo:RepoPathPath to the repository
pathspec:str | bytes | NonePath to forget (currently not implemented, forgets all)
def rerere_gc(repo: RepoPath = '.', max_age_days: int = 60):

Garbage collect old rerere resolutions.

Parameters
repo:RepoPathPath to the repository
max_age_days:intMaximum age in days for keeping resolutions
def rerere_status(repo: RepoPath = '.') -> list[tuple[str, bool]]:

Get the status of all conflicts in the rerere cache.

Parameters
repo:RepoPathPath to the repository
Returns
list[tuple[str, bool]]List of tuples (conflict_id, has_resolution)
def reset(repo: str | os.PathLike[str] | Repo, mode: str, treeish: str | bytes | Commit | Tree | Tag = 'HEAD'):

Reset current HEAD to the specified state.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
mode:strMode ("hard", "soft", "mixed")
treeish:str | bytes | Commit | Tree | TagTreeish to reset to
def reset_file(repo: Repo, file_path: str, target: str | bytes | Commit | Tree | Tag = b'HEAD', symlink_fn: Callable[[(str | bytes | os.PathLike[str]), (str | bytes | os.PathLike[str])], None] | None = None):

Reset the file to specific commit or branch.

Parameters
repo:Repodulwich Repo object
file_path:strfile to reset, relative to the repository path
target:str | bytes | Commit | Tree | Tagbranch or commit or b'HEAD' to reset
symlink_fn:Callable[[(str | bytes | os.PathLike[str]), (str | bytes | os.PathLike[str])], None] | NoneFunction to use for creating symlinks
def restore(repo: str | os.PathLike[str] | Repo, paths: list[bytes | str], source: str | bytes | Commit | Tag | None = None, staged: bool = False, worktree: bool = True):

Restore working tree files.

This is similar to 'git restore', allowing you to restore specific files from a commit or the index without changing HEAD.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or repository object
paths:list[bytes | str]List of specific paths to restore
source:str | bytes | Commit | Tag | NoneBranch name, tag, or commit SHA to restore from. If None, restores staged files from HEAD, or worktree files from index
staged:boolRestore files in the index (--staged)
worktree:boolRestore files in the working tree (default: True)
Raises
CheckoutErrorIf restore cannot be performed
ValueErrorIf neither staged nor worktree is specified
KeyErrorIf the source reference cannot be found
def rev_list(repo: RepoPath, commits: Sequence[str | bytes], outstream: BinaryIO = default_bytes_out_stream):

Lists commit objects in reverse chronological order.

Parameters
repo:RepoPathPath to repository
commits:Sequence[str | bytes]Commits over which to iterate
outstream:BinaryIOStream to write to
def rev_parse(repo: str | os.PathLike[str] | Repo, rev: str | bytes) -> bytes:

Parse a revision string and return the object SHA.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
rev:str | bytesRevision string (e.g., 'HEAD', 'main', 'abc123')
Returns
bytesObject SHA as bytes
def revert(repo: str | os.PathLike[str] | Repo, commits: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag], no_commit: bool = False, message: str | bytes | None = None, author: bytes | None = None, committer: bytes | None = None) -> bytes | None:

Revert one or more commits.

This creates a new commit that undoes the changes introduced by the specified commits. Unlike reset, revert creates a new commit that preserves history.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or repository object
commits:str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag]List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
no_commit:boolIf True, apply changes to index/working tree but don't commit
message:str | bytes | NoneOptional commit message (default: "Revert <original subject>")
author:bytes | NoneOptional author for revert commit
committer:bytes | NoneOptional committer for revert commit
Returns
bytes | NoneSHA1 of the new revert commit, or None if no_commit=True
Raises
ErrorIf revert fails due to conflicts or other issues
def set_branch_tracking(repo: str | os.PathLike[str] | Repo, branch_name: bytes, remote_name: bytes, remote_ref: bytes):

Set up branch tracking configuration.

Parameters
repo:str | os.PathLike[str] | RepoRepository to open
branch_name:bytesName of the local branch
remote_name:bytesName of the remote (e.g. b"origin")
remote_ref:bytesRemote reference to track (e.g. b"refs/heads/main")
def shortlog(repo: str | os.PathLike[str] | Repo, summary_only: bool = False, sort_by_commits: bool = False) -> list[dict[str, str]]:

Summarize commits by author, like git shortlog.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or Repo object.
summary_only:boolIf True, only show counts per author.
sort_by_commits:boolIf True, sort authors by number of commits.
Returns
A list where each item is a dict containing
  • "author": the author's name as a string
  • "messages": all commit messages concatenated into a single string
def show(repo: RepoPath = '.', objects: Sequence[str | bytes] | None = None, outstream: TextIO = sys.stdout, default_encoding: str = DEFAULT_ENCODING):

Print the changes in a commit.

Parameters
repo:RepoPathPath to repository
objects:Sequence[str | bytes] | NoneObjects to show (defaults to [HEAD])
outstream:TextIOStream to write to
default_encoding:strDefault encoding to use if none is set in the commit
def show_blob(repo: RepoPath, blob: Blob, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout):

Write a blob to a stream.

Parameters
repo:RepoPathA Repo object
blob:BlobA Blob object
decode:Callable[[bytes], str]Function for decoding bytes to unicode string
outstream:TextIOA stream file to write to
def show_branch(repo: Repo | str = '.', branches: list[str | bytes] | None = None, all_branches: bool = False, remotes: bool = False, current: bool = False, topo_order: bool = False, more: int | None = None, list_branches: bool = False, independent_branches: bool = False, merge_base: bool = False) -> list[str]:

Display branches and their commits.

Parameters
repo:Repo | strPath to the repository
branches:list[str | bytes] | NoneList of specific branches to show (default: all local branches)
all_branches:boolShow both local and remote branches
remotes:boolShow only remote branches
current:boolInclude current branch if not specified
topo_order:boolShow in topological order instead of chronological
more:int | NoneShow N more commits beyond common ancestor (negative to show only headers)
list_branches:boolSynonym for more=-1 (show only branch headers)
independent_branches:boolShow only branches not reachable from others
merge_base:boolShow merge bases instead of commit list
Returns
list[str]List of output lines
def show_commit(repo: RepoPath, commit: Commit, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout):

Show a commit to a stream.

Parameters
repo:RepoPathA Repo object
commit:CommitA Commit object
decode:Callable[[bytes], str]Function for decoding bytes to unicode string
outstream:TextIOStream to write to
def show_index(index_path: str | os.PathLike[str], repo: str | os.PathLike[str] | Repo = '.') -> list[tuple[int, RawObjectID, int | None]]:

Show the contents of a pack index file.

Parameters
index_path:str | os.PathLike[str]Path to the pack index file
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object (for object format)
Returns
list[tuple[int, RawObjectID, int | None]]List of tuples (offset, sha, crc32) for each entry
Raises
FileNotFoundErrorIf the index file doesn't exist
def show_object(repo: RepoPath, obj: Tree | Blob | Commit | Tag, decode: Callable[[bytes], str], outstream: TextIO):

Show details of a git object.

def show_ref(repo: Repo | str = '.', patterns: list[str | bytes] | None = None, head: bool = False, branches: bool = False, tags: bool = False, dereference: bool = False, verify: bool = False) -> list[tuple[bytes, bytes]]:

List references in a local repository.

Returns: List of tuples with (sha, ref_name) or (sha, ref_name^{}) for dereferenced tags

Parameters
repo:Repo | strPath to the repository
patterns:list[str | bytes] | NoneOptional list of patterns to filter refs (matched from the end)
head:boolShow the HEAD reference
branches:boolLimit to local branches (refs/heads/)
tags:boolLimit to local tags (refs/tags/)
dereference:boolDereference tags into object IDs
verify:boolEnable stricter reference checking (exact path match)
Returns
list[tuple[bytes, bytes]]Undocumented
def show_tag(repo: RepoPath, tag: Tag, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout):

Print a tag to a stream.

Parameters
repo:RepoPathA Repo object
tag:TagA Tag object
decode:Callable[[bytes], str]Function for decoding bytes to unicode string
outstream:TextIOStream to write to
def show_tree(repo: RepoPath, tree: Tree, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout):

Print a tree to a stream.

Parameters
repo:RepoPathA Repo object
tree:TreeA Tree object
decode:Callable[[bytes], str]Function for decoding bytes to unicode string
outstream:TextIOStream to write to
def sparse_checkout(repo: str | os.PathLike[str] | Repo, patterns: list[str] | None = None, force: bool = False, cone: bool | None = None):

Perform a sparse checkout in the repository (either 'full' or 'cone mode').

Perform sparse checkout in either 'cone' (directory-based) mode or 'full pattern' (.gitignore) mode, depending on the cone parameter.

If cone is None, the mode is inferred from the repository's core.sparseCheckoutCone config setting.

Steps:
  1. If patterns is provided, write them to .git/info/sparse-checkout.
  2. Determine which paths in the index are included vs. excluded. - If cone=True, use "cone-compatible" directory-based logic. - If cone=False, use standard .gitignore-style matching.
  3. Update the index's skip-worktree bits and add/remove files in the working tree accordingly.
  4. If force=False, refuse to remove files that have local modifications.
Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object.
patterns:list[str] | NoneOptional list of sparse-checkout patterns to write.
force:boolWhether to force removal of locally modified files (default False).
cone:bool | NoneBoolean indicating cone mode (True/False). If None, read from config.
Returns
None
def stash_drop(repo: str | os.PathLike[str] | Repo, index: int):

Drop a stash from the stack.

def stash_list(repo: str | os.PathLike[str] | Repo) -> Iterator[tuple[int, tuple[bytes, bytes]]]:

List all stashes in a repository.

def stash_pop(repo: str | os.PathLike[str] | Repo):

Pop a stash from the stack.

def stash_push(repo: str | os.PathLike[str] | Repo):

Push a new stash onto the stack.

def status(repo: str | os.PathLike[str] | Repo = '.', ignored: bool = False, untracked_files: str = 'normal') -> GitStatus:

Returns staged, unstaged, and untracked changes relative to the HEAD.

Returns: GitStatus tuple,
staged - dict with lists of staged paths (filesystem paths as bytes) unstaged - list of unstaged paths (filesystem paths as bytes) untracked - list of untracked paths (filesystem paths as bytes)
Parameters
repo:str | os.PathLike[str] | RepoPath to repository or repository object
ignored:boolWhether to include ignored files in untracked
untracked_files:str
How to handle untracked files, defaults to "all":
"no": do not return untracked files "normal": return untracked directories, not their contents "all": include all files in untracked directories
Using untracked_files="no" can be faster than "all" when the worktree
contains many untracked files/directories.
Using untracked_files="normal" provides a good balance, only showing
directories that are entirely untracked without listing all their contents.
Returns
GitStatusUndocumented
def stripspace(text: str | bytes, *, strip_comments: bool = False, comment_char: str = '#', comment_lines: bool = False) -> bytes:

Strip unnecessary whitespace from text.

This function implements the functionality of git stripspace, commonly used to clean up commit messages and other text content.

The function performs the following operations:
  1. If comment_lines is True, prepend comment_char + space to each line
  2. Strip trailing whitespace from each line
  3. If strip_comments is True, remove lines starting with comment_char
  4. Collapse multiple consecutive blank lines into a single blank line
  5. Remove leading blank lines
  6. Remove trailing blank lines
  7. Ensure the text ends with a newline (unless empty)

Examples

>>> stripspace(b"  hello  \\n\\n\\nworld  \\n\\n")
b'hello\\n\\nworld\\n'
>>> stripspace(b"# comment\\ntext\\n", strip_comments=True)
b'text\\n'
>>> stripspace(b"line\\n", comment_lines=True)
b'# line\\n'
Parameters
text:str | bytesThe text to process (string or bytes)
strip_comments:boolIf True, remove lines that begin with comment_char
comment_char:strThe comment character to use (default: "#")
comment_lines:boolIf True, prepend comment_char to each line
Returns
bytesThe processed text as bytes
def submodule_add(repo: str | os.PathLike[str] | Repo, url: str, path: str | os.PathLike[str] | None = None, name: str | None = None):

Add a new submodule.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
url:strURL of repository to add as submodule
path:str | os.PathLike[str] | NonePath where submodule should live
name:str | NoneName for the submodule
def submodule_init(repo: str | os.PathLike[str] | Repo):

Initialize submodules.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
def submodule_list(repo: RepoPath) -> Iterator[tuple[str, str]]:

List submodules.

Parameters
repo:RepoPathPath to repository
Returns
Iterator[tuple[str, str]]Undocumented
def submodule_update(repo: str | os.PathLike[str] | Repo, paths: Sequence[str | bytes | os.PathLike[str]] | None = None, init: bool = False, force: bool = False, recursive: bool = False, errstream: BinaryIO | None = None):

Update submodules.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository
paths:Sequence[str | bytes | os.PathLike[str]] | NoneOptional list of specific submodule paths to update. If None, updates all.
init:boolIf True, initialize submodules first
force:boolForce update even if local changes exist
recursive:boolIf True, recursively update nested submodules
errstream:BinaryIO | NoneError stream for error messages
def switch(repo: str | os.PathLike[str] | Repo, target: str | bytes | Commit | Tag, create: str | bytes | None = None, force: bool = False, detach: bool = False):

Switch branches.

This is similar to 'git switch', allowing you to switch to a different branch or commit, updating both HEAD and the working tree.

Parameters
repo:str | os.PathLike[str] | RepoPath to repository or repository object
target:str | bytes | Commit | TagBranch name, tag, or commit SHA to switch to
create:str | bytes | NoneCreate a new branch at target before switching (like git switch -c)
force:boolForce switch even if there are local changes
detach:boolSwitch to a commit in detached HEAD state (like git switch --detach)
Raises
CheckoutErrorIf switch cannot be performed due to conflicts
KeyErrorIf the target reference cannot be found
ValueErrorIf both create and detach are specified
def symbolic_ref(repo: RepoPath, ref_name: str | bytes, force: bool = False):

Set git symbolic ref into HEAD.

Parameters
repo:RepoPathpath to the repository
ref_name:str | bytesshort name of the new ref
force:boolforce settings without checking if it exists in refs/heads
def tag_create(repo: RepoPath, tag: str | bytes, author: str | bytes | None = None, message: str | bytes | None = None, annotated: bool = False, objectish: str | bytes = 'HEAD', tag_time: int | None = None, tag_timezone: int | None = None, sign: bool | None = None, encoding: str | None = None):

Creates a tag in git via dulwich calls.

Parameters
repo:RepoPathPath to repository
tag:str | bytestag string
author:str | bytes | Nonetag author (optional, if annotated is set)
message:str | bytes | Nonetag message (optional)
annotated:boolwhether to create an annotated tag
objectish:str | bytesobject the tag should point at, defaults to HEAD
tag_time:int | NoneOptional time for annotated tag
tag_timezone:int | NoneOptional timezone for annotated tag
sign:bool | NoneGPG Sign the tag (bool, defaults to False, pass True to use default GPG key, pass a str containing Key ID to use a specific GPG key)
encoding:str | NoneEncoding to use for tag messages
def tag_delete(repo: RepoPath, name: str | bytes):

Remove a tag.

Parameters
repo:RepoPathPath to repository
name:str | bytesName of tag to remove
def tag_list(repo: RepoPath, outstream: TextIO = sys.stdout) -> list[Ref]:

List all tags.

Parameters
repo:RepoPathPath to repository
outstream:TextIOStream to write tags to
Returns
list[Ref]Undocumented
def tree_path_to_fs_path(tree_path: bytes, tree_encoding: str = DEFAULT_ENCODING) -> bytes:

Convert a git tree path to a filesystem path (relative).

Returns: Filesystem path as bytes (with os.sep, filesystem encoding)

Parameters
tree_path:bytesPath from git tree (bytes with "/" separators, UTF-8 encoded)
tree_encoding:strEncoding used for tree paths (default: utf-8)
Returns
bytesUndocumented
def unpack_objects(pack_path: str | os.PathLike[str], target: str | os.PathLike[str] = '.') -> int:

Unpack objects from a pack file into the repository.

Parameters
pack_path:str | os.PathLike[str]Path to the pack file to unpack
target:str | os.PathLike[str]Path to the repository to unpack into
Returns
intNumber of objects unpacked
def update_head(repo: RepoPath, target: str | bytes, detached: bool = False, new_branch: str | bytes | None = None):

Update HEAD to point at a new branch/commit.

Note that this does not actually update the working tree.

Parameters
repo:RepoPathPath to the repository
target:str | bytesBranch or committish to switch to
detached:boolCreate a detached head
new_branch:str | bytes | NoneNew branch to create
def update_ref(repo: str | os.PathLike[str] | Repo, ref: str | bytes, new_value: str | bytes | None, old_value: str | bytes | None = None, message: str | bytes | None = None):

Update the object name stored in a ref safely.

Parameters
repo:str | os.PathLike[str] | RepoPath to the repository or a Repo object
ref:str | bytesName of the ref to update (e.g., 'refs/heads/main', 'HEAD')
new_value:str | bytes | NoneNew object SHA to set the ref to (None to delete)
old_value:str | bytes | NoneOptional old value to verify before updating (for atomic updates)
message:str | bytes | NoneOptional message for the reflog
Raises
ValueErrorIf the old value doesn't match
def update_server_info(repo: RepoPath = '.'):

Update server info files for a repository.

Parameters
repo:RepoPathpath to the repository
def upload_pack(path: str | os.PathLike[str] = '.', inf: BinaryIO | None = None, outf: BinaryIO | None = None) -> int:

Upload a pack file after negotiating its contents using smart protocol.

Parameters
path:str | os.PathLike[str]Path to the repository
inf:BinaryIO | NoneInput stream to communicate with client
outf:BinaryIO | NoneOutput stream to communicate with client
Returns
intUndocumented
def var(repo: RepoPath = '.', variable: str = 'GIT_AUTHOR_IDENT') -> str:

Get the value of a specific Git logical variable.

Parameters
repo:RepoPathPath to the repository
variable:strThe variable to query (e.g., 'GIT_AUTHOR_IDENT')
Returns
strThe value of the requested variable as a string
Raises
KeyErrorIf the requested variable has no value
def var_list(repo: RepoPath = '.') -> dict[str, str]:

List all Git logical variables.

Parameters
repo:RepoPathPath to the repository
Returns
dict[str, str]A dictionary of all logical variables with their values
def verify_commit(repo: RepoPath, committish: str | bytes = 'HEAD', keyids: list[str] | None = None):

Verify signature on a commit.

Parameters
repo:RepoPathPath to repository
committish:str | bytesCommit to verify (defaults to HEAD)
keyids:list[str] | NoneOptional list of trusted key IDs. If provided, the commit must be signed by one of these keys. If not provided, just verifies that the commit has a valid signature.
Raises
gpg.errors.BadSignaturesif GPG signature verification fails
gpg.errors.MissingSignaturesif commit was not signed by a key specified in keyids
def verify_tag(repo: RepoPath, tagname: str | bytes, keyids: list[str] | None = None):

Verify signature on a tag.

Parameters
repo:RepoPathPath to repository
tagname:str | bytesName of tag to verify
keyids:list[str] | NoneOptional list of trusted key IDs. If provided, the tag must be signed by one of these keys. If not provided, just verifies that the tag has a valid signature.
Raises
gpg.errors.BadSignaturesif GPG signature verification fails
gpg.errors.MissingSignaturesif tag was not signed by a key specified in keyids
def web_daemon(path: str | os.PathLike[str] = '.', address: str | None = None, port: int | None = None):

Run a daemon serving Git requests over HTTP.

Parameters
path:str | os.PathLike[str]Path to the directory to serve
address:str | NoneOptional address to listen on (defaults to ::)
port:int | NoneOptional port to listen on (defaults to 80)
def worktree_add(repo: RepoPath = '.', path: str | os.PathLike[str] | None = None, branch: str | bytes | None = None, commit: str | bytes | None = None, detach: bool = False, force: bool = False) -> str:

Add a new worktree.

Parameters
repo:RepoPathPath to repository
path:str | os.PathLike[str] | NonePath for new worktree
branch:str | bytes | NoneBranch to checkout (creates if doesn't exist)
commit:str | bytes | NoneSpecific commit to checkout
detach:boolCreate with detached HEAD
force:boolForce creation even if branch is already checked out
Returns
strPath to the newly created worktree
def worktree_list(repo: RepoPath = '.') -> list[WorkTreeInfo]:

List all worktrees for a repository.

Parameters
repo:RepoPathPath to repository
Returns
list[WorkTreeInfo]List of WorkTreeInfo objects
def worktree_lock(repo: RepoPath = '.', path: str | os.PathLike[str] | None = None, reason: str | None = None):

Lock a worktree to prevent it from being pruned.

Parameters
repo:RepoPathPath to repository
path:str | os.PathLike[str] | NonePath to worktree to lock
reason:str | NoneOptional reason for locking
def worktree_move(repo: RepoPath = '.', old_path: str | os.PathLike[str] | None = None, new_path: str | os.PathLike[str] | None = None):

Move a worktree to a new location.

Parameters
repo:RepoPathPath to repository
old_path:str | os.PathLike[str] | NoneCurrent path of worktree
new_path:str | os.PathLike[str] | NoneNew path for worktree
def worktree_prune(repo: RepoPath = '.', dry_run: bool = False, expire: int | None = None) -> list[str]:

Prune worktree administrative files.

Parameters
repo:RepoPathPath to repository
dry_run:boolOnly show what would be removed
expire:int | NoneOnly prune worktrees older than this many seconds
Returns
list[str]List of pruned worktree names
def worktree_remove(repo: RepoPath = '.', path: str | os.PathLike[str] | None = None, force: bool = False):

Remove a worktree.

Parameters
repo:RepoPathPath to repository
path:str | os.PathLike[str] | NonePath to worktree to remove
force:boolForce removal even if there are local changes
def worktree_repair(repo: RepoPath = '.', paths: list[str | os.PathLike[str]] | None = None) -> list[str]:

Repair worktree administrative files.

Parameters
repo:RepoPathPath to repository
paths:list[str | os.PathLike[str]] | NoneOptional list of worktree paths to repair. If None, repairs connections from the main repository to all linked worktrees.
Returns
list[str]List of repaired worktree paths
def worktree_unlock(repo: RepoPath = '.', path: str | os.PathLike[str] | None = None):

Unlock a worktree.

Parameters
repo:RepoPathPath to repository
path:str | os.PathLike[str] | NonePath to worktree to unlock
def write_commit_graph(repo: RepoPath = '.', reachable: bool = True):

Write a commit graph file for a repository.

Parameters
repo:RepoPathpath to the repository or a Repo object
reachable:boolif True, include all commits reachable from refs. if False, only include direct ref targets.
def write_tree(repo: RepoPath) -> bytes:

Write a tree object from the index.

Returns: tree id for the tree that was written

Parameters
repo:RepoPathRepository for which to write tree
Returns
bytesUndocumented
DEFAULT_ENCODING: str =

Undocumented

Value
'utf-8'
INFINITE_DEPTH: int =

Undocumented

Value
2147483647
T =

Undocumented

Value
TypeVar('T',
        bound='BaseRepo')
default_bytes_err_stream: BinaryIO =

Undocumented

default_bytes_out_stream: BinaryIO =

Undocumented

GitStatus =

Undocumented

RepoPath =

Undocumented

def _canonical_part(url: str) -> str:

Undocumented

def _check_uncommitted_changes(repo: Repo, target_tree_id: ObjectID, force: bool = False):

Check for uncommitted changes that would conflict with a checkout/switch.

Parameters
repo:RepoRepository object
target_tree_id:ObjectIDTree ID to check conflicts against
force:boolIf True, skip the check
Raises
CheckoutErrorIf there are conflicting local changes
def _do_merge(r: Repo, merge_commit_id: ObjectID, no_commit: bool = False, no_ff: bool = False, message: bytes | None = None, author: bytes | None = None, committer: bytes | None = None) -> tuple[ObjectID | None, list[bytes]]:

Internal merge implementation that operates on an open repository.

Parameters
r:RepoOpen repository object
merge_commit_id:ObjectIDSHA of commit to merge
no_commit:boolIf True, do not create a merge commit
no_ff:boolIf True, force creation of a merge commit
message:bytes | NoneOptional merge commit message
author:bytes | NoneOptional author for merge commit
committer:bytes | NoneOptional committer for merge commit
Returns
tuple[ObjectID | None, list[bytes]]Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None if no_commit=True or there were conflicts
def _do_octopus_merge(r: Repo, merge_commit_ids: list[ObjectID], no_commit: bool = False, no_ff: bool = False, message: bytes | None = None, author: bytes | None = None, committer: bytes | None = None) -> tuple[ObjectID | None, list[bytes]]:

Internal octopus merge implementation that operates on an open repository.

Parameters
r:RepoOpen repository object
merge_commit_ids:list[ObjectID]List of commit SHAs to merge
no_commit:boolIf True, do not create a merge commit
no_ff:boolIf True, force creation of a merge commit (ignored for octopus)
message:bytes | NoneOptional merge commit message
author:bytes | NoneOptional author for merge commit
committer:bytes | NoneOptional committer for merge commit
Returns
tuple[ObjectID | None, list[bytes]]Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None if no_commit=True or there were conflicts
def _filter_transport_kwargs(**kwargs: object) -> TransportKwargs:

Filter kwargs to only include parameters accepted by get_transport_and_path.

Parameters
**kwargs:objectArbitrary keyword arguments
Returns
TransportKwargsDictionary containing only the kwargs that get_transport_and_path accepts
def _find_reachable_tags(r: BaseRepo, pushed_shas: set[ObjectID], already_included: set[Ref], remote_refs: dict[Ref, ObjectID]) -> Iterator[tuple[Ref, ObjectID]]:

Yield annotated tags whose targets are reachable from pushed commits.

Parameters
r:BaseRepoLocal repository
pushed_shas:set[ObjectID]SHAs being pushed (non-deletion)
already_included:set[Ref]Refs already being pushed
remote_refs:dict[Ref, ObjectID]Current remote refs
Returns
Iterator[tuple[Ref, ObjectID]]Undocumented
def _get_branch_merge_status(repo: RepoPath) -> Iterator[tuple[bytes, bool]]:

Get merge status for all branches relative to current HEAD.

Parameters
repo:RepoPathPath to the repository
Returns
Iterator[tuple[bytes, bool]]Undocumented
Yields
tuple of (branch_name, is_merged) where
  • branch_name: Branch name without refs/heads/ prefix
  • is_merged: True if branch is merged into HEAD, False otherwise
def _get_current_head_tree(repo: Repo) -> ObjectID | None:

Get the current HEAD tree ID.

Parameters
repo:RepoRepository object
Returns
ObjectID | NoneTree ID of current HEAD, or None if no HEAD exists (empty repo)
def _get_reflog_message(default_message: bytes, explicit_message: bytes | None = None) -> bytes:

Get reflog message, checking GIT_REFLOG_ACTION environment variable.

Parameters
default_message:bytesDefault message to use if no explicit message or env var
explicit_message:bytes | NoneExplicit message passed as argument (takes precedence)
Returns
The reflog message with priority
  1. explicit_message if provided
  2. GIT_REFLOG_ACTION environment variable if set
  3. default_message otherwise
def _get_variables(repo: RepoPath = '.') -> dict[str, str]:

Internal function to get all Git logical variables.

Parameters
repo:RepoPathPath to the repository
Returns
dict[str, str]A dictionary of all logical variables with values
def _get_worktree_update_config(repo: Repo) -> tuple[bool, Callable[[bytes], bool], Callable[[(str | bytes | os.PathLike[str]), (str | bytes | os.PathLike[str])], None]]:

Get configuration for working tree updates.

Parameters
repo:RepoRepository object
Returns
tuple[bool, Callable[[bytes], bool], Callable[[(str | bytes | os.PathLike[str]), (str | bytes | os.PathLike[str])], None]]Tuple of (honor_filemode, validate_path_element, symlink_fn)
def _is_subdir(subdir: str | os.PathLike[str], parentdir: str | os.PathLike[str]) -> bool:

Check whether subdir is parentdir or a subdir of parentdir.

If parentdir or subdir is a relative path, it will be disamgibuated relative to the pwd.

def _make_branch_ref(name: str | bytes) -> Ref:

Undocumented

def _make_replace_ref(name: str | bytes | ObjectID) -> Ref:

Undocumented

def _noop_context_manager(obj: T) -> Iterator[T]:

Context manager that has the same api as closing but does nothing.

def _perform_tree_switch(repo: Repo, current_tree_id: ObjectID | None, target_tree_id: ObjectID, force: bool = False):

Perform the actual working tree switch.

Parameters
repo:RepoRepository object
current_tree_id:ObjectID | NoneCurrent tree ID (or None for empty repo)
target_tree_id:ObjectIDTarget tree ID to switch to
force:boolIf True, force removal of untracked files and allow overwriting modified files
def _precompose_unicode_path(path: str) -> str:

Normalize a filesystem path to NFC (precomposed) Unicode form.

On macOS, HFS+/APFS filesystems return filenames in NFD (decomposed) form. This function normalizes them to NFC so they match the paths stored in the git index.

def _quote_path(path: str) -> str:

Quote a path using C-style quoting similar to git's core.quotePath.

Parameters
path:strPath to quote
Returns
strQuoted path string
def _select_push_refs(r: BaseRepo, remote_refs: dict[Ref, ObjectID], refspecs: str | bytes | Sequence[str | bytes] | None, *, force: bool = False, mirror_mode: bool = False, all: bool = False, tags: bool = False, delete: bool = False) -> list[tuple[Ref | None, Ref | None, bool]]:

Select which refs to push based on mode flags or user refspecs.

Returns a list of (local_ref, remote_ref, force) tuples. local_ref is None for deletions.

Parameters
r:BaseRepoLocal repository
remote_refs:dict[Ref, ObjectID]Current remote refs dict
refspecs:str | bytes | Sequence[str | bytes] | NoneUser-provided refspecs (may be None)
force:boolForce overwriting refs
mirror_mode:boolPush all refs
all:boolPush all branches
tags:boolPush all tags
delete:boolDelete the specified remote refs
Returns
list[tuple[Ref | None, Ref | None, bool]]Undocumented
def _walk_working_dir_paths(frompath: str | bytes | os.PathLike[str], basepath: str | bytes | os.PathLike[str], prune_dirnames: Callable[[str, list[str]], list[str]] | None = None, precompose_unicode: bool = False) -> Iterator[tuple[str | bytes, bool]]:

Get path, is_dir for files in working dir from frompath.

Parameters
frompath:str | bytes | os.PathLike[str]Path to begin walk
basepath:str | bytes | os.PathLike[str]Path to compare to
prune_dirnames:Callable[[str, list[str]], list[str]] | NoneOptional callback to prune dirnames during os.walk dirnames will be set to result of prune_dirnames(dirpath, dirnames)
precompose_unicode:boolIf True, normalize paths to NFC Unicode form
Returns
Iterator[tuple[str | bytes, bool]]Undocumented