Git Handbook

06 · Rebase & History Editing

Làm sạch feature branch, replay commit, squash/fixup/reword, cherry-pick và force push có kiểm soát.

1. Rebase = replay commits trên base mới

git-rebase

Replay commit của branch hiện tại lên một base khác.
Official docs ↗
Cú pháp
git rebase <upstream>
Hiểu đơn giản
Rebase tạo commit mới tương đương về thay đổi nhưng có object ID mới.
git fetch origin
git switch feature/login
git rebase origin/main
Trước:
      C---D  feature
     /
A---B---E---F  main

Sau:
A---B---E---F---C'---D'  feature
Tránh rewrite commit public/shared nếu người khác đã dựa vào các commit đó.

Resolve conflict khi rebase

git status
# sửa conflict
git add <file>
git rebase --continue

# bỏ commit hiện tại nếu thực sự muốn
git rebase --skip

# hủy toàn bộ rebase
git rebase --abort

2. Interactive rebase

git rebase -i HEAD~5
ActionDùng khi
pickgiữ commit
rewordđổi message
editdừng để sửa commit
squashgộp và chỉnh message
fixupgộp, bỏ message commit này
droploại commit khỏi history mới
pick   a1 feat: login form
fixup  b2 fix typo
fixup  c3 remove debug
reword d4 add validation

3. Cherry-pick

git-cherry-pick

Áp dụng thay đổi của commit cụ thể thành commit mới trên branch hiện tại.
Official docs ↗
Cú pháp
git cherry-pick <commit>
Hiểu đơn giản
Hữu ích cho hotfix hoặc lấy một commit độc lập mà không merge cả branch.
git switch release/1.2
git cherry-pick abc123

git cherry-pick -n abc123

4. Force push có kiểm tra

Sau rebase, commit IDs thay đổi nên push thường bị non-fast-forward.

git push --force-with-lease
--force-with-lease an toàn hơn --force vì nó từ chối overwrite nếu remote ref không còn ở trạng thái bạn dự kiến. Vẫn cần hiểu rõ trước khi dùng.