Changing Recent Commits with Git

Have you ever committed to your repo and realised you've done something a bit silly? I just did that. I moved to a new machine and forgot to setup my .gitconfig with the correct username and email, so when I committed, the commit had the wrong user against it. Not a big problem, but it just looks a bit...well, untidy.

Fear not. Git is all-powerful and allows you to change your mistake even though you've already committed it. Thanks to Tekkub on the GitHub Google Group for the nudge in the right direction.

How does I dos it?

Like this.

1
git reset --soft HEAD^

This will reset your working copy to the state before you committed and remove the commit so you can make changes to your working copy (if needed) and re-commit.

Re-commit the changes.

1
git commit -m "Changed something"

If you've already pushed to "GitHub":http://www.github.com or another external repo, you can re-push, but you'll need to add --force because we have removed a commit locally and Git doesn't like that.

1
git push origin --force

I'm not sure whether this would be a good idea if someone else has cloned your repo, but I'm ok because I am the only person who pushes to this one.

Git is great, but powerful, so be careful. I'm sure it would be easy to completely trash your repo with the wrong series of commands.