Skip to content

交互式 Rebase 清理历史

中等 约 35 分钟

你将构建什么

一个含 5 个混乱提交的特性分支,通过交互式 rebase 整理为 2 个干净、命名良好的提交。

学习目标

  • 将多个提交压缩为一个
  • 在 rebase 期间重写提交消息
  • 通过编辑待办列表重排提交
  • 解决 rebase 期间产生的冲突

前置要求

  • 基础 Git 提交与分支
  • 合并概念
  • 命令行操作

步骤

  1. 1

    创建混乱分支

    创建特性分支并做 5 个小提交,消息如 'wip'、'fix typo'、'add tests'、'wip2'、'final'。这模拟真实的混乱开发。

    代码
    git checkout -b feature/cleanup
    # Make 5 commits with messy messages
    echo 'a' >> file.txt && git add . && git commit -m 'wip'
    echo 'b' >> file.txt && git add . && git commit -m 'fix typo'
    echo 'c' >> file.txt && git add . && git commit -m 'add tests'
    echo 'd' >> file.txt && git add . && git commit -m 'wip2'
    echo 'e' >> file.txt && git add . && git commit -m 'final'

    预期结果

    一个领先 main 5 个提交的特性分支。

  2. 2

    启动交互式 rebase

    运行 git rebase -i HEAD~5 在编辑器中打开最近 5 个提交。Git 显示一个'待办列表',每行一个提交和动作动词(pick、squash、reword 等)。

    代码
    git rebase -i HEAD~5

    预期结果

    编辑器打开,显示 5 行以 'pick <hash> <message>' 开头。

  3. 3

    压缩提交

    将第 2、3、4 行的动作动词从 'pick' 改为 'squash'(或 's')。这告诉 Git 将这些提交合并到上方那个。保存并关闭。

    代码
    # In the editor, change:
    # pick abc1234 wip
    # pick def5678 fix typo
    # pick ghi9012 add tests
    # pick jkl3764 wip2
    # pick mno5321 final
    #
    # To:
    pick abc1234 wip2
    squash def5678 wip
    squash ghi9012 fix typo
    pick jkl3764 add tests
    squash mno5321 final

    预期结果

    Git 合并被压缩的提交并提示输入新的提交消息。

  4. 4

    重写压缩后的消息

    当 Git 提示输入合并后的提交消息时,删除旧消息并写一个干净的,如 'Add core feature with tests'。对第二组重复。

    代码
    # First squash prompt — replace all lines with:
    Add core feature implementation
    
    # Second squash prompt — replace with:
    Finalize with tests and cleanup

    预期结果

    两个干净提交替代了原来的五个。

  5. 5

    验证干净历史

    运行 git log --oneline 查看结果。应看到 2 个干净提交而非 5 个混乱提交。验证文件内容未变。

    代码
    git log --oneline -5
    # Expected:
    # <hash> Finalize with tests and cleanup
    # <hash> Add core feature implementation
    # ... (main's commits below)
    
    git diff main --stat  # Should show the same total changes

    预期结果

    日志显示 2 个干净提交;对 main 的 diff 未变。

自己动手试试

你学到了什么

你掌握了交互式 rebase——让团队在混乱开发后保持干净、可读历史的工具。它是准备 PR 的必备技能。

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题