git学习 分支管理(2):解决分支合并冲突(第六天)
发布日期:2021-05-14 08:43:18 浏览次数:22 分类:精选文章

本文共 2304 字,大约阅读时间需要 7 分钟。

分支管理

人生不如意之事有十之八九,合并分支往往也不是一帆风顺的。当然,如果不会合并请参考以下步骤。

分支冲突

准备新的 feature1 分支,继续我们的新分支开发:

asus@XXX MINGW64 /e/Git_warehouse (master)$ git switch -c feature1
Switched to a new branch 'feature1'
asus@XXX MINGW64 /e/Git_warehouse (feature1)$ git branch * feature1 master

修改 readme.txt 的最后一行,改为:

Creating a new branch is quick and simple.

feature1 分支上提交:

asus@XXX MINGW64 /e/Git_warehouse (feature1)$ git add readme.txt
asus@XXX MINGW64 /e/Git_warehouse (feature1)$ git commit -m "and simple"

切换到 master 分支:

asus@XXX MINGW64 /e/Git_warehouse (feature1)$ git switch master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
asus@XXX MINGW64 /e/Git_warehouse (master)$ git branch feature1* master

master 分支上修改 readme.txt 的最后一行:

Creating a new branch is quick & simple.

master 分支上提交 readme.txt

asus@XXX MINGW64 /e/Git_warehouse (master)$ git add readme.txt
asus@XXX MINGW64 /e/Git_warehouse (master)$ git commit -m "& simple"

此时,master 分支和 feature1 分支各自都分别有新的提交。

解决冲突

这种情况下,Git 无法执行“快速合并”,只能试图把各自的修改合并起来,但这种合并就可能会有冲突。运行以下命令尝试:

git merge feature1

结果显示冲突:

Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Automatic merge failed; fix conflicts and then commit the result.

果然冲突了!Git 告诉我们 readme.txt 存在冲突,必须手动解决冲突后再提交。运行 git status 可以看到冲突的文件:

git status

输出结果显示:

On branch master
Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)
You have unmerged paths. (fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
both modified: readme.txt
(no changes added to commit (use "git add" and/or "git commit -a"))

我们可以直接查看 readme.txt 的内容,使用合适的编辑器(如 Notepad++ 或 Vim)去掉其他部分,保留我们希望的内容:

Creating a new branch is quick and simple.

保存文件后,继续提交:

git add readme.txt
git status

运行后,状态显示:

On branch master
Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)
All conflicts fixed but you are still merging. (use "git commit" to conclude merge)
Changes to be committed:
modified: readme.txt

继续提交:

git commit -m "conflict fixed"

此时,master 分支和 feature1 分支变为了下图所示。

最后,删除 feature1 分支:

git branch -d feature1
Deleted branch feature1 (was 2809b02).
git branch * master

小结

当 Git 无法自动合并分支时,必须首先解决冲突。解决冲突后,再提交,合并完成。解决冲突就是手动编辑 Git 合并失败的文件为我们希望的内容,再提交。

上一篇:git学习 分支管理(3):分支管理策略——禁用Fast forward模式(分支图)(第七天)
下一篇:抱歉,又得鸽两天了

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月20日 14时29分53秒