成为git砖家(9): rebase进阶: 拆分commit为多个

问题描述

当一次性 git add 了多个修改点, 并且快速的执行了 git commit 后, 你觉得有点懊恼: 明明可以独立为两次或多次 commit, 揉在一块导致历史记录不太清晰。

比如我在 nn1 这个练手项目中, 最近一次 commit, 增加了三个函数:

  • evaluate()
  • test_softmax()
  • accuracy()

git commit 后我后悔了,想要拆解为3次 commit,每次一个函数。

我们知道,对于已经存在的多个commit如果要合并起来,那么 rebase 是相当简单的。拆分 commit 呢? 也是可以用 rebase 来做的,用到的是 edit 这个动作。随后恢复暂存区,重新按需add和commit代码。

具体操作

  1. 备份现有代码到新的分支
    这一步是防止 git 操作失误。 其实熟练了可以省略,因为后续修改如果中途不满意可以 git rebase --abort
bash 复制代码
git checkout backup
  1. rebase到需要修改的commit的前一次commit

例如我最近一次 commit 需要被拆分, 它是 HEAD; 它的上一次commit用 HEAD~ 来表示:

bash 复制代码
git rebase -i HEAD~
  1. 把 edit 改为 pick
bash 复制代码
pick f29f90e 理解argmax; 理解accuracy

改为

bash 复制代码
edit f29f90e 理解argmax; 理解accuracy
  1. 恢复整个git工作区到文件已经修改了、尚未 git add 的状态

    复制代码
        --mixed
            Resets the index but not the working tree (i.e., the changed
            files are preserved but not marked for commit) and reports what
            has not been updated. This is the default action.
bash 复制代码
git reset HEAD~
  1. 手动添加文件中的一部分
    可以使用 git add -p xxx_file, 也可以用 vscode 图形界面操作, 选中代码区域后右键选择 Staging Selected Ranges
  1. 执行 git status 查看内容

确实生效了,增加了一个新的 commit "理解 argmax":

  1. 重复 git add, git commit 动作, 直到满意

  2. 执行 git commit --continue, 来告诉 git 你完成了 rebase 操作

  3. 最终查看效果

相关推荐
深海鱼在掘金5 天前
Git 完全指南 —— 第1章:Git 概览与版本控制演进
git
noravinsc6 天前
关于Git Flow
git
蜜獾云6 天前
在Git中配置用户名和密码
git
scx_link6 天前
通过git bash在本地创建分支,并推送到远程仓库中
开发语言·git·bash
南大白6 天前
IntelliJ IDEA 运行时的 JVM 本地内存溢出崩溃
git
码农小旋风6 天前
Claude Code 基础用法大全:对话、分析、修改、测试、Git 和工作流
人工智能·git·chatgpt·claude
南大白6 天前
Git 撤回提交完整方案
git
像风一样的男人@6 天前
python --实现代理服务器
git·ui
sbjdhjd6 天前
从零搭建企业级 CI/CD(下):Jenkins+GitLab+Harbor 全链路实战指南
git·servlet·ci/cd·云原生·云计算·gitlab·jenkins
码云数智-大飞6 天前
Go Channel 详解:并发通信的正确姿势
前端·数据库·git