使用GitPython检查合并是否存在冲突

时间:2015-12-01 21:20:32

标签: python gitpython

我正在使用GitPython执行合并:

repo.merge_tree(branch1, branch2)

合并后,我想看看是否有任何合并冲突。我该怎么做?

2 个答案:

答案 0 :(得分:5)

Nota buena:当我在自己的项目中尝试时,我还没有能够得到这个答案。我不确定是否因为我在此答案中提供的信息不正确,或者是因为我的代码中存在其他问题。

无论如何,这个答案中的信息很难找到,我相信它正确或非常接近正确,所以它仍然有用。请注意,当您使用此建议时会有龙。

合并后,GitPython将工作目录的状态存储在repo.index中。 repo.index包含一个方法index.unmerged_blobs,可让您检查已修改但未提交的每个blob(文件)的状态。 您可以迭代这些blob以查看是否存在合并冲突。

每个blob都与0到3(含)的状态相关联。状态为0的Blob已成功合并。合并后,状态为1,2或3的Blob会发生冲突。

准确地说,index.unmerged_blobs函数将文件路径字典返回到元组列表。每个元组包含一个0到3的阶段和一个blob。以下是如何分解的:

  • 字典中的每个键都是项目中某个文件的路径。
  • 每个值实际上是一个blob列表,用于修改键引用的文件。这是因为,在一般情况下,可能会有多个影响同一文件的更改。
    • 由值存储的列表中的每个条目都是元组。
      • 元组中的第一个条目是blob的阶段。合并后,阶段0表示blob没有合并冲突。 1到3的阶段意味着存在冲突。
      • 元组中的第二个条目是blob本身。如果您选择,您可以对其进行分析,以查看blob原始内容的更改。出于问题中所述的目的,您可以忽略blob。

这里有一些代码将它们联系在一起:

# We'll use this as a flag to determine whether we found any files with conflicts
found_a_conflict = False

# This gets the dictionary discussed above 
unmerged_blobs = repo.index.unmerged_blobs()

# We're really interested in the stage each blob is associated with.
# So we'll iterate through all of the paths and the entries in each value
# list, but we won't do anything with most of the values.
for path in unmerged_blobs:
  list_of_blobs = unmerged_blobs[path]
  for (stage, blob) in list_of_blobs:
    # Now we can check each stage to see whether there were any conflicts
    if stage != 0:
      found_a_conflict = true

答案 1 :(得分:1)

您可以为此创建一个函数,如下所示:

import os
import git

def git_conflicts(set_repo=os.getcwd()):
    # Get the ".git" repository using the set_repo parameter or if nothing is 
    # checked, check the current folder.
    repo = git.Repo(set_repo)

    # Check the status of the ".git" repository and move to a list.
    status_git = repo.git.status(porcelain=True).split()

    # Checks if "UU" which means conflict, is in the "status_git" list, if it 
    # has the function "conflicts" it returns True, otherwise False
    if "UU" in status_git:
        return True

    return False