module documentation

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

Currently implemented:
  • archive
  • add
  • branch{_create,_delete,_list}
  • check-ignore
  • checkout
  • clone
  • commit
  • commit-tree
  • daemon
  • describe
  • diff-tree
  • fetch
  • init
  • ls-files
  • ls-remote
  • ls-tree
  • pull
  • push
  • rm
  • remote{_add}
  • receive-pack
  • reset
  • submodule_add
  • submodule_init
  • submodule_list
  • rev-list
  • tag{_create,_delete,_list}
  • upload-pack
  • update-server-info
  • status
  • symbolic-ref

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

Class NoneStream Fallback if stdout or stderr are unavailable, does nothing.
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 archive Create an archive.
Function branch_create Create a branch.
Function branch_delete Delete a branch.
Function branch_list List all branches.
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 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 Undocumented
Function commit_encode Undocumented
Function commit_tree Create a new commit object.
Function daemon Run a daemon serving Git requests over TCP/IP.
Function describe Describe the repository version.
Function diff_tree Compares the content and mode of blobs found via two tree objects.
Function fetch Fetch objects from a remote server.
Function find_unique_abbrev For now, just return 7 characters.
Function fsck Check a repository.
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 Undocumented
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 https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt Returns: A tuple containing author timezone, committer timezone
Function init Create a new git repository.
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 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. 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.
Function pack_objects Pack objects into a 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_status Print a simple status summary, listing changed files.
Function print_tag Write a human-readable tag.
Function pull Pull from remote via dulwich.client
Function push Remote push with dulwich via dulwich.client
Function receive_pack Receive a pack file after negotiating its contents using smart protocol.
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 reset Reset current HEAD to the specified state.
Function reset_file Reset the file to specific commit or branch.
Function rev_list Lists commit objects in reverse chronological order.
Function show Print the changes in a commit.
Function show_blob Write a blob to a stream.
Function show_commit Show a commit to a stream.
Function show_object Undocumented
Function show_tag Print a tag to a stream.
Function show_tree Print a tree to a stream.
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 submodule_add Add a new submodule.
Function submodule_init Initialize submodules.
Function submodule_list List submodules.
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 update_head Update HEAD to point at a new branch/commit.
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 web_daemon Run a daemon serving Git requests over HTTP.
Function write_tree Write a tree object from the index.
Constant DEFAULT_ENCODING Undocumented
Variable default_bytes_err_stream Undocumented
Variable default_bytes_out_stream Undocumented
Variable GitStatus Undocumented
Function _canonical_part Undocumented
Function _is_subdir Check whether subdir is parentdir or a subdir of parentdir
Function _make_branch_ref Undocumented
Function _make_tag_ref Undocumented
Function _noop_context_manager Context manager that has the same api as closing but does nothing.
Function _walk_working_dir_paths Get path, is_dir for files in working dir from frompath
def active_branch(repo):

Return the active branch in the repository, if any.

Parameters
repoRepository to open
Returns
branch name
Raises
KeyErrorif the repository does not have a working tree
IndexErrorif HEAD is floating
def add(repo='.', paths=None):

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.

Parameters
repoRepository for the files
pathsPaths to add. No value passed stages all modified files.
def archive(repo, committish=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream):

Create an archive.

Parameters
repoPath of repository for which to generate an archive.
committishCommit SHA1 or ref to use
outstreamOutput stream (defaults to stdout)
errstreamError stream (defaults to stderr)
def branch_create(repo, name, objectish=None, force=False):

Create a branch.

Parameters
repoPath to the repository
nameName of the new branch
objectishTarget object to point new branch at (defaults to HEAD)
forceForce creation of branch, even if it already exists
def branch_delete(repo, name):

Delete a branch.

Parameters
repoPath to the repository
nameName of the branch
def branch_list(repo):

List all branches.

Parameters
repoPath to the repository
def check_diverged(repo, current_sha, new_sha):

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

Parameters
repoRepository object
current_shaCurrent head sha
new_shaNew head sha
def check_ignore(repo, paths, no_index=False):

Debug gitignore files.

Returns: List of ignored files

Parameters
repoPath to the repository
pathsList of paths to check for
no_indexDon't check index
def check_mailmap(repo, contact):

Check canonical name and email of contact.

Returns: Canonical contact data

Parameters
repoPath to the repository
contactContact name and/or email
def clean(repo='.', target_dir=None):

Remove any untracked files from the target directory recursively

Equivalent to running git clean -fd in target_dir.

