### Navigation

- index
- modules |
- next |
- previous |
- GitPython v0.3.0-beta2 documentation »

# API Reference

## Objects.Base

class `git.objects.base.``Object`(repo, binsha)

  Implements an Object which may be Blobs, Trees, Commits and Tags

  `binsha`
  `data_stream`

    Returns: | File Object compatible stream to the uncompressed raw data of the object
    Note: | returned streams must be read in order

  `hexsha`

    Returns: | 40 byte hex version of our 20 byte binary sha

  classmethod `new`(repo, id)

    Returns: | New Object instance of a type appropriate to the object type behind id. The id of the newly created object will be a binsha even though the input id may have been a Reference or Rev-Spec
    Parameter: | id – reference, rev-spec, or hexsha
    Note: | This cannot be a __new__ method as it would always call __init__ with the input id which is not necessarily a binsha.

  classmethod `new_from_sha`(repo, sha1)

    Returns: | new object instance of a type appropriate to represent the given binary sha1
    Parameter: | sha1 – 20 byte binary sha1

  `repo`
  `size`
  `stream_data`(ostream)
    Writes our data directly to the given output stream :param ostream: File object compatible stream object. :return: self

class `git.objects.base.``IndexObject`(repo, binsha, mode=None, path=None)

  Base for all objects that can be part of the index file , namely Tree, Blob and SubModule objects

  `abspath`

    Returns: | Absolute path to this index object in the file system ( as opposed to the .path field which is a path relative to the git repository ). The returned path will be native to the system and contains ‘’ on windows.

  `mode`
  `name`

    Returns: | Name portion of the path, effectively being the basename

  `path`

## Objects.Blob

class `git.objects.blob.``Blob`(repo, binsha, mode=None, path=None)

  A Blob encapsulates a git blob object

  `mime_type`

    Returns: | String describing the mime type of this file (based on the filename)
    Note: | Defaults to ‘text/plain’ in case the actual file type is unknown.

## Objects.Commit

class `git.objects.commit.``Commit`(repo, binsha, tree=None, author=None, authored_date=None, author_tz_offset=None, committer=None, committed_date=None, committer_tz_offset=None, message=None, parents=None, encoding=None)

  Wraps a git Commit object.

  This class will act lazily on some of its attributes and will query the value on demand only if it involves calling the git binary.

  `author`
  `author_tz_offset`
  `authored_date`
  `committed_date`
  `committer`
  `committer_tz_offset`
  `count`(paths='', **kwargs)

    Count the number of commits reachable from this commit

    Parameters: | paths – is an optinal path or a list of paths restricting the return value to commits actually containing the paths kwargs – Additional options to be passed to git-rev-list. They must not alter the ouput style of the command, or parsing will yield incorrect results
    Returns: | int defining the number of reachable commits

  classmethod `create_from_tree`(repo, tree, message, parent_commits=None, head=False)

    Commit the given tree, creating a commit object.

    Parameters: | repo – Repo object the commit should be part of tree – Tree object or hex or bin sha the tree of the new commit message – Commit message. It may be an empty string if no message is provided. It will be converted to a string in any case. parent_commits – Optional Commit objects to use as parents for the new commit. If empty list, the commit will have no parents at all and become a root commit. If None , the current head commit will be the parent of the new commit object head – If True, the HEAD will be advanced to the new commit automatically. Else the HEAD will remain pointing on the previous commit. This could lead to undesired results when diffing files.
    Returns: | Commit object representing the new commit
    Note: | Additional information about the committer and Author are taken from the environment or from the git configuration, see git-commit-tree for more information

  `encoding`
  classmethod `iter_items`(repo, rev, paths='', **kwargs)

    Find all commits matching the given criteria.

    Parameters: | repo – is the Repo rev – revision specifier, see git-rev-parse for viable options paths – is an optinal path or list of paths, if set only Commits that include the path or paths will be considered kwargs – optional keyword arguments to git rev-list where `max_count` is the maximum number of commits to fetch `skip` is the number of commits to skip `since` all commits since i.e. ‘1970-01-01’
    Returns: | iterator yielding Commit items

  `iter_parents`(paths='', **kwargs)

    Iterate _all_ parents of this commit.

    Parameters: | paths – Optional path or list of paths limiting the Commits to those that contain at least one of the paths kwargs – All arguments allowed by git-rev-list
    Returns: | Iterator yielding Commit objects which are parents of self

  `message`
  `name_rev`

    Returns: | String describing the commits hex sha based on the closest Reference. Mostly useful for UI purposes

  `parents`
  `stats`

    Create a git stat from changes between this commit and its first parent or from all changes done if this is the very first commit.

    Returns: | git.Stats

  `summary`

    Returns: | First line of the commit message

  `tree`

## Objects.Tag

Module containing all object based types.

class `git.objects.tag.``TagObject`(repo, binsha, object=None, tag=None, tagger=None, tagged_date=None, tagger_tz_offset=None, message=None)

  Non-Lightweight tag carrying additional information about an object we are pointing to.

  `message`
  `object`
  `tag`
  `tagged_date`
  `tagger`
  `tagger_tz_offset`

## Objects.Tree

class `git.objects.tree.``TreeModifier`(cache)

  A utility class providing methods to alter the underlying cache in a list-like fashion.

  Once all adjustments are complete, the _cache, which really is a refernce to the cache of a tree, will be sorted. Assuring it will be in a serializable state

  `add`(sha, mode, name, force=False)

    Add the given item to the tree. If an item with the given name already exists, nothing will be done, but a ValueError will be raised if the sha and mode of the existing item do not match the one you add, unless force is True

    Parameters: | sha – The 20 or 40 byte sha of the item to add mode – int representing the stat compatible mode of the item force – If True, an item with your name and information will overwrite any existing item with the same name, no matter which information it has
    Returns: | self

  `add_unchecked`(binsha, mode, name)
    Add the given item to the tree, its correctness is assumed, which puts the caller into responsibility to assure the input is correct. For more information on the parameters, see `add` :param binsha: 20 byte binary sha
  `set_done`()
    Call this method once you are done modifying the tree information. It may be called several times, but be aware that each call will cause a sort operation :return self:

class `git.objects.tree.``Tree`(repo, binsha, mode=16384, path=None)

  Tree objects represent an ordered list of Blobs and other Trees.

  `Tree as a list`:

      Access a specific blob using the
      tree['filename'] notation.

      You may as well access by index
      blob = tree[0]

  `blobs`

    Returns: | list(Blob, ...) list of blobs directly below this tree

  `cache`

    Returns: | An object allowing to modify the internal cache. This can be used to change the tree’s contents. When done, make sure you call `set_done` on the tree modifier, or serialization behaviour will be incorrect. See the `TreeModifier` for more information on how to alter the cache

  `traverse`(predicate=<function <lambda> at 0x26386e0>, prune=<function <lambda> at 0x2638758>, depth=-1, branch_first=True, visit_once=False, ignore_self=1)
    For documentation, see util.Traversable.traverse Trees are set to visit_once = False to gain more performance in the traversal
  `trees`

    Returns: | list(Tree, ...) list of trees directly below this tree

## Objects.Functions

Module with functions which are supposed to be as fast as possible

