繁体   English   中英

使用 GitPython 检查合并冲突

[英]Check merge for conflicts using GitPython

我正在使用 GitPython 执行合并:

repo.merge_tree(branch1, branch2)

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

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 原始内容的变化。 出于问题中所述的目的,您可以忽略斑点。

这是一些将它们联系在一起的代码:

# 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM