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.
git fetch origin
git switch feature/login
git rebase origin/mainTrước:
C---D feature
/
A---B---E---F main
Sau:
A---B---E---F---C'---D' featureTrá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 --abort2. Interactive rebase
git rebase -i HEAD~5| Action | Dùng khi |
|---|---|
| pick | giữ commit |
| reword | đổi message |
| edit | dừng để sửa commit |
| squash | gộp và chỉnh message |
| fixup | gộp, bỏ message commit này |
| drop | loại commit khỏi history mới |
pick a1 feat: login form
fixup b2 fix typo
fixup c3 remove debug
reword d4 add validation3. 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.
git switch release/1.2
git cherry-pick abc123
git cherry-pick -n abc1234. 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.