Git 合并冲突是多人协作开发中常见的问题,以下是一套完整的解决方案:
当合并或拉取代码时遇到冲突,Git 会显示类似消息:
CONFLICT (content): Merge conflict in <filename>
Automatic merge failed; fix conflicts and then commit the result.
冲突文件会包含特殊标记:
<<<<<<< HEAD
你的代码
=======
别人的代码
>>>>>>> branch-name
git status
会显示所有冲突文件<<<<<<<
, =======
, >>>>>>>
),保留正确的代码git add <filename>
或 git add .
git commit
(Git 会提供默认合并消息)git mergetool
:启动配置的合并工具(如 vimdiff, kdiff3 等)git diff
:查看当前所有冲突git checkout --ours/--theirs <file>
:选择保留当前分支或合并分支的版本git merge --abort
:放弃当前合并尝试,回到合并前状态git reset --hard
:重置所有更改(谨慎使用)git merge --no-commit
先不自动提交git rerere
(reuse recorded resolution) 功能可以记住冲突解决方案git pull --rebase
定期同步远程变更git checkout --ours/--theirs
选择完整文件记住:解决冲突后务必测试代码,确保合并后的版本能正常工作。