Tips
コミット履歴を整理するGit Rebaseの活用
複数回のコミットを一つにまとめたり、コミットメッセージを編集したりして、より綺麗な履歴を作成する方法を紹介します。PR(プルリクエスト)提出前に履歴を整理することで、レビューアが変更内容を理解しやすくなり、チーム開発の効率が向上します。
Git
複数回のコミットを一つにまとめたり、コミットメッセージを編集したりして、より綺麗な履歴を作成する方法を紹介します。PR(プルリクエスト)提出前に履歴を整理することで、レビューアが変更内容を理解しやすくなり、チーム開発の効率が向上します。
コミット履歴を整理するGit Rebaseの活用
git rebase -i(インタラクティブrebase)コマンドを使って、ローカルのコミット履歴を編集し、より論理的で分かりやすい状態に整理する方法です。複数の修正コミットを1つに統合したり、コミットの順序を変更したり、コミットメッセージを修正したりできます。
# まず、整理したいブランチにいることを確認
git switch feature/my-new-feature
# ベースとなるブランチ(例: main)から現在のブランチまでのコミットをインタラクティブにrebase
# HEAD~3 は直近3つのコミットを対象にする例。あるいは 'git rebase -i main' でメインブランチ以降のコミットを対象にできる
git rebase -i HEAD~3
上記のコマンドを実行すると、エディタが開きます。
pick 0123abc feat: Initial commit
pick 4567def fix: Bug fix
pick 8901ghi refactor: Improve code readability
# Rebase 1234abc..8901ghi onto 1234abc (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 and stop for editing its message
# f, fixup <commit> = use commit, but meld into previous commit
# 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 one specified)
# . use -c <commit> to re-use the given commit's message as-is
#
# 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.
#
これを以下のように変更し、たとえば2つ目と3つ目のコミットを最初のコミットに結合します。
pick 0123abc feat: Implement new feature
squash 4567def fix: Related bug fix
fixup 8901ghi refactor: Cleanup for new feature
エディタを保存して閉じると、squashしたコミットのメッセージを編集するエディタが開きます。新しいコミットメッセージを記述し、保存して閉じると、コミットが結合されます。
# rebase後にリモートリポジトリにプッシュする場合(履歴が書き換わるため強制プッシュが必要)
git push --force-with-lease origin feature/my-new-feature
注意点やおすすめポイント
- 公開済みのコミットにはRebaseしない: リモートにプッシュされ、他の開発者がPull/Fetch済みのコミットをRebaseすると、履歴が書き換わりチームメンバーとの整合性が取れなくなり、強力な競合が発生する可能性があります。Rebaseはローカルの未プッシュのコミットに対して行うのが基本です。
- オプション:
pick(そのまま採用),reword(メッセージのみ編集),edit(コミット内容を編集して再コミット),squash(前のコミットと結合し、メッセージを編集),fixup(前のコミットと結合し、前のコミットのメッセージを維持) などがあります。 --force-with-leaseを使うことで、他の誰かが同じブランチにプッシュしていないことを確認しながら強制プッシュできるため、単なる--forceよりも安全です。- 綺麗なコミット履歴は、後で変更履歴を追うときや、
git blame、git bisectを使う際に非常に役立ちます。特に、変更を一つにまとめることで、レビューアがPRの内容を理解しやすくなります。