class documentation

class GitRepository(object):

View In Hierarchy

Represents a git repository at path. It's currently assumed that the git repository is stored in a directory named .git/ below path.

Raises
GitRepositoryErroron git errors GitRepositoryError is raised by all methods.
Class Method clone Clone a git repository at remote to path.
Class Method create Create a repository at path
Class Method git_inout As _git_inout but can be used without an instance
Static Method ensure_refs_heads Make sure a branch name is prefixed with `refs/heads'
Static Method strip_sha1 Strip a given sha1 and check if the resulting hash has the expected length.
Method __init__ No summary
Method abort_merge Abort a merge
Method add_files Add files to a the repository
Method add_remote_repo Add a tracked remote repository
Method add_submodule Add a submodule
Method apply_patch Apply a patch using git apply
Method archive Create an archive from a treeish
Method branch_contains Check if branch branch contains commit commit
Method checkout Checkout treeish
Method clean Remove untracked files from the working tree.
Method collect_garbage Cleanup unnecessary files and optimize the local repository
Method commit_all Commit all changes to the repository
Method commit_dir Replace the current tip of branch branch with the contents from unpack_dir
Method commit_files Commit the given files to the repository
Method commit_staged Commit currently staged files to the repository
Method commit_tree Commit a tree with commit msg msg and parents parents
Method create_branch Create a new branch
Method create_tag Create a new tag.
Method delete_branch Delete branch branch
Method delete_tag Delete a tag named tag
Method describe Describe commit, relative to the latest tag reachable from it.
Method diff Diff two git repository objects
Method diff_status Get file-status of two git repository objects
Method fetch Download objects and refs from another repository.
Method find_branch_tag Find the closest tag on a certain branch to a given commit
Method find_tag Find the closest tag to a given commit
Method force_head Force HEAD to a specific commit
Method format_patches Output the commits between start and end as patches in output_dir.
Method get_author_info Determine a sane values for author name and author email from git's config and environment variables.
Method get_branch On what branch is the current working copy
Method get_commit_info Look up data of a specific commit-ish. Dereferences given commit-ish to the commit it points to.
Method get_commits Get commits from since to until touching paths
Method get_config Gets the config value associated with name
Method get_local_branches Get a list of local branches
Method get_merge_base Get the common ancestor between two commits
Method get_merge_branch Get the branch we'd merge from
Method get_obj_type Get type of a git repository object
Method get_remote_branches Get a list of remote branches
Method get_remote_repos Get all remote repositories
Method get_remotes Get a list of remote repositories
Method get_subject Gets the subject of a commit.
Method get_submodules List the submodules of treeish
Method get_tags List tags
Method get_upstream_branch Get upstream branch for the local branch
Method grep_log Get commmits matching regex
Method has_branch Check if the repository has branch named branch.
Method has_remote_repo Do we know about a remote named name?
Method has_submodules Does the repo have any submodules?
Method has_tag Check if the repository has a tag named tag.
Method has_treeish Check if the repository has the treeish object treeish.
Method is_clean Does the repository contain any uncommitted modifications?
Method is_empty Is the repository empty?
Method is_fast_forward Check if an update from from_branch to to_branch would be a fast forward or if the branch is up to date already.
Method is_in_merge Undocumented
Method list_files List files in index and working tree
Method list_tree Get a trees content. It yields tuples that match the 'ls-tree' output: (mode, type, sha1, path). When sizes is True, includes object sizes: (mode, type, sha1, size, path)
Method make_tree Create a tree based on contents.
Method merge Merge changes from the named commit into the current branch
Method move_tag Undocumented
Method pull Fetch and merge from another repository
Method push Push changes to the remote repo
Method push_tag Push a tag to the remote repo
Method remove_files Remove files from the repository
Method remove_remote_repo Undocumented
Method rename_branch Rename branch
Method rename_file Rename file, directory, or symlink
Method rev_parse Find the SHA1 of a given name
Method set_branch Switch to branch branch
Method set_config Set a git config value in this repository
Method set_upstream_branch Set upstream branches for local branch
Method set_user_email Sets the email address to use for git commits.
Method set_user_name Sets the full name to use for git commits.
Method show Show a git object
Method status Check status of repository.
Method update_ref Update ref ref to commit new if ref currently points to old
Method update_submodules Update all submodules
Method verify_tag Verify a signed tag
Method write_file Hash a single file and write it into the object database
Method write_tree Create a tree object from the current index
Property bare Whether this is a bare repository
Property branch The currently checked out branch
Property git_dir The absolute path to git's metadata
Property head SHA1 of the current HEAD
Property path The absolute path to the repository
Property tags List of all tags in the repository
Static Method __build_env Prepare environment for subprocess calls
Method _check_bare Check whether this is a bare repository
Method _check_repo Undocumented
Method _cmd_has_feature Check if the git command has certain feature enabled.
Method _commit Undocumented
Method _get_branches Get a list of branches
Method _get_git_dir Undocumented
Method _git_command Execute git command with arguments args and environment env at path.
Method _git_getoutput Run a git command and return the output
Method _git_inout Run a git command with input and return output
Method _status Undocumented
Instance Variable _bare Whether this is a bare repository
Instance Variable _git_dir Undocumented
Instance Variable _path The path to the working tree
@classmethod
def clone(cls, path, remote, depth=0, recursive=False, mirror=False, bare=False, auto_name=True, reference=None):

Clone a git repository at remote to path.

Parameters
path:strwhere to clone the repository to
remote:strURL to clone
depth:intcreate a shallow clone of depth depth
recursive:boolwhether to clone submodules
mirror:boolwhether to pass --mirror to git-clone
bare:boolwhether to create a bare repository
auto_name:boolIf True create a directory below path based on the remotes name. Otherwise create the repo directly at path.
reference:strcreate a clone using local objects from reference repository
Returns
GitRepositorygit repository object
@classmethod
def create(cls, path, description=None, bare=False):

Create a repository at path

Parameters
path:strwhere to create the repository
descriptionUndocumented
bare:boolwhether to create a bare repository
Returns
GitRepositorygit repository object
@classmethod
def git_inout(cls, command, args, input, extra_env, cwd, capture_stderr, config_args=None):

As _git_inout but can be used without an instance

@staticmethod
def ensure_refs_heads(branch):

Make sure a branch name is prefixed with `refs/heads'

