How to fix an overcommit
Have you ever accidentally committed more files than you intended? Have you ever accidentally used git commit -a
when you just meant git commit
? I know I have on occasion.
So let's say you were trying to commit file1
and file2
, but you have changes in file3
that you were wanting to commit separately. Note that in this case I want to preserve the changes in file3
, I just want to commit them later. If I didn't care about the changes I could use git reset --hard HEAD^
and just start over. However, then I would have to redo the work in the various files, which of course is no fun. But if you keep track of the current SHA of HEAD, which you can get via git log --oneline -1
, then you can actually cherry-pick
the change back with the --no-commit
flag. Then you can use git reset
to reset the files you don't care about. This sounds pretty abstract, so here's the steps one by one:
git add file1 file2
git commit -a -m 'some message' # oops!
git log --oneline -1 # keep the SHA reported from this command
git reset --hard HEAD^
git cherry-pick --no-commit 0b13436 # This is the kept SHA from earlier
git reset file3
git commit # This recommits the earlier change, but without file3
After those commands, file3
will be in a modified but uncommitted state, which is exactly what I wanted. You can then commit file3 separately with a different message or continue development.