问题
When I run git log
, I get the this line for each commit: "Author: name < email >". How do I get the exact same format for a commit in Python for a local repo? When I run the code below, I get just the author name.
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)
回答1:
It seems that gitpython's Commit
objects do not have an attribute for the author email.
You can also use gitpython to call git commands directly. You can use the git show command, passing in the commit HASH (from commit.hexsha
) and then a --format option that gives you just the author's name and email (you can of course pass other format options you need).
Using plain git:
$ git show -s --format='%an <%ae>' 4e13ccfbde2872c23aec4f105f334c3ae0cb4bf8
me <me@somewhere.com>
Using gitpython to use git directly:
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)
回答2:
According to the gitpython API documentation, a commit object—an instance of class git.objects.commit.Commit
—has author
and committer
attributes that are instances of class git.util.Actor, which in turn has fields conf_email
, conf_name
, email
, and name
.
Hence (untested):
print(commit.author.name, commit.author.email)
will likely get you the two fields you want, though you may wish to format them in some way.
Edit: I'll defer to Gino Mempin's answer since I don't have gitpython installed to test this.
来源:https://stackoverflow.com/questions/58550252/how-to-get-commit-author-name-and-email-with-gitpython