Quickly fixing small whoopsies with git amend


Quickly fixing small whoopsies with git amend

git amend

It’s not unusual to commit something, only to realize later that a minor detail was left behind, such as a comment or typo. Through git, there are many ways to fix this, the easiest one would be to create a new commit, obviously, but that probably wouldn’t look pretty in the git history. Another way is through rebasing, but that’s sort of overkill. Instead, let’s explore how git amend works, and how easily it can solve our troubles.

Scenario

So let’s suppose we are in a big team, creating an e-commerce website, and we are currently implementing the wishlist. We have finished all the crazy logic, the unit tests are OK, so it’s time to commit. But then, as soon as you push your commit, you realize something terrible: a typo.

private void AddItemToDishlist()
{
    // Handle item added to wishlist
}

Oh noes! How do we fix this? We could simply create a new commit with a message such as “Fix typo” and be done with it. But then that small typo would be forever in our git history, shaming us. And what if happens again? We would like our git history to be meaningful, with constructive git messages.

Git amend to the rescue

Through the use of Git amend, we do not have to worry about staining our git history. With it, we can apparently include our fixes in the last commit. And I say apparently because under the hood, the commit is replaced entirely. Let’s see some commands:

git add .
git commit --amend
git push -f

We begin by adding the files that we need to fix. In this case, we just added everything. We then use git commit with the –amend flag to perform our desired magic.

And to finish it, we push it with the -f flag. If we hadn’t pushed already, this wouldn’t be needed, but that’s not our current scenario. Also, we need the -f flag because since we are replacing commits, git wants us to confirm that we know what the hell we are doing, otherwise we would get an error similar to this:

error: failed to push some refs to 'giturl'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

And last but definitely not least, remember to be extra careful when using the -f flag, since it can cause a lot of trouble.