Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 78 ยท Projects

Project: Quality Gates with Hooks

Build a team's quality gates with Git hooks: a pre-commit check of staged files, a commit-msg format check, a pre-push test run, a shared hooks directory and automated tests for the hooks.

Code review catches design problems, but nobody wants to spend a review comment on a missing semicolon, a forgotten debug marker or a commit message that says "stuff". Those checks are cheap for a machine and annoying for a human, so they belong in hooks: small scripts that Git runs at fixed moments and that can stop the operation by exiting with an error.

In this project you will build the complete set of quality gates for a small repository: a pre-commit hook that inspects what you are about to commit, a commit-msg hook that enforces the message format used in the earlier projects, and a pre-push hook that runs the tests and protects main. You will put them in a tracked .githooks folder so the whole team can share them, write an install script, and, because hooks are code that can be wrong too, test the hooks with a small test harness. This project assumes you have read Git Hooks; it applies that lesson end to end.

Hooks run on each developer's machine, and every developer can skip them with --no-verify or by never installing them. So client-side hooks are a convenience that gives fast feedback, not a security barrier. The authoritative checks must also run on the server: a CI job on every pull request, and branch protection on the hosting service (GitHub Actions, Signing and Security).

The design

The gates, in the order a change meets them:

Hook When it runs What this project checks
pre-commit before the commit is created staged shell scripts parse (bash -n), no NOCOMMIT marker, no staged file over 100 KB, no whitespace errors
commit-msg after the message is written subject is type(scope): summary, at most 72 characters, blank line before the body
pre-push before objects are sent no direct pushes to main, the test suite passes

Three principles guide the code:

  1. Check what will be committed, not what is on disk. The working tree may hold unstaged edits (the file you fixed but did not git add). The hook reads the staged version with git show :path, where :path means "the file as it is in the index".
  2. Be fast. A pre-commit hook that takes 30 seconds gets bypassed. Look only at the changed files (git diff --cached --name-only), and keep slow work such as the full test suite for pre-push or CI.
  3. Explain the failure. A hook that exits 1 without saying why teaches nobody anything. Print what is wrong and how to fix it, on stderr.

Gate 1: pre-commit

git diff --cached --name-only --diff-filter=ACM -z lists the files that are staged and Added, Copied or Modified (deleted files cannot be checked), separated by NUL bytes so unusual file names survive. For each file the hook runs the checks and sets a flag instead of stopping at the first problem, so you see all problems at once. Finally git diff --cached --check reuses Git's own whitespace check (trailing spaces, space before tab, leftover conflict markers) and the hook exits with the flag.

Bash Gate 1: the pre-commit hook in six scenarios

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Walk through the six scenarios in the output:

  1. A clean script is committed. (The chore: add the pre-commit hook commit happened first; the hook files are tracked in .githooks, and they are skipped by the checks so the marker word in the hook's own text does not trigger it.)
  2. A script with an unclosed if fails bash -n, which parses a script without running it. The hook reports broken.sh: shell syntax error.
  3. A file with the marker is rejected and named.
  4. Trailing spaces are reported by Git itself (spaces.txt:1: trailing whitespace.) followed by the hook's own line.
  5. The interesting one: the broken script is staged, then fixed on disk without staging the fix. The first commit is rejected because the staged version is still broken; after git add fix.sh the same commit goes through. The hook did what a reviewer would want: it judged what would actually be committed.
  6. A 150,000-byte file is stopped at the 100 KB limit, the kind of rule that keeps accidental binaries and dumps out of history (see Repository Maintenance).

Be careful with grep -q inside a pipeline when you use set -o pipefail. grep -q exits as soon as it finds a match; the program feeding it may then get SIGPIPE and the whole pipeline reports failure even though the match was found. The hook uses grep -E ... > /dev/null, which reads all its input. In if conditions this is a classic source of hooks that fail only on large files.

Gate 2: commit-msg

Git calls commit-msg with one argument: the path of the file that holds the message. The hook reads it, and a non-zero exit cancels the commit. A regular expression expresses the format:

TEXT
^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9-]+\))?!?: .+

That is: one of the allowed types, an optional scope in parentheses, an optional ! for breaking changes, a colon, a space, and at least one character. Messages that Git writes itself (Merge ..., Revert ..., fixup! ..., squash! ...) are let through, otherwise you could not merge or use autosquash (Interactive Rebase). The hook also limits the subject to 72 characters, and requires an empty line between subject and body, because many tools treat the first paragraph as the title.

Bash Gate 2: the commit-msg hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The loop shows the verdicts, and the first column makes them easy to read. added some stuff, Feat: capital letter (the match is case-sensitive) and fix:no space after the colon are rejected with the usage help. The 102-character subject is rejected for length, and the message whose second line is not empty is rejected for layout. The same scripts then run as a real commit: git commit -m "stuff" is refused with exit code 1, a valid message succeeds, and --no-verify skips the hook, which is why quick and dirty is in the history. That last line is the reminder from the note at the start: a local hook is a safety net, and the CI check on the server decides.

Gate 3: pre-push

