API Reference
Top-Level
- git.__version__
Current GitPython version.
- git.refresh(path:str|os.PathLike[str]|None=None)→None
Convenience method for setting the git executable path.
- Parameters:
path – Optional path to the Git executable. If not absolute, it is resolvedimmediately, relative to the current directory.
- Note:
Thepath parameter is usually omitted and cannot be used to specify a customcommand whose location is looked up in a path search on each call. See
Git.refresh
for details on how to achieve this.- Note:
This calls
Git.refresh
and sets other globalconfiguration according to the effect of doing so. As such, this function shouldusually be used instead of usingGit.refresh
orFetchInfo.refresh
directly.- Note:
This function is called automatically, with no arguments, at import time.
Objects.Base
- classgit.objects.base.IndexObject(repo:Repo,binsha:bytes,mode:None|int=None,path:None|str|os.PathLike[str]=None)
Base for all objects that can be part of the index file.
The classes representing git object types that can be part of the index file are
Blob
. In addition,Submodule
, which is not really a git objecttype but can be part of an index file, is also a subclass.- __annotations__={}
- __hash__()→int
- Returns:
Hash of our path as index items are uniquely identifiable by path, not bytheir data!
- __init__(repo:Repo,binsha:bytes,mode:None|int=None,path:None|str|os.PathLike[str]=None)→None
Initialize a newly instanced
IndexObject
.- Parameters:
repo – The
Repo
we are located in.binsha – 20 byte sha1.
mode – The stat-compatible file mode as
int
.Use thestat
module to evaluate the information.path – The path to the file in the file system, relative to the git repositoryroot, like
file.ext
orfolder/other.ext
.
- Note:
Path may not be set if the index object has been created directly, as itcannot be retrieved without knowing the parent tree.
- __module__='git.objects.base'
- __slots__=('path','mode')
- propertyabspath:str|os.PathLike[str]
- 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
\
onWindows.
- mode
- propertyname:str
- Returns:
Name portion of the path, effectively being the basename
- path
- classgit.objects.base.Object(repo:Repo,binsha:bytes)
Base class for classes representing git object types.
The following four leaf classes represent specific kinds of git objects:
Seegitglossary(7) on:
“object type”:https://git-scm.com/docs/gitglossary#def_object_type
“tree object”:https://git-scm.com/docs/gitglossary#def_tree_object
“commit object”:https://git-scm.com/docs/gitglossary#def_commit_object
“tag object”:https://git-scm.com/docs/gitglossary#def_tag_object
- Note:
See the
AnyGitObject
union type of the four leaf subclassesthat represent actual git object types.- Note:
Submodule
is defined under the hierarchyrooted at thisObject
class, even though submodules are not really atype of git object. (This also applies to itsRootModule
subclass.)- Note:
This
Object
class should not be confused withobject
(the rootof the class hierarchy in Python).
- NULL_BIN_SHA=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- NULL_HEX_SHA='0000000000000000000000000000000000000000'
- TYPES=(b'blob',b'tree',b'commit',b'tag')
- __annotations__={'type':typing.Optional[typing.Literal['commit','tag','blob','tree']]}
- __eq__(other:Any)→bool
- Returns:
True
if the objects have the same SHA1
- __hash__()→int
- Returns:
Hash of our id allowing objects to be used in dicts and sets
- __init__(repo:Repo,binsha:bytes)→None
Initialize an object by identifying it by its binary sha.
All keyword arguments will be set on demand if
None
.- Parameters:
repo – Repository this object is located in.
binsha – 20 byte SHA1
- __module__='git.objects.base'
- __ne__(other:Any)→bool
- Returns:
True
if the objects do not have the same SHA1
- __repr__()→str
- Returns:
String with pythonic representation of our object
- __slots__=('repo','binsha','size')
- __str__()→str
- Returns:
String of our SHA1 as understood by all git commands
- binsha
- propertydata_stream:OStream
- Returns:
File-object compatible stream to the uncompressed raw data of the object
- Note:
Returned streams must be read in order.
- propertyhexsha:str
- Returns:
40 byte hex version of our 20 byte binary sha
- classmethodnew(repo:Repo,id:str|Reference)→Commit|Tree|TagObject|Blob
- Returns:
New
Object
instance of a type appropriate to the object type behindid. The id of the newly created object will be a binsha even though theinput id may have been a~git.refs.reference.Reference or rev-spec.- Parameters:
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.
- classmethodnew_from_sha(repo:Repo,sha1:bytes)→Commit|Tree|TagObject|Blob
- Returns:
New object instance of a type appropriate to represent the given binary sha1
- Parameters:
sha1 – 20 byte binary sha1.
- repo
- size
- stream_data(ostream:OStream)→Object
Write our data directly to the given output stream.
- Parameters:
ostream – File-object compatible stream object.
- Returns:
self
- type:Literal['commit','tag','blob','tree']|None=None
String identifying (a concrete
Object
subtype for) a git object type.The subtypes that this may name correspond to the kinds of git objects that exist,i.e., the objects that may be present in a git repository.
- Note:
Most subclasses represent specific types of git objects and override this classattribute accordingly. This attribute is
None
in theObject
baseclass, as well as theIndexObject
intermediate subclass, but neverNone
in concrete leaf subclasses representing specific git object types.- Note:
See also
GitObjectTypeString
.
Objects.Blob
- classgit.objects.blob.Blob(repo:Repo,binsha:bytes,mode:None|int=None,path:None|str|os.PathLike[str]=None)
A Blob encapsulates a git blob object.
Seegitglossary(7) on “blob”:https://git-scm.com/docs/gitglossary#def_blob_object
- DEFAULT_MIME_TYPE='text/plain'
- __annotations__={'type':typing.Literal['blob']}
- __module__='git.objects.blob'
- __slots__=()
- executable_mode=33261
- file_mode=33188
- link_mode=40960
- propertymime_type:str
- 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.
- type:Literal['blob']='blob'
String identifying (a concrete
Object
subtype for) a git object type.The subtypes that this may name correspond to the kinds of git objects that exist,i.e., the objects that may be present in a git repository.
- Note:
Most subclasses represent specific types of git objects and override this classattribute accordingly. This attribute is
None
in theObject
baseclass, as well as theIndexObject
intermediate subclass, but neverNone
in concrete leaf subclasses representing specific git object types.- Note:
See also
GitObjectTypeString
.
Objects.Commit
- classgit.objects.commit.Commit(repo:Repo,binsha:bytes,tree:Tree|None=None,author:Actor|None=None,authored_date:int|None=None,author_tz_offset:None|float=None,committer:Actor|None=None,committed_date:int|None=None,committer_tz_offset:None|float=None,message:str|bytes|None=None,parents:Sequence[Commit]|None=None,encoding:str|None=None,gpgsig:str|None=None)
Wraps a git commit object.
Seegitglossary(7) on “commit object”:https://git-scm.com/docs/gitglossary#def_commit_object
- Note:
This class will act lazily on some of its attributes and will query the value ondemand only if it involves calling the git binary.
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','parents':typing.Sequence[ForwardRef('Commit')],'repo':"'Repo'",'type':typing.Literal['commit']}
- __init__(repo:Repo,binsha:bytes,tree:Tree|None=None,author:Actor|None=None,authored_date:int|None=None,author_tz_offset:None|float=None,committer:Actor|None=None,committed_date:int|None=None,committer_tz_offset:None|float=None,message:str|bytes|None=None,parents:Sequence[Commit]|None=None,encoding:str|None=None,gpgsig:str|None=None)→None
Instantiate a new
Commit
. All keyword arguments takingNone
asdefault will be implicitly set on first query.- Parameters:
binsha – 20 byte sha1.
tree – A
Tree
object.author – The author
Actor
object.authored_date – int_seconds_since_epochThe authored DateTime - use
time.gmtime()
to convert it into adifferent format.author_tz_offset – int_seconds_west_of_utcThe timezone that theauthored_date is in.
committer – The committer string, as an
Actor
object.committed_date – int_seconds_since_epochThe committed DateTime - use
time.gmtime()
to convert it into adifferent format.committer_tz_offset – int_seconds_west_of_utcThe timezone that thecommitted_date is in.
message – stringThe commit message.
encoding – stringEncoding of the message, defaults to UTF-8.
parents – List or tuple of
Commit
objects which are our parent(s) in thecommit dependency graph.
- Returns:
- Note:
Timezone information is in the same format and in the same sign as what
time.altzone()
returns. The sign is inverted compared to git’s UTCtimezone.
- __module__='git.objects.commit'
- __parameters__=()
- __slots__=('tree','author','authored_date','author_tz_offset','committer','committed_date','committer_tz_offset','message','parents','encoding','gpgsig')
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- author
- author_tz_offset
- authored_date
- propertyauthored_datetime:datetime
- propertyco_authors:List[Actor]
Search the commit message for any co-authors of this commit.
Details on co-authors:https://github.blog/2018-01-29-commit-together-with-co-authors/
- Returns:
List of co-authors for this commit (as
Actor
objects).
- committed_date
- propertycommitted_datetime:datetime
- committer
- committer_tz_offset
- conf_encoding='i18n.commitencoding'
- count(paths:str|PathLike[str]|Sequence[str|PathLike[str]]='',**kwargs:Any)→int
Count the number of commits reachable from this commit.
- Parameters:
paths – An optional path or a list of paths restricting the return value to commitsactually containing the paths.
kwargs – Additional options to be passed togit-rev-list(1). They must notalter the output style of the command, or parsing will yield incorrectresults.
- Returns:
An int defining the number of reachable commits
- classmethodcreate_from_tree(repo:Repo,tree:Tree|str,message:str,parent_commits:None|List[Commit]=None,head:bool=False,author:None|Actor=None,committer:None|Actor=None,author_date:None|str|datetime=None,commit_date:None|str|datetime=None)→Commit
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 willbe converted to a string, in any case.
parent_commits – Optional
Commit
objects to use as parents for the new commit. Ifempty list, the commit will have no parents at all and become a root commit.IfNone
, the current head commit will be the parent of the new commitobject.head – If
True
, the HEAD will be advanced to the new commit automatically.Otherwise the HEAD will remain pointing on the previous commit. This couldlead to undesired results when diffing files.author – The name of the author, optional.If unset, the repository configuration is used to obtain this value.
committer – The name of the committer, optional.If unset, the repository configuration is used to obtain this value.
author_date – The timestamp for the author field.
commit_date – The timestamp for the committer field.
- Returns:
Commit
object representing the new commit.- Note:
Additional information about the committer and author are taken from theenvironment or from the git configuration. Seegit-commit-tree(1)for more information.
- default_encoding='UTF-8'
- encoding
- env_author_date='GIT_AUTHOR_DATE'
- env_committer_date='GIT_COMMITTER_DATE'
- gpgsig
- classmethoditer_items(repo:Repo,rev:str|Commit|SymbolicReference,paths:str|os.PathLike[str]|Sequence[str|os.PathLike[str]]='',**kwargs:Any)→Iterator[Commit]
Find all commits matching the given criteria.
- Parameters:
repo – The
Repo
.rev – Revision specifier. Seegit-rev-parse(1) for viable options.
paths – An optional path or list of paths. If set only
Commit
s thatinclude the path or paths will be considered.kwargs –
Optional keyword arguments togit-rev-list(1) where:
max_count
is the maximum number of commits to fetch.skip
is the number of commits to skip.since
selects all commits since some date, e.g."1970-01-01"
.
- Returns:
Iterator yielding
Commit
items.
- iter_parents(paths:str|PathLike[str]|Sequence[str|PathLike[str]]='',**kwargs:Any)→Iterator[Commit]
Iterate _all_ parents of this commit.
- Parameters:
paths – Optional path or list of paths limiting the
Commit
s to those thatcontain at least one of the paths.kwargs – All arguments allowed bygit-rev-list(1).
- Returns:
Iterator yielding
Commit
objects which are parents ofself
- message
- propertyname_rev:str
- Returns:
String describing the commits hex sha based on the closest~git.refs.reference.Reference.
- Note:
Mostly useful for UI purposes.
- replace(**kwargs:Any)→Commit
Create new commit object from an existing commit object.
Any values provided as keyword arguments will replace the correspondingattribute in the new object.
- propertystats:Stats
Create a git stat from changes between this commit and its first parentor from all changes done if this is the very first commit.
- Returns:
Stats
- propertysummary:str|bytes
- Returns:
First line of the commit message
- propertytrailers:Dict[str,str]
Deprecated. Get the trailers of the message as a dictionary.
- Note:
This property is deprecated, please use either
trailers_list
ortrailers_dict
.- Returns:
Dictionary containing whitespace stripped trailer information.Only contains the latest instance of each trailer key.
- propertytrailers_dict:Dict[str,List[str]]
Get the trailers of the message as a dictionary.
Git messages can contain trailer information that are similar toRFC 822e-mail headers. Seegit-interpret-trailers(1).
This function calls
gitinterpret-trailers--parse
onto the message toextract the trailer information. The key value pairs are stripped of leading andtrailing whitespaces before they get saved into a dictionary.Valid message with trailer:
Subjectlinesomebodyinformationanotherinformationkey1:value1.1key1:value1.2key2:value2withinnerspaces
Returned dictionary will look like this:
{"key1":["value1.1","value1.2"],"key2":["value 2 with inner spaces"],}
- Returns:
Dictionary containing whitespace stripped trailer information, mappingtrailer keys to a list of their corresponding values.
- propertytrailers_list:List[Tuple[str,str]]
Get the trailers of the message as a list.
Git messages can contain trailer information that are similar toRFC 822e-mail headers. Seegit-interpret-trailers(1).
This function calls
gitinterpret-trailers--parse
onto the message toextract the trailer information, returns the raw trailer data as a list.Valid message with trailer:
Subjectlinesomebodyinformationanotherinformationkey1:value1.1key1:value1.2key2:value2withinnerspaces
Returned list will look like this:
[("key1","value1.1"),("key1","value1.2"),("key2","value 2 with inner spaces"),]
- Returns:
List containing key-value tuples of whitespace stripped trailer information.
- tree
- type:Literal['commit']='commit'
String identifying (a concrete
Object
subtype for) a git object type.The subtypes that this may name correspond to the kinds of git objects that exist,i.e., the objects that may be present in a git repository.
- Note:
Most subclasses represent specific types of git objects and override this classattribute accordingly. This attribute is
None
in theObject
baseclass, as well as theIndexObject
intermediate subclass, but neverNone
in concrete leaf subclasses representing specific git object types.- Note:
See also
GitObjectTypeString
.
Objects.Tag
Provides anObject
-based type for annotated tags.
This defines theTagObject
class, which represents annotated tags.For lightweight tags, see thegit.refs.tag
module.
- classgit.objects.tag.TagObject(repo:Repo,binsha:bytes,object:None|Object=None,tag:None|str=None,tagger:None|Actor=None,tagged_date:int|None=None,tagger_tz_offset:int|None=None,message:str|None=None)
Annotated (i.e. non-lightweight) tag carrying additional information about anobject we are pointing to.
Seegitglossary(7) on “tag object”:https://git-scm.com/docs/gitglossary#def_tag_object
- __annotations__={'type':typing.Literal['tag']}
- __init__(repo:Repo,binsha:bytes,object:None|Object=None,tag:None|str=None,tagger:None|Actor=None,tagged_date:int|None=None,tagger_tz_offset:int|None=None,message:str|None=None)→None
Initialize a tag object with additional data.
- Parameters:
repo – Repository this object is located in.
binsha – 20 byte SHA1.
object –
Object
instance of object we are pointing to.tag – Name of this tag.
tagger –
Actor
identifying the tagger.tagged_date – int_seconds_since_epochThe DateTime of the tag creation.Use
time.gmtime()
to convert it into a different format.tagger_tz_offset – int_seconds_west_of_utcThe timezone that thetagged_date is in, in a format similar to
time.altzone
.
- __module__='git.objects.tag'
- __slots__=('object','tag','tagger','tagged_date','tagger_tz_offset','message')
- message
- object:'Commit'|'Blob'|'Tree'|'TagObject'
- tag
- tagged_date
- tagger
- tagger_tz_offset
- type:Literal['tag']='tag'
String identifying (a concrete
Object
subtype for) a git object type.The subtypes that this may name correspond to the kinds of git objects that exist,i.e., the objects that may be present in a git repository.
- Note:
Most subclasses represent specific types of git objects and override this classattribute accordingly. This attribute is
None
in theObject
baseclass, as well as theIndexObject
intermediate subclass, but neverNone
in concrete leaf subclasses representing specific git object types.- Note:
See also
GitObjectTypeString
.
Objects.Tree
- classgit.objects.tree.Tree(repo:Repo,binsha:bytes,mode:int=16384,path:str|os.PathLike[str]|None=None)
Tree objects represent an ordered list of
Blob
s andotherTree
s.Seegitglossary(7) on “tree object”:https://git-scm.com/docs/gitglossary#def_tree_object
Subscripting is supported, as with a list or dict:
Access a specific blob using the
tree["filename"]
notation.You may likewise access by index, like
blob=tree[0]
.
- __abstractmethods__=frozenset({})
- __annotations__={'_map_id_to_type':typing.Dict[int,typing.Type[typing.Union[ForwardRef('Tree'),ForwardRef('Blob'),ForwardRef('Submodule')]]],'repo':"'Repo'",'type':typing.Literal['tree']}
- __init__(repo:Repo,binsha:bytes,mode:int=16384,path:str|os.PathLike[str]|None=None)
Initialize a newly instanced
IndexObject
.- Parameters:
repo – The
Repo
we are located in.binsha – 20 byte sha1.
mode – The stat-compatible file mode as
int
.Use thestat
module to evaluate the information.path – The path to the file in the file system, relative to the git repositoryroot, like
file.ext
orfolder/other.ext
.
- Note:
Path may not be set if the index object has been created directly, as itcannot be retrieved without knowing the parent tree.
- __len__()→int
- __module__='git.objects.tree'
- __slots__=('_cache',)
- __truediv__(file:str)→Tree|Blob|Submodule
The
/
operator is another syntax for joining.See
join()
for details.
- blob_id=8
- propertycache:TreeModifier
- Returns:
An object allowing modification of the internal cache. This can be used tochange the tree’s contents. When done, make sure you call
set_done()
on the tree modifier, or serializationbehaviour will be incorrect.- Note:
See
TreeModifier
for more information on how to alter the cache.
- commit_id=14
- list_traverse(*args:Any,**kwargs:Any)→IterableList[Tree|Blob|Submodule]
- Returns:
IterableList
with the results of the traversal asproduced bytraverse()
Tree -> IterableList[Union[Submodule, Tree, Blob]]
- symlink_id=10
- traverse(predicate:~typing.Callable[[~git.objects.tree.Tree|~git.objects.blob.Blob|~git.objects.submodule.base.Submodule|~typing.Tuple[~git.objects.tree.Tree|None,~git.objects.tree.Tree|~git.objects.blob.Blob|~git.objects.submodule.base.Submodule,~typing.Tuple[~git.objects.submodule.base.Submodule,~git.objects.submodule.base.Submodule]],int],bool]=<functionTree.<lambda>>,prune:~typing.Callable[[~git.objects.tree.Tree|~git.objects.blob.Blob|~git.objects.submodule.base.Submodule|~typing.Tuple[~git.objects.tree.Tree|None,~git.objects.tree.Tree|~git.objects.blob.Blob|~git.objects.submodule.base.Submodule,~typing.Tuple[~git.objects.submodule.base.Submodule,~git.objects.submodule.base.Submodule]],int],bool]=<functionTree.<lambda>>,depth:int=-1,branch_first:bool=True,visit_once:bool=False,ignore_self:int=1,as_edge:bool=False)→Iterator[Tree|Blob|Submodule]|Iterator[Tuple[Tree|None,Tree|Blob|Submodule,Tuple[Submodule,Submodule]]]
For documentation, seeTraversable._traverse() <git.objects.util.Traversable._traverse>.
Trees are set to
visit_once=False
to gain more performance in thetraversal.
- tree_id=4
- type:Literal['tree']='tree'
String identifying (a concrete
Object
subtype for) a git object type.The subtypes that this may name correspond to the kinds of git objects that exist,i.e., the objects that may be present in a git repository.
- Note:
Most subclasses represent specific types of git objects and override this classattribute accordingly. This attribute is
None
in theObject
baseclass, as well as theIndexObject
intermediate subclass, but neverNone
in concrete leaf subclasses representing specific git object types.- Note:
See also
GitObjectTypeString
.
- classgit.objects.tree.TreeModifier(cache:List[Tuple[bytes,int,str]])
A utility class providing methods to alter the underlying cache in a list-likefashion.
Once all adjustments are complete, the
_cache
, which really is a referenceto the cache of a tree, will be sorted. This ensures it will be in a serializablestate.- __delitem__(name:str)→None
Delete an item with the given name if it exists.
- __init__(cache:List[Tuple[bytes,int,str]])→None
- __module__='git.objects.tree'
- __slots__=('_cache',)
- add(sha:bytes,mode:int,name:str,force:bool=False)→TreeModifier
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 notmatch the one you add, unlessforce isTrue
.- 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 anyexisting item with the same name, no matter which information it has.
- Returns:
self
- add_unchecked(binsha:bytes,mode:int,name:str)→None
Add the given item to the tree. Its correctness is assumed, so it is thecaller’s responsibility to ensure that the input is correct.
For more information on the parameters, see
add()
.- Parameters:
binsha – 20 byte binary sha.
- set_done()→TreeModifier
Call this method once you are done modifying the tree information.
This may be called several times, but be aware that each call will cause a sortoperation.
- Returns:
self
Objects.Functions
Functions that are supposed to be as fast as possible.
- git.objects.fun.traverse_tree_recursive(odb:GitCmdObjectDB,tree_sha:bytes,path_prefix:str)→List[Tuple[bytes,int,str]]
- Returns:
List of entries of the tree pointed to by the binarytree_sha.
An entry has the following format:
[0] 20 byte sha
[1] mode as int
[2] path relative to the repository
- Parameters:
path_prefix – Prefix to prepend to the front of all returned paths.
- git.objects.fun.traverse_trees_recursive(odb:GitCmdObjectDB,tree_shas:Sequence[bytes|None],path_prefix:str)→List[Tuple[Tuple[bytes,int,str]|None,...]]
- Returns:
List of list with entries according to the given binary tree-shas.
The result is encoded in a listof 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 thegiven 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 caseNone
.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.tree_entries_from_data(data:bytes)→List[Tuple[bytes,int,str]]
Read the binary representation of a tree and returns tuples of
Tree
items.- Parameters:
data – Data block with tree data (as bytes).
- Returns:
list(tuple(binsha, mode, tree_relative_path), …)
- git.objects.fun.tree_to_stream(entries:Sequence[Tuple[bytes,int,str]],write:Callable[[ReadableBuffer],int|None])→None
Write the given list of entries into a stream using its
write
method.- Parameters:
entries –Sorted list of tuples with (binsha, mode, name).
write – A
write
method which takes a data string.
Objects.Submodule.base
- classgit.objects.submodule.base.Submodule(repo:Repo,binsha:bytes,mode:int|None=None,path:str|os.PathLike[str]|None=None,name:str|None=None,parent_commit:Commit|None=None,url:str|None=None,branch_path:str|os.PathLike[str]|None=None)
Implements access to a git submodule. They are special in that their sharepresents a commit in the submodule’s repository which is to be checked outat the path of this instance.
The submodule type does not have a string type associated with it, as it existssolely as a marker in the tree and index.
All methods work in bare and non-bare repositories.
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','type':typing.Literal['submodule']}
- __eq__(other:Any)→bool
Compare with another submodule.
- __hash__()→int
Hash this instance using its logical id, not the sha.
- __init__(repo:Repo,binsha:bytes,mode:int|None=None,path:str|os.PathLike[str]|None=None,name:str|None=None,parent_commit:Commit|None=None,url:str|None=None,branch_path:str|os.PathLike[str]|None=None)→None
Initialize this instance with its attributes.
We only document the parameters that differ from
IndexObject
.- Parameters:
repo – Our parent repository.
binsha – Binary sha referring to a commit in the remote repository.See theurl parameter.
parent_commit – The
Commit
whose tree is supposed to containthe.gitmodules
blob, orNone
to always point to the most recentcommit. Seeset_parent_commit()
for details.url – The URL to the remote repository which is the submodule.
branch_path – Full repository-relative path to ref to checkout when cloning the remoterepository.
- __module__='git.objects.submodule.base'
- __ne__(other:object)→bool
Compare with another submodule for inequality.
- __parameters__=()
- __repr__()→str
- Returns:
String with pythonic representation of our object
- __slots__=('_parent_commit','_url','_branch_path','_name','__weakref__')
- __str__()→str
- Returns:
String of our SHA1 as understood by all git commands
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- __weakref__
- classmethodadd(repo:Repo,name:str,path:str|os.PathLike[str],url:str|None=None,branch:str|None=None,no_checkout:bool=False,depth:int|None=None,env:Mapping[str,str]|None=None,clone_multi_options:Sequence[Any]|None=None,allow_unsafe_options:bool=False,allow_unsafe_protocols:bool=False)→Submodule
Add a new submodule to the given repository. This will alter the index aswell as the
.gitmodules
file, but will not create a new commit. If thesubmodule already exists, no matter if the configuration differs from the oneprovided, the existing submodule will be returned.- Parameters:
repo – Repository instance which should receive the submodule.
name – The name/identifier for the submodule.
path – Repository-relative or absolute path at which the submodule should belocated.It will be created as required during the repository initialization.
url –
gitclone...
-compatible URL. Seegit-clone(1) for moreinformation. IfNone
, the repository is assumed to exist, and the URL ofthe first remote is taken instead. This is useful if you want to make anexisting repository a submodule of another one.branch – Name of branch at which the submodule should (later) be checked out. Thegiven branch must exist in the remote repository, and will be checked outlocally as a tracking branch.It will only be written into the configuration if it not
None
, which iswhen the checked out branch will be the one the remote HEAD pointed to.The result you get in these situation is somewhat fuzzy, and it isrecommended to specify at leastmaster
here.Examples aremaster
orfeature/new
.no_checkout – If
True
, and if the repository has to be cloned manually, no checkoutwill be performed.depth – Create a shallow clone with a history truncated to the specified number ofcommits.
env –
Optional dictionary containing the desired environment variables.
Note: Provided variables will be used to update the execution environmentfor
git
. If some variable is not specified inenv and is defined inattr:os.environ, the value from attr:os.environ will be used. If youwant to unset some variable, consider providing an empty string as itsvalue.clone_multi_options – A list of clone options. Please see
Repo.clone
for details.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.
- Returns:
The newly created
Submodule
instance.- Note:
Works atomically, such that no change will be done if, for example, therepository update fails.
- propertybranch:Head
- Returns:
The branch instance that we are to checkout
- Raises:
git.exc.InvalidGitRepositoryError – If our module is not yet checked out.
- propertybranch_name:str
- Returns:
The name of the branch, which is the shortest possible branch name
- propertybranch_path:str|PathLike[str]
- Returns:
Full repository-relative path as string to the branch we would checkout fromthe remote and track
- children()→IterableList[Submodule]
- Returns:
IterableList(Submodule, …) An iterable list of
Submodule
instances which are children of this submodule or 0 if the submodule is notchecked out.
- config_reader()→SectionConstraint[SubmoduleConfigParser]
- Returns:
ConfigReader instance which allows you to query the configuration values ofthis submodule, as provided by the
.gitmodules
file.- Note:
The config reader will actually read the data directly from the repositoryand thus does not need nor care about your working tree.
- Note:
Should be cached by the caller and only kept as long as needed.
- Raises:
IOError – If the
.gitmodules
file/blob could not be read.
- config_writer(index:IndexFile|None=None,write:bool=True)→SectionConstraint[SubmoduleConfigParser]
- Returns:
A config writer instance allowing you to read and write the data belongingto this submodule into the
.gitmodules
file.- Parameters:
- Note:
The parameters allow for a more efficient writing of the index, as you canpass in a modified index on your own, prevent automatic writing, and writeyourself once the whole operation is complete.
- Raises:
ValueError – If trying to get a writer on a parent_commit which does not match thecurrent head commit.
IOError – If the
.gitmodules
file/blob could not be read.
- exists()→bool
- Returns:
True
if the submodule exists,False
otherwise.Please note that a submodule may exist (in the.gitmodules
file) eventhough its module doesn’t exist on disk.
- classmethoditer_items(repo:Repo,parent_commit:Commit|TagObject|str='HEAD',*args:Any,**kwargs:Any)→Iterator[Submodule]
- Returns:
Iterator yielding
Submodule
instances available in the givenrepository
- k_default_mode=57344
Submodule flags. Submodules are directories with link-status.
- k_head_default='master'
- k_head_option='branch'
- k_modules_file='.gitmodules'
- module()→Repo
- Returns:
Repo
instance initialized from the repository at oursubmodule path- Raises:
git.exc.InvalidGitRepositoryError – If a repository was not available.This could also mean that it was not yet initialized.
- module_exists()→bool
- Returns:
True
if our module exists and is a valid git repository.See themodule()
method.
- move(module_path:str|PathLike[str],configuration:bool=True,module:bool=True)→Submodule
Move the submodule to a another module path. This involves physically movingthe repository at our current path, changing the configuration, as well asadjusting our index entry accordingly.
- Parameters:
module_path – The path to which to move our module in the parent repository’s workingtree, given as repository-relative or absolute path. Intermediatedirectories will be created accordingly. If the path already exists, it mustbe empty. Trailing (back)slashes are removed automatically.
configuration – If
True
, the configuration will be adjusted to let the submodule pointto the given path.module – If
True
, the repository managed by this submodule will be moved as well.IfFalse
, we don’t move the submodule’s checkout, which may leave theparent repository in an inconsistent state.
- Returns:
self
- Raises:
ValueError – If the module path existed and was not empty, or was a file.
- Note:
Currently the method is not atomic, and it could leave the repository in aninconsistent state if a sub-step fails for some reason.
- propertyname:str
- Returns:
The name of this submodule. It is used to identify it within the
.gitmodules
file.- Note:
By default, this is the name is the path at which to find the submodule, butin GitPython it should be a unique identifier similar to the identifiersused for remotes, which allows to change the path of the submodule easily.
- propertyparent_commit:Commit
- Returns:
Commit
instance with the tree containing the.gitmodules
file- Note:
Will always point to the current head’s commit if it was not set explicitly.
- remove(module:bool=True,force:bool=False,configuration:bool=True,dry_run:bool=False)→Submodule
Remove this submodule from the repository. This will remove our entryfrom the
.gitmodules
file and the entry in the.git/config
file.- Parameters:
module –
If
True
, the checked out module we point to will be deleted as well. Ifthat module is currently on a commit outside any branch in the remote, or ifit is ahead of its tracking branch, or if there are modified or untrackedfiles in its working tree, then the removal will fail. In case the removalof the repository fails for these reasons, the submodule status will nothave been altered.If this submodule has child modules of its own, these will be deleted priorto touching the direct submodule.
force – Enforces the deletion of the module even though it contains modifications.This basically enforces a brute-force file system based deletion.
configuration – If
True
, the submodule is deleted from the configuration, otherwise itisn’t. Although this should be enabled most of the time, this flag enablesyou to safely delete the repository of your submodule.dry_run – If
True
, we will not actually do anything, but throw the errors we wouldusually throw.
- Returns:
self
- Note:
Doesn’t work in bare repositories.
- Note:
Doesn’t work atomically, as failure to remove any part of the submodule willleave an inconsistent state.
- Raises:
git.exc.InvalidGitRepositoryError – Thrown if the repository cannot be deleted.
OSError – If directories or files could not be removed.
- rename(new_name:str)→Submodule
Rename this submodule.
- Note:
This method takes care of renaming the submodule in various places, such as:
$parent_git_dir/config
$working_tree_dir/.gitmodules
(git >= v1.8.0: move submodule repository to new name)
As
.gitmodules
will be changed, you would need to make a commit afterwards.The changed.gitmodules
file will already be added to the index.- Returns:
This
Submodule
instance
- set_parent_commit(commit:Commit|TagObject|str|None,check:bool=True)→Submodule
Set this instance to use the given commit whose tree is supposed tocontain the
.gitmodules
blob.- Parameters:
commit – Commit-ish reference pointing at the root tree, or
None
to always pointto the most recent commit.check – If
True
, relatively expensive checks will be performed to verifyvalidity of the submodule.
- Raises:
ValueError – If the commit’s tree didn’t contain the
.gitmodules
blob.ValueError – If the parent commit didn’t store this submodule under the current path.
- Returns:
self
- type:Literal['submodule']='submodule'
This is a bogus type string for base class compatibility.
- update(recursive:bool=False,init:bool=True,to_latest_revision:bool=False,progress:UpdateProgress|None=None,dry_run:bool=False,force:bool=False,keep_going:bool=False,env:Mapping[str,str]|None=None,clone_multi_options:Sequence[Any]|None=None,allow_unsafe_options:bool=False,allow_unsafe_protocols:bool=False)→Submodule
Update the repository of this submodule to point to the checkout we point atwith the binsha of this instance.
- Parameters:
recursive – If
True
, we will operate recursively and update child modules as well.init – If
True
, the module repository will be cloned into place if necessary.to_latest_revision – If
True
, the submodule’s sha will be ignored during checkout. Instead,the remote will be fetched, and the local tracking branch updated. This onlyworks if we have a local tracking branch, which is the case if the remoterepository had a master branch, or if thebranch
option was specifiedfor this submodule and the branch existed remotely.progress –
UpdateProgress
instance, orNone
if no progress should beshown.dry_run – If
True
, the operation will only be simulated, but not performed.All performed operations are read-only.force –
If
True
, we may reset heads even if the repository in question is dirty.Additionally we will be allowed to set a tracking branch which is ahead ofits remote branch back into the past or the location of the remote branch.This will essentially ‘forget’ commits.If
False
, local tracking branches that are in the future of theirrespective remote branches will simply not be moved.keep_going – If
True
, we will ignore but log all errors, and keep going recursively.Unlessdry_run is set as well,keep_going could causesubsequent/inherited errors you wouldn’t see otherwise.In conjunction withdry_run, it can be useful to anticipate all errorswhen updating submodules.env –
Optional dictionary containing the desired environment variables.
Note: Provided variables will be used to update the execution environmentfor
git
. If some variable is not specified inenv and is defined inattr:os.environ, value from attr:os.environ will be used.If you want to unset some variable, consider providing the empty string asits value.
clone_multi_options – List ofgit-clone(1) options.Please see
Repo.clone
for details.They only take effect with theinit option.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.
- Note:
Does nothing in bare repositories.
- Note:
This method is definitely not atomic ifrecursive is
True
.- Returns:
self
- propertyurl:str
- Returns:
The url to the repository our submodule’s repository refers to
- classgit.objects.submodule.base.UpdateProgress
Class providing detailed progress information to the caller who shouldderive from it and implement the
update(...)
message.- CLONE=512
- FETCH=1024
- UPDWKTREE=2048
- __annotations__={'_cur_line':'Optional[str]','_num_op_codes':<class'int'>,'_seen_ops':'List[int]','error_lines':'List[str]','other_lines':'List[str]'}
- __module__='git.objects.submodule.base'
- __slots__=()
Objects.Submodule.root
- classgit.objects.submodule.root.RootModule(repo:Repo)
A (virtual) root of all submodules in the given repository.
This can be used to more easily traverse all submodules of thesuperproject (master repository).
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','type':"Literal['submodule']"}
- __init__(repo:Repo)→None
Initialize this instance with its attributes.
We only document the parameters that differ from
IndexObject
.- Parameters:
repo – Our parent repository.
binsha – Binary sha referring to a commit in the remote repository.See theurl parameter.
parent_commit – The
Commit
whose tree is supposed to containthe.gitmodules
blob, orNone
to always point to the most recentcommit. Seeset_parent_commit()
for details.url – The URL to the remote repository which is the submodule.
branch_path – Full repository-relative path to ref to checkout when cloning the remoterepository.
- __module__='git.objects.submodule.root'
- __parameters__=()
- __slots__=()
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- k_root_name='__ROOT__'
- update(previous_commit:Commit|TagObject|str|None=None,recursive:bool=True,force_remove:bool=False,init:bool=True,to_latest_revision:bool=False,progress:None|RootUpdateProgress=None,dry_run:bool=False,force_reset:bool=False,keep_going:bool=False)→RootModule
Update the submodules of this repository to the current HEAD commit.
This method behaves smartly by determining changes of the path of a submodule’srepository, next to changes to the to-be-checked-out commit or the branch to bechecked out. This works if the submodule’s ID does not change.
Additionally it will detect addition and removal of submodules, which will behandled gracefully.
- Parameters:
previous_commit – If set to a commit-ish, the commit we should use as the previous commit theHEAD pointed to before it was set to the commit it points to now.If
None
, it defaults toHEAD@{1}
otherwise.recursive – If
True
, the children of submodules will be updated as well using thesame technique.force_remove – If submodules have been deleted, they will be forcibly removed. Otherwisethe update may fail if a submodule’s repository cannot be deleted as changeshave been made to it.(See
Submodule.update
for more information.)init – If we encounter a new module which would need to be initialized, then do it.
to_latest_revision –
If
True
, instead of checking out the revision pointed to by thissubmodule’s sha, the checked out tracking branch will be merged with thelatest remote branch fetched from the repository’s origin.Unlessforce_reset is specified, a local tracking branch will never bereset into its past, therefore the remote branch must be in the future forthis to have an effect.
force_reset – If
True
, submodules may checkout or reset their branch even if therepository has pending changes that would be overwritten, or if the localtracking branch is in the future of the remote tracking branch and would bereset into its past.progress –
RootUpdateProgress
instance, orNone
if no progress should besent.dry_run – If
True
, operations will not actually be performed. Progress messageswill change accordingly to indicate the WOULD DO state of the operation.keep_going – If
True
, we will ignore but log all errors, and keep going recursively.Unlessdry_run is set as well,keep_going could causesubsequent/inherited errors you wouldn’t see otherwise.In conjunction withdry_run, this can be useful to anticipate all errorswhen updating submodules.
- Returns:
self
- classgit.objects.submodule.root.RootUpdateProgress
Utility class which adds more opcodes to
UpdateProgress
.- BRANCHCHANGE=16384
- PATHCHANGE=8192
- REMOVE=4096
- URLCHANGE=32768
- __annotations__={'_cur_line':'Optional[str]','_num_op_codes':'int','_seen_ops':'List[int]','error_lines':'List[str]','other_lines':'List[str]'}
- __module__='git.objects.submodule.root'
- __slots__=()
Objects.Submodule.util
- classgit.objects.submodule.util.SubmoduleConfigParser(*args:Any,**kwargs:Any)
Catches calls to
write()
, and updates the.gitmodules
blob in the index with the new data, if we have written into astream.Otherwise it would add the local file to the index to make it correspond with theworking tree. Additionally, the cache must be cleared.
Please note that no mutating method will work in bare mode.
- __abstractmethods__=frozenset({})
- __init__(*args:Any,**kwargs:Any)→None
Initialize a configuration reader to read the givenfile_or_files and topossibly allow changes to it by settingread_only False.
- Parameters:
file_or_files – A file path or file object, or a sequence of possibly more than one of them.
read_only – If
True
, the ConfigParser may only read the data, but not change it.IfFalse
, only a single file path or file object may be given. We willwrite back the changes when they happen, or when the ConfigParser isreleased. This will not happen if other configuration files have beenincluded.merge_includes – If
True
, we will read files mentioned in[include]
sections andmerge their contents into ours. This makes it impossible to write back anindividual configuration file. Thus, if you want to modify a singleconfiguration file, turn this off to leave the original dataset unalteredwhen reading it.repo – Reference to repository to use if
[includeIf]
sections are found inconfiguration files.
- __module__='git.objects.submodule.util'
- flush_to_index()→None
Flush changes in our configuration file to the index.
- set_submodule(submodule:Submodule)→None
Set this instance’s submodule. It must be called before the first writeoperation begins.
- write()→None
Write changes to our file, if there are changes at all.
- Raises:
IOError – If this is a read-only writer instance or if we could not obtain a filelock.
- git.objects.submodule.util.find_first_remote_branch(remotes:Sequence[Remote],branch_name:str)→RemoteReference
Find the remote branch matching the name of the given branch or raise
InvalidGitRepositoryError
.
- git.objects.submodule.util.mkhead(repo:Repo,path:str|os.PathLike[str])→Head
- Returns:
New branch/head instance
- git.objects.submodule.util.sm_name(section:str)→str
- Returns:
Name of the submodule as parsed from the section name
- git.objects.submodule.util.sm_section(name:str)→str
- Returns:
Section title used in
.gitmodules
configuration file
Objects.Util
Utility functions for working with git objects.
- classgit.objects.util.Actor(name:str|None,email:str|None)
Actors hold information about a person acting on the repository. They can becommitters and authors or anything with a name and an email as mentioned in the gitlog entries.
- __eq__(other:Any)→bool
Return self==value.
- __hash__()→int
Return hash(self).
- __init__(name:str|None,email:str|None)→None
- __module__='git.util'
- __ne__(other:Any)→bool
Return self!=value.
- __repr__()→str
Return repr(self).
- __slots__=('name','email')
- __str__()→str
Return str(self).
- classmethodauthor(config_reader:None|GitConfigParser|SectionConstraint=None)→Actor
Same as
committer()
, but defines the main author. It may be specifiedin the environment, but defaults to the committer.
- classmethodcommitter(config_reader:None|GitConfigParser|SectionConstraint=None)→Actor
- Returns:
Actor
instance corresponding to the configured committer. Itbehaves similar to the git implementation, such that the environment willoverride configuration values ofconfig_reader. If no value is set at all,it will be generated.- Parameters:
config_reader – ConfigReader to use to retrieve the values from in case they are not set inthe environment.
- conf_email='email'
- conf_name='name'
- email
- env_author_email='GIT_AUTHOR_EMAIL'
- env_author_name='GIT_AUTHOR_NAME'
- env_committer_email='GIT_COMMITTER_EMAIL'
- env_committer_name='GIT_COMMITTER_NAME'
- name
- name_email_regex=re.compile('(.*)<(.*?)>')
- name_only_regex=re.compile('<(.*)>')
- classgit.objects.util.ProcessStreamAdapter(process:Popen,stream_name:str)
Class wiring all calls to the contained Process instance.
Use this type to hide the underlying process to provide access only to a specifiedstream. The process is usually wrapped into an
AutoInterrupt
class to kill it if the instance goes out of scope.- __getattr__(attr:str)→Any
- __init__(process:Popen,stream_name:str)→None
- __module__='git.objects.util'
- __slots__=('_proc','_stream')
- classgit.objects.util.Traversable
Simple interface to perform depth-first or breadth-first traversals in onedirection.
Subclasses only need to implement one function.
Instances of the subclass must be hashable.
Defined subclasses:
- __abstractmethods__=frozenset({'_get_intermediate_items','list_traverse','traverse'})
- __annotations__={}
- __module__='git.objects.util'
- __slots__=()
- abstractlist_traverse(*args:Any,**kwargs:Any)→Any
Traverse self and collect all items found.
Calling this directly on the abstract base class, including via a
super()
proxy, is deprecated. Only overridden implementations should be called.
- abstracttraverse(*args:Any,**kwargs:Any)→Any
Iterator yielding items found when traversing self.
Calling this directly on the abstract base class, including via a
super()
proxy, is deprecated. Only overridden implementations should be called.
- git.objects.util.altz_to_utctz_str(altz:float)→str
Convert a timezone offset west of UTC in seconds into a Git timezone offsetstring.
- Parameters:
altz – Timezone offset in seconds west of UTC.
- git.objects.util.get_object_type_by_name(object_type_name:bytes)→Type[Commit]|Type[TagObject]|Type[Tree]|Type[Blob]
Retrieve the Python class GitPython uses to represent a kind of Git object.
- Returns:
A type suitable to handle the given asobject_type_name.This type can be called create new instances.
- Parameters:
object_type_name – Member of
Object.TYPES
.- Raises:
ValueError – Ifobject_type_name is unknown.
- git.objects.util.parse_actor_and_date(line:str)→Tuple[Actor,int,int]
Parse out the actor (author or committer) info from a line like:
authorTomPreston-Werner<tom@mojombo.com>1191999972-0700
- Returns:
[Actor, int_seconds_since_epoch, int_timezone_offset]
- git.objects.util.parse_date(string_date:str|datetime)→Tuple[int,int]
Parse the given date as one of the following:
Aware datetime instance
Git internal format: timestamp offset
RFC 2822:
Thu,07Apr200522:13:13+0200
ISO 8601:
2005-04-07T22:13:13
- TheT
can be a space as well.
- Returns:
Tuple(int(timestamp_UTC), 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
andDD.MM.YYYY
.
- classgit.objects.util.tzoffset(secs_west_of_utc:float,name:None|str=None)
- __dict__=mappingproxy({'__module__':'git.objects.util','__init__':<functiontzoffset.__init__>,'__reduce__':<functiontzoffset.__reduce__>,'utcoffset':<functiontzoffset.utcoffset>,'tzname':<functiontzoffset.tzname>,'dst':<functiontzoffset.dst>,'__dict__':<attribute'__dict__'of'tzoffset'objects>,'__weakref__':<attribute'__weakref__'of'tzoffset'objects>,'__doc__':None,'__annotations__':{}})
- __init__(secs_west_of_utc:float,name:None|str=None)→None
- __module__='git.objects.util'
- __weakref__
list of weak references to the object
- dst(dt:datetime|None)→timedelta
datetime -> DST offset as timedelta positive east of UTC.
- tzname(dt:datetime|None)→str
datetime -> string name of time zone.
- utcoffset(dt:datetime|None)→timedelta
datetime -> timedelta showing offset from UTC, negative values indicating West of UTC
- git.objects.util.utctz_to_altz(utctz:str)→int
Convert a git timezone offset into a timezone offset west of UTC in seconds(compatible with
time.altzone
).- Parameters:
utctz – git utc timezone string, e.g. +0200
- git.objects.util.verify_utctz(offset:str)→str
- Raises:
ValueError – Ifoffset is incorrect.
- Returns:
offset
Index.Base
Module containingIndexFile
, an Index implementation facilitating all kindsof index manipulations such as querying and merging.
- exceptiongit.index.base.CheckoutError(message:str,failed_files:Sequence[str|os.PathLike[str]],valid_files:Sequence[str|os.PathLike[str]],failed_reasons:List[str])
Thrown if a file could not be checked out from the index as it containedchanges.
The
failed_files
attribute contains a list of relative paths that failed tobe checked out as they contained changes that did not exist in the index.The
failed_reasons
attribute contains a string informing about the actualcause of the issue.The
valid_files
attribute contains a list of relative paths to files thatwere checked out successfully and hence match the version stored in the index.- __init__(message:str,failed_files:Sequence[str|os.PathLike[str]],valid_files:Sequence[str|os.PathLike[str]],failed_reasons:List[str])→None
- __module__='git.exc'
- __str__()→str
Return str(self).
- classgit.index.base.IndexFile(repo:Repo,file_path:str|os.PathLike[str]|None=None)
An Index that can be manipulated using a native implementation in order to savegit command function calls wherever possible.
This provides custom merging facilities allowing to merge without actually changingyour index or your working tree. This way you can perform your own test merges basedon the index only without having to deal with the working copy. This is useful incase 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 theindex directly before operating on it using the git command.- S_IFGITLINK=57344
Flags for a submodule.
- __abstractmethods__=frozenset({})
- __annotations__={'_file_path':'PathLike','repo':"'Repo'"}
- __init__(repo:Repo,file_path:str|os.PathLike[str]|None=None)→None
Initialize this Index instance, optionally from the givenfile_path.
If nofile_path is given, we will be created from the current index file.
If a stream is not given, the stream will be initialized from the currentrepository’s index on demand.
- __module__='git.index.base'
- __slots__=('repo','version','entries','_extension_data','_file_path')
- add(items:str|~os.PathLike[str]|~typing.Sequence[str|~os.PathLike[str]|~git.objects.blob.Blob|~git.index.typ.BaseIndexEntry|~git.objects.submodule.base.Submodule],force:bool=True,fprogress:~typing.Callable=<functionIndexFile.<lambda>>,path_rewriter:~typing.Callable[[...],str|~os.PathLike[str]]|None=None,write:bool=True,write_extension_data:bool=False)→List[BaseIndexEntry]
Add files from the working tree, specific blobs, or
BaseIndexEntry
s to the index.- Parameters:
items –
Multiple types of items are supported, types can be mixed within one call.Different types imply a different handling. File paths may generally berelative or absolute.
path string
Strings denote a relative or absolute path into the repository pointingto an existing file, e.g.,
CHANGES
,lib/myfile.ext`,/home/gitrepo/lib/myfile.ext
.Absolute paths must start with working tree directory of this index’srepository to be considered valid. For example, if it was initializedwith a non-normalized path, like
/root/repo/../repo
, absolute pathsto be added must start with/root/repo/../repo
.Paths provided like this must exist. When added, they will be writteninto the object database.
PathStrings may contain globs, such as
lib/__init__*
. Or they can bedirectories likelib
, which will add all the files within thedirectory and subdirectories.This equals a straightgit-add(1).
They are added at stage 0.
:class:~`git.objects.blob.Blob` or
Submodule
objectBlobs are added as they are assuming a valid mode is set.
The file they refer to may or may not exist in the file system, but mustbe a path relative to our repository.
If their sha is null (40*0), their path must exist in the file systemrelative to the git repository as an object will be created from thedata at the path.
The handling now very much equals the way string paths are processed,except that the mode you have set will be kept. This allows you tocreate symlinks by settings the mode respectively and writing the targetof the symlink directly into the file. This equals a default Linuxsymlink which is not dereferenced automatically, except that it can becreated on filesystems not supporting it as well.
Please note that globs or directories are not allowed in
Blob
objects.They are added at stage 0.
BaseIndexEntry
or typeHandling equals the one of :class:~`git.objects.blob.Blob` objects, butthe stage may be explicitly set. Please note that Index Entries requirebinary sha’s.
force –CURRENTLY INEFFECTIVEIf
True
, otherwise ignored or excluded files will be added anyway. Asopposed to thegit-add(1) command, we enable this flag by defaultas the API user usually wants the item to be added even though they might beexcluded.fprogress –
Function with signature
f(path,done=False,item=item)
called for eachpath to be added, one time once it is about to be added wheredone=False
and once after it was added wheredone=True
.item
is set to the actual item we handle, either a path or aBaseIndexEntry
.Please note that the processed path is not guaranteed to be present in theindex already as the index is currently being processed.
path_rewriter – Function, with signature
(string)func(BaseIndexEntry)
, returning a pathfor each passed entry which is the path to be actually recorded for theobject created fromentry.path
.This allows you to write an index which is not identical to the layout ofthe actual files on your hard-disk. If notNone
anditems containplain paths, these paths will be converted to Entries beforehand and passedto the path_rewriter. Please note thatentry.path
is relative to the gitrepository.write – If
True
, the index will be written once it was altered. Otherwise thechanges only exist in memory and are not available to git commands.write_extension_data –
If
True
, extension data will be written back to the index. This can leadto issues in case it is containing the ‘TREE’ extension, which will causethegit-commit(1) command to write an old tree, instead of a newone representing the now changed index.This doesn’t matter if you use
IndexFile.commit()
, which ignores the‘TREE’ extension altogether. You should set it toTrue
if you intend touseIndexFile.commit()
exclusively while maintaining support forthird-party extensions. Besides that, you can usually safely ignore thebuilt-in extensions when using GitPython on repositories that are nothandled manually at all.All current built-in extensions are listed here:https://git-scm.com/docs/index-format
- Returns:
List of
BaseIndexEntry
s representing the entriesjust actually added.- Raises:
OSError – If a supplied path did not exist. Please note that
BaseIndexEntry
objects that do not have a null shawill be added even if their paths do not exist.
- checkout(paths:None|~typing.Iterable[str|~os.PathLike[str]]=None,force:bool=False,fprogress:~typing.Callable=<functionIndexFile.<lambda>>,**kwargs:~typing.Any)→None|Iterator[str|PathLike[str]]|Sequence[str|PathLike[str]]
Check out the given paths or all files from the version known to the indexinto the working tree.
- Note:
Be sure you have written pending changes using the
write()
method incase you have altered the entries dictionary directly.- Parameters:
paths – If
None
, all paths in the index will be checked out.Otherwise an iterable of relative or absolute paths or a single pathpointing to files or directories in the index is expected.force – If
True
, existing files will be overwritten even if they contain localmodifications.IfFalse
, these will trigger aCheckoutError
.fprogress –
See
IndexFile.add()
for signature and explanation.The provided progress information will contain
None
as path and item ifno explicit paths are given. Otherwise progress information will be sendprior and after a file has been checked out.kwargs – Additional arguments to be passed togit-checkout-index(1).
- Returns:
Iterable yielding paths to files which have been checked out and areguaranteed to match the version stored in the index.
- Raises:
If at least one file failed to be checked out. This is a summary, hence itwill checkout as many files as it can anyway.
If one of files or directories do not exist in the index (as opposed tothe original git command, which ignores them).
git.exc.GitCommandError – If error lines could not be parsed - this truly is an exceptional state.
- Note:
The checkout is limited to checking out the files in the index. Files whichare not in the index anymore and exist in the working tree will not bedeleted. This behaviour is fundamentally different to
head.checkout
,i.e. if you wantgit-checkout(1)-like behaviour, usehead.checkout
instead ofindex.checkout
.
- commit(message:str,parent_commits:List[Commit]|None=None,head:bool=True,author:None|Actor=None,committer:None|Actor=None,author_date:datetime|str|None=None,commit_date:datetime|str|None=None,skip_hooks:bool=False)→Commit
Commit the current default index file, creating a
Commit
object.For more information on the arguments, see
Commit.create_from_tree
.
- diff(other:~typing.Literal[<DiffConstants.INDEX:2>]|~git.objects.tree.Tree|~git.objects.commit.Commit|str|None=DiffConstants.INDEX,paths:str|~os.PathLike[str]|~typing.List[str|~os.PathLike[str]]|~typing.Tuple[str|~os.PathLike[str],...]|None=None,create_patch:bool=False,**kwargs:~typing.Any)→DiffIndex[Diff]
Diff this index against the working copy or a
Tree
orCommit
object.For documentation of the parameters and return values, see
Diffable.diff
.- Note:
Will only work with indices that represent the default git index as theyhave not been initialized with a stream.
- entries
- classmethodentry_key(*entry:BaseIndexEntry|str|PathLike[str]|int)→Tuple[str|PathLike[str],int]
- classmethodfrom_tree(repo:Repo,*treeish:Tree|Commit|str|bytes,**kwargs:Any)→IndexFile
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,Commit
s 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 twoway 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 treebeing 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 togit-read-tree(1).
- Returns:
New
IndexFile
instance. It will point to a temporary index locationwhich does not exist anymore. If you intend to write such a merged Index,supply an alternatefile_path
to itswrite()
method.- Note:
In the three-way merge case,
--aggressive
will be specified toautomatically resolve more cases in a commonly correct manner. Specifytrivial=True
as a keyword argument to override that.As the underlyinggit-read-tree(1) command takes into account thecurrent index, it will be temporarily moved out of the way to prevent anyunexpected interference.
- iter_blobs(predicate:~typing.Callable[[~typing.Tuple[int,~git.objects.blob.Blob]],bool]=<functionIndexFile.<lambda>>)→Iterator[Tuple[int,Blob]]
- Returns:
Iterator yielding tuples of
Blob
objects andstages, tuple(stage, Blob).- Parameters:
predicate – Function(t) returning
True
if tuple(stage, Blob) should be yielded bythe iterator. A default filter, the~git.index.typ.BlobFilter, allows youto yield blobs only if they match a given list of paths.
- merge_tree(rhs:Tree|Commit|str|bytes,base:None|Tree|Commit|str|bytes=None)→IndexFile
Merge the givenrhs treeish into the current index, possibly takinga common base treeish into account.
As opposed to the
from_tree()
method, this allows you to use an alreadyexisting tree as the left side of the merge.- Parameters:
rhs – Treeish reference pointing to the ‘other’ side of the merge.
base – Optional treeish reference pointing to the common base ofrhs and thisindex which equals lhs.
- Returns:
self (containing the merge and possibly unmerged entries in case ofconflicts)
- Raises:
git.exc.GitCommandError – If there is a merge conflict. The error will be raised at the firstconflicting path. If you want to have proper merge resolution to be done byyourself, you have to commit the changed index (or make a valid tree fromit) and retry with a three-way
index.from_tree
call.
- move(items:str|PathLike[str]|Sequence[str|PathLike[str]|Blob|BaseIndexEntry|Submodule],skip_errors:bool=False,**kwargs:Any)→List[Tuple[str,str]]
Rename/move the items, whereas the last item is considered the destination ofthe move operation.
If the destination is a file, the first item (of two) must be a file as well.
If the destination is a directory, it may be preceded by one or more directoriesor files.
The working tree will be affected in non-bare repositories.
- Parameters:
- Returns:
List(tuple(source_path_string, destination_path_string), …)
A list of pairs, containing the source file moved as well as its actualdestination. Relative to the repository root.
- Raises:
ValueError – If only one item was given.
git.exc.GitCommandError – If git could not handle your request.
- classmethodnew(repo:Repo,*tree_sha:str|Tree)→IndexFile
Merge the given treeish revisions into a new index which is returned.
This method behaves like
git-read-tree--aggressive
when doing the merge.
- propertypath:str|PathLike[str]
- Returns:
Path to the index file we are representing
- remove(items:str|PathLike[str]|Sequence[str|PathLike[str]|Blob|BaseIndexEntry|Submodule],working_tree:bool=False,**kwargs:Any)→List[str]
Remove the given items from the index and optionally from the working treeas well.
- Parameters:
items –
Multiple types of items are supported which may be be freely mixed.
path string
Remove the given path at all stages. If it is a directory, you mustspecify the
r=True
keyword argument to remove all file entries belowit. If absolute paths are given, they will be converted to a pathrelative to the git repository directory containing the working treeThe path string may include globs, such as
*.c
.:class:~`git.objects.blob.Blob` object
Only the path portion is used in this case.
BaseIndexEntry
or compatible typeThe only relevant information here is the path. The stage is ignored.
working_tree – If
True
, the entry will also be removed from the working tree,physically removing the respective file. This may fail if there areuncommitted changes in it.kwargs – Additional keyword arguments to be passed togit-rm(1), such as
r
to allow recursive removal.
- Returns:
List(path_string, …) list of repository relative paths that have beenremoved effectively.
This is interesting to know in case you have provided a directory or globs.Paths are relative to the repository.
- reset(commit:Commit|Reference|str='HEAD',working_tree:bool=False,paths:None|Iterable[str|os.PathLike[str]]=None,head:bool=False,**kwargs:Any)→IndexFile
Reset the index to reflect the tree at the given commit. This will not adjustour HEAD reference by default, as opposed to
HEAD.reset
.- Parameters:
commit –
Revision,
Reference
orCommit
specifying the commit we shouldrepresent.If you want to specify a tree only, use
IndexFile.from_tree()
andoverwrite the default index.working_tree – If
True
, the files in the working tree will reflect the changed index.IfFalse
, the working tree will not be touched.Please note that changes to the working copy will be discarded withoutwarning!head – If
True
, the head will be set to the given commit. This isFalse
bydefault, but ifTrue
, this method behaves likeHEAD.reset
.paths – If given as an iterable of absolute or repository-relative paths, only thesewill be reset to their state at the given commit-ish.The paths need to exist at the commit, otherwise an exception will beraised.
kwargs – Additional keyword arguments passed togit-reset(1).
- Note:
IndexFile.reset()
, as opposed toHEAD.reset
, will not delete any files inorder to maintain a consistent working tree. Instead, it will just check outthe files according to their state in the index.If you wantgit-reset(1)-like behaviour, useHEAD.reset
instead.- Returns:
self
- resolve_blobs(iter_blobs:Iterator[Blob])→IndexFile
Resolve the blobs given in blob iterator.
This will effectively remove the index entries of the respective path at allnon-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 beraised 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()→Dict[str|PathLike[str],List[Tuple[int,Blob]]]
- Returns:
Dict(path : list(tuple(stage, Blob, …))), being a dictionary associating apath 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 givenstage. That is, a file removed on the ‘other’ branch whose entries are atstage 3 will not have a stage 3 entry.
- update()→IndexFile
Reread the contents of our index file, discarding all cached informationwe might have.
- Note:
This is a possibly dangerous operations as it will discard your changes to
index.entries
.- Returns:
self
- version
- write(file_path:None|str|PathLike[str]=None,ignore_extension_data:bool=False)→None
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 beeninitialized. Otherwise we write to the given file path. Please note thatthis will change thefile_path of this index to the one you gave.ignore_extension_data – If
True
, the TREE type extension data read in the index will not bewritten to disk. NOTE that no extension data is actually written. Use thisif you have altered the index and would like to usegit-write-tree(1) afterwards to create a tree representing yourwritten changes. If this data is present in the written index,git-write-tree(1) will instead write the stored/cached tree.Alternatively, usewrite_tree()
to handle this case automatically.
- write_tree()→Tree
Write this index to a corresponding
Tree
objectinto 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 doesnot yet exist in the object database. This could happen if you added entriesto the index directly.
- Raises:
ValueError – If there are no entries in the cache.
- git.index.base.StageType
alias of
int
Index.Functions
Standalone functions to accompany the index implementation and make it moreversatile.
- git.index.fun.S_IFGITLINK=57344
Flags for a submodule.
- git.index.fun.entry_key(*entry:BaseIndexEntry|str|PathLike[str]|int)→Tuple[str|PathLike[str],int]
- Returns:
Key suitable to be used for the
index.entries
dictionary.- Parameters:
entry – One instance of type BaseIndexEntry or the path and the stage.
- git.index.fun.hook_path(name:str,git_dir:str|PathLike[str])→str
- Returns:
path to the given named hook in the given git repository directory
- git.index.fun.read_cache(stream:IO[bytes])→Tuple[int,Dict[Tuple[str|PathLike[str],int],IndexEntry],bytes,bytes]
Read a cache file from the given stream.
- Returns:
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 astage.
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.run_commit_hook(name:str,index:IndexFile,*args:str)→None
Run the commit hook of the given name. Silently ignore hooks that do not exist.
- Parameters:
name – Name of hook, like
pre-commit
.index –
IndexFile
instance.args – Arguments passed to hook file.
- Raises:
- git.index.fun.stat_mode_to_index_mode(mode:int)→int
Convert the given mode from a stat call to the corresponding index mode andreturn it.
- git.index.fun.write_cache(entries:~typing.Sequence[~git.index.typ.BaseIndexEntry|~git.index.typ.IndexEntry],stream:~typing.IO[bytes],extension_data:None|bytes=None,ShaStreamCls:~typing.Type[~git.util.IndexFileSHA1Writer]=<class'git.util.IndexFileSHA1Writer'>)→None
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.write_tree_from_cache(entries:List[IndexEntry],odb:GitCmdObjectDB,sl:slice,si:int=0)→Tuple[bytes,List[TreeCacheTup]]
Create a tree from the given sorted list of entries and put the respectivetrees into the given object database.
- Parameters:
entries –Sorted list of
IndexEntry
s.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.
Index.Types
Additional types used by the index.
- classgit.index.typ.BaseIndexEntry(inp_tuple:Tuple[int,bytes,int,str|os.PathLike[str]]|Tuple[int,bytes,int,str|os.PathLike[str],bytes,bytes,int,int,int,int,int])
Small brother of an index entry which can be created to describe changesdone to the index in which case plenty of additional information is not required.
As the first 4 data members match exactly to the
IndexEntry
type, methodsexpecting aBaseIndexEntry
can also handle fullIndexEntry
s evenif they use numeric indices for performance reasons.- __annotations__={}
- __dict__=mappingproxy({'__module__':'git.index.typ','__doc__':'Smallbrotherofanindexentrywhichcanbecreatedtodescribechanges\n donetotheindexinwhichcaseplentyofadditionalinformationisnotrequired.\n\n Asthefirst4datamembersmatchexactlytothe:class:`IndexEntry`type,methods\n expectinga:class:`BaseIndexEntry`canalsohandlefull:class:`IndexEntry`\\seven\n iftheyusenumericindicesforperformancereasons.\n ','__new__':<staticmethod(<functionBaseIndexEntry.__new__>)>,'__str__':<functionBaseIndexEntry.__str__>,'__repr__':<functionBaseIndexEntry.__repr__>,'hexsha':<propertyobject>,'stage':<propertyobject>,'from_blob':<classmethod(<functionBaseIndexEntry.from_blob>)>,'to_blob':<functionBaseIndexEntry.to_blob>,'__dict__':<attribute'__dict__'of'BaseIndexEntry'objects>,'__annotations__':{'mode':'int','binsha':'bytes','flags':'int','path':'PathLike','ctime_bytes':'bytes','mtime_bytes':'bytes','dev':'int','inode':'int','uid':'int','gid':'int','size':'int'}})
- __module__='git.index.typ'
- static__new__(cls,inp_tuple:Tuple[int,bytes,int,str|os.PathLike[str]]|Tuple[int,bytes,int,str|os.PathLike[str],bytes,bytes,int,int,int,int,int])→BaseIndexEntry
Override
__new__
to allow construction from a tuple for backwardscompatibility.
- __repr__()→str
Return a nicely formatted representation string
- __str__()→str
Return str(self).
- classmethodfrom_blob(blob:Blob,stage:int=0)→BaseIndexEntry
- Returns:
Fully equipped BaseIndexEntry at the given stage
- propertyhexsha:str
hex version of our sha
- propertystage:int
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, seegit-read-tree(1).
- classgit.index.typ.BlobFilter(paths:Sequence[str|os.PathLike[str]])
Predicate to be used by
IndexFile.iter_blobs
allowing tofilter only return blobs which match the given list of directories or files.The given paths are given relative to the repository.
- __init__(paths:Sequence[str|os.PathLike[str]])→None
- Parameters:
paths – Tuple or list of paths which are either pointing to directories or to filesrelative to the current repository.
- __module__='git.index.typ'
- __slots__=('paths',)
- paths
- classgit.index.typ.IndexEntry(inp_tuple:Tuple[int,bytes,int,str|os.PathLike[str]]|Tuple[int,bytes,int,str|os.PathLike[str],bytes,bytes,int,int,int,int,int])
Allows convenient access to index entry data as defined in
BaseIndexEntry
without completely unpacking it.Attributes usually accessed often are cached in the tuple whereas others areunpacked on demand.
See the properties for a mapping between names and tuple indices.
- __annotations__={}
- __module__='git.index.typ'
- propertyctime:Tuple[int,int]
- Returns:
Tuple(int_time_seconds_since_epoch, int_nano_seconds) of thefile’s creation time
- classmethodfrom_base(base:BaseIndexEntry)→IndexEntry
- Returns:
Minimal entry as created from the given
BaseIndexEntry
instance.Missing values will be set to null-like values.- Parameters:
base – Instance of type
BaseIndexEntry
.
- classmethodfrom_blob(blob:Blob,stage:int=0)→IndexEntry
- Returns:
Minimal entry resembling the given blob object
- git.index.typ.StageType
alias of
int
Index.Util
Index utilities.
- classgit.index.util.TemporaryFileSwap(file_path:str|PathLike[str])
Utility class moving a file to a temporary location within the same directory andmoving it back on to where on object deletion.
- __enter__()→TemporaryFileSwap
- __exit__(exc_type:Type[BaseException]|None,exc_val:BaseException|None,exc_tb:TracebackType|None)→Literal[False]
- __init__(file_path:str|PathLike[str])→None
- __module__='git.index.util'
- __slots__=('file_path','tmp_file_path')
- file_path
- tmp_file_path
- git.index.util.default_index(func:Callable[[...],_T])→Callable[[...],_T]
Decorator ensuring the wrapped method may only run if we are the defaultrepository index.
This is as we rely on git commands that operate on that index only.
- git.index.util.git_working_dir(func:Callable[[...],_T])→Callable[[...],_T]
Decorator which changes the current working dir to the one of the gitrepository in order to ensure relative paths are handled correctly.
- git.index.util.post_clear_cache(func:Callable[[...],_T])→Callable[[...],_T]
Decorator for functions that alter the index using the git command.
When a git command alters the index, this invalidates our possibly existing entriesdictionary, which is why it must be deleted to allow it to be lazily reread later.
GitCmd
- classgit.cmd.Git(working_dir:None|str|PathLike[str]=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' programrval=g.ls_files()# calls 'git ls-files' program
Debugging:
Set the
GIT_PYTHON_TRACE
environment variable to print each invocationof the command to stdout.Set its value to
full
to see details about the returned values.
- classAutoInterrupt(proc:None|Popen,args:Any)
Process wrapper that terminates the wrapped process on finalization.
This kills/interrupts the stored process instance once this instance goes out ofscope. It is used to prevent processes piling up in case iterators stop reading.
All attributes are wired through to the contained process object.
The wait method is overridden to perform automatic status code checking andpossibly raise.
- __annotations__={'_status_code_if_terminate':'int'}
- __del__()→None
- __getattr__(attr:str)→Any
- __init__(proc:None|Popen,args:Any)→None
- __module__='git.cmd'
- __slots__=('proc','args','status')
- args
- proc
- status:int|None
- wait(stderr:None|str|bytes=b'')→int
Wait for the process and return its status code.
- Parameters:
stderr – Previously read value of stderr, in case stderr is already closed.
- Warn:
May deadlock if output or error pipes are used and not handledseparately.
- Raises:
git.exc.GitCommandError – If the return status is not 0.
- classCatFileContentStream(size:int,stream:IO[bytes])
Object representing a sized read-only stream returning the contents ofan object.
This behaves like a stream, but counts the data read and simulates an emptystream once our sized content region is empty.
If not all data are read to the end of the object’s lifetime, we read therest to ensure the underlying stream continues to work.
- __del__()→None
- __init__(size:int,stream:IO[bytes])→None
- __iter__()→CatFileContentStream
- __module__='git.cmd'
- __next__()→bytes
- __slots__=('_stream','_nbr','_size')
- next()→bytes
- read(size:int=-1)→bytes
- readline(size:int=-1)→bytes
- readlines(size:int=-1)→List[bytes]
- GIT_PYTHON_GIT_EXECUTABLE='git'
Provide the full path to the git executable. Otherwise it assumes git is in theexecutable search path.
- Note:
The git executable is actually found during the refresh step in the top level
__init__
. It can also be changed by explicitly callinggit.refresh()
.
- GIT_PYTHON_TRACE=False
Enables debugging of GitPython’s git commands.
- USE_SHELL:bool=False
Deprecated. If set to
True
, a shell will be used when executing git commands.Code that uses
USE_SHELL=True
or that passesshell=True
to any GitPythonfunctions should be updated to use the default value ofFalse
instead.True
is unsafe unless the effect of syntax treated specially by the shell is fullyconsidered and accounted for, which is not possible under most circumstances. Asdetailed below, it is also no longer needed, even where it had been in the past.It is in many if not most cases a command injection vulnerability for an applicationto set
USE_SHELL
toTrue
. Any attacker who can cause a specially craftedfragment of text to make its way into any part of any argument to any git command(including paths, branch names, etc.) can cause the shell to read and writearbitrary files and execute arbitrary commands. Innocent input may also accidentallycontain special shell syntax, leading to inadvertent malfunctions.In addition, how a value of
True
interacts with some aspects of GitPython’soperation is not precisely specified and may change without warning, even beforeGitPython 4.0.0 whenUSE_SHELL
may be removed. This includes:Whether or how GitPython automatically customizes the shell environment.
Whether, outside of Windows (where
subprocess.Popen
supports lists ofseparate arguments even whenshell=True
), this can be used with any GitPythonfunctionality other than direct calls to theexecute()
method.Whether any GitPython feature that runs git commands ever attempts to partiallysanitize data a shell may treat specially. Currently this is not done.
Prior to GitPython 2.0.8, this had a narrow purpose in suppressing console windowsin graphical Windows applications. In 2.0.8 and higher, it provides no benefit, asGitPython solves that problem more robustly and safely by using the
CREATE_NO_WINDOW
process creation flag on Windows.Because Windows path search differs subtly based on whether a shell is used, in rarecases changing this from
True
toFalse
may keep an unusual git “executable”,such as a batch file, from being found. To fix this, set the command name or fullpath in theGIT_PYTHON_GIT_EXECUTABLE
environment variable or pass thefull path togit.refresh()
(or invoke the script using a.exe
shim).Further reading:
- __annotations__={'USE_SHELL':'bool','_environment':'Dict[str,str]','_git_options':'Union[List[str],Tuple[str,...]]','_persistent_git_options':'List[str]','_version_info':'Union[Tuple[int,...],None]','_version_info_token':'object','cat_file_all':'Union[None,TBD]','cat_file_header':'Union[None,TBD]'}
- __call__(**kwargs:Any)→Git
Specify command line options to the git executable for a subcommand call.
- Parameters:
kwargs – A dict of keyword arguments.These arguments are passed as in
_call_process()
, but will be passedto the git command rather than the subcommand.
Examples:
git(work_tree='/tmp').difftool()
- __getattr__(name:str)→Any
A convenience method as it allows to call the command as if it was an object.
- Returns:
Callable object that will execute call
_call_process()
with yourarguments.
- __getattribute__(name:str)→Any
Return getattr(self, name).
- __getstate__()→Dict[str,Any]
Helper for pickle.
- __init__(working_dir:None|str|PathLike[str]=None)→None
Initialize this instance with:
- Parameters:
working_dir – Git directory we should work in. If
None
, we always work in the currentdirectory as returned byos.getcwd()
.This is meant to be the working tree directory if available, or the.git
directory in case of bare repositories.
- __module__='git.cmd'
- __setstate__(d:Dict[str,Any])→None
- __slots__=('_working_dir','cat_file_all','cat_file_header','_version_info','_version_info_token','_git_options','_persistent_git_options','_environment')
- cat_file_all:None|Any
- cat_file_header:None|Any
- classmethodcheck_unsafe_options(options:List[str],unsafe_options:List[str])→None
Check for unsafe options.
Some options that are passed to
git<command>
can be used to executearbitrary commands. These are blocked by default.
- classmethodcheck_unsafe_protocols(url:str)→None
Check for unsafe protocols.
Apart from the usual protocols (http, git, ssh), Git allows “remote helpers”that have the form
<transport>::<address>
. One of these helpers (ext::
)can be used to invoke any arbitrary command.See:
- clear_cache()→Git
Clear all kinds of internal caches to release resources.
Currently persistent commands will be interrupted.
- Returns:
self
- custom_environment(**kwargs:Any)→Iterator[None]
A context manager around the above
update_environment()
method torestore the environment back to its previous state after operation.Examples:
withself.custom_environment(GIT_SSH='/bin/ssh_wrapper'):repo.remotes.origin.fetch()
- Parameters:
kwargs – See
update_environment()
.
- environment()→Dict[str,str]
- execute(command:str|Sequence[Any],*,as_process:Literal[True])→AutoInterrupt
- execute(command:str|Sequence[Any],*,as_process:Literal[False]=False,stdout_as_string:Literal[True])→str|Tuple[int,str,str]
- execute(command:str|Sequence[Any],*,as_process:Literal[False]=False,stdout_as_string:Literal[False]=False)→bytes|Tuple[int,bytes,str]
- execute(command:str|Sequence[Any],*,with_extended_output:Literal[False],as_process:Literal[False],stdout_as_string:Literal[True])→str
- execute(command:str|Sequence[Any],*,with_extended_output:Literal[False],as_process:Literal[False],stdout_as_string:Literal[False])→bytes
Handle executing the command, and consume and return the returnedinformation (stdout).
- Parameters:
command – The command argument list to execute.It should be a sequence of program arguments, or a string. Theprogram to execute is the first item in the args sequence or string.
istream – Standard input filehandle passed to
subprocess.Popen
.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 whichstreams can be read on demand. This will renderwith_extended_outputandwith_exceptions ineffective - the caller will have to deal withthe details. It is important to note that the process will be placedinto an
AutoInterrupt
wrapper that will interrupt the processonce it goes out of scope. If you use the command in iterators, youshould 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 becopied to the given stream instead of being returned as a string.This feature only has any effect ifas_process is
False
.stdout_as_string – If
False
, the command’s standard output will be bytes. Otherwise, itwill be decoded into a string using the default encoding (usually UTF-8).The latter can fail, if the output contains binary data.kill_after_timeout –
Specifies a timeout in seconds for the git command, after which the processshould be killed. This will have no effect ifas_process is set to
True
. It is set toNone
by default and will let the process rununtil the timeout is explicitly specified. Uses of this feature should becarefully considered, due to the following limitations:This feature is not supported at all on Windows.
Effectiveness may vary by operating system.
ps--ppid
is used toenumerate child processes, which is available on most GNU/Linux systemsbut not most others.Deeper descendants do not receive signals, though they may sometimesterminate as a consequence of their parent processes being killed.
kill_after_timeout uses
SIGKILL
, which can have negative sideeffects on a repository. For example, stale locks in case ofgit-gc(1) could render the repository incapable of acceptingchanges until the lock is manually removed.
with_stdout – If
True
, defaultTrue
, we open stdout on the created process.universal_newlines – If
True
, pipes will be opened as text, and lines are split at all knownline endings.shell –
Whether to invoke commands through a shell(see
Popen(...,shell=True)
).If this is notNone
, it overridesUSE_SHELL
.Passing
shell=True
to this or any other GitPython function should beavoided, as it is unsafe under most circumstances. This is because it istypically not feasible to fully consider and account for the effect of shellexpansions, especially when passingshell=True
to other methods thatforward it toGit.execute()
. Passingshell=True
is also no longerneeded (nor useful) to work around any known operating system specificissues.env – A dictionary of environment variables to be passed to
subprocess.Popen
.max_chunk_size – Maximum number of bytes in one chunk of data passed to theoutput_streamin one invocation of its
write()
method. If the given number is notpositive then the default value is used.strip_newline_in_stdout – Whether to strip the trailing
\n
of the command stdout.subprocess_kwargs – Keyword arguments to be passed to
subprocess.Popen
. Please notethat some of the valid kwargs are already set by this method; the ones youspecify may not be the same ones.
- Returns:
str(output), ifextended_output is
False
(Default)tuple(int(status), str(stdout), str(stderr)),ifextended_output is
True
Ifoutput_stream is
True
, the stdout value will be your output stream:output_stream, ifextended_output is
False
tuple(int(status), output_stream, str(stderr)),ifextended_output is
True
Note that git is executed with
LC_MESSAGES="C"
to ensure consistentoutput regardless of system language.- Raises:
- Note:
If you add additional keyword arguments to the signature of this method, youmust update the
execute_kwargs
variable housed in this module.
- get_object_data(ref:str)→Tuple[str,str,int,bytes]
Similar to
get_object_header()
, but returns object data as well.- Returns:
(hexsha, type_string, size_as_int, data_string)
- Note:
Not threadsafe.
- get_object_header(ref:str)→Tuple[str,str,int]
Use this method to quickly examine the type and size of the object behind thegiven ref.
- Note:
The method will only suffer from the costs of command invocation once andreuses the command in subsequent calls.
- Returns:
(hexsha, type_string, size_as_int)
- git_exec_name='git'
Default git command that should work on Linux, Windows, and other systems.
- classmethodis_cygwin()→bool
- classmethodpolish_url(url:str,is_cygwin:Literal[False]=None)→str
- classmethodpolish_url(url:str,is_cygwin:None|bool=None)→str
Remove any backslashes from URLs to be written in config files.
Windows might create config files containing paths with backslashes, but gitstops liking them as it will escape the backslashes. Hence we undo the escapingjust to be sure.
- re_unsafe_protocol=re.compile('(.+)::.+')
- classmethodrefresh(path:None|str|PathLike[str]=None)→bool
Update information about the git executable
Git
objects will use.Called by the
git.refresh()
function in the top level__init__
.- Parameters:
path – Optional path to the git executable. If not absolute, it is resolvedimmediately, relative to the current directory. (See note below.)
- Note:
The top-level
git.refresh()
should be preferred because it calls thismethod and may also update other state accordingly.- Note:
There are three different ways to specify the command that refreshing causesto be used for git:
Pass nopath argument and do not set the
GIT_PYTHON_GIT_EXECUTABLE
environment variable. The commandnamegit
is used. It is looked up in a path search by the system, ineach command run (roughly similar to how git is found when runninggit
commands manually). This is usually the desired behavior.Pass nopath argument but set the
GIT_PYTHON_GIT_EXECUTABLE
environment variable. The command given as the value of that variable isused. This may be a simple command or an arbitrary path. It is looked upin each command run. SettingGIT_PYTHON_GIT_EXECUTABLE
togit
has the same effect as not setting it.Pass apath argument. This path, if not absolute, is immediatelyresolved, relative to the current directory. This resolution occurs atthe time of the refresh. When git commands are run, they are run usingthat previously resolved path. If apath argument is passed, the
GIT_PYTHON_GIT_EXECUTABLE
environment variable is notconsulted.
- Note:
Refreshing always sets the
Git.GIT_PYTHON_GIT_EXECUTABLE
classattribute, which can be read on theGit
class or any of itsinstances to check what command is used to run git. This attribute shouldnot be confused with the relatedGIT_PYTHON_GIT_EXECUTABLE
environment variable. The class attribute is set no matter how refreshing isperformed.
- set_persistent_git_options(**kwargs:Any)→None
Specify command line options to the git executable for subsequentsubcommand calls.
- Parameters:
kwargs – A dict of keyword arguments.These arguments are passed as in
_call_process()
, but will be passedto the git command rather than the subcommand.
- stream_object_data(ref:str)→Tuple[str,str,int,CatFileContentStream]
Similar to
get_object_data()
, but returns the data as a stream.- Returns:
(hexsha, type_string, size_as_int, stream)
- Note:
This method is not threadsafe. You need one independent
Git
instance per thread to be safe!
- transform_kwarg(name:str,value:Any,split_single_char_options:bool)→List[str]
- transform_kwargs(split_single_char_options:bool=True,**kwargs:Any)→List[str]
Transform Python-style kwargs into git command line options.
- update_environment(**kwargs:Any)→Dict[str,str|None]
Set environment variables for future git invocations. Return all changedvalues in a format that can be passed back into this function to revert thechanges.
Examples:
old_env=self.update_environment(PWD='/tmp')self.update_environment(**old_env)
- Parameters:
kwargs – Environment variables to use for git processes.
- Returns:
Dict that maps environment variables to their old values
- propertyversion_info:Tuple[int,...]
- Returns:
Tuple with integers representing the major, minor and additionalversion numbers as parsed fromgit-version(1). Up to four fieldsare used.
This value is generated on demand and is cached.
- propertyworking_dir:None|str|PathLike[str]
- Returns:
Git directory we are working on
- git.cmd.GitMeta
Alias of
Git
’s metaclass, whether it istype
or a custom metaclass.Whether the
Git
class has the defaulttype
as its metaclass or uses acustom metaclass is not documented and may change at any time. This statically checkablemetaclass alias is equivalent at runtime totype(Git)
. This should almost never beused. Code that benefits from it is likely to be remain brittle even if it is used.In view of the
Git
class’s intended use andGit
objects’ dynamiccallable attributes representing git subcommands, it rarely makes sense to inherit fromGit
at all. UsingGit
in multiple inheritance can be especially trickyto do correctly. Attempting uses ofGit
where its metaclass is relevant, suchas when a sibling class has an unrelated metaclass and a shared lower bound metaclassmight have to be introduced to solve a metaclass conflict, is not recommended.- Note:
The correct static type of the
Git
class itself, and any subclasses, isType[Git]
. (This can be written astype[Git]
in Python 3.9 later.)GitMeta
should never be used in any annotation whereType[Git]
isintended or otherwise possible to use. This alias is truly only for very rare andinherently precarious situations where it is necessary to deal with the metaclassexplicitly.
Config
Parser for reading and writing configuration files.
- git.config.GitConfigParser
alias of
GitConfigParser
- classgit.config.SectionConstraint(config:T_ConfigParser,section:str)
Constrains a ConfigParser to only option commands which are constrained toalways use the section we have been initialized with.
It supports all ConfigParser methods that operate on an option.
- Note:
If used as a context manager, will release the wrapped ConfigParser.
- __annotations__={}
- __del__()→None
- __enter__()→SectionConstraint[T_ConfigParser]
- __exit__(exception_type:str,exception_value:str,traceback:str)→None
- __getattr__(attr:str)→Any
- __init__(config:T_ConfigParser,section:str)→None
- __module__='git.config'
- __orig_bases__=(typing.Generic[~T_ConfigParser],)
- __parameters__=(~T_ConfigParser,)
- __slots__=('_config','_section_name')
- propertyconfig:T_ConfigParser
return: ConfigParser instance we constrain
- release()→None
Equivalent to
GitConfigParser.release()
, which is called on ourunderlying parser instance.
Diff
- classgit.diff.Diff(repo:Repo,a_rawpath:bytes|None,b_rawpath:bytes|None,a_blob_id:str|bytes|None,b_blob_id:str|bytes|None,a_mode:bytes|str|None,b_mode:bytes|str|None,new_file:bool,deleted_file:bool,copied_file:bool,raw_rename_from:bytes|None,raw_rename_to:bytes|None,diff:str|bytes|None,change_type:Literal['A','D','C','M','R','T','U']|None,score:int|None)
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 indicate 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_modeisNonea_blobisNonea_pathisNone
Deleted File:
b_modeisNoneb_blobisNoneb_pathisNone
Working Tree Blobs:
When comparing to working trees, the working tree blob will have a null hexshaas a corresponding object does not yet exist. The mode will be null as well. Thepath will be available, though.
If it is listed in a diff, the working tree version of the file must differ fromthe version in the index or tree, and hence has been modified.
- NULL_BIN_SHA=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- NULL_HEX_SHA='0000000000000000000000000000000000000000'
- __eq__(other:object)→bool
Return self==value.
- __hash__()→int
Return hash(self).
- __init__(repo:Repo,a_rawpath:bytes|None,b_rawpath:bytes|None,a_blob_id:str|bytes|None,b_blob_id:str|bytes|None,a_mode:bytes|str|None,b_mode:bytes|str|None,new_file:bool,deleted_file:bool,copied_file:bool,raw_rename_from:bytes|None,raw_rename_to:bytes|None,diff:str|bytes|None,change_type:Literal['A','D','C','M','R','T','U']|None,score:int|None)→None
- __module__='git.diff'
- __ne__(other:object)→bool
Return self!=value.
- __slots__=('a_blob','b_blob','a_mode','b_mode','a_rawpath','b_rawpath','new_file','deleted_file','copied_file','raw_rename_from','raw_rename_to','diff','change_type','score')
- __str__()→str
Return str(self).
- a_blob:'IndexObject'|None
- a_mode
- propertya_path:str|None
- a_rawpath
- b_blob:'IndexObject'|None
- b_mode
- propertyb_path:str|None
- b_rawpath
- change_type:Lit_change_type|None
- copied_file:bool
- deleted_file:bool
- diff
- new_file:bool
- raw_rename_from
- raw_rename_to
- re_header=re.compile(b'\n ^diff[]--git\n [](?P<a_path_fallback>"?[ab]/.+?"?)[](?P<b_path_fallback>"?[ab]/.+?"?)\\n\n (?:^,re.MULTILINE|re.VERBOSE)
- propertyrename_from:str|None
- propertyrename_to:str|None
- propertyrenamed:bool
Deprecated, use
renamed_file
instead.- Returns:
True
if the blob of our diff has been renamed- Note:
This property is deprecated.Please use the
renamed_file
property instead.
- propertyrenamed_file:bool
- Returns:
True
if the blob of our diff has been renamed
- score
- classgit.diff.DiffConstants(value,names=<notgiven>,*values,module=None,qualname=None,type=None,start=1,boundary=None)
Special objects for
Diffable.diff()
.See the
Diffable.diff()
method’sother
parameter, which accepts variousvalues including these.- Note:
These constants are also available as attributes of the
git.diff
module,theDiffable
class and its subclasses and instances, and the top-levelgit
module.
- INDEX=2
Stand-in indicating you want to diff against the index.
Also accessible as
git.INDEX
,git.diff.INDEX
, andDiffable.INDEX
, as well asDiffable.Index
. The latter has beenkept for backward compatibility and made an alias of this, so it may still be used.
- NULL_TREE=1
Stand-in indicating you want to compare against the empty tree in diffs.
Also accessible as
git.NULL_TREE
,git.diff.NULL_TREE
, andDiffable.NULL_TREE
.
- __module__='git.diff'
- classgit.diff.DiffIndex(iterable=(),/)
An index for diffs, allowing a list of
Diff
s to be queried by the diffproperties.The class improves the diff handling convenience.
- __annotations__={}
- __dict__=mappingproxy({'__module__':'git.diff','__doc__':'Anindexfordiffs,allowingalistof:class:`Diff`\\stobequeriedbythediff\n properties.\n\n Theclassimprovesthediffhandlingconvenience.\n ','change_type':('A','C','D','R','M','T'),'iter_change_type':<functionDiffIndex.iter_change_type>,'__orig_bases__':(typing.List[~T_Diff],),'__dict__':<attribute'__dict__'of'DiffIndex'objects>,'__weakref__':<attribute'__weakref__'of'DiffIndex'objects>,'__parameters__':(~T_Diff,),'__annotations__':{}})
- __module__='git.diff'
- __orig_bases__=(typing.List[~T_Diff],)
- __parameters__=(~T_Diff,)
- __weakref__
list of weak references to the object
- change_type=('A','C','D','R','M','T')
Change type invariant identifying possible ways a blob can have changed:
A
= AddedD
= DeletedR
= RenamedM
= ModifiedT
= Changed in the type
- iter_change_type(change_type:Literal['A','D','C','M','R','T','U'])→Iterator[T_Diff]
- Returns:
Iterator yielding
Diff
instances that match the givenchange_type- Parameters:
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
’T’ for changed in the type paths
- classgit.diff.Diffable
Common interface for all objects that can be diffed against another object ofcompatible type.
- Note:
Subclasses require a
repo
member, as it is the case forObject
instances. For practical reasons we do notderive fromObject
.
- INDEX=2
Stand-in indicating you want to diff against the index.
See the
diff()
method, which accepts this as a value of itsother
parameter.This is the same as
DiffConstants.INDEX
, and may also be accessed asgit.INDEX
andgit.diff.INDEX
, as well asDiffable.INDEX
,which is kept for backward compatibility (it is now defined an alias of this).
- Index=2
Stand-in indicating you want to diff against the index(same as
INDEX
).This is an alias of
INDEX
, for backward compatibility. SeeINDEX
anddiff()
for details.- Note:
Although always meant for use as an opaque constant, this was formerly definedas a class. Its usage is unchanged, but static type annotations that attemptto permit only this object must be changed to avoid new mypy errors. This waspreviously not possible to do, though
Type[Diffable.Index]
approximated it.It is now possible to do precisely, usingLiteral[DiffConstants.INDEX]
.
- NULL_TREE=1
Stand-in indicating you want to compare against the empty tree in diffs.
See the
diff()
method, which accepts this as a value of itsother
parameter.This is the same as
DiffConstants.NULL_TREE
, and may also be accessed asgit.NULL_TREE
andgit.diff.NULL_TREE
.
- __annotations__={'repo':'Repo'}
- __module__='git.diff'
- __slots__=()
- diff(other:DiffConstants|Tree|Commit|str|None=DiffConstants.INDEX,paths:str|os.PathLike[str]|List[str|os.PathLike[str]]|Tuple[str|os.PathLike[str],...]|None=None,create_patch:bool=False,**kwargs:Any)→DiffIndex[Diff]
Create diffs between two items being trees, trees and index or an index andthe working tree. Detects renames automatically.
- Parameters:
other –
This the item to compare us with.
If
None
, we will be compared to the working tree.If a
Tree_ish
or string, it will be compared againstthe respective tree.If
INDEX
, it will be compared against the index.If
NULL_TREE
, it will compare against the empty tree.
This parameter defaults to
INDEX
(rather thanNone
) so that themethod will not by default fail on bare repositories.paths – This a list of paths or a single path to limit the diff to. It will onlyinclude at least one of the given path or paths.
create_patch – If
True
, the returnedDiff
contains a detailed patch that ifapplied makes the self to other. Patches are somewhat costly as blobs haveto be read and diffed.kwargs – Additional arguments passed togit-diff(1), such as
R=True
toswap both sides of the diff.
- Returns:
A
DiffIndex
representing the computed diff.- Note:
On a bare repository,other needs to be provided as
INDEX
, or asan instance ofTree
orCommit
, or a git command error will occur.
- git.diff.INDEX:INDEX:2>]=DiffConstants.INDEX
Stand-in indicating you want to diff against the index.
See
Diffable.diff()
, which accepts this as a value of itsother
parameter.This is an alias of
DiffConstants.INDEX
, which may also be accessed asgit.INDEX
andDiffable.INDEX
, as well asDiffable.Index
.
- git.diff.NULL_TREE:NULL_TREE:1>]=DiffConstants.NULL_TREE
Stand-in indicating you want to compare against the empty tree in diffs.
See
Diffable.diff()
, which accepts this as a value of itsother
parameter.This is an alias of
DiffConstants.NULL_TREE
, which may also be accessed asgit.NULL_TREE
andDiffable.NULL_TREE
.
Exceptions
Exceptions thrown throughout the git package.
- exceptiongit.exc.AmbiguousObjectName
Thrown if a possibly shortened name does not uniquely represent a single objectin the database
- __module__='gitdb.exc'
- exceptiongit.exc.BadName
A name provided to rev_parse wasn’t understood
- __annotations__={}
- __module__='gitdb.exc'
- __str__()
Return str(self).
- exceptiongit.exc.BadObject
The object with the given SHA does not exist. Instantiate with thefailed sha
- __annotations__={}
- __module__='gitdb.exc'
- __str__()
Return str(self).
- exceptiongit.exc.BadObjectType
The object had an unsupported type
- __annotations__={}
- __module__='gitdb.exc'
- exceptiongit.exc.CacheError
Base for all errors related to the git index, which is called “cache”internally.
- __annotations__={}
- __module__='git.exc'
- exceptiongit.exc.CheckoutError(message:str,failed_files:Sequence[str|os.PathLike[str]],valid_files:Sequence[str|os.PathLike[str]],failed_reasons:List[str])
Thrown if a file could not be checked out from the index as it containedchanges.
The
failed_files
attribute contains a list of relative paths that failed tobe checked out as they contained changes that did not exist in the index.The
failed_reasons
attribute contains a string informing about the actualcause of the issue.The
valid_files
attribute contains a list of relative paths to files thatwere checked out successfully and hence match the version stored in the index.- __annotations__={}
- __init__(message:str,failed_files:Sequence[str|os.PathLike[str]],valid_files:Sequence[str|os.PathLike[str]],failed_reasons:List[str])→None
- __module__='git.exc'
- __str__()→str
Return str(self).
- exceptiongit.exc.CommandError(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception=None,stderr:bytes|str|None=None,stdout:bytes|str|None=None)
Base class for exceptions thrown at every stage of
Popen
execution.- Parameters:
command – A non-empty list of argv comprising the command-line.
- __annotations__={}
- __init__(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception=None,stderr:bytes|str|None=None,stdout:bytes|str|None=None)→None
- __module__='git.exc'
- __str__()→str
Return str(self).
- exceptiongit.exc.GitCommandError(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception=None,stderr:bytes|str|None=None,stdout:bytes|str|None=None)
Thrown if execution of the git command fails with non-zero status code.
- __annotations__={}
- __init__(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception=None,stderr:bytes|str|None=None,stdout:bytes|str|None=None)→None
- __module__='git.exc'
- exceptiongit.exc.GitCommandNotFound(command:List[str]|Tuple[str]|str,cause:str|Exception)
Thrown if we cannot find the
git
executable in thePATH
or at thepath given by theGIT_PYTHON_GIT_EXECUTABLE
environment variable.- __annotations__={}
- __init__(command:List[str]|Tuple[str]|str,cause:str|Exception)→None
- __module__='git.exc'
- exceptiongit.exc.GitError
Base class for all package exceptions.
- __annotations__={}
- __module__='git.exc'
- __weakref__
list of weak references to the object
- exceptiongit.exc.HookExecutionError(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception,stderr:bytes|str|None=None,stdout:bytes|str|None=None)
Thrown if a hook exits with a non-zero exit code.
This provides access to the exit code and the string returned via standard output.
- __annotations__={}
- __init__(command:List[str]|Tuple[str,...]|str,status:str|int|None|Exception,stderr:bytes|str|None=None,stdout:bytes|str|None=None)→None
- __module__='git.exc'
- exceptiongit.exc.InvalidDBRoot
Thrown if an object database cannot be initialized at the given path
- __annotations__={}
- __module__='gitdb.exc'
- exceptiongit.exc.InvalidGitRepositoryError
Thrown if the given repository appears to have an invalid format.
- __annotations__={}
- __module__='git.exc'
- exceptiongit.exc.NoSuchPathError
Thrown if a path could not be access by the system.
- __annotations__={}
- __module__='git.exc'
- __weakref__
list of weak references to the object
- exceptiongit.exc.ODBError
All errors thrown by the object database
- __annotations__={}
- __module__='gitdb.exc'
- __weakref__
list of weak references to the object
- exceptiongit.exc.ParseError
Thrown if the parsing of a file failed due to an invalid format
- __annotations__={}
- __module__='gitdb.exc'
- exceptiongit.exc.RepositoryDirtyError(repo:Repo,message:str)
Thrown whenever an operation on a repository fails as it has uncommitted changesthat would be overwritten.
- __annotations__={}
- __module__='git.exc'
- __str__()→str
Return str(self).
- exceptiongit.exc.UnmergedEntriesError
Thrown if an operation cannot proceed as there are still unmergedentries in the cache.
- __annotations__={}
- __module__='git.exc'
- exceptiongit.exc.UnsafeOptionError
Thrown if unsafe options are passed without being explicitly allowed.
- __annotations__={}
- __module__='git.exc'
- exceptiongit.exc.UnsafeProtocolError
Thrown if unsafe protocols are passed without being explicitly allowed.
- __annotations__={}
- __module__='git.exc'
Refs.symbolic
- classgit.refs.symbolic.SymbolicReference(repo:Repo,path:str|os.PathLike[str],check_path:bool=False)
Special case of a reference that is symbolic.
This 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
.- __annotations__={'reference':typing.Union[ForwardRef('Head'),ForwardRef('TagReference'),ForwardRef('RemoteReference'),ForwardRef('Reference')]}
- __eq__(other:object)→bool
Return self==value.
- __hash__()→int
Return hash(self).
- __module__='git.refs.symbolic'
- __ne__(other:object)→bool
Return self!=value.
- __repr__()→str
Return repr(self).
- __slots__=('repo','path')
- __str__()→str
Return str(self).
- propertyabspath:str|PathLike[str]
- classmethodcreate(repo:Repo,path:str|os.PathLike[str],reference:SymbolicReference|str='HEAD',logmsg:str|None=None,force:bool=False,**kwargs:Any)→T_References
Create a new symbolic reference: 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,e.g.
NEW_HEAD
orsymrefs/my_new_symref
.reference – The reference which the new symbolic reference should point to.If it is a commit-ish, the symbolic ref will be detached.
force – If
True
, force creation even if a symbolic reference with that namealready exists. RaiseOSError
otherwise.logmsg – If not
None
, the message to append to the reflog.IfNone
, no reflog entry is written.
- Returns:
Newly created symbolic reference
- Raises:
OSError – If a (Symbolic)Reference with the same name but different contents alreadyexists.
- Note:
This does not alter the current HEAD, index or working tree.
- classmethoddelete(repo:Repo,path:str|os.PathLike[str])→None
Delete the reference at the given path.
- Parameters:
repo – Repository to delete the reference from.
path – Short or full path pointing to the reference, e.g.
refs/myreference
orjustmyreference
, hencerefs/
is implied.Alternatively the symbolic reference to be deleted.
- classmethoddereference_recursive(repo:Repo,ref_path:str|os.PathLike[str]|None)→str
- Returns:
hexsha stored in the reference at the givenref_path, recursivelydereferencing all intermediate references as required
- Parameters:
repo – The repository containing the reference atref_path.
- classmethodfrom_path(repo:Repo,path:str|os.PathLike[str])→T_References
Make a symbolic reference from a path.
- Parameters:
path – Full
.git
-directory-relative path name to the Reference to instantiate.- Note:
Use
to_full_path()
if you only have a partial path of a knownReference type.- Returns:
Instance of type
Reference
,Head
, orTag
, depending onthe given path.
- propertyis_detached:bool
- Returns:
True
if we are a detached reference, hence we point to a specific commitinstead to another reference.
- is_remote()→bool
- Returns:
True if this symbolic reference points to a remote branch
- is_valid()→bool
- Returns:
True
if the reference is valid, hence it can be read and points to avalid object or reference.
- classmethoditer_items(repo:Repo,common_path:str|os.PathLike[str]|None=None,*args:Any,**kwargs:Any)→Iterator[T_References]
Find all refs in the repository.
- Parameters:
repo – The
Repo
.common_path – Optional keyword argument to the path which is to be shared by all returnedRef objects.Defaults to class specific portion if
None
, ensuring that only refssuitable for the actual class are returned.
- Returns:
A list of
SymbolicReference
, each guaranteed to be a symbolic refwhich is not detached and pointing to a valid ref.The list is lexicographically sorted. The returned objects are instances ofconcrete subclasses, such as
Head
orTagReference
.
- log()→RefLog
- Returns:
RefLog
for this reference.Its last entry reflects the latest change applied to this reference.- Note:
As the log is parsed every time, its recommended to cache it for use insteadof calling this method repeatedly. It should be considered read-only.
- log_append(oldbinsha:bytes,message:str|None,newbinsha:bytes|None=None)→RefLogEntry
Append a logentry to the logfile of this ref.
- Parameters:
oldbinsha – Binary sha this ref used to point to.
message – A message describing the change.
newbinsha – The sha the ref points to now. If None, our current commit sha will be used.
- Returns:
The added
RefLogEntry
instance.
- log_entry(index:int)→RefLogEntry
- Returns:
RefLogEntry
at the given index- Parameters:
index – Python list compatible positive or negative index.
- Note:
This method must read part of the reflog during execution, hence it shouldbe used sparingly, or only if you need just one index. In that case, it willbe faster than the
log()
method.
- propertyname:str
- Returns:
In case of symbolic references, the shortest assumable name is the pathitself.
- path
- propertyref:SymbolicReference
Returns the Reference we point to
- propertyreference:SymbolicReference
Returns the Reference we point to
- rename(new_path:str|PathLike[str],force:bool=False)→SymbolicReference
Rename self to a new path.
- Parameters:
new_path – Either a simple name or a full path, e.g.
new_name
orfeatures/new_name
.The prefixrefs/
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 namealready exists. It will be overwritten in that case.
- Returns:
self
- Raises:
OSError – If a file at path but with different contents already exists.
- repo
- set_commit(commit:Commit|SymbolicReference|str,logmsg:str|None=None)→SymbolicReference
Like
set_object()
, but restricts the type of object to be aCommit
.- Raises:
ValueError – Ifcommit is not a
Commit
object, nor does itpoint to a commit.- Returns:
self
- set_object(object:Commit|Tree|TagObject|Blob|SymbolicReference|str,logmsg:str|None=None)→SymbolicReference
Set the object we point to, possibly dereference our symbolic referencefirst. If the reference does not exist, it will be created.
- Parameters:
object –
A refspec, a
SymbolicReference
or anObject
instance.SymbolicReference
instances will be dereferenced beforehand toobtain the git object they point to.Object
instances must represent git objects(AnyGitObject
).
logmsg – If not
None
, the message will be used in the reflog entry to be written.Otherwise the reflog is not altered.
- Note:
Plain
SymbolicReference
instances may not actually point to objectsby convention.- Returns:
self
- set_reference(ref:Commit|Tree|TagObject|Blob|SymbolicReference|str,logmsg:str|None=None)→SymbolicReference
Set ourselves to the givenref.
It will stay a symbol if theref is a
Reference
.Otherwise a git object, specified as a
Object
instance or refspec, is assumed. If it is valid, this reference will be set toit, which effectively detaches the reference if it was a purely symbolic one.- Parameters:
ref – A
SymbolicReference
instance, anObject
instance (specifically anAnyGitObject
), or a refspecstring. Only if the ref is aSymbolicReference
instance, we willpoint to it. Everything else is dereferenced to obtain the actual object.logmsg –
If set to a string, the message will be used in the reflog.Otherwise, a reflog entry is not written for the changed reference.The previous commit of the entry will be the commit we point to now.
See also:
log_append()
- Returns:
self
- Note:
This symbolic reference will not be dereferenced. For that, see
set_object()
.
- classmethodto_full_path(path:str|PathLike[str]|SymbolicReference)→str|PathLike[str]
- Returns:
String with a full repository-relative path which can be used to initializea
Reference
instance, for instance by usingReference.from_path
.
Refs.reference
- classgit.refs.reference.Reference(repo:Repo,path:str|os.PathLike[str],check_path:bool=True)
A named reference to any object.
Subclasses may apply restrictions though, e.g., a
Head
canonly point to commits.- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','path':'str','reference':"Union['Head','TagReference','RemoteReference','Reference']"}
- __init__(repo:Repo,path:str|os.PathLike[str],check_path:bool=True)→None
Initialize this instance.
- Parameters:
repo – Our parent repository.
path – Path relative to the
.git/
directory pointing to the ref in question,e.g.refs/heads/master
.check_path – If
False
, you can provide any path.Otherwise the path must start with the default path prefix of this type.
- __module__='git.refs.reference'
- __parameters__=()
- __slots__=()
- __str__()→str
Return str(self).
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- classmethoditer_items(repo:Repo,common_path:str|os.PathLike[str]|None=None,*args:Any,**kwargs:Any)→Iterator[T_References]
Equivalent to
SymbolicReference.iter_items
,but will return non-detached references as well.
- propertyname:str
- Returns:
(shortest) Name of this reference - it may contain path components
- propertyremote_head:_T
- propertyremote_name:_T
Refs.head
Some ref-based objects.
Note the distinction between theHEAD
andHead
classes.
- classgit.refs.head.HEAD(repo:Repo,path:str|os.PathLike[str]='HEAD')
Special case of a
SymbolicReference
representing therepository’s HEAD reference.- __annotations__={'commit':'Commit'}
- __module__='git.refs.head'
- __slots__=()
- orig_head()→SymbolicReference
- Returns:
SymbolicReference
pointing at the ORIG_HEAD,which is maintained to contain the previous value of HEAD.
- reset(commit:Commit|TagObject|SymbolicReference|str='HEAD',index:bool=True,working_tree:bool=False,paths:str|os.PathLike[str]|Sequence[str|os.PathLike[str]]|None=None,**kwargs:Any)→HEAD
Reset our HEAD to the given commit optionally synchronizing the index andworking tree. The reference we refer to will be set to commit as well.
- Parameters:
commit –
Commit
,Reference
,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 givencommit, possibly overwriting uncommitted changes without warning.Ifworking_tree isTrue
,index must beTrue
as well.paths – Single path or list of paths relative to the git root directorythat are to be reset. This allows to partially reset individual files.
kwargs – Additional arguments passed togit-reset(1).
- Returns:
self
- classgit.refs.head.Head(repo:Repo,path:str|os.PathLike[str],check_path:bool=True)
A Head is a named reference to a
Commit
. Every Headinstance contains a name and aCommit
object.Examples:
>>>repo=Repo("/path/to/repo")>>>head=repo.heads[0]>>>head.name'master'>>>head.commit<git.Commit "1c09f116cbc2cb4100fb6935bb162daa4723f455">>>>head.commit.hexsha'1c09f116cbc2cb4100fb6935bb162daa4723f455'
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','path':'str','reference':"Union['Head','TagReference','RemoteReference','Reference']"}
- __dict__=mappingproxy({'__module__':'git.refs.head','__doc__':'AHeadisanamedreferencetoa:class:`~git.objects.commit.Commit`.EveryHead\n instancecontainsanameanda:class:`~git.objects.commit.Commit`object.\n\n Examples::\n\n >>>repo=Repo("/path/to/repo")\n >>>head=repo.heads[0]\n\n >>>head.name\n \'master\'\n\n >>>head.commit\n <git.Commit"1c09f116cbc2cb4100fb6935bb162daa4723f455">\n\n >>>head.commit.hexsha\n \'1c09f116cbc2cb4100fb6935bb162daa4723f455\'\n ','_common_path_default':'refs/heads','k_config_remote':'remote','k_config_remote_ref':'merge','delete':<classmethod(<functionHead.delete>)>,'set_tracking_branch':<functionHead.set_tracking_branch>,'tracking_branch':<functionHead.tracking_branch>,'rename':<functionHead.rename>,'checkout':<functionHead.checkout>,'_config_parser':<functionHead._config_parser>,'config_reader':<functionHead.config_reader>,'config_writer':<functionHead.config_writer>,'__dict__':<attribute'__dict__'of'Head'objects>,'__weakref__':<attribute'__weakref__'of'Head'objects>,'__parameters__':(),'_is_protocol':False,'__subclasshook__':<classmethod(<function_proto_hook>)>,'__abstractmethods__':frozenset(),'_abc_impl':<_abc._abc_dataobject>,'__annotations__':{'path':'str','reference':"Union['Head','TagReference','RemoteReference','Reference']",'_id_attribute_':'str'}})
- __module__='git.refs.head'
- __parameters__=()
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- __weakref__
list of weak references to the object
- checkout(force:bool=False,**kwargs:Any)→HEAD|Head
Check out this head by setting the HEAD to this reference, by updating theindex to reflect the tree we point to and by updating the working tree toreflect 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.IfFalse
,GitCommandError
will be raised in thatsituation.kwargs – Additional keyword arguments to be passed to git checkout, e.g.
b="new_branch"
to create a new branch at the given spot.
- Returns:
The active branch after the checkout operation, usually self unless a newbranch has been created.If there is no active branch, as the HEAD is now detached, the HEADreference will be returned instead.
- Note:
By default it is only allowed to checkout heads - everything else will leavethe HEAD detached which is allowed and possible, but remains a special statethat some tools might not be able to handle.
- config_reader()→SectionConstraint[GitConfigParser]
- Returns:
A configuration parser instance constrained to only read this instance’svalues.
- config_writer()→SectionConstraint[GitConfigParser]
- Returns:
A configuration writer instance with read-and write access to options ofthis head.
- classmethoddelete(repo:Repo,*heads:Head|str,force:bool=False,**kwargs:Any)→None
Delete the given heads.
- Parameters:
force – If
True
, the heads will be deleted even if they are not yet merged intothe main development stream. DefaultFalse
.
- k_config_remote='remote'
- k_config_remote_ref='merge'
- rename(new_path:str|os.PathLike[str],force:bool=False)→Head
Rename self to a new path.
- Parameters:
new_path – Either a simple name or a path, e.g.
new_name
orfeatures/new_name
.The prefixrefs/heads
is implied.force – If
True
, the rename will succeed even if a head with the target namealready exists.
- Returns:
self
- Note:
Respects the ref log, as git commands are used.
- set_tracking_branch(remote_reference:RemoteReference|None)→Head
Configure this branch to track the given remote reference. This willalter this branch’s configuration accordingly.
- Parameters:
remote_reference – The remote reference to track or None to untrack any references.
- Returns:
self
- tracking_branch()→RemoteReference|None
- Returns:
The remote reference we are tracking, or
None
if we are not a trackingbranch.
Refs.tag
Provides aReference
-based type for lightweight tags.
This defines theTagReference
class (and its aliasTag
), whichrepresents lightweight tags. For annotated tags (which are git objects), see thegit.objects.tag
module.
- git.refs.tag.Tag
alias of
TagReference
- classgit.refs.tag.TagReference(repo:Repo,path:str|os.PathLike[str],check_path:bool=True)
A lightweight tag reference which either points to a commit, a tag object or anyother object. In the latter case additional information, like the signature or thetag-creator, is available.
This tag object will always point to a commit object, but may carry additionalinformation in a tag object:
tagref=TagReference.list_items(repo)[0]print(tagref.commit.message)iftagref.tagisnotNone:print(tagref.tag.message)
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','path':'str','reference':"Union['Head','TagReference','RemoteReference','Reference']"}
- __module__='git.refs.tag'
- __parameters__=()
- __slots__=()
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- propertycommit:Commit
- Returns:
Commit object the tag ref points to
- Raises:
ValueError – If the tag points to a tree or blob.
- classmethodcreate(repo:Repo,path:str|os.PathLike[str],reference:str|SymbolicReference='HEAD',logmsg:str|None=None,force:bool=False,**kwargs:Any)→TagReference
Create a new tag reference.
- Parameters:
repo – The
Repo
to create the tag in.path – The name of the tag, e.g.
1.0
orreleases/1.0
.The prefixrefs/tags
is implied.reference – A reference to the
Object
you want to tag.The referenced object can be a commit, tree, or blob.logmsg –
If not
None
, the message will be used in your tag object. This will alsocreate an additional tag object that allows to obtain that information,e.g.:tagref.tag.message
message – Synonym for thelogmsg parameter. Included for backwards compatibility.logmsg takes precedence if both are passed.
force – If
True
, force creation of a tag even though that tag already exists.kwargs – Additional keyword arguments to be passed togit-tag(1).
- Returns:
A new
TagReference
.
- classmethoddelete(repo:Repo,*tags:TagReference)→None
Delete the given existing tag or tags.
Refs.remote
Module implementing a remote object allowing easy access to git remotes.
- classgit.refs.remote.RemoteReference(repo:Repo,path:str|os.PathLike[str],check_path:bool=True)
A reference pointing to a remote head.
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','path':'str','reference':"Union['Head','TagReference','RemoteReference','Reference']"}
- __module__='git.refs.remote'
- __parameters__=()
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- classmethodcreate(*args:Any,**kwargs:Any)→NoReturn
Raise
TypeError
. Defined so thecreate
method is disabled.
- classmethoddelete(repo:Repo,*refs:RemoteReference,**kwargs:Any)→None
Delete the given remote references.
- Note:
kwargs are given for comparability with the base class method as weshould not narrow the signature.
- classmethoditer_items(repo:Repo,common_path:str|os.PathLike[str]|None=None,remote:Remote|None=None,*args:Any,**kwargs:Any)→Iterator[RemoteReference]
Iterate remote references, and if given, constrain them to the given remote.
Refs.log
- classgit.refs.log.RefLog(filepath:str|os.PathLike[str]|None=None)
A reflog contains
RefLogEntry
s, each of which defines a certain stateof the head in question. Custom query methods allow to retrieve log entries by dateor by other criteria.Reflog entries are ordered. The first added entry is first in the list. The lastentry, i.e. the last change of the head or reference, is last in the list.
- __abstractmethods__=frozenset({})
- __annotations__={}
- __init__(filepath:str|os.PathLike[str]|None=None)→None
Initialize this instance with an optional filepath, from which we willinitialize our data. The path is also used to write changes back using the
write()
method.
- __module__='git.refs.log'
- __orig_bases__=(typing.List[git.refs.log.RefLogEntry],<class'git.objects.util.Serializable'>)
- __parameters__=()
- __slots__=('_path',)
- classmethodappend_entry(config_reader:Actor|GitConfigParser|SectionConstraint|None,filepath:str|os.PathLike[str],oldbinsha:bytes,newbinsha:bytes,message:str,write:bool=True)→RefLogEntry
Append a new log entry to the revlog at filepath.
- Parameters:
config_reader – Configuration reader of the repository - used to obtain user information.May also be an
Actor
instance identifying the committerdirectly orNone
.filepath – Full path to the log file.
oldbinsha – Binary sha of the previous commit.
newbinsha – Binary sha of the current commit.
message – Message describing the change to the reference.
write – If
True
, the changes will be written right away.Otherwise the change will not be written.
- Returns:
RefLogEntry
objects which was appended to the log.- Note:
As we are append-only, concurrent access is not a problem as we do notinterfere with readers.
- classmethodentry_at(filepath:str|os.PathLike[str],index:int)→RefLogEntry
- Returns:
RefLogEntry
at the given index.- Parameters:
filepath – Full path to the index file from which to read the entry.
index – Python list compatible index, i.e. it may be negative to specify an entrycounted from the end of the list.
- Raises:
IndexError – If the entry didn’t exist.
- Note:
This method is faster as it only parses the entry at index, skipping allother lines. Nonetheless, the whole file has to be read if the index isnegative.
- classmethodfrom_file(filepath:str|os.PathLike[str])→RefLog
- Returns:
A new
RefLog
instance containing all entries from the reflog at thegivenfilepath.- Parameters:
filepath – Path to reflog.
- Raises:
ValueError – If the file could not be read or was corrupted in some way.
- classmethoditer_entries(stream:str|BytesIO|mmap)→Iterator[RefLogEntry]
- Returns:
Iterator yielding
RefLogEntry
instances, one for each line readfrom the given stream.- Parameters:
stream – File-like object containing the revlog in its native format or stringinstance pointing to a file to read.
- classmethodpath(ref:SymbolicReference)→str
- Returns:
String to absolute path at which the reflog of the given ref instance wouldbe found. The path is not guaranteed to point to a valid file though.
- Parameters:
ref –
SymbolicReference
instance
- to_file(filepath:str|os.PathLike[str])→None
Write the contents of the reflog instance to a file at the given filepath.
- Parameters:
filepath – Path to file. Parent directories are assumed to exist.
- classgit.refs.log.RefLogEntry(iterable=(),/)
Named tuple allowing easy access to the revlog data fields.
- __annotations__={}
- __module__='git.refs.log'
- __orig_bases__=(typing.Tuple[str,str,git.util.Actor,typing.Tuple[int,int],str],)
- __parameters__=()
- __repr__()→str
Representation of ourselves in git reflog format.
- __slots__=()
- format()→str
- Returns:
A string suitable to be placed in a reflog file.
- classmethodfrom_line(line:bytes)→RefLogEntry
- Returns:
New
RefLogEntry
instance from the given revlog line.- Parameters:
line – Line bytes without trailing newline
- Raises:
ValueError – Ifline could not be parsed.
- propertymessage:str
Message describing the operation that acted on the reference.
- classmethodnew(oldhexsha:str,newhexsha:str,actor:Actor,time:int,tz_offset:int,message:str)→RefLogEntry
- Returns:
New instance of a
RefLogEntry
- propertynewhexsha:str
The hexsha to the commit the ref now points to, after the change.
- propertyoldhexsha:str
The hexsha to the commit the ref pointed to before the change.
- propertytime:Tuple[int,int]
Time as tuple:
[0] =
int(time)
[1] =
int(timezone_offset)
intime.altzone
format
Remote
Module implementing a remote object allowing easy access to git remotes.
- classgit.remote.FetchInfo(ref:SymbolicReference,flags:int,note:str='',old_commit:Commit|Tree|TagObject|Blob|None=None,remote_ref_path:str|os.PathLike[str]|None=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_HEADinfo.flags# additional flags to be & with enumeration members,# i.e. info.flags & info.REJECTED# is 0 if ref is SymbolicReferenceinfo.note# additional notes given by git-fetch intended for the userinfo.old_commit# if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD,# field is set to the previous location of ref, otherwise Noneinfo.remote_ref_path# The path from which we fetched on the remote. It's the remote's version of our info.ref
- ERROR=128
- FAST_FORWARD=64
- FORCED_UPDATE=32
- HEAD_UPTODATE=4
- NEW_HEAD=2
- NEW_TAG=1
- REJECTED=16
- TAG_UPDATE=8
- __abstractmethods__=frozenset({})
- __annotations__={'_flag_map':typing.Dict[typing.Literal['','!','+','-','*','=','t','?'],int],'_id_attribute_':'str'}
- __init__(ref:SymbolicReference,flags:int,note:str='',old_commit:Commit|Tree|TagObject|Blob|None=None,remote_ref_path:str|os.PathLike[str]|None=None)→None
Initialize a new instance.
- __module__='git.remote'
- __parameters__=()
- __slots__=('ref','old_commit','flags','note','remote_ref_path')
- __str__()→str
Return str(self).
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- flags
- classmethoditer_items(repo:Repo,*args:Any,**kwargs:Any)→NoReturn
Find (all) items of this type.
Subclasses can specifyargs andkwargs differently, and may use them forfiltering. However, when the method is called with no additional positional orkeyword arguments, subclasses are obliged to to yield all items.
- Returns:
Iterator yielding Items
- propertyname:str
- Returns:
Name of our remote ref
- note
- old_commit
- ref
- classmethodrefresh()→Literal[True]
Update information about whichgit-fetch(1) flags are supportedby the git executable being used.
Called by the
git.refresh()
function in the top level__init__
.
- remote_ref_path
- classgit.remote.PushInfo(flags:int,local_ref:SymbolicReference|None,remote_ref_string:str,remote:Remote,old_commit:str|None=None,summary:str='')
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 resultinfo.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 sideinfo.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 indicatedinfo.summary# summary line providing human readable english text about the push
- DELETED=64
- ERROR=1024
- FAST_FORWARD=256
- FORCED_UPDATE=128
- NEW_HEAD=2
- NEW_TAG=1
- NO_MATCH=4
- REJECTED=8
- REMOTE_FAILURE=32
- REMOTE_REJECTED=16
- UP_TO_DATE=512
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str'}
- __init__(flags:int,local_ref:SymbolicReference|None,remote_ref_string:str,remote:Remote,old_commit:str|None=None,summary:str='')→None
Initialize a new instance.
local_ref: HEAD | Head | RemoteReference | TagReference | Reference | SymbolicReference | None
- __module__='git.remote'
- __parameters__=()
- __slots__=('local_ref','remote_ref_string','flags','_old_commit_sha','_remote','summary')
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- flags
- classmethoditer_items(repo:Repo,*args:Any,**kwargs:Any)→NoReturn
Find (all) items of this type.
Subclasses can specifyargs andkwargs differently, and may use them forfiltering. However, when the method is called with no additional positional orkeyword arguments, subclasses are obliged to to yield all items.
- Returns:
Iterator yielding Items
- local_ref
- propertyremote_ref:RemoteReference|TagReference
- Returns:
Remote
Reference
orTagReference
in the local repository corresponding totheremote_ref_string
kept in this instance.
- remote_ref_string
- summary
- classgit.remote.Remote(repo:Repo,name:str)
Provides easy read and write access to a git remote.
Everything not part of this interface is considered an option for the currentremote, allowing constructs like
remote.pushurl
to query the pushurl.- Note:
When querying configuration, the configuration accessor will be cached to speedup subsequent accesses.
- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':'str','url':<class'str'>}
- __eq__(other:object)→bool
Return self==value.
- __getattr__(attr:str)→Any
Allows to call this instance like
remote.special(*args,**kwargs)
tocallgitremotespecialself.name
.
- __hash__()→int
Return hash(self).
- __init__(repo:Repo,name:str)→None
Initialize a remote instance.
- Parameters:
repo – The repository we are a remote of.
name – The name of the remote, e.g.
origin
.
- __module__='git.remote'
- __ne__(other:object)→bool
Return self!=value.
- __parameters__=()
- __repr__()→str
Return repr(self).
- __slots__=('repo','name','_config_reader')
- __str__()→str
Return str(self).
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- add_url(url:str,allow_unsafe_protocols:bool=False,**kwargs:Any)→Remote
Adds a new url on current remote (special case of
gitremoteset-url
).This command adds new URLs to a given remote, making it possible to havemultiple URLs for a single remote.
- Parameters:
url – String being the URL to add as an extra remote URL.
allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.
- Returns:
self
- propertyconfig_reader:SectionConstraint[GitConfigParser]
- Returns:
GitConfigParser
compatible object able to read optionsfor only our remote. Hence you may simply typeconfig.get("pushurl")
toobtain the information.
- propertyconfig_writer:SectionConstraint
- Returns:
GitConfigParser
-compatible object able to write optionsfor this remote.- Note:
You can only own one writer at a time - delete it to release theconfiguration file and make it usable by others.
To assure consistent results, you should only query options through thewriter. Once you are done writing, you are free to use the config readeronce again.
- classmethodcreate(repo:Repo,name:str,url:str,allow_unsafe_protocols:bool=False,**kwargs:Any)→Remote
Create a new remote to the given repository.
- Parameters:
repo – Repository instance that is to receive the new remote.
name – Desired name of the remote.
url – URL which corresponds to the remote’s name.
allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.kwargs – Additional arguments to be passed to the
gitremoteadd
command.
- Returns:
New
Remote
instance- Raises:
git.exc.GitCommandError – In case an origin with that name already exists.
- delete_url(url:str,**kwargs:Any)→Remote
Deletes a new url on current remote (special case of
gitremoteset-url
).This command deletes new URLs to a given remote, making it possible to havemultiple URLs for a single remote.
- Parameters:
url – String being the URL to delete from the remote.
- Returns:
self
- exists()→bool
- Returns:
True
if this is a valid, existing remote.Valid remotes have an entry in the repository’s configuration.
- fetch(refspec:str|List[str]|None=None,progress:RemoteProgress|None|UpdateProgress=None,verbose:bool=True,kill_after_timeout:None|float=None,allow_unsafe_protocols:bool=False,allow_unsafe_options:bool=False,**kwargs:Any)→IterableList[FetchInfo]
Fetch the latest changes for this remote.
- Parameters:
refspec –
A “refspec” is used by fetch and push to describe the mappingbetween remote ref and local ref. They are combined with a colon inthe format
<src>:<dst>
, preceded by an optional plus sign,+
.For example:gitfetch$URLrefs/heads/master:refs/heads/origin
means“grab the master branch head from the $URL and store it as my originbranch head”. Andgitpush$URLrefs/heads/master:refs/heads/to-upstream
means “publish my master branch head as to-upstream branch at $URL”.See alsogit-push(1).Taken from the git manual,gitglossary(7).
Fetch supports multiple refspecs (as the underlyinggit-fetch(1)does) - supplying a list rather than a string for ‘refspec’ will make use ofthis facility.
progress – See the
push()
method.verbose – Boolean for verbose output.
kill_after_timeout – To specify a timeout in seconds for the git command, after which the processshould be killed. It is set to
None
by default.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.kwargs – Additional arguments to be passed togit-fetch(1).
- Returns:
IterableList(FetchInfo, …) list of
FetchInfo
instances providingdetailed information about the fetch results- Note:
As fetch does not provide progress information to non-ttys, we cannot makeit available here unfortunately as in the
push()
method.
- classmethoditer_items(repo:Repo,*args:Any,**kwargs:Any)→Iterator[Remote]
- Returns:
Iterator yielding
Remote
objects of the given repository
- name
- pull(refspec:str|List[str]|None=None,progress:RemoteProgress|UpdateProgress|None=None,kill_after_timeout:None|float=None,allow_unsafe_protocols:bool=False,allow_unsafe_options:bool=False,**kwargs:Any)→IterableList[FetchInfo]
Pull changes from the given branch, being the same as a fetch followed by amerge of branch with your local branch.
- Parameters:
refspec – See
fetch()
method.progress – See
push()
method.kill_after_timeout – See
fetch()
method.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.kwargs – Additional arguments to be passed togit-pull(1).
- Returns:
Please see
fetch()
method.
- push(refspec:str|List[str]|None=None,progress:RemoteProgress|UpdateProgress|Callable[[...],RemoteProgress]|None=None,kill_after_timeout:None|float=None,allow_unsafe_protocols:bool=False,allow_unsafe_options:bool=False,**kwargs:Any)→PushInfoList
Push changes from source branch in refspec to target branch in refspec.
- Parameters:
refspec – See
fetch()
method.progress –
Can take one of many value types:
None
, to discard progress information.A function (callable) that is called with the progress information.Signature:
progress(op_code,cur_count,max_count=None,message='')
.SeeRemoteProgress.update
for adescription of all arguments given to the function.An instance of a class derived from
RemoteProgress
thatoverrides theRemoteProgress.update
method.
kill_after_timeout – To specify a timeout in seconds for the git command, after which the processshould be killed. It is set to
None
by default.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--receive-pack
.kwargs – Additional arguments to be passed togit-push(1).
- Note:
No further progress information is returned after push returns.
- Returns:
A
PushInfoList
object, where each list member represents anindividual 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
PushInfoList
will be 0.Call
raise_if_error()
on the returned object to raise onany failure.
- propertyrefs:IterableList[RemoteReference]
- Returns:
IterableList
ofRemoteReference
objects.It is prefixed, allowing you to omit the remote path portion, e.g.:
remote.refs.master# yields RemoteReference('/refs/remotes/origin/master')
- classmethodremove(repo:Repo,name:str)→str
Remove the remote with the given name.
- Returns:
The passed remote name to remove
- repo
- classmethodrm(repo:Repo,name:str)→str
Alias of remove.Remove the remote with the given name.
- Returns:
The passed remote name to remove
- set_url(new_url:str,old_url:str|None=None,allow_unsafe_protocols:bool=False,**kwargs:Any)→Remote
Configure URLs on current remote (cf. command
gitremoteset-url
).This command manages URLs on the remote.
- Parameters:
new_url – String being the URL to add as an extra remote URL.
old_url – When set, replaces this URL withnew_url for the remote.
allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.
- Returns:
self
- propertystale_refs:IterableList[Reference]
- Returns:
IterableList
ofRemoteReference
objects that do not have a corresponding head in the remote referenceanymore as they have been deleted on the remote side, but are stillavailable locally.The
IterableList
is prefixed, hence the ‘origin’ must beomitted. Seerefs
property for an example.To make things more complicated, it can be possible for the list to includeother kinds of references, for example, tag references, if these are staleas well. This is a fix for the issue described here:https://github.com/gitpython-developers/GitPython/issues/260
- unsafe_git_fetch_options=['--upload-pack']
- unsafe_git_pull_options=['--upload-pack']
- unsafe_git_push_options=['--receive-pack','--exec']
- update(**kwargs:Any)→Remote
Fetch all changes for this remote, including new branches which will beforced in (in case your local remote branch is not part the new remote branch’sancestry anymore).
- Parameters:
kwargs – Additional arguments passed to
gitremoteupdate
.- Returns:
self
- url:str
The URL configured for the remote.
- propertyurls:Iterator[str]
- Returns:
Iterator yielding all configured URL targets on a remote as strings
- classgit.remote.RemoteProgress
Handler providing an interface to parse progress information emitted bygit-push(1) andgit-fetch(1) and to dispatch callbacksallowing subclasses to react to the progress.
- BEGIN=1
- CHECKING_OUT=256
- COMPRESSING=8
- COUNTING=4
- DONE_TOKEN='done.'
- END=2
- FINDING_SOURCES=128
- OP_MASK=-4
- RECEIVING=32
- RESOLVING=64
- STAGE_MASK=3
- TOKEN_SEPARATOR=','
- WRITING=16
- __annotations__={'_cur_line':'Optional[str]','_num_op_codes':<class'int'>,'_seen_ops':'List[int]','error_lines':'List[str]','other_lines':'List[str]'}
- __init__()→None
- __module__='git.util'
- __slots__=('_cur_line','_seen_ops','error_lines','other_lines')
- error_lines:List[str]
- line_dropped(line:str)→None
Called whenever a line could not be understood and was therefore dropped.
- new_message_handler()→Callable[[str],None]
- Returns:
A progress handler suitable for
handle_process_output()
,passing lines on to this progress handler in a suitable format.
- other_lines:List[str]
- re_op_absolute=re.compile('(remote:)?([\\w\\s]+):\\s+()(\\d+)()(.*)')
- re_op_relative=re.compile('(remote:)?([\\w\\s]+):\\s+(\\d+)%\\((\\d+)/(\\d+)\\)(.*)')
- update(op_code:int,cur_count:str|float,max_count:str|float|None=None,message:str='')→None
Called whenever the progress changes.
- Parameters:
op_code –
Integer allowing to be compared against Operation IDs and stage IDs.
Stage IDs are
BEGIN
andEND
.BEGIN
will only beset once for each Operation ID as well asEND
. It may be thatBEGIN
andEND
are set at once in case only one progressmessage was emitted due to the speed of the operation. BetweenBEGIN
andEND
, none of these flags will be set.Operation IDs are all held within the
OP_MASK
. Only one OperationID 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 nomaximum number of items or if it is (yet) unknown.message – In case of the
WRITING
operation, it contains the amount of bytestransferred. It may possibly be used for other purposes as well.
- Note:
You may read the contents of the current line in
self._cur_line
.
Repo.Base
- classgit.repo.base.Repo(path:str|~os.PathLike[str]|None=None,odbt:~typing.Type[~gitdb.db.loose.LooseObjectDB]=<class'git.db.GitCmdObjectDB'>,search_parent_directories:bool=False,expand_vars:bool=True)
Represents a git repository and allows you to query references, create commitinformation, generate diffs, create and clone repositories, and query the log.
The following attributes are worth using:
working_dir
is the working directory of the git command, which is theworking tree directory if available or the.git
directory in case of barerepositories.working_tree_dir
is the working tree directory, but will returnNone
if we are a bare repository.git_dir
is the.git
repository directory, which is always set.
- DAEMON_EXPORT_FILE='git-daemon-export-ok'
- GitCommandWrapperType
Subclasses may easily bring in their own custom types by placing a constructor ortype here.
alias of
Git
- __annotations__={'_common_dir':'PathLike','_working_tree_dir':'Optional[PathLike]','config_level':'ConfigLevels_Tup','git_dir':'PathLike','working_dir':'PathLike'}
- __del__()→None
- __dict__=mappingproxy({'__module__':'git.repo.base','__annotations__':{'working_dir':'PathLike','_working_tree_dir':'Optional[PathLike]','git_dir':'PathLike','_common_dir':'PathLike','config_level':'ConfigLevels_Tup'},'__doc__':'Representsagitrepositoryandallowsyoutoqueryreferences,createcommit\n information,generatediffs,createandclonerepositories,andquerythelog.\n\n Thefollowingattributesareworthusing:\n\n *:attr:`working_dir`istheworkingdirectoryofthegitcommand,whichisthe\n workingtreedirectoryifavailableorthe``.git``directoryincaseofbare\n repositories.\n\n *:attr:`working_tree_dir`istheworkingtreedirectory,butwillreturn``None``\n ifweareabarerepository.\n\n *:attr:`git_dir`isthe``.git``repositorydirectory,whichisalwaysset.\n ','DAEMON_EXPORT_FILE':'git-daemon-export-ok','git':None,'_working_tree_dir':None,'_common_dir':'','re_whitespace':re.compile('\\s+'),'re_hexsha_only':re.compile('^[0-9A-Fa-f]{40}$'),'re_hexsha_shortened':re.compile('^[0-9A-Fa-f]{4,40}$'),'re_envvars':re.compile('(\\$(\\{\\s?)?[a-zA-Z_]\\w*(\\}\\s?)?|%\\s?[a-zA-Z_]\\w*\\s?%)'),'re_author_committer_start':re.compile('^(author|committer)'),'re_tab_full_line':re.compile('^\\t(.*)$'),'unsafe_git_clone_options':['--upload-pack','-u','--config','-c'],'config_level':('system','user','global','repository'),'GitCommandWrapperType':<class'git.cmd.Git'>,'__init__':<functionRepo.__init__>,'__enter__':<functionRepo.__enter__>,'__exit__':<functionRepo.__exit__>,'__del__':<functionRepo.__del__>,'close':<functionRepo.close>,'__eq__':<functionRepo.__eq__>,'__ne__':<functionRepo.__ne__>,'__hash__':<functionRepo.__hash__>,'description':<propertyobject>,'working_tree_dir':<propertyobject>,'common_dir':<propertyobject>,'bare':<propertyobject>,'heads':<propertyobject>,'branches':<propertyobject>,'references':<propertyobject>,'refs':<propertyobject>,'index':<propertyobject>,'head':<propertyobject>,'remotes':<propertyobject>,'remote':<functionRepo.remote>,'submodules':<propertyobject>,'submodule':<functionRepo.submodule>,'create_submodule':<functionRepo.create_submodule>,'iter_submodules':<functionRepo.iter_submodules>,'submodule_update':<functionRepo.submodule_update>,'tags':<propertyobject>,'tag':<functionRepo.tag>,'_to_full_tag_path':<staticmethod(<functionRepo._to_full_tag_path>)>,'create_head':<functionRepo.create_head>,'delete_head':<functionRepo.delete_head>,'create_tag':<functionRepo.create_tag>,'delete_tag':<functionRepo.delete_tag>,'create_remote':<functionRepo.create_remote>,'delete_remote':<functionRepo.delete_remote>,'_get_config_path':<functionRepo._get_config_path>,'config_reader':<functionRepo.config_reader>,'_config_reader':<functionRepo._config_reader>,'config_writer':<functionRepo.config_writer>,'commit':<functionRepo.commit>,'iter_trees':<functionRepo.iter_trees>,'tree':<functionRepo.tree>,'iter_commits':<functionRepo.iter_commits>,'merge_base':<functionRepo.merge_base>,'is_ancestor':<functionRepo.is_ancestor>,'is_valid_object':<functionRepo.is_valid_object>,'daemon_export':<propertyobject>,'_get_alternates':<functionRepo._get_alternates>,'_set_alternates':<functionRepo._set_alternates>,'alternates':<propertyobject>,'is_dirty':<functionRepo.is_dirty>,'untracked_files':<propertyobject>,'_get_untracked_files':<functionRepo._get_untracked_files>,'ignored':<functionRepo.ignored>,'active_branch':<propertyobject>,'blame_incremental':<functionRepo.blame_incremental>,'blame':<functionRepo.blame>,'init':<classmethod(<functionRepo.init>)>,'_clone':<classmethod(<functionRepo._clone>)>,'clone':<functionRepo.clone>,'clone_from':<classmethod(<functionRepo.clone_from>)>,'archive':<functionRepo.archive>,'has_separate_working_tree':<functionRepo.has_separate_working_tree>,'rev_parse':<functionrev_parse>,'__repr__':<functionRepo.__repr__>,'currently_rebasing_on':<functionRepo.currently_rebasing_on>,'__dict__':<attribute'__dict__'of'Repo'objects>,'__weakref__':<attribute'__weakref__'of'Repo'objects>})
- __eq__(rhs:object)→bool
Return self==value.
- __exit__(*args:Any)→None
- __hash__()→int
Return hash(self).
- __init__(path:str|~os.PathLike[str]|None=None,odbt:~typing.Type[~gitdb.db.loose.LooseObjectDB]=<class'git.db.GitCmdObjectDB'>,search_parent_directories:bool=False,expand_vars:bool=True)→None
Create a new
Repo
instance.- Parameters:
path –
The path to either the worktree directory or the .git directory itself:
repo=Repo("/Users/mtrier/Development/git-python")repo=Repo("/Users/mtrier/Development/git-python.git")repo=Repo("~/Development/git-python.git")repo=Repo("$REPOSITORIES/Development/git-python.git")repo=Repo(R"C:\Users\mtrier\Development\git-python\.git")
InCygwin,path may be a
cygdrive/...
prefixed path.Ifpath is
None
or an empty string,GIT_DIR
is used. Ifthat environment variable is absent or empty, the current directory isused.
odbt – Object DataBase type - a type which is constructed by providing thedirectory containing the database objects, i.e.
.git/objects
. It will beused to access all object data.search_parent_directories –
If
True
, all parent directories will be searched for a valid repo aswell.Please note that this was the default behaviour in older versions ofGitPython, which is considered a bug though.
- Raises:
- Returns:
- __module__='git.repo.base'
- __ne__(rhs:object)→bool
Return self!=value.
- __repr__()→str
Return repr(self).
- __weakref__
list of weak references to the object
- propertyactive_branch:Head
The name of the currently active branch.
- Raises:
TypeError – If HEAD is detached.
- Returns:
Head
to the active branch
- propertyalternates:List[str]
Retrieve a list of alternates paths or set a list paths to be used as alternates
- archive(ostream:TextIO|BinaryIO,treeish:str|None=None,prefix:str|None=None,**kwargs:Any)→Repo
Archive the tree at the given revision.
- Parameters:
ostream – File-compatible stream object to which the archive will be written as bytes.
treeish – The treeish name/id, defaults to active branch.
prefix – The optional prefix to prepend to each filename in the archive.
kwargs –
Additional arguments passed togit-archive(1):
Use the
format
argument to define the kind of format. Use specializedostreams to write any format supported by Python.You may specify the special
path
keyword, which may either be arepository-relative path to a directory or file to place into the archive,or a list or tuple of multiple paths.
- Raises:
git.exc.GitCommandError – If something went wrong.
- Returns:
self
- propertybare:bool
- Returns:
True
if the repository is bare
- blame(rev:str|HEAD|None,file:str,incremental:bool=False,rev_opts:List[str]|None=None,**kwargs:Any)→List[List[Commit|List[str|bytes]|None]]|Iterator[BlameEntry]|None
The blame information for the given file at the given revision.
- Parameters:
rev – Revision specifier. If
None
, the blame will include all the latestuncommitted changes. Otherwise, anything successfully parsed bygit-rev-parse(1) is a valid option.- Returns:
list: [git.Commit, list: [<line>]]
A list of lists associating a
Commit
objectwith a list of lines that changed within the given commit. TheCommit
objects will be given in order ofappearance.
- blame_incremental(rev:str|HEAD|None,file:str,**kwargs:Any)→Iterator[BlameEntry]
Iterator for blame information for the given file at the given revision.
Unlike
blame()
, this does not return the actual file’s contents, only astream ofBlameEntry
tuples.- Parameters:
rev – Revision specifier. If
None
, the blame will include all the latestuncommitted changes. Otherwise, anything successfully parsed bygit-rev-parse(1) is a valid option.- Returns:
Lazy iterator of
BlameEntry
tuples, where the commit indicates thecommit to blame for the line, and range indicates a span of line numbers inthe resulting file.
If you combine all line number ranges outputted by this command, you should geta continuous range spanning all line numbers in the file.
- propertybranches:IterableList[Head]
Alias for heads.A list of
Head
objects representing the branch headsin this repo.- Returns:
git.IterableList(Head,...)
- clone(path:str|PathLike[str],progress:Callable[[int,str|float,str|float|None,str],None]|None=None,multi_options:List[str]|None=None,allow_unsafe_protocols:bool=False,allow_unsafe_options:bool=False,**kwargs:Any)→Repo
Create a clone from this repository.
- Parameters:
path – The full path of the new repo (traditionally ends with
./<name>.git
).progress – See
Remote.push
.multi_options –
A list ofgit-clone(1) options that can be provided multipletimes.
One option per list item which is passed exactly as specified to clone.For example:
["--config core.filemode=false","--config core.ignorecase","--recurse-submodule=repo1_path","--recurse-submodule=repo2_path",]
allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.kwargs –
odbt
= ObjectDatabase Type, allowing to determine the object databaseimplementation used by the returnedRepo
instance.All remaining keyword arguments are given to thegit-clone(1)command.
- Returns:
Repo
(the newly cloned repo)
- classmethodclone_from(url:str|PathLike[str],to_path:str|PathLike[str],progress:Callable[[int,str|float,str|float|None,str],None]|None=None,env:Mapping[str,str]|None=None,multi_options:List[str]|None=None,allow_unsafe_protocols:bool=False,allow_unsafe_options:bool=False,**kwargs:Any)→Repo
Create a clone from the given URL.
- Parameters:
url – Valid git url, see:https://git-scm.com/docs/git-clone#URLS
to_path – Path to which the repository should be cloned to.
progress – See
Remote.push
.env –
Optional dictionary containing the desired environment variables.
Note: Provided variables will be used to update the execution environmentfor
git
. If some variable is not specified inenv and is defined inos.environ
, value fromos.environ
will be used. If you wantto unset some variable, consider providing empty string as its value.multi_options – See the
clone()
method.allow_unsafe_protocols – Allow unsafe protocols to be used, like
ext
.allow_unsafe_options – Allow unsafe options to be used, like
--upload-pack
.kwargs – See the
clone()
method.
- Returns:
Repo
instance pointing to the cloned directory.
- close()→None
- commit(rev:str|Commit_ish|None=None)→Commit
The
Commit
object for the specified revision.- Parameters:
rev – Revision specifier, seegit-rev-parse(1) for viable options.
- Returns:
- propertycommon_dir:str|PathLike[str]
- Returns:
The git dir that holds everything except possibly HEAD, FETCH_HEAD,ORIG_HEAD, COMMIT_EDITMSG, index, and logs/.
- config_level:Tuple[Literal['system'],Literal['user'],Literal['global'],Literal['repository']]=('system','user','global','repository')
Represents the configuration level of a configuration file.
- config_reader(config_level:Literal['system','global','user','repository']|None=None)→GitConfigParser
- Returns:
GitConfigParser
allowing to read the full gitconfiguration, but not to write it.The configuration will include values from the system, user and repositoryconfiguration files.
- Parameters:
config_level – For possible values, see the
config_writer()
method. IfNone
, allapplicable levels will be used. Specify a level in case you know which fileyou wish to read to prevent reading multiple files.- Note:
On Windows, system configuration cannot currently be read as the path isunknown, instead the global path will be used.
- config_writer(config_level:Literal['system','global','user','repository']='repository')→GitConfigParser
- Returns:
A
GitConfigParser
allowing to write values of thespecified configuration file level. Config writers should be retrieved, usedto change the configuration, and written right away as they will lock theconfiguration file in question and prevent other’s to write it.- Parameters:
config_level –
One of the following values:
"system"
= system wide configuration file"global"
= user level configuration file"`repository"
= configuration file for this repository only
- create_head(path:PathLike,commit:'SymbolicReference'|'str'='HEAD',force:bool=False,logmsg:str|None=None)→Head
Create a new head within the repository.
- Note:
For more documentation, please see the
Head.create
method.- Returns:
Newly created
Head
Reference.
- create_remote(name:str,url:str,**kwargs:Any)→Remote
Create a new remote.
For more information, please see the documentation of the
Remote.create
method.- Returns:
Remote
reference
- create_submodule(*args:Any,**kwargs:Any)→Submodule
Create a new submodule.
- Note:
For a description of the applicable parameters, see the documentation of
Submodule.add
.- Returns:
The created submodule.
- create_tag(path:PathLike,ref:str|'SymbolicReference'='HEAD',message:str|None=None,force:bool=False,**kwargs:Any)→TagReference
Create a new tag reference.
- Note:
For more documentation, please see the
TagReference.create
method.- Returns:
TagReference
object
- currently_rebasing_on()→Commit|None
- Returns:
The commit which is currently being replayed while rebasing.
None
if we are not currently rebasing.
- propertydaemon_export:bool
If True, git-daemon may export this repository
- delete_head(*heads:str|Head,**kwargs:Any)→None
Delete the given heads.
- Parameters:
kwargs – Additional keyword arguments to be passed togit-branch(1).
- delete_tag(*tags:TagReference)→None
Delete the given tag references.
- propertydescription:str
the project’s description
- git=None
- git_dir:str|PathLike[str]
The
.git
repository directory.
- has_separate_working_tree()→bool
- Returns:
True if our
git_dir
is not at the root of ourworking_tree_dir
, but a.git
file with a platform-agnosticsymbolic link. Ourgit_dir
will be wherever the.git
file pointsto.- Note:
Bare repositories will always return
False
here.
- propertyheads:IterableList[Head]
A list of
Head
objects representing the branch headsin this repo.- Returns:
git.IterableList(Head,...)
- ignored(*paths:str|PathLike[str])→List[str]
Checks if paths are ignored via
.gitignore
.This does so using thegit-check-ignore(1) method.
- Parameters:
paths – List of paths to check whether they are ignored or not.
- Returns:
Subset of those paths which are ignored
- classmethodinit(path:str|~os.PathLike[str]|None=None,mkdir:bool=True,odbt:~typing.Type[~git.db.GitCmdObjectDB]=<class'git.db.GitCmdObjectDB'>,expand_vars:bool=True,**kwargs:~typing.Any)→Repo
Initialize a git repository at the given path if specified.
- Parameters:
path – The full path to the repo (traditionally ends with
/<name>.git
). OrNone
, in which case the repository will be created in the currentworking directory.mkdir – If specified, will create the repository directory if it doesn’t alreadyexist. Creates the directory with a mode=0755.Only effective if a path is explicitly given.
odbt – Object DataBase type - a type which is constructed by providing thedirectory containing the database objects, i.e.
.git/objects
. It will beused to access all object data.expand_vars – If specified, environment variables will not be escaped. This can lead toinformation disclosure, allowing attackers to access the contents ofenvironment variables.
kwargs – Keyword arguments serving as additional options to thegit-init(1) command.
- Returns:
Repo
(the newly created repo)
- is_ancestor(ancestor_rev:Commit,rev:Commit)→bool
Check if a commit is an ancestor of another.
- Parameters:
ancestor_rev – Rev which should be an ancestor.
rev – Rev to test againstancestor_rev.
- Returns:
True
ifancestor_rev is an ancestor torev.
- is_dirty(index:bool=True,working_tree:bool=True,untracked_files:bool=False,submodules:bool=True,path:str|PathLike[str]|None=None)→bool
- Returns:
True
if the repository is considered dirty. By default it will reactlike agit-status(1) without untracked files, hence it is dirtyif the index or the working copy have changes.
- is_valid_object(sha:str,object_type:str|None=None)→bool
- iter_commits(rev:str|Commit|'SymbolicReference'|None=None,paths:PathLike|Sequence[PathLike]='',**kwargs:Any)→Iterator[Commit]
An iterator of
Commit
objects representing thehistory of a given ref/commit.- Parameters:
rev – Revision specifier, seegit-rev-parse(1) for viable options.If
None
, the active branch will be used.paths – An optional path or a list of paths. If set, only commits that include thepath or paths will be returned.
kwargs – Arguments to be passed togit-rev-list(1).Common ones are
max_count
andskip
.
- Note:
To receive only commits between two named revisions, use the
"revA...revB"
revision specifier.- Returns:
Iterator of
Commit
objects
- iter_submodules(*args:Any,**kwargs:Any)→Iterator[Submodule]
An iterator yielding Submodule instances.
See the~git.objects.util.Traversable interface for a description ofargsandkwargs.
- Returns:
Iterator
- iter_trees(*args:Any,**kwargs:Any)→Iterator['Tree']
- Returns:
Iterator yielding
Tree
objects- Note:
Accepts all arguments known to the
iter_commits()
method.
- merge_base(*rev:Any,**kwargs:Any)→List[Commit]
Find the closest common ancestor for the given revision(
Commit
s,Tag
s,Reference
s, etc.).- Parameters:
rev – At least two revs to find the common ancestor for.
kwargs – Additional arguments to be passed to the
repo.git.merge_base()
commandwhich does all the work.
- Returns:
A list of
Commit
objects. If--all
wasnot passed as a keyword argument, the list will have at max oneCommit
, or is empty if no common merge baseexists.- Raises:
ValueError – If fewer than two revisions are provided.
- re_author_committer_start=re.compile('^(author|committer)')
- re_envvars=re.compile('(\\$(\\{\\s?)?[a-zA-Z_]\\w*(\\}\\s?)?|%\\s?[a-zA-Z_]\\w*\\s?%)')
- re_hexsha_only=re.compile('^[0-9A-Fa-f]{40}$')
- re_hexsha_shortened=re.compile('^[0-9A-Fa-f]{4,40}$')
- re_tab_full_line=re.compile('^\\t(.*)$')
- re_whitespace=re.compile('\\s+')
- propertyreferences:IterableList[Reference]
A list of
Reference
objects representing tags,heads and remote references.- Returns:
git.IterableList(Reference,...)
- propertyrefs:IterableList[Reference]
Alias for references.A list of
Reference
objects representing tags,heads and remote references.- Returns:
git.IterableList(Reference,...)
- remote(name:str='origin')→Remote
- Returns:
The remote with the specified name
- Raises:
ValueError – If no remote with such a name exists.
- propertyremotes:IterableList[Remote]
A list of
Remote
objects allowing to access andmanipulate remotes.- Returns:
git.IterableList(Remote,...)
- rev_parse(rev:str)→AnyGitObject
Parse a revision string. Likegit-rev-parse(1).
- Returns:
~git.objects.base.Object at the given revision.
This may be any type of git object:
- Parameters:
rev –git-rev-parse(1)-compatible revision specification as string.Please seegit-rev-parse(1) for details.
- Raises:
gitdb.exc.BadObject – If the given revision could not be found.
ValueError – Ifrev couldn’t be parsed.
IndexError – If an invalid reflog index is specified.
- submodule(name:str)→Submodule
- Returns:
The submodule with the given name
- Raises:
ValueError – If no such submodule exists.
- submodule_update(*args:Any,**kwargs:Any)→Iterator[Submodule]
Update the submodules, keeping the repository consistent as it willtake the previous state into consideration.
- Note:
For more information, please see the documentation of
RootModule.update
.
- propertysubmodules:IterableList[Submodule]
- Returns:
git.IterableList(Submodule, …) of direct submodules available from thecurrent head
- tag(path:str|PathLike[str])→TagReference
- Returns:
TagReference
object, reference pointing to aCommit
or tag- Parameters:
path – Path to the tag reference, e.g.
0.1.5
ortags/0.1.5
.
- propertytags:IterableList[TagReference]
A list of
TagReference
objects that are available inthis repo.- Returns:
git.IterableList(TagReference,...)
- tree(rev:Tree_ish|str|None=None)→Tree
The
Tree
object for the given tree-ish revision.Examples:
repo.tree(repo.heads[0])
- Parameters:
rev – A revision pointing to a Treeish (being a commit or tree).
- Returns:
- 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 andsubsequent operations might have unexpected results.
- unsafe_git_clone_options=['--upload-pack','-u','--config','-c']
Options togit-clone(1) that allow arbitrary commands to be executed.
The
--upload-pack
/-u
option allows users to execute arbitrary commandsdirectly:https://git-scm.com/docs/git-clone#Documentation/git-clone.txt—upload-packltupload-packgtThe
--config
/-c
option allows users to override configuration variables likeprotocol.allow
andcore.gitProxy
to execute arbitrary commands:https://git-scm.com/docs/git-clone#Documentation/git-clone.txt—configltkeygtltvaluegt
- propertyuntracked_files:List[str]
- Returns:
list(str,…)
Files currently untracked as they have not been staged yet. Paths arerelative to the current working directory of the git command.
- Note:
Ignored files will not appear here, i.e. files mentioned in
.gitignore
.- Note:
This property is expensive, as no cache is involved. To process the result,please consider caching it yourself.
- working_dir:str|PathLike[str]
The working directory of the git command.
- propertyworking_tree_dir:str|PathLike[str]|None
- Returns:
The working tree directory of our git repository.If this is a bare repository,
None
is returned.
Repo.Functions
General repository-related functions.
- git.repo.fun.deref_tag(tag:Tag)→AnyGitObject
Recursively dereference a tag and return the resulting object.
- git.repo.fun.find_submodule_git_dir(d:str|PathLike[str])→str|PathLike[str]|None
Search for a submodule repo.
- git.repo.fun.find_worktree_git_dir(dotgit:str|PathLike[str])→str|None
Search for a gitdir for this worktree.
- git.repo.fun.is_git_dir(d:str|PathLike[str])→bool
This is taken from the git setup.c:is_git_directory function.
- Raises:
git.exc.WorkTreeRepositoryUnsupported – If it sees a worktree directory. It’s quite hacky to do that here, but at leastclearly indicates that we don’t support it. There is the unlikely danger tothrow if we see directories which just look like a worktree dir, but are none.
- git.repo.fun.name_to_object(repo:Repo,name:str,return_ref:Literal[False]=False)→AnyGitObject
- git.repo.fun.name_to_object(repo:Repo,name:str,return_ref:Literal[True])→AnyGitObject|SymbolicReference
- git.repo.fun.rev_parse(repo:Repo,rev:str)→AnyGitObject
Parse a revision string. Likegit-rev-parse(1).
- Returns:
~git.objects.base.Object at the given revision.
This may be any type of git object:
- Parameters:
rev –git-rev-parse(1)-compatible revision specification as string.Please seegit-rev-parse(1) for details.
- Raises:
gitdb.exc.BadObject – If the given revision could not be found.
ValueError – Ifrev couldn’t be parsed.
IndexError – If an invalid reflog index is specified.
- git.repo.fun.short_to_long(odb:GitCmdObjectDB,hexsha:str)→bytes|None
- Returns:
Long hexadecimal sha1 from the given less than 40 byte hexsha, or
None
if nocandidate could be found.- Parameters:
hexsha – hexsha with less than 40 bytes.
- git.repo.fun.to_commit(obj:Object)→Commit
Convert the given object to a commit if possible and return it.
- git.repo.fun.touch(filename:str)→str
Compat
Utilities to help provide compatibility with Python 3.
This module exists for historical reasons. Code outside GitPython may make use of publicmembers of this module, but is unlikely to benefit from doing so. GitPython continues touse some of these utilities, in some cases for compatibility across different platforms.
- git.compat.__dir__()→List[str]
- git.compat.__getattr__(name:str)→Any
- git.compat.defenc='utf-8'
The encoding used to convert between Unicode and bytes filenames.
- git.compat.is_darwin:bool=False
Deprecated alias for
sys.platform=="darwin"
to check for macOS (Darwin).This is deprecated because it clearer to write out
os.name
orsys.platform
checks explicitly.- Note:
For macOS (Darwin),
os.name=="posix"
as in other Unix-like systems, whilesys.platform=="darwin"
.
- git.compat.is_posix:bool=True
Deprecated alias for
os.name=="posix"
to check for Unix-like (“POSIX”) systems.This is deprecated because it clearer to write out
os.name
orsys.platform
checks explicitly, especially in cases where it matters which isused.- Note:
For POSIX systems, more detailed information is available in
sys.platform
,whileos.name
is always"posix"
on such systems, including macOS(Darwin).
- git.compat.is_win:bool=False
Deprecated alias for
os.name=="nt"
to check for native Windows.This is deprecated because it is clearer to write out
os.name
orsys.platform
checks explicitly, especially in cases where it matters which isused.- Note:
is_win
isFalse
on Cygwin, but is often wrongly assumedTrue
. To detectCygwin, usesys.platform=="cygwin"
.
- git.compat.safe_decode(s:None)→None
- git.compat.safe_decode(s:AnyStr)→str
Safely decode a binary string to Unicode.
- git.compat.safe_encode(s:None)→None
- git.compat.safe_encode(s:AnyStr)→bytes
Safely encode a binary string to Unicode.
- git.compat.win_encode(s:None)→None
- git.compat.win_encode(s:AnyStr)→bytes
Encode Unicode strings for process arguments on Windows.
DB
Module with our own gitdb implementation - it uses the git command.
- classgit.db.GitCmdObjectDB(root_path:str|os.PathLike[str],git:Git)
A database representing the default git object store, which includes looseobjects, pack files and an alternates file.
It will create objects only in the loose object database.
- __init__(root_path:str|os.PathLike[str],git:Git)→None
Initialize this instance with the root and a git command.
- __module__='git.db'
- info(binsha:bytes)→OInfo
Get a git object header (using git itself).
- partial_to_complete_sha_hex(partial_hexsha:str)→bytes
- Returns:
Full binary 20 byte sha from the given partial hexsha
- Raises:
- Note:
Currently we only raise
BadObject
as git does notcommunicate ambiguous objects separately.
- stream(binsha:bytes)→OStream
Get git object data as a stream supporting
read()
(using git itself).
- classgit.db.GitDB(root_path)
A git-style object database, which contains all objects in the ‘objects’subdirectory
IMPORTANT
: The usage of this implementation is highly discouraged as it fails to release file-handles.This can be a problem with long-running processes and/or big repositories.- LooseDBCls
alias of
LooseObjectDB
- PackDBCls
alias of
PackedDB
- ReferenceDBCls
alias of
ReferenceDB
- __annotations__={}
- __init__(root_path)
Initialize ourselves on a git objects directory
- __module__='gitdb.db.git'
- alternates_dir='info/alternates'
- loose_dir=''
- ostream()
Return the output stream
- Returns:
overridden output stream this instance will write to, or Noneif it will write to the default stream
- packs_dir='pack'
- set_ostream(ostream)
Adjusts the stream to which all data should be sent when storing new objects
- Parameters:
stream – if not None, the stream to use, if None the default streamwill be used.
- Returns:
previously installed stream, or None if there was no override
- Raises:
TypeError – if the stream doesn’t have the supported functionality
- store(istream)
Create a new object in the database:return: the input istream object with its sha set to its corresponding value
- Parameters:
istream – IStream compatible instance. If its sha is already setto a value, the object will just be stored in the our database format,in which case the input stream is expected to be in object format ( header + contents ).
- Raises:
IOError – if data could not be written
Types
- git.types.AnyGitObject
Union of the
Object
-based types that represent actual gitobject types.As noted in
Object
, which has further details, these are:Those GitPython classes represent the four git object types, pergitglossary(7):
“tree object”:https://git-scm.com/docs/gitglossary#def_tree_object
“commit object”:https://git-scm.com/docs/gitglossary#def_commit_object
“tag object”:https://git-scm.com/docs/gitglossary#def_tag_object
For more general information on git objects and their types as git understands them:
“object type”:https://git-scm.com/docs/gitglossary#def_object_type
- Note:
See also the
Tree_ish
andCommit_ish
unions.
alias of
Union
[Commit
,Tree
,TagObject
,Blob
]
- git.types.CallableProgress
General type of a function or other callable used as a progress reporter for cloning.
This is the type of a function or other callable that reports the progress of a clone,when passed as a
progress
argument toRepo.clone
orRepo.clone_from
.- Note:
Those
clone()
andclone_from()
methods also acceptRemoteProgress()
instances, including instancesof itsCallableRemoteProgress()
subclass.- Note:
Unlike objects that match this type,
RemoteProgress()
instances arenot directly callable, not even when they are instances ofCallableRemoteProgress()
, which wraps a callable and forwardsinformation to it but is not itself callable.- Note:
This type also allows
None
, for cloning without reporting progress.
alias of
Optional
[Callable
[[int
,Union
[str
,float
],Optional
[Union
[str
,float
]],str
],None
]]
- git.types.Commit_ish
Union of
Object
-based types that are typically commit-ish.Seegitglossary(7) on “commit-ish”:https://git-scm.com/docs/gitglossary#def_commit-ish
- Note:
Commit
is the only class whose instances are allcommit-ish. This union type includesCommit
, but alsoTagObject
, onlymost of whose instances arecommit-ish. Whether a particularTagObject
peels(recursively dereferences) to a commit, rather than a tree or blob, can in generalonly be known at runtime. In practice, git tag objects are nearly always used fortagging commits, and such tags are of course commit-ish.- Note:
See also the
AnyGitObject
union of all four classes corresponding to gitobject types.
alias of
Union
[Commit
,TagObject
]
- git.types.ConfigLevels_Tup
Static type of a tuple of the four strings representing configuration levels.
alias of
Tuple
[Literal
[‘system’],Literal
[‘user’],Literal
[‘global’],Literal
[‘repository’]]
- classgit.types.Files_TD
Dictionary with stat counts for the diff of a particular file.
For the
files
attribute ofStats
objects.- __annotations__={'change_type':<class'str'>,'deletions':<class'int'>,'insertions':<class'int'>,'lines':<class'int'>}
- __dict__=mappingproxy({'__module__':'git.types','__annotations__':{'insertions':<class'int'>,'deletions':<class'int'>,'lines':<class'int'>,'change_type':<class'str'>},'__doc__':'Dictionarywithstatcountsforthediffofaparticularfile.\n\n Forthe:class:`~git.util.Stats.files`attributeof:class:`~git.util.Stats`\n objects.\n ','__orig_bases__':(<functionTypedDict>,),'__dict__':<attribute'__dict__'of'Files_TD'objects>,'__weakref__':<attribute'__weakref__'of'Files_TD'objects>,'__required_keys__':frozenset({'insertions','change_type','lines','deletions'}),'__optional_keys__':frozenset(),'__total__':True})
- __module__='git.types'
- __optional_keys__=frozenset({})
- __orig_bases__=(<functionTypedDict>,)
- __required_keys__=frozenset({'change_type','deletions','insertions','lines'})
- __total__=True
- __weakref__
list of weak references to the object
- change_type:str
- deletions:int
- insertions:int
- lines:int
- git.types.GitObjectTypeString
Literal strings identifying git object types and the
Object
-based types that represent them.See the
Object.type
attribute. These are itsvalues inObject
subclasses that represent git objects. Theseliterals therefore correspond to the types in theAnyGitObject
union.These are the same strings git itself uses to identify its four object types.Seegitglossary(7) on “object type”:https://git-scm.com/docs/gitglossary#def_object_type
alias of
Literal
[‘commit’, ‘tag’, ‘blob’, ‘tree’]
- classgit.types.HSH_TD
Dictionary carrying the same information as a
Stats
object.- __annotations__={'files':typing.Dict[typing.Union[str,ForwardRef('os.PathLike[str]')],git.types.Files_TD],'total':<class'git.types.Total_TD'>}
- __dict__=mappingproxy({'__module__':'git.types','__annotations__':{'total':<class'git.types.Total_TD'>,'files':typing.Dict[typing.Union[str,ForwardRef('os.PathLike[str]')],git.types.Files_TD]},'__doc__':'Dictionarycarryingthesameinformationasa:class:`~git.util.Stats`object.','__orig_bases__':(<functionTypedDict>,),'__dict__':<attribute'__dict__'of'HSH_TD'objects>,'__weakref__':<attribute'__weakref__'of'HSH_TD'objects>,'__required_keys__':frozenset({'total','files'}),'__optional_keys__':frozenset(),'__total__':True})
- __module__='git.types'
- __optional_keys__=frozenset({})
- __orig_bases__=(<functionTypedDict>,)
- __required_keys__=frozenset({'files','total'})
- __total__=True
- __weakref__
list of weak references to the object
- classgit.types.Has_Repo(*args,**kwargs)
Protocol for having a
repo
attribute, the repository to operate on.- __abstractmethods__=frozenset({})
- __annotations__={'repo':'Repo'}
- __dict__=mappingproxy({'__module__':'git.types','__annotations__':{'repo':'Repo'},'__doc__':'Protocolforhavinga:attr:`repo`attribute,therepositorytooperateon.','__dict__':<attribute'__dict__'of'Has_Repo'objects>,'__weakref__':<attribute'__weakref__'of'Has_Repo'objects>,'__parameters__':(),'_is_protocol':True,'__subclasshook__':<classmethod(<function_proto_hook>)>,'__init__':<function_no_init_or_replace_init>,'__abstractmethods__':frozenset(),'_abc_impl':<_abc._abc_dataobject>,'__protocol_attrs__':{'repo'},'_is_runtime_protocol':True,'__non_callable_proto_members__':{'repo'}})
- __init__(*args,**kwargs)
- __module__='git.types'
- __non_callable_proto_members__={'repo'}
- __parameters__=()
- __protocol_attrs__={'repo'}
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- __weakref__
list of weak references to the object
- classgit.types.Has_id_attribute(*args,**kwargs)
Protocol for having
_id_attribute_
used in iteration and traversal.- __abstractmethods__=frozenset({})
- __annotations__={'_id_attribute_':<class'str'>}
- __dict__=mappingproxy({'__module__':'git.types','__annotations__':{'_id_attribute_':<class'str'>},'__doc__':'Protocolforhaving:attr:`_id_attribute_`usediniterationandtraversal.','__dict__':<attribute'__dict__'of'Has_id_attribute'objects>,'__weakref__':<attribute'__weakref__'of'Has_id_attribute'objects>,'__parameters__':(),'_is_protocol':True,'__subclasshook__':<classmethod(<function_proto_hook>)>,'__init__':<function_no_init_or_replace_init>,'__abstractmethods__':frozenset(),'_abc_impl':<_abc._abc_dataobject>,'__protocol_attrs__':{'_id_attribute_'},'_is_runtime_protocol':True,'__non_callable_proto_members__':{'_id_attribute_'}})
- __init__(*args,**kwargs)
- __module__='git.types'
- __non_callable_proto_members__={'_id_attribute_'}
- __parameters__=()
- __protocol_attrs__={'_id_attribute_'}
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- __weakref__
list of weak references to the object
- git.types.Lit_commit_ish
Deprecated. Type of literal strings identifying typically-commitish git object types.
Prior to a bugfix, this type had been defined more broadly. Any usage is in practiceambiguous and likely to be incorrect. This type has therefore been made a static typeerror to appear in annotations. It is preserved, with a deprecated status, to avoidintroducing runtime errors in code that refers to it, but it should not be used.
Instead of this type:
For the type of the string literals associated with
Commit_ish
, useLiteral["commit","tag"]
or create a new type alias for it. That is equivalent tothis type as currently defined (but usable in statically checked type annotations).For the type of all four string literals associated with
AnyGitObject
, useGitObjectTypeString
. That is equivalent to the old definition of this typeprior to the bugfix (and is also usable in statically checked type annotations).
alias of
Literal
[‘commit’, ‘tag’]
- git.types.Lit_config_levels
Type of literal strings naming git configuration levels.
These strings relate to which file a git configuration variable is in.
alias of
Literal
[‘system’, ‘global’, ‘user’, ‘repository’]
- git.types.PathLike
A
str
(Unicode) based file or directory path.alias of
Union
[str
,os.PathLike[str]
]
- git.types.TBD
Alias of
Any
, when a type hint is meant to become more specific.
- classgit.types.Total_TD
Dictionary with total stats from any number of files.
For the
total
attribute ofStats
objects.- __annotations__={'deletions':<class'int'>,'files':<class'int'>,'insertions':<class'int'>,'lines':<class'int'>}
- __dict__=mappingproxy({'__module__':'git.types','__annotations__':{'insertions':<class'int'>,'deletions':<class'int'>,'lines':<class'int'>,'files':<class'int'>},'__doc__':'Dictionarywithtotalstatsfromanynumberoffiles.\n\n Forthe:class:`~git.util.Stats.total`attributeof:class:`~git.util.Stats`\n objects.\n ','__orig_bases__':(<functionTypedDict>,),'__dict__':<attribute'__dict__'of'Total_TD'objects>,'__weakref__':<attribute'__weakref__'of'Total_TD'objects>,'__required_keys__':frozenset({'insertions','lines','files','deletions'}),'__optional_keys__':frozenset(),'__total__':True})
- __module__='git.types'
- __optional_keys__=frozenset({})
- __orig_bases__=(<functionTypedDict>,)
- __required_keys__=frozenset({'deletions','files','insertions','lines'})
- __total__=True
- __weakref__
list of weak references to the object
- deletions:int
- files:int
- insertions:int
- lines:int
- git.types.Tree_ish
Union of
Object
-based types that are typically tree-ish.Seegitglossary(7) on “tree-ish”:https://git-scm.com/docs/gitglossary#def_tree-ish
- Note:
Tree
andCommit
are theclasses whose instances are all tree-ish. This union includes them, but alsoTagObject
, onlymost of whose instances are tree-ish.Whether a particularTagObject
peels (recursivelydereferences) to a tree or commit, rather than a blob, can in general only be knownat runtime. In practice, git tag objects are nearly always used for tagging commits,and such tags are tree-ish because commits are tree-ish.- Note:
See also the
AnyGitObject
union of all four classes corresponding to gitobject types.
alias of
Union
[Commit
,Tree
,TagObject
]
- git.types.__dir__()→List[str]
- git.types.__getattr__(name:str)→Any
- git.types.assert_never(inp:NoReturn,raise_error:bool=True,exc:Exception|None=None)→None
For use in exhaustive checking of a literal or enum in if/else chains.
A call to this function should only be reached if not all members are handled, or ifan attempt is made to pass non-members through the chain.
- Parameters:
inp – If all members are handled, the argument forinp will have the
Never
/NoReturn
type.Otherwise, the type will mismatch and cause a mypy error.raise_error – If
True
, will also raiseValueError
with a general“unhandled literal” message, or the exception object passed asexc.exc – It not
None
, this should be an already-constructed exception object, to beraised ifraise_error isTrue
.
Util
- classgit.util.Actor(name:str|None,email:str|None)
Actors hold information about a person acting on the repository. They can becommitters and authors or anything with a name and an email as mentioned in the gitlog entries.
- __annotations__={}
- __eq__(other:Any)→bool
Return self==value.
- __hash__()→int
Return hash(self).
- __init__(name:str|None,email:str|None)→None
- __module__='git.util'
- __ne__(other:Any)→bool
Return self!=value.
- __repr__()→str
Return repr(self).
- __slots__=('name','email')
- __str__()→str
Return str(self).
- classmethodauthor(config_reader:None|GitConfigParser|SectionConstraint=None)→Actor
Same as
committer()
, but defines the main author. It may be specifiedin the environment, but defaults to the committer.
- classmethodcommitter(config_reader:None|GitConfigParser|SectionConstraint=None)→Actor
- Returns:
Actor
instance corresponding to the configured committer. Itbehaves similar to the git implementation, such that the environment willoverride configuration values ofconfig_reader. If no value is set at all,it will be generated.- Parameters:
config_reader – ConfigReader to use to retrieve the values from in case they are not set inthe environment.
- conf_email='email'
- conf_name='name'
- email
- env_author_email='GIT_AUTHOR_EMAIL'
- env_author_name='GIT_AUTHOR_NAME'
- env_committer_email='GIT_COMMITTER_EMAIL'
- env_committer_name='GIT_COMMITTER_NAME'
- name
- name_email_regex=re.compile('(.*)<(.*?)>')
- name_only_regex=re.compile('<(.*)>')
- classgit.util.BlockingLockFile(file_path:str|PathLike[str],check_interval_s:float=0.3,max_block_time_s:int=9223372036854775807)
The lock file will block until a lock could be obtained, or fail after aspecified timeout.
- Note:
If the directory containing the lock was removed, an exception will be raisedduring the blocking period, preventing hangs as the lock can never be obtained.
- __init__(file_path:str|PathLike[str],check_interval_s:float=0.3,max_block_time_s:int=9223372036854775807)→None
Configure the instance.
- Parameters:
check_interval_s – Period of time to sleep until the lock is checked the next time.By default, it waits a nearly unlimited time.
max_block_time_s – Maximum amount of seconds we may lock.
- __module__='git.util'
- __slots__=('_check_interval','_max_block_time')
- classgit.util.CallableRemoteProgress(fn:Callable)
A
RemoteProgress
implementation forwarding updates to any callable.- Note:
Like direct instances of
RemoteProgress
, instances of thisCallableRemoteProgress
class are not themselves directly callable.Rather, instances of this class wrap a callable and forward to it. This shouldtherefore not be confused withgit.types.CallableProgress
.
- __annotations__={}
- __init__(fn:Callable)→None
- __module__='git.util'
- __slots__=('_callable',)
- update(*args:Any,**kwargs:Any)→None
Called whenever the progress changes.
- Parameters:
op_code –
Integer allowing to be compared against Operation IDs and stage IDs.
Stage IDs are
BEGIN
andEND
.BEGIN
will only beset once for each Operation ID as well asEND
. It may be thatBEGIN
andEND
are set at once in case only one progressmessage was emitted due to the speed of the operation. BetweenBEGIN
andEND
, none of these flags will be set.Operation IDs are all held within the
OP_MASK
. Only one OperationID 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 nomaximum number of items or if it is (yet) unknown.message – In case of the
WRITING
operation, it contains the amount of bytestransferred. It may possibly be used for other purposes as well.
- Note:
You may read the contents of the current line in
self._cur_line
.
- git.util.HIDE_WINDOWS_KNOWN_ERRORS=False
We need an easy way to see if Appveyor TCs start failing,so the errors marked with this var are considered “acknowledged” ones, awaiting remedy,till then, we wish to hide them.
- classgit.util.IndexFileSHA1Writer(f:IO)
Wrapper around a file-like object that remembers the SHA1 of the data written toit. It will write a sha when the stream is closed or if asked for explicitly using
write_sha()
.Only useful to the index file.
- Note:
Based on the dulwich project.
- __init__(f:IO)→None
- __module__='git.util'
- __slots__=('f','sha1')
- close()→bytes
- f
- sha1
- tell()→int
- write(data:AnyStr)→int
- write_sha()→bytes
- classgit.util.IterableList(id_attr:str,prefix:str='')
List of iterable objects allowing to query an object by id or by named index:
heads=repo.headsheads.masterheads['master']heads[0]
Iterable parent objects:
Iterable via inheritance:
This requires an
id_attribute
name to be set which will be queried from itscontained items to have a means for comparison.A prefix can be specified which is to be used in case the id returned by the itemsalways contains a prefix that does not matter to the user, so it can be left out.
- __annotations__={}
- __contains__(attr:object)→bool
Return bool(key in self).
- __delitem__(index:SupportsIndex|int|slice|str)→None
Delete self[key].
- __getattr__(attr:str)→T_IterableObj
- __getitem__(index:SupportsIndex|int|slice|str)→T_IterableObj
Return self[index].
- __init__(id_attr:str,prefix:str='')→None
- __module__='git.util'
- static__new__(cls,id_attr:str,prefix:str='')→IterableList[T_IterableObj]
- __orig_bases__=(typing.List[+T_IterableObj],)
- __parameters__=(+T_IterableObj,)
- __slots__=('_id_attr','_prefix')
- classgit.util.IterableObj(*args,**kwargs)
Defines an interface for iterable items, so there is a uniform way to retrieveand iterate items within the git repository.
Subclasses:
- __abstractmethods__=frozenset({'iter_items'})
- __annotations__={'_id_attribute_':<class'str'>}
- __init__(*args,**kwargs)
- __module__='git.util'
- __non_callable_proto_members__={'_id_attribute_'}
- __parameters__=()
- __protocol_attrs__={'_id_attribute_','iter_items','list_items'}
- __slots__=()
- classmethod__subclasshook__(other)
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().It should return True, False or NotImplemented. If it returnsNotImplemented, the normal algorithm is used. Otherwise, itoverrides the normal algorithm (and the outcome is cached).
- abstractclassmethoditer_items(repo:Repo,*args:Any,**kwargs:Any)→Iterator[T_IterableObj]
Find (all) items of this type.
Subclasses can specifyargs andkwargs differently, and may use them forfiltering. However, when the method is called with no additional positional orkeyword arguments, subclasses are obliged to to yield all items.
- Returns:
Iterator yielding Items
- classmethodlist_items(repo:Repo,*args:Any,**kwargs:Any)→IterableList[T_IterableObj]
Find (all) items of this type and collect them into a list.
For more information about the arguments, see
iter_items()
.- Note:
Favor the
iter_items()
method as it will avoid eagerly collecting allitems. When there are many items, that can slow performance and increasememory usage.- Returns:
list(Item,…) list of item instances
- classgit.util.LockFile(file_path:str|PathLike[str])
Provides methods to obtain, check for, and release a file based lock whichshould 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.
- __annotations__={}
- __del__()→None
- __init__(file_path:str|PathLike[str])→None
- __module__='git.util'
- __slots__=('_file_path','_owns_lock')
- classgit.util.RemoteProgress
Handler providing an interface to parse progress information emitted bygit-push(1) andgit-fetch(1) and to dispatch callbacksallowing subclasses to react to the progress.
- BEGIN=1
- CHECKING_OUT=256
- COMPRESSING=8
- COUNTING=4
- DONE_TOKEN='done.'
- END=2
- FINDING_SOURCES=128
- OP_MASK=-4
- RECEIVING=32
- RESOLVING=64
- STAGE_MASK=3
- TOKEN_SEPARATOR=','
- WRITING=16
- __annotations__={'_cur_line':'Optional[str]','_num_op_codes':<class'int'>,'_seen_ops':'List[int]','error_lines':'List[str]','other_lines':'List[str]'}
- __init__()→None
- __module__='git.util'
- __slots__=('_cur_line','_seen_ops','error_lines','other_lines')
- error_lines:List[str]
- line_dropped(line:str)→None
Called whenever a line could not be understood and was therefore dropped.
- new_message_handler()→Callable[[str],None]
- Returns:
A progress handler suitable for
handle_process_output()
,passing lines on to this progress handler in a suitable format.
- other_lines:List[str]
- re_op_absolute=re.compile('(remote:)?([\\w\\s]+):\\s+()(\\d+)()(.*)')
- re_op_relative=re.compile('(remote:)?([\\w\\s]+):\\s+(\\d+)%\\((\\d+)/(\\d+)\\)(.*)')
- update(op_code:int,cur_count:str|float,max_count:str|float|None=None,message:str='')→None
Called whenever the progress changes.
- Parameters:
op_code –
Integer allowing to be compared against Operation IDs and stage IDs.
Stage IDs are
BEGIN
andEND
.BEGIN
will only beset once for each Operation ID as well asEND
. It may be thatBEGIN
andEND
are set at once in case only one progressmessage was emitted due to the speed of the operation. BetweenBEGIN
andEND
, none of these flags will be set.Operation IDs are all held within the
OP_MASK
. Only one OperationID 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 nomaximum number of items or if it is (yet) unknown.message – In case of the
WRITING
operation, it contains the amount of bytestransferred. It may possibly be used for other purposes as well.
- Note:
You may read the contents of the current line in
self._cur_line
.
- classgit.util.Stats(total:Total_TD,files:Dict[str|PathLike[str],Files_TD])
Represents stat information as presented by git at the end of a merge. It iscreated from the output of a diff operation.
Example:
c=Commit(sha1)s=c.statss.total# full-stat-dicts.files# dict( filepath : stat-dict )
stat-dict
A dictionary with the following keys and values:
deletions=numberofdeletedlinesasintinsertions=numberofinsertedlinesasintlines=totalnumberoflineschangedasint,ordeletions+insertionschange_type=typeofchangeasstr,A|C|D|M|R|T|U|X|B
full-stat-dict
In addition to the items in the stat-dict, it features additional information:
files=numberofchangedfilesasint
- __module__='git.util'
- __slots__=('total','files')
- files
- total
- git.util.assure_directory_exists(path:str|PathLike[str],is_file:bool=False)→bool
Make sure that the directory pointed to by path exists.
- Parameters:
is_file – If
True
,path is assumed to be a file and handled correctly.Otherwise it must be a directory.- Returns:
True
if the directory was created,False
if it already existed.
- git.util.get_user_id()→str
- Returns:
String identifying the currently active system user as
name@node
- git.util.join_path(a:str|PathLike[str],*p:str|PathLike[str])→str|PathLike[str]
Join path tokens together similar to osp.join, but always use
/
instead ofpossibly\
on Windows.
- git.util.join_path_native(a:str|PathLike[str],*p:str|PathLike[str])→str|PathLike[str]
Like
join_path()
, but makes sure an OS native path is returned.This is only needed to play it safe on Windows and to ensure nice paths that onlyuse
\
.
- git.util.rmtree(path:str|PathLike[str])→None
Remove the given directory tree recursively.
- Note:
We use
shutil.rmtree()
but adjust its behaviour to see whether files thatcouldn’t be deleted are read-only. Windows will not remove them in that case.
- git.util.stream_copy(source:BinaryIO,destination:BinaryIO,chunk_size:int=524288)→int
Copy all data from thesource stream into thedestination stream in chunksof sizechunk_size.
- Returns:
Number of bytes written
- git.util.to_native_path_linux(path:str|PathLike[str])→str
- git.util.unbare_repo(func:Callable[[...],T])→Callable[[...],T]
Methods with this decorator raise
InvalidGitRepositoryError
ifthey encounter a bare repository.