@staticmethod
def strip_sha1(sha1, length=0):

Strip a given sha1 and check if the resulting hash has the expected length.

>>> GitRepository.strip_sha1('  58ef37dbeb12c44b206b92f746385a6f61253c0a\n')
'58ef37dbeb12c44b206b92f746385a6f61253c0a'
>>> GitRepository.strip_sha1('58ef37d', 10)
Traceback (most recent call last):
...
gbp.git.repository.GitRepositoryError: '58ef37d' is not a valid sha1 of length 10
>>> GitRepository.strip_sha1('58ef37d', 7)
'58ef37d'
>>> GitRepository.strip_sha1('123456789', 7)
'123456789'
>>> GitRepository.strip_sha1('foobar')
Traceback (most recent call last):
...
gbp.git.repository.GitRepositoryError: 'foobar' is not a valid sha1
def __init__(self, path, toplevel=True):
Parameters
path:strpath to git repo (or subdir)
toplevel:boolwhether path points to the toplevel dir of git repository
def abort_merge(self):

Abort a merge

def add_files(self, paths, force=False, index_file=None, work_tree=None):

Add files to a the repository

Parameters
paths:list or strlist of files to add
force:booladd files even if they would be ignored by .gitignore
index_filealternative index file to use
work_treealternative working tree to use
def add_remote_repo(self, name, url, tags=True, fetch=False):

Add a tracked remote repository

Parameters
name:strthe name to use for the remote
url:strthe url to add
tags:boolwhether to fetch tags
fetch:boolwhether to fetch immediately from the remote side
def add_submodule(self, repo_path):

Add a submodule

Parameters
repo_path:strpath to submodule
def apply_patch(self, patch, index=True, context=None, strip=None, fix_ws=False):

Apply a patch using git apply

def archive(self, format, prefix, output, treeish, cwd=None):

Create an archive from a treeish