Parameters
repoRepository where the files may be tracked
target_dirDirectory to clean - current directory if None
def clone(source, target=None, bare=False, checkout=None, errstream=default_bytes_err_stream, outstream=None, origin='origin', depth=None, branch=None, config=None, **kwargs):

Clone a local or remote git repository.

Returns: The new repository

Parameters
sourcePath or URL for source repository
targetPath to target repository (optional)
bareWhether or not to create a bare repository
checkoutWhether or not to check-out HEAD after cloning
errstreamOptional stream to write progress to
outstreamOptional stream to write progress to (deprecated)
origin:Optional[str]Name of remote from the repository used to clone
depth:Optional[int]Depth to fetch at
branch:Optional[Union[str, bytes]]Optional branch or tag to be used as HEAD in the new repository instead of the cloned repository's HEAD.
config:Optional[Config]Configuration to use
**kwargsUndocumented
def commit(repo='.', message=None, author=None, author_timezone=None, committer=None, commit_timezone=None, encoding=None, no_verify=False, signoff=False):

Create a new commit.

Returns: SHA1 of the new commit

Parameters
repoPath to repository
messageOptional commit message
authorOptional author name and email
author_timezoneAuthor timestamp timezone
committerOptional committer name and email
commit_timezoneCommit timestamp timezone
encodingUndocumented
no_verifySkip pre-commit and commit-msg hooks
signoffGPG Sign the commit (bool, defaults to False, pass True to use default GPG key, pass a str containing Key ID to use a specific GPG key)
def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):

Undocumented

def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING):

Undocumented

def commit_tree(repo, tree, message=None, author=None, committer=None):

Create a new commit object.

Parameters
repoPath to repository
treeAn existing tree object
messageUndocumented
authorOptional author name and email
committerOptional committer name and email
def daemon(path='.', address=None, port=None):

Run a daemon serving Git requests over TCP/IP.

Parameters
pathPath to the directory to serve.
addressOptional address to listen on (defaults to ::)
portOptional port to listen on (defaults to TCP_GIT_PORT)
def describe(repo, abbrev=7):

Describe the repository version.

Returns: a string description of the current git revision

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

Parameters
repogit repository
abbrevnumber of characters of commit to take, default is 7
def diff_tree(repo, old_tree, new_tree, outstream=default_bytes_out_stream):

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

Parameters
repoPath to repository
old_treeId of old tree
new_treeId of new tree
outstreamStream to write to
def fetch(repo, remote_location=None, outstream=sys.stdout, errstream=default_bytes_err_stream, message=None, depth=None, prune=False, prune_tags=False, force=False, **kwargs):

Fetch objects from a remote server.

Parameters
repoPath to the repository
remote_locationString identifying a remote server
outstreamOutput stream (defaults to stdout)
errstreamError stream (defaults to stderr)
messageReflog message (defaults to b"fetch: from <remote_name>")
depthDepth to fetch at
prunePrune remote removed refs
prune_tagsPrune reomte removed tags
forceUndocumented
**kwargsUndocumented
Returns
Dictionary with refs on the remote
def find_unique_abbrev(object_store, object_id):

For now, just return 7 characters.

def fsck(repo):

Check a repository.

Returns: Iterator over errors/warnings

Parameters
repoA path to the repository
def get_branch_remote(repo):

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

Parameters
repoRepository to open
Returns
remote name
Raises
KeyErrorif the repository does not have a working tree
def get_object_by_path(repo, path, committish=None):

Get an object by path.

Returns: A ShaFile object

Parameters
repoA path to the repository
pathPath to look up
committishCommit to look up path in
def get_remote_repo(repo, remote_location=None):

Undocumented

Parameters
repo:RepoUndocumented
remote_location:Optional[Union[str, bytes]]Undocumented
Returns
Tuple[Optional[str], str]Undocumented
def get_tree_changes(repo):

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

Returns: dict with lists for each type of change

Parameters
reporepo path or object
def get_untracked_paths(frompath, basepath, index, exclude_ignored=False, untracked_files='all'):

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
frompathPath to walk
basepathPath to compare to
indexIndex to check against
exclude_ignoredWhether to exclude ignored paths
untracked_filesHow to handle untracked files: - "no": return an empty list - "all": return all files in untracked directories - "normal": Not implemented
def get_user_timezones():

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

def init(path='.', bare=False):

Create a new git repository.

Returns: A Repo instance

Parameters
pathPath to repository.
bareWhether to create a bare repository.
def log(repo='.', paths=None, outstream=sys.stdout, max_entries=None, reverse=False, name_status=False):

Write commit logs.

