Home > Enterprise >  How can I add a new commit before a previous commit?
How can I add a new commit before a previous commit?

Time:08-19

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?

CodePudding user response:

First off, you cannot insert a commit in front of another and have the second keep its original 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

This has the advantage that you can always git rebase --abort to get back to a clean state where all your commits are available. 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; 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

  1. git rebase -i. Insert a new line containing just break to the start of the change list
  2. Git will stop at the point you said "break", so before any changes were applied. 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).
  3. 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.

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. 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.

  • Related