🔀 Git Merge vs Rebase

Giữ lịch sử vs Viết lại lịch sử — Golden Rule of Rebase

🟢 Git Merge

Gộp 2 branch, tạo merge commit. Giữ nguyên lịch sử. Safe, non-destructive.

🟠 Git Rebase

Di chuyển commits lên đầu branch khác. Viết lại lịch sử. Linear, clean history.

1. Git Merge

Trước merge:
main:     A ── B ── C
                      \
feature:               D ── E

Sau: git checkout main && git merge feature

main:     A ── B ── C ──────── M (merge commit)
                      \       /
feature:               D ── E

→ Tạo merge commit M, giữ nguyên D, E
# Git Merge workflow
git checkout main
git pull origin main
git merge feature/login

# Nếu conflict:
# 1. Sửa conflict trong file
# 2. git add .
# 3. git commit

Ưu điểm:

  • Non-destructive — không thay đổi lịch sử
  • Traceability — biết chính xác khi nào merge
  • Safe — dùng trên shared branches

Nhược điểm:

  • History rối với nhiều merge commits
  • Git log khó đọc khi nhiều branches

2. Git Rebase

Trước rebase:
main:     A ── B ── C
                      \
feature:               D ── E

Sau: git checkout feature && git rebase main

main:     A ── B ── C
                      \
feature:               D' ── E' (commits MỚI, hash khác)

→ D, E được "replay" lên đầu main → D', E'
→ Linear history, không merge commit
# Git Rebase workflow
git checkout feature/login
git rebase main

# Nếu conflict (từng commit một):
# 1. Sửa conflict
# 2. git add .
# 3. git rebase --continue

# Interactive rebase (squash commits):
git rebase -i HEAD~3
# pick → squash (gộp commits)
# pick → reword (đổi message)

Ưu điểm:

  • Clean, linear history
  • Dễ đọc git log
  • Squash nhiều commits thành 1

Nhược điểm:

  • Viết lại lịch sử — NGUY HIỂM trên shared branches
  • Force push cần thiết sau rebase
  • Mất context khi nào feature được merge

3. Bảng So Sánh

Tiêu chí 🟢 Merge 🟠 Rebase
History Non-linear (giữ nguyên) Linear (viết lại)
Merge commit Tạo merge commit Không tạo
Safe? An toàn Nguy hiểm nếu sai
Conflict Giải quyết 1 lần Giải quyết từng commit
Force push Không cần Cần (sau rebase)
Git log Phức tạp khi nhiều branches Sạch, dễ đọc

4. Golden Rule of Rebase

⚠️ KHÔNG BAO GIỜ rebase branch mà người khác đang dùng!

Rebase viết lại commit hash → người khác sẽ bị conflict nặng.
git rebase main khi đang ở shared branch
✅ Chỉ rebase feature branch CỦA BẠN trước khi merge

5. Workflow Phổ Biến

✅ Workflow khuyến nghị:
1. Rebase feature branch lên main trước khi merge
2. Squash commits (interactive rebase)
3. Merge (hoặc fast-forward) vào main

git checkout feature
git rebase -i main (squash + cleanup)
git checkout main
git merge feature (fast-forward)