Parameters
repoPath to repository
pathsOptional set of specific paths to print entries for
outstreamStream to write log output to
max_entriesOptional maximum number of entries to display
reverseReverse order in which entries are printed
name_statusPrint name status
def ls_files(repo):

List all files in an index.

def ls_remote(remote, config=None, **kwargs):

List the refs in a remote.

Parameters
remoteRemote repository location
config:Optional[Config]Configuration to use
**kwargsUndocumented
Returns
Dictionary with remote refs
def ls_tree(repo, treeish=b'HEAD', outstream=sys.stdout, recursive=False, name_only=False):

List contents of a tree.

Parameters
repoPath to the repository
treeishTree id to list
outstreamOutput stream (defaults to stdout)
recursiveWhether to recursively list files
name_onlyOnly print item name
def open_repo(path_or_repo):

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

def open_repo_closing(path_or_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, object_ids, packf, idxf, delta_window_size=None):

Pack objects into a file.

Parameters
repoPath to the repository
object_idsList of object ids to write
packfFile-like object to write to
idxfFile-like object to write to (can be None)
delta_window_sizeUndocumented
def parse_timezone_format(tz_str):

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_strdatetime string
Raises
TimezoneFormatErrorif timezone information cannot be extracted
def path_to_tree_path(repopath, path, tree_encoding=DEFAULT_ENCODING):

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
repopathRepository path, absolute or relative to the cwd
pathA path, absolute or relative to the cwd
tree_encodingUndocumented
def print_commit(commit, decode, outstream=sys.stdout):

Write a human-readable commit log entry.

Parameters
commitA Commit object
decodeUndocumented
outstreamA stream file to write to
def print_name_status(changes):

Print a simple status summary, listing changed files.

def print_tag(tag, decode, outstream=sys.stdout):

Write a human-readable tag.

Parameters
tagA Tag object
decodeFunction for decoding bytes to unicode string
outstreamA stream to write to
def pull(repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, fast_forward=True, force=False, **kwargs):

Pull from remote via dulwich.client

Parameters
repoPath to repository
remote_locationLocation of the remote
refspecsrefspecs to fetch
outstreamA stream file to write to output
errstreamA stream file to write to errors
fast_forwardUndocumented
forceUndocumented
**kwargsUndocumented
def push(repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, force=False, **kwargs):

Remote push with dulwich via dulwich.client

Parameters
repoPath to repository
remote_locationLocation of the remote
refspecsRefs to push to remote
outstreamA stream file to write output
errstreamA stream file to write errors
forceForce overwriting refs
**kwargsUndocumented
def receive_pack(path='.', inf=None, outf=None):

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

Parameters
pathPath to the repository
infInput stream to communicate with client
outfOutput stream to communicate with client
def remote_add(repo, name, url):

Add a remote.

Parameters
repo:RepoPath to the repository
name:Union[bytes, str]Remote name
url:Union[bytes, str]Remote URL
def remote_remove(repo, name):

Remove a remote

Parameters
repo:RepoPath to the repository
name:Union[bytes, str]Remote name
def remove(repo='.', paths=None, cached=False):

Remove files from the staging area.

Parameters
repoRepository for the files
pathsPaths to remove
cachedUndocumented
def repack(repo):

Repack loose files in a repository.

Currently this only packs loose objects.

Parameters
repoPath to the repository
def reset(repo, mode, treeish='HEAD'):

Reset current HEAD to the specified state.

Parameters
repoPath to repository
modeMode ("hard", "soft", "mixed")
treeishTreeish to reset to
def reset_file(repo, file_path, target=b'HEAD', symlink_fn=None):

Reset the file to specific commit or branch.

Parameters
repodulwich Repo object
file_path:strfile to reset, relative to the repository path
target:bytesbranch or commit or b'HEAD' to reset
symlink_fnUndocumented
def rev_list(repo, commits, outstream=sys.stdout):

Lists commit objects in reverse chronological order.

Parameters
repoPath to repository
commitsCommits over which to iterate
outstreamStream to write to
def show(repo='.', objects=None, outstream=sys.stdout, default_encoding=DEFAULT_ENCODING):

Print the changes in a commit.

Parameters
repoPath to repository
objectsObjects to show (defaults to [HEAD])
outstreamStream to write to
default_encodingDefault encoding to use if none is set in the commit
def show_blob(repo, blob, decode, outstream=sys.stdout):

Write a blob to a stream.

Parameters
repoA Repo object
blobA Blob object
decodeFunction for decoding bytes to unicode string
outstreamA stream file to write to
def show_commit(repo, commit, decode, outstream=sys.stdout):

Show a commit to a stream.

