Alo*_*lon 2 python git gitpython
当我运行时git log,每次提交都会得到这一行:“作者:姓名 <电子邮件>”。如何在 Python 中为本地存储库获取完全相同的提交格式?当我运行下面的代码时,我只得到作者姓名。
from git import Repo
repo_path = 'mockito'
repo = Repo(repo_path)
commits_list = list(repo.iter_commits())
for i in range(5):
commit = commits_list[i]
print(commit.hexsha)
print(commit.author)
print(commit.committer)
Run Code Online (Sandbox Code Playgroud)
根据该gitpython API文档,一个commit对象的-an实例class git.objects.commit.Commit都具有一个author和committer属性,这些属性是的实例class git.util.Actor,这反过来又具有字段conf_email,conf_name,email,和name。
因此(未经测试):
print(commit.author.name, commit.author.email)
Run Code Online (Sandbox Code Playgroud)
可能会为您提供您想要的两个字段,但您可能希望以某种方式格式化它们。
编辑:我将遵循 Gino Mempin 的回答,因为我没有安装 gitpython 来测试这个。
似乎 gitpython 的Commit对象没有作者电子邮件的属性。
也可以使用 gitpython直接调用 git 命令。您可以使用该git show命令,传入提交 HASH(来自commit.hexsha),然后传入一个--format仅提供作者姓名和电子邮件的选项(您当然可以传递您需要的其他格式选项)。
使用普通的 git:
$ git show -s --format='%an <%ae>' 4e13ccfbde2872c23aec4f105f334c3ae0cb4bf8
me <me@somewhere.com>
Run Code Online (Sandbox Code Playgroud)
使用 gitpython直接使用 git:
from git import Repo
repo_path = 'myrepo'
repo = Repo(repo_path)
commits_list = list(repo.iter_commits())
for i in range(5):
commit = commits_list[i]
author = repo.git.show("-s", "--format=Author: %an <%ae>", commit.hexsha)
print(author)
Run Code Online (Sandbox Code Playgroud)