Git rebase学习笔记
Git rebase
用法
git rebase
[-i | --interactive]
[options]
[--exec <cmd>]
[--onto <newbase>]
[<upstream> [<branch>]]
git rebase
[-i | --interactive]
[options]
[--exec <cmd>]
[--onto <newbase>]
--root
[<branch>]
git rebase --continue | --skip | --abort | --quit | --edit-todo
在日常提交代码的过程中,我想我用到频率最高的命令之一就是git pull --rebase, 很多人都知道,默认情况下,git pull就相当于执行了如下命令:
git fetch
git merge FETCH_HEAD
而git pull --rebase:
git fetch
git rebase FETCH_HEAD
但是git merge FETCH_HEAD 和 git rebase FETCH_HEAD背后都作了什么有时候我并不是很清楚,想弄懂这些可以去看看git的官方文档,其实就是git --help中的内容。
rebase
通常我使用rebase最多的方式基本就是这样:
git rebase [<upsteram>] [<branch>]
��
这有一个小点是:
如果指定了<branch>,git rebase 将会在执行其它动作之前自动执行git checkout <branch>。
假设存在如下的提交history,当前我的工作branch是"topic":
A---B---C topic
/
D---E---F---G master
此时,无论我们执行如下命令中的任何一个命令:
git rebase master
git rebase master topic
都会得到:
A'--B'--C' topic
/
D---E---F---G master
至于为什么为一样,我想你懂的。需要注意的是A, B, C都变成了A', B', C',虽然它们的commit信息都一样,但commit hash已经改变,这表明它们已经是不同的commit。
还有一点,假设upstream分支已经有一个commit A',而在你的新分支上有一个commit A,这个commit所修改的内容都一样,那么在rebase过程中,A将会被跳过。
例如:
A---B---C topic
/
D---E---A'---F master
执行git rebase master topic后:
B'---C' topic
/
D---E---A'---F master
rebase --onto
首先,假设你的topic是基于next分支的,例如,一个在topic分支上开发的feature依赖于next分支上的一些功能。
o---o---o---o---o master
\
o---o---o---o---o next
\
o---o---o topic
我想使topic分支是从master分支fork出来的。例如,topic分支所依赖的功能已经merge到更加稳定的master分支了,然后,我们想让我们的tree就成下面这样:
o---o---o---o---o master
| \
| o'--o'--o' topic
\
o---o---o---o---o next
我们可以使用如下命令:
git rebase --onto master next topi�c
另外一个关于--onto option的例子是rebase分支的一部分。如果我们有如下的情形:
H---I---J topicB
/
E---F---G topicA
/
A---B---C---D master
当执行命令:
git rebase --onto master topicA topicB
结果将成为:
H'--I'--J' topicB
/
| E---F---G topicA
|/
A---B---C---D master
但是需要注意的是,这个情况适用于,topicB并不依赖于topicA.
一个区间内的commits也可以使用rebase将其移除。如果我们有如下的情形:
E---F---G---H---I---J topicA
当执行命令:
git rebase --onto topicA~�5 topicA~3 topic��A
将会导致F和G被移除了:
E---H'---I'---J' topicA
这在F和G不应该在topicA分支上的情况下很有用。
从upstream恢复rebase
假设一个分支A,但是分支A已经有其它分支基于它了,这时去rebase A是不太好的: 因为这样它的任何一个downstream都会被迫要手动的去fix它们的history. 要真正fix它,最好就是避免rebase它们的upstream.
为了阐明它,让我们设想现在有这样一个情况:有人在开发一个subsystem分支,并且你就在topic分支上工作,并且你的topic是依赖于这个subsystem分支的。你可能会有如下的commit history:
o---o---o---o---o---o---o---o---o master
\
o---o---o---o---o subsystem
\
*---*---* topic
如果 subsystem被rebase到master上,如下:
o---o---o---o---o---o---o---o master
\ \
o---o---o---o---o o'--o'--o'--o'--o' subsystem
\
*---*---* topic
如果你继续在topic分支上开发,最后将topic和subsystem合并,subsystem上的commit将一直存在重复的commit记录。
o---o---o---o---o---o---o---o master
\ \
o---o---o---o---o o'--o'--o'--o'--o'--M subsystem
\ /
*---*---*-..........-*--* topic