如何在GitPython中使用git blame?

4
我正在尝试在我的脚本中使用GitPython模块,但无法使用。这方面的文档不是很详细:GitPython Blame 我认为我并没有离目标太远,因为我想要复制的通常 Git blame 命令如下: 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)

以下两行代码是为了最终目标,在我的"lineDeb.txt"文件中对每个行号进行git blame。

我有以下输出:

...
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
...

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

2个回答

5
for commit, lines in repo.blame('HEAD', filepath):
    print("%s changed these lines: %s" % (commit, lines))
commit是修改了给定lines的那个提交,按照文件中出现的顺序排列。因此,如果您将所有lines写入文件,则在修订版HEAD中会在filepath找到该文件。

如果您只想查找特定行,并且当前没有可以传递给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


1
谢谢回答。我看到了这个命令 repo.blame('HEAD', filepath),但是我该如何只针对特定行(例如第127行)进行责备,并获取提交者的电子邮件? - Algorys
Python不允许在函数外使用return commit,但是只用print就可以。谢谢。 - Algorys

1
如果你在抱怨代码行数过多,你可以尝试以下方法来提高性能:
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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接