commitlint & Git Hooks Deep Dive: Automate Commit Message Validation
This article details how to enforce commit message standards with commitlint and husky Git hooks, including step-by-step configuration, hook execution flow, the husky 'h' engine internals, and a practical cheatsheet for commit types and bypass commands.
Overview: One Commit, Two Checks
The article builds on a previous setup using husky + lint-staged for code formatting. It adds a second gate: commit-msg hook with commitlint to validate commit message structure (type/scope/subject). The full toolchain uses only four dev dependencies: husky, lint-staged, prettier, commitlint.
Step 1: Prettier + lint-staged for Code Formatting
Configure lint-staged in package.json to run Prettier on staged files:
// package.json
"lint-staged": {
"*.{js,jsx,ts,mjs,astro,css,md}": "prettier --write"
}Prettier config ( .prettierrc) matches team style:
{
"printWidth": 120,
"singleQuote": true,
"semi": true,
"tabWidth": 2
}Gotcha: lint-staged matches files in the Git staging area. If a file’s content hasn’t changed since last commit, git add won’t stage it, and lint-staged reports “No staged files match”. Fix: modify the file then git add again.
Step 2: Husky pre-commit Hook
npm i -D husky
npx husky init # creates .husky/ and adds "prepare": "husky" to package.jsonThe prepare script is an npm lifecycle hook: after any npm install, hooks activate automatically — zero manual config for teammates.
Edit .husky/pre-commit to run lint-staged:
npx lint-stagedStep 3: commitlint for Commit Messages
npm i -D @commitlint/cli @commitlint/config-conventionalCreate commitlint.config.js (ESM syntax requires "type": "module" in package.json; otherwise use CommonJS or .mjs extension):
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', [
'feat', 'fix', 'docs', 'style', 'refactor',
'perf', 'test', 'build', 'ci', 'chore', 'revert'
]],
'subject-case': [0], // allow Chinese subject
'header-max-length': [2, 'always', 100]
}
};Rule structure: each rule is [level, condition, value]:
Level: 0 = disable, 1 = warn (pass), 2 = error (reject commit)
Condition: always (always enforce) or never (inverse)
Value: e.g., max length 100 for header-max-length Add .husky/commit-msg hook:
npx --no -- commitlint --edit "$1"$1is the path to the commit message file (Git passes it). --no -- forces local commitlint, avoiding global version conflicts.
Live Test: Rejected Commit
git commit -m "添加格式文件"Output shows pre-commit (prettier) passes (four ✔), then commit-msg fails:
⧗ input: 添加格式文件
✖ subject may not be empty [subject-empty]
✖ type may not be empty [type-empty]
husky - commit-msg script failed (code 1)Fix: use conventional format, e.g., chore: 添加格式化配置. Any hook returning non-zero exit code aborts the commit.
Internals: How Git Hooks Are Invoked
Git commit internal sequence:
① Check staging area
② pre-commit ← commit message doesn’t exist yet; only code checks
③ Generate .git/COMMIT_EDITMSG
④ commit-msg "$1" ← message file path passed as argument; message validation
⑤ Create commit object, write historyThis explains the natural division: pre-commit runs before message exists (code only); commit-msg runs after message file is created (message validation).
How Git Finds Hooks: core.hooksPath
Git reads git config core.hooksPath (set to .husky/_ by husky init). This redirects hooks from default .git/hooks/ (local, not committed) to .husky/_ (committed, shared).
Each hook in .husky/_ is a tiny forwarder:
#!/usr/bin/env sh
. "$(dirname "$0")/h" # source the h scriptThe real logic lives in h (excerpt):
n=$(basename "$0") # hook name, e.g., commit-msg
s=$(dirname "$(dirname "$0")")/$n # locate your .husky/commit-msg
[ ! -f "$s" ] && exit 0 # no custom hook → silent pass
[ "${HUSKY-}" = "0" ] && exit 0 # HUSKY=0 global skip
sh -e "$s" "$@" # ★ strict mode, forward args
[ $c != 0 ] && echo "husky - $n script failed (code $c)"
exit $c # non-zero → abort commitSummary: forwarder = empty shell; h = universal dispatch engine; your .husky/xxx = actual business logic. Add a new hook by creating a file in .husky/ with the hook name; h picks it up automatically.
.husky/_ Directory & 14 Built-in Hooks
.husky/
├── pre-commit ← your code (prettier, active)
├── commit-msg ← your code (commitlint, active)
└── _/ ← husky-generated, do not edit
├── pre-commit, commit-msg… 14 placeholder forwarders
├── h ← only file with logic (dispatch engine)
├── husky.sh ← v8 compatibility shim
└── .gitignore ← content "*", not committed; regenerated on npm installKey hooks and typical uses:
pre-commit (before commit): check/modify staged content (active)
commit-msg (after message finalized): validate message (active)
prepare-commit-msg (before editor opens): auto-generate message template
post-commit (after commit): notifications; cannot abort
pre-push (before push): run build/tests, block bad pushes
pre-merge-commit / post-merge : merge checks / auto npm install
post-checkout / pre-rebase / post-rewrite : cleanup, pre-checks, post-processing
applypatch series / pre-auto-gc : patch workflow & GC notifications
Inactive forwarders are skipped by h ’s first guard: [ ! -f "$s" ] && exit 0. Maintenance rule: only edit files directly under .husky/; never touch _/.
Daily Cheatsheet
Commit message format: <type>(<scope>): <subject> Allowed types (from config):
feat – new feature
fix – bug fix
docs – documentation
style – code formatting
refactor – refactoring
perf – performance
test – tests
build – build/deps
ci – CI config
chore – misc
revert – rollback
Bypass / debug commands:
git commit --no-verify # skip all hooks
HUSKY=0 git commit # same effect (h script switch)
HUSKY=2 git commit # debug mode, prints hook executionTip: LF will be replaced by CRLF warning on Windows is harmless; enforce LF with .gitattributes ( * text=auto eol=lf).
Summary: Four Dependencies, Three Outcomes
① Staged code auto-formatted, clean diffs (pre-commit)
② Commit messages forced to convention, readable history (commit-msg)
③ npm install → hooks active for everyone, zero collaboration cost (prepare hook)Core principle: forwarder wires, h engine dispatches, your hooks are business; pre-commit guards content, commit-msg guards message; any non-zero exit aborts commit.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
