Sub topic 9
Enforcing the format with a commit-msg hook and commitlint
A convention that relies on memory fades within weeks. This chapter covers automated checks that reject a non-conforming message at the moment it is written, and again in CI for anything that slips past. It assumes you can write Conventional Commits messages (type, scope, description, body, footers), run commands in a terminal, and use basic Git. Some familiarity with npm helps for the commitlint part.
Where a check can run
A commit message can be checked at three points. Each catches different mistakes.
| Where | What it checks | Strength | Weakness |
|---|---|---|---|
| Local `commit-msg` hook | The message, before the commit is created | Immediate feedback, nothing bad enters history | Easy to skip, and not shared by default |
| CI job on a branch | Every commit in a range | Cannot be bypassed on the developer's machine | Feedback comes after the push |
| CI check on the PR title | The title that becomes the squash commit | Matches what lands on the main branch under squash merges | Does not check the individual commits on the branch |
Use the local hook for speed and CI for enforcement. The rest of the chapter builds both.
How the commit-msg hook works
Git runs the commit-msg hook after you finish writing the message and before it creates the commit. Git passes one argument: the path to a file holding the message, usually .git/COMMIT_EDITMSG. If the hook exits with a non-zero status, Git aborts the commit. If it exits with 0, the commit proceeds.
A hand-written hook
The smallest useful hook is a shell script that tests the first line against a regular expression. Save it as .git/hooks/commit-msg and make it executable with chmod +x .git/hooks/commit-msg.
#!/bin/sh
# .git/hooks/commit-msg (must be executable)
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9._-]+\))?!?: .+'
if ! head -n 1 "$1" | grep -Eq "$pattern"; then
echo "Commit message must look like: type(scope)!: description" >&2
exit 1
fiThe pattern reads left to right:
^(feat|fix|...)requires one of the allowed types at the start of the line.(\([a-z0-9._-]+\))?allows an optional scope in parentheses.!?allows the optional breaking-change marker.: .+requires a colon, a space, and at least one character of description.
Try it with a message that should fail:
git commit --allow-empty -m "updated stuff"Git prints your error message and does not create the commit. Run the same command with -m "chore: try the hook" and it succeeds.
What the hand-written hook misses
This hook is a good starting point, but it has gaps you should know about:
- It checks only the first line. A missing blank line before the body, or a malformed
BREAKING CHANGE:footer, passes. - It does not limit the header length or check the case of the description.
- Git generates some messages itself.
git mergewritesMerge branch 'x', andgit revertwritesRevert "feat: ..."with a capital R. Both fail the pattern above. - Hooks in
.git/hooksare not part of the repository, so teammates do not receive them when they clone. - Anyone can skip the hook with
git commit --no-verify.
You can handle Git-generated messages by letting them through before the pattern test:
#!/bin/sh
first_line=$(head -n 1 "$1")
case "$first_line" in
"Merge "*|"Revert \""*) exit 0 ;;
esac
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9._-]+\))?!?: .+'
if ! printf '%s\n' "$first_line" | grep -Eq "$pattern"; then
echo "Commit message must look like: type(scope)!: description" >&2
exit 1
fiWhether to exempt Revert "..." messages is a team decision. Exempting them keeps git revert frictionless. Rejecting them forces authors to rewrite the message as revert: ... so release tooling can see it.
Sharing hooks with the team
Because .git/hooks is not versioned, put hooks in a tracked directory and point Git at it:
mkdir .githooks
cp .git/hooks/commit-msg .githooks/commit-msg
git config core.hooksPath .githooksEach developer still has to run the git config line once. A setup script, a Makefile target, or a package manager step is the usual place to run it. This is why most JavaScript projects use a hook manager such as Husky, described below.
Using commitlint
Writing regular expressions for every rule gets tedious. commitlint is a tool that parses a message into its parts (type, scope, subject, body, footers) and checks each part against named rules. Its shared ruleset @commitlint/config-conventional encodes the Conventional Commits conventions.
Install it and create a config file:
npm install --save-dev @commitlint/cli @commitlint/config-conventional
# commitlint.config.js
module.exports = { extends: ['@commitlint/config-conventional'] };
# check the most recent commit message
npx commitlint --from HEAD~1 --to HEADThe # commitlint.config.js line marks the start of the file's contents, so create that file with the module.exports line in it. If your package.json sets "type": "module", a .js config is treated as an ES module. Either name the file commitlint.config.cjs or write export default { extends: ['@commitlint/config-conventional'] };.
You can also test a message without making a commit by piping it in:
echo "added a thing." | npx commitlint
echo "feat(parser): add array literals" | npx commitlintThe first command prints the rule violations and exits with a non-zero status. The second prints nothing and exits with 0. The exit status is what hooks and CI jobs act on.
What the shared rules check
The ruleset covers more than the regular expression did. The main rules are:
type-enum: the type must be one ofbuild,chore,ci,docs,feat,fix,perf,refactor,revert,style,test.type-caseandtype-empty: the type must be lowercase and present.subject-emptyandsubject-full-stop: a description is required and must not end with a period.subject-case: the description must not use sentence case, start case, pascal case, or upper case.header-max-length: the first line must be at most 100 characters.body-leading-blankandfooter-leading-blank: a blank line must separate the header, body, and footers.
Rule names and defaults can change between major versions, so check the documentation for the version you install.
Customizing rules
Each rule is an array of [level, applicable, value]. The level is 0 (off), 1 (warning), or 2 (error). The applicable field is 'always' or 'never'. Override rules after the extends line:
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
// restrict scopes to a known list
'scope-enum': [2, 'always', ['api', 'parser', 'cli', 'docs']],
// keep headers short enough for `git log --oneline`
'header-max-length': [2, 'always', 72],
// require a scope on every commit
'scope-empty': [2, 'never'],
},
};A fixed scope list prevents parser, Parser, and parsing from all appearing in the same history. The trade-off is maintenance: someone has to update the list when the project grows a new area.
Running commitlint from a hook
commitlint can read the message file that Git passes to the hook, using --edit. With Husky, a hook manager that installs shared hooks for everyone who runs npm install, the setup looks like this:
npm install --save-dev husky
npx husky init
echo 'npx --no -- commitlint --edit "$1"' > .husky/commit-msgnpx husky init adds a prepare script to package.json, so each developer's npm install configures the hooks automatically. The --no flag stops npx from downloading packages during a commit, which keeps the hook fast and offline-safe. The "$1" is the message file path that Git supplies. Husky's setup commands have changed between major versions, so check its documentation if the commands above do not match your version.
Running commitlint in CI
The local hook is a convenience. CI is the real gate, because it runs for everyone and cannot be skipped with --no-verify. Lint every commit that the branch adds:
npx commitlint --from origin/main --to HEAD --verboseIn a GitHub Actions job, make sure the checkout fetches enough history for that range to exist. The default shallow checkout fetches only one commit.
name: commitlint
on: [pull_request]
jobs:
lint-commits:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx commitlint --from "origin/${{ github.base_ref }}" --to HEAD --verboseIf your team uses squash merges, individual commits on a branch disappear on merge, and only the PR title survives as the commit subject. In that case, lint the title instead of the branch commits:
- run: echo "$PR_TITLE" | npx commitlint
env:
PR_TITLE: ${{ github.event.pull_request.title }}Passing the title through an environment variable, not pasting it into the shell command, avoids shell injection from a title that contains quotes or $(...).
Common failure modes
- The hook never runs. The file is not executable, it has the wrong name (it must be exactly
commit-msg, with no extension), orcore.hooksPathpoints somewhere else. Check withgit config core.hooksPathandls -l. - CI fails with "bad revision". The checkout was shallow. Set
fetch-depth: 0. - Merge commits fail the lint. commitlint ignores default merge and revert messages in most setups. A hand-written hook needs the explicit exemption shown earlier.
- Developers bypass the hook.
--no-verifyis a legitimate escape hatch for emergencies. Rely on CI to catch it. - The config is silently ignored. The file name or module format does not match your project's
typesetting. Runnpx commitlint --print-configto see the rules that were actually loaded.
Exercise
A teammate says the commit-msg hook is installed and passing, yet a commit with the message "stuff" appears on the main branch. Give two plausible causes and the control that prevents each from reaching main.
Show answer
Either the author skipped the hook with git commit --no-verify, or the hook was never installed on their machine because .git/hooks is not shared through the repository. Both are prevented by running commitlint in CI and making it a required check on pull requests. CI runs the same rules regardless of local configuration. If the team squash merges, lint the PR title as well, because that title becomes the commit message on main.
Exercise
Write a commitlint config that extends the conventional ruleset, requires a scope on every commit, and limits scopes to api and cli.
Show answer
module.exports = { extends: ['@commitlint/config-conventional'], rules: { 'scope-empty': [2, 'never'], 'scope-enum': [2, 'always', ['api', 'cli']] } };