git是一个很好用的版本管理工具,然而,有时候一些冲突还是让人很郁闷的。
遇到过两次​​​merge​​报错,是在不同的情形下出现的。

  • 本地分支各自​​commit​​​之后,​​merge​
  • 本地​​master​​​分支 pull 远程​​master​​分支

下面记录以下两种情况的处理。

情形1:


我在本地仓库的两条分支​​dev​​​和 ​​master​​​同时开发,各自经过2个提交之后,​​merge​​报错:

fatal: Not possible to fast-forward, aborting.

如果git环境是中文的,那么这个错误信息就是这样的:

fatal:无法快进,终止。

问题的原因:

两个分之同时改了同样的地方,造成冲突。
按理,这种冲突也可以直接运行​​​merge​​​,然后手动解决这些冲突,再​​commit​​​就行了。
然而,这次不行。

那就使用另一种合并分支的办法:​​rebase​​​,我的目的是将​​dev​​​合并到​​master​​​,然后删除​​dev​​:

git checkout master
git rebase dev

这时候报以下错误:

First, rewinding head to replay your work on top of it...
Applying: text:I am on master
Using index info to reconstruct a base tree...
M a.txt
Falling back to patching base and 3-way merge...
Auto-merging a.txt
CONFLICT (content): Merge conflict in a.txt
error: Failed to merge in the changes.
Patch failed at 0001 text:I am on master
The copy of the patch that failed is found in: .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

这时候需要手动去修改冲突的地方:

<<<<<<< HEAD
I am on dev

I am on my mark.
=======
I am on master
>>>>>>> text:I am on master

然后,根据上面报错的提示信息,​​continue​

When you have resolved this problem, run "git rebase --continue".
git rebase --continue

a.txt: needs merge
You must edit all merge conflicts and then
mark them as resolved using git add

根据提示,​​add​​之后,再看下状态:

git add .
git status

rebase in progress; onto 6114f0b
You are currently rebasing branch 'master' on '6114f0b'.
(all conflicts fixed: run "git rebase --continue")

Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

modified: a.txt

已经提示冲突都已经解决,可以继续了:

git rebase --continue

Applying: text:I am on master
Applying: commit 2nd
Using index info to reconstruct a base tree...
M a.txt
Falling back to patching base and 3-way merge...
Auto-merging a.txt

这时候​​dev​​​分支已经完全合并到了​​master​​分支上了:

git status

On branch master
nothing to commit, working tree clean

情形2:


其实处理方式跟情形1是一样的,只是稍有不同。

git pull origin master

From https://gitee.com/leonxtp/xxxxx
* branch master -> FETCH_HEAD
fatal: Not possible to fast-forward, aborting.

这时候直接应用​​rebase​​解决:

git pull origin master --rebase

First, rewinding head to replay your work on top of it...
Applying: xxxxxx
Using index info to reconstruct a base tree...
M gradle.properties
Falling back to patching base and 3-way merge...
Auto-merging path/of/file...
Auto-merging path/of/file...
Applying: yyyyyyy
...

关于​​merge​​​和​​rebase​​​的区别,可以参考:​​这篇文章​​​。
个人总结起来就是:

  • ​merge​​​不影响原来的​​commit​​​,并会新增一个合并的​​commit​​。
  • ​rebase​​是将目标分支插入到两个分支的共同祖先与当前分支的最后面(不是最新)之间,并且修改当前分支原来的commit,但不会增加新的​​commit​​。

问题解决参考​​SOF​​。