Parameters
format:strthe type of archive to create, e.g. 'tar.gz'
prefix:strprefix to prepend to each filename in the archive
output:strthe name of the archive to create
treeish:strthe treeish to create the archive from
cwd:strThe directory to run in. Defaults to the current dir
def branch_contains(self, branch, commit, remote=False):

Check if branch branch contains commit commit

Parameters
branch:strthe branch the commit should be on
commit:strthe str commit to check
remote:boolwhether to check remote instead of local branches
def checkout(self, treeish):

Checkout treeish

Parameters
treeish:strthe treeish to check out
def clean(self, directories=False, force=False, dry_run=False):

Remove untracked files from the working tree.

Parameters
directories:boolremove untracked directories, too
force:boolsatisfy git configuration variable clean.requireForce
dry_run:booldon’t actually remove anything
def collect_garbage(self, auto=False, prune=False, aggressive=False):

Cleanup unnecessary files and optimize the local repository

param auto: only cleanup if required param auto: bool

def commit_all(self, msg, author_info=None, edit=False):

Commit all changes to the repository

Parameters
msg:strcommit message
author_info:GitModifierauthorship information
editUndocumented
def commit_dir(self, unpack_dir, msg, branch, other_parents=None, author={}, committer={}, create_missing_branch=False):

Replace the current tip of branch branch with the contents from unpack_dir

Parameters
unpack_dir:strcontent to add
msg:strcommit message to use
branch:strbranch to add the contents of unpack_dir to
other_parents:list of stradditional parents of this commit
author:dict with keys name, email, dateauthor information to use for commit
committer:dict with keys name, email, date or GitModifiercommitter information to use for commit
create_missing_branch:boolcreate branch as detached branch if it doesn't already exist.
def commit_files(self, files, msg, author_info=None):

Commit the given files to the repository

Parameters
files:str or listfile or files to commit
msg:strcommit message
author_info:GitModifierauthorship information
def commit_staged(self, msg, author_info=None, edit=False):

Commit currently staged files to the repository

Parameters
msg:strcommit message
author_info:GitModifierauthorship information
edit:boolwhether to spawn an editor to edit the commit info
def commit_tree(self, tree, msg, parents, author={}, committer={}):

Commit a tree with commit msg msg and parents parents

Parameters
treetree to commit
msgcommit message
parentsparents of this commit
author:dict with keys 'name' and 'email' or GitModifierauthorship information
committer:dict with keys 'name' and 'email'committer information
def create_branch(self, branch, rev=None, force=False):

Create a new branch

Parameters
branchthe branch's name
revwhere to start the branch from
force

reset branch HEAD to start point, if it already exists

If rev is None the branch starts from the current HEAD.

def create_tag(self, name, msg=None, commit=None, sign=False, keyid=None):

Create a new tag.

Parameters
name:strthe tag's name
msg:strThe tag message.
commit:strthe commit or object to create the tag at, default is HEAD
sign:boolWhether to sing the tag
keyid:strthe GPG keyid used to sign the tag
def delete_branch(self, branch, remote=False):

Delete branch branch

Parameters
branch:strname of the branch to delete
remotebool
def delete_tag(self, tag):

Delete a tag named tag

Parameters
tag:strthe tag to delete
def describe(self, commitish, pattern=None, longfmt=False, always=False, abbrev=None, tags=False, exact_match=False):

Describe commit, relative to the latest tag reachable from it.

Parameters
commitish:strthe commit-ish to describe
pattern:stronly look for tags matching pattern
longfmt:booldescribe the commit in the long format
always:boolreturn commit sha1 as fallback if no tag is found
abbrev:None or longabbreviate sha1 to given length instead of the default
tags:boolenable matching a lightweight (non-annotated) tag
exact_match:boolonly output exact matches (a tag directly references the supplied commit)
Returns
strtag name plus/or the abbreviated sha1
def diff(self, obj1, obj2=None, paths=None, stat=False, summary=False, text=False, ignore_submodules=True, abbrev=None, renames=False):

Diff two git repository objects

Parameters
obj1:strfirst object
obj2:strsecond object
paths:listList of paths to diff
stat:bool or int or strShow diffstat
summary:boolShow diffstat
text:boolGenerate textual diffs, treat all files as text
ignore_submodules:boolignore changes to submodules
abbrevUndocumented
renamesUndocumented
Returns
binarydiff
def diff_status(self, obj1, obj2):

