问题描述
当一次性 git add 了多个修改点, 并且快速的执行了 git commit 后, 你觉得有点懊恼: 明明可以独立为两次或多次 commit, 揉在一块导致历史记录不太清晰。
比如我在 nn1 这个练手项目中, 最近一次 commit, 增加了三个函数:
evaluate()
test_softmax()
accuracy()
git commit 后我后悔了,想要拆解为3次 commit,每次一个函数。
我们知道,对于已经存在的多个commit如果要合并起来,那么 rebase 是相当简单的。拆分 commit 呢? 也是可以用 rebase 来做的,用到的是 edit 这个动作。随后恢复暂存区,重新按需add和commit代码。
具体操作
- 备份现有代码到新的分支
这一步是防止 git 操作失误。 其实熟练了可以省略,因为后续修改如果中途不满意可以git rebase --abort
git checkout backup
- rebase到需要修改的commit的前一次commit
例如我最近一次 commit 需要被拆分, 它是 HEAD
; 它的上一次commit用 HEAD~
来表示:
git rebase -i HEAD~
- 把 edit 改为 pick
pick f29f90e 理解argmax; 理解accuracy
改为
edit f29f90e 理解argmax; 理解accuracy
-
恢复整个git工作区到文件已经修改了、尚未 git add 的状态
--mixedResets the index but not the working tree (i.e., the changedfiles are preserved but not marked for commit) and reports whathas not been updated. This is the default action.
git reset HEAD~
- 手动添加文件中的一部分
可以使用git add -p xxx_file
, 也可以用 vscode 图形界面操作, 选中代码区域后右键选择 Staging Selected Ranges
- 执行 git status 查看内容
确实生效了,增加了一个新的 commit “理解 argmax”:
-
重复 git add, git commit 动作, 直到满意
-
执行
git commit --continue
, 来告诉 git 你完成了 rebase 操作
-
最终查看效果