`git.objects.fun.``tree_to_stream`(entries, write)
  Write the give list of entries into a stream using its write method :param entries: sorted list of tuples with (binsha, mode, name) :param write: write method which takes a data string

`git.objects.fun.``tree_entries_from_data`(data)
  Reads the binary representation of a tree and returns tuples of Tree items :param data: data block with tree data :return: list(tuple(binsha, mode, tree_relative_path), ...)

`git.objects.fun.``traverse_trees_recursive`(odb, tree_shas, path_prefix)

  Returns: | list with entries according to the given binary tree-shas. The result is encoded in a list of n tuple|None per blob/commit, (n == len(tree_shas)), where * [0] == 20 byte sha * [1] == mode as int * [2] == path relative to working tree root The entry tuple is None if the respective blob/commit did not exist in the given tree.
  Parameters: | tree_shas – iterable of shas pointing to trees. All trees must be on the same level. A tree-sha may be None in which case None path_prefix – a prefix to be added to the returned paths on this level, set it ‘’ for the first iteration
  Note: | The ordering of the returned items will be partially lost

`git.objects.fun.``traverse_tree_recursive`(odb, tree_sha, path_prefix)

  Returns: | list of entries of the tree pointed to by the binary tree_sha. An entry has the following format: * [0] 20 byte sha * [1] mode as int * [2] path relative to the repository
  Parameter: | path_prefix – prefix to prepend to the front of all returned paths

## Objects.Submodule

class `git.objects.submodule.``Submodule`(repo, binsha, mode=None, path=None)
  Implements access to a git submodule. They are special in that their sha represents a commit in the submodule’s repository which is to be checked out at the path of this instance. The submodule type does not have a string type associated with it, as it exists solely as a marker in the tree and index

## Objects.Util

Module for general utility functions

`git.objects.util.``get_object_type_by_name`(object_type_name)

  Returns: | type suitable to handle the given object type name. Use the type to create new instances.
  Parameter: | object_type_name – Member of TYPES
  Raises ValueError:
  | In case object_type_name is unknown

`git.objects.util.``get_user_id`()

  Returns: | string identifying the currently active system user as name@node
  Note: | user can be set with the ‘USER’ environment variable, usually set on windows

`git.objects.util.``parse_date`(string_date)

  Parse the given date as one of the following

  > - Git internal format: timestamp offset

  > - RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.

  > - ISO 8601 2005-04-07T22:13:13

  >     The T can be a space as well

  Returns: | Tuple(int(timestamp), int(offset)), both in seconds since epoch
  Raises ValueError:
  | If the format could not be understood
  Note: | Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY

`git.objects.util.``parse_actor_and_date`(line)

  Parse out the actor (author or committer) info from a line like:

      author Tom Preston-Werner <tom@mojombo.com> 1191999972 -0700

  Returns: | [Actor, int_seconds_since_epoch, int_timezone_offset]

class `git.objects.util.``ProcessStreamAdapter`(process, stream_name)

  Class wireing all calls to the contained Process instance.

  Use this type to hide the underlying process to provide access only to a specified stream. The process is usually wrapped into an AutoInterrupt class to kill it if the instance goes out of scope.

class `git.objects.util.``Traversable`

  Simple interface to perforam depth-first or breadth-first traversals into one direction. Subclasses only need to implement one function. Instances of the Subclass must be hashable

  `traverse`(predicate=<function <lambda> at 0x2627c08>, prune=<function <lambda> at 0x2627c80>, depth=-1, branch_first=True, visit_once=True, ignore_self=1, as_edge=False)

    Returns: | iterator yieling of items found when traversing self
    Parameters: | predicate – f(i,d) returns False if item i at depth d should not be included in the result prune – f(i,d) return True if the search should stop at item i at depth d. Item i will not be returned. depth – define at which level the iteration should not go deeper if -1, there is no limit if 0, you would effectively only get self, the root of the iteration i.e. if 1, you would only get the first level of predessessors/successors branch_first – if True, items will be returned branch first, otherwise depth first visit_once – if True, items will only be returned once, although they might be encountered several times. Loops are prevented that way. ignore_self – if True, self will be ignored and automatically pruned from the result. Otherwise it will be the first item to be returned. If as_edge is True, the source of the first edge is None as_edge – if True, return a pair of items, first being the source, second the destinatination, i.e. tuple(src, dest) with the edge spanning from source to destination

`git.objects.util.``altz_to_utctz_str`(altz)
  As above, but inverses the operation, returning a string that can be used in commit objects

`git.objects.util.``utctz_to_altz`(utctz)
  we convert utctz to the timezone in seconds, it is the format time.altzone returns. Git stores it as UTC timezon which has the opposite sign as well, which explains the -1 * ( that was made explicit here ) :param utctz: git utc timezone string, i.e. +0200

`git.objects.util.``verify_utctz`(offset)

  Raises ValueError:
  | if offset is incorrect
  Returns: | offset

## Index.Base

Module containing Index implementation, allowing to perform all kinds of index manipulations such as querying and merging.

