git rebase -i で複数のコミットをまとめる

いつもrebaseをするときやり方を忘れてググるので自分用に残しておきます。

git rebase -i

HEADの後ろに”~”を追加することで表示したいコミット数を指定できます。

//4コミット分を表示
git rebase -i HEAD~~~

するとvimが開き、HEADから3つ分のコミットが表示される。

pick 51ece3c fix
pick 83cbe1a typo
pick 32216b5 typo

# Rebase 90e4277..32216b5 onto 90e4277 (3 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

今回は83cbe1aと32216b5を51ece3cにまとめたいと思います。
任意のまとめたいコミットIDのpickをsに変更します。

pick 51ece3c fix
pick s typo
pick s typo

すると以下のようにコミットメッセージ編集画面が表示されます。

# This is a combination of 3 commits.
# This is the 1st commit message:

fix

# This is the commit message #2:

typo

# This is the commit message #3:

typo

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Mon Nov 14 21:22:07 2022 +0900
#
# interactive rebase in progress; onto 90e4277
# Last commands done (3 commands done):
#    squash 83cbe1a typo
#    squash 32216b5 typo
# No commands remaining.
# You are currently rebasing branch 'master' on '90e4277'.
#
# Changes to be committed:
#       modified:   index.html
#

任意のコミットメッセージを編集します。

コミットをまとめました

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Mon Nov 14 21:22:07 2022 +0900
#
# interactive rebase in progress; onto 90e4277
# Last commands done (3 commands done):
#    squash 83cbe1a typo
#    squash 32216b5 typo
# No commands remaining.
# You are currently rebasing branch 'master' on '90e4277'.
#
# Changes to be committed:
#       modified:   index.html
#

これでコミットがまとまりました。git logなどで確認してみてください。

git log --oneline
21ecc0c (HEAD -> master) コミットをまとめました
90e4277 first commit

git push -fでプッシュする

リモートリポジトリに push する際は、コミットハッシュが変わるので -f オプションが必要です。
強制プッシュをする際は十分に気をつけてください。

git push -f origin <ブランチ>

git rebaseを中断する

rebaseを中断したいときは以下のコマンドで中断できます。

git rebase --abort

git reflogでrebaseを元に戻す

git reflog で直近の変更が表示されるので、戻りたいところでgit resetをします
nの中には任意の数字を入れてください

git reflog
git reset --hard HEAD@{n} 

コメントを残す

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。