cherry-pickでブランチ整理

はじめに

プルリクやブランチ管理ミスった時に整理する術として「cherry-pick」は、とても便利です。 これから行う操作は、ターミナル(Mac)やGit Bash(Windows)での操作を想定しています。

cherry-pickとは

他ブランチに存在する特定のコミットのみを反映させるコマンドです。

やりたいこと

3つのコミットのうち2つのコミットだけを反映させたブランチを作りたい。

操作

まずコミットのログを確認してみましょう。
現在のコミットは、以下の通りです。
・third commit(3番目)
・second commit(2番目)
・first commit(1番目)

$ git log
commit ハッシュ値3 (HEAD -> master, origin/master, master)
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:17:21 2019 +0900

 third commit

commit ハッシュ値2
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:15:28 2019 +0900

 second commit

commit ハッシュ値1
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:05:52 2019 +0900

 first commit

新しいブランチは、以下の通り反映させたい。
・third commit(3番目)
・first commit(1番目)

では、新しいブランチを作り、切り替えます。

$ git branch branchname
$ git branch
branchname
* master
$ git checkout branchname
Switched to branch 'branchname'

新しく作ったブランチのコミットの確認です。
masterと同じコミットですが念のため。。。

$ git log
commit ハッシュ値3 (HEAD -> branchname, origin/master, master)
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:17:21 2019 +0900

 third commit

commit ハッシュ値2
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:15:28 2019 +0900

 second commit

commit ハッシュ値1
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:05:52 2019 +0900

 first commit

ここからが本番です。 1番目のコミットまで状態を戻します。

$ reset --hard ハッシュ値1

その後、cherry-pickで欲しいコミットを持ってくれば完了です。 お疲れ様でした。

$ git cherry-pick ハッシュ値3
[xxxxx] third commit
Date: Thu Mar 7 22:17:21 2019 +0900
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 b.txt
$ git log
commit ハッシュ値3 (HEAD -> branchname)
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:17:21 2019 +0900

 third commit

commit ハッシュ値1
Author: ユーザ名 <xxx@xxx.co.jp>
Date:   Thu Mar 7 22:05:52 2019 +0900

 first commit
Date:   Thu Mar 7 22:05:52 2019 +0900