git的cherry-pick與rebase命令

cherry-pick命令

cherry-pick命令可以將另一分支的commit內容合併到當前分支。

假如現在有兩個分支v1.0,v1.1。
v1.0有如下commit:

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

    feature5

commit 65ad383c977acd6c7e7bed486bbf3631851a9eda
Author: bin <[email protected]>
Date:   Tue Mar 19 10:30:44 2019 +0800

    feature4

commit a2a438f2652166f13a6a2aa36f447968fff3b15d
Author: bin <[email protected]>
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,就會出現這個錯誤。先把別人的分支拉取到本地再執行命令就可以了。

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 用法小結

commit補提文件

還有一個小技巧,如果我們commit之後發現漏掉了一個文件, 這時候可以對這個文件再進行commit一次, 但這樣做就顯得很多餘,而且容易污染commit記錄,而進行版本回退再添加也比較麻煩. 這個時候就可以使用這個amend命令.如下:

$ git commit -m "版本1.5開發代碼"
 
# 正當你鬆了一口氣的時候發現配置文件忘記修改了, 你趕緊修改,並適合用add到暫存區
$ git add project.property
$ git commit --amend         
# 你會神奇的發現你沒有增加任何多餘的操作就把漏掉的文件補齊到最後一次提交中

參考:
Git 王者超神之路

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章