如何在 GitPython 中使用 git blame?

How to use git blame in GitPython?

我正在尝试在我的脚本中使用 GitPython 模块...但我不能。这不是很好的记录:GitPython Blame

我想我还不算太远,因为通常 git 我想重现的是以下内容:git blame -L127,+1 ../../core/src/filepath.cpp -e

这是我的脚本:

from git import *
    repo = Repo("C:\Path\to\my\repos\")
    assert not repo.bare
    # log_line = open("lineDeb.txt")
    # for line in log_line:
    repo.git.blame(L='127,+1' '../../core/src/filepath.cpp', e=True)

评论的两行是为了最终目标 git 归咎于我的 "lineDeb.txt" 文件中的每个数字行。

我有以下输出:

...
git.exc.GitCommandError: 'git blame -L127,+1../../core/src/filepath.cpp -e' returned with exit code 129
stderr: 'usage: git blame [options] [rev-opts] [rev] [--] file
...

我知道我可以使用 os 模块,但我想保留 python。

如果这个模块的专家或python可以帮助我?

可能是我没有正确使用 GitPython?

目标是获取行提交者的电子邮件...

提前致谢。

for commit, lines in repo.blame('HEAD', filepath):
    print("%s changed these lines: %s" % (commit, lines))

commit 是根据文件中出现的顺序更改给定 lines 的那个。因此,如果您将所有 lines 写入一个文件,您的文件将位于 filepath 修订版 HEAD.

如果您只查找特定行,并且由于当前没有可以传递给 blame 子命令的选项,您将不得不自己计算到该行。

ln = 127 # lines start at 0 here
tlc = 0

for commit, lines in repo.blame('HEAD', filepath):
    if tlc <= ln < (tlc + len(lines)):
         print(commit)
    tlc += len(lines)

这不如将相应的 -L 选项传递给 git blame 最佳,但应该可以完成工作。

如果发现速度太慢,你可以考虑做一个 PR,将 **kwargs 添加到 Repo.blame 以传递给 git blame

如果您指责大量行,您可能会发现此性能更高:

blame = []
cmd = 'cd {path};git blame {fname}'.format(
            path=repo_path,
            fname=rootpath + fname)
with os.popen(cmd) as process:
   blame = process.readlines()

print blame[line_number]