The other day I had a great discussion with a few of my coworkers about improving our Git Commits. After some back and forth, and discussing Sal Ferrarello’s rules for git commits, I decided to create a git commit template that would open up in my editor each time I used git commit
in my terminal.
If your git config isn’t set up to open up in your preferred code editor, that can be done in a few quick steps.
Enabling The Code Command for VS Code
First, you’ll want to make sure that your code editor can be opened via the command line. My preferred code editor is VS Code and can be opened via the command line by using code
.
If you’re also using VS Code, you can enable this functionality by opening the command palette (shift + command + p
) and selecting the “Shell Command: install ‘code’ command in PATH” option.
Once you’ve done that, you should be able to open the editor with a new text file with:
code my_new_file.txt
Configuring Your Git Config
Your global git config provides lots of options for you to configure how your git responds in certain conditions. The option we’re concerned about right now is core.editor
.
By adjusting this setting, we can tell git that any time it needs input from the user, such as a git commit, to use our code editor instead of a command line editor like vim or nano.
Use this command to set this up in your config:
git config --global core.editor "code --wait"
We need to use the --wait
flag with VS Code because we need git to pause it’s execution until the commit message file is saved and closed. That flag will keep it from automatically committing a blank message.
Now, when you type git commit
your editor will open with a text file instead of opening in the terminal window. When you’re done writing your commit message, save the file, then close it to finish the commit and allow git to resume.
Git Commit Message Templates
Something cool that I found out about git config
is that you can set up your own commit template messages instead of the default one that shows up in your editor.
To change this to something a little more useful, we can update that message with:
git config commit.template ~/.git-commit-template
Be sure to create the ~/.git-commit-template
file somewhere you’ll be able to find it in the future. I store my templates in ~/.git/templates
just to keep everything together.
Here’s the template that I’m currently using in my git config
and I find that it helps me create far more useful commits:
Here’s that template in use within VS Code. The commented lines will not actually be used in the commit message, but they’re helpful reminders on how to frame your commit.
And afterwards, here is what actually made it into the commit.
One response to “Using VS Code to Improve Your Git Commits”
Here’s a VSCode extension to get a better Git commit message experience: https://marketplace.visualstudio.com/items?itemName=walles.git-commit-message-plus
Wrote it mostly for myself but it should be useful to others as well.