git - 使用 git rebase -i 更改以前提交的代码

标签 git rebase git-amend

我有一个包含各种提交的存储库,我想将其 merge 到两个补丁中。 一个补丁引入了该功能,另一个补丁更改了现有代码以使用它。 问题是,当我编码和提交时,我并没有考虑到这一点,所以有些提交可以同时完成这两项工作。我如何拆分这些提交?

我知道我可以用 git rebase -i 并为我想更改的每个提交选择编辑,但这样我只能更改提交消息,而不是代码

最佳答案

Git rebase允许您 split commits :

In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:

  • Start an interactive rebase with git rebase -i ^, where is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.

  • Mark the commit you want to split with the action "edit".

  • When it comes to editing that commit, execute git reset HEAD^. The effect is that the HEAD is rewound by one, and the index follows suit. However, the working tree stays the same.

  • Now add the changes to the index that you want to have in the first commit. You can use git add (possibly interactively) or git gui (or both) to do that.

  • Commit the now-current index with whatever commit message is appropriate now.

  • Repeat the last two steps until your working tree is clean.

  • Continue the rebase with git rebase --continue.

If you are not absolutely sure that the intermediate revisions are consistent (they compile, pass the testsuite, etc.) you should use git stash to stash away the not-yet-committed changes after each commit, test, and amend the commit if fixes are necessary.

关于git - 使用 git rebase -i 更改以前提交的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540824/

相关文章:

具有多个命令的 Git 别名

Git commit --amend merge 两个提交

git commit in terminal 打开VIM,但是无法回到终端

git - 如何响应 bashrc 函数的 git 输出?

git - rebase 后无法推送到分支

git - 您是否重新使用(或其他介词)另一个分支?

git - 在预提交 Hook 中,查找正在创建的提交的父级的哈希值

git - autodoc 指令在本地有效,但在 readthedocs 上无效

git - 反正有没有查看所有以前的 GIT 还原

git - 当不进行 cherry-pick 时,之前的 cherry-pick 现在为空