git cherry-pick与rebase

cherry-pick

假如现在有两个分支v1.0,v1.1。
v1.0有如下commit:

commit 4d3b38f3e6b9f49776f6e2d2861f0425e10df8d6 (HEAD -> v1.0)
Author: bin 
Date:   Tue Mar 19 10:33:43 2019 +0800

    feature5

commit 65ad383c977acd6c7e7bed486bbf3631851a9eda
Author: bin 
Date:   Tue Mar 19 10:30:44 2019 +0800

    feature4

commit a2a438f2652166f13a6a2aa36f447968fff3b15d
Author: bin 
Date:   Tue Mar 19 10:30:09 2019 +0800

    feature3

现在v1.1需要合并feature4的功能,但不能合并feature3,feature5,怎么办?
把代码复制过来吗?不!用cherry-pick

git cherry-pick  65ad383c977acd6c7e

如果文件有冲突,cherry-pick 会中断,
你解决冲突后,使用git add添加冲突文件,使用git cherry-pick --continue完成cherry-pick操作。
或者使用git cherry-pick --abort中断操作。

如果你cherry-pick的是别人分支的commit,可能会遇到错误fatal: bad object ...,那是因为git cherry-pick是本地特性,本地要有这个commit才可以被git cherry-pick。如果没有这个commit id,就会出现这个错误。

git rebase

之前都不太在意 git rebase的使用,直到看了这篇文章
彻底搞懂 git rebase,规范项目的commit

想想也是的,如果git log充斥着大量如下commit:

fixbug
fixbug
fixbug
add log
add log
add log
add log

除了文章中提到的
1.不利于代码 review
2.不利于代码回滚
也不利于自己回顾跟踪代码。

所以可以使用rebase合并commit。
我把上面v1.0所有commit合并为一个

git rebase -i    a2a438f2652   4d3b38f3e

其中-i的意思是--interactive,即弹出交互式的界面让用户编辑完成合并操作。
这时会弹出编辑页面

r a2a438f feature3


# Rebase 1822165..46c1e55 onto 1822165 (3 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.

上面是指令编辑,下面注释是指令说明:
pick:保留该commit(缩写:p)
reword:保留该commit,但我需要修改该commit的注释(缩写:r)
edit:保留该commit, 但我要停下来修改该提交(不仅仅修改注释)(缩写:e)
squash:将该commit和前一个commit合并(缩写:s)
fixup:将该commit和前一个commit合并,但我不要保留该提交的注释信息(缩写:f)
exec:执行shell命令(缩写:x)
drop:我要丢弃该commit(缩写:d)

根据我们需要编辑指令后保存,就可以完成commit的合并了。

git rebase合并其他分支与git cherry-pick异曲同工,这里不再复述了。

上面文章中也说到,git rebase会修改commit 记录,属于危险操作,需小心操作。

参考:
rebase 用法小结

你可能感兴趣的:(git cherry-pick与rebase)