跳轉到內容

Git 合併commit 精簡提交 歷史記錄管理

命令特點
Merge合併兩個分支,保留所有歷史記錄。
Rebase將一個分支的更改應用到另一個分支的頂部,形成線性歷史。
Reset --soft撤銷最後一次提交,但保留更改在工作目錄和暫存區,適合需要撤銷合併但保留修改的場景。
Fixup創建修復某次提交的臨時提交,可配合 rebase -i 自動合併,簡化歷史記錄。

Merge 的使用方法

創建臨時分支並切換

sh
git checkout -b temp-branch

在臨時分支上做更改並提交

sh
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on temp-branch"

切換回 main 併合並臨時分支

sh
git checkout main
git merge temp-branch

推送更改到遠程倉庫

sh
git push origin main

刪除臨時分支

sh
git branch -d temp-branch

Rebase 的使用方法

創建臨時分支並切換

sh
git checkout -b temp-branch

在臨時分支上做更改並提交

sh
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on temp-branch"

切換回 main 並進行 rebase

sh
git checkout main
git rebase temp-branch

推送更改到遠程倉庫

sh
git push origin main

刪除臨時分支

sh
git branch -d temp-branch

Reset --soft 的使用方法

在 main 分支上做更改並提交

sh
echo "Some changes" > file.txt
git add file.txt
git commit -m "Changes on main"

撤銷最後一次提交

sh
git reset --soft HEAD^

重新提交或進行其他操作,然後推送到遠程倉庫

sh
echo "Updated changes" > file.txt
git add file.txt
git commit -m "Updated changes on main"

git push origin main

Fixup 的使用方法

查看提交歷史並找到要修復的提交的哈希

sh
git log --oneline

進行修改並創建 fixup 提交

sh
# 修改代碼
git add .

# 用 --fixup 創建修復指定提交的臨時提交
git commit --fixup <commit-hash>

使用自動 rebase 將 fixup 合併進目標提交

sh
git rebase -i --autosquash <commit-hash>^

注意:將 <commit-hash> 替換為目標提交的哈希值。git rebase 會自動把 fixup 提交合併到該目標提交中。

強制推送更新後的歷史

sh
git push --force-with-lease

通過合理使用 fixuprebase --autosquash,可以讓 Git 歷史更簡潔、易讀。

最後更新於: