简体   繁体   English

如何在之前的提交之前添加新的提交?

[英]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:我认为你有两个选择:

Create a commit after the current one, then reorder them在当前提交之后创建一个提交,然后重新排序

  1. Make you changes and commit them让你改变并提交它们
  2. 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.这可能会也可能不会变得复杂。

Use git-rebase -i and break and create a new change before the first one使用git-rebase -i并在第一个更改之前break并创建一个新更改

  1. git rebase -i . git rebase -i Insert a new line containing just break to the start of the change list在更改列表的开头插入一个仅包含break的新行
  2. Git will stop at the point you said "break", so before any changes were applied. Git 将在您所说的“中断”处停止,因此在应用任何更改之前。 You can make the changes you need.您可以进行所需的更改。 Commit your changes (you may wish to note down the commit SHA, so that you can easily reapply these changes if the next step goes wrong).提交您的更改(您可能希望记下提交 SHA,以便在下一步出错时可以轻松地重新应用这些更改)。
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM