Many programmers make Git commits in a haphazard way that makes it easy to make mistakes and commit things they didn’t mean to.
Here’s a six-step process that I use every time I make a Git commit.
1. Make sure I have a clean working state
In Git terminology, “working state” refers to what you get when you run
I always run
git status before I start working on a feature. Otherwise I might start working, only to discover later that the work I’ve done is mixed in with some other, unrelated changes from earlier. Then I’ll have to fix my mistake. It’s cheaper just to check my working state in the beginning to make sure it’s clean.
2. Make the change
This step is of course actually the biggest, most complicated, and most time-consuming, but the content of this step is outside the scope of this post. What I will say is that I perform this step using feedback loops.
3. Run git status
When I think I’m finished with my change, I’ll run a
git status. This will help me compare what I think I’m about to commit with what I’m actually about to commit. Those two things aren’t always the same thing.
4. Run git add .
git add . will stage all the current changes (including untracked files) to be committed.
5. Run git diff –staged
git diff --staged will show a line-by-line diff of everything that’s staged for commit. Just like the step where I ran
git status, this step is to help compare what I think I’m about to commit with what I’m actually about to commit—this time at a line-by-line level rather than a file-by-file level.
Finally, I make the commit, using an appropriately descriptive commit message.
The reason I say appropriately descriptive commit message is because, in my opinion, different types of changes call for different types of commit messages. If the content of the commit makes the idea behind the commit blindingly obvious, then a vague commit message is totally fine. If the idea behind the commit can’t easily be inferred from the code that was changed, a more descriptive commit is called for. No sense in wasting brainpower on writing a highly descriptive commit message when none is called for.
By using this Git commit process, you can code faster and with fewer mistakes, while using up less brainpower.