1. 程式人生 > >Git cherry-pick 使用總結

Git cherry-pick 使用總結

假設:

假設我們有 branch_01 和 branch_02 兩個開發分支,那麼我們怎麼把 branch_01 上的一個或者幾個commit合併到 branch_02 上呢?

假設 branch_01 有如下兩個commit的hash值

59e7e6545a2eda9b82f5795173792e6490c9cd13

21b385c03a032d90102f1c8321f7858ff8788714

如何檢視commit得hash值呢?

使用 $ git log 命令檢視。

$ git log

在 commit 右邊的就是commit的hash值:

commit 8261c51c2f7aa4282f58e6579dbf35b112d4626b (HEAD -> rel/7.16)
Author: wang_zg <
[email protected]
> Date: Tue Sep 11 17:04:17 2018 +0800

每次commit都會生成一個hash值,這個值是唯一的。

結果:

cherry-pick 在 Git 文件中的解釋如下:

Apply the changes introduced by some existing commits 

意思是這個命令可以對已經存在的 commit 進行再次提交。

接下來,我們把 branch_01 的兩個commit合併到 branch_02 中。

首先我們要切換到 branch_02 分支,合併到哪個分支就切換到哪個分支。

$ git checkout branch_02

$ git cherry-pick -n 59e7e6545a2eda9b82f5795173792e6490c9cd13 21b385c03a032d90102f1c8321f7858ff8788714

注意:

  • branch_01 的兩個 commit 就被 合併到本地的 branch_02 分支上了,這時候的更改並沒有被提交到遠端倉庫,使用 git status 可以檢視所有的更改。
  • 多個commit的hash使用空格分割, commit的hash最好按提交時間先後排列, 即最先提交的commit放在前面。

這兩行命令執行之後,如果順利沒有報錯,就可以使用 git  commit , git  push 命令進行正常提交到遠端倉庫,就行。

如果報錯了,也就是說在 cherry-pick 過程中產生了衝突,會報如下錯誤:

Automatic cherry-pick failed.  After resolving the conflicts,
mark the corrected paths with 'git add <paths>' or 'git rm <paths>'

那我們只需跟解決普通衝突一樣,手動解決就行。

$ git status    #檢視哪些檔案出現了衝突

  both modified:      app/home/viewcontrollor.m 

$ vim app/home/viewcontrollor.m    #手動解決

$ git add app/home/viewcontrollor.m

$ git commit         #提交

$ git push           #推送到遠端倉庫