我在使用 python 检索 git repo 的以下信息时遇到问题:
- 我想获取此存储库的所有标签的列表。
- 我想签出另一个分支并创建一个新的分期分支。
- 我想用带注释的标签来标记提交。
我查看了德威的文档,它的工作方式似乎非常简单。还有更容易使用的替代品吗?
使用 Dulwich 获取所有标签的最简单方法是:
from dulwich.repo import Repo
r = Repo("/path/to/repo")
tags = r.refs.as_dict("refs/tags")
tags现在是一个字典,将标签映射到提交 SHA1。
检查另一个分支:
r.refs.set_symbolic_ref("HEAD", "refs/heads/foo")
r.reset_index()
创建分支:
r.refs["refs/heads/foo"] = head_sha1_of_new_branch
现在您还可以获得按字母顺序排列的标签标签列表。
from dulwich.repo import Repo
from dulwich.porcelain import tag_list
repo = Repo('.')
tag_labels = tag_list(repo)
通过调用 git subprocess
。从我自己的程序之一:
def gitcmd(cmds, output=False):
"""Run the specified git command.
Arguments:
cmds -- command string or list of strings of command and arguments
output -- wether the output should be captured and returned, or
just the return value
"""
if isinstance(cmds, str):
if ' ' in cmds:
raise ValueError('No spaces in single command allowed.')
cmds = [cmds] # make it into a list.
# at this point we'll assume cmds was a list.
cmds = ['git'] + cmds # prepend with git
if output: # should the output be captured?
rv = subprocess.check_output(cmds, stderr=subprocess.STDOUT).decode()
else:
with open(os.devnull, 'w') as bb:
rv = subprocess.call(cmds, stdout=bb, stderr=bb)
return rv
一些例子:
rv = gitcmd(['gc', '--auto', '--quiet',])
outp = gitcmd('status', True)