git 差异 hexsha:directorypath/file

git diff hexsha:directorypath/file

鉴于 hexshadirectoryfile 是已知的,我怎样才能获得 2 个特定文件之间的差异,例如以下将 return 差异两次修订之间:

irepo.git.diff("93ba8ae12f79e7f90e5ec5217e44ce28624a66d8..d144da4b5f0dff89b918bc88629cb7902150d77c")

但是,我怎样才能生成包含在上述两个修订版中的 <directory>/<file> 的差异?

您可以使用 GitPython 的内置差异工具来做到这一点。

import git
r = git.Repo(path_to_repo)
diff_index = r.commit(lhs_hexsha).diff(rhs_hexsha, create_patch=True)
# find all modified paths you are interested in
for diff_info in diff_index.iter_change_type('M'):
    if diff_info.a_blob.path == my_path:
        print(str(diff_info))

点击链接以获取有关其中包含的 diffing objects, the diff() call, the returned DiffIndex object, or the Diff objects 的更多信息。

示例中引用的 a_blob 是一个 Blob 对象,它在 lhs_hexsha 提交时提供对比较文件的读取访问。还有一个 b_blob 代表文件在 rhs_hexsha.

提交时的状态