Git 合併commit 精簡提交 歷史記錄管理
| 命令 | 特點 |
|---|---|
Merge | 合併兩個分支,保留所有歷史記錄。 |
Rebase | 將一個分支的更改應用到另一個分支的頂部,形成線性歷史。 |
Reset --soft | 撤銷最後一次提交,但保留更改在工作目錄和暫存區,適合需要撤銷合併但保留修改的場景。 |
Fixup | 創建修復某次提交的臨時提交,可配合 rebase -i 自動合併,簡化歷史記錄。 |
Merge 的使用方法
創建臨時分支並切換
git checkout -b temp-branch在臨時分支上做更改並提交
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on temp-branch"切換回 main 併合並臨時分支
git checkout main
git merge temp-branch推送更改到遠程倉庫
git push origin main刪除臨時分支
git branch -d temp-branchRebase 的使用方法
創建臨時分支並切換
git checkout -b temp-branch在臨時分支上做更改並提交
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on temp-branch"切換回 main 並進行 rebase
git checkout main
git rebase temp-branch推送更改到遠程倉庫
git push origin main刪除臨時分支
git branch -d temp-branchReset --soft 的使用方法
在 main 分支上做更改並提交
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on main"撤銷最後一次提交
git reset --soft HEAD^重新提交或進行其他操作,然後推送到遠程倉庫
echo "Updated changes" > file.txt
git add file.txt
git commit -m "Updated changes on main"
git push origin mainFixup 的使用方法
查看提交歷史並找到要修復的提交的哈希
git log --oneline進行修改並創建 fixup 提交
# 修改代碼
git add .
# 用 --fixup 創建修復指定提交的臨時提交
git commit --fixup <commit-hash>使用自動 rebase 將 fixup 合併進目標提交
git rebase -i --autosquash <commit-hash>^注意:將
<commit-hash>替換為目標提交的哈希值。git rebase 會自動把 fixup 提交合併到該目標提交中。
強制推送更新後的歷史
git push --force-with-lease通過合理使用 fixup 與 rebase --autosquash,可以讓 Git 歷史更簡潔、易讀。