Get file-status of two git repository objects

Parameters
obj1:strfirst object
obj2:strsecond object
Returns
defaultdict of strname-status
def fetch(self, repo=None, tags=False, depth=0, refspec=None, all_remotes=False):

Download objects and refs from another repository.

Parameters
repo:strrepository to fetch from
tags:boolwhether to fetch all tag objects
depth:intdeepen the history of (shallow) repository to depth depth
refspec:strrefspec to use instead of the default from git config
all_remotes:boolfetch all remotes
def find_branch_tag(self, commit, branch, pattern=None):

Find the closest tag on a certain branch to a given commit

Parameters
commit:strthe commit to describe
branch:strUndocumented
pattern:stronly look for tags matching pattern
Returns
strthe found tag
def find_tag(self, commit, pattern=None):

Find the closest tag to a given commit

Parameters
commit:strthe commit to describe
pattern:stronly look for tags matching pattern
Returns
strthe found tag
def force_head(self, commit, hard=False):

Force HEAD to a specific commit

Parameters
commitcommit to move HEAD to
hard:boolalso update the working copy
def format_patches(self, start, end, output_dir, signature=True, thread=None, symmetric=True):

Output the commits between start and end as patches in output_dir.

This outputs the revisions start...end by default. When using symmetric to false it uses start..end instead.

Parameters
startthe commit on the left side of the revision range
endthe commit on the right hand side of the revisino range
output_dirdirectory to write the patches to
signaturewhether to output a signature
threadwhether to include In-Reply-To references
symmetricwhether to use the symmetric difference (see above)
def get_author_info(self):

Determine a sane values for author name and author email from git's config and environment variables.

Returns
GitModifiername and email
def get_branch(self):

On what branch is the current working copy

Returns
strcurrent branch or None in an empty repo
Raises
GitRepositoryErrorif HEAD is not a symbolic ref (e.g. when in detached HEAD state)
def get_commit_info(self, commitish):

Look up data of a specific commit-ish. Dereferences given commit-ish to the commit it points to.

Parameters
commitishthe commit-ish to inspect
Returns
dictthe commit's including id, author, email, subject and body
def get_commits(self, since=None, until=None, paths=None, num=0, first_parent=False, options=None):

Get commits from since to until touching paths

Parameters
since:strcommit to start from
until:strlast commit to get
paths:list of stronly list commits touching paths
num:intmaximum number of commits to fetch
first_parent:boolonly follow first parent when seeing a merge commit
options:list of stringslist of additional options passed to git log
def get_config(self, name):

Gets the config value associated with name

Parameters
nameconfig value to get
Returns
strfetched config value
def get_local_branches(self):

Get a list of local branches

Returns
listlocal branches
def get_merge_base(self, commit1, commit2):

Get the common ancestor between two commits

Parameters
commit1:strcommit SHA1 or name of a branch or tag
commit2:strcommit SHA1 or name of a branch or tag
Returns
strSHA1 of the common ancestor
def get_merge_branch(self, branch):

Get the branch we'd merge from

Returns
strrepo and branch we would merge from
def get_obj_type(self, obj):

Get type of a git repository object

Parameters
obj:strrepository object
Returns
strtype of the repository object
def get_remote_branches(self):

Get a list of remote branches

Returns
listremote branches
def get_remote_repos(self):

Get all remote repositories

Returns
list of strremote repositories
Unknown Field: deprecated
Use get_remotes() instead
def get_remotes(self):

Get a list of remote repositories

Returns
dict of GitRemoteremote repositories
def get_subject(self, commit):

Gets the subject of a commit.

Parameters
committhe commit to get the subject from
Returns
strthe commit's subject
Unknown Field: deprecated
Use get_commit_info directly
def get_submodules(self, treeish, path=None, recursive=True):

List the submodules of treeish

Returns
list of tuplesa list of submodule/commit-id tuples
def get_tags(self, pattern=None):

List tags

Parameters
pattern:stronly list tags matching pattern
Returns
list of strtags
def get_upstream_branch(self, local_branch):

Get upstream branch for the local branch

