Rebase: 履歴の整理

コミット履歴を直線的に整理し、読みやすくする。

歴史の教科書の改訂 (Revising History Textbooks)

Rebaseは「歴史の教科書の改訂」です。 過去の事実(コミット)を書き換えて、きれいなストーリー(直線的な履歴)にまとめます。 出版済み(push済み)の教科書を書き換えると、すでに読んでいる学生(チームメンバー)が混乱します。 **ゴールデンルール**: 他の人がpullしたブランチはrebaseしない。

用語集

Rebase
コミットを別のベースに再適用。
Interactive
コミットを編集・整理しながらrebase。
Squash
複数コミットを1つに統合。
Force Push
リモート履歴を上書き(危険)。

基本Rebase(mainに追従)

feature ブランチを最新の main に追従させる。

Merge
Terminal window
# Merge creates a merge commit
# History looks like:
#
# main ──●──●──────●──M──
# \ /
# feature ●──●──●
Rebase
Terminal window
# Rebase creates linear history
# History looks like:
#
# main ──●──●──●──●──●──●
# ↑
# feature commits re-applied
rebase-sync.sh
# Sync feature branch with latest main
git switch feature/user-profile
git fetch origin
git rebase origin/main
# If conflicts occur:
# 1. Fix conflicts in your editor
# 2. Stage resolved files
git add resolved_file.ts
# 3. Continue rebase
git rebase --continue
# Or abort if things go wrong
git rebase --abort
実行結果
Successfully rebased and updated refs/heads/feature/user-profile.

Interactive Rebase(履歴編集)

コミットの編集、統合、削除ができる強力なツール。

interactive-rebase.sh
# Edit last 3 commits
git rebase -i HEAD~3
# In the editor, you'll see:
pick abc1234 feat: Add user form
pick def5678 fix: Typo in validation
pick ghi9012 feat: Add email field
# Change 'pick' to:
# p, pick = use commit as-is
# r, reword = use commit, but edit message
# e, edit = use commit, but stop for amending
# s, squash = meld into previous commit (keep message)
# f, fixup = meld into previous (discard message)
# d, drop = remove commit entirely

Squash の例

squash-example.sh
# Before: Messy commits
pick abc1234 feat: Add user form
pick def5678 wip
pick ghi9012 fix typo
pick jkl3456 oops
# After: Clean squash
pick abc1234 feat: Add user form
squash def5678 wip
squash ghi9012 fix typo
squash jkl3456 oops
# Result: One clean commit with combined message
Tip: PR前に git rebase -i で「wip」「fix typo」などの雑なコミットを整理すると、レビューが楽になる。

Force Push(履歴の上書き)

警告: rebase後は通常のpushが拒否されます。force pushが必要ですが、他の人の作業を壊す可能性があります。
force-push.sh
# After rebase, history has changed
# Regular push will be rejected
# Use --force-with-lease (safer than --force)
git push --force-with-lease origin feature/user-profile
# --force-with-lease checks if anyone else pushed
# before overwriting (prevents data loss)
ゴールデンルール: 自分だけが使っているブランチでのみ force push する。共有ブランチ (main, develop) では絶対にしない。

合格ライン

git rebase で main に追従できる
git rebase -i でコミットを整理できる
squash と fixup の違いを説明できる
force push のリスクを理解している

参考リンク

演習課題

課題1: 基本的なリベース
feature ブランチを main にリベースしてみてください。履歴が直線的になることを確認してください。
課題2: Interactive Rebase
git rebase -i HEAD~3 を使って、コミットを squash してみてください。

関連ページ