成为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. 最终查看效果

相关推荐
驭渊的小故事19 小时前
linux 基础命令 + git 仓库创建和配置命令
linux·git
行者-全栈开发1 天前
华为云码道 CodeArts 实测:让 AI 用 Rust 写一个 Git 仓库健康度体检台「仓衡」
git·rust·tauri·桌面应用·ai 编程·华为云码道·codearts 代码智能体
挖掘狂人3 天前
Git 从 0 到 1:用一个小项目走完 add / commit / reset / merge / rebase / push
git·后端·github
codigger3 天前
Git 三区域模型:把 add、commit、reset、merge 一次讲透
git·github·编程·编程语言
水饺编程3 天前
第1章:开发环境搭建,在 Windows 中安装 Git
linux·c语言·汇编·git·ubuntu
idanzk3 天前
Git 推送 GitHub 报 SSL_READ /src refspec main 不匹配 完整踩坑记录
git·github·ssl
星恒随风3 天前
Linux开发工具详解(二):Git版本控制、GitHub协作与GDB调试实战
linux·笔记·git·学习·github
寺中人4 天前
Xshell 完全入门指南:从安装到实战,远程连接+文件传输+会话管理全拆解
git·ssh·github·php·远程连接·xshell·运维工具
酬谢神明则必安4 天前
git学习记录01
linux·git·学习
lingchen19064 天前
版本控制 Git源代码项目管理
git