我正在使用GitPython执行合并:
repo.merge_tree(branch1, branch2)
合并后,我想看看是否有任何合并冲突。我该怎么做?
答案 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。以下是如何分解的:
这里有一些代码将它们联系在一起:
# 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