setoya-blog

システム開発技術、データ分析関連でお勉強したことや、山奥生活を綴る、テンション低めなブログです。

rebaseを使って、featureブランチの複数のコミットを1つにまとめる

1つ前のコミットにaddするのを忘れたものがある場合などに使う。 また、featureブランチで自分だけが作業しているような場合に使う。 masterブランチや複数人の開発での作業元ブランチなどでrebaseをするのは危険なのでNG(このあたりの情報はググればいろいろでてくるので、この記事では割愛)。

rebaseコマンドを実行

直近複数のコミットを1つにまとめたい状況で、以下を実行。

$ git rebase -i HEAD~2

vimで編集

gitに設定したエディタ(大抵はvimのはず)が立上がるので、どのコミットを使うかを設定。ここでは、commit 1とcommit 2を統合して1つにするので、commit 2の方の冒頭のキーワードをfixupに変更している。

pick 9ecfb200 commit 1 message
fixup a3f7701b commit 2 message

# Rebase d689a48c..a3f7701b onto d689a48c (2 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name

これで、commit 1にcommit2の内容が取り込まれて、コミットメッセージはcommit1のものが使われる。

修正が終わったら:wqを入力して、vimを保存して終了すると編集した内容にしたがって、rebase処理が実行される。

ちなみに、:wqで保存した場合にCould not execute editorエラーが出る場合は、gitのデフォルトエディタが設定されていないはずなので、以下のようにしてエディタを設定する。

$ $ git config --global core.editor vim

これで、~/.gitconfigに設定が書き込まれる。

ここではgitらしくvimを設定しているけど、自分は本当はemacs派。ただRubyMineをemacキーバインドで使っているときは、RubyMineのターミナルパネルで使うとCtrl+X Ctrl+SがCtrl+Sと衝突してめんどくさかったので、vimを使ってあげることにした。