How to Remove Text from Your Entire Git History

Sometimes, you have a bad day and end up in a rut. Some people cope by playing videogames. Some may even step outside to smell the roses and realize that their mistake isn't the end-all-be-all for their lives. Some people, like me, like to scream profanities and console.log("A bad word") in my codebase while debugging.

If you're just like me and typed some random obscenity and pushed it to your production codebase while not noticing it for a couple commits, then I have the solution just for you.

BFG Repo-Cleaner

While searching for a solution online, I stumbled across a GitHub article on Removing Sensitive Data. This is typically used when you accidentally pushed an API key or personally identifiable information. However dear reader, in our case, we'll be using their strategy to delete our revolting console.log statement.

I was then recommended to use BFG Repo-Cleaner, an open source tool to mass manipulate git history, to get rid of my stray line of code.

Prerequisites

  1. You'll need to have the permissions to push to your Git repository. If you're simply a contributor and do not have access to the branches where your profanity exists, I'm sorry to tell you that this tutorial is not for you. You should probably read up on how to apologize and make ammends with your teammates.
  2. You'll also need to download the .jar file from the BFG Repo-Cleaner website and have your CLI's java command working.

The Commands

This will replace your specified text content into ***REMOVED*** from all your branches if you have push access.

You'll have to --mirror clone your repo to the same directory where you downloaded the bfg.jar file. In my case it was bfg-1.14.0.jar.

$ ls
bfg-1.14.0.jar
$ git clone --mirror git@github.com:Luzefiru/repo.git
Cloning into bare repository 'repo.git'...
$ echo "console.log('Something really bad');" > badwords.txt
$ java -jar bfg-1.14.0.jar --replace-text badwords.txt repo.git
In total, 33 object ids were changed. Full details are logged here:

C:\Users\LENOVO\Desktop\Programming\repo.git.bfg-report\2024-04-08\21-54-46

BFG run is complete! When ready, run: git reflog expire --expire=now --all && git gc --prune=now --aggressive
$ cd repo.git
$ git reflog expire --expire=now --all && git gc --prune=now --aggressive 
$ git push -f

All instances of the words you added in your badwords.txt file are not transformed into ***REMOVED***.

Conclusion

And voilà, your repository is cleaned (including all its branches) and your boss won't scold you for having a random profanity in your codebase!

References