pre-push receives the remote's name and URL as arguments and a list of the refs about to be updated on standard input, one per line: <local ref> <local sha> <remote ref> <remote sha>. This hook uses it for a policy (nobody pushes straight to refs/heads/main, with ALLOW_MAIN_PUSH=1 as a deliberate, visible override) and then runs ./test.sh. A failing test cancels the whole push, and nothing is sent.

Bash Gate 3: the pre-push hook with a local remote

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The four pushes in the output show the gate working. The feature branch is pushed after the tests pass (the hook's messages go to stderr, mixed in here with 2>&1). With a file named BROKEN present, the test script fails and Git reports failed to push some refs. Pushing to main is refused before the tests even start. The override works, and the final listing shows feature/login and main on the server.

One limit to remember: the hook runs the tests against your working tree, which is not necessarily the commit you push. If you have uncommitted changes the result can differ from what the server will see. Teams that care run the push check in a clean checkout, or just rely on CI.

Sharing the hooks with the team

Nothing inside .git/ is cloned, so a hook in .git/hooks stays on your machine. The fix is to keep the hooks in the repository, in a normal tracked folder, and tell Git to use that folder:

CONSOLE
git config core.hooksPath .githooks

A relative core.hooksPath is resolved from the root of the working tree. Because this is a setting and not a file, it is not cloned either, so each person runs it once. That is the job of scripts/install-hooks.sh, which you point new teammates to in the README (or run from a make setup or npm install step). The complete project below shows both sides: a new clone has the hooks but Git ignores them until the install script runs.

Git tracks the executable bit, so mark the files with chmod +x before the first commit; a hook without it is silently skipped. Larger teams often use a hook manager (the pre-commit framework, Husky, Lefthook) that does the installing and runs a configurable list of tools. They need network access and package managers, which the sandbox lacks, so they are only mentioned here; the principles are exactly the ones in this project.

Testing the hooks

A hook that is wrong is worse than no hook: it blocks valid work or lets bad work through, and nobody notices until a bad day. So treat hooks as code and test them. The harness in the example below follows a pattern you can reuse for any script:

  • check <name> <ok|fail> <command...> runs a command, hides its output, compares success or failure with the expectation and counts passes and failures;
  • a scratch repository in a temporary directory (mktemp -d, removed by trap ... EXIT) uses the project's hooks through core.hooksPath, with a bare repository as the "server";
  • try_commit stages a file and tries to commit, and cleans up after a rejection so the next test starts from a known state;
  • the script itself exits non-zero if anything failed, so CI can run it.

The marker word is built at run time (printf 'NO%s' COMMIT) because the pre-commit hook would otherwise flag the test file itself. Run the tests from the example, which also shows the clone-and-install scenario:

Bash The whole project: shared hooks, install script and tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

All 12 checks pass. The last step is as important as the others: the script weakens the length rule on purpose (> 72 )) becomes > 7200 ))) and runs the tests again. Now rejects a long subject fails (wanted fail, got ok) and the summary reads 11 passed, 1 failed. A test you have never seen fail proves nothing; this is the quickest way to check that the harness can actually fail.

Extend the project

  1. Add a prepare-commit-msg hook that pre-fills the type from the branch name (feature/login suggests feat:).
  2. Make pre-commit run a formatter in check mode only on staged files, and print the command that fixes them.
  3. Add a post-merge hook that reminds people to reinstall dependencies when a lock file changed (Hooks).
  4. Write a server-side pre-receive hook for the bare repository that rejects pushes with badly formatted commit messages, so --no-verify cannot get around it.
  5. Run tests/test-hooks.sh in CI on every pull request.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the pre-commit hook read files with git show :path instead of reading them from disk?

    The commit contains what is in the index. Unstaged edits on disk are not part of it, so the check must look at the staged content.
  2. 2. Two developers clone the repository. One of them never runs the install script. What happens?

    Hook files are cloned with the repository, but the core.hooksPath setting is local configuration and is not. Without it Git looks in .git/hooks.
  3. 3. What exits the commit-msg hook with success for Merge branch 'x'?

    Merge, Revert, fixup! and squash! subjects are generated by Git, so the hook lets them pass instead of demanding the conventional format.
  4. 4. What does a pre-push hook read from standard input?

    The remote name and URL arrive as arguments. The refs to be updated are written to the hook's standard input.
  5. 5. Why does the project test the hooks and deliberately break one of them?

    A test that cannot fail gives false confidence. Breaking the hook and watching the matching check fail proves the harness really exercises the hook.

Summary

  • Hooks are executable scripts in .git/hooks (or the folder named by core.hooksPath); exit 0 lets the operation continue and any other status cancels it.
  • pre-commit should inspect the staged content (git show :path, git diff --cached), be fast and report every problem with a clear message.
  • commit-msg receives the message file path; pre-push receives refs on stdin; both can enforce team rules.
  • Keep hooks in a tracked folder and set core.hooksPath through an install script, because neither .git/hooks nor Git settings are cloned.
  • Client-side hooks can be skipped (--no-verify), so repeat the important checks in CI and on the server.
  • Treat hooks as code: write tests for them, make the tests fail on purpose once, and run them in CI.

Next: Git Cheat Sheet