git rebaseで過去のコミットを削除。履歴を書き直す。

最終更新:2017-07-03 by Joe

ブランチの履歴や、過去のコミットを修正するために用いる方法です。

過去のコミットを削除する

過去のコミットを削除する、ということは、その過去のある時点のファイルに基づいてその後の変更に影響を与える可能性があるということです。映画で、過去に戻って何かをしでかすと、その後の歴史に影響でて、主人公が半透明になってしまうような自体と一緒ですね。

git rebaseを使った過去のコミットの削除で、何が起きるか見てみます。

過去の自分にリベースする

さて、繰り返しになりますが、過去のコミットを本当に「削除」すると、それ後に続く、すべてのコミットに影響がでます。これらの影響を一つずつ「どう対応するか?」を決定する必要があります。

それが「rebase -i <commit>」です。

「-i」は「--interactive」のショートハンドです。「どうするか」をインタラクティブに答えて行くことになります。

実行してみます。

// 実行。
git rebase -i <commit A>


// Editor が起動
pick 425b10a Fix the meta query for a blog post which wasn't working.
pick bd11112 Fix the logo icon. Fix the banner.
pick 37464ab Add the flag of whether to show the icon.
pick a013bba Fix the layout for mobiles. Make the button smaller.

# Rebase a013bba..425b10a onto 026b5f9 (4 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 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.
#
# Note that empty commits are commented out

 

各行頭の「pick」を適宜書き換えて、保存すればOKです。

下の方にたくさんガイドのコメントが付いているので迷うことはあまりないと思います。一応解説しておくと、

リクエスト 効果
p, pick コミットを採用
r, reword コミットを採用、でもコミットメッセージを編集
e, edit コミットを採用、でも、途中で、内容の修正のためリベースを中断する
s, squash(握りつぶす) コミットを採用、でも変更内容を直前のコミットに統合する
f, fixup squashと同じ。でもコミットメッセージを捨てる。
x, exec 残りの行でシェルでコマンドを実行
d, drop コミットを削除

よく使うのは、コミット履歴を整えるために使うreword, コミットをまとめるために使う、squashなどでしょうか。

もちろん、コミットを削除するのはdropですが、その影響をよく考えて実行しましょう。

やばい、とおもったら、git reflogを使って戻りましょう。

参考