使用GitPython检查合并是否有冲突

问题描述 投票:3回答:2

我正在使用GitPython执行合并:

repo.merge_tree(branch1, branch2)

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

python gitpython
2个回答
7
投票

Nota buena:当我在自己的项目中尝试此方法时,我不太能得到这个答案。我不确定这是因为我在此答案中提供的信息不正确,还是因为我的代码中还有另一个问题。

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


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

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


确切地说,index.unmerged_blobs函数将文件路径的字典返回到元组列表。每个元组包含一个从0到3的级和一个Blob。这是如何分解的:

  • 字典中的每个键都是您项目中文件之一的路径。
  • 每个值实际上是修改键引用的文件的blob列表。这是因为在通常情况下,可能会分阶段进行多个更改以影响同一文件。
    • 列表中由值存储的每个条目都是一个元组。
      • 元组的第一个条目是Blob的阶段。合并后,阶段0立即表示blob没有合并冲突。 1到3的阶段表示存在冲突。
      • 元组中的第二个条目是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

0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.