Parameters
local_branch:strname fo the local branch
Returns
strupstream (remote/branch) or '' if no upstream found
def grep_log(self, regex, since=None, merges=True):

Get commmits matching regex

Parameters
regex:strregular expression
since:strwhere to start grepping (e.g. a branch)
mergesUndocumented
def has_branch(self, branch, remote=False):

Check if the repository has branch named branch.

Parameters
branchbranch to look for
remote:boolonly look for remote branches
Returns
boolTrue if the repository has this branch, False otherwise
def has_remote_repo(self, name):

Do we know about a remote named name?

Parameters
name:strname of the remote repository
Returns
boolTrue if the remote repositore is known, False otherwise
def has_submodules(self, treeish=None):

Does the repo have any submodules?

Parameters
treeish:strlook into treeish
Returns
boolTrue if the repository has any submodules, False otherwise
def has_tag(self, tag):

Check if the repository has a tag named tag.

Parameters
tag:strtag to look for
Returns
boolTrue if the repository has that tag, False otherwise
def has_treeish(self, treeish):

Check if the repository has the treeish object treeish.

Parameters
treeish:strtreeish object to look for
Returns
boolTrue if the repository has that tree, False otherwise
def is_clean(self, ignore_untracked=False, paths=None):

Does the repository contain any uncommitted modifications?

Parameters
ignore_untracked:boolwhether to ignore untracked files when checking the repository status
paths:list of stingsonly check changes on paths
Returns
tupleTrue if the repository is clean, False otherwise and Git's status message
def is_empty(self):

Is the repository empty?

Returns
boolTrue if the repositorydoesn't have any commits, False otherwise
def is_fast_forward(self, from_branch, to_branch):

Check if an update from from_branch to to_branch would be a fast forward or if the branch is up to date already.

Returns
tuplecan_fast_forward, up_to_date
def is_in_merge(self):

Undocumented

def list_files(self, types=['cached']):

List files in index and working tree

Parameters
types:listlist of types to show
Returns
list of strlist of files as byte string
def list_tree(self, treeish, recurse=False, paths=None, sizes=False):

Get a trees content. It yields tuples that match the 'ls-tree' output: (mode, type, sha1, path). When sizes is True, includes object sizes: (mode, type, sha1, size, path)

Parameters
treeish:strthe treeish object to list
recurse:boolwhether to list the tree recursively
pathsUndocumented
sizeswhether to include object sizes
Returns
list of objects. See above.the tree
def make_tree(self, contents):

Create a tree based on contents.

Parameters
contents:list of strsame format as GitRepository.list_tree output.
def merge(self, commit, verbose=False, edit=False):

Merge changes from the named commit into the current branch

Parameters
commit:strthe commit to merge from (usually a branch name or tag)
verbose:boolwhether to print a summary after the merge
edit:boolwhether to invoke an editor to edit the merge message
def move_tag(self, old, new):

Undocumented

def pull(self, repo=None, ff_only=False, all_remotes=False):

Fetch and merge from another repository

Parameters
repo:strrepository to fetch from
ff_only:boolonly merge if this results in a fast forward merge
all_remotes:boolfetch all remotes
def push(self, repo=None, src=None, dst=None, ff_only=True, force=False, tags=False, dry_run=False):

Push changes to the remote repo

Parameters
repo:strrepository to push to
src:strthe source ref to push
dst:strthe name of the destination ref to push to
ff_only:boolonly push if it's a fast forward update
force:boolforce push, can cause the remote repository to lose commits; use it with care
tags:boolpush all refs under refs/tags, in addition to other refs
dry_run:booldry run
def push_tag(self, repo, tag, dry_run=False):

Push a tag to the remote repo

Parameters
repo:strrepository to push to
tag:strthe name of the tag
dry_run:booldry run
def remove_files(self, paths, verbose=False):

Remove files from the repository

Parameters
pathslist or str
verbose:boolbe verbose
def remove_remote_repo(self, name):

Undocumented

def rename_branch(self, branch, newbranch):

Rename branch

Parameters
branchname of the branch to be renamed
newbranchnew name of the branch
def rename_file(self, old, new):

Rename file, directory, or symlink