class `git.index.base.``IndexFile`(repo, file_path=None)

  Implements an Index that can be manipulated using a native implementation in order to save git command function calls wherever possible.

  It provides custom merging facilities allowing to merge without actually changing your index or your working tree. This way you can perform own test-merges based on the index only without having to deal with the working copy. This is useful in case of partial working trees.

  `Entries`

  The index contains an entries dict whose keys are tuples of type IndexEntry to facilitate access.

  You may read the entries dict or manipulate it using IndexEntry instance, i.e.:

      index.entries[index.entry_key(index_entry_instance)] = index_entry_instance

  Make sure you use index.write() once you are done manipulating the index directly before operating on it using the git command

  `add`(*args, **kwargs)
  `checkout`(*args, **kwargs)
  `commit`(message, parent_commits=None, head=True)

    Commit the current default index file, creating a commit object.

    For more information on the arguments, see tree.commit. :note:

    > If you have manually altered the .entries member of this instance, don’t forget to write() your changes to disk beforehand.

    Returns: | Commit object representing the new commit

  `diff`(*args, **kwargs)
  `entries`
  classmethod `entry_key`(*entry)
  classmethod `from_tree`(repo, *treeish, **kwargs)

    Merge the given treeish revisions into a new index which is returned. The original index will remain unaltered

    Parameters: | repo – The repository treeish are located in. treeish – One, two or three Tree Objects, Commits or 40 byte hexshas. The result changes according to the amount of trees. If 1 Tree is given, it will just be read into a new index If 2 Trees are given, they will be merged into a new index using a two way merge algorithm. Tree 1 is the ‘current’ tree, tree 2 is the ‘other’ one. It behaves like a fast-forward. If 3 Trees are given, a 3-way merge will be performed with the first tree being the common ancestor of tree 2 and tree 3. Tree 2 is the ‘current’ tree, tree 3 is the ‘other’ one kwargs – Additional arguments passed to git-read-tree
    Returns: | New IndexFile instance. It will point to a temporary index location which does not exist anymore. If you intend to write such a merged Index, supply an alternate file_path to its ‘write’ method.
    Note: | In the three-way merge case, –aggressive will be specified to automatically resolve more cases in a commonly correct manner. Specify trivial=True as kwarg to override that. As the underlying git-read-tree command takes into account the current index, it will be temporarily moved out of the way to assure there are no unsuspected interferences.

  `iter_blobs`(predicate=<function <lambda> at 0x26abed8>)

    Returns: | Iterator yielding tuples of Blob objects and stages, tuple(stage, Blob)
    Parameter: | predicate – Function(t) returning True if tuple(stage, Blob) should be yielded by the iterator. A default filter, the BlobFilter, allows you to yield blobs only if they match a given list of paths.

  `merge_tree`(*args, **kwargs)
  `move`(*args, **kwargs)
  classmethod `new`(repo, *tree_sha)

    Merge the given treeish revisions into a new index which is returned. This method behaves like git-read-tree –aggressive when doing the merge.

    Parameters: | repo – The repository treeish are located in. tree_sha – 20 byte or 40 byte tree sha or tree objects
    Returns: | New IndexFile instance. Its path will be undefined. If you intend to write such a merged Index, supply an alternate file_path to its ‘write’ method.

  `path`

    Returns: | Path to the index file we are representing

  `remove`(*args, **kwargs)
  `repo`
  `reset`(*args, **kwargs)
  `resolve_blobs`(iter_blobs)

    Resolve the blobs given in blob iterator. This will effectively remove the index entries of the respective path at all non-null stages and add the given blob as new stage null blob.

    For each path there may only be one blob, otherwise a ValueError will be raised claiming the path is already at stage 0.

    Raises ValueError:
    | if one of the blobs already existed at stage 0
    Returns: | self
    Note: | You will have to write the index manually once you are done, i.e. index.resolve_blobs(blobs).write()

  `unmerged_blobs`()

    Returns: | Iterator yielding dict(path : list( tuple( stage, Blob, ...))), being a dictionary associating a path in the index with a list containing sorted stage/blob pairs
    Note: | Blobs that have been removed in one side simply do not exist in the given stage. I.e. a file removed on the ‘other’ branch whose entries are at stage 3 will not have a stage 3 entry.

  `update`()

    Reread the contents of our index file, discarding all cached information we might have.

    Note: | This is a possibly dangerious operations as it will discard your changes to index.entries
    Returns: | self

  `version`
  `write`(file_path=None, ignore_tree_extension_data=False)

    Write the current state to our file path or to the given one

    Parameters: | file_path – If None, we will write to our stored file path from which we have been initialized. Otherwise we write to the given file path. Please note that this will change the file_path of this index to the one you gave. ignore_tree_extension_data – If True, the TREE type extension data read in the index will not be written to disk. Use this if you have altered the index and would like to use git-write-tree afterwards to create a tree representing your written changes. If this data is present in the written index, git-write-tree will instead write the stored/cached tree. Alternatively, use IndexFile.write_tree() to handle this case automatically
    Returns: | self

  `write_tree`()

    Writes this index to a corresponding Tree object into the repository’s object database and return it.

    Returns: | Tree object representing this index
    Note: | The tree will be written even if one or more objects the tree refers to does not yet exist in the object database. This could happen if you added Entries to the index directly.
    Raises ValueError:
    | if there are no entries in the cache
    Raises UnmergedEntriesError:

exception `git.index.base.``CheckoutError`(message, failed_files, valid_files, failed_reasons)

  Thrown if a file could not be checked out from the index as it contained changes.

  The .failed_files attribute contains a list of relative paths that failed to be checked out as they contained changes that did not exist in the index.

  The .failed_reasons attribute contains a string informing about the actual cause of the issue.

  The .valid_files attribute contains a list of relative paths to files that were checked out successfully and hence match the version stored in the index

## Index.Functions

Contains standalone functions to accompany the index implementation and make it more versatile

`git.index.fun.``write_cache`(entries, stream, extension_data=None, ShaStreamCls=<class 'git.util.IndexFileSHA1Writer'>)

  Write the cache represented by entries to a stream

  Parameters: | entries – sorted list of entries stream – stream to wrap into the AdapterStreamCls - it is used for final output. ShaStreamCls – Type to use when writing to the stream. It produces a sha while writing to it, before the data is passed on to the wrapped stream extension_data – any kind of data to write as a trailer, it must begin a 4 byte identifier, followed by its size ( 4 bytes )

`git.index.fun.``read_cache`(stream)

  Read a cache file from the given stream :return: tuple(version, entries_dict, extension_data, content_sha)

  > - version is the integer version number

  > - entries dict is a dictionary which maps IndexEntry instances to a path

  >     at a stage

  > - extension_data is ‘’ or 4 bytes of type + 4 bytes of size + size bytes

  > - content_sha is a 20 byte sha on all cache file contents

`git.index.fun.``write_tree_from_cache`(entries, odb, sl, si=0)

  Create a tree from the given sorted list of entries and put the respective trees into the given object database

  Parameters: | entries – sorted list of IndexEntries odb – object database to store the trees in si – start index at which we should start creating subtrees sl – slice indicating the range we should process on the entries list
  Returns: | tuple(binsha, list(tree_entry, ...)) a tuple of a sha and a list of tree entries being a tuple of hexsha, mode, name

`git.index.fun.``entry_key`(*entry)

  Returns: | Key suitable to be used for the index.entries dictionary
  Parameter: | entry – One instance of type BaseIndexEntry or the path and the stage

`git.index.fun.``stat_mode_to_index_mode`(mode)
  Convert the given mode from a stat call to the corresponding index mode and return it

## Index.Types

Module with additional types used by the index

class `git.index.typ.``BlobFilter`(paths)

  Predicate to be used by iter_blobs allowing to filter only return blobs which match the given list of directories or files.

  The given paths are given relative to the repository.

  `paths`

class `git.index.typ.``BaseIndexEntry`

  Small Brother of an index entry which can be created to describe changes done to the index in which case plenty of additional information is not requried.

  As the first 4 data members match exactly to the IndexEntry type, methods expecting a BaseIndexEntry can also handle full IndexEntries even if they use numeric indices for performance reasons.

  `binsha`
    binary sha of the blob
  `flags`

    Returns: | flags stored with this entry

  classmethod `from_blob`(blob, stage=0)

    Returns: | Fully equipped BaseIndexEntry at the given stage

  `hexsha`
    hex version of our sha
  `mode`
    File Mode, compatible to stat module constants
  `path`

    Returns: | our path relative to the repository working tree root

  `stage`

    Stage of the entry, either:

    > - 0 = default stage
    > - 1 = stage before a merge or common ancestor entry in case of a 3 way merge
    > - 2 = stage of entries from the ‘left’ side of the merge
    > - 3 = stage of entries from the right side of the merge

    Note: | For more information, see http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html

  `to_blob`(repo)

    Returns: | Blob using the information of this index entry

class `git.index.typ.``IndexEntry`

  Allows convenient access to IndexEntry data without completely unpacking it.

  Attributes usully accessed often are cached in the tuple whereas others are unpacked on demand.

  See the properties for a mapping between names and tuple indices.

  `ctime`

    Returns: | Tuple(int_time_seconds_since_epoch, int_nano_seconds) of the file’s creation time

  `dev`
    Device ID
  classmethod `from_base`(base)

    Returns: | Minimal entry as created from the given BaseIndexEntry instance. Missing values will be set to null-like values
    Parameter: | base – Instance of type BaseIndexEntry

  classmethod `from_blob`(blob, stage=0)

    Returns: | Minimal entry resembling the given blob object

  `gid`
    Group ID
  `inode`
    Inode ID
  `mtime`
    See ctime property, but returns modification time
  `size`

    Returns: | Uncompressed size of the blob

  `uid`
    User ID

