Skip to main content

git

📅 2026-03-25 ✏️ 2026-03-25 CS CLI
No related notes

1 · git#

1.1 · conflict#

多个分支对同文件同位置进行了不同的修改,然后尝试合并时,

Git 无法自动决定使用哪个版本的代码,因为两个修改都有效但互相排斥,

如何识别冲突?如何解决冲突?如何避免冲突?

  • 识别冲突
git merge <branch>  # 如果有冲突会提示
git status          # 显示冲突文件状态为 "both modified"

冲突标记:

<<<<<<< HEAD
当前分支的代码
=======
要合并的分支的代码
>>>>>>> feature-branch
  • 解决冲突
  1. 编辑文件:手动选择要保留的代码

  2. 或用 git checkout 选择

    git checkout --ours <file>    # 选择一个版本
    git checkout --theirs <file>  # 或选择另一个版本

    merge 时

    • --ours:当前分支(HEAD)的版本
    • --theirs:要合并的分支的版本

    rebase 时(相反):

    • --ours:即将 apply 的 commit 的代码
    • --theirs:rebase 基础(目标分支)的代码
  3. 标记已解决

    git add <file>
    
    # merge 冲突后
    git commit -m "Resolve conflict"
    
    # rebase 冲突后
    git rebase --continue
  • 避免冲突
    • 频繁拉取主分支更新
    • 将大功能分成小的、独立的 PR
    • 定期合并长期分支
    • 使用 rebase 而非 merge 保持历史线性

为什么 merge 和 rebase 的定义相反?#

都是 apply commits,但接收方不同

操作位置apply 的来源接收方ourstheirs
merge停留在 HEAD外部分支HEAD(稳定)HEAD外部分支
rebase移动到目标分支当前分支的 commits目标分支(稳定)当前分支 commits目标分支

语义:ours = 我们已有的稳定代码,theirs = 要整合进来的新代码

  • merge:我们在 HEAD,别人的代码来进来 → ours = HEAD
  • rebase:我们的 commits 要重新放到别处 → ours = 我们的 commits

记忆

  • merge:ours = HEAD(我们),theirs = incoming(他们)
  • rebase:ours = commit being rebased,theirs = target branch