![](/img/trans.png)
[英]gitpython to check for if there are any changes in files using PYTHON
[英]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。 这是分解的方式:
这是一些将它们联系在一起的代码:
# 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.