## Index.Util

Module containing index utilities

class `git.index.util.``TemporaryFileSwap`(file_path)

  Utility class moving a file to a temporary location within the same directory and moving it back on to where on object deletion.

  `file_path`
  `tmp_file_path`

`git.index.util.``post_clear_cache`(func)

  Decorator for functions that alter the index using the git command. This would invalidate our possibly existing entries dictionary which is why it must be deleted to allow it to be lazily reread later.

  Note: | This decorator will not be required once all functions are implemented natively which in fact is possible, but probably not feasible performance wise.

`git.index.util.``default_index`(func)
  Decorator assuring the wrapped method may only run if we are the default repository index. This is as we rely on git commands that operate on that index only.

`git.index.util.``git_working_dir`(func)
  Decorator which changes the current working dir to the one of the git repository in order to assure relative paths are handled correctly

## GitCmd

class `git.cmd.``Git`(working_dir=None)

  The Git class manages communication with the Git binary.

  It provides a convenient interface to calling the Git binary, such as in:

      g = Git( git_dir )
      g.init()                                       # calls 'git init' program
      rval = g.ls_files()            # calls 'git ls-files' program

  `Debugging`
    Set the GIT_PYTHON_TRACE environment variable print each invocation of the command to stdout. Set its value to ‘full’ to see details about the returned values.
  class `AutoInterrupt`(proc, args)

    Kill/Interrupt the stored process instance once this instance goes out of scope. It is used to prevent processes piling up in case iterators stop reading. Besides all attributes are wired through to the contained process object.

    The wait method was overridden to perform automatic status code checking and possibly raise.

    `args`
    `proc`
    `wait`()

      Wait for the process and return its status code.

      Raises GitCommandError:
      | if the return status is not 0

  class `Git.``CatFileContentStream`(size, stream)

    Object representing a sized read-only stream returning the contents of an object. It behaves like a stream, but counts the data read and simulates an empty stream once our sized content region is empty. If not all data is read to the end of the objects’s lifetime, we read the rest to assure the underlying stream continues to work

    `next`()
    `read`(size=-1)
    `readline`(size=-1)
    `readlines`(size=-1)
  `Git.``cat_file_all`
  `Git.``cat_file_header`
  `Git.``clear_cache`()

    Clear all kinds of internal caches to release resources.

    Currently persistent commands will be interrupted.

    Returns: | self

  `Git.``execute`(command, istream=None, with_keep_cwd=False, with_extended_output=False, with_exceptions=True, as_process=False, output_stream=None, **subprocess_kwargs)

    Handles executing the command on the shell and consumes and returns the returned information (stdout)

    Parameters: | command – The command argument list to execute. It should be a string, or a sequence of program arguments. The program to execute is the first item in the args sequence or string. istream – Standard input filehandle passed to subprocess.Popen. with_keep_cwd – Whether to use the current working directory from os.getcwd(). The cmd otherwise uses its own working_dir that it has been initialized with if possible. with_extended_output – Whether to return a (status, stdout, stderr) tuple. with_exceptions – Whether to raise an exception when git returns a non-zero status. as_process – Whether to return the created process instance directly from which streams can be read on demand. This will render with_extended_output and with_exceptions ineffective - the caller will have to deal with the details himself. It is important to note that the process will be placed into an AutoInterrupt wrapper that will interrupt the process once it goes out of scope. If you use the command in iterators, you should pass the whole process instance instead of a single stream. output_stream – If set to a file-like object, data produced by the git command will be output to the given stream directly. This feature only has any effect if as_process is False. Processes will always be created with a pipe due to issues with subprocess. This merely is a workaround as data will be copied from the output pipe to the given output stream directly. subprocess_kwargs – Keyword arguments to be passed to subprocess.Popen. Please note that some of the valid kwargs are already set by this method, the ones you specify may not be the same ones.
    Returns: | str(output) if extended_output = False (Default) tuple(int(status), str(stdout), str(stderr)) if extended_output = True if ouput_stream is True, the stdout value will be your output stream: * output_stream if extended_output = False * tuple(int(status), output_stream, str(stderr)) if extended_output = True
    Raises GitCommandError:
    Note: | If you add additional keyword arguments to the signature of this method, you must update the execute_kwargs tuple housed in this module.

  `Git.``get_object_data`(ref)
    As get_object_header, but returns object data as well :return: (hexsha, type_string, size_as_int,data_string) :note: not threadsafe
  `Git.``get_object_header`(ref)

    Use this method to quickly examine the type and size of the object behind the given ref.

    Note: | The method will only suffer from the costs of command invocation once and reuses the command in subsequent calls.
    Returns: | (hexsha, type_string, size_as_int)

  `Git.``stream_object_data`(ref)

    As get_object_header, but returns the data as a stream :return: (hexsha, type_string, size_as_int, stream) :note: This method is not threadsafe, you need one independent Command instance

    > per thread to be safe !

  `Git.``transform_kwargs`(**kwargs)
    Transforms Python style kwargs into git command line options.
  `Git.``working_dir`

    Returns: | Git directory we are working on

## Config

Module containing module parser implementation able to properly read and write configuration files

`git.config.``GitConfigParser`
  alias of `write`

## Diff

class `git.diff.``Diffable`

  Common interface for all object that can be diffed against another object of compatible type.

  Note: | Subclasses require a repo member as it is the case for Object instances, for practical reasons we do not derive from Object.

  class `Index`
  `Diffable.``diff`(other=<class 'git.diff.Index'>, paths=None, create_patch=False, **kwargs)

    Creates diffs between two items being trees, trees and index or an index and the working tree.

    Parameters: | other – Is the item to compare us with. If None, we will be compared to the working tree. If Treeish, it will be compared against the respective tree If Index ( type ), it will be compared against the index. It defaults to Index to assure the method will not by-default fail on bare repositories. paths – is a list of paths or a single path to limit the diff to. It will only include at least one of the givne path or paths. create_patch – If True, the returned Diff contains a detailed patch that if applied makes the self to other. Patches are somwhat costly as blobs have to be read and diffed. kwargs – Additional arguments passed to git-diff, such as R=True to swap both sides of the diff.
    Returns: | git.DiffIndex
    Note: | Rename detection will only work if create_patch is True. On a bare repository, ‘other’ needs to be provided as Index or as as Tree/Commit, or a git command error will occour

class `git.diff.``DiffIndex`

  Implements an Index for diffs, allowing a list of Diffs to be queried by the diff properties.

  The class improves the diff handling convenience

  `iter_change_type`(change_type)

    Returns: | iterator yieling Diff instances that match the given change_type
    Parameter: | change_type – Member of DiffIndex.change_type, namely: ‘A’ for added paths ‘D’ for deleted paths ‘R’ for renamed paths ‘M’ for paths with modified data

class `git.diff.``Diff`(repo, a_path, b_path, a_blob_id, b_blob_id, a_mode, b_mode, new_file, deleted_file, rename_from, rename_to, diff)

  A Diff contains diff information between two Trees.

  It contains two sides a and b of the diff, members are prefixed with “a” and “b” respectively to inidcate that.

  Diffs keep information about the changed blob objects, the file mode, renames, deletions and new files.

  There are a few cases where None has to be expected as member variable value:

  `New File`:

      a_mode is None
      a_blob is None

  `Deleted File`:

      b_mode is None
      b_blob is None

  `Working Tree Blobs`

  > When comparing to working trees, the working tree blob will have a null hexsha as a corresponding object does not yet exist. The mode will be null as well. But the path will be available though. If it is listed in a diff the working tree version of the file must be different to the version in the index or tree, and hence has been modified.

  `a_blob`
  `a_mode`
  `b_blob`
  `b_mode`
  `deleted_file`
  `diff`
  `new_file`
  `rename_from`
  `rename_to`
  `renamed`

    Returns: | True if the blob of our diff has been renamed

## Errors

Module containing all exceptions thrown througout the git package,

exception `git.errors.``GitCommandError`(command, status, stderr=None)
  Thrown if execution of the git command fails with non-zero status code.

exception `git.errors.``InvalidGitRepositoryError`
  Thrown if the given repository appears to have an invalid format.

exception `git.errors.``NoSuchPathError`
  Thrown if a path could not be access by the system.

## Refs

Module containing all ref based objects

class `git.refs.``SymbolicReference`(repo, path)

  Represents a special case of a reference such that this reference is symbolic. It does not point to a specific commit, but to another Head, which itself specifies a commit.

  A typical example for a symbolic reference is HEAD.

  `commit`
    Query or set commits directly
  classmethod `create`(repo, path, reference='HEAD', force=False)

    Create a new symbolic reference, hence a reference pointing to another reference.

    Parameters: | repo – Repository to create the reference in path – full path at which the new symbolic reference is supposed to be created at, i.e. “NEW_HEAD” or “symrefs/my_new_symref” reference – The reference to which the new symbolic reference should point to force – if True, force creation even if a symbolic reference with that name already exists. Raise OSError otherwise
    Returns: | Newly created symbolic Reference
    Raises OSError: | If a (Symbolic)Reference with the same name but different contents already exists.
    Note: | This does not alter the current HEAD, index or Working Tree

  classmethod `delete`(repo, path)

    Delete the reference at the given path

    Parameters: | repo – Repository to delete the reference from path – Short or full path pointing to the reference, i.e. refs/myreference or just “myreference”, hence ‘refs/’ is implied. Alternatively the symbolic reference to be deleted

  classmethod `dereference_recursive`(repo, ref_path)

    Returns: | hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required
    Parameter: | repo – the repository containing the reference at ref_path

  classmethod `from_path`(repo, path)

    Returns: | Instance of type Reference, Head, or Tag depending on the given path

  `is_detached`

    Returns: | True if we are a detached reference, hence we point to a specific commit instead to another reference

  `is_valid`()

    Returns: | True if the reference is valid, hence it can be read and points to a valid object or reference.

  classmethod `iter_items`(repo, common_path=None)

    Find all refs in the repository

    Parameters: | repo – is the Repo common_path – Optional keyword argument to the path which is to be shared by all returned Ref objects. Defaults to class specific portion if None assuring that only refs suitable for the actual class are returned.
    Returns: | git.SymbolicReference[], each of them is guaranteed to be a symbolic ref which is not detached. List is lexigraphically sorted The returned objects represent actual subclasses, such as Head or TagReference

  `name`

    Returns: | In case of symbolic references, the shortest assumable name is the path itself.

  `path`
  `ref`
    Returns the Reference we point to
  `reference`
    Returns the Reference we point to
  `rename`(new_path, force=False)

    Rename self to a new path

    Parameters: | new_path – Either a simple name or a full path, i.e. new_name or features/new_name. The prefix refs/ is implied for references and will be set as needed. In case this is a symbolic ref, there is no implied prefix force – If True, the rename will succeed even if a head with the target name already exists. It will be overwritten in that case
    Returns: | self
    Raises OSError: | In case a file at path but a different contents already exists

  `repo`
  classmethod `to_full_path`(path)

    Returns: | string with a full path name which can be used to initialize a Reference instance, for instance by using `Reference.from_path`

class `git.refs.``Reference`(repo, path)

  Represents a named reference to any object. Subclasses may apply restrictions though, i.e. Heads can only point to commits.

  classmethod `create`(repo, path, commit='HEAD', force=False)

    Create a new reference.

    Parameters: | repo – Repository to create the reference in path – The relative path of the reference, i.e. ‘new_branch’ or feature/feature1. The path prefix ‘refs/’ is implied if not given explicitly commit – Commit to which the new reference should point, defaults to the current HEAD force – if True, force creation even if a reference with that name already exists. Raise OSError otherwise
    Returns: | Newly created Reference
    Note: | This does not alter the current HEAD, index or Working Tree

  classmethod `iter_items`(repo, common_path=None)
    Equivalent to SymbolicReference.iter_items, but will return non-detached references as well.
  `name`

    Returns: | (shortest) Name of this reference - it may contain path components

  `object`
    Return the object our ref currently refers to

class `git.refs.``HEAD`(repo, path='HEAD')

  Special case of a Symbolic Reference as it represents the repository’s HEAD reference.

  `reset`(commit='HEAD', index=True, working_tree=False, paths=None, **kwargs)

    Reset our HEAD to the given commit optionally synchronizing the index and working tree. The reference we refer to will be set to commit as well.

    Parameters: | commit – Commit object, Reference Object or string identifying a revision we should reset HEAD to. index – If True, the index will be set to match the given commit. Otherwise it will not be touched. working_tree – If True, the working tree will be forcefully adjusted to match the given commit, possibly overwriting uncommitted changes without warning. If working_tree is True, index must be true as well paths – Single path or list of paths relative to the git root directory that are to be reset. This allows to partially reset individual files. kwargs – Additional arguments passed to git-reset.
    Returns: | self

class `git.refs.``Head`(repo, path)

  A Head is a named reference to a Commit. Every Head instance contains a name and a Commit object.

  Examples:

      >>> repo = Repo("/path/to/repo")
      >>> head = repo.heads[0]

      >>> head.name
      'master'

      >>> head.commit
      <git.Commit "1c09f116cbc2cb4100fb6935bb162daa4723f455">

      >>> head.commit.hexsha
      '1c09f116cbc2cb4100fb6935bb162daa4723f455'

  `checkout`(force=False, **kwargs)

    Checkout this head by setting the HEAD to this reference, by updating the index to reflect the tree we point to and by updating the working tree to reflect the latest index.

    The command will fail if changed working tree files would be overwritten.

    Parameters: | force – If True, changes to the index and the working tree will be discarded. If False, GitCommandError will be raised in that situation. kwargs – Additional keyword arguments to be passed to git checkout, i.e. b=’new_branch’ to create a new branch at the given spot.
    Returns: | The active branch after the checkout operation, usually self unless a new branch has been created.
    Note: | By default it is only allowed to checkout heads - everything else will leave the HEAD detached which is allowed and possible, but remains a special state that some tools might not be able to handle.

  classmethod `create`(repo, path, commit='HEAD', force=False, **kwargs)

    Create a new head. :param repo: Repository to create the head in :param path:

    > The name or path of the head, i.e. ‘new_branch’ or feature/feature1. The prefix refs/heads is implied.

    Parameters: | commit – Commit to which the new head should point, defaults to the current HEAD force – if True, force creation even if branch with that name already exists. kwargs – Additional keyword arguments to be passed to git-branch, i.e. track, no-track, l
    Returns: | Newly created Head
    Note: | This does not alter the current HEAD, index or Working Tree

  classmethod `delete`(repo, *heads, **kwargs)

    Delete the given heads :param force:

    > If True, the heads will be deleted even if they are not yet merged into the main development stream. Default False

  `rename`(new_path, force=False)

    Rename self to a new path

    Parameters: | new_path – Either a simple name or a path, i.e. new_name or features/new_name. The prefix refs/heads is implied force – If True, the rename will succeed even if a head with the target name already exists.
    Returns: | self
    Note: | respects the ref log as git commands are used

class `git.refs.``TagReference`(repo, path)

  Class representing a lightweight tag reference which either points to a commit ,a tag object or any other object. In the latter case additional information, like the signature or the tag-creator, is available.

  This tag object will always point to a commit object, but may carray additional information in a tag object:

      tagref = TagReference.list_items(repo)[0]
      print tagref.commit.message
      if tagref.tag is not None:
             print tagref.tag.message

  `commit`

    Returns: | Commit object the tag ref points to

  classmethod `create`(repo, path, ref='HEAD', message=None, force=False, **kwargs)

    Create a new tag reference.

    - Parameters: | path – The name of the tag, i.e. 1.0 or releases/1.0. The prefix refs/tags is implied ref – A reference to the object you want to tag. It can be a commit, tree or blob. message – If not None, the message will be used in your tag object. This will also create an additional tag object that allows to obtain that information, i.e.:
          tagref.tag.message
    force – If True, to force creation of a tag even though that tag already exists. kwargs – Additional keyword arguments to be passed to git-tag
    Returns: | A new TagReference

  classmethod `delete`(repo, *tags)
    Delete the given existing tag or tags
  `object`

    Returns: | The object our ref currently refers to. Refs can be cached, they will always point to the actual object as it gets re-created on each query

  `tag`

    Returns: | Tag object this tag ref points to or None in case we are a light weight tag

class `git.refs.``RemoteReference`(repo, path)

  Represents a reference pointing to a remote head.

  classmethod `delete`(repo, *refs, **kwargs)

    Delete the given remote references. :note:

    > kwargs are given for compatability with the base class method as we should not narrow the signature.

  `remote_head`

    Returns: | Name of the remote head itself, i.e. master.
    Note: | The returned name is usually not qualified enough to uniquely identify a branch

  `remote_name`

    Returns: | Name of the remote we are a reference of, such as ‘origin’ for a reference named ‘origin/master’

`git.refs.``Tag`
  alias of `TagReference`

## Remote

Module implementing a remote object allowing easy access to git remotes

class `git.remote.``RemoteProgress`

  Handler providing an interface to parse progress information emitted by git-push and git-fetch and to dispatch callbacks allowing subclasses to react to the progress.

  `line_dropped`(line)
    Called whenever a line could not be understood and was therefore dropped.
  `update`(op_code, cur_count, max_count=None, message='')

    Called whenever the progress changes

    Parameters: | op_code – Integer allowing to be compared against Operation IDs and stage IDs. Stage IDs are BEGIN and END. BEGIN will only be set once for each Operation ID as well as END. It may be that BEGIN and END are set at once in case only one progress message was emitted due to the speed of the operation. Between BEGIN and END, none of these flags will be set Operation IDs are all held within the OP_MASK. Only one Operation ID will be active per call. cur_count – Current absolute count of items max_count – The maximum count of items we expect. It may be None in case there is no maximum number of items or if it is (yet) unknown. message – In case of the ‘WRITING’ operation, it contains the amount of bytes transferred. It may possibly be used for other purposes as well.

    You may read the contents of the current line in self._cur_line

class `git.remote.``PushInfo`(flags, local_ref, remote_ref_string, remote, old_commit=None, summary='')

  Carries information about the result of a push operation of a single head:

      info = remote.push()[0]
      info.flags                      # bitflags providing more information about the result
      info.local_ref          # Reference pointing to the local reference that was pushed
                                              # It is None if the ref was deleted.
      info.remote_ref_string # path to the remote reference located on the remote side
      info.remote_ref # Remote Reference on the local side corresponding to
                                      # the remote_ref_string. It can be a TagReference as well.
      info.old_commit # commit at which the remote_ref was standing before we pushed
                                      # it to local_ref.commit. Will be None if an error was indicated
      info.summary    # summary line providing human readable english text about the push

  `flags`
  `local_ref`
  `old_commit`
  `remote_ref`

    Returns: | Remote Reference or TagReference in the local repository corresponding to the remote_ref_string kept in this instance.

  `remote_ref_string`
  `summary`

class `git.remote.``FetchInfo`(ref, flags, note='', old_commit=None)

  Carries information about the results of a fetch operation of a single head:

      info = remote.fetch()[0]
      info.ref                       # Symbolic Reference or RemoteReference to the changed
                                             # remote head or FETCH_HEAD
      info.flags                     # additional flags to be & with enumeration members,
                                             # i.e. info.flags & info.REJECTED
                                             # is 0 if ref is SymbolicReference
      info.note                      # additional notes given by git-fetch intended for the user
      info.old_commit        # if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD,
                                             # field is set to the previous location of ref, otherwise None

  `commit`

    Returns: | Commit of our remote ref

  `flags`
  `name`

    Returns: | Name of our remote ref

  `note`
  `old_commit`
  `ref`

