GIT tip: Easily create a commit in the past

GIT tip: Easily create a commit in the past

Sometimes it makes sense to create a commit in the past when you’re working on a new feature branch. For example when you refactor some code, where the new feature relies on, after you’ve already made some progress.

  1. Open git log and copy the id of the commit that’s two places before where you want to insert your commit.
  2. Temporarily store your changes with git stash.
  3. Begin a rebase with git rebase -i {ID from step 1}.
  4. Change the commit you want to insert after from pick to edit.
  5. Begin the rebase and it will automatically pause, so we can insert a new commit.
  6. unstash your saved changes with git stash pop. Stage and commit your changes, be sure to make a new commit and don’t amend the previous commit.
  7. git stash any potential leftover changes and use git rebase --continue to replay the successive commits.

Note: If you previously pushed to your branch you’ll have to force push because your git history had been altered.

Take for example the following git history:

Tue Oct 1 20:40:15 2019 +0200 278701a (HEAD -> master) Add Awesome stuff
Tue Oct 1 20:39:09 2019 +0200 81a9cd5 Refactor to support secret function
Tue Oct 1 20:38:11 2019 +0200 f243b64 Fix horrible bug
Tue Oct 1 20:37:41 2019 +0200 0952d8e Add some magic
Tue Oct 1 20:36:48 2019 +0200 4b43f38 My first commit

Let’s say I want to insert a commit with my changes after 0952d8e. In this case, I would stash my changes and start with git rebase -i 4b43f38 and change 0952d8e from pick to edit. Now that my rebase is paused after 0952d8e I can unstash, stage and commit my changes. When that’s done I’m able to continue the rebase.

And that is, my git timeline will now contain a new commit at the desired place in history.