commitをまとめたい

pullreqでpush済みの複数コミットを一つにまとめるやり方について残しておく。

コミットIDを調べる

以下のコマンドなどをたたいて、まとめたいコミットより前のコミットIDを調べる。

% git log --oneline

e58a089d (HEAD -> feature/develop, origin/develop) foofoo
0c9516e0 barbar
fd358d82 bazbaz
4e37f343 bazbaz
dc6aa3e5 foofoofoo

この中で以下の二つをまとめたいので一つ下のdc6aa3e5をメモ。

fd358d82 bazbaz
4e37f343 bazbaz

コミットをまとめる

git rebase -iとメモしたコミットIDをたたく。

% git rebase -i dc6aa3e5

すると以下のように画面遷移する

そして、まとめたいコミットで新しい方のコミットの先頭のpicksに変更する。

pick 4e37f343 bazbaz
pick fd358d82 bazbaz
pick 0c9516e0 barbar
pick e58a089d foofoo

# Rebase dc6aa3e5..e58a089d onto dc6aa3e5 (4 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 [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but
#                    opens the editor
# 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.
#

変更後↓

pick 4e37f343 bazbaz
s fd358d82 bazbaz
pick 0c9516e0 barbar
pick e58a089d foofoo

# Rebase dc6aa3e5..e58a089d onto dc6aa3e5 (4 commands)
#

~~~~~~~~~~~~~~~

:wqで変更を保存して終了すると、さらに画面が遷移する。

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

barbar

# This is the commit message #2:

barbar

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#

~~~~~~~~~~~~~~~~

コミットメッセージを編集するので以下のように変える。

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

squash barbar

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
~~~~~~~~~~~~~~~~

:wqで保存して終了して完了。

pushする場合は強制pushしないとされない。