我想用Python代码解析git diff,我有兴趣从diff parser获得以下信息:
为此,我使用unidiff 0.5.2,并编写了以下代码:
from unidiff import PatchSet
import git
import os
commit_sha1 = 'b4defafcb26ab86843bbe3464a4cf54cdc978696'
repo_directory_address = '/my/git/repo'
repository = git.Repo(repo_directory_address)
commit = repository.commit(commit_sha1)
diff_index = commit.diff(commit_sha1+'~1', create_patch=True)
diff_text = reduce(lambda x, y: str(x)+os.linesep+str(y), diff_index).split(os.linesep)
patch = PatchSet(diff_text)
print patch[0].is_added_file
我正在使用GitPython生成Git diff。对于上述代码,我收到以下错误:
^{pr2}$如果你能帮我纠正这个错误,我将不胜感激。在
使用diff_index[i].diff作为tdichp的建议,并将源文件和目标文件行添加到diff中,否则unidiff将抛出。以下是我的工作代码示例:
更新:
我发现我以前的答案已经不起作用了。以下是新的解决方案:
对于这个解决方案,您需要 git 和{a2}包。在
旧解决方案(此方案可能不再有效)
最后,我找到了解决办法。gitpython的输出与标准git diff输出略有不同。在标准的git diff源文件中,以-开头,但是gitpython的输出以开头,正如您在运行以下python代码的输出中看到的那样(这个示例是用elasticsearch repository)生成的:
^{pr2}$部分输出如下:
如您所见,源文件的第4行以开头。要解决此问题,您需要编辑unidiff 0.5.2的源文件中的正则表达式,该文件位于/unidiff/constants.py中:
收件人:
PS:如果源文件重命名,gitpython将生成diff start with-。但它不会抛出错误,因为我过滤了重命名文件的git diff(diff_filter='cr')。在
相关问题 更多 >
编程相关推荐