Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
gitpython和gitdiff_Git_Git Diff_Gitpython - Fatal编程技术网

gitpython和gitdiff

gitpython和gitdiff,git,git-diff,gitpython,Git,Git Diff,Gitpython,我希望只获得从git回购更改的文件的差异。现在,我正在使用gitpython实际获取git更改的提交对象和文件,但我只想对文件更改的部分进行依赖性分析。有什么方法可以从GitPython获得git diff吗?或者我必须通过逐行读取来比较每个文件吗?正如您所注意到的,Git不存储差异。给定两个blob(更改前后),您可以使用来比较数据。我不确定您是否得到了所需的数据 这是你怎么做的 import git repo = git.Repo("path/of/repo/") # the below

我希望只获得从git回购更改的文件的差异。现在,我正在使用gitpython实际获取git更改的提交对象和文件,但我只想对文件更改的部分进行依赖性分析。有什么方法可以从GitPython获得git diff吗?或者我必须通过逐行读取来比较每个文件吗?

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

我不确定您是否得到了所需的数据

这是你怎么做的

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)

干杯。

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

repo = Repo('/git/repository')
t = repo.head.commit.tree
repo.git.diff(t)
这将打印此提交中包含的所有文件的“所有”差异,因此如果您想要每个文件,必须对它们进行迭代

对于实际分支,它是:

repo.git.diff('HEAD~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)
这将显示对指定文件执行的两个最新提交之间的差异


希望这有帮助。

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

repo=git.repo(repo\u root.as\u posix())
commit\u dev=repo.commit(“dev”)
commit\u origin\u dev=repo.commit(“origin/dev”)
diff\u index=commit\u origin\u dev.diff(commit\u dev)
对于差异索引中的差异项。iter变更类型('M'):
打印(“A blob:\n{}”.format(diff_item.A_blob.data_stream.read().decode('utf-8'))
打印(“B blob:\n{}”.format(diff_item.B_blob.data_stream.read().decode('utf-8'))

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

我建议您改用(它在内部使用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")

我正在处理的回购协议只有一个主分支。如果我试图得到两个斑点,如何得到第二个斑点来比较更改前的斑点?对不起,这是另一个问题。因此,除了尝试获取a blob和b blob并了解它们是什么之外,这些blob是否真的会给我文件内容的更改?@user1816561如果您指的是工作树中的两个blob与最近提交的两个blob,您应该使用
repo.head.commit.diff(None)
此代码不起作用<代码>属性错误:“Repo”对象没有属性“diff”并且
属性错误:“Repo”对象没有属性“commits”
非常好。这是使用gitpythonapi实现的方法,而不是像这样直接委托给gitcli。