Skip to content

合并 Conflict Resolution

中等 约 20 分钟

你将构建什么

仓库哪里 two 分支更改相同行 的相同 file, 创建 conflict. 你将 resolve conflict manually and 完整合并.

学习目标

  • 创建合并 conflict intentionally
  • 读取 and 理解 conflict markers (<<<<<<<, =======, >>>>>>>)
  • Resolve conflict 通过编辑 file
  • 完整合并使用 git 添加 and git 提交

前置要求

  • git 分支, checkout, 合并 (分支 Workflow Simulation)

步骤

  1. 1

    设置基础 file

    创建仓库使用配置 file 那个两者都分支将 修改 differently.

    代码
    mkdir conflict-demo
    cd conflict-demo
    git init
    echo "port=3000" > config.txt
    git add .
    git commit -m "Add config with port 3000"

    预期结果

    仓库 on 主要使用 one 提交包含配置.txt.

  2. 2

    创建 conflicting 更改 on two 分支

    创建 feature 分支那个更改 port 到 8080, 然后切换后面到 主要 and 更改 port 到 5000. 两者都分支修改相同行.

    代码
    git checkout -b feature/api-port
    echo "port=8080" > config.txt
    git commit -am "Change port to 8080 for API"
    git checkout main
    echo "port=5000" > config.txt
    git commit -am "Change port to 5000 for dev"

    预期结果

    两者都分支更改相同行 到不同值.

  3. 3

    合并 and hit conflict

    合并 feature 分支到 主要. Git 将 report 合并 conflict 因为两者都分支更改相同行.

    代码
    git merge feature/api-port

    预期结果

    Git prints 'CONFLICT (内容): 合并 conflict in 配置.txt' and pauses 合并.

  4. 4

    Examine and resolve conflict

    打开配置.txt — 你将 see conflict markers. 小节之间 <<<<<<< HEAD and ======= 是你的主要分支 version; 之间 ======= and >>>>>>> 是 feature 分支 version. 编辑 file 到 keep 正确 version (8080) and 移除所有 markers.

    代码
    cat config.txt
    # You see:
    # <<<<<<< HEAD
    # port=5000
    # =======
    # port=8080
    # >>>>>>> feature/api-port
    
    # Resolve: keep 8080, remove markers
    echo "port=8080" > config.txt

    预期结果

    配置.txt 包含仅 'port=8080' 使用否 conflict markers.

  5. 5

    完整合并

    Stage resolved file and 提交到 完整合并. conflict 是 resolved and 合并是 recorded in history.

    代码
    git add config.txt
    git commit -m "Merge feature/api-port: resolve port conflict, use 8080"
    git log --oneline

    预期结果

    合并是 完整; git log shows 合并提交.

自己动手试试

你学到了什么

你创建, examined, and resolved 合并 conflict 从开始到 finish. Conflicts 是不 scary — 它们是 只是 Git asking 你到 选择之间 two versions. 读取 markers, 选取正确 version, stage, and 提交.

相关资源

相关课程

相关速查表

相关错误

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题