class `git.remote.``Remote`(repo, name)

  Provides easy read and write access to a git remote.

  Everything not part of this interface is considered an option for the current remote, allowing constructs like remote.pushurl to query the pushurl.

  NOTE: When querying configuration, the configuration accessor will be cached to speed up subsequent accesses.

  classmethod `add`(repo, name, url, **kwargs)

    Create a new remote to the given repository :param repo: Repository instance that is to receive the new remote :param name: Desired name of the remote :param url: URL which corresponds to the remote’s name :param kwargs:

    > Additional arguments to be passed to the git-remote add command

    Returns: | New Remote instance
    Raises GitCommandError:
    | in case an origin with that name already exists

  `config_reader`

    Returns: | GitConfigParser compatible object able to read options for only our remote. Hence you may simple type config.get(“pushurl”) to obtain the information

  `config_writer`

    Returns: | GitConfigParser compatible object able to write options for this remote.
    Note: | You can only own one writer at a time - delete it to release the configuration file and make it useable by others. To assure consistent results, you should only query options through the writer. Once you are done writing, you are free to use the config reader once again.

  classmethod `create`(repo, name, url, **kwargs)

    Create a new remote to the given repository :param repo: Repository instance that is to receive the new remote :param name: Desired name of the remote :param url: URL which corresponds to the remote’s name :param kwargs:

    > Additional arguments to be passed to the git-remote add command

    Returns: | New Remote instance
    Raises GitCommandError:
    | in case an origin with that name already exists

  `fetch`(refspec=None, progress=None, **kwargs)

    Fetch the latest changes for this remote

    Parameters: | refspec – A “refspec” is used by fetch and push to describe the mapping between remote ref and local ref. They are combined with a colon in the format <src>:<dst>, preceded by an optional plus sign, +. For example: git fetch $URL refs/heads/master:refs/heads/origin means “grab the master branch head from the $URL and store it as my origin branch head”. And git push $URL refs/heads/master:refs/heads/to-upstream means “publish my master branch head as to-upstream branch at $URL”. See also git-push(1). Taken from the git manual progress – See ‘push’ method kwargs – Additional arguments to be passed to git-fetch
    Returns: | IterableList(FetchInfo, ...) list of FetchInfo instances providing detailed information about the fetch results
    Note: | As fetch does not provide progress information to non-ttys, we cannot make it available here unfortunately as in the ‘push’ method.

  classmethod `iter_items`(repo)

    Returns: | Iterator yielding Remote objects of the given repository

  `name`
  `pull`(refspec=None, progress=None, **kwargs)

    Pull changes from the given branch, being the same as a fetch followed by a merge of branch with your local branch.

    Parameters: | refspec – see ‘fetch’ method progress – see ‘push’ method kwargs – Additional arguments to be passed to git-pull
    Returns: | Please see ‘fetch’ method

  `push`(refspec=None, progress=None, **kwargs)

    Push changes from source branch in refspec to target branch in refspec.

    Parameters: | refspec – see ‘fetch’ method progress – Instance of type RemoteProgress allowing the caller to receive progress information until the method returns. If None, progress information will be discarded kwargs – Additional arguments to be passed to git-push
    Returns: | IterableList(PushInfo, ...) iterable list of PushInfo instances, each one informing about an individual head which had been updated on the remote side. If the push contains rejected heads, these will have the PushInfo.ERROR bit set in their flags. If the operation fails completely, the length of the returned IterableList will be null.

  `refs`

    Returns: | IterableList of RemoteReference objects. It is prefixed, allowing you to omit the remote path portion, i.e.:
        remote.refs.master # yields RemoteReference('/refs/remotes/origin/master')

  classmethod `remove`(repo, name)
    Remove the remote with the given name
  `rename`(new_name)
    Rename self to the given new_name :return: self
  `repo`
  classmethod `rm`(repo, name)
    Remove the remote with the given name
  `stale_refs`

    Returns: | IterableList RemoteReference objects that do not have a corresponding head in the remote reference anymore as they have been deleted on the remote side, but are still available locally. The IterableList is prefixed, hence the ‘origin’ must be omitted. See ‘refs’ property for an example.

  `update`(**kwargs)

    Fetch all changes for this remote, including new branches which will be forced in ( in case your local remote branch is not part the new remote branches ancestry anymore ).

    Parameter: | kwargs – Additional arguments passed to git-remote update
    Returns: | self

## Repo.Base

class `git.repo.base.``Repo`(path=None, odbt=<class 'gitdb.db.git.GitDB'>)

  Represents a git repository and allows you to query references, gather commit information, generate diffs, create and clone repositories query the log.

  The following attributes are worth using:

  ‘working_dir’ is the working directory of the git command, wich is the working tree directory if available or the .git directory in case of bare repositories

  ‘working_tree_dir’ is the working tree directory, but will raise AssertionError if we are a bare repository.

  ‘git_dir’ is the .git repository directoy, which is always set.

  `active_branch`

    The name of the currently active branch.

    Returns: | Head to the active branch

  `alternates`
    Retrieve a list of alternates paths or set a list paths to be used as alternates
  `archive`(ostream, treeish=None, prefix=None, **kwargs)

    Archive the tree at the given revision. :parm ostream: file compatible stream object to which the archive will be written :parm treeish: is the treeish name/id, defaults to active branch :parm prefix: is the optional prefix to prepend to each filename in the archive :parm kwargs:

    > Additional arguments passed to git-archive NOTE: Use the ‘format’ argument to define the kind of format. Use specialized ostreams to write any format supported by python

    Raises GitCommandError:
    | in case something went wrong
    Returns: | self

  `bare`

    Returns: | True if the repository is bare

  `blame`(rev, file)

    The blame information for the given file at the given revision.

    Parm rev: | revision specifier, see git-rev-parse for viable options.
    Returns: | list: [git.Commit, list: [<line>]] A list of tuples associating a Commit object with a list of lines that changed within the given commit. The Commit objects will be given in order of appearance.

  `branches`

    A list of `Head` objects representing the branch heads in this repo

    Returns: | `git.IterableList(Head, ...)`

  `clone`(path, **kwargs)

    Create a clone from this repository. :param path:

    > is the full path of the new repo (traditionally ends with ./<name>.git).

    Parameter: | kwargs – odbt = ObjectDatabase Type, allowing to determine the object database implementation used by the returned Repo instance All remaining keyword arguments are given to the git-clone command
    Returns: | `git.Repo` (the newly cloned repo)

  classmethod `clone_from`(url, to_path, **kwargs)
    Create a clone from the given URL :param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS :param to_path: Path to which the repository should be cloned to :param **kwargs: see the `clone` method :return: Repo instance pointing to the cloned directory
  `commit`(rev=None)
    The Commit object for the specified revision :param rev: revision specifier, see git-rev-parse for viable options. :return: `git.Commit`
  `config_reader`(config_level=None)

    Returns: | GitConfigParser allowing to read the full git configuration, but not to write it The configuration will include values from the system, user and repository configuration files.
    Parameter: | config_level – For possible values, see config_writer method If None, all applicable levels will be used. Specify a level in case you know which exact file you whish to read to prevent reading multiple files for instance
    Note: | On windows, system configuration cannot currently be read as the path is unknown, instead the global path will be used.

  `config_writer`(config_level='repository')

    Returns: | GitConfigParser allowing to write values of the specified configuration file level. Config writers should be retrieved, used to change the configuration ,and written right away as they will lock the configuration file in question and prevent other’s to write it.
    Parameter: | config_level – One of the following values system = sytem wide configuration file global = user level configuration file repository = configuration file for this repostory only

  `create_head`(path, commit='HEAD', force=False, **kwargs)

    Create a new head within the repository. For more documentation, please see the Head.create method.

    Returns: | newly created Head Reference

  `create_remote`(name, url, **kwargs)

    Create a new remote.

    For more information, please see the documentation of the Remote.create methods

    Returns: | Remote reference

  `create_tag`(path, ref='HEAD', message=None, force=False, **kwargs)

    Create a new tag reference. For more documentation, please see the TagReference.create method.

    Returns: | TagReference object

  `daemon_export`
    If True, git-daemon may export this repository
  `delete_head`(*heads, **kwargs)

    Delete the given heads

    Parameter: | kwargs – Additional keyword arguments to be passed to git-branch

  `delete_remote`(remote)
    Delete the given remote.
  `delete_tag`(*tags)
    Delete the given tag references
  `description`
    the project’s description
  `git`
  `git_dir`
  `head`

    Returns: | HEAD Object pointing to the current head reference

  `heads`

    A list of `Head` objects representing the branch heads in this repo

    Returns: | `git.IterableList(Head, ...)`

  `index`

    Returns: | IndexFile representing this repository’s index.

  classmethod `init`(path=None, mkdir=True, **kwargs)

    Initialize a git repository at the given path if specified

    Parameter: | path – is the full path to the repo (traditionally ends with /<name>.git) or None in which case the repository will be created in the current working directory
    Parm mkdir: | if specified will create the repository directory if it doesn’t already exists. Creates the directory with a mode=0755. Only effective if a path is explicitly given
    Parm kwargs: | keyword arguments serving as additional options to the git-init command
    Returns: | `git.Repo` (the newly created repo)

  `is_dirty`(index=True, working_tree=True, untracked_files=False)

    Returns: | `True`, the repository is considered dirty. By default it will react like a git-status without untracked files, hence it is dirty if the index or the working copy have changes.

  `iter_commits`(rev=None, paths='', **kwargs)

    A list of Commit objects representing the history of a given ref/commit

    Parm rev: | revision specifier, see git-rev-parse for viable options. If None, the active branch will be used.
    Parm paths: | is an optional path or a list of paths to limit the returned commits to Commits that do not contain that path or the paths will not be returned.
    Parm kwargs: | Arguments to be passed to git-rev-list - common ones are max_count and skip
    Note: | to receive only commits between two named revisions, use the “revA..revB” revision specifier

    :return `git.Commit[]`

  `iter_trees`(*args, **kwargs)

    Returns: | Iterator yielding Tree objects
    Note: | Takes all arguments known to iter_commits method

  `odb`
  `references`

    A list of Reference objects representing tags, heads and remote references.

    Returns: | IterableList(Reference, ...)

  `refs`

    A list of Reference objects representing tags, heads and remote references.

    Returns: | IterableList(Reference, ...)

  `remote`(name='origin')

    Returns: | Remote with the specified name
    Raises ValueError:
    | if no remote with such a name exists

  `remotes`
    A list of Remote objects allowing to access and manipulate remotes :return: `git.IterableList(Remote, ...)`
  `rev_parse`(repo, rev)

    Returns: | Object at the given revision, either Commit, Tag, Tree or Blob
    Parameter: | rev – git-rev-parse compatible revision specification, please see http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html for details
    Note: | Currently there is no access to the rev-log, rev-specs may only contain topological tokens such ~ and ^.
    Raises BadObject:
    | if the given revision could not be found

  `tag`(path)

    Returns: | TagReference Object, reference pointing to a Commit or Tag
    Parameter: | path – path to the tag reference, i.e. 0.1.5 or tags/0.1.5

  `tags`
    A list of `Tag` objects that are available in this repo :return: `git.IterableList(TagReference, ...)`
  `tree`(rev=None)

    The Tree object for the given treeish revision Examples:

        repo.tree(repo.heads[0])

    Parameter: | rev – is a revision pointing to a Treeish ( being a commit or tree )
    Returns: | `git.Tree`
    Note: | If you need a non-root level tree, find it by iterating the root tree. Otherwise it cannot know about its path relative to the repository root and subsequent operations might have unexpected results.

  `untracked_files`

    Returns: | list(str,...) Files currently untracked as they have not been staged yet. Paths are relative to the current working directory of the git command.
    Note: | ignored files will not appear here, i.e. files mentioned in .gitignore

  `working_dir`
  `working_tree_dir`

    Returns: | The working tree directory of our git repository
    Raises AssertionError:
    | If we are a bare repository

