现实中我们常碰到这样的情况,新建一个feature分支,做了一些修改,git commit和push,花了好几天时间完成测试,提交pull request,这时发现主分支(main或master)已经有很多改动了,费劲地把所有conflicts解决了,merge进主分支后你看到的时间线是这样的:
![](https://i-blog.csdnimg.cn/blog_migrate/587cdc838c0e30632420aea46a45efb2.png)
你希望看到时间线是干净整洁、线性的:
![](https://i-blog.csdnimg.cn/blog_migrate/e18da997365674c612a4c6dba232d034.png)
这时我们需要使用git rebase
下面是简单的场景模拟。
先创建feature分支,做feature 1修改,然后git commit和push
回到main分支,做feature 2修改,然后git commit和push
创建pull request feature -> master,解决冲突,merge
$ git branch feature
$ git checkout feature
$ echo 'add feature 1' >> afile.txt
$ git add .
$ git commit -m "add feature 1"
$ git push --set-upstream origin feature
$ git checkout main
$ echo 'add feature 2' >> afile.txt
$ git add .
$ git commit -m "add feature 2"
$ git push
git历史时间线是这样的,你会发现feature 1早于feature 2
![](https://i-blog.csdnimg.cn/blog_migrate/27abad6ebee6dbf6da760a5f967704a0.png)
其实在pull request之前我们可以切回到feature分支,rebase一下,把自己的修改放到时间线的最前面。
$ git branch feature
$ git rebase origin/main
Auto-merging afile.txt
CONFLICT (content): Merge conflict in afile.txt
error: could not apply 08a800d... add feature 1
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Could not apply 08a800d... add feature 1
$ git status
interactive rebase in progress; onto 819aa7c
Last command done (1 command done):
pick 08a800d add feature 1
No commands remaining.
You are currently rebasing branch 'new-feature' on '819aa7c'.
(fix conflicts and then run "git rebase --continue")
(use "git rebase --skip" to skip this patch)
(use "git rebase --abort" to check out the original branch)
Unmerged paths:
(use "git restore --staged <file>..." to unstage)
(use "git add <file>..." to mark resolution)
both modified: afile.txt
$ git rebase --continue
afile.txt: needs merge
You must edit all merge conflicts and then
mark them as resolved using git add
$ git add .
$ git rebase --continue
$ git push -f
rebase以后你的feature 1就晚于feature 2了。
![](https://i-blog.csdnimg.cn/blog_migrate/ddbefc678e3def07d949deae301fc6c9.png)
这时再提交pull request,无需处理任何conflict就可以合版了,main分支的记录是干净整洁线性的。
![](https://i-blog.csdnimg.cn/blog_migrate/e95956c2d37aa077b04d031a31ad815c.png)
![](https://i-blog.csdnimg.cn/blog_migrate/8ba3ed5d6598bcbe0ca3a543ca66a3ae.png)