あまブログ

ドキドキ......ドキドキ2択クイ〜〜〜〜〜〜〜ズ!!

【Git】複数のコミットを一つにまとめる(rebase -i で squash)

この記事では、git rebase -iを使って複数のコミットを一つにまとめる方法を紹介します。

1. 連続したコミットの場合

以下のedit2, edit3, edit4を一つにまとめて、edit 2 & 3 & 4にします。

$ git log --oneline
96a8b1e (HEAD -> main) edit4
30600dd edit3
452c39e edit2
ac56720 edit1

ac56720以降のコミットを表示させたいので、以下のコマンドを実行

$ git rebase -i ac56720
# git rebase -i HEAD~3でも可

テキストエディタに以下が表示される(古いコミットが上)

pick 452c39e edit2
pick 30600dd edit3
pick 96a8b1e edit4

edit3edit4picks(またはsquash)に変更して、ファイルを保存して閉じる。

pick 452c39e edit2
s 30600dd edit3
s 96a8b1e edit4
  • f(fixup)にするとコミットメッセージの編集画面は表示されず、まとめられたコミットのコミットメッセージがedit2になる(squashfixupの違いはこれだけ)

以下のコミットメッセージの編集画面が表示される

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

edit 2

# This is the commit message #2:

edit 3

# This is the commit message #3:

edit 4

コミットメッセージをedit 2 & 3 & 4に変更してファイルを保存して閉じる。(他のコミットメッセージは消しても消さなくてもいい)

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

edit 2 & 3 & 4

# This is the commit message #2:

edit 3

# This is the commit message #3:

edit 4

コミットを一つにまとめることができた

$ git log --oneline
2897eb6 (HEAD -> main) edit2 & 3 & 4
ac56720 edit1

2. 離れたコミットの場合

以下のadd 1 to a.txtadd 2 to a.txtを一つにまとめて、add 1 & 2 to a.txtにします。

$ git log --oneline
bec04cd (HEAD -> main) add 2 to a.txt
58c00dd add 222 to b.txt
2407669 add 1 to a.txt
c90dfb0 add 111 to b.txt

c90dfb0以降のコミットを表示させたいので、以下のコマンドを実行

$ git rebase -i c90dfb0
# git rebase -i HEAD~3でも可

テキストエディタに以下が表示される(古いコミットが上)

pick 2407669 add 1 to a.txt
pick 58c00dd add 222 to b.txt
pick bec04cd add 2 to a.txt

add 2 to a.txtpicks(またはsquash)に変更

pick 2407669 add 1 to a.txt
pick 58c00dd add 222 to b.txt
s bec04cd add 2 to a.txt

sにしたadd 2 to a.txtを合体させたいコミット(add 1 to a.txt)の下に移動して、ファイルを保存して閉じる。

pick 2407669 add 1 to a.txt
s bec04cd add 2 to a.txt
pick 58c00dd add 222 to b.txt

以下のコミットメッセージの編集画面が表示される

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

add 1 to a.txt

# This is the commit message #2:

add 2 to a.txt

コミットメッセージをadd 1 & 2 to a.txtに変更してファイルを保存して閉じる。

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

add 1 & 2 to a.txt

# This is the commit message #2:

add 2 to a.txt

コミットを一つにまとめることができた

$ git log --oneline
fa57a41 (HEAD -> main) add 222 to b.txt
4eb72b8 add 1 & 2 to a.txt
c90dfb0 add 111 to b.txt

【参考】