## Repo.Functions

Package with general repository related functions

`git.repo.fun.``rev_parse`(repo, rev)

  Returns: | Object at the given revision, either Commit, Tag, Tree or Blob
  Parameter: | rev – git-rev-parse compatible revision specification, please see http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html for details
  Note: | Currently there is no access to the rev-log, rev-specs may only contain topological tokens such ~ and ^.
  Raises BadObject:
  | if the given revision could not be found

`git.repo.fun.``is_git_dir`(d)
  This is taken from the git setup.c:is_git_directory function.

`git.repo.fun.``touch`(filename)

## Util

`git.util.``stream_copy`(source, destination, chunk_size=524288)

  Copy all data from the source stream into the destination stream in chunks of size chunk_size

  Returns: | amount of bytes written

`git.util.``join_path`(a, *p)
  Join path tokens together similar to os.path.join, but always use ‘/’ instead of possibly ‘’ on windows.

`git.util.``to_native_path_windows`(path)

`git.util.``to_native_path_linux`(path)

`git.util.``join_path_native`(a, *p)
  As join path, but makes sure an OS native path is returned. This is only needed to play it safe on my dear windows and to assure nice paths that only use ‘’

class `git.util.``Stats`(total, files)

  Represents stat information as presented by git at the end of a merge. It is created from the output of a diff operation.

  `Example`:

      c = Commit( sha1 )
      s = c.stats
      s.total                 # full-stat-dict
      s.files                 # dict( filepath : stat-dict )

  `stat-dict`

  A dictionary with the following keys and values:

      deletions = number of deleted lines as int
      insertions = number of inserted lines as int
      lines = total number of lines changed as int, or deletions + insertions

  `full-stat-dict`

  In addition to the items in the stat-dict, it features additional information:

      files = number of changed files as int

  `files`
  `total`

class `git.util.``IndexFileSHA1Writer`(f)

  Wrapper around a file-like object that remembers the SHA1 of the data written to it. It will write a sha when the stream is closed or if the asked for explicitly usign write_sha.

  Only useful to the indexfile

  Note: | Based on the dulwich project

  `close`()
  `f`
  `sha1`
  `tell`()
  `write`(data)
  `write_sha`()

class `git.util.``Iterable`

  Defines an interface for iterable items which is to assure a uniform way to retrieve and iterate items within the git repository

  classmethod `iter_items`(repo, *args, **kwargs)
    For more information about the arguments, see list_items :return: iterator yielding Items
  classmethod `list_items`(repo, *args, **kwargs)

    Find all items of this type - subclasses can specify args and kwargs differently. If no args are given, subclasses are obliged to return all items if no additional arguments arg given.

    Note: | Favor the iter_items method as it will

    :return:list(Item,...) list of item instances

class `git.util.``IterableList`(id_attr, prefix='')

  List of iterable objects allowing to query an object by id or by named index:

      heads = repo.heads
      heads.master
      heads['master']
      heads[0]

  It requires an id_attribute name to be set which will be queried from its contained items to have a means for comparison.

  A prefix can be specified which is to be used in case the id returned by the items always contains a prefix that does not matter to the user, so it can be left out.

class `git.util.``BlockingLockFile`(file_path, check_interval_s=0.29999999999999999, max_block_time_s=9223372036854775807)

  The lock file will block until a lock could be obtained, or fail after a specified timeout.

  Note: | If the directory containing the lock was removed, an exception will be raised during the blocking period, preventing hangs as the lock can never be obtained.

class `git.util.``LockFile`(file_path)

  Provides methods to obtain, check for, and release a file based lock which should be used to handle concurrent access to the same file.

  As we are a utility class to be derived from, we only use protected methods.

  Locks will automatically be released on destruction

### Navigation

- index
- modules |
- next |
- previous |
- GitPython v0.3.0-beta2 documentation »