Skip to content

Git 提交整理:merge、rebase、soft reset 与 fixup ​

本次在 .cache/git-pnpm-walkthrough/repo 的示例分支操作。先完成基本提交,main 起点为 6648cd8。merge 保留提交关系;rebase、soft reset 后重提和 autosquash 都可能改写提交 ID,主要用于尚未共享的提交。

Merge 的使用方法 ​

下方完成 rebase 与 fixup 后,切回 main 合并:

powershell
git switch main
git merge codex/demo
git log --graph --oneline -6

实际合并输出:

text
Updating fbdb55f..626f45f
Fast-forward
 feature.txt | 2 ++
 1 file changed, 2 insertions(+)
 create mode 100644 feature.txt

main 包含了功能文件的两行内容。若出现冲突,先处理并暂存;放弃本次合并可用 git merge --abort。

Rebase 的使用方法 ​

在 main 起点创建功能分支,再让 main 向前提交另一个文件:

powershell
git switch -c codex/demo
Set-Content -Encoding utf8 feature.txt 'Feature version 1'
git add feature.txt
git commit -m "feat: add demo feature"
git switch main
Set-Content -Encoding utf8 main-note.txt 'Main moved ahead'
git add main-note.txt
git commit -m "docs: add main note"
git switch codex/demo
git rebase main
git log --oneline -3

功能提交最初为 e2bb0ea,重放后的日志为:

text
ea4ffad feat: add demo feature
fbdb55f docs: add main note
6648cd8 chore: ignore local files

功能提交已移到新的 main 之上,ID 也发生变化。冲突修复后 git add 明确路径,再 git rebase --continue;取消用 git rebase --abort。

Reset --soft 的使用方法 ​

本次在另一条 codex/reset 分支运行:

powershell
git reset --soft HEAD~1
git diff --cached --stat

输出为 README.md | 1 +、1 file changed, 1 insertion(+)。分支回退一条,新增文字仍在暂存区。完整创建提交、重新提交和 revert 的顺序见版本回退。

仅适用于 HEAD 至少有一个父提交、且目标提交尚未共享的情况。检查后可用 git commit -m "更清楚的说明" 重提;默认 mixed reset 则会取消暂存。

Fixup 的使用方法 ​

在上面的 codex/demo 分支继续:

powershell
Add-Content -Encoding utf8 feature.txt 'Feature corrected'
git add feature.txt
git commit --fixup=HEAD
git log --oneline -3
git -c sequence.editor=true rebase -i --autosquash main
git log --oneline -3
Get-Content feature.txt

fixup 提交后的前两条日志为:

text
3e49d04 fixup! feat: add demo feature
ea4ffad feat: add demo feature

autosquash 后,两条变为一条 626f45f feat: add demo feature。文件保留两行:

text
Feature version 1
Feature corrected

本次用单次 -c sequence.editor=true 接受 Git 自动生成的排序,不保存编辑器设置。需要手工检查列表时,用 git rebase -i --autosquash 目标SHA^,把 目标SHA 换为真实值;创建 fixup 的通用形式是 git commit --fixup=目标SHA。目标为根提交时用 git rebase -i --root --autosquash。

Git 学习路径 ​

常规推送用 git push。已共享分支需改写时先与协作者协调,并按带明确预期 SHA 的推送检查操作。撤销功能而保留历史,优先读 revert。

官方资料 ​

最近更新