Gitを使って開発していると「あ、このコミットさっきのコミットにまとめたかったな…」ってことがあります。
コミットを整理することは、レビュアーの負担軽減にもなるので大切です。
そこでこのエントリでは、ブランチをPushする前に git rebase -i を使ってコミットを整理する方法を紹介します。
コミットを整理するには git rebase -i <COMMIT_ID> を使うと便利です。
例えば次のような履歴があったとします。
- Fix view
- Add controllers
- Add routing
- Add views
直近のFix viewコミットは4つ前のAdd viewsコミットとまとめてしまいたいです。
そんなときは git rebase -i HEAD~4 とします(Add viewsのコミットID~1 を指定しても良いです)。
すると、下記のような内容が書かれたエディタが立ち上がります。
pick から始まる行が1コミットを表しています。git log とは逆で、下が新しいコミットになっています。
pick xxxxxxxxx Add views
pick xxxxxxxxx Add routing
pick xxxxxxxxx Add controllers
pick xxxxxxxxx Fix view これを次のように編集します。
Fix viewのコミットをAdd viewsの下に移動し、 pick を fixup もしくは f に変更します。
pick xxxxxxxxx Add views
f xxxxxxxxx Fix view
pick xxxxxxxxx Add routing
pick xxxxxxxxx Add controllers 編集したら保存して終了します。
成功するとコミットがまとめられ、下記のようなメッセージが表示されます。
git log や git diff で確認するとコミットがまとめられたことを確認できます。
Successfully rebased and updated refs/heads/xxx. 今回は行の順番を変えて fixup コマンドを使いましたが、実は git rebase -i で使えるコマンドの説明はエディタを開いた際の下部に書かれています。
# 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
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# . create a merge commit using the original merge commit's
# . message (or the oneline, if no original merge commit was
# . specified). Use -c <commit> to reword the commit message.
#
# 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.
# fixup の説明を見ると「コミットメッセージを破棄する squash」と書かれています。
fixup ではコミットメッセージは編集できませんでしたが、編集したい場合は squash を使います。
個人的には他のコマンドはほぼ使いません。コミットメッセージを編集するためにたまに edit を使う程度でしょうか。でも edit より reword の方が便利そうですね。
また、
These lines can be re-ordered; they are executed from top to bottom.
とあるように、行を入れ替えるとコミットの順番を変えることができます。行を削除するとコミットを消すことができます。
ぜひ git rebase -i を使いこなしてコミットを整理してみてくださいね。
以上です。
このエントリでは、ブランチをPushする前に git rebase -i を使ってコミットを整理する方法を紹介しました。
コメントを送る
コメントはブログオーナーのみ閲覧できます