19

我希望仅从 git repo 更改文件的差异。现在,我正在使用 gitpython 来实际获取提交对象和 git 更改的文件,但我只想对文件更改的部分进行依赖分析。有没有办法从 git python 获取 git diff?还是我必须逐行阅读来比较每个文件?

4

7 回答 7

19

如果你想访问差异的内容,试试这个:

repo = git.Repo(repo_root.as_posix())
commit_dev = repo.commit("dev")
commit_origin_dev = repo.commit("origin/dev")
diff_index = commit_origin_dev.diff(commit_dev)

for diff_item in diff_index.iter_change_type('M'):
    print("A blob:\n{}".format(diff_item.a_blob.data_stream.read().decode('utf-8')))
    print("B blob:\n{}".format(diff_item.b_blob.data_stream.read().decode('utf-8'))) 

这将打印每个文件的内容。

于 2017-09-01T21:14:37.493 回答
16

您可以将 GitPython 与 git 命令“diff”一起使用,只需使用每个提交的“tree”对象或要查看差异的分支,例如:

repo = Repo('/git/repository')
t = repo.head.commit.tree
repo.git.diff(t)

这将打印此提交中包含的所有文件的“所有”差异,因此如果您想要每个文件,您必须遍历它们。

使用实际的分支是:

repo.git.diff('HEAD~1')

希望这有帮助,问候。

于 2014-04-27T06:15:20.187 回答
5

Git does not store the diffs, as you have noticed. Given two blobs (before and after a change), you can use Python's difflib module to compare the data.

于 2013-11-19T04:36:21.720 回答
3

我建议您改用PyDriller(它在内部使用 GitPython)。更容易使用:

for commit in RepositoryMining("path_to_repo").traverse_commits():
    for modified_file in commit.modifications: # here you have the list of modified files
        print(modified_file.diff)
        # etc...

您还可以通过执行以下操作来分析单个提交:

for commit in RepositoryMining("path_to_repo", single="123213")
于 2019-02-08T11:11:36.267 回答
1

如果您想在两次提交之间对文件执行 git diff 操作,可以这样做:

import git

repo = git.Repo()
path_to_a_file = "diff_this_file_across_commits.txt"

commits_touching_path = list(repo.iter_commits(paths=path))

print repo.git.diff(commits_touching_path[0], commits_touching_path[1], path_to_a_file)

这将向您显示对您指定的文件所做的两次最新提交之间的差异。

希望这有帮助。

于 2016-09-13T05:42:29.027 回答
0

如果您希望重新创建接近标准git diff显示的内容,请尝试:

# cloned_repo = git.Repo.clone_from(
#     url=ssh_url,
#     to_path=repo_dir,
#     env={"GIT_SSH_COMMAND": "ssh -i " + SSH_KEY},
# ) 
for diff_item in cloned_repo.index.diff(None, create_patch=True):
    repo_diff += (
        f"--- a/{diff_item.a_blob.name}\n+++ b/{diff_item.b_blob.name}\n"
        f"{diff_item.diff.decode('utf-8')}\n\n"
        )
于 2021-10-01T21:50:59.330 回答
-2

我不确定你是否得到了你想要的东西!

这是你的做法

import git
repo = git.Repo("path/of/repo/")

# the below gives us all commits
repo.commits()

# take the first and last commit

a_commit = repo.commits()[0]
b_commit = repo.commits()[1]

# now get the diff
repo.diff(a_commit,b_commit)

干杯。

于 2014-03-07T09:12:22.663 回答