API引用
顶层
- git.__version__
当前gitpython版本。
- git.refresh(path: str | os.PathLike[str] | None = None) None
设置git可执行文件路径的便捷方法。
- 参数:
path -- Git可执行文件的可选路径。如果不是绝对的,则相对于当前目录立即进行解析。
- 注意事项:
这个 path 参数通常被省略,并且不能用于指定在每个调用的路径搜索中查找其位置的自定义命令。看见
Git.refresh
有关如何实现这一点的详细信息。- 注意事项:
这调用
Git.refresh
并根据这样做的效果设置其他全局配置。因此,通常应该使用此函数,而不是使用Git.refresh
或FetchInfo.refresh
直接去吧。- 注意事项:
此函数在导入时自动调用,不带参数。
Objects.Base
- class git.objects.base.IndexObject(repo: Repo, binsha: bytes, mode: None | int = None, path: None | str | os.PathLike[str] = None)
可以作为索引文件一部分的所有对象的基。
表示可以作为索引文件一部分的git对象类型的类包括
Tree and :class:
~git.objects.blob.Blob`。此外,Submodule
,它实际上不是Git对象类型,但可以是索引文件的一部分,它也是一个子类。- __annotations__ = {}
- __hash__() int
- 返回:
作为索引项的路径散列可由路径唯一标识,而不是由它们的数据标识!
- __init__(repo: Repo, binsha: bytes, mode: None | int = None, path: None | str | os.PathLike[str] = None) None
初始化新实例化的
IndexObject
。- 参数:
repo -- 这个
Repo
我们位于。binsha -- 20字节SHA1。
mode -- 与Stat兼容的文件模式为
int
。使用stat
模块来评估信息。path -- 文件系统中文件的路径,相对于git存储库根,如
file.ext
或folder/other.ext
。
- 注意事项:
如果索引对象是直接创建的,则不能设置路径,因为在不知道父树的情况下无法检索它。
- __module__ = 'git.objects.base'
- __slots__ = ('path', 'mode')
- property abspath: str | os.PathLike[str]
- 返回:
此索引对象在文件系统中的绝对路径(与
path
字段,它是相对于Git存储库的路径)。返回的路径将是系统的本机路径,并包含\
在Windows上。
- mode
- property name: str
- 返回:
路径的名称部分,实际上是基本名称
- path
- class git.objects.base.Object(repo: Repo, binsha: bytes)
表示Git对象类型的类的基类。
以下四个叶类表示特定类型的Git对象:
看见 gitglossary(7) 打开:
“提交对象”:https://git-scm.com/docs/gitglossary#def_commit_object
“Tag Object”:https://git-scm.com/docs/gitglossary#def_tag_object
- 注意事项:
请参阅
AnyGitObject
表示实际Git对象类型的四个叶子类的联合类型。- 注意事项:
Submodule
在以此为根的层次结构下定义Object
类,即使子模块实际上不是一种类型的Git对象。(这也适用于其RootModule
子类。)- 注意事项:
这
Object
类不应与object
(在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
- 返回:
True
如果对象具有相同的SHA1
- __hash__() int
- 返回:
我们ID的散列,允许在字典和集合中使用对象
- __init__(repo: Repo, binsha: bytes) None
通过由对象的二进制SHA标识对象来初始化该对象。
如果满足以下条件,则将按需设置所有关键字参数
None
。- 参数:
repo -- 此对象所在的存储库。
binsha -- 20字节SHA1
- __module__ = 'git.objects.base'
- __ne__(other: Any) bool
- 返回:
True
如果对象不具有相同的SHA1
- __repr__() str
- 返回:
带有我们对象的古典式表示形式的字符串
- __slots__ = ('repo', 'binsha', 'size')
- __str__() str
- 返回:
所有git命令都能理解的SHA1字符串
- binsha
- property data_stream: OStream
- 返回:
对象的未压缩原始数据的文件-对象兼容流
- 注意事项:
返回的流必须按顺序读取。
- property hexsha: str
- 返回:
40字节十六进制版本的20字节二进制文件
- classmethod new(repo: Repo, id: str | Reference) Commit | Tree | TagObject | Blob
- 返回:
新的
Object
与后面的对象类型相对应的类型的实例 id 。新创建的对象的id将是binha,即使输入id可能已经是 ~git.refs.reference.Reference 或者是版本规格。- 参数:
id --
Reference
、REV-SPEC或HIXSHA。- 注意事项:
这不可能是
__new__
方法,因为它总是调用__init__()
其中输入ID不一定是BINSHA。
- classmethod new_from_sha(repo: Repo, sha1: bytes) Commit | Tree | TagObject | Blob
- 返回:
适合表示给定二进制SHA1的类型的新对象实例
- 参数:
sha1 -- 20字节二进制SHA1。
- repo
- size
- type: Literal['commit', 'tag', 'blob', 'tree'] | None = None
字符串标识(混凝土
Object
子类型)GIT对象类型。这可能命名的子类型对应于存在的Git对象的类型,即,可能存在于Git存储库中的对象。
- 注意事项:
大多数子类表示特定类型的Git对象,并相应地覆盖这个类属性。此属性为
None
在Object
基类以及IndexObject
中间子类,但从不None
在表示特定Git对象类型的具体叶子子类中。- 注意事项:
另请参阅
GitObjectTypeString
。
Objects.Blob
- class git.objects.blob.Blob(repo: Repo, binsha: bytes, mode: None | int = None, path: None | str | os.PathLike[str] = None)
Blob封装Git Blob对象。
看见 gitglossary(7) 关于《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
- property mime_type: str
- 返回:
描述此文件的MIME类型的字符串(基于文件名)
- 注意事项:
默认为
text/plain
在实际文件类型未知的情况下。
- type: Literal['blob'] = 'blob'
字符串标识(混凝土
Object
子类型)GIT对象类型。这可能命名的子类型对应于存在的Git对象的类型,即,可能存在于Git存储库中的对象。
- 注意事项:
大多数子类表示特定类型的Git对象,并相应地覆盖这个类属性。此属性为
None
在Object
基类以及IndexObject
中间子类,但从不None
在表示特定Git对象类型的具体叶子子类中。- 注意事项:
另请参阅
GitObjectTypeString
。
Objects.Commit
- class git.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)
包装Git提交对象。
看见 gitglossary(7) 关于“提交对象”:https://git-scm.com/docs/gitglossary#def_commit_object
- 注意事项:
这个类将延迟处理它的一些属性,并且仅当它涉及调用git二进制文件时才会按需查询值。
- __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
实例化新的
Commit
。所有关键字参数都采用None
AS默认设置将在第一次查询时隐式设置。- 参数:
binsha -- 20字节SHA1。
tree -- A
Tree
对象。author -- 作者
Actor
对象。authored_date -- INT_SECONDS_SIME_EPOCH创作的日期时间-使用
time.gmtime()
将其转换为不同的格式。author_tz_offset -- UTC的Int_Second_West_of_UTC时区 authored_date 是很流行的。
committer -- 提交者字符串,如
Actor
对象。committed_date -- INT_SECONDS_SIME_EPOCH提交的日期时间-使用
time.gmtime()
将其转换为不同的格式。committer_tz_offset -- UTC的Int_Second_West_of_UTC时区 committed_date 是很流行的。
message -- 字符串提交消息。
encoding -- 消息的字符串编码,默认为UTF-8。
parents -- 列表或元组
Commit
对象,这些对象是提交依赖图中的父对象(S)。
- 返回:
- 注意事项:
时区信息的格式和符号与
time.altzone()
回归。与Git的UTC时区相比,这个符号是颠倒的。
- __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)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- author
- author_tz_offset
- authored_date
- property authored_datetime: datetime
- property co_authors: List[Actor]
在提交消息中搜索此提交的任何合著者。
合著者详情:https://github.blog/2018-01-29-commit-together-with-co-authors/
- 返回:
此提交的合著者列表(AS
Actor
对象)。
- committed_date
- property committed_datetime: datetime
- committer
- committer_tz_offset
- conf_encoding = 'i18n.commitencoding'
- count(paths: str | PathLike[str] | Sequence[str | PathLike[str]] = '', **kwargs: Any) int
计算可从该提交到达的提交数。
- 参数:
paths -- 将返回值限制为提交的可选路径或路径列表,实际上包含这些路径。
kwargs -- 要传递给的其他选项 git-rev-list(1) 。它们不得更改命令的输出样式,否则解析将产生不正确的结果。
- 返回:
定义可访问提交数的int
- classmethod create_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
对象。- 参数:
repo --
Repo
提交应该是其中一部分的对象。tree --
Tree
对象或十六进制或二进制数。新提交的树。message -- 提交消息。如果未提供消息,则可能为空字符串。在任何情况下,它都将被转换为字符串。
parent_commits -- 任选
Commit
要用作新提交的父级的对象。如果列表为空,则提交将根本没有父级并成为根提交。如果None
,则当前头提交将是新提交对象的父对象。head -- 如果
True
,则头将自动前进到新的提交。否则,头将保持指向前一次提交。这可能会导致在区分文件时出现不希望看到的结果。author -- 作者姓名,可选。如果未设置,则使用存储库配置来获取此值。
committer -- 提交者的姓名,可选。如果未设置,则使用存储库配置来获取此值。
author_date -- 作者字段的时间戳。
commit_date -- 提交者字段的时间戳。
- 返回:
Commit
表示新提交的。- 注意事项:
有关提交者和作者的其他信息来自环境或GIT配置。看见 git-commit-tree(1) 以获取更多信息。
- default_encoding = 'UTF-8'
- encoding
- env_author_date = 'GIT_AUTHOR_DATE'
- env_committer_date = 'GIT_COMMITTER_DATE'
- gpgsig
- classmethod iter_items(repo: Repo, rev: str | Commit | SymbolicReference, paths: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] = '', **kwargs: Any) Iterator[Commit]
查找与给定条件匹配的所有提交。
- 参数:
repo -- 这个
Repo
。rev -- 修订说明符。看见 git-rev-parse(1) 寻找可行的选择。
paths -- 可选路径或路径列表。如果仅设置
Commit
包含路径的S将被考虑。kwargs -- 可选的关键字参数 git-rev-list(1) 其中: *
max_count
is the maximum number of commits to fetch. *skip
要跳过的提交数。*since
选择自某个日期以来的所有提交,例如"1970-01-01"
。
- 返回:
迭代器屈服
Commit
物品。
- iter_parents(paths: str | PathLike[str] | Sequence[str | PathLike[str]] = '', **kwargs: Any) Iterator[Commit]
迭代 _all_ 这一承诺的父母。
- 参数:
paths -- 可选路径或路径列表限制
Commit
S设置为至少包含其中一条路径的路径。kwargs -- 允许的所有参数 git-rev-list(1) 。
- 返回:
迭代器屈服
Commit
作为父对象的对象self
- message
- property name_rev: str
- 返回:
描述基于最接近的 ~git.refs.reference.Reference 。
- 注意事项:
主要用于用户界面目的。
- property summary: str | bytes
- 返回:
提交消息的第一行
- property trailers: Dict[str, str]
已弃用。把这条信息的预告片编成词典。
- 注意事项:
此属性已弃用,请使用
trailers_list
或trailers_dict
。- 返回:
包含空格删除的尾部信息的词典。仅包含每个尾部密钥的最新实例。
- property trailers_dict: Dict[str, List[str]]
把这条信息的预告片编成词典。
Git消息可以包含类似于以下内容的尾部信息 RFC 822 电子邮件标题。看见 git-interpret-trailers(1) 。
此函数调用
git interpret-trailers --parse
放到消息上以提取预告片信息。在将键值对保存到词典之前,它们会被去掉前导空格和尾随空格。带有尾部的有效消息::
Subject line some body information another information key1: value1.1 key1: value1.2 key2 : value 2 with inner spaces
返回的词典如下所示::
{ "key1": ["value1.1", "value1.2"], "key2": ["value 2 with inner spaces"], }
- 返回:
包含去掉空格的尾部信息的字典,将尾部键映射到其相应值的列表。
- property trailers_list: List[Tuple[str, str]]
以列表的形式获取消息的预告片。
Git消息可以包含类似于以下内容的尾部信息 RFC 822 电子邮件标题。看见 git-interpret-trailers(1) 。
此函数调用
git interpret-trailers --parse
在消息上提取尾部信息,以列表的形式返回原始尾部数据。带有尾部的有效消息::
Subject line some body information another information key1: value1.1 key1: value1.2 key2 : value 2 with inner spaces
返回的列表如下所示::
[ ("key1", "value1.1"), ("key1", "value1.2"), ("key2", "value 2 with inner spaces"), ]
- 返回:
包含空格删除的尾部信息的键值元组的列表。
- tree
- type: Literal['commit'] = 'commit'
字符串标识(混凝土
Object
子类型)GIT对象类型。这可能命名的子类型对应于存在的Git对象的类型,即,可能存在于Git存储库中的对象。
- 注意事项:
大多数子类表示特定类型的Git对象,并相应地覆盖这个类属性。此属性为
None
在Object
基类以及IndexObject
中间子类,但从不None
在表示特定Git对象类型的具体叶子子类中。- 注意事项:
另请参阅
GitObjectTypeString
。
Objects.Tag
提供了一种 Object
-带注释的标记的基于类型。
这定义了 TagObject
类,它表示带批注的标记。有关轻量级标记,请参阅 git.refs.tag
模块。
- class git.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)
带有注释的(即非轻量级)标记,包含有关我们所指向的对象的附加信息。
看见 gitglossary(7) 关于“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
使用附加数据初始化Tag对象。
- __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'
字符串标识(混凝土
Object
子类型)GIT对象类型。这可能命名的子类型对应于存在的Git对象的类型,即,可能存在于Git存储库中的对象。
- 注意事项:
大多数子类表示特定类型的Git对象,并相应地覆盖这个类属性。此属性为
None
在Object
基类以及IndexObject
中间子类,但从不None
在表示特定Git对象类型的具体叶子子类中。- 注意事项:
另请参阅
GitObjectTypeString
。
Objects.Tree
- class git.objects.tree.Tree(repo: Repo, binsha: bytes, mode: int = 16384, path: str | os.PathLike[str] | None = None)
-
看见 gitglossary(7) 关于“树对象”:https://git-scm.com/docs/gitglossary#def_tree_object
支持订阅,如列表或词典:
属性访问特定的Blob
tree["filename"]
记数法。同样,您可以通过索引进行访问,如
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)
初始化新实例化的
IndexObject
。- 参数:
repo -- 这个
Repo
我们位于。binsha -- 20字节SHA1。
mode -- 与Stat兼容的文件模式为
int
。使用stat
模块来评估信息。path -- 文件系统中文件的路径,相对于git存储库根,如
file.ext
或folder/other.ext
。
- 注意事项:
如果索引对象是直接创建的,则不能设置路径,因为在不知道父树的情况下无法检索它。
- __len__() int
- __module__ = 'git.objects.tree'
- __slots__ = ('_cache',)
- blob_id = 8
- property cache: TreeModifier
- 返回:
允许修改内部缓存的对象。这可用于更改树的内容。做完后,一定要打电话给
set_done()
在树修饰符上,否则序列化行为将不正确。- 注意事项:
看见
TreeModifier
有关如何更改缓存的详细信息,请参阅。
- commit_id = 14
- list_traverse(*args: Any, **kwargs: Any) IterableList[Tree | Blob | Submodule]
- 返回:
IterableList
所生成的遍历结果traverse()
树->重复列表 [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] = <function Tree.<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] = <function Tree.<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]]]
有关文档,请参阅 Traversable._traverse() <git.objects.util.Traversable._traverse> 。
树设置为
visit_once = False
以在遍历中获得更高的性能。
- tree_id = 4
- type: Literal['tree'] = 'tree'
字符串标识(混凝土
Object
子类型)GIT对象类型。这可能命名的子类型对应于存在的Git对象的类型,即,可能存在于Git存储库中的对象。
- 注意事项:
大多数子类表示特定类型的Git对象,并相应地覆盖这个类属性。此属性为
None
在Object
基类以及IndexObject
中间子类,但从不None
在表示特定Git对象类型的具体叶子子类中。- 注意事项:
另请参阅
GitObjectTypeString
。
- class git.objects.tree.TreeModifier(cache: List[Tuple[bytes, int, str]])
一个实用程序类,提供以类似列表的方式更改底层缓存的方法。
完成所有调整后,
_cache
,它实际上是对树的缓存的引用,将被排序。这确保了它将处于可序列化状态。- __delitem__(name: str) None
删除具有给定名称的项目(如果该项目存在)。
- __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
将给定的项目添加到树中。
如果具有给定名称的项已存在,则不会执行任何操作,但
ValueError
如果现有项的SHA和模式与您添加的项不匹配,将引发 force 是True
。- 参数:
sha -- 要添加的项的20或40字节SHA。
mode --
int
表示项的统计兼容模式。force -- 如果
True
,具有您的姓名和信息的项目将覆盖任何具有相同名称的现有项目,无论它具有哪些信息。
- 返回:
自性
- add_unchecked(binsha: bytes, mode: int, name: str) None
将给定的项目添加到树中。它的正确性是假定的,因此调用者有责任确保输入是正确的。
有关参数的详细信息,请参阅
add()
。- 参数:
binsha -- 20字节的二进制SHA。
- set_done() TreeModifier
一旦完成了树信息的修改,就调用此方法。
这可能会被调用几次,但请注意,每次调用都会导致排序操作。
- 返回:
自性
Objects.Functions
应该尽可能快的函数。
- git.objects.fun.traverse_tree_recursive(odb: GitCmdObjectDB, tree_sha: bytes, path_prefix: str) List[Tuple[bytes, int, str]]
- 返回:
二进制对象指向的树的条目列表 tree_sha 。
条目的格式如下:
[0] 20个字节的SHA
[1] 模式为整型
[2] 相对于存储库的路径
- 参数:
path_prefix -- 添加到所有返回路径前面的前缀。
- git.objects.fun.traverse_trees_recursive(odb: GitCmdObjectDB, tree_shas: Sequence[bytes | None], path_prefix: str) List[Tuple[Tuple[bytes, int, str] | None, ...]]
- 返回:
具有根据给定二叉树的条目的列表-SHAS。
结果以n元组|无每个Blob/Commit的列表进行编码,(n==len(Tree_Shas)),其中:
[0] ==20个字节的SHA
[1] ==模式为整型
[2] ==相对于工作树根的路径
条目元组是
None
如果在给定树中不存在相应的BLOB/COMMIT。- 参数:
tree_shas -- 沙斯的重复指着树。所有的树必须在同一层。一棵树-沙可能是
None
,在这种情况下None
。path_prefix -- 要添加到此级别上的返回路径的前缀。设置它
""
对于第一次迭代。
- 注意事项:
退回物品的订购将部分丢失。
- git.objects.fun.tree_entries_from_data(data: bytes) List[Tuple[bytes, int, str]]
读取树的二进制表示形式,并返回
Tree
物品。- 参数:
data -- 带有树数据的数据块(以字节为单位)。
- 返回:
List(tuple(binasha,mode,tree_Relative_Path),...)
- git.objects.fun.tree_to_stream(entries: Sequence[Tuple[bytes, int, str]], write: Callable[[ReadableBuffer], int | None]) None
属性将给定的条目列表写入流中。
write
方法。- 参数:
entries -- Sorted 包含(binasha,模式,名称)的元组列表。
write -- A
write
接受数据字符串的方法。
Objects.Submodule.base
- class git.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)
实现对Git子模块的访问。它们的特殊之处在于,它们的SHA表示子模块的存储库中的提交,该提交将在该实例的路径处签出。
子模块类型没有与其关联的字符串类型,因为它在树和索引中仅作为标记存在。
所有方法都适用于裸存储库和非裸存储库。
- __abstractmethods__ = frozenset({})
- __annotations__ = {'_id_attribute_': 'str', 'type': typing.Literal['submodule']}
- __eq__(other: Any) bool
请与其他子模块进行比较。
- __hash__() int
使用该实例的逻辑ID(而不是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
使用其属性初始化此实例。
我们只记录与以下内容不同的参数
IndexObject
。- 参数:
repo -- 我们的上级储存库。
binsha -- 二进制SHA指的是远程储存库中的提交。请参阅 url 参数。
parent_commit -- 这个
Commit
它的树应该包含.gitmodules
BLOB,或None
始终指向最近提交的。看见set_parent_commit()
了解更多细节。url -- 指向作为子模块的远程存储库的URL。
branch_path -- 完整存储库-克隆远程存储库时引用的签出的相对路径。
- __module__ = 'git.objects.submodule.base'
- __ne__(other: object) bool
与另一个子模块比较不等式。
- __parameters__ = ()
- __repr__() str
- 返回:
带有我们对象的古典式表示形式的字符串
- __slots__ = ('_parent_commit', '_url', '_branch_path', '_name', '__weakref__')
- __str__() str
- 返回:
所有git命令都能理解的SHA1字符串
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- __weakref__
- classmethod add(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
将新的子模块添加到给定的存储库中。这将改变索引以及
.gitmodules
文件,但不会创建新的提交。如果子模块已经存在,无论配置与提供的配置是否不同,都会返回已有的子模块。- 参数:
repo -- 应该接收子模块的存储库实例。
name -- 子模块的名称/标识符。
path -- 存储库-子模块应位于的相对或绝对路径。它将在存储库初始化期间根据需要创建。
url --
git clone ...
-兼容的URL。看见 git-clone(1) 以获取更多信息。如果None
,则假定存储库存在,取而代之的是第一个远程服务器的URL。如果您想要使现有存储库成为另一个存储库的子模块,这将非常有用。branch -- 应该(稍后)签出子模块的分支的名称。给定的分支必须存在于远程存储库中,并且将作为跟踪分支在本地签出。只有在未写入配置的情况下才会将其写入配置
None
,此时检出的分支将是远程头指向的分支。您在这些情况下得到结果有些模糊,建议您至少指定master
这里。以下是例子master
或feature/new
。no_checkout -- 如果
True
,如果必须手动克隆存储库,则不会执行签出。depth -- 使用截断到指定提交次数的历史记录创建浅克隆。
env -- 包含所需环境变量的可选词典。注意:提供的变量将用于更新执行环境
git
。如果中未指定某个变量 env 并且在attr:`os.Environmental`中定义,将使用attr:`os.Environmental`中的值。如果要取消某些变量的设置,请考虑提供空字符串作为其值。clone_multi_options -- 克隆选项列表。请看
Repo.clone
了解更多细节。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。
- 返回:
新创建的
Submodule
举个例子。- 注意事项:
以原子方式工作,例如,如果存储库更新失败,则不会进行任何更改。
- property branch: Head
- 返回:
我们要签出的分支实例
- 抛出:
git.exc.InvalidGitRepositoryError -- 如果我们的模块尚未签出。
- property branch_name: str
- 返回:
分支的名称,这是可能的最短分支名称
- property branch_path: str | PathLike[str]
- 返回:
完整存储库-我们将从远程和跟踪签出的分支的相对路径,以字符串形式表示
- children() IterableList[Submodule]
- 返回:
迭代列表(子模块,...)的可迭代列表
Submodule
实例,如果该子模块未检出,则为0。
- config_reader() SectionConstraint[SubmoduleConfigParser]
- 返回:
ConfigReader实例,允许您查询该子模块的配置值,如
.gitmodules
文件。- 注意事项:
配置读取器实际上将直接从存储库中读取数据,因此不需要也不关心您的工作树。
- 注意事项:
应该由调用方缓存,并且只保留需要的时间。
- 抛出:
IOError -- 如果
.gitmodules
无法读取文件/Blob。
- config_writer(index: IndexFile | None = None, write: bool = True) SectionConstraint[SubmoduleConfigParser]
- exists() bool
- 返回:
True
如果子模块存在,False
否则的话。请注意,可能存在一个子模块(在.gitmodules
文件),即使其模块不存在于磁盘上。
- classmethod iter_items(repo: Repo, parent_commit: Commit | TagObject | str = 'HEAD', *args: Any, **kwargs: Any) Iterator[Submodule]
- 返回:
迭代器屈服
Submodule
给定存储库中可用的实例
- k_default_mode = 57344
子模块标志。子模块是具有链接状态的目录。
- k_head_default = 'master'
- k_head_option = 'branch'
- k_modules_file = '.gitmodules'
- module() Repo
- 返回:
Repo
实例从我们的子模块路径的存储库中初始化- 抛出:
git.exc.InvalidGitRepositoryError -- 如果存储库不可用。这也可能意味着它尚未初始化。
- move(module_path: str | PathLike[str], configuration: bool = True, module: bool = True) Submodule
将子模块移动到另一个模块路径。这涉及到在当前路径上物理移动存储库、更改配置以及相应地调整索引项。
- 参数:
module_path -- 在父存储库的工作树中将模块移动到的路径,给定为存储库相对路径或绝对路径。将相应地创建中间目录。如果该路径已存在,则它必须为空。拖尾(反)斜杠将自动删除。
configuration -- 如果
True
,将调整配置以使子模块指向给定路径。module -- 如果
True
,由该子模块管理的存储库也将被移动。如果False
,我们不移动子模块的签出,这可能会使父存储库处于不一致的状态。
- 返回:
自性
- 抛出:
ValueError -- 如果模块路径存在且不为空,或为文件。
- 注意事项:
目前,该方法不是原子的,如果子步骤由于某种原因失败,它可能会使存储库处于不一致的状态。
- property name: str
- 返回:
此子模块的名称。它被用来在
.gitmodules
文件。- 注意事项:
默认情况下,这是用于查找子模块的路径,但在GitPython中,它应该是一个唯一的标识符,类似于用于远程的标识符,这允许轻松更改子模块的路径。
- remove(module: bool = True, force: bool = False, configuration: bool = True, dry_run: bool = False) Submodule
从存储库中删除此子模块。这将从
.gitmodules
文件中的条目和.git/config
文件。- 参数:
module -- 如果
True
,我们指向的已签出模块也将被删除。如果该模块当前在遥控器中任何分支之外提交,或者如果它在其跟踪分支之前,或者如果在其工作树中存在已修改或未跟踪的文件,则删除将失败。如果由于这些原因导致存储库删除失败,子模块状态将不会更改。如果此子模块有自己的子模块,则在接触直接子模块之前,这些子模块将被删除。force -- 强制删除模块,即使它包含修改。这基本上强制执行基于暴力文件系统的删除。
configuration -- 如果
True
,则该子模块将从配置中删除,否则不会删除。虽然这应该在大多数情况下启用,但该标志使您能够安全地删除子模块的存储库。dry_run -- 如果
True
,我们实际上不会做任何事情,而是抛出我们通常会抛出的错误。
- 返回:
自性
- 注意事项:
在空存储库中不起作用。
- 注意事项:
不能自动工作,因为不删除子模块的任何部分都会留下不一致的状态。
- 抛出:
git.exc.InvalidGitRepositoryError -- 如果无法删除存储库,则抛出。
OSError -- 如果无法删除目录或文件。
- rename(new_name: str) Submodule
重命名此子模块。
- 注意事项:
此方法负责在不同位置重命名该子模块,例如:
$parent_git_dir / config
$working_tree_dir / .gitmodules
(Git>=v1.8.0:将子模块存储库移至新名称)
AS
.gitmodules
将被改变,您将需要在之后做出承诺。改变了的.gitmodules
文件将已添加到索引中。- 返回:
这
Submodule
实例
- set_parent_commit(commit: Commit | TagObject | str | None, check: bool = True) Submodule
设置此实例以使用给定的提交,该提交的树应该包含
.gitmodules
斑点。- 参数:
commit -- 指向根树的类似提交的引用,或者
None
始终指向最近提交的。check -- 如果
True
,将执行相对昂贵的检查来验证子模块的有效性。
- 抛出:
ValueError -- 如果提交的树不包含
.gitmodules
斑点。ValueError -- 如果父提交没有将此子模块存储在当前路径下。
- 返回:
自性
- type: Literal['submodule'] = 'submodule'
这是一个用于基类兼容性的伪类型字符串。
- 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
更新此子模块的存储库,以指向我们使用该实例的binsha指向的签出。
- 参数:
recursive -- 如果
True
,我们将递归操作并更新子模块。init -- 如果
True
,如有必要,模块存储库将克隆到位。to_latest_revision -- 如果
True
,则在签出过程中将忽略该子模块的SHA。取而代之的是获取遥控器,并更新本地跟踪分支。只有当我们有一个本地跟踪分支时才有效,如果远程存储库有一个主分支,或者branch
已为此子模块指定选项,并且分支远程存在。progress --
UpdateProgress
实例,或None
如果不应该显示任何进展。dry_run -- 如果
True
,该操作将仅被模拟,但不执行。所有执行的操作都是只读的。force -- 如果
True
,我们可能会重置磁头,即使有问题的存储库是脏的。此外,我们将被允许将跟踪分支设置在其远程分支之前,返回到过去或远程分支的位置。这从本质上来说将“忘记”承诺。如果False
,位于各自远程分支机构未来的本地跟踪分支机构将不会被移动。keep_going -- 如果
True
,我们将忽略但记录所有错误,并继续递归运行。除非 dry_run 也设置好了, keep_going 可能会导致后续/继承的错误,否则您不会看到。与 dry_run 因此,在更新子模块时预测所有错误可能很有用。env -- 包含所需环境变量的可选词典。注意:提供的变量将用于更新执行环境
git
。如果中未指定某个变量 env 并且在attr:`os.Environmental`中定义,将使用attr:`os.Environmental`中的值。如果要取消某些变量的设置,请考虑提供空字符串作为其值。clone_multi_options -- 列表 git-clone(1) 选择。请看
Repo.clone
了解更多细节。它们只对以下对象生效 init 选择。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。
- 注意事项:
在空存储库中不执行任何操作。
- 注意事项:
在以下情况下,此方法肯定不是原子的 recursive 是
True
。- 返回:
自性
- property url: str
- 返回:
子模块的存储库引用的存储库的URL
- class git.objects.submodule.base.UpdateProgress
类向调用方提供详细的进度信息,调用方应从中派生并实现
update(...)
留言。- 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
- class git.objects.submodule.root.RootModule(repo: Repo)
给定存储库中所有子模块的(虚拟)根。
这可用于更轻松地遍历超级项目(主资料库)的所有子模块。
- __abstractmethods__ = frozenset({})
- __annotations__ = {'_id_attribute_': 'str', 'type': "Literal['submodule']"}
- __init__(repo: Repo) None
使用其属性初始化此实例。
我们只记录与以下内容不同的参数
IndexObject
。- 参数:
repo -- 我们的上级储存库。
binsha -- 二进制SHA指的是远程储存库中的提交。请参阅 url 参数。
parent_commit -- 这个
Commit
它的树应该包含.gitmodules
BLOB,或None
始终指向最近提交的。看见set_parent_commit()
了解更多细节。url -- 指向作为子模块的远程存储库的URL。
branch_path -- 完整存储库-克隆远程存储库时引用的签出的相对路径。
- __module__ = 'git.objects.submodule.root'
- __parameters__ = ()
- __slots__ = ()
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- 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
将此存储库的子模块更新为当前Head Commit。
此方法通过确定子模块的存储库路径的更改,然后是要签出的提交或要签出的分支的更改,来灵活地执行此操作。如果子模块的ID不变,这将起作用。
此外,它还将检测子模块的添加和删除,这将得到妥善处理。
- 参数:
previous_commit -- 如果设置为Commit-ish,则在将Head设置为Now指向的Commit之前,我们应将该Commit用作Head指向的前一次提交。如果
None
,则默认为HEAD@{1}
否则的话。recursive -- 如果
True
,子模块的子模块也将使用相同的技术进行更新。force_remove -- 如果子模块已被删除,它们将被强制删除。否则,如果子模块的存储库因更改而无法删除,则更新可能会失败。(请参阅
Submodule.update
了解更多信息。)init -- 如果我们遇到一个需要初始化的新模块,那么就这样做。
to_latest_revision -- 如果
True
,而不是签出此子模块的SHA所指向的修订,签出的跟踪分支将与从存储库的原始位置获取的最新远程分支合并。除非 force_reset 则本地跟踪分支将永远不会重置为其过去,因此远程分支必须在将来才能生效。force_reset -- 如果
True
子模块可以签出或重置其分支,即使储存库具有将被重写的未决更改,或者如果本地跟踪分支在远程跟踪分支的未来并且将被重置为其过去。progress --
RootUpdateProgress
实例,或None
如果不应发送任何进度,则返回。dry_run -- 如果
True
,则不会实际执行操作。进度消息将相应更改,以指示操作的Will DO状态。keep_going -- 如果
True
,我们将忽略但记录所有错误,并继续递归运行。除非 dry_run 也设置好了, keep_going 可能会导致后续/继承的错误,否则您不会看到。与 dry_run ,这对于在更新子模块时预测所有错误非常有用。
- 返回:
自性
- class git.objects.submodule.root.RootUpdateProgress
将更多操作码添加到的实用程序类
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
- class git.objects.submodule.util.SubmoduleConfigParser(*args: Any, **kwargs: Any)
接听来电至
write()
,并更新.gitmodules
如果我们已经写入到流中,则使用新数据在索引中添加BLOB。否则,它会将本地文件添加到索引中,使其与工作树相对应。此外,还必须清除缓存。
请注意,任何变异方法都不能在裸模式下工作。
- __abstractmethods__ = frozenset({})
- __init__(*args: Any, **kwargs: Any) None
初始化配置读取器以读取给定的 file_or_files 并可能允许通过设置 read_only 假的。
- 参数:
file_or_files -- 文件路径或文件对象,或一系列可能多于一个的路径或文件对象。
read_only -- 如果
True
,ConfigParser只能读取数据,而不能更改数据。如果False
,则只能给出单个文件路径或文件对象。我们将在更改发生时或在ConfigParser发布时回写更改。如果已包含其他配置文件,则不会发生这种情况。merge_includes -- 如果
True
,我们将阅读中提到的文件[include]
部分,并将其内容合并到我们的。这使得不可能回写单个配置文件。因此,如果要修改单个配置文件,请关闭此选项以在读取原始数据集时保持其不变。repo -- 引用要在以下情况下使用的存储库
[includeIf]
节可以在配置文件中找到。
- __module__ = 'git.objects.submodule.util'
- flush_to_index() None
将配置文件中的更改刷新到索引。
- write() None
如果有任何更改,请将更改写入我们的文件。
- 抛出:
IOError -- 如果这是一个只读编写器实例,或者如果我们无法获取文件锁。
- git.objects.submodule.util.find_first_remote_branch(remotes: Sequence[Remote], branch_name: str) RemoteReference
查找与给定分支或RAISE名称匹配的远程分支
InvalidGitRepositoryError
。
- git.objects.submodule.util.sm_name(section: str) str
- 返回:
从节名解析的子模块的名称
- git.objects.submodule.util.sm_section(name: str) str
- 返回:
使用的章节标题
.gitmodules
配置文件
Objects.Util
用于处理Git对象的实用程序函数。
- class git.objects.util.Actor(name: str | None, email: str | None)
参与者保存有关在存储库上执行操作的人员的信息。他们可以是提交者和作者,也可以是git日志条目中提到的具有名称和电子邮件的任何内容。
- __eq__(other: Any) bool
返回self==值。
- __hash__() int
返回hash(Self)。
- __init__(name: str | None, email: str | None) None
- __module__ = 'git.util'
- __ne__(other: Any) bool
返回自我!=值。
- __repr__() str
返回epr(Self)。
- __slots__ = ('name', 'email')
- __str__() str
返回str(Self)。
- classmethod author(config_reader: None | GitConfigParser | SectionConstraint = None) Actor
相同于
committer()
,但定义了主要作者。它可以在环境中指定,但缺省为提交者。
- classmethod committer(config_reader: None | GitConfigParser | SectionConstraint = None) Actor
- 返回:
Actor
实例,该实例与配置的提交者对应。它的行为类似于git实现,因此环境将覆盖 config_reader 。如果根本没有设置任何值,则会生成该值。- 参数:
config_reader -- ConfigReader用于在环境中未设置值的情况下从中检索值。
- 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('<(.*)>')
- class git.objects.util.ProcessStreamAdapter(process: Popen, stream_name: str)
类将所有调用连接到包含的流程实例。
使用此类型隐藏基础进程,以便仅提供对指定流的访问。该过程通常被包装到一个
AutoInterrupt
类在实例超出作用域时终止它。- __getattr__(attr: str) Any
- __init__(process: Popen, stream_name: str) None
- __module__ = 'git.objects.util'
- __slots__ = ('_proc', '_stream')
- class git.objects.util.Traversable
在一个方向上执行深度优先或广度优先遍历的简单界面。
子类只需要实现一个函数。
子类的实例必须是可哈希的。
定义的子类:
- __abstractmethods__ = frozenset({'_get_intermediate_items', 'list_traverse', 'traverse'})
- __annotations__ = {}
- __module__ = 'git.objects.util'
- __slots__ = ()
- abstract list_traverse(*args: Any, **kwargs: Any) Any
遍历自己并收集找到的所有物品。
直接在抽象基类上调用此方法,包括通过
super()
代理,已弃用。只应调用重写的实现。
- abstract traverse(*args: Any, **kwargs: Any) Any
迭代器生成遍历自身时发现的项。
直接在抽象基类上调用此方法,包括通过
super()
代理,已弃用。只应调用重写的实现。
- git.objects.util.altz_to_utctz_str(altz: float) str
将UTC以西的时区偏移量(秒)转换为Git时区偏移量字符串。
- 参数:
altz -- UTC以西的时区偏移量(秒)。
- git.objects.util.get_object_type_by_name(object_type_name: bytes) Type[Commit] | Type[TagObject] | Type[Tree] | Type[Blob]
检索GitPython用来表示一种Git对象的Python类。
- 返回:
适合于处理给定的AS的类型 object_type_name 。这种类型可以称为创建新实例。
- 参数:
object_type_name -- 成员:
Object.TYPES
。- 抛出:
ValueError -- 如果 object_type_name 是未知的。
- git.objects.util.parse_actor_and_date(line: str) Tuple[Actor, int, int]
从类似::的代码行中解析出参与者(作者或提交者)信息
author Tom Preston-Werner <tom@mojombo.com> 1191999972 -0700
- 返回:
[Actor, int_seconds_since_epoch, int_timezone_offset]
- git.objects.util.parse_date(string_date: str | datetime) Tuple[int, int]
将给定日期解析为以下内容之一:
可识别的DateTime实例
Git内部格式:时间戳偏移量
RFC 2822:
Thu, 07 Apr 2005 22:13:13 +0200
ISO 8601:
2005-04-07T22:13:13
--T
也可以是一个空间。
- 返回:
元组(int(TIMESTAMP_UTC),int(偏移量)),两者都是从纪元开始的秒数
- 抛出:
ValueError -- 如果格式不能被理解。
- 注意事项:
日期也可以是
YYYY.MM.DD
,MM/DD/YYYY
和DD.MM.YYYY
。
- class git.objects.util.tzoffset(secs_west_of_utc: float, name: None | str = None)
- __dict__ = mappingproxy({'__module__': 'git.objects.util', '__init__': <function tzoffset.__init__>, '__reduce__': <function tzoffset.__reduce__>, 'utcoffset': <function tzoffset.utcoffset>, 'tzname': <function tzoffset.tzname>, 'dst': <function tzoffset.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__
对象的弱引用列表
- dst(dt: datetime | None) timedelta
DATETIME->DST偏移量,以UTC以东的时间增量正数表示。
- tzname(dt: datetime | None) str
DateTime->字符串时区名称。
- utcoffset(dt: datetime | None) timedelta
日期时间->时间增量显示与UTC的偏移量,负值表示UTC以西
- git.objects.util.utctz_to_altz(utctz: str) int
将GIT时区偏移转换为UTC以西的时区偏移(以秒为单位)(与兼容
time.altzone
)。- 参数:
utctz -- Git UTC时区字符串,例如+0200
- git.objects.util.verify_utctz(offset: str) str
- 抛出:
ValueError -- 如果 offset 是不正确的。
- 返回:
offset
Index.Base
包含以下内容的模块 IndexFile
,索引实现方便了所有类型的索引操作,如查询和合并。
- exception git.index.base.CheckoutError(message: str, failed_files: Sequence[str | os.PathLike[str]], valid_files: Sequence[str | os.PathLike[str]], failed_reasons: List[str])
如果文件因包含更改而无法从索引中签出,则抛出。
这个
failed_files
属性包含无法签出的相对路径的列表,因为它们包含索引中不存在的更改。这个
failed_reasons
属性包含一个字符串,该字符串通知问题的实际原因。这个
valid_files
属性包含文件的相对路径列表,这些文件已成功签出,因此与索引中存储的版本匹配。- __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
返回str(Self)。
- class git.index.base.IndexFile(repo: Repo, file_path: str | os.PathLike[str] | None = None)
可以使用本机实现操作的索引,以便尽可能地保存git命令函数调用。
这提供了定制的合并工具,允许在不实际更改索引或工作树的情况下进行合并。这样,您就可以仅基于索引执行您自己的测试合并,而不必处理工作副本。这在部分工作树的情况下很有用。
条目:
该索引包含一个条目DICT,其键是以下类型的元组
IndexEntry
以方便访问。您可以使用IndexEntry实例读取条目dict或对其进行操作,即::
index.entries[index.entry_key(index_entry_instance)] = index_entry_instance
确保您使用
index.write()
在使用git命令对索引进行操作之前,直接对其进行操作。- S_IFGITLINK = 57344
子模块的标志。
- __abstractmethods__ = frozenset({})
- __annotations__ = {'_file_path': 'PathLike', 'repo': "'Repo'"}
- __init__(repo: Repo, file_path: str | os.PathLike[str] | None = None) None
初始化此Index实例,也可以从给定的 file_path 。
如果没有 file_path ,我们将从当前索引文件创建。
如果没有给定流,则将根据当前存储库的索引按需初始化流。
- __module__ = 'git.index.base'
- __slots__ = ('repo', 'version', 'entries', '_extension_data', '_file_path')
- add(items: ~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 = <function IndexFile.<lambda>>, path_rewriter: ~typing.Callable[[...], str | ~os.PathLike[str]] | None = None, write: bool = True, write_extension_data: bool = False) List[BaseIndexEntry]
从工作树、特定Blob或添加文件
BaseIndexEntry
S到索引。- 参数:
items -- 支持多种类型的项目,类型可以在一个调用中混合使用。不同的类型意味着不同的处理方式。文件路径通常可以是相对路径或绝对路径。-路径字符串表示指向现有文件的储存库的相对或绝对路径,例如,
CHANGES
, lib/myfile.ext , `/home/gitrepo/lib/myfile.ext`` 。绝对路径必须以此索引的存储库的工作树目录开头,才能被视为有效。例如,如果它是用非规范化路径初始化的,如/root/repo/../repo
,要添加的绝对路径必须以/root/repo/../repo
。像这样提供的路径必须存在。添加时,它们将被写入对象数据库。路径字符串可以包含GLOB,例如lib/__init__*
。或者它们可以是这样的目录lib
,它将添加目录和子目录中的所有文件。这等于一条直线 git-add(1) 。它们是在阶段0添加的。- :class:~`git.objects.blob.Blob` orSubmodule
添加对象斑点是因为它们假定设置了有效模式。它们引用的文件可能存在于文件系统中,也可能不存在,但必须是相对于我们的存储库的路径。如果它们的SHA为空(40*0),则它们的路径必须存在于相对于GIT存储库的文件系统中,因为将从路径处的数据创建对象。现在的处理方式与处理字符串路径的方式非常相同,只是您设置的模式将保持不变。这允许您通过分别设置模式并将符号链接的目标直接写入文件来创建符号链接。这等同于默认的Linux符号链接,它不会自动取消引用,只是它也可以在不支持它的文件系统上创建。请注意,不允许使用GLOB或目录Blob
物体。它们是在阶段0添加的。-BaseIndexEntry
或者类型处理等同于:CLASS:~`git.objects.blob.Blob`对象,但可以显式设置舞台。请注意,索引条目需要二进制SHA。force -- CURRENTLY INEFFECTIVE 如果
True
,否则无论如何都会添加被忽略或排除的文件。,而不是 git-add(1) 命令时,我们默认启用此标志,因为API用户通常希望添加项,即使它们可能被排除。fprogress -- 带签名的函数
f(path, done=False, item=item)
调用要添加的每条路径,一旦即将添加,调用一次,其中done=False
有一次,它被添加到哪里done=True
。item
设置为我们处理的实际项,可以是路径,也可以是BaseIndexEntry
。请注意,由于当前正在处理索引,因此不能保证已处理的路径已存在于索引中。path_rewriter -- 函数,带签名
(string) func(BaseIndexEntry)
,返回每个传递条目的路径,该路径是要为从中创建的对象实际记录的路径entry.path
。这允许您写入与硬盘上实际文件的布局不同的索引。如果不是None
和 items 包含普通路径,则这些路径将被预先转换为条目并传递给路径重写器。请注意entry.path
是相对于Git存储库的。write -- 如果
True
,索引一旦被更改就会被写入。否则,更改只存在于内存中,不能用于git命令。write_extension_data -- 如果
True
,扩展数据将被写回索引。如果它包含‘tree’扩展名,这可能会导致问题,这将导致 git-commit(1) 命令来编写旧树,而不是表示现在更改的索引的新树。这不重要,如果您使用IndexFile.commit()
,它完全忽略了‘tree’扩展名。您应该将其设置为True
如果您打算使用IndexFile.commit()
在维护对第三方扩展的支持的同时独占。除此之外,在根本不需要手动处理的存储库上使用GitPython时,您通常可以安全地忽略内置扩展。此处列出了所有当前的内置扩展:https://git-scm.com/docs/index-format
- 返回:
列表
BaseIndexEntry
代表刚才实际添加的条目的S。- 抛出:
OSError -- 如果提供的路径不存在。请注意
BaseIndexEntry
不具有空SHA的对象将被添加,即使它们的路径不存在。
- checkout(paths: None | ~typing.Iterable[str | ~os.PathLike[str]] = None, force: bool = False, fprogress: ~typing.Callable = <function IndexFile.<lambda>>, **kwargs: ~typing.Any) None | Iterator[str | PathLike[str]] | Sequence[str | PathLike[str]]
将索引已知版本的给定路径或所有文件签出到工作树中。
- 注意事项:
确保您已使用
write()
方法,以防您直接更改条目词典。- 参数:
paths -- 如果
None
,则将签出索引中的所有路径。否则,需要可迭代的相对或绝对路径或指向索引中的文件或目录的单个路径。force -- 如果
True
,现有文件将被覆盖,即使它们包含本地修改。如果False
,这些将触发一个CheckoutError
。fprogress -- 看见
IndexFile.add()
以供签署和解释。提供的进度信息将包含None
如果未给出显式路径,则作为路径和项。否则,将在签出文件之前和之后发送进度信息。kwargs -- 要传递给的其他参数 git-checkout-index(1) 。
- 返回:
已签出并保证与索引中存储的版本匹配的文件的可重复生成路径。
- 抛出:
如果至少有一个文件签出失败。这是一个摘要,因此无论如何它都会签出尽可能多的文件。
如果其中一个文件或目录在索引中不存在(与原始的git命令相反,该命令会忽略它们)。
git.exc.GitCommandError -- 如果无法解析错误行-这确实是一种异常状态。
- 注意事项:
检出仅限于检出索引中的文件。不会删除不再位于索引中而存在于工作树中的文件。这种行为从根本上与
head.checkout
也就是说,如果你想 git-checkout(1) -类似的行为,使用head.checkout
而不是index.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
对象。有关参数的更多信息,请参见
Commit.create_from_tree
。
- diff(other: Literal[DiffConstants.INDEX] | Tree | Commit | str | None = DiffConstants.INDEX, paths: str | PathLike[str] | List[str | PathLike[str]] | Tuple[str | PathLike[str], ...] | None = None, create_patch: bool = False, **kwargs: Any) DiffIndex
-
有关参数和返回值的文档,请参见
Diffable.diff
。- 注意事项:
将仅使用表示默认GIT索引的索引,因为它们尚未使用流进行初始化。
- entries
- classmethod entry_key(*entry: BaseIndexEntry | str | PathLike[str] | int) Tuple[str | PathLike[str], int]
- classmethod from_tree(repo: Repo, *treeish: Tree | Commit | str | bytes, **kwargs: Any) IndexFile
将给定的树形修订合并到返回的新索引中。原始索引将保持不变。
- 参数:
repo -- 树形的储存库位于其中。
treeish -- 一、二或三
Tree
对象,Commit
S或40字节十六进制。结果会根据树的数量而变化:1.如果给定1棵树,则只会将其读取到新的索引中。2.如果给定2棵树,则使用双向合并算法将它们合并到新的索引中。树1是“当前”树,树2是“其他”树。它的行为就像是快进。3.如果给定3棵树,则执行3向合并,第一棵树是树2和树3的共同祖先。树2是当前树,树3是另一棵树。kwargs -- 传递到的其他参数 git-read-tree(1) 。
- 返回:
新的
IndexFile
举个例子。它将指向一个不再存在的临时索引位置。如果您打算编写这样的合并索引,请提供一个替代索引file_path
至ITSwrite()
方法。- 注意事项:
在三方合并的情况下,
--aggressive
将被指定为以通常正确的方式自动解决更多案例。指定trivial=True
作为关键字参数来覆盖它。作为基础 git-read-tree(1) 命令考虑到当前的索引时,它会暂时移到一边,以防止任何意外的干扰。
- iter_blobs(predicate: ~typing.Callable[[~typing.Tuple[int, ~git.objects.blob.Blob]], bool] = <function IndexFile.<lambda>>) Iterator[Tuple[int, Blob]]
- 返回:
迭代器生成的元组
Blob
对象和阶段,元组(阶段,Blob)。- 参数:
predicate -- 函数(%t)返回
True
如果迭代器应生成元组(Stage,Blob)。默认筛选器,即 ~git.index.typ.BlobFilter ,允许您仅在Blob与给定的路径列表匹配时才生成Blob。
- merge_tree(rhs: Tree | Commit | str | bytes, base: None | Tree | Commit | str | bytes = None) IndexFile
合并给定的 rhs 将树木纳入当前指数,可能会考虑到共同的基础树木。
,而不是
from_tree()
方法,这使您可以使用已有的树作为合并的左侧。- 参数:
rhs -- 指向合并的另一边的树形引用。
base -- 可选的树状引用,指向 rhs 这个指数等于LHS。
- 返回:
自身(包含合并条目和可能的未合并条目,以防发生冲突)
- 抛出:
git.exc.GitCommandError -- 如果存在合并冲突。错误将在第一个冲突路径处引发。如果您希望自己完成正确的合并解析,则必须提交更改的索引(或从它创建有效的树),然后使用三向重试
index.from_tree
打电话。
- move(items: Sequence[str | PathLike[str] | Blob | BaseIndexEntry | Submodule], skip_errors: bool = False, **kwargs: Any) List[Tuple[str, str]]
重命名/移动项,而最后一项被视为移动操作的目的地。
如果目标是文件,则第一项(共两项)也必须是文件。
如果目标是目录,则其前面可能会有一个或多个目录或文件。
在非裸存储库中,工作树将受到影响。
- 参数:
- 返回:
列表(元组(SOURCE_PATH_STRING,Destination_Path_STRING),...)配对列表,包含已移动的源文件及其实际目标。相对于存储库根。
- 抛出:
ValueError -- 如果只给一件物品的话。
git.exc.GitCommandError -- 如果Git无法处理您的请求。
- classmethod new(repo: Repo, *tree_sha: str | Tree) IndexFile
将给定的树形修订合并到返回的新索引中。
此方法的行为类似于
git-read-tree --aggressive
在进行合并时。
- property path: str | PathLike[str]
- 返回:
我们表示的索引文件的路径
- remove(items: Sequence[str | PathLike[str] | Blob | BaseIndexEntry | Submodule], working_tree: bool = False, **kwargs: Any) List[str]
从索引中删除给定的项,也可以选择从工作树中删除。
- 参数:
items -- 支持多种类型的物品,可以自由混合。-Path字符串在所有阶段删除给定路径。如果是目录,则必须指定
r=True
关键字参数删除其下面的所有文件条目。如果给定了绝对路径,则它们将被转换为相对于包含工作树的Git存储库目录的路径。路径字符串可能包括GLOB,例如*.c
。- :class:~`git.objects.blob.Blob` object Only the path portion is used in this case. -BaseIndexEntry
或兼容类型此处唯一相关的信息是路径。舞台被忽略。working_tree -- 如果
True
,则该条目也将从工作树中删除,从而物理删除相应的文件。如果其中存在未提交的更改,则此操作可能失败。kwargs -- 要传递给的其他关键字参数 git-rm(1) ,例如
r
以允许递归删除。
- 返回:
LIST(路径字符串,...)已有效删除的存储库相对路径的列表。如果您提供了一个目录或GLOB,了解这一点是很有趣的。路径是相对于存储库的。
- reset(commit: Commit | Reference | str = 'HEAD', working_tree: bool = False, paths: None | Iterable[str | os.PathLike[str]] = None, head: bool = False, **kwargs: Any) IndexFile
重置索引以反映给定提交时的树。默认情况下,这不会调整我们的头部引用,而不是
HEAD.reset
。- 参数:
commit -- 修订,
Reference
或Commit
指定我们应该表示的提交。如果只想指定树,请使用IndexFile.from_tree()
并覆盖默认索引。working_tree -- 如果
True
,则工作树中的文件将反映更改后的索引。如果False
,则不会触摸工作树。请注意,对工作副本的更改将在没有警告的情况下被丢弃!head -- 如果
True
,则头将被设置为给定的提交。这是False
默认情况下,但如果True
,此方法的行为类似于HEAD.reset
。paths -- 如果作为绝对路径或存储库相对路径的可迭代形式给出,则只有这些路径将被重置为其在给定提交时的状态。提交时路径需要存在,否则将引发异常。
kwargs -- 传递给的其他关键字参数 git-reset(1) 。
- 注意事项:
IndexFile.reset()
,而不是HEAD.reset
,不会删除任何文件,以保持一致的工作树。相反,它只会根据文件在索引中的状态签出文件。如果你想的话 git-reset(1) -类似的行为,使用HEAD.reset
取而代之的是。- 返回:
自性
- resolve_blobs(iter_blobs: Iterator[Blob]) IndexFile
解析BLOB迭代器中给出的BLOB。
这将在所有非空阶段有效地移除相应路径的索引项,并将给定斑点添加为新的阶段空斑点。
对于每条路径,可能只有一个斑点,否则为
ValueError
将引发声明路径已处于阶段0的消息。- 抛出:
ValueError -- 如果其中一个斑点已存在于阶段0。
- 返回:
自性
- 注意事项:
一旦完成,您将不得不手动编写索引,即
index.resolve_blobs(blobs).write()
。
- unmerged_blobs() Dict[str | PathLike[str], List[Tuple[int, Blob]]]
- 返回:
Dict(Path:List(tuple(Stage,Blob,...),是将索引中的路径与包含排序的阶段/Blob对的列表相关联的字典。
- 注意事项:
已在一侧移除的斑点在给定的阶段中根本不存在。也就是说,在条目处于阶段3的‘Other’分支上删除的文件将不具有阶段3条目。
- update() IndexFile
重新读取索引文件的内容,丢弃我们可能拥有的所有缓存信息。
- 注意事项:
这可能是危险的操作,因为它将丢弃您对
index.entries
。- 返回:
自性
- version
- write(file_path: None | str | PathLike[str] = None, ignore_extension_data: bool = False) None
将当前状态写入我们的文件路径或给定的路径。
- 参数:
file_path -- 如果
None
,我们将写入已从其进行初始化的存储文件路径。否则,我们将写入给定的文件路径。请注意,这将更改 file_path 这个索引与你给的那个相同。ignore_extension_data -- 如果
True
,则不会将在索引中读取的树型扩展数据写入磁盘。请注意,实际上没有写入任何扩展数据。如果您已更改索引并希望使用 git-write-tree(1) 然后创建一个树来表示您编写的更改。如果该数据存在于写入的索引中, git-write-tree(1) 将改为写入存储/缓存的树。或者,使用write_tree()
自动处理这起案件。
- git.index.base.StageType
int
的别名
Index.Functions
伴随索引实现的独立功能,使其更具通用性。
- git.index.fun.S_IFGITLINK = 57344
子模块的标志。
- git.index.fun.entry_key(*entry: BaseIndexEntry | str | PathLike[str] | int) Tuple[str | PathLike[str], int]
- 返回:
适用于
index.entries
字典。- 参数:
entry -- 类型BaseIndexEntry或Path和Stage的一个实例。
- git.index.fun.hook_path(name: str, git_dir: str | PathLike[str]) str
- 返回:
给定Git存储库目录中给定命名挂接的路径
- git.index.fun.read_cache(stream: IO[bytes]) Tuple[int, Dict[Tuple[str | PathLike[str], int], IndexEntry], bytes, bytes]
从给定流中读取缓存文件。
- 返回:
元组(版本,条目_字典,扩展_数据,内容_夏)
version 是整数版本号。
entries_dict 是一个字典,它将IndexEntry实例映射到某个阶段的路径。
extension_data 是
""
或4字节类型+4字节大小+大小字节。content_sha 是所有高速缓存文件内容上的20字节的SHA。
- git.index.fun.run_commit_hook(name: str, index: IndexFile, *args: str) None
运行给定名称的提交挂钩。静默忽略不存在的挂钩。
- 参数:
name -- 钩子的名称,如
pre-commit
。index --
IndexFile
举个例子。args -- 传递给挂钩文件的参数。
- 抛出:
- git.index.fun.stat_mode_to_index_mode(mode: int) int
将给定模式从STAT调用转换为相应的索引模式并返回。
- 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
将条目表示的缓存写入流。
- 参数:
entries -- Sorted 条目列表。
stream -- 流包装到AdapterStreamCls中-它用于最终输出。
ShaStreamCls -- 写入流时要使用的类型。在将数据传递到被包装的流之前,它在向其写入数据时生成一个SHA。
extension_data -- 任何类型的数据都要写入尾部,它必须以4个字节的标识符开头,后跟其大小(4个字节)。
- git.index.fun.write_tree_from_cache(entries: List[IndexEntry], odb: GitCmdObjectDB, sl: slice, si: int = 0) Tuple[bytes, List[TreeCacheTup]]
从给定的条目排序列表创建一棵树,并将相应的树放入给定的对象数据库中。
- 参数:
entries -- Sorted 清单
IndexEntry
S。odb -- 要在其中存储树的对象数据库。
si -- 我们应该开始创建子树的起始索引。
sl -- 切片,指示我们应该在条目列表上处理的范围。
- 返回:
元组(binsha,list(tree_entry,...))SHA的元组和作为HexSHA、模式、名称的元组的树条目的列表。
Index.Types
索引使用的其他类型。
- class git.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])
索引条目的小兄弟,可以创建它来描述对索引所做的更改,在这种情况下,不需要大量的额外信息。
因为前4个数据成员与
IndexEntry
类型、方法应为BaseIndexEntry
还可以处理完全IndexEntry
S,即使他们出于性能原因使用数字索引。- __annotations__ = {}
- __dict__ = mappingproxy({'__module__': 'git.index.typ', '__doc__': 'Small brother of an index entry which can be created to describe changes\n done to the index in which case plenty of additional information is not required.\n\n As the first 4 data members match exactly to the :class:`IndexEntry` type, methods\n expecting a :class:`BaseIndexEntry` can also handle full :class:`IndexEntry`\\s even\n if they use numeric indices for performance reasons.\n ', '__new__': <staticmethod(<function BaseIndexEntry.__new__>)>, '__str__': <function BaseIndexEntry.__str__>, '__repr__': <function BaseIndexEntry.__repr__>, 'hexsha': <property object>, 'stage': <property object>, 'from_blob': <classmethod(<function BaseIndexEntry.from_blob>)>, 'to_blob': <function BaseIndexEntry.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
超覆
__new__
以允许从元组构造以实现向后兼容性。
- __repr__() str
返回格式良好的表示字符串
- __str__() str
返回str(Self)。
- classmethod from_blob(blob: Blob, stage: int = 0) BaseIndexEntry
- 返回:
在给定阶段配备齐全的BaseIndexEntry
- property hexsha: str
我们的SHA的十六进制版本
- property stage: int
参赛作品的阶段:
0=默认阶段
1=在3向合并的情况下位于合并或公共祖先条目之前的阶段
2=合并“左侧”条目的阶段
3=合并“右侧”条目的阶段
- 注意事项:
有关详细信息,请参阅 git-read-tree(1) 。
- class git.index.typ.BlobFilter(paths: Sequence[str | os.PathLike[str]])
要使用的谓词
IndexFile.iter_blobs
允许只过滤与给定目录或文件列表匹配的返回BLOB。给定的路径是相对于存储库给出的。
- __init__(paths: Sequence[str | os.PathLike[str]]) None
- 参数:
paths -- 指向与当前存储库相关的目录或文件的路径元组或列表。
- __module__ = 'git.index.typ'
- __slots__ = ('paths',)
- paths
- class git.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])
允许方便地访问中定义的索引条目数据
BaseIndexEntry
在没有完全拆开的情况下。经常访问的属性被缓存在元组中,而其他属性则按需解包。
有关名称和元组索引之间的映射,请参阅属性。
- __annotations__ = {}
- __module__ = 'git.index.typ'
- property ctime: Tuple[int, int]
- 返回:
文件创建时间的元组(int_time_Second_from_pech,int_nano_s
- classmethod from_base(base: BaseIndexEntry) IndexEntry
- 返回:
从给定项创建的最小条目
BaseIndexEntry
举个例子。缺少的值将被设置为类似于空的值。- 参数:
base -- 类型的实例
BaseIndexEntry
。
- classmethod from_blob(blob: Blob, stage: int = 0) IndexEntry
- 返回:
与给定BLOB对象类似的最小条目
- git.index.typ.StageType
int
的别名
Index.Util
索引实用程序。
- class git.index.util.TemporaryFileSwap(file_path: str | PathLike[str])
实用程序类将文件移动到同一目录中的临时位置,然后将其移回删除对象时的位置。
- __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]
装饰者确保只有当我们是默认的存储库索引时,包装方法才能运行。
这是因为我们依赖于仅对该索引进行操作的git命令。
- git.index.util.git_working_dir(func: Callable[[...], _T]) Callable[[...], _T]
修饰符,它将当前工作目录更改为GIT存储库之一,以确保正确处理相对路径。
- git.index.util.post_clear_cache(func: Callable[[...], _T]) Callable[[...], _T]
使用git命令更改索引的函数的修饰符。
当git命令更改索引时,这将使我们可能已有的条目字典失效,这就是为什么必须删除它以便稍后可以懒惰地重新读取它的原因。
GitCmd
- class git.cmd.Git(working_dir: None | str | PathLike[str] = None)
Git类管理与Git二进制文件的通信。
它为调用Git二进制文件提供了一个方便的接口,例如在::
g = Git( git_dir ) g.init() # calls 'git init' program rval = g.ls_files() # calls 'git ls-files' program
调试:
设置
GIT_PYTHON_TRACE
环境变量将命令的每次调用输出到stdout。将其值设置为
full
以查看有关返回值的详细信息。
- class AutoInterrupt(proc: None | Popen, args: Any)
进程包装器,用于在完成时终止包装的进程。
一旦存储的流程实例超出作用域,就会终止/中断该实例。它用于防止进程堆积,以防迭代器停止读取。
所有属性都连接到包含的Process对象。
重写Wait方法以执行自动状态代码检查并可能引发。
- __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
等待进程并返回其状态代码。
- 参数:
stderr -- 以前读取的stderr的值,以防stderr已经关闭。
- 警告:
如果使用输出管道或错误管道而不单独处理,则可能会死锁。
- 抛出:
git.exc.GitCommandError -- 如果返回状态不为0。
- class CatFileContentStream(size: int, stream: IO[bytes])
对象,表示返回对象内容的大小只读流。
它的行为类似于流,但计算读取的数据,并在大小为空的内容区域为空时模拟空流。
如果不是所有数据都被读取到对象生命周期的末尾,我们将读取其余数据以确保底层流继续工作。
- __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'
提供git可执行文件的完整路径。否则,它假定git在可执行文件搜索路径中。
- 注意事项:
Git可执行文件实际上是在顶层的刷新步骤中找到的
__init__
。也可以通过显式调用git.refresh()
。
- GIT_PYTHON_TRACE = False
启用对GitPython的git命令的调试。
- USE_SHELL: bool = False
已弃用。如果设置为
True
,在执行git命令时将使用Shell。使用以下代码的代码
USE_SHELL = True
否则就会过去shell=True
任何GitPython函数都应更新为使用默认值False
取而代之的是。True
除非充分考虑和考虑Shell程序特殊处理的语法的影响,否则是不安全的,而这在大多数情况下是不可能的。正如下面详细说明的那样,它也不再需要,即使在过去也是如此。在许多情况下,如果不是大多数情况下,它是应用程序要设置的命令注入漏洞
USE_SHELL
至True
。任何攻击者,可以使巧尽心思构建的文本片段进入任何git命令的任何参数的任何部分(包括路径、分支名称等)。可导致Shell读写任意文件并执行任意命令。未经授权的输入还可能意外包含特殊的Shell语法,从而导致意外故障。此外,一个价值如何
True
与GitPython操作的某些方面的交互没有精确指定,并且可能会在没有警告的情况下更改,即使在GitPython4.0.0之前的情况下USE_SHELL
可能会被移除。这包括:GitPython是否或如何自动自定义Shell环境。
是否在Windows之外(在哪里
subprocess.Popen
即使在以下情况下也支持单独参数列表shell=True
),它可以与任何GitPython功能一起使用,而不是直接调用execute()
方法。是否有任何运行git命令的GitPython功能曾试图部分清理Shell可能会特殊处理的数据。目前还没有做到这一点。
在GitPython2.0.8之前,这仅限于抑制图形Windows应用程序中的控制台窗口。在2.0.8及更高版本中,它没有提供任何好处,因为GitPython通过使用
CREATE_NO_WINDOW
Windows上的进程创建标志。由于Windows路径搜索会根据是否使用Shell而略有不同,因此在极少数情况下将此更改为
True
至False
可能会阻止找到不寻常的GIT“可执行文件”,例如批处理文件。若要解决此问题,请在GIT_PYTHON_GIT_EXECUTABLE
环境变量,或将完整路径传递到git.refresh()
(或使用.exe
Shim)。进一步阅读:
- __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
为子命令调用的git可执行文件指定命令行选项。
- 参数:
kwargs -- 关键字参数词典。这些参数按如下方式传递
_call_process()
,但将传递给git命令而不是子命令。
示例:
git(work_tree='/tmp').difftool()
- __getattr__(name: str) Any
一个方便的方法,因为它允许调用命令,就像它是一个对象一样。
- 返回:
将执行调用的可调用对象
_call_process()
带着你的论点。
- __getattribute__(name: str) Any
返回getattr(self,name)。
- __getstate__() Dict[str, Any]
泡菜的帮手。
- __init__(working_dir: None | str | PathLike[str] = None) None
使用以下命令初始化此实例:
- 参数:
working_dir -- 我们应该在其中工作的Git目录。如果
None
,我们始终在由返回的当前目录中工作os.getcwd()
。这将是工作树目录(如果可用),或者.git
如果是裸库,则为目录。
- __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
- classmethod check_unsafe_options(options: List[str], unsafe_options: List[str]) None
检查是否有不安全的选项。
传递到的一些选项
git <command>
可用于执行任意命令。默认情况下,这些是被阻止的。
- classmethod check_unsafe_protocols(url: str) None
检查不安全协议。
除了常见的协议(http、git、ssh)之外,Git还允许具有以下形式的“远程助手”
<transport>::<address>
。这些帮手中的一个 (ext::
)可以用来调用任何任意命令。请参见:
- custom_environment(**kwargs: Any) Iterator[None]
围绕以上内容的上下文管理器
update_environment()
方法,以便在操作后将环境恢复到其以前的状态。示例:
with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'): repo.remotes.origin.fetch()
- 参数:
kwargs -- 看见
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
处理命令的执行,消费并返回返回的信息(Stdout)。
- 参数:
command -- 要执行的命令参数列表。它应该是一个程序参数序列,或一个字符串。要执行的程序是args序列或字符串中的第一项。
istream -- 传递给的标准输入文件句柄
subprocess.Popen
。with_extended_output -- 是否返回(Status,stdout,stderr)元组。
with_exceptions -- 当git返回非零状态时是否引发异常。
as_process -- 是否直接返回创建的可按需读取流的流程实例。这将呈现 with_extended_output 和 with_exceptions 无效-呼叫者将不得不处理细节。需要注意的是,该进程将被放入
AutoInterrupt
一旦超出范围,将中断进程的包装器。如果在迭代器中使用该命令,则应该传递整个流程实例,而不是单个流。output_stream -- 如果设置为类似文件的对象,则git命令生成的数据将被复制到给定流,而不是作为字符串返回。此功能仅在以下情况下才有效 as_process 是
False
。stdout_as_string -- 如果
False
,则该命令的标准输出将是字节。否则,它将被解码为使用默认编码(通常为UTF-8)的字符串。如果输出包含二进制数据,则后者可能失败。kill_after_timeout -- 指定git命令的超时时间(以秒为单位),在超时后应终止进程。在以下情况下,这将不起作用 as_process 设置为
True
。它被设置为None
默认情况下,并将允许进程运行,直到显式指定超时。由于以下限制,应慎重考虑此功能的用法:1.Windows完全不支持此功能。2.有效性可能因操作系统而异。ps --ppid
用于枚举子进程,这在大多数GNU/Linux系统上都可用,但在大多数其他系统上不可用。3.更深的后代不会收到信号,尽管它们有时可能会因为其父进程被终止而终止。4. kill_after_timeout 用途SIGKILL
,这可能会对存储库产生负面影响。例如,在以下情况下使用过时的锁 git-gc(1) 可能会使存储库无法接受更改,直到手动移除锁定。with_stdout -- 如果
True
,默认True
,我们在创建的进程上打开stdout。universal_newlines -- 如果
True
,管道将以文本形式打开,并在所有已知的行尾拆分行。shell -- 是否通过Shell调用命令(请参见
Popen(..., shell=True)
)。如果这不是None
,它会覆盖USE_SHELL
。传球shell=True
应避免使用此函数或任何其他GitPython函数,因为它在大多数情况下都是不安全的。这是因为完全考虑和说明Shell扩展的影响通常是不可行的,尤其是在传递shell=True
传递给其他方法,将其转发到Git.execute()
。传球shell=True
也不再需要(也不再有用)来解决任何已知的操作系统特定问题。env -- 要传递到的环境变量的字典
subprocess.Popen
。max_chunk_size -- 对象的数据块中的最大字节数。 output_stream 在一次调用其
write()
方法。如果给定的数字不是正数,则使用缺省值。strip_newline_in_stdout -- 是否剥离拖尾
\n
命令stdout的。subprocess_kwargs -- 要传递给的关键字参数
subprocess.Popen
。请注意,此方法已经设置了一些有效的kwarg;您指定的kwarg可能不同。
- 返回:
字符串(输出),如果 extended_output 是
False
(默认)元组(int(状态),str(Stdout),str(Stderr)),如果 extended_output 是
True
如果 output_stream 是
True
,标准输出值将是您的输出流:输出流,如果 extended_output 是
False
数组(int(状态),outputstream,str(Stderr)),如果 extended_output 是
True
请注意,执行git时使用
LC_MESSAGES="C"
以确保一致的输出,而不考虑系统语言。- 抛出:
- 注意事项:
如果向此方法的签名添加其他关键字参数,则必须更新
execute_kwargs
变量安装在此模块中。
- get_object_data(ref: str) Tuple[str, str, int, bytes]
类似于
get_object_header()
,但也会返回对象数据。- 返回:
(HEXSHA,TYPE_STRING,SIZE_AS_INT,Data_STRING)
- 注意事项:
而不是线程安全。
- get_object_header(ref: str) Tuple[str, str, int]
使用此方法可以快速检查给定引用后面的对象的类型和大小。
- 注意事项:
该方法只需要调用一次命令,并在后续调用中重复使用该命令。
- 返回:
(HEXSHA,TYPE_STRING,大小_AS_INT)
- git_exec_name = 'git'
应该在Linux、Windows和其他系统上工作的默认git命令。
- classmethod is_cygwin() bool
- classmethod polish_url(url: str, is_cygwin: Literal[False] = None) str
- classmethod polish_url(url: str, is_cygwin: None | bool = None) str
删除要写入配置文件的URL中的任何反斜杠。
Windows可能会创建包含带反斜杠的路径的配置文件,但Git不再喜欢它们,因为它会转义反斜杠。因此,为了确保安全,我们取消了逃逸。
- re_unsafe_protocol = re.compile('(.+)::.+')
- classmethod refresh(path: None | str | PathLike[str] = None) bool
更新有关git可执行文件的信息
Git
对象将使用的。由
git.refresh()
顶层功能__init__
。- 参数:
path -- Git可执行文件的可选路径。如果不是绝对的,则相对于当前目录立即进行解析。(请参阅下面的注释。)
- 注意事项:
最高层
git.refresh()
应该是首选的,因为它调用此方法并可能相应地更新其他状态。- 注意事项:
有三种不同的方法可以指定刷新导致GIT使用的命令:
通过编号 path 参数,并且不要将
GIT_PYTHON_GIT_EXECUTABLE
环境变量。命令名git
使用的是。在每次运行命令时,系统都会在路径搜索中查找它(与运行时查找git的方式大致相似git
手动命令)。这通常是所需的行为。通过编号 path 参数,但将
GIT_PYTHON_GIT_EXECUTABLE
环境变量。使用作为该变量的值给出的命令。这可能是简单的命令,也可能是任意路径。在每次运行命令时都会查找它。设置GIT_PYTHON_GIT_EXECUTABLE
至git
与不设置它具有相同的效果。传递一个 path 争论。此路径(如果不是绝对路径)将相对于当前目录立即解析。此分辨率在刷新时发生。当运行git命令时,它们将使用先前解析的路径运行。如果一个 path 参数传递后,
GIT_PYTHON_GIT_EXECUTABLE
未参考环境变量。
- 注意事项:
刷新始终会设置
Git.GIT_PYTHON_GIT_EXECUTABLE
属性,该属性可以在Git
类或其任何实例来检查使用了什么命令来运行git。此属性不应与相关的GIT_PYTHON_GIT_EXECUTABLE
环境变量。无论如何执行刷新,都会设置类属性。
- set_persistent_git_options(**kwargs: Any) None
为后续的子命令调用指定git可执行文件的命令行选项。
- 参数:
kwargs -- 关键字参数词典。这些参数按如下方式传递
_call_process()
,但将传递给git命令而不是子命令。
- stream_object_data(ref: str) Tuple[str, str, int, CatFileContentStream]
类似于
get_object_data()
,但将数据作为流返回。- 返回:
(HEXSHA,TYPE_STRING,大小_AS_INT,STREAM)
- 注意事项:
此方法不是ThreadSafe。你需要一个独立的
Git
每个线程的实例是安全的!
- 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]
将Python样式的kwargs转换为git命令行选项。
- update_environment(**kwargs: Any) Dict[str, str | None]
为将来的git调用设置环境变量。以可以传递回此函数以恢复更改的格式返回所有更改的值。
示例:
old_env = self.update_environment(PWD='/tmp') self.update_environment(**old_env)
- 参数:
kwargs -- 用于git进程的环境变量。
- 返回:
将环境变量映射到其旧值的字典
- property version_info: Tuple[int, ...]
- 返回:
元组,其中包含表示从中分析的主要、次要和附加版本号的整数 git-version(1) 。最多可使用四个字段。该值是按需生成并缓存的。
- property working_dir: None | str | PathLike[str]
- 返回:
我们正在处理的Git目录
- git.cmd.GitMeta
的别名
Git
的元类,无论它是type
或自定义元类。无论是
Git
类的默认设置为type
因为它的元类或使用自定义元类,所以没有文档记录,并且可能随时更改。此可静态检查的元类别名在运行时等效于type(Git)
。这几乎永远不应该使用。受益于它的代码即使被使用,也可能仍然脆弱。鉴于
Git
类的预期用途和Git
对象的动态可调用属性表示git子命令,因此从Git
完全没有。vbl.使用Git
在多重继承中,正确地进行继承可能特别棘手。尝试使用Git
如果它的元类是相关的,例如当兄弟类具有不相关的元类,并且可能必须引入共享的下限元类来解决元类冲突时,不建议这样做。
配置
用于读写配置文件的解析器。
- git.config.GitConfigParser
GitConfigParser
的别名
- class git.config.SectionConstraint(config: T_ConfigParser, section: str)
将ConfigParser约束为仅选项命令,这些命令被约束为始终使用我们初始化时使用的节。
它支持对选项进行操作的所有ConfigParser方法。
- 注意事项:
如果用作上下文管理器,将释放包装的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')
- property config: T_ConfigParser
返回:我们约束的ConfigParser实例
- release() None
相当于
GitConfigParser.release()
,它在我们的底层解析器实例上调用。
微分
- class git.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和b。成员的前缀分别为“a”和“b”,以表示这一点。
Diffs保留有关更改的BLOB对象、文件模式、重命名、删除和新文件的信息。
在少数情况下,
None
必须作为成员变量值:新文件::
a_mode is None a_blob is None a_path is None
已删除文件::
b_mode is None b_blob is None b_path is None
工作树BLOB:
当与工作树进行比较时,工作树BLOB将具有空的十六进制,因为对应的对象尚不存在。模式也将为空。不过,这条路径将是可用的。
如果它列在diff中,则文件的工作树版本必须与索引或树中的版本不同,因此已被修改。
- 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
返回self==值。
- __hash__() int
返回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
返回自我!=值。
- __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
返回str(Self)。
- a_blob: 'IndexObject' | None
- a_mode
- property a_path: str | None
- a_rawpath
- b_blob: 'IndexObject' | None
- b_mode
- property b_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)
- property rename_from: str | None
- property rename_to: str | None
- property renamed: bool
已弃用,请使用
renamed_file
取而代之的是。- 返回:
True
如果我们的diff的斑点已重命名- 注意事项:
此属性已弃用。请使用
renamed_file
属性而不是。
- property renamed_file: bool
- 返回:
True
如果我们的diff的斑点已重命名
- score
- class git.diff.DiffConstants(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)
的特殊对象
Diffable.diff()
。请参阅
Diffable.diff()
方法的other
参数,该参数接受各种值,包括这些值。- INDEX = 2
替身,表明您想要与索引不同。
也可访问为
git.INDEX
,git.diff.INDEX
,以及Diffable.INDEX
,以及Diffable.Index
。后者被保留是为了向后兼容,并为此做了一个别名,因此它仍然可能被使用。
- NULL_TREE = 1
替身指示您要与Diffs中的空树进行比较。
也可访问为
git.NULL_TREE
,git.diff.NULL_TREE
,以及Diffable.NULL_TREE
。
- __module__ = 'git.diff'
- class git.diff.DiffIndex(iterable=(), /)
Diffs的索引,允许列出
Diff
S要通过diff属性进行查询。这个类提高了diff处理的便利性。
- __annotations__ = {}
- __dict__ = mappingproxy({'__module__': 'git.diff', '__doc__': 'An index for diffs, allowing a list of :class:`Diff`\\s to be queried by the diff\n properties.\n\n The class improves the diff handling convenience.\n ', 'change_type': ('A', 'C', 'D', 'R', 'M', 'T'), 'iter_change_type': <function DiffIndex.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__
对象的弱引用列表
- change_type = ('A', 'C', 'D', 'R', 'M', 'T')
更改类型不变量标识Blob可能发生更改的可能方式:
A
=已添加D
=已删除R
=已重命名M
=已修改T
=更改了类型
- iter_change_type(change_type: Literal['A', 'D', 'C', 'M', 'R', 'T', 'U']) Iterator[T_Diff]
- 返回:
迭代器屈服
Diff
与给定的 change_type- 参数:
change_type -- 成员:
DiffIndex.change_type
,即: * 'A' for added paths * 用于已删除路径的‘d’ * 'R' for renamed paths * M‘表示已修改数据的路径*’T‘表示类型路径中已更改的数据
- class git.diff.Diffable
可以与兼容类型的另一个对象不同的所有对象的公共接口。
- INDEX = 2
替身,表明您想要与索引不同。
请参阅
diff()
方法,该方法将其作为其other
参数。这与
DiffConstants.INDEX
,也可以通过以下方式访问git.INDEX
和git.diff.INDEX
,以及Diffable.INDEX
,保留它是为了向后兼容(现在将其定义为它的别名)。
- Index = 2
指示您要与索引不同的替身(与
INDEX
)。这是的别名
INDEX
,以实现向后兼容。看见INDEX
和diff()
了解更多细节。- 注意事项:
尽管它总是作为不透明常量使用,但它以前被定义为类。它的用法没有改变,但试图只允许此对象的静态类型批注必须更改,以避免新的类型错误。然而,这在以前是不可能做到的
Type[Diffable.Index]
近似地。现在可以精确地执行操作,使用Literal[DiffConstants.INDEX]
。
- NULL_TREE = 1
替身指示您要与Diffs中的空树进行比较。
请参阅
diff()
方法,该方法将其作为其other
参数。这与
DiffConstants.NULL_TREE
,也可以通过以下方式访问git.NULL_TREE
和git.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
在树、树和索引或索引和工作树这两个项之间创建差异。自动检测重命名。
- 参数:
other -- 这就是我们要比较的项目。 * If
None
, we will be compared to the working tree. * 如果一个Tree_ish
或字符串,则将其与相应的树进行比较。 * IfINDEX
, it will be compared against the index. * 如果NULL_TREE
,它将与空树进行比较。此参数默认为INDEX
(而不是None
),以便该方法在缺省情况下不会在裸存储库上失败。paths -- 这是要限制差异的路径列表或单个路径。它将仅包括至少一条或多条给定路径。
create_patch -- 如果
True
,归来的Diff
包含一个详细的补丁,如果应用该补丁,将使自己成为他人的补丁。由于必须读取和区分斑点,因此补丁的成本较高。kwargs -- 传递到的其他参数 git-diff(1) ,例如
R=True
互换分歧的两面。
- 返回:
A
DiffIndex
表示计算出的差异。- 注意事项:
在一个空储存库上, other 需要以下列形式提供
INDEX
,或作为Tree
或Commit
,否则将出现GIT命令错误。
- git.diff.INDEX: Literal[DiffConstants.INDEX] = DiffConstants.INDEX
替身,表明您想要与索引不同。
看见
Diffable.diff()
,它将此作为其other
参数。这是的别名
DiffConstants.INDEX
,也可以通过以下方式访问git.INDEX
和Diffable.INDEX
,以及Diffable.Index
。
- git.diff.NULL_TREE: Literal[DiffConstants.NULL_TREE] = DiffConstants.NULL_TREE
替身指示您要与Diffs中的空树进行比较。
看见
Diffable.diff()
,它将此作为其other
参数。这是的别名
DiffConstants.NULL_TREE
,也可以通过以下方式访问git.NULL_TREE
和Diffable.NULL_TREE
。
例外情况
在整个GIT包中引发的异常。
- exception git.exc.BadName
无法理解提供给rev_parse的名称
- __annotations__ = {}
- __module__ = 'gitdb.exc'
- __str__()
返回str(Self)。
- exception git.exc.BadObject
具有给定SHA的对象不存在。使用失败的SHA实例化
- __annotations__ = {}
- __module__ = 'gitdb.exc'
- __str__()
返回str(Self)。
- exception git.exc.CacheError
与git索引相关的所有错误的base,在内部称为“缓存”。
- __annotations__ = {}
- __module__ = 'git.exc'
- exception git.exc.CheckoutError(message: str, failed_files: Sequence[str | os.PathLike[str]], valid_files: Sequence[str | os.PathLike[str]], failed_reasons: List[str])
如果文件因包含更改而无法从索引中签出,则抛出。
这个
failed_files
属性包含无法签出的相对路径的列表,因为它们包含索引中不存在的更改。这个
failed_reasons
属性包含一个字符串,该字符串通知问题的实际原因。这个
valid_files
属性包含文件的相对路径列表,这些文件已成功签出,因此与索引中存储的版本匹配。- __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
返回str(Self)。
- exception git.exc.CommandError(command: List[str] | Tuple[str, ...] | str, status: str | int | None | Exception = None, stderr: bytes | str | None = None, stdout: bytes | str | None = None)
的每个阶段引发的异常的基类。
Popen
行刑。- 参数:
command -- 组成命令行的一个非空的argv列表。
- __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
返回str(Self)。
- exception git.exc.GitCommandError(command: List[str] | Tuple[str, ...] | str, status: str | int | None | Exception = None, stderr: bytes | str | None = None, stdout: bytes | str | None = None)
如果执行git命令失败并返回非零状态代码,则抛出。
- __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'
- exception git.exc.GitCommandNotFound(command: List[str] | Tuple[str] | str, cause: str | Exception)
如果我们找不到
git
中的可执行文件PATH
或在由GIT_PYTHON_GIT_EXECUTABLE
环境变量。- __annotations__ = {}
- __init__(command: List[str] | Tuple[str] | str, cause: str | Exception) None
- __module__ = 'git.exc'
- exception git.exc.GitError
所有包异常的基类。
- __annotations__ = {}
- __module__ = 'git.exc'
- __weakref__
对象的弱引用列表
- exception git.exc.HookExecutionError(command: List[str] | Tuple[str, ...] | str, status: str | int | None | Exception, stderr: bytes | str | None = None, stdout: bytes | str | None = None)
如果钩子以非零退出代码退出,则抛出。
这提供了对退出代码和通过标准输出返回的字符串的访问。
- __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'
- exception git.exc.InvalidDBRoot
如果无法在给定路径上初始化对象数据库,则抛出
- __annotations__ = {}
- __module__ = 'gitdb.exc'
- exception git.exc.InvalidGitRepositoryError
如果给定的存储库似乎具有无效的格式,则抛出。
- __annotations__ = {}
- __module__ = 'git.exc'
- exception git.exc.NoSuchPathError
如果系统无法访问路径,则抛出。
- __annotations__ = {}
- __module__ = 'git.exc'
- __weakref__
对象的弱引用列表
- exception git.exc.ODBError
对象数据库引发的所有错误
- __annotations__ = {}
- __module__ = 'gitdb.exc'
- __weakref__
对象的弱引用列表
- exception git.exc.RepositoryDirtyError(repo: Repo, message: str)
每当存储库上的操作失败时抛出,因为它具有将被覆盖的未提交更改。
- __annotations__ = {}
- __module__ = 'git.exc'
- __str__() str
返回str(Self)。
- exception git.exc.UnmergedEntriesError
如果操作无法继续,因为缓存中仍有未合并的条目,则抛出。
- __annotations__ = {}
- __module__ = 'git.exc'
- exception git.exc.UnsafeOptionError
如果在未显式允许的情况下传递不安全选项,则引发。
- __annotations__ = {}
- __module__ = 'git.exc'
- exception git.exc.UnsafeProtocolError
如果在未显式允许的情况下传递不安全协议,则抛出。
- __annotations__ = {}
- __module__ = 'git.exc'
Refs.symbolic
- class git.refs.symbolic.SymbolicReference(repo: Repo, path: str | os.PathLike[str], check_path: bool = False)
具有象征性的引用的特殊情况。
这不是指向特定的提交,而是指向另一个
Head
,它本身指定提交。符号引用的一个典型示例是
HEAD
。- __annotations__ = {'reference': typing.Union[ForwardRef('Head'), ForwardRef('TagReference'), ForwardRef('RemoteReference'), ForwardRef('Reference')]}
- __eq__(other: object) bool
返回self==值。
- __hash__() int
返回hash(Self)。
- __module__ = 'git.refs.symbolic'
- __ne__(other: object) bool
返回自我!=值。
- __repr__() str
返回epr(Self)。
- __slots__ = ('repo', 'path')
- __str__() str
返回str(Self)。
- property abspath: str | PathLike[str]
- classmethod create(repo: Repo, path: str | os.PathLike[str], reference: SymbolicReference | str = 'HEAD', logmsg: str | None = None, force: bool = False, **kwargs: Any) T_References
创建新的符号引用:指向另一个引用的引用。
- 参数:
repo -- 要在其中创建引用的存储库。
path -- 应创建新符号引用的完整路径,例如
NEW_HEAD
或symrefs/my_new_symref
。reference -- 新符号引用应指向的引用。如果它是提交式的,则符号引用将被分离。
force -- 如果
True
,强制创建,即使具有该名称的符号引用已存在。加薪OSError
否则的话。logmsg -- 如果不是
None
,要追加到reflog的消息。如果None
,则不写入任何引用日志条目。
- 返回:
新建的符号引用
- 抛出:
OSError -- 如果名称相同但内容不同的(符号)引用已存在。
- 注意事项:
这不会改变当前的头、索引或工作树。
- classmethod delete(repo: Repo, path: str | os.PathLike[str]) None
删除给定路径处的引用。
- 参数:
repo -- 要从中删除引用的存储库。
path -- 指向引用的短路径或完整路径,例如
refs/myreference
或者只是myreference
,因此refs/
是隐含的。或者,要删除的符号引用。
- classmethod dereference_recursive(repo: Repo, ref_path: str | os.PathLike[str] | None) str
- 返回:
HexSHA存储在给定的引用中 ref_path ,根据需要递归取消引用所有中间引用
- 参数:
repo -- 包含位于的引用的存储库 ref_path 。
- classmethod from_path(repo: Repo, path: str | os.PathLike[str]) T_References
从路径进行符号引用。
- 参数:
path -- 饱满
.git
-要实例化的引用的目录相对路径名。- 注意事项:
使用
to_full_path()
如果您只有已知引用类型的部分路径。- 返回:
- property is_detached: bool
- 返回:
True
如果我们是分离的引用,则指向特定的提交,而不是指向另一个引用。
- is_remote() bool
- 返回:
如果此符号引用指向远程分支,则为True
- is_valid() bool
- 返回:
True
如果引用有效,则它可以被读取并指向有效的对象或引用。
- classmethod iter_items(repo: Repo, common_path: str | os.PathLike[str] | None = None, *args: Any, **kwargs: Any) Iterator[T_References]
在存储库中查找所有引用。
- 参数:
repo -- 这个
Repo
。common_path -- 要由所有返回的引用对象共享的路径的可选关键字参数。如果出现以下情况,则默认为类特定部分
None
,确保只返回适合实际类的引用。
- 返回:
一份名单
SymbolicReference
,每个都保证是一个不分离的符号引用,并指向有效的引用。该列表是按词典顺序排序的。返回的对象是具体子类的实例,例如Head
或TagReference
。
- log() RefLog
- 返回:
RefLog
以供参考。其最后一个条目反映了应用于此引用的最新更改。- 注意事项:
由于每次都会解析日志,因此建议将其缓存以供使用,而不是重复调用此方法。应将其视为只读。
- log_append(oldbinsha: bytes, message: str | None, newbinsha: bytes | None = None) RefLogEntry
将日志条目追加到此引用的日志文件中。
- 参数:
oldbinsha -- 此裁判过去常指向的二进制SHA。
message -- 描述更改的消息。
newbinsha -- 裁判指的是现在的沙阿。如果没有,将使用我们当前的提交SHA。
- 返回:
增加的
RefLogEntry
举个例子。
- log_entry(index: int) RefLogEntry
- 返回:
RefLogEntry
在给定索引处- 参数:
index -- 与Python列表兼容的正索引或负索引。
- 注意事项:
此方法必须在执行期间读取部分reflog,因此应谨慎使用,或者仅在只需要一个索引的情况下使用。在这种情况下,它将比
log()
方法。
- property name: str
- 返回:
在符号引用的情况下,最短的可假定名称是路径本身。
- path
- property ref: SymbolicReference
返回我们指向的引用
- property reference: SymbolicReference
返回我们指向的引用
- rename(new_path: str | PathLike[str], force: bool = False) SymbolicReference
将自身重命名为新路径。
- 参数:
new_path -- 可以是简单名称,也可以是完整路径。
new_name
或features/new_name
。前缀refs/
暗示用于参考,并将根据需要进行设置。如果这是一个符号引用,则没有隐含的前缀。force -- 如果
True
,即使具有目标名称的头已存在,重命名也将成功。在这种情况下,它将被覆盖。
- 返回:
自性
- 抛出:
OSError -- 如果位于路径但具有不同内容的文件已存在。
- repo
- set_commit(commit: Commit | SymbolicReference | str, logmsg: str | None = None) SymbolicReference
喜欢
set_object()
,但将对象类型限制为Commit
。- 抛出:
ValueError -- 如果 commit 不是一个
Commit
对象,它也不指向提交。- 返回:
自性
- set_object(object: Commit | Tree | TagObject | Blob | SymbolicReference | str, logmsg: str | None = None) SymbolicReference
设置我们指向的对象,可能首先取消对符号引用的引用。如果引用不存在,则会创建它。
- 参数:
object -- 一个反射镜,一个
SymbolicReference
或者是一个Object
举个例子。 *SymbolicReference
instances will be dereferenced beforehand to obtain the git object they point to. *Object
实例必须表示Git对象 (AnyGitObject
)。logmsg -- 如果不是
None
,该消息将用于要写入的引用日志条目中。否则,REFLOG不会改变。
- 注意事项:
平地
SymbolicReference
按照惯例,实例可能并不实际指向对象。- 返回:
自性
- set_reference(ref: Commit | Tree | TagObject | Blob | SymbolicReference | str, logmsg: str | None = None) SymbolicReference
把我们自己设定在给定的位置 ref 。
它将仍然是一个符号,如果 ref 是一种
Reference
。否则为Git对象,指定为
Object
假定为实例或refSpec。如果它有效,则此引用将被设置为它,这将有效地分离引用(如果它是纯符号引用)。- 参数:
ref -- A
SymbolicReference
实例,则会引发Object
实例(具体地说是一个AnyGitObject
),或refspecc字符串。只有当裁判是SymbolicReference
实例,我们将指向它。其他所有内容都被取消引用,以获得实际对象。logmsg -- 如果设置为字符串,消息将在引用日志中使用。否则,不会为更改的引用写入引用日志条目。条目的前一次提交将是我们现在指向的提交。另见:
log_append()
- 返回:
自性
- 注意事项:
不会取消对此符号引用的引用。有关这一点,请参见
set_object()
。
- classmethod to_full_path(path: str | PathLike[str] | SymbolicReference) str | PathLike[str]
- 返回:
具有完整的存储库相对路径的字符串,可用于初始化
Reference
例如,通过使用Reference.from_path
。
Refs.reference
- class git.refs.reference.Reference(repo: Repo, path: str | os.PathLike[str], check_path: bool = True)
对任何对象的命名引用。
子类可以应用限制,例如,
Head
只能指向提交。- __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
初始化此实例。
- 参数:
repo -- 我们的上级储存库。
path -- 相对于
.git/
指向相关引用的目录,例如refs/heads/master
。check_path -- 如果
False
,您可以提供任何路径。否则,路径必须以此类型的默认路径前缀开头。
- __module__ = 'git.refs.reference'
- __parameters__ = ()
- __slots__ = ()
- __str__() str
返回str(Self)。
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- classmethod iter_items(repo: Repo, common_path: str | os.PathLike[str] | None = None, *args: Any, **kwargs: Any) Iterator[T_References]
相当于
SymbolicReference.iter_items
,但也将返回非分离的引用。
- property name: str
- 返回:
此引用的(最短)名称-它可以包含路径组件
- property remote_head: _T
- property remote_name: _T
Refs.head
一些基于参照的对象。
- class git.refs.head.HEAD(repo: Repo, path: str | os.PathLike[str] = 'HEAD')
A的特殊情况
SymbolicReference
表示存储库的头引用。- __annotations__ = {'commit': 'Commit'}
- __module__ = 'git.refs.head'
- __slots__ = ()
- orig_head() SymbolicReference
- 返回:
SymbolicReference
指向orig_head,它被维护为包含先前的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
将我们的头重置为给定的COMMIT,也可以选择同步索引和工作树。我们引用的引用也将设置为Commit。
- 参数:
index -- 如果
True
,则索引将被设置为与给定的提交匹配。否则不会有人碰它。working_tree -- 如果
True
,工作树将被强制调整以匹配给定的提交,可能会在没有警告的情况下覆盖未提交的更改。如果 working_tree 是True
, index 一定是True
也是。paths -- 相对于要重置的Git根目录的单个路径或路径列表。这允许部分重置单个文件。
kwargs -- 传递到的其他参数 git-reset(1) 。
- 返回:
自性
- class git.refs.head.Head(repo: Repo, path: str | os.PathLike[str], check_path: bool = True)
标头是对
Commit
。每个Head实例都包含一个名称和一个Commit
对象。示例:
>>> 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__': 'A Head is a named reference to a :class:`~git.objects.commit.Commit`. Every Head\n instance contains a name and a :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(<function Head.delete>)>, 'set_tracking_branch': <function Head.set_tracking_branch>, 'tracking_branch': <function Head.tracking_branch>, 'rename': <function Head.rename>, 'checkout': <function Head.checkout>, '_config_parser': <function Head._config_parser>, 'config_reader': <function Head.config_reader>, 'config_writer': <function Head.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_data object>, '__annotations__': {'path': 'str', 'reference': "Union['Head', 'TagReference', 'RemoteReference', 'Reference']", '_id_attribute_': 'str'}})
- __module__ = 'git.refs.head'
- __parameters__ = ()
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- __weakref__
对象的弱引用列表
- checkout(force: bool = False, **kwargs: Any) HEAD | Head
通过将Head设置为该引用、通过更新索引以反映我们所指向的树以及通过更新工作树以反映最新的索引来检查此Head。
如果更改的工作树文件将被覆盖,则该命令将失败。
- 参数:
force -- 如果
True
,对索引和工作树的更改将被丢弃。如果False
,GitCommandError
将在这种情况下被提出。kwargs -- 要传递给Git签出的其他关键字参数,例如
b="new_branch"
在给定点创建一个新的分支。
- 返回:
检出操作后的活动分支,通常为自身分支,除非已创建新分支。如果没有活动分支,因为Head现在被分离,则将改为返回Head引用。
- 注意事项:
默认情况下,它只允许检出磁头--其他任何东西都将使磁头分离(这是允许的,也是可能的),但仍是一些工具可能无法处理的特殊状态。
- config_reader() SectionConstraint[GitConfigParser]
- 返回:
被约束为仅读取此实例的值的配置分析器实例。
- config_writer() SectionConstraint[GitConfigParser]
- 返回:
对此头的选项具有读写访问权限的配置编写器实例。
- classmethod delete(repo: Repo, *heads: Head | str, force: bool = False, **kwargs: Any) None
删除给定的标题。
- 参数:
force -- 如果
True
,将删除头部,即使它们尚未合并到主要发展流中。默认False
。
- k_config_remote = 'remote'
- k_config_remote_ref = 'merge'
- rename(new_path: str | os.PathLike[str], force: bool = False) Head
将自身重命名为新路径。
- 参数:
new_path -- 可以是简单的名称,也可以是路径。
new_name
或features/new_name
。前缀refs/heads
是隐含的。force -- 如果
True
,即使具有目标名称的头已存在,重命名也将成功。
- 返回:
自性
- 注意事项:
尊重引用日志,因为使用了git命令。
- set_tracking_branch(remote_reference: RemoteReference | None) Head
配置此分支以跟踪给定的远程引用。这将相应地更改此分支的配置。
- 参数:
remote_reference -- 远程引用为Track或None以取消跟踪任何引用。
- 返回:
自性
- tracking_branch() RemoteReference | None
- 返回:
我们正在跟踪的远程引用,或
None
如果我们不是跟踪分支机构的话。
Refs.tag
提供了一种 Reference
-基于轻量级标记的类型。
这定义了 TagReference
类(及其别名 Tag
),它代表轻量级标记。有关带注释的标记(是Git对象),请参阅 git.objects.tag
模块。
- git.refs.tag.Tag
TagReference
的别名
- class git.refs.tag.TagReference(repo: Repo, path: str | os.PathLike[str], check_path: bool = True)
指向提交、标记对象或任何其他对象的轻量级标记引用。在后一种情况下,可以获得附加信息,如签名或标签创建者。
此标记对象将始终指向提交对象,但可能在标记对象中携带附加信息::
tagref = TagReference.list_items(repo)[0] print(tagref.commit.message) if tagref.tag is not None: 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)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- classmethod create(repo: Repo, path: str | os.PathLike[str], reference: str | SymbolicReference = 'HEAD', logmsg: str | None = None, force: bool = False, **kwargs: Any) TagReference
创建一个新的标记引用。
- 参数:
repo -- 这个
Repo
要在中创建标记,请执行以下操作。path -- 标记的名称,例如
1.0
或releases/1.0
。前缀refs/tags
是隐含的。reference -- 引用
Object
你想贴上标签。引用的对象可以是提交、树或BLOB。logmsg -- 如果不是
None
,该消息将用于您的Tag对象。这还将创建一个允许获取该信息的附加标记对象,例如::tgref.tag。message -- 的同义词 logmsg 参数。包括它是为了向后兼容。 logmsg 如果两项都通过,则优先。
force -- 如果
True
,强制创建标记,即使该标记已存在。kwargs -- 要传递给的其他关键字参数 git-tag(1) 。
- 返回:
一种新的
TagReference
。
- classmethod delete(repo: Repo, *tags: TagReference) None
删除给定的一个或多个现有标记。
Refs.remote
实现远程对象的模块,允许轻松访问GIT远程。
- class git.refs.remote.RemoteReference(repo: Repo, path: str | os.PathLike[str], check_path: bool = True)
指向远程头部的引用。
- __abstractmethods__ = frozenset({})
- __annotations__ = {'_id_attribute_': 'str', 'path': 'str', 'reference': "Union['Head', 'TagReference', 'RemoteReference', 'Reference']"}
- __module__ = 'git.refs.remote'
- __parameters__ = ()
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- classmethod create(*args: Any, **kwargs: Any) NoReturn
加薪
TypeError
。定义为create
方法已禁用。
- classmethod delete(repo: Repo, *refs: RemoteReference, **kwargs: Any) None
删除给定的远程引用。
- 注意事项:
kwargs 都是为了与基类方法的可比性,因为我们不应该缩小签名的范围。
- classmethod iter_items(repo: Repo, common_path: str | os.PathLike[str] | None = None, remote: Remote | None = None, *args: Any, **kwargs: Any) Iterator[RemoteReference]
迭代远程引用,如果给定,则将其约束到给定的远程。
Refs.log
- class git.refs.log.RefLog(filepath: str | os.PathLike[str] | None = None)
引用日志包含
RefLogEntry
S,其中每一个都定义了所讨论的头部的某种状态。自定义查询方法允许按日期或其他条件检索日志条目。重新开票条目是有序的。第一个添加的条目是列表中的第一个条目。最后一个条目,即标题或引用的最后更改,位于列表的最后。
- __abstractmethods__ = frozenset({})
- __annotations__ = {}
- __init__(filepath: str | os.PathLike[str] | None = None) None
使用可选的文件路径初始化该实例,我们将从该文件路径初始化数据。该路径还用于使用
write()
方法。
- __module__ = 'git.refs.log'
- __orig_bases__ = (typing.List[git.refs.log.RefLogEntry], <class 'git.objects.util.Serializable'>)
- __parameters__ = ()
- __slots__ = ('_path',)
- classmethod append_entry(config_reader: Actor | GitConfigParser | SectionConstraint | None, filepath: str | os.PathLike[str], oldbinsha: bytes, newbinsha: bytes, message: str, write: bool = True) RefLogEntry
在文件路径处将新的日志条目附加到revlog中。
- 参数:
config_reader -- 存储库的配置读取器-用于获取用户信息。也可能是一种
Actor
实例直接标识提交者,或者None
。filepath -- 日志文件的完整路径。
oldbinsha -- 上次提交的二进制SHA。
newbinsha -- 当前提交的二进制SHA。
message -- 描述对引用的更改的消息。
write -- 如果
True
,更改将立即写入。否则,将不会写入更改。
- 返回:
RefLogEntry
追加到日志的对象。- 注意事项:
因为我们是仅附加的,所以并发访问不是问题,因为我们不干扰读取器。
- classmethod entry_at(filepath: str | os.PathLike[str], index: int) RefLogEntry
- 返回:
RefLogEntry
在给定的索引处。- 参数:
filepath -- 要从中读取条目的索引文件的完整路径。
index -- Python列表兼容索引,即指定从列表末尾开始计数的条目可能为负数。
- 抛出:
IndexError -- 如果条目不存在。
- 注意事项:
此方法速度更快,因为它只解析索引处的条目,跳过所有其他行。尽管如此,如果索引为负值,则必须读取整个文件。
- classmethod from_file(filepath: str | os.PathLike[str]) RefLog
- 返回:
一种新的
RefLog
实例,该实例包含来自给定 filepath 。- 参数:
filepath -- 重做日志的路径。
- 抛出:
ValueError -- 如果文件无法读取或以某种方式损坏。
- classmethod iter_entries(stream: str | BytesIO | mmap) Iterator[RefLogEntry]
- 返回:
迭代器屈服
RefLogEntry
实例,从给定流中读取的每一行对应一个。- 参数:
stream -- 类似文件的对象,包含本机格式的revlog或指向要读取的文件的字符串实例。
- classmethod path(ref: SymbolicReference) str
- 返回:
将找到给定引用实例的引用日志的绝对路径的字符串。不过,不能保证该路径指向有效的文件。
- 参数:
ref --
SymbolicReference
实例
- to_file(filepath: str | os.PathLike[str]) None
将reflog实例的内容写入给定文件路径下的文件。
- 参数:
filepath -- 文件的路径。假定父目录存在。
- class git.refs.log.RefLogEntry(iterable=(), /)
命名元组,允许轻松访问RevLog数据字段。
- __annotations__ = {}
- __module__ = 'git.refs.log'
- __orig_bases__ = (typing.Tuple[str, str, git.util.Actor, typing.Tuple[int, int], str],)
- __parameters__ = ()
- __repr__() str
以git reflog格式表示我们自己。
- __slots__ = ()
- format() str
- 返回:
适合放置在reflog文件中的字符串。
- classmethod from_line(line: bytes) RefLogEntry
- 返回:
新的
RefLogEntry
实例从给定的revlog行。- 参数:
line -- 不带尾随换行符的行字节
- 抛出:
ValueError -- 如果 line 无法解析。
- property message: str
描述对引用执行的操作的消息。
- classmethod new(oldhexsha: str, newhexsha: str, actor: Actor, time: int, tz_offset: int, message: str) RefLogEntry
- 返回:
的新实例
RefLogEntry
- property newhexsha: str
更改后,引用现在指向的提交的XHYSHA。
- property oldhexsha: str
更改前引用指向的提交的XHXHA。
- property time: Tuple[int, int]
元组形式的时间:
[0] =
int(time)
[1] =
int(timezone_offset)
在……里面time.altzone
格式
远程的
实现远程对象的模块,允许轻松访问GIT远程。
- class git.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)
携带有关单个磁头的获取操作结果的信息::
info = remote.fetch()[0] info.ref # Symbolic Reference or RemoteReference to the changed # remote head or FETCH_HEAD info.flags # additional flags to be & with enumeration members, # i.e. info.flags & info.REJECTED # is 0 if ref is SymbolicReference info.note # additional notes given by git-fetch intended for the user info.old_commit # if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD, # field is set to the previous location of ref, otherwise None info.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
初始化新实例。
- __module__ = 'git.remote'
- __parameters__ = ()
- __slots__ = ('ref', 'old_commit', 'flags', 'note', 'remote_ref_path')
- __str__() str
返回str(Self)。
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- flags
- classmethod iter_items(repo: Repo, *args: Any, **kwargs: Any) NoReturn
查找(所有)此类型的项目。
子类可以指定 args 和 kwargs 不同,并且可以使用它们进行过滤。但是,如果在不使用其他位置参数或关键字参数的情况下调用该方法,则子类必须生成所有项。
- 返回:
迭代器产生项
- property name: str
- 返回:
我们的远程引用的名称
- note
- old_commit
- ref
- classmethod refresh() Literal[True]
更新有关哪些项目的信息 git-fetch(1) 所使用的git可执行文件支持标志。
由
git.refresh()
顶层功能__init__
。
- remote_ref_path
- class git.remote.PushInfo(flags: int, local_ref: SymbolicReference | None, remote_ref_string: str, remote: Remote, old_commit: str | None = None, summary: str = '')
携带有关单个磁头推送操作结果的信息::
info = remote.push()[0] info.flags # bitflags providing more information about the result info.local_ref # Reference pointing to the local reference that was pushed # It is None if the ref was deleted. info.remote_ref_string # path to the remote reference located on the remote side info.remote_ref # Remote Reference on the local side corresponding to # the remote_ref_string. It can be a TagReference as well. info.old_commit # commit at which the remote_ref was standing before we pushed # it to local_ref.commit. Will be None if an error was indicated info.summary # summary line providing human readable english text about the push
- 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
初始化新实例。
LOCAL_REF:Head|Head|RemoteReference|TagReference|Reference|SymbolicReference|无
- __module__ = 'git.remote'
- __parameters__ = ()
- __slots__ = ('local_ref', 'remote_ref_string', 'flags', '_old_commit_sha', '_remote', 'summary')
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- flags
- classmethod iter_items(repo: Repo, *args: Any, **kwargs: Any) NoReturn
查找(所有)此类型的项目。
子类可以指定 args 和 kwargs 不同,并且可以使用它们进行过滤。但是,如果在不使用其他位置参数或关键字参数的情况下调用该方法,则子类必须生成所有项。
- 返回:
迭代器产生项
- local_ref
- property remote_ref: RemoteReference | TagReference
- 返回:
远距
Reference
或TagReference
在本地存储库中与remote_ref_string
保存在这种情况下。
- remote_ref_string
- summary
- class git.remote.Remote(repo: Repo, name: str)
提供对GIT遥控器的轻松读写访问。
不属于此接口的所有内容都被认为是当前遥控器的一个选项,允许如下结构
remote.pushurl
来询问推杆。- 注意事项:
在查询配置时,将缓存配置访问器,以加快后续访问。
- __abstractmethods__ = frozenset({})
- __annotations__ = {'_id_attribute_': 'str', 'url': <class 'str'>}
- __eq__(other: object) bool
返回self==值。
- __getattr__(attr: str) Any
允许以如下方式调用此实例
remote.special(*args, **kwargs)
拨打电话git remote special self.name
。
- __hash__() int
返回hash(Self)。
- __module__ = 'git.remote'
- __ne__(other: object) bool
返回自我!=值。
- __parameters__ = ()
- __repr__() str
返回epr(Self)。
- __slots__ = ('repo', 'name', '_config_reader')
- __str__() str
返回str(Self)。
- classmethod __subclasshook__(other)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- add_url(url: str, allow_unsafe_protocols: bool = False, **kwargs: Any) Remote
在当前远程添加新的URL(特殊情况下
git remote set-url
)。此命令将新URL添加到给定的远程,从而使单个远程可以有多个URL。
- 参数:
url -- 字符串是要作为额外远程URL添加的URL。
allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。
- 返回:
自性
- property config_reader: SectionConstraint[GitConfigParser]
- 返回:
GitConfigParser
兼容对象能够读取选项,只有我们的遥控器。因此,您只需输入config.get("pushurl")
以获取信息。
- property config_writer: SectionConstraint
- 返回:
GitConfigParser
-能够为此遥控器写入选项的兼容对象。- 注意事项:
您一次只能拥有一个编写器-删除它以释放配置文件并使其可供其他人使用。
为了确保一致的结果,您应该只通过编写器查询选项。一旦您完成了编写,您就可以再次使用配置读取器了。
- classmethod create(repo: Repo, name: str, url: str, allow_unsafe_protocols: bool = False, **kwargs: Any) Remote
创建到给定存储库的新远程。
- 参数:
repo -- 要接收新遥控器的存储库实例。
name -- 遥控器的所需名称。
url -- 与远程服务器名称对应的URL。
allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。kwargs -- 要传递给
git remote add
指挥部。
- 返回:
新的
Remote
实例- 抛出:
git.exc.GitCommandError -- 如果具有该名称的原点已存在。
- delete_url(url: str, **kwargs: Any) Remote
删除当前远程上的新URL(特殊情况下
git remote set-url
)。此命令删除给定远程的新URL,从而使单个远程可以有多个URL。
- 参数:
url -- 字符串是要从远程删除的URL。
- 返回:
自性
- exists() bool
- 返回:
True
如果这是有效的现有遥控器。有效的远程在存储库的配置中有一个条目。
- 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]
获取此遥控器的最新更改。
- 参数:
refspec -- FETCH和PUSH使用“refspec”来描述远程ref和本地ref之间的映射。它们在格式中与冒号组合在一起
<src>:<dst>
,前面有一个可选的加号,+
。例如:git fetch $URL refs/heads/master:refs/heads/origin
表示“从$URL中获取主分支头并将其存储为我的原始分支头”。和git push $URL refs/heads/master:refs/heads/to-upstream
意思是“将我的主分支机构负责人发布为-上游分支机构,地址为$URL”。另请参阅 git-push(1) 。摘自GIT手册, gitglossary(7) 。FETCH支持多个引用规范(作为基础 git-fetch(1) 提供一个列表而不是一个字符串来表示‘refspec’,这样就可以使用这个工具。progress -- 请参阅
push()
方法。verbose -- 用于详细输出的布尔值。
kill_after_timeout -- 指定git命令的超时时间(以秒为单位),在超时后应终止进程。它被设置为
None
默认情况下。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。kwargs -- 要传递给的其他参数 git-fetch(1) 。
- 返回:
IterableList(提取信息,...)清单
FetchInfo
实例,提供有关提取结果的详细信息- 注意事项:
由于FETCH不向非TTY提供进度信息,很遗憾,我们无法在这里提供它,就像在
push()
方法。
- classmethod iter_items(repo: Repo, *args: Any, **kwargs: Any) Iterator[Remote]
- 返回:
迭代器屈服
Remote
给定存储库的对象
- 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]
从给定的分支提取更改,这与FETCH之后的分支与本地分支的合并相同。
- 参数:
refspec -- 看见
fetch()
方法。progress -- 看见
push()
方法。kill_after_timeout -- 看见
fetch()
方法。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。kwargs -- 要传递给的其他参数 git-pull(1) 。
- 返回:
请看
fetch()
方法。
- 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
将更改从refSpec中的源分支推送到refSpec中的目标分支。
- 参数:
refspec -- 看见
fetch()
方法。progress -- 可以采用多种值类型之一: *
None
, to discard progress information. * 使用进度信息调用的函数(可调用)。签署:progress(op_code, cur_count, max_count=None, message='')
。看见RemoteProgress.update
有关提供给函数的所有参数的说明,请参见。*派生自的类的实例RemoteProgress
它覆盖了RemoteProgress.update
方法。kill_after_timeout -- 指定git命令的超时时间(以秒为单位),在超时后应终止进程。它被设置为
None
默认情况下。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--receive-pack
。kwargs -- 要传递给的其他参数 git-push(1) 。
- 注意事项:
推流返回后,不会返回进一步的进度信息。
- 返回:
A
PushInfoList
对象,其中每个列表成员表示已在远程端更新的单个标头。如果推送包含被拒绝的头,则这些头将具有PushInfo.ERROR
在它们的标志中设置位。如果操作完全失败,则返回的PushInfoList
将为0。打电话raise_if_error()
在任何失败时引发的返回对象上。
- property refs: IterableList[RemoteReference]
- 返回:
IterableList
的RemoteReference
物体。它是前缀,允许您省略远程路径部分,例如::Remote.refs.master#YIES RemoteReference(‘/refs/remotes/origin/master’)
- repo
- set_url(new_url: str, old_url: str | None = None, allow_unsafe_protocols: bool = False, **kwargs: Any) Remote
在当前远程配置URL(参见命令
git remote set-url
)。此命令管理远程上的URL。
- 参数:
new_url -- 字符串是要作为额外远程URL添加的URL。
old_url -- 设置时,将此URL替换为 new_url 为了遥控器。
allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。
- 返回:
自性
- property stale_refs: IterableList[Reference]
- 返回:
IterableList
的RemoteReference
在远程引用中不再具有对应标头的对象,因为它们已在远程端被删除,但在本地仍可用。这个IterableList
是前缀,因此必须省略‘Origin’。看见refs
属性以获取一个示例。让事情变得更复杂的是,列表可以包括其他类型的引用,例如,标记引用,如果这些引用也是陈旧的。这是对此处描述的问题的修复: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
获取此远程分支的所有更改,包括强制加入的新分支(以防您的本地远程分支不再是新远程分支的祖先的一部分)。
- 参数:
kwargs -- 传递到的其他参数
git remote update
。- 返回:
自性
- url: str
为远程配置的URL。
- property urls: Iterator[str]
- 返回:
迭代器将远程服务器上的所有已配置URL目标生成为字符串
- class git.remote.RemoteProgress
提供接口以解析由发出的进度信息的处理器 git-push(1) 和 git-fetch(1) 并分派回调,以允许子类对进度做出反应。
- 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
每当线路无法理解时调用,因此被删除。
- new_message_handler() Callable[[str], None]
- 返回:
一种进程处理程序,适用于
handle_process_output()
,以适当的格式将行传递给该进度处理程序。
- 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
每当进度发生变化时调用。
- 参数:
op_code -- 允许与操作ID和阶段ID进行比较的整数。阶段ID为
BEGIN
和END
。BEGIN
将仅为每个操作ID设置一次END
。可能是因为BEGIN
和END
一次设置,以防由于操作速度的原因只发出一条进度消息。介于BEGIN
和END
,则不会设置任何这些标志。操作ID都保存在OP_MASK
。每个呼叫将只有一个操作ID处于活动状态。cur_count -- 当前项目的绝对计数。
max_count -- 我们期望的最大项目数。可能是因为
None
如果没有最大数量的项目或如果它(尚)未知。message -- 如果是在
WRITING
操作时,它包含传输的字节数。它也可能被用于其他目的。
- 注意事项:
可以在中阅读当前行的内容
self._cur_line
。
Repo.Base
- class git.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)
表示Git存储库,允许您查询引用、创建提交信息、生成差异、创建和克隆存储库以及查询日志。
以下属性值得使用:
working_dir
是git命令的工作目录,这是工作树目录(如果可用)或.git
如果是裸库,则为目录。working_tree_dir
是工作树目录,但将返回None
如果我们是一个空储存库。git_dir
是.git
存储库目录,该目录始终处于设置状态。
- DAEMON_EXPORT_FILE = 'git-daemon-export-ok'
- __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__': 'Represents a git repository and allows you to query references, create commit\n information, generate diffs, create and clone repositories, and query the log.\n\n The following attributes are worth using:\n\n * :attr:`working_dir` is the working directory of the git command, which is the\n working tree directory if available or the ``.git`` directory in case of bare\n repositories.\n\n * :attr:`working_tree_dir` is the working tree directory, but will return ``None``\n if we are a bare repository.\n\n * :attr:`git_dir` is the ``.git`` repository directory, which is always set.\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__': <function Repo.__init__>, '__enter__': <function Repo.__enter__>, '__exit__': <function Repo.__exit__>, '__del__': <function Repo.__del__>, 'close': <function Repo.close>, '__eq__': <function Repo.__eq__>, '__ne__': <function Repo.__ne__>, '__hash__': <function Repo.__hash__>, 'description': <property object>, 'working_tree_dir': <property object>, 'common_dir': <property object>, 'bare': <property object>, 'heads': <property object>, 'references': <property object>, 'refs': <property object>, 'branches': <property object>, 'index': <property object>, 'head': <property object>, 'remotes': <property object>, 'remote': <function Repo.remote>, 'submodules': <property object>, 'submodule': <function Repo.submodule>, 'create_submodule': <function Repo.create_submodule>, 'iter_submodules': <function Repo.iter_submodules>, 'submodule_update': <function Repo.submodule_update>, 'tags': <property object>, 'tag': <function Repo.tag>, '_to_full_tag_path': <staticmethod(<function Repo._to_full_tag_path>)>, 'create_head': <function Repo.create_head>, 'delete_head': <function Repo.delete_head>, 'create_tag': <function Repo.create_tag>, 'delete_tag': <function Repo.delete_tag>, 'create_remote': <function Repo.create_remote>, 'delete_remote': <function Repo.delete_remote>, '_get_config_path': <function Repo._get_config_path>, 'config_reader': <function Repo.config_reader>, '_config_reader': <function Repo._config_reader>, 'config_writer': <function Repo.config_writer>, 'commit': <function Repo.commit>, 'iter_trees': <function Repo.iter_trees>, 'tree': <function Repo.tree>, 'iter_commits': <function Repo.iter_commits>, 'merge_base': <function Repo.merge_base>, 'is_ancestor': <function Repo.is_ancestor>, 'is_valid_object': <function Repo.is_valid_object>, 'daemon_export': <property object>, '_get_alternates': <function Repo._get_alternates>, '_set_alternates': <function Repo._set_alternates>, 'alternates': <property object>, 'is_dirty': <function Repo.is_dirty>, 'untracked_files': <property object>, '_get_untracked_files': <function Repo._get_untracked_files>, 'ignored': <function Repo.ignored>, 'active_branch': <property object>, 'blame_incremental': <function Repo.blame_incremental>, 'blame': <function Repo.blame>, 'init': <classmethod(<function Repo.init>)>, '_clone': <classmethod(<function Repo._clone>)>, 'clone': <function Repo.clone>, 'clone_from': <classmethod(<function Repo.clone_from>)>, 'archive': <function Repo.archive>, 'has_separate_working_tree': <function Repo.has_separate_working_tree>, 'rev_parse': <function rev_parse>, '__repr__': <function Repo.__repr__>, 'currently_rebasing_on': <function Repo.currently_rebasing_on>, '__dict__': <attribute '__dict__' of 'Repo' objects>, '__weakref__': <attribute '__weakref__' of 'Repo' objects>})
- __eq__(rhs: object) bool
返回self==值。
- __exit__(*args: Any) None
- __hash__() int
返回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
创建新的
Repo
举个例子。- 参数:
path --
指向git根目录或裸git repo::的路径
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")
在……里面 Cygwin , path 可能是一种
cygdrive/...
带前缀的路径。如果 path 是
None
或空字符串,GIT_DIR
使用的是。如果该环境变量不存在或为空,则使用当前目录。
odbt -- 对象数据库类型-通过提供包含数据库对象的目录构建的类型,即
.git/objects
。它将用于访问所有对象数据。search_parent_directories -- 如果
True
,还将在所有父目录中搜索有效的回购。请注意,这是较旧版本的GitPython的默认行为,但这被认为是一个错误。
- 抛出:
- 返回:
- __module__ = 'git.repo.base'
- __ne__(rhs: object) bool
返回自我!=值。
- __repr__() str
返回epr(Self)。
- __weakref__
对象的弱引用列表
- property alternates: List[str]
检索备选路径列表或设置要用作备选路径的列表路径
- archive(ostream: TextIO | BinaryIO, treeish: str | None = None, prefix: str | None = None, **kwargs: Any) Repo
将给定修订版的树存档。
- 参数:
ostream -- 档案将以字节形式写入的文件兼容流对象。
treeish -- 树状名称/ID,默认为活动分支。
prefix -- 要添加到存档中每个文件名前面的可选前缀。
kwargs -- 传递到的其他参数 git-archive(1) : * Use the
format
argument to define the kind of format. Use specialized ostreams to write any format supported by Python. * 您可以指定特价path
关键字,它可以是指向要放入存档中的目录或文件的存储库相对路径,也可以是多个路径的列表或元组。
- 抛出:
git.exc.GitCommandError -- 如果出了什么差错。
- 返回:
自性
- property bare: bool
- 返回:
True
如果存储库是空的
- 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
给定版本的给定文件的错误信息。
- 参数:
rev -- 修订说明符。如果
None
,责任将包括所有最新的未提交的更改。否则,任何成功解析的 git-rev-parse(1) 是一个有效的选项。- 返回:
名单: [git.Commit, list: [<line>] ]关联于
Commit
使用在给定提交内更改的行列表创建。这个Commit
将按照出现的顺序给出对象。
- blame_incremental(rev: str | HEAD | None, file: str, **kwargs: Any) Iterator[BlameEntry]
用于给定版本的给定文件的错误信息的迭代器。
不像
blame()
,这不会返回实际文件的内容,而只返回BlameEntry
元组。- 参数:
rev -- 修订说明符。如果
None
,责任将包括所有最新的未提交的更改。否则,任何成功解析的 git-rev-parse(1) 是一个有效的选项。- 返回:
懒惰的迭代器
BlameEntry
元组,其中Commit表示该行的提交,Range表示结果文件中行号的范围。
如果您组合了该命令输出的所有行号范围,您应该会得到一个跨越文件中所有行号的连续范围。
- property branches: IterableList[Head]
一份名单
Head
对象,表示此回购中的分支头。- 返回:
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
从此存储库中创建克隆。
- 参数:
path -- 新回购的完整路径(传统上以
./<name>.git
)。progress -- 看见
Remote.push
。multi_options -- 一份名单 git-clone(1) 可以多次提供的选项。每个列表项都有一个选项,该选项完全按照指定传递给克隆。例如:: [ "--config core.filemode=false", "--config core.ignorecase", "--recurse-submodule=repo1_path", "--recurse-submodule=repo2_path", ]
allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。kwargs --
odbt
=对象数据库类型,允许确定返回的Repo
举个例子。所有剩余的关键字参数都将提供给 git-clone(1) 指挥部。
- 返回:
Repo
(新克隆的回购)
- classmethod clone_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
从给定的URL创建克隆。
- 参数:
url -- 有效的GIT URL,请参阅:https://git-scm.com/docs/git-clone#URLS
to_path -- 存储库应克隆到的路径。
progress -- 看见
Remote.push
。env -- 包含所需环境变量的可选词典。注意:提供的变量将用于更新执行环境
git
。如果中未指定某个变量 env 并在中定义os.environ
、价值来源os.environ
将会被使用。如果要取消某些变量的设置,请考虑提供空字符串作为其值。multi_options -- 请参阅
clone()
方法。allow_unsafe_protocols -- 允许使用不安全协议,如
ext
。allow_unsafe_options -- 允许使用不安全选项,如
--upload-pack
。kwargs -- 请参阅
clone()
方法。
- 返回:
Repo
实例,指向克隆的目录。
- close() None
- commit(rev: str | Commit_ish | None = None) Commit
这个
Commit
为指定修订版本创建。- 参数:
rev -- 修订说明符,请参见 git-rev-parse(1) 寻找可行的选择。
- 返回:
- property common_dir: str | PathLike[str]
- 返回:
Git目录包含除HEAD、FETCH_HEAD、ORIG_HEAD、COMMIT_EDITMSG、INDEX和LOGS/之外的所有内容。
- config_level: Tuple[Literal['system'], Literal['user'], Literal['global'], Literal['repository']] = ('system', 'user', 'global', 'repository')
表示配置文件的配置级别。
- config_reader(config_level: Literal['system', 'global', 'user', 'repository'] | None = None) GitConfigParser
- 返回:
GitConfigParser
允许读取完整的GIT配置,但不允许写入它。配置将包括来自系统、用户和存储库配置文件的值。- 参数:
config_level -- 有关可能的值,请参见
config_writer()
方法。如果None
,将使用所有适用级别。指定一个级别,以防您知道要读取哪个文件以防止读取多个文件。- 注意事项:
在Windows上,由于路径未知,因此当前无法读取系统配置,而将使用全局路径。
- config_writer(config_level: Literal['system', 'global', 'user', 'repository'] = 'repository') GitConfigParser
- 返回:
A
GitConfigParser
允许写入指定配置文件级别的值。应该检索配置编写器,用于更改配置,并立即写入,因为它们将锁定有问题的配置文件,并防止其他人写入它。- 参数:
config_level -- 下列值之一: *
"system"
= system wide configuration file *"global"
=用户级配置文件*"`repository"
=仅此存储库的配置文件
- create_head(path: PathLike, commit: 'SymbolicReference' | 'str' = 'HEAD', force: bool = False, logmsg: str | None = None) Head
在存储库中创建一个新的头。
- 注意事项:
有关更多文档,请参阅
Head.create
方法。- 返回:
新创建的
Head
参考资料。
- create_remote(name: str, url: str, **kwargs: Any) Remote
创建新遥控器。
有关更多信息,请参阅
Remote.create
方法。- 返回:
Remote
参考文献
- create_submodule(*args: Any, **kwargs: Any) Submodule
创建一个新子模块。
- 注意事项:
有关适用参数的说明,请参阅的文档
Submodule.add
。- 返回:
创建的子模块。
- create_tag(path: PathLike, ref: str | 'SymbolicReference' = 'HEAD', message: str | None = None, force: bool = False, **kwargs: Any) TagReference
创建一个新的标记引用。
- 注意事项:
有关更多文档,请参阅
TagReference.create
方法。- 返回:
TagReference
对象
- property daemon_export: bool
如果为True,则git-daemon可能会导出此存储库
- delete_head(*heads: str | Head, **kwargs: Any) None
删除给定的标题。
- 参数:
kwargs -- 要传递给的其他关键字参数 git-branch(1) 。
- delete_tag(*tags: TagReference) None
删除给定的标记引用。
- property description: str
该项目的描述
- git = None
- git_dir: str | PathLike[str]
这个
.git
存储库目录。
- has_separate_working_tree() bool
- 返回:
如果我们的
git_dir
并不是我们的working_tree_dir
,而是一个.git
带有平台无关符号链接的文件。我们的git_dir
将会在任何地方.git
文件指向。- 注意事项:
空储存库将始终返回
False
这里。
- property heads: IterableList[Head]
一份名单
Head
对象,表示此回购中的分支头。- 返回:
git.IterableList(Head, ...)
- ignored(*paths: str | PathLike[str]) List[str]
检查是否通过以下方式忽略路径
.gitignore
。这是使用 git-check-ignore(1) 方法。
- 参数:
paths -- 检查它们是否被忽略的路径列表。
- 返回:
被忽略的那些路径的子集
- classmethod init(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
在给定路径下初始化GIT存储库(如果指定)。
- 参数:
path -- 回购的完整路径(通常以
/<name>.git
)。或None
,在这种情况下,将在当前工作目录中创建存储库。mkdir -- 如果指定,将创建存储库目录(如果该目录不存在)。创建模式为0755的目录。只有在明确指定路径的情况下才有效。
odbt -- 对象数据库类型-通过提供包含数据库对象的目录构建的类型,即
.git/objects
。它将用于访问所有对象数据。expand_vars -- 如果指定,则不会转义环境变量。这可能导致信息泄露,从而允许攻击者访问环境变量的内容。
kwargs -- 关键字参数用作 git-init(1) 指挥部。
- 返回:
Repo
(新增回购)
- is_ancestor(ancestor_rev: Commit, rev: Commit) bool
检查一个提交是否是另一个提交的祖先。
- 参数:
ancestor_rev -- 应该是祖先的牧师。
rev -- 要测试的Rev ancestor_rev 。
- 返回:
True
如果 ancestor_rev 是人类的祖先 rev 。
- is_dirty(index: bool = True, working_tree: bool = True, untracked_files: bool = False, submodules: bool = True, path: str | PathLike[str] | None = None) bool
- 返回:
True
如果存储库被认为是脏的。默认情况下,它的反应类似于 git-status(1) 没有未跟踪的文件,因此,如果索引或工作副本有更改,则它是脏的。
- 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]
的迭代器
Commit
对象,表示给定引用/提交的历史记录。- 参数:
rev -- 修订说明符,请参见 git-rev-parse(1) 寻找可行的选择。如果
None
,将使用活动分支。paths -- 可选路径或路径列表。如果设置,则只返回包括路径的提交。
kwargs -- 要传递给 git-rev-list(1) 。常见的有
max_count
和skip
。
- 注意事项:
若要仅接收两个命名修订之间的提交,请使用
"revA...revB"
修订说明符。- 返回:
迭代器
Commit
对象
- iter_submodules(*args: Any, **kwargs: Any) Iterator[Submodule]
生成子模块实例的迭代器。
请参阅 ~git.objects.util.Traversable 用于描述的接口 args 和 kwargs 。
- 返回:
迭代器
- iter_trees(*args: Any, **kwargs: Any) Iterator['Tree']
- 返回:
迭代器屈服
Tree
对象- 注意事项:
方法已知的所有参数
iter_commits()
方法。
- 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+')
- property references: IterableList[Reference]
一份名单
Reference
表示标记、头和远程引用的对象。- 返回:
git.IterableList(Reference, ...)
- property refs: IterableList[Reference]
一份名单
Reference
表示标记、头和远程引用的对象。- 返回:
git.IterableList(Reference, ...)
- property remotes: IterableList[Remote]
一份名单
Remote
对象,这些对象允许访问和操作远程。- 返回:
git.IterableList(Remote, ...)
- rev_parse(rev: str) AnyGitObject
分析修订字符串。喜欢 git-rev-parse(1) 。
- 返回:
~git.objects.base.Object 在给定的修订版本。
这可以是任何类型的Git对象:
- 参数:
rev -- git-rev-parse(1) -兼容的修订规范为字符串。请看 git-rev-parse(1) 了解更多细节。
- 抛出:
gitdb.exc.BadObject -- 如果找不到给定的修订版本。
ValueError -- 如果 rev 无法解析。
IndexError -- 如果指定了无效的reflog索引。
- submodule_update(*args: Any, **kwargs: Any) Iterator[Submodule]
更新子模块,保持存储库的一致性,因为它将考虑以前的状态。
- 注意事项:
有关更多信息,请参阅的文档
RootModule.update
。
- property submodules: IterableList[Submodule]
- 返回:
Git.IterableList(子模块,...)可从当前头部获得的直接子模块的
- tag(path: str | PathLike[str]) TagReference
- 返回:
TagReference
对象,引用指向Commit
或标签- 参数:
path -- 标记引用的路径,例如
0.1.5
或tags/0.1.5
。
- property tags: IterableList[TagReference]
一份名单
TagReference
此回购中可用的对象。- 返回:
git.IterableList(TagReference, ...)
- tree(rev: Tree_ish | str | None = None) Tree
这个
Tree
为给定的类似树的修订设置。示例:
repo.tree(repo.heads[0])
- 参数:
rev -- 指向树的修订(作为提交或树)。
- 返回:
- 注意事项:
如果您需要非根级树,可以通过迭代根树来找到它。否则,它无法知道其相对于存储库根的路径,并且后续操作可能会产生意外的结果。
- unsafe_git_clone_options = ['--upload-pack', '-u', '--config', '-c']
选项至 git-clone(1) 允许执行任意命令的。
这个
--upload-pack
/-u
选项允许用户直接执行任意命令:https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---upload-packltupload-packgt这个
--config
/-c
选项允许用户覆盖配置变量,如protocol.allow
和core.gitProxy
执行任意命令:https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---configltkeygtltvaluegt
- property untracked_files: List[str]
- 返回:
列表(字符串,...)当前未跟踪文件,因为它们尚未暂存。路径相对于git命令的当前工作目录。
- 注意事项:
此处不会显示忽略的文件,即中提到的文件
.gitignore
。- 注意事项:
此属性的开销很大,因为不涉及缓存。要处理结果,请考虑自己缓存它。
- working_dir: str | PathLike[str]
Git命令的工作目录。
- property working_tree_dir: str | PathLike[str] | None
- 返回:
我们的Git存储库的工作树目录。如果这是一个空储存库,
None
是返回的。
Repo.Functions
与存储库相关的常规功能。
- git.repo.fun.deref_tag(tag: Tag) AnyGitObject
递归地取消引用标记并返回结果对象。
- git.repo.fun.find_submodule_git_dir(d: str | PathLike[str]) str | PathLike[str] | None
搜索子模块回购。
- git.repo.fun.find_worktree_git_dir(dotgit: str | PathLike[str]) str | None
搜索此工作树的Gitdir。
- git.repo.fun.is_git_dir(d: str | PathLike[str]) bool
这取自git setup.c:is_git_目录函数。
- 抛出:
git.exc.WorkTreeRepositoryUnsupported -- 如果它看到工作树目录。在这里这样做是相当愚蠢的,但至少清楚地表明我们不支持它。如果我们看到的目录看起来只是像一个工作树目录,但实际上并不是,那么就不太可能抛出危险。
- 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
分析修订字符串。喜欢 git-rev-parse(1) 。
- 返回:
~git.objects.base.Object 在给定的修订版本。
这可以是任何类型的Git对象:
- 参数:
rev -- git-rev-parse(1) -兼容的修订规范为字符串。请看 git-rev-parse(1) 了解更多细节。
- 抛出:
gitdb.exc.BadObject -- 如果找不到给定的修订版本。
ValueError -- 如果 rev 无法解析。
IndexError -- 如果指定了无效的reflog索引。
- git.repo.fun.short_to_long(odb: GitCmdObjectDB, hexsha: str) bytes | None
- 返回:
从给定的小于40字节的十六进制长SHA1,或
None
如果找不到候选人。- 参数:
hexsha -- 少于40个字节的HIXSHA。
- git.repo.fun.touch(filename: str) str
比较
帮助提供与Python3兼容性的实用程序。
这个模块的存在是有历史原因的。GitPython外部的代码可能会使用此模块的公共成员,但不太可能从中受益。GitPython继续使用其中的一些实用程序,在某些情况下是为了兼容不同的平台。
- git.compat.__dir__() List[str]
- git.compat.__getattr__(name: str) Any
- git.compat.defenc = 'utf-8'
用于在Unicode和字节文件名之间进行转换的编码。
- git.compat.is_darwin: bool = False
的别名已弃用
sys.platform == "darwin"
检查MacOS(达尔文)。这是不赞成的,因为这样写出来更清楚
os.name
或sys.platform
显式检查。- 注意事项:
对于MacOS(达尔文)来说,
os.name == "posix"
与其他类Unix系统一样,而sys.platform == "darwin"
。
- git.compat.is_posix: bool = True
的别名已弃用
os.name == "posix"
检查类Unix(“POSIX”)系统。这是不赞成的,因为这样写出来更清楚
os.name
或sys.platform
显式检查,特别是在使用的关键情况下。- 注意事项:
有关POSIX系统的更详细信息,请参阅
sys.platform
,而os.name
永远都是"posix"
在这样的系统上,包括MacOS(达尔文)。
- git.compat.is_win: bool = False
的别名已弃用
os.name == "nt"
若要检查本机Windows,请执行以下操作。不赞成这样做,因为这样写出来更清楚
os.name
或sys.platform
显式检查,特别是在使用的关键情况下。- 注意事项:
is_win
是False
关于Cygwin,但经常被错误地认为True
。要检测Cygwin,请使用sys.platform == "cygwin"
。
- git.compat.safe_decode(s: None) None
- git.compat.safe_decode(s: AnyStr) str
安全地将二进制字符串解码为Unicode。
- git.compat.safe_encode(s: None) None
- git.compat.safe_encode(s: AnyStr) bytes
将二进制字符串安全地编码为Unicode。
- git.compat.win_encode(s: None) None
- git.compat.win_encode(s: AnyStr) bytes
为Windows上的进程参数编码Unicode字符串。
DB
模块和我们自己的gitdb实现-它使用git命令。
- class git.db.GitCmdObjectDB(root_path: str | os.PathLike[str], git: Git)
表示默认Git对象存储的数据库,其中包括松散对象、包文件和备用文件。
它将仅在松散对象数据库中创建对象。
- __module__ = 'git.db'
- info(binsha: bytes) OInfo
获取Git对象头(使用Git本身)。
- partial_to_complete_sha_hex(partial_hexsha: str) bytes
- 返回:
来自给定部分十六进制数的全二进制20字节SHA
- 抛出:
- 注意事项:
目前我们只筹集
BadObject
因为Git不会单独传递不明确的对象。
- stream(binsha: bytes) OStream
以流形式获取Git对象数据,支持
read()
(使用Git本身)。
- class git.db.GitDB(root_path)
一个Git样式的对象数据库,其中包含‘Objects’子目录中的所有对象
IMPORTANT
:强烈反对使用此实现,因为它无法释放文件句柄。对于长时间运行的流程和/或大型存储库,这可能是一个问题。- LooseDBCls
LooseObjectDB
的别名
- PackDBCls
PackedDB
的别名
- ReferenceDBCls
ReferenceDB
的别名
- __annotations__ = {}
- __init__(root_path)
在Git对象目录上初始化我们自己
- __module__ = 'gitdb.db.git'
- alternates_dir = 'info/alternates'
- loose_dir = ''
- ostream()
返回输出流
- 返回:
此实例将写入的重写输出流,如果它将写入默认流,则为None
- packs_dir = 'pack'
- set_ostream(ostream)
调整在存储新对象时应将所有数据发送到的流
- 参数:
stream -- 如果不是None,则为要使用的流;如果没有,则将使用默认流。
- 返回:
以前安装的流,如果没有覆盖,则为None
- 抛出:
TypeError -- 如果流不具有受支持的功能
- store(istream)
在数据库中创建一个新对象:返回:输入IStream对象,并将其SHA设置为其相应值
- 参数:
istream -- 与IStream兼容的实例。如果其SHA已被设置为值,则对象将仅以我们的数据库格式存储,在这种情况下,输入流预期为对象格式(标题+内容)。
- 抛出:
IOError -- 如果无法写入数据
类型
- git.types.AnyGitObject
世界银行联盟
Object
基于类型,表示实际的Git对象类型。如中所述
Object
,其中有更多细节,这些是:这些GitPython类代表四种Git对象类型 gitglossary(7) :
“提交对象”:https://git-scm.com/docs/gitglossary#def_commit_object
“Tag Object”:https://git-scm.com/docs/gitglossary#def_tag_object
有关Git对象及其类型的更多一般信息,请参阅:
- 注意事项:
另请参阅
Tree_ish
和Commit_ish
工会。
Union
[Commit
,Tree
,TagObject
,Blob
] 的别名
- git.types.CallableProgress
用作克隆进度报告器的函数或其他可调用函数的一般类型。
这是报告克隆进度的函数或其他可调用类型,当作为
progress
参数为Repo.clone
或Repo.clone_from
。- 注意事项:
那些
clone()
和clone_from()
方法也接受RemoteProgress()
实例,包括其CallableRemoteProgress()
子类。- 注意事项:
与匹配此类型的对象不同,
RemoteProgress()
实例不能直接调用,即使它们是CallableRemoteProgress()
,它包装一个可调用的,并将信息转发给它,但本身不是可调用的。- 注意事项:
此类型还允许
None
,用于克隆而不报告进展。
Optional
[Callable
[[int
,Union
[str
,float
],Optional
[Union
[str
,float
]],str
],None
]] 的别名
- git.types.Commit_ish
联合
Object
通常是提交式的基于类型的。看见 gitglossary(7) 关于“承诺式的”:https://git-scm.com/docs/gitglossary#def_commit-ish
- 注意事项:
Commit
是唯一一个实例都是提交式的类。此联合类型包括Commit
,但也TagObject
,仅限 most 其中的实例是提交式的。无论是一个特定的TagObject
通常只有在运行时才能知道对提交的剥离(递归解除引用),而不是树或BLOB。在实践中,Git标记对象几乎总是用于标记提交,这样的标记当然是提交式的。- 注意事项:
另请参阅
AnyGitObject
对应于Git对象类型的所有四个类的联合。
Union
[Commit
,TagObject
] 的别名
- git.types.ConfigLevels_Tup
表示配置级别的四个字符串的元组的静态类型。
Tuple
[Literal
['system'],Literal
['user'],Literal
['global'],Literal
['repository']] 的别名
- class git.types.Files_TD
带有针对特定文件的差异的统计计数的字典。
- __annotations__ = {'deletions': <class 'int'>, 'insertions': <class 'int'>, 'lines': <class 'int'>}
- __dict__ = mappingproxy({'__module__': 'git.types', '__annotations__': {'insertions': <class 'int'>, 'deletions': <class 'int'>, 'lines': <class 'int'>}, '__doc__': 'Dictionary with stat counts for the diff of a particular file.\n\n For the :class:`~git.util.Stats.files` attribute of :class:`~git.util.Stats`\n objects.\n ', '__orig_bases__': (<function TypedDict>,), '__dict__': <attribute '__dict__' of 'Files_TD' objects>, '__weakref__': <attribute '__weakref__' of 'Files_TD' objects>, '__required_keys__': frozenset({'lines', 'insertions', 'deletions'}), '__optional_keys__': frozenset(), '__total__': True})
- __module__ = 'git.types'
- __optional_keys__ = frozenset({})
- __orig_bases__ = (<function TypedDict>,)
- __required_keys__ = frozenset({'deletions', 'insertions', 'lines'})
- __total__ = True
- __weakref__
对象的弱引用列表
- deletions: int
- insertions: int
- lines: int
- git.types.GitObjectTypeString
标识Git对象类型的文本字符串和
Object
表示它们的基于类型的。请参阅
Object.type
属性。以下是它的价值Object
表示Git对象的子类。因此,这些文字对应于AnyGitObject
友联市。这些字符串与Git本身用来标识其四种对象类型的字符串相同。看见 gitglossary(7) 关于“对象类型”:https://git-scm.com/docs/gitglossary#def_object_type
Literal
['commit', 'tag', 'blob', 'tree'] 的别名
- class git.types.HSH_TD
词典中包含与
Stats
对象。- __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__': 'Dictionary carrying the same information as a :class:`~git.util.Stats` object.', '__orig_bases__': (<function TypedDict>,), '__dict__': <attribute '__dict__' of 'HSH_TD' objects>, '__weakref__': <attribute '__weakref__' of 'HSH_TD' objects>, '__required_keys__': frozenset({'files', 'total'}), '__optional_keys__': frozenset(), '__total__': True})
- __module__ = 'git.types'
- __optional_keys__ = frozenset({})
- __orig_bases__ = (<function TypedDict>,)
- __required_keys__ = frozenset({'files', 'total'})
- __total__ = True
- __weakref__
对象的弱引用列表
- class git.types.Has_Repo(*args, **kwargs)
一种协议,用于
repo
属性,即要操作的存储库。- __abstractmethods__ = frozenset({})
- __annotations__ = {'repo': 'Repo'}
- __dict__ = mappingproxy({'__module__': 'git.types', '__annotations__': {'repo': 'Repo'}, '__doc__': 'Protocol for having a :attr:`repo` attribute, the repository to operate on.', '__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_data object>, '__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)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- __weakref__
对象的弱引用列表
- class git.types.Has_id_attribute(*args, **kwargs)
协议,以使
_id_attribute_
用于迭代和遍历。- __abstractmethods__ = frozenset({})
- __annotations__ = {'_id_attribute_': <class 'str'>}
- __dict__ = mappingproxy({'__module__': 'git.types', '__annotations__': {'_id_attribute_': <class 'str'>}, '__doc__': 'Protocol for having :attr:`_id_attribute_` used in iteration and traversal.', '__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_data object>, '__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)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- __weakref__
对象的弱引用列表
- git.types.Lit_commit_ish
已弃用。标识典型的通用GIT对象类型的文字字符串类型。
在错误修复之前,这种类型的定义更加宽泛。任何用法在实践中都是模棱两可的,很可能是不正确的。因此,已将此类型设置为静态类型错误,以便出现在批注中。它以弃用状态保留,以避免在引用它的代码中引入运行时错误,但不应使用它。
而不是这种类型:
关联的字符串文字的类型
Commit_ish
,使用Literal["commit", "tag"]
或为其创建新的类型别名。这等同于当前定义的该类型(但在静态检查的类型批注中可用)。关联的所有四个字符串文字的类型
AnyGitObject
,使用GitObjectTypeString
。这等同于错误修复之前对该类型的旧定义(也可用于静态检查的类型批注)。
Literal
['commit', 'tag'] 的别名
- git.types.Lit_config_levels
命名GIT配置级别的文字字符串的类型。
这些字符串与GIT配置变量所在的文件相关。
Literal
['system', 'global', 'user', 'repository'] 的别名
- git.types.PathLike
A
str
基于(Unicode)的文件或目录路径。Union
[str
,os.PathLike[str]
] 的别名
- git.types.TBD
的别名
Any
,当类型提示要变得更具体时。
- class git.types.Total_TD
包含任意数量文件的总统计数据的字典。
- __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__': 'Dictionary with total stats from any number of files.\n\n For the :class:`~git.util.Stats.total` attribute of :class:`~git.util.Stats`\n objects.\n ', '__orig_bases__': (<function TypedDict>,), '__dict__': <attribute '__dict__' of 'Total_TD' objects>, '__weakref__': <attribute '__weakref__' of 'Total_TD' objects>, '__required_keys__': frozenset({'lines', 'files', 'insertions', 'deletions'}), '__optional_keys__': frozenset(), '__total__': True})
- __module__ = 'git.types'
- __optional_keys__ = frozenset({})
- __orig_bases__ = (<function TypedDict>,)
- __required_keys__ = frozenset({'deletions', 'files', 'insertions', 'lines'})
- __total__ = True
- __weakref__
对象的弱引用列表
- deletions: int
- files: int
- insertions: int
- lines: int
- git.types.Tree_ish
联合
Object
通常类似于树的基于类型的。看见 gitglossary(7) 关于“像树一样的”:https://git-scm.com/docs/gitglossary#def_tree-ish
- 注意事项:
Tree
和Commit
是实例都是树型的类。这个联盟包括他们,但也包括TagObject
,仅限 most 其中一些实例是树状的。无论是一个特定的TagObject
剥离(递归解除引用)到树或提交,而不是BLOB,通常只有在运行时才能知道。在实践中,Git Tag对象几乎总是用于标记提交,这种标记是树状的,因为提交是树状的。- 注意事项:
另请参阅
AnyGitObject
对应于Git对象类型的所有四个类的联合。
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
用于对If/Else链中的文本或枚举进行全面检查。
只有当并非所有成员都得到处理,或者试图通过链传递非成员时,才应调用此函数。
- 参数:
inp -- 如果处理了所有成员,则 inp 将会有
Never
/NoReturn
打字。否则,类型将不匹配并导致mypy错误。raise_error -- 如果
True
,也将提高ValueError
带有一般的“未处理的文字”消息,或异常对象作为 exc 。exc -- 不是的
None
,这应该是一个已经构造的异常对象,如果 raise_error 是True
。
乌蒂尔
- class git.util.Actor(name: str | None, email: str | None)
参与者保存有关在存储库上执行操作的人员的信息。他们可以是提交者和作者,也可以是git日志条目中提到的具有名称和电子邮件的任何内容。
- __annotations__ = {}
- __eq__(other: Any) bool
返回self==值。
- __hash__() int
返回hash(Self)。
- __init__(name: str | None, email: str | None) None
- __module__ = 'git.util'
- __ne__(other: Any) bool
返回自我!=值。
- __repr__() str
返回epr(Self)。
- __slots__ = ('name', 'email')
- __str__() str
返回str(Self)。
- classmethod author(config_reader: None | GitConfigParser | SectionConstraint = None) Actor
相同于
committer()
,但定义了主要作者。它可以在环境中指定,但缺省为提交者。
- classmethod committer(config_reader: None | GitConfigParser | SectionConstraint = None) Actor
- 返回:
Actor
实例,该实例与配置的提交者对应。它的行为类似于git实现,因此环境将覆盖 config_reader 。如果根本没有设置任何值,则会生成该值。- 参数:
config_reader -- ConfigReader用于在环境中未设置值的情况下从中检索值。
- 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('<(.*)>')
- class git.util.BlockingLockFile(file_path: str | PathLike[str], check_interval_s: float = 0.3, max_block_time_s: int = 9223372036854775807)
锁定文件将被阻止,直到可以获得锁定,或者在指定的超时后失败。
- 注意事项:
如果包含锁的目录被删除,则在阻塞期间将引发异常,防止挂起,因为永远无法获得锁。
- __init__(file_path: str | PathLike[str], check_interval_s: float = 0.3, max_block_time_s: int = 9223372036854775807) None
配置实例。
- 参数:
check_interval_s -- 下一次检查锁之前的休眠时间。默认情况下,它几乎无限制地等待时间。
max_block_time_s -- 我们可以锁定的最大秒数。
- __module__ = 'git.util'
- __slots__ = ('_check_interval', '_max_block_time')
- class git.util.CallableRemoteProgress(fn: Callable)
A
RemoteProgress
实现将更新转发到任何可调用的。- 注意事项:
类似于
RemoteProgress
,这一实例CallableRemoteProgress
类本身不是可直接调用的。相反,此类的实例包装了一个可调用的,并转发给它。因此,这不应与git.types.CallableProgress
。
- __annotations__ = {}
- __init__(fn: Callable) None
- __module__ = 'git.util'
- __slots__ = ('_callable',)
- update(*args: Any, **kwargs: Any) None
每当进度发生变化时调用。
- 参数:
op_code -- 允许与操作ID和阶段ID进行比较的整数。阶段ID为
BEGIN
和END
。BEGIN
将仅为每个操作ID设置一次END
。可能是因为BEGIN
和END
一次设置,以防由于操作速度的原因只发出一条进度消息。介于BEGIN
和END
,则不会设置任何这些标志。操作ID都保存在OP_MASK
。每个呼叫将只有一个操作ID处于活动状态。cur_count -- 当前项目的绝对计数。
max_count -- 我们期望的最大项目数。可能是因为
None
如果没有最大数量的项目或如果它(尚)未知。message -- 如果是在
WRITING
操作时,它包含传输的字节数。它也可能被用于其他目的。
- 注意事项:
可以在中阅读当前行的内容
self._cur_line
。
- git.util.HIDE_WINDOWS_KNOWN_ERRORS = False
我们需要一种简单的方法来查看Appveyor TCS是否开始失败,因此标记了此变量的错误被认为是“已确认”的错误,等待补救,在此之前,我们希望隐藏它们。
- class git.util.IndexFileSHA1Writer(f: IO)
对一个类似文件的对象进行包装,该对象记住写入其中的数据的SHA1。它将在流关闭时或如果要求显式使用
write_sha()
。仅对索引文件有用。
- 注意事项:
基于达利奇项目。
- __init__(f: IO) None
- __module__ = 'git.util'
- __slots__ = ('f', 'sha1')
- close() bytes
- f
- sha1
- tell() int
- write(data: AnyStr) int
- write_sha() bytes
- class git.util.IterableList(id_attr: str, prefix: str = '')
允许按id或按命名索引查询对象的可迭代对象列表::
heads = repo.heads heads.master heads['master'] heads[0]
可重复使用的父对象:
可通过继承迭代:
这需要一个
id_attribute
要设置的名称,该名称将从其包含的项中进行查询,以便具有比较手段。可以指定在项返回的ID总是包含对用户无关紧要的前缀的情况下要使用的前缀,因此可以省略该前缀。
- __annotations__ = {}
- __contains__(attr: object) bool
返回bool(在自身中键入)。
- __delitem__(index: SupportsIndex | int | slice | str) None
删除自我 [key] 。
- __getattr__(attr: str) T_IterableObj
- __getitem__(index: SupportsIndex | int | slice | str) T_IterableObj
回归自我 [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')
- class git.util.IterableObj(*args, **kwargs)
定义了可迭代项的接口,因此有一种统一的方式来检索和迭代git存储库中的项。
子类:
- __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)
抽象类可以覆盖它来定制issubclass()。
这在早期由abc.ABCMeta.__subClasscheck__()调用。它应返回True、False或NotImplemented。如果返回NotImplemented,则使用普通算法。否则,它将覆盖常规算法(结果将被缓存)。
- abstract classmethod iter_items(repo: Repo, *args: Any, **kwargs: Any) Iterator[T_IterableObj]
查找(所有)此类型的项目。
子类可以指定 args 和 kwargs 不同,并且可以使用它们进行过滤。但是,如果在不使用其他位置参数或关键字参数的情况下调用该方法,则子类必须生成所有项。
- 返回:
迭代器产生项
- classmethod list_items(repo: Repo, *args: Any, **kwargs: Any) IterableList[T_IterableObj]
查找(所有)此类型的项目并将其收集到列表中。
有关参数的更多信息,请参见
iter_items()
。- 注意事项:
支持
iter_items()
方法,因为它将避免急于收集所有项。当有许多项时,这可能会降低性能并增加内存使用量。- 返回:
列表(项目,...)项目实例列表
- class git.util.LockFile(file_path: str | PathLike[str])
提供获取、检查和释放基于文件的锁的方法,该锁应用于处理对同一文件的并发访问。
因为我们是要派生的实用程序类,所以我们只使用受保护的方法。
锁将在销毁时自动释放。
- __annotations__ = {}
- __del__() None
- __init__(file_path: str | PathLike[str]) None
- __module__ = 'git.util'
- __slots__ = ('_file_path', '_owns_lock')
- class git.util.RemoteProgress
提供接口以解析由发出的进度信息的处理器 git-push(1) 和 git-fetch(1) 并分派回调,以允许子类对进度做出反应。
- 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
每当线路无法理解时调用,因此被删除。
- new_message_handler() Callable[[str], None]
- 返回:
一种进程处理程序,适用于
handle_process_output()
,以适当的格式将行传递给该进度处理程序。
- 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
每当进度发生变化时调用。
- 参数:
op_code -- 允许与操作ID和阶段ID进行比较的整数。阶段ID为
BEGIN
和END
。BEGIN
将仅为每个操作ID设置一次END
。可能是因为BEGIN
和END
一次设置,以防由于操作速度的原因只发出一条进度消息。介于BEGIN
和END
,则不会设置任何这些标志。操作ID都保存在OP_MASK
。每个呼叫将只有一个操作ID处于活动状态。cur_count -- 当前项目的绝对计数。
max_count -- 我们期望的最大项目数。可能是因为
None
如果没有最大数量的项目或如果它(尚)未知。message -- 如果是在
WRITING
操作时,它包含传输的字节数。它也可能被用于其他目的。
- 注意事项:
可以在中阅读当前行的内容
self._cur_line
。
- class git.util.Stats(total: Total_TD, files: Dict[str | PathLike[str], Files_TD])
表示GIT在合并结束时显示的统计信息。它是从diff操作的输出创建的。
示例::
c = Commit( sha1 ) s = c.stats s.total # full-stat-dict s.files # dict( filepath : stat-dict )
stat-dict
具有以下键和值的字典:
deletions = number of deleted lines as int insertions = number of inserted lines as int lines = total number of lines changed as int, or deletions + insertions
full-stat-dict
除了统计词典中的条目外,它还提供了其他信息:
files = number of changed files as int
- __module__ = 'git.util'
- __slots__ = ('total', 'files')
- files
- total
- git.util.assure_directory_exists(path: str | PathLike[str], is_file: bool = False) bool
确保PATH指向的目录存在。
- 参数:
is_file -- 如果
True
, path 被假定为文件并被正确处理。否则它必须是一个目录。- 返回:
True
如果创建了该目录,False
如果它已经存在的话。
- git.util.get_user_id() str
- 返回:
将当前活动的系统用户标识为
name@node
- git.util.join_path(a: str | PathLike[str], *p: str | PathLike[str]) str | PathLike[str]
将路径标记联接在一起类似于osp.Join,但始终使用
/
而不是可能\
在Windows上。
- git.util.join_path_native(a: str | PathLike[str], *p: str | PathLike[str]) str | PathLike[str]
喜欢
join_path()
,但确保返回操作系统本机路径。这只是为了在Windows上确保安全,并确保仅使用
\
。
- git.util.rmtree(path: str | PathLike[str]) None
递归删除给定的目录树。
- 注意事项:
我们用
shutil.rmtree()
但调整其行为,以查看无法删除的文件是否为只读文件。在这种情况下,Windows不会删除它们。
- git.util.stream_copy(source: BinaryIO, destination: BinaryIO, chunk_size: int = 524288) int
将所有数据从 source 流到 destination 以大块大小的溪流 chunk_size 。
- 返回:
写入的字节数
- git.util.to_native_path_linux(path: str | PathLike[str]) str
- git.util.unbare_repo(func: Callable[[...], T]) Callable[[...], T]
使用此修饰符引发的方法
InvalidGitRepositoryError
如果他们遇到一个空储存库。