Git

Git: insert a new commit between two past commits

I recently had to commit a bunch of stuff I’d been working on in a logical sequence, but forgot to include a crucial bit of code until I’d already done a bunch of the commits. I didn’t want to have to redo all of them just to add the missing code, but I also didn’t want to end up with a commit sequence that wouldn’t work if checked out at a point before the missing code. This is where Git saved my ass. While I use TortoiseGit rather than the commandline, the concepts are the same:

Turns out to be quite simple, the answer found here. Suppose you’re on a branch branch. Perform these steps:

  • create a temporary branch from the commit after you want to insert the new commit (in this case commit A):

    git checkout -b temp A
    
  • perform the changes and commit them, creating a the commit, let’s call it N:

    git commit -a -m "Message"
    

    (or git add followed by git commit)

  • rebase the commits you want to have after the new commit (in this case commits B and C) onto the new commit:

    git rebase temp branch
    

(possibly you need to use -p to preserve merges, if there were any - thanks to a no longer existing comment by ciekawy)

  • delete the temporary branch:

    git branch -d temp
    

After this, the history looks as follows:

A -- N -- B -- C

It is of course possible that some conflicts will appear while rebasing.

In case your branch is not local-only this will introduce rewriting history, so might cause serious problems.

GitHub and GitLab commit patches

Bet you didn’t know that both GitHub and GitLab can provide you with a patch file by appending “.patch” to the end of the commit URL? I sure didn’t. For example, this commit:

https://gitlab.com/Ambient.Impact/drupal-modules/commit/6b4b2e808cb842de83c97a722b804e1ca88a2e7f

becomes:

https://gitlab.com/Ambient.Impact/drupal-modules/commit/6b4b2e808cb842de83c97a722b804e1ca88a2e7f.patch

This is super useful when you need to use a patch for a Composer package, etc.