gitpython和git diff

时间:2013-11-19 02:19:50

标签: git git-diff gitpython

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

6 个答案:

答案 0 :(得分:9)

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

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

这将打印"所有"这个提交中包含的所有文件的差异,所以如果你想要每个文件,你必须迭代它们。

使用实际分支:

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

希望对此有所帮助。

答案 1 :(得分:5)

如果要访问diff的内容,请尝试以下操作:

select text, from_user_id, to_user_id, created
from message m1
where 13 in (from_user_id, to_user_id)
and not exists
(
  select *
  from message m2
  where 13 in (m2.from_user_id, m2.to_user_id)
  and m2.from_user_id + m2.to_user_id = m1.from_user_id + m1.to_user_id
  and m2.created > m1.created
);

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

答案 2 :(得分:4)

正如您所注意到的,Git不存储差异。给定两个blob(更改前后),您可以使用Python's difflib module来比较数据。

答案 3 :(得分:1)

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

>>> a = torch.ByteTensor([0, 1, 1, 0])
>>> b = torch.ByteTensor([1, 1, 0, 0])

>>> a & b  # logical and
tensor([0, 1, 0, 0], dtype=torch.uint8)

>>> a | b  # logical or
tensor([1, 1, 1, 0], dtype=torch.uint8)

>>> a ^ b  # logical xor
tensor([1, 0, 1, 0], dtype=torch.uint8)

>>> ~a  # logical not
tensor([1, 0, 0, 1], dtype=torch.uint8)

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

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

答案 4 :(得分:0)

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

这是你如何做的

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)

干杯。

答案 5 :(得分:0)

如果你想在两次提交之间的文件上执行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)

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

希望这会有所帮助。