Parameters
repoA Repo object
commitA Commit object
decodeFunction for decoding bytes to unicode string
outstreamStream to write to
def show_object(repo, obj, decode, outstream):

Undocumented

def show_tag(repo, tag, decode, outstream=sys.stdout):

Print a tag to a stream.

Parameters
repoA Repo object
tagA Tag object
decodeFunction for decoding bytes to unicode string
outstreamStream to write to
def show_tree(repo, tree, decode, outstream=sys.stdout):

Print a tree to a stream.

Parameters
repoA Repo object
treeA Tree object
decodeFunction for decoding bytes to unicode string
outstreamStream to write to
def stash_drop(repo, index):

Drop a stash from the stack.

def stash_list(repo):

List all stashes in a repository.

def stash_pop(repo, index):

Pop a stash from the stack.

def stash_push(repo):

Push a new stash onto the stack.

def status(repo='.', ignored=False, untracked_files='all'):

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

Note: untracked_files="normal" (git's default) is not implemented.

Returns: GitStatus tuple,
staged - dict with lists of staged paths (diff index/HEAD) unstaged - list of unstaged paths (diff index/working-tree) untracked - list of untracked, un-ignored & non-.git paths
Parameters
repoPath to repository or repository object
ignoredWhether to include ignored files in untracked
untracked_files
How to handle untracked files, defaults to "all":
"no": do not return untracked files "all": include all files in untracked directories
Using untracked_files="no" can be faster than "all" when the worktreee
contains many untracked files/directories.
def submodule_add(repo, url, path=None, name=None):

Add a new submodule.

Parameters
repoPath to repository
urlURL of repository to add as submodule
pathPath where submodule should live
nameUndocumented
def submodule_init(repo):

Initialize submodules.

Parameters
repoPath to repository
def submodule_list(repo):

List submodules.

Parameters
repoPath to repository
def symbolic_ref(repo, ref_name, force=False):

Set git symbolic ref into HEAD.

Parameters
repopath to the repository
ref_nameshort name of the new ref
forceforce settings without checking if it exists in refs/heads
def tag_create(repo, tag, author=None, message=None, annotated=False, objectish='HEAD', tag_time=None, tag_timezone=None, sign=False, encoding=DEFAULT_ENCODING):

Creates a tag in git via dulwich calls:

Parameters
repoPath to repository
tagtag string
authortag author (optional, if annotated is set)
messagetag message (optional)
annotatedwhether to create an annotated tag
objectishobject the tag should point at, defaults to HEAD
tag_timeOptional time for annotated tag
tag_timezoneOptional timezone for annotated tag
signGPG 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)
encodingUndocumented
def tag_delete(repo, name):

Remove a tag.

Parameters
repoPath to repository
nameName of tag to remove
def tag_list(repo, outstream=sys.stdout):

List all tags.

Parameters
repoPath to repository
outstreamStream to write tags to
def update_head(repo, target, detached=False, new_branch=None):

Update HEAD to point at a new branch/commit.

Note that this does not actually update the working tree.

Parameters
repoPath to the repository
targetBranch or committish to switch to
detachedCreate a detached head
new_branchNew branch to create
def update_server_info(repo='.'):

Update server info files for a repository.

Parameters
repopath to the repository
def upload_pack(path='.', inf=None, outf=None):

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

Parameters
pathPath to the repository
infInput stream to communicate with client
outfOutput stream to communicate with client
def web_daemon(path='.', address=None, port=None):

Run a daemon serving Git requests over HTTP.

Parameters
pathPath to the directory to serve
addressOptional address to listen on (defaults to ::)
portOptional port to listen on (defaults to 80)
def write_tree(repo):

Write a tree object from the index.

Returns: tree id for the tree that was written

Parameters
repoRepository for which to write tree
DEFAULT_ENCODING: str =

Undocumented

Value
'utf-8'
default_bytes_err_stream =

Undocumented

default_bytes_out_stream =

Undocumented

GitStatus =

Undocumented

def _canonical_part(url):

Undocumented

Parameters
url:strUndocumented
Returns
strUndocumented
def _is_subdir(subdir, parentdir):

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):

Undocumented

def _make_tag_ref(name):

Undocumented

@contextmanager
def _noop_context_manager(obj):

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

def _walk_working_dir_paths(frompath, basepath, prune_dirnames=None):

Get path, is_dir for files in working dir from frompath

Parameters
frompathPath to begin walk
basepathPath to compare to
prune_dirnamesOptional callback to prune dirnames during os.walk dirnames will be set to result of prune_dirnames(dirpath, dirnames)