import git
repo = git.Repo(repo_dir)
ref_name = 'master'
for commit in repo.iter_commits(rev=ref_name):
<some code here>
此代码遍历所有提交。我想迭代b / w 2提交。就像git log commit1...commit2
一样
我怎样才能使用GitPython的iter_commits()方法做同样的事情。
你可以使用纯gitpython。
如果你想能够遍历某些提交(假设第一次提交是HEAD),只需使用max_count
。见The Commit object
two_commits = list(repo.iter_commits('master', max_count=2))
assert len(two_commits) == 2
如果你想要像你提到的git log commit1...commit2
相似的能力:
logs = repo.git.log("--oneline", "f5035ce..f63d26b")
会给你:
>>> logs
'f63d26b Fix urxvt name to match debian repo\n571f449 Add more key for helm-org-rifle\nbea2697 Drop bm package'
你也可以使用logs = repo.git.log("f5035ce..f63d26b")
但它会给你所有信息(就像你使用没有git log
的--oneline
)
如果你想要不错的输出,请使用漂亮的打印:
from pprint import pprint as pp
>>> pp(logs)
('f63d26b Fix urxvt name to match debian repo\n'
'571f449 Add more key for helm-org-rifle\n'
'bea2697 Drop bm package')
有关repo.git.log
的更多解释,请参阅https://stackoverflow.com/a/55545500/6000005
我建议你使用PyDriller(一个围绕GitPython的包装器,以使事情变得更容易)。你问的问题可以这样做:
for commit in RepositoryMining("path_to_repo", from_commit="first", to_commit="second").traverse_commits():
# your code
首先,创建一个运行git
命令的函数。
from git import *
from subprocess import Popen, PIPE
def execute_gitcmd(cmd, repo):
pipe = subprocess.Popen(cmd, shell=True, cwd=repo, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, error) = pipe.communicate()
return out, error
pipe.wait()
然后在终端上使用时编写任何git
命令,例如:
gitcmd = "git log -n1 --oneline"
最后,调用你的函数:
log = (execute_gitcmd(gitcmd, your_repository))
希望这可以提供帮助。