Tips
最新のN個のコミットを整理する場合 (例: 最新3個)
`git rebase -i`を使ってGitのコミット履歴をきれいに整理しましょう。複数のコミットをまとめたり、コミットメッセージを修正したり、順序を入れ替えたりすることで、より分かりやすく管理されたプロジェクト履歴を作成できます。
技術・言語・ツール: Git
git rebase -iを使ってGitのコミット履歴をきれいに整理しましょう。複数のコミットをまとめたり、コミットメッセージを修正したり、順序を入れ替えたりすることで、より分かりやすく管理されたプロジェクト履歴を作成できます。
Gitコミット履歴をインタラクティブに整理する
開発中に増えてしまった細かなコミットや、コミットメッセージを修正したい時に役立つのがgit rebase -iです。対話形式でコミットの編集、結合、削除、順序変更などが行え、後から見ても理解しやすいクリーンな履歴を保てます。
# 最新のN個のコミットを整理する場合 (例: 最新3個)
git rebase -i HEAD~3
# ある特定のコミットから現在のブランチまでのコミットを整理する場合
# (例: <commit-hash>は整理を開始したいコミットのハッシュ)
git rebase -i <commit-hash>
git rebase -iを実行すると、エディタが開きます。そこには選択した範囲のコミットが新しい順にリストされ、各行の先頭にはpickが記述されています。
pick <commit-hash-1> Commit message 1
pick <commit-hash-2> Commit message 2
pick <commit-hash-3> Commit message 3
# Rebase <commit-hash-parent>..<commit-hash-current> onto <commit-hash-parent> (<N> 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) for each commit
# 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 re-use the given merge commit's 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
よく使うコマンド例:
pick: コミットをそのまま採用(デフォルト)reword(r): コミットメッセージを編集squash(s): 前のコミットと結合し、新しいコミットメッセージを作成fixup(f): 前のコミットと結合し、このコミットのメッセージは破棄drop(d): コミットを削除edit(e): コミット内容を修正するために一時停止(git commit --amendなどで修正後、git rebase --continueで再開)- コミットの順序を入れ替えるには、行の順番を入れ替える。
注意点やおすすめポイント:
- 公開済みのコミットには使用しない:
git rebase -iはコミットハッシュを変更するため、既に共有済みのブランチや、他の開発者がPull/Pushしている履歴に対しては、予期せぬ衝突や問題を引き起こす可能性があります。ローカルでの作業中や、まだ公開していないブランチでの利用が推奨されます。 - 作業コピーをクリーンに保つ:
git rebaseを開始する前に、すべての変更をコミットするか、git stashで一時的に保存しておきましょう。 - バックアップの習慣: 重要な作業を行う前には、念のためブランチのバックアップを取っておくと安心です(例:
git branch backup-branch)。 - 丁寧なコミット履歴: 小さな変更ごとにコミットし、後で
fixupやsquashでまとめてきれいなコミットにするというワークフローは非常に効率的です。Pull Requestを出す前に履歴を整理することで、レビュー担当者も理解しやすくなります。