[英]How can I add a new commit before a previous commit?
I created a new branch, then I created one new commit on this new branch.我创建了一个新分支,然后在这个新分支上创建了一个新提交。 Now, I want create a new commit that will be before the previous commit.现在,我想创建一个新提交,该提交将在上一次提交之前。 And I don't want to change the previous commit.而且我不想更改以前的提交。
How can I do it in a simple way?我怎样才能以简单的方式做到这一点?
First off, you cannot insert a commit in front of another and have the second keep its original SHA.首先,您不能在另一个之前插入一个提交并让第二个保留其原始 SHA。 However, the changes applied by the second commit can be unchanged.但是,第二次提交所应用的更改可以保持不变。
I think you have two choices:我认为你有两个选择:
git rebase -i
and reorder the commits git rebase -i
并重新排序提交This has the advantage that you can always git rebase --abort
to get back to a clean state where all your commits are available.这样做的好处是,您始终可以git rebase --abort
回到干净的 state ,其中所有提交都可用。 On the other hand, if your two commits touch the same bit of code, you will be applying your new change to the current state of the code, and then will have to re-write it for the previous state;另一方面,如果您的两次提交涉及相同的代码位,您将对代码的当前 state 应用您的新更改,然后必须为之前的 state 重新编写它; this might or might not turn out to be complicated.这可能会也可能不会变得复杂。
git-rebase -i
and break
and create a new change before the first one使用git-rebase -i
并在第一个更改之前break
并创建一个新更改git rebase -i
. git rebase -i
。 Insert a new line containing just break
to the start of the change list在更改列表的开头插入一个仅包含break
的新行git rebase --continue
. git rebase --continue
。 Your existing commit will be added on top of the current one.您现有的提交将添加到当前提交之上。 There may be conflicts to resolve.可能会有冲突需要解决。This has the advantage that you'll be making your changes when your working directly is in the state you expect it to be.这样做的好处是,当您直接在您期望的 state 中工作时,您将进行更改。
It has the disadvantage that if there are conflicts in the second commit, you can't just use git rebase --abort
to get back to a safe place as it will lose your new commit.它的缺点是,如果在第二次提交中存在冲突,您不能只使用git rebase --abort
回到安全的地方,因为它将丢失您的新提交。 If you did remember to note down the commit SHA of your new change, you can start from step 1 again, and do git cherry-pick THE-SHA
to get your changes back for step 2.如果您确实记得记下新更改的提交 SHA,则可以再次从第 1 步开始,然后执行git cherry-pick THE-SHA
以获取第 2 步的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.