Git会在冲突文件中标记冲突区域:
|
1 2 3 4 5 |
<<<<<<< HEAD 当前分支的代码 ======= 合并分支的代码 >>>>>>> branch-name |
|
1 2 3 4 5 |
# 查看哪些文件有冲突 git status
# 查看具体冲突内容 git diff |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# 方法1:中止合并,回到合并前状态 git merge --abort git rebase --abort
# 方法2:手动解决后继续 # 编辑冲突文件 → 标记为已解决 → 完成合并 git add <resolved-file> git commit # 或 git rebase --continue
# 方法3:使用某一方版本(慎用) # 保留当前分支版本 git checkout --ours <file> # 保留合并分支版本 git checkout --theirs <file> |
|
1 2 3 4 5 |
# 编译测试 make test
# 运行自动化测试 npm test # 或相应项目的测试命令 |
|
1 2 3 4 5 6 7 8 |
# 标准流程 git merge feature-branch # 出现冲突后... # 1. 编辑冲突文件 # 2. 添加解决的文件 git add . # 3. 完成合并 git commit |
|
1 2 3 4 5 6 7 8 9 10 |
# 变基流程 git rebase main # 每次提交都可能产生冲突 # 解决后... git add . git rebase --continue # 或跳过当前提交(慎用) git rebase --skip # 或中止变基 git rebase --abort |
|
1 2 3 4 5 6 |
# 相当于 git fetch + git merge # 建议使用 rebase 方式 git pull --rebase origin main # 解决冲突后 git add . git rebase --continue |
|
1 2 3 4 5 6 7 8 |
# 查看工作区和暂存区的差异 git diff
# 查看暂存区和仓库的差异 git diff --cached
# 查看两个分支的差异 git diff branch1..branch2 |
|
1 2 3 4 5 6 |
# 配置VS Code为默认合并工具 git config --global merge.tool vscode git config --global mergetool.vscode.cmd 'code --wait $MERGED'
# 使用合并工具 git mergetool |
|
1 2 3 4 5 6 7 |
# 一次性接受所有 ours/theirs 版本 # 使用ours策略(保留当前分支) git merge -X ours branch-name
# 批量解决相似冲突 git checkout --ours -- path/to/directory git add path/to/directory |
|
1 2 |
# 查找包含冲突标记的文件 grep -r "<<<<<<<" . # 或使用 git grep "<<<<<<<" |
|
1 2 3 4 |
# 检查是否所有冲突都解决 git status # 检查是否有未添加的文件 git add . |
|
1 2 3 4 |
# 查看合并历史 git log --merges --oneline # 查看特定合并的详细信息 git show <merge-commit-id> |
|
1 2 3 4 5 6 |
遇到冲突时: 1. git status 查看冲突文件 2. 编辑文件解决冲突(删除<<<<<<<等标记) 3. git add 标记为已解决 4. git commit/git rebase --continue 完成操作 5. 运行测试确保正确性 |
通过掌握以上方法和工具,Git冲突将不再是开发中的障碍,而是团队协作和代码质量控制的有益环节。记住:每次冲突的解决都是对代码理解加深的机会。