Cover Image for Flash Tip — I Made a Commit on the Wrong Branch! Help!

Flash Tip — I Made a Commit on the Wrong Branch! Help!

By Charlie Dalldorf on

Picture this. Let's say you are working on multiple features in a repository, and when you context-switched to a different ticket, you forgot to change branches with it. You hammer away, did the git add . and the git commit -m "<Comment Here>" and only after you committed the change you go:

"Darn it! I committed on the wrong branch!"

Have no fear! This is something every software and database developer goes through. So how do we best get out of our problem?

For this demonstration, I am using Powershell on Windows. If you don't already, I highly recommend installing the posh-git module because it will make life much easier. If you are Linux, I recommend zsh + ohmyzsh.

I made a commit and haven't pushed it up to the branch

If your terminal looks like this:

image2

Then getting out of it isn't too bad. All you need to do is type in:

git reset --soft HEAD^

image3

What happens is we took the changes from commit 3bd0bd1 and staged your changes back before you made the commit. Now we can swap to the correct branch, commit, and push the changes as needed.

I made a commit and did push it up to the wrong branch

Now it's a bit more complicated. You have a couple of options here.

Revert

The first option is to do a git revert. Get the commit you need to revert and execute git revert <Commit Id> and then a git push.

image4

Be aware that this will add additional commits to your history.

image5

Hard Reset

The other option is to do a HARD reset, which is destructive. The way we do that is we find the last good commit and we do a git reset --hard on that commit. In my example, it would be 1fe5390. Then we do a git push -f which does a force push into that branch.

Author Note: Be extremely careful if you do this. This is a destructive operation where you lose what you have been working on. If you want to retain your work, do NOT under any circumstance do this.

image6

Bonus: Git…a Dog?

If you noticed in my terminal messages, I am pulling the git history for all of these examples. If you want a simple way of aliasing that long-winded CLI command, we can add a git config alias:

git config --global alias.adog "log --all --decorate --oneline --graph"

Then we can type in:

git adog

image7

image8

Hope that helps out! Until next time!

Additional Resources

git reset documentation

git revert documentation