def rev_parse(self, name, short=0):

Find the SHA1 of a given name

Parameters
name:strthe name to look for
short:inttry to abbreviate SHA1 to given length
Returns
strthe name's sha1
def set_branch(self, branch):

Switch to branch branch

Parameters
branch:strname of the branch to switch to
def set_config(self, name, value):

Set a git config value in this repository

def set_upstream_branch(self, local_branch, upstream):

Set upstream branches for local branch

Parameters
local_branch:strname of the local branch
upstream:strRemote branch in the form remote/branch, e.g. origin/master
def set_user_email(self, email):

Sets the email address to use for git commits.

Parameters
emailemail address to use
def set_user_name(self, name):

Sets the full name to use for git commits.

Parameters
namefull name to use
def show(self, id):

Show a git object

Returns
bytestrUndocumented
def status(self, pathlist=None):

Check status of repository.

Parameters
pathlist:list @return dict of lists of paths, where key is a git status flag. @rtype dictList of paths to check status for
def update_ref(self, ref, new, old=None, msg=None):

Update ref ref to commit new if ref currently points to old

Parameters
ref:strthe ref to update
new:strthe new value for ref
old:strthe old value of ref
msg:strthe reason for the update
def update_submodules(self, init=True, recursive=True, fetch=False):

Update all submodules

Parameters
init:boolwhether to initialize the submodule if necessary
recursive:boolwhether to update submodules recursively
fetch:boolwhether to fetch new objects
def verify_tag(self, tag):

Verify a signed tag

Parameters
tag:strthe tag's name
Returns
boolWhether the signature on the tag could be verified
def write_file(self, filename, filters=True):

Hash a single file and write it into the object database

Parameters
filename:bytestrthe filename to the content of the file to hash
filters:boolwhether to run filters
Returns
strthe hash of the file
def write_tree(self, index_file=None):

Create a tree object from the current index

Parameters
index_file:stralternate index file to read changes from
Returns
strthe new tree object's sha1
@property
bare =

Whether this is a bare repository

@property
branch =

The currently checked out branch

@property
git_dir =

The absolute path to git's metadata

@property
head =

SHA1 of the current HEAD

@property
path =

The absolute path to the repository

@property
tags =

List of all tags in the repository

@staticmethod
def __build_env(extra_env):

Prepare environment for subprocess calls

def _check_bare(self):

Check whether this is a bare repository

def _check_repo(self, path, toplevel):

Undocumented

def _cmd_has_feature(self, command, feature):

Check if the git command has certain feature enabled.

Parameters
command:strgit command
feature:strfeature / command option to check
Returns
boolTrue if feature is supported
def _commit(self, msg, args=[], author_info=None):

Undocumented

def _get_branches(self, remote=False):

Get a list of branches

Parameters
remote:boolwhether to list local or remote branches
Returns
listlocal or remote branches
def _get_git_dir(self):

Undocumented

def _git_command(self, command, args=[], extra_env=None):

Execute git command with arguments args and environment env at path.

Parameters
command:strgit command
args:listcommand line arguments
extra_env:dictextra environment variables to set when running command
def _git_getoutput(self, command, args=[], extra_env=None, cwd=None):

Run a git command and return the output

Parameters
command:strgit command to run
args:listlist of arguments
extra_env:dictextra environment variables to pass
cwd:strdirectory to switch to when running the command, defaults to self.path
Returns
tuple of list of bytestr and intstdout, return code
Unknown Field: deprecated
use gbp.git.repository.GitRepository._git_inout instead.
def _git_inout(self, command, args, input=None, extra_env=None, cwd=None, capture_stderr=False, config_args=None):

Run a git command with input and return output

Parameters
command:strgit command to run
args:listlist of arguments
input:strinput to pipe to command
extra_env:dictextra environment variables to pass
cwd:strdirectory to switch to when running the command, defaults to self.path
capture_stderr:boolwhether to capture stderr
config_argsUndocumented
Returns
tuple of bytestr, bytestr, intstdout, stderr, return code
def _status(self, porcelain, ignore_untracked, paths):

Undocumented

_bare: bool =

Whether this is a bare repository

_git_dir =

Undocumented

_path: str =

The path to the working tree