Keith T. Butler

Erase commits from git branch history

February 18, 2018 | 2 Minute Read

tags: [ git  code  ]
Re-writing history is one of the things that terrifies me about `git`. The idea that with a few rogue keystrokes I can play Joe Stalin on the history of a project seems like a bit too much power. Luckily it is not that easy to do by mistake, but what if you did want to do it, for some reason?
Fig1. A re-writer of history.

I was recently working on a few new branches and obviously, being careless committed changes meant for one branch to the other. I didn’t realise this until it came time for me to issue a pull request, for someone to merge my branch into the master. Naturally the rogue commit was both confusing and embarrassing; so I wanted it gone.

Thanks to Dan Nixon for showing me this fix.

  • Establish which commit it is I want to remove
git log

This gives:

commit d13179c754d03fec3842177da0dff5a6da78ea45
Author: fodblog <keith.butler@stfc.ac.uk>
Date:   Mon Feb 12 16:32:02 2018 +0000

    switched to new instrument definition file

commit 8b2bb692e62aa9307398be896d109e39e7c73e6f (error-report-gui)
Author: Keith Butler <keith.butler@stfc.ac.uk>
Date:   Fri Feb 9 16:49:22 2018 +0000

    The first files for the error reporting GUI, not yet functional

commit de7faa7c3d5a99f11705349206f5f7e3affb1ce4 (origin/21734_wavelength_rebin, master)
Merge: ec7c97ea9e 68c3c3d3f5
Author: fdsfj jkjlk  <abshhdbh>
Date:   Fri Feb 9 14:58:56 2018 -0500
  • Here I want to remove: The first files for the error reporting GUI, not yet functional
  • Be sure that this is committed to another branch - otherwise we will lose it!
  • Copy the hash of the commit immediately below this commit, in this case: de7faa7c3d5a99f11705349206f5f7e3affb1ce4
  • Run an interactive rebase:
 git rebase -i de7faa7c3d5a99f11705349206f5f7e3affb1ce4

This lands us in an editor like this:

	pick fcd442c880 switched to new instrument definition file
	pick 9be43d8b6a Re #21735 Added the parameters files to match new MAPS IDF.
	pick fb5ecc711c Re #21735 Modified valid from field to avoid conflicts
  • Choose the commit to drop and change pick to drop
  • wq
  • Finally: git push --force-with-lease
  • DONE