clueless coding // TODO: be smarter


Undoing and Fixing a Bad Git Commit

Re-committing a Mistake in Git

If you’re anything like me, you’ve probably committed a mistake in Git before. Maybe you imported something you didn’t need, or left in a // FIX THIS SOON comment into your code. Maybe you committed code, tested it, and then found out your commit broke every test your codebase knows. That’s okay - I’ll keep your secret.

Luckily, git provides us a handy little way to undo that commit, make our changes, and then recommit our now pristine code.

NOTE: This is not recommended at all if you’ve already pushed your misguided commit and others are relying on that history. This snippet relies on force pushing a changed history - if you’re working in a collaborative environment, you could cause issues with the repo for others working with you.

In a snippet, here’s what you’ll have to do:

git add mistakeFile.txt
git commit -m 'this commit is full of horrible mistakes'
git push origin feature-branch

# to reset the above bad commit
git commit reset HEAD~
vim mistakeFile.txt
git add mistakeFile.txt
git commit -c ORIG_HEAD
git push -f origin feature-branch

We’ll break it down a little farther if you’d like to understand the magic that git just performed for you:



Resetting History in Git

git commit reset HEAD~
vim mistakeFile.txt
git add mistakeFile.txt

This sequence of commands simply resets the head of your branch to right before your failed commit. If you’re familiar with git, you probably are familiar with moving the head of your branch around as well. It’s pretty simple - we’re just telling git to treat us like we’re one commit in the past, i.e. just before the commit of mistakes. We then make our changes and add them to be ready to be committed again.

reset head, showing our broken commit and a fixed commit along side it after resetting

Our bad commit is represented by our red bubble - when we reset to HEAD~, we reset to the commit before it. We then stage a fixed version - our green bubble - so that it’s ready to be committed.

Now, because we want to remove our old commit and replace it with our fixed one, we execute:

git commit -c ORIG_HEAD

This will override our old commit - in our previous image, it will commit our green bubble over our red bubble, effectively replacing it.

fixed git branch, after recommitting our old broken commits with new fixes

Finally, to push this to our remote repository, we run:

git push -f origin feature-branch

This force pushes our changes our changes to the remote. Our branch now looks like we never made a mistake to begin with, and nobody will have to look at a bunch of ‘fix typo’ commits in our history.