在GitPython中迭代提交b / w 2指定的提交

问题描述 投票:1回答:3
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()方法做同样的事情。

python git loops commit gitpython
3个回答
2
投票

你可以使用纯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


1
投票

我建议你使用PyDriller(一个围绕GitPython的包装器,以使事情变得更容易)。你问的问题可以这样做:

for commit in RepositoryMining("path_to_repo", from_commit="first", to_commit="second").traverse_commits():
    # your code

-1
投票

首先,创建一个运行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))

希望这可以提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.