Alon Swartz - Mon, 2010/12/27 - 09:42 - 7 comments | Latest by Jeremy
I use Git. I use it a lot. I basically use it for everything I do, from code revision control to revisioning my notes, my journal, even my email archive (don't ask, it's a long story).
As with anything you do, you are bound to make mistakes. When it comes to coding and revision control, mistakes can range from bad commit messages, to buggy code, to code that shouldn't have been committed together with other code, or even at all.
Here are a couple of tips I find myself using quite often.
Correcting mistakes in the last commit
This is very easy with git-commit --amend, For example:
I decide I don't like the commit description I used.
git-commit --amend # just edit the description
I want to edit buggy code I just committed to path/to/file.
editor path/to/file git-add path/to/file git-commit -v --amend # note your recent changes are part of the commit
I want to remove a file I included accidentally in the last commit (e.g., because I want to commit changes to that file separately).
git-reset HEAD^1 path/to/file # this doesn't delete your changes to path/to/file git-commit --amend -v git-commit -v path/to/file # make a new commit with changes to path/to/file
Correcting mistakes in previous commits
This also uses git-commit --amend, but involves two extra steps:
1) git-checkout <bad-commit> ... make your changes ... 2) git-commit --amend -v 3) git-rebase --onto HEAD <bad-commit> <checked-out-branch>
If a conflict occurs while re-applying your commits, you may have to manually resolve the conflict and then git-rebase --continue. See the manual page for further details.
For example, I notice I made a mistake in commit 0f0d8a27622e7bf7f008983c4b8ee23bfb9843ab several revisions ago and I'm checked out to branch master.
To correct the commit history:
git-checkout 0f0d8a27622e7bf7f008983c4b8ee23bfb9843ab editor path/to/file git-add path/to/file git-commit --amend -v git-rebase --onto HEAD 0f0d8a27622e7bf7f008983c4b8ee23bfb9843ab master
Note that by editing your commit history you are effectively re-applying your changes, and thus creating new commits with new commit ids. For example, this means you'll have to recreate existing tags.