プログラムを中心とした個人的なメモ用のブログです。 タイトルは迷走中。
内容の保証はできませんのであしからずご了承ください。

2021/07/02

git でコミットを一つにまとめる

update2021/08/13 event_note2021/07/02 4:44

Windows 環境では TortoiseGit を使っているので GUI で出来るのですが、Ubuntu で使っている RabbitGit では出来なさそうだったので、コマンドでやりました。

TortoiseGit でのやり方は以下です。

環境

  • Ubuntu 20.04

まずログを確認

$ git log --oneline

以下のように表示されます。

5418fe (HEAD -> master) fuga
f3896f7 piyo
af6639b hoge
b1da633 initial commit

ここで3つのコミット(hoge、piyo、fuga のメッセージのやつ)を一つにまとめてみます。

リベースの開始

まとめたいコミット群の一つ前のコミットに対してリベースを行います。

$ git rebase -i HEAD~3

HEAD~3HEAD~~~ やハッシュ値でも構いません。

すると、テキストエディタで編集画面が表示されます。
私の場合は nano で表示されました(vi じゃなくてよかった)。

pick af6639b hoge
pick f3896f7 piyo
pick c5418fe fuga

# Rebase b1da633..c5418fe onto b1da633 (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
# 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.
#
# Note that empty commits are commented out

-i オプションを指定したので、この画面では Rebase を使って現在と過去の間に残ってるコミットをどう処理するかを聞かれています。

最新以外の pick の箇所を s または squash に変更します。

変更前

pick af6639b hoge
pick f3896f7 piyo
pick c5418fe fuga

変更後

pick af6639b hoge
s f3896f7 piyo
s c5418fe fuga

保存して終了すると、コミットメッセージの編集画面が開きます。
必要に応じて編集し、終了します。