It’s incredibly easy to forget to stage all your files for a given commit. Whether its an untracked file that you only realise should be tracked few commits down the road, or if you’re divving up changed files to stage and commit them logically and in doing so leave a file out accidentally, its something that is bound to happen sooner or later.
In my team we’ve decided that we’re going to strive for more granular commits to make our repository version history more meaningful, as a result the above has been happening to me a lot more often than usual!
In the past I would just create a new commit and include the file with some sort of apologetic comment, but thinking of the bigger picture it makes sense to maintain a brighter, cleaner repo where contributors can theoretically checkout any revision and for it to be exactly what it says on the tin (ie. the commit message and description).
Adding an unstaged file to a previous commit
So you’ve run git status and found out that you have an unstaged file that should be added to a previous commit.
C:\Code\GitTrackingExample>git status # On branch master # Untracked files: # (use "git add
..." to include in what will be committed) # # bootstrap.less nothing added to commit but untracked files present (use "git add" to track)
Running git log or using your Git client of choice should give you a list of commits
C:\Code\GitTrackingExample>git log WARNING: terminal is not fully functional commit 75667aea53252063388914fcf9f07e1bd52cd654 Author: Stephen James
Date: Thu Sep 12 13:05:57 2013 +0100 modified page header commit af2eb46ec051d2f4b7f8e4eb82ce59a7905f4290 Author: Stephen James Date: Thu Sep 12 13:03:47 2013 +0100 adding style to the site commit e9877d1469716b3fc3afe282742300f9f24b18bf Author: Stephen James Date: Thu Sep 12 13:01:40 2013 +0100 created site
- Stage the file
git add bootstrap.less
- Commit it to the desired revision (commit af2eb46)
C:\Code\GitTrackingExample>git commit --amend -C af2eb46 [master 226b94c] adding style to site 2 files changed, 1 insertion(+) create mode 100644 bootstrap.less
- When you're happy that everything is well staged and cleanly committed, push to the upstream repo
Amend and it's parameters
git commit --amend -m "new commit message" <revision hash>or if you want to leave it untouched, use
git commit --amend -C <revision hash>
(as we did in the example above)
or if you want to edit this on the fly in your terminal/console with vi, just leave out the
-C argument and it’ll bring that up for direct editing.