AZ-401: Git Hooks for Fast Local Code Feedback
Use a local Git hook to reject a small, reproducible problem close to the developer's work, then keep required merge validation on the repository platform. This procedure installs one reviewable pre-commit whitespace check in a disposable repository, verifies accepted and rejected staged changes, and restores any previous hook. Confirm the effective hook location and runtime before installation; do not assume that every checkout uses its own hooks directory.
A local pre-commit hook can be missing or bypassed. Its result therefore provides developer feedback, while Azure Repos branch policies or GitHub branch protection must separately enforce the required merge conditions. The example below describes expected observations rather than a completed lab: no hook was installed or executed for this article.
Choose a check with a precise local purpose
The chosen event is pre-commit. Git invokes it before creating the commit; it receives no arguments, and a nonzero exit aborts the commit attempt. Git's default sample includes whitespace checking. The illustrative hook below keeps that bounded mechanism and makes its exit handling explicit.
Whitespace checking is useful because the developer can usually correct the reported line immediately. It does not establish that code compiles, tests pass, secrets are absent or a change is safe. Choose a hook for feedback that is quick enough to use routinely and whose failure message identifies a practical next action.
The distinction between the working tree and index matters. The index contains the staged change intended for a commit. This example checks that staged change against HEAD, or against the empty tree for an initial commit. An unstaged correction does not repair a staged error; the corrected content must be staged again.
If a team needs a formatter, linter or test command instead, define its input and runtime contract before substituting it. A command that inspects the whole working tree answers a different question from one that inspects the staged snapshot. Avoid quietly changing that contract while retaining the same reassuring hook name.
Establish the location and preserve existing behavior
Use an ordinary, non-bare disposable repository with an approved Portable Operating System Interface (POSIX)-compatible shell and Git available to the hook. Check the installed Git version and the actual interpreter used by that Git installation. This shell example is not a PowerShell script; Windows users must verify the installed Git environment, line endings and executable handling before relying on it.
Git normally uses the hooks directory under its repository metadata directory, but the core.hooksPath configuration variable can select another location. Inspect the effective setting and its configuration scope before choosing a destination. In a straightforward repository without an override, the usual directory is .git/hooks. For this disposable exercise, confirm the effective hook directory and its ownership before writing any file. Consult Branch Strategies and Git Worktree Boundaries separately for linked-worktree mechanics.
Record the following before editing:
- The disposable repository's actual root and effective hooks directory.
- Whether core.hooksPath is unset or configured, and which scope supplies it.
- Whether an active pre-commit file already exists, including its contents and executable permissions.
- The approved backup location and the person responsible for restoration.
- The interpreter and Git commands required by the reviewed hook.
If the effective directory is shared or outside the exercise's owned scope, stop and arrange a separate disposable setup. Do not redirect a global hooks setting or overwrite an organization's managed hook merely to complete this example.
Preserve an existing hook byte-for-byte with its permissions before replacing it. Keep that backup outside the active hook filename, in an owned location. If there was no previous hook, record that absence. These two starting states require different cleanup actions.
Create the reviewable pre-commit file
Create a file named pre-commit in the confirmed effective hooks directory. Review the entire file before making it executable. The code is an illustrative adaptation of the whitespace-checking mechanism in Git's shipped sample, not a claim that every installed sample has identical contents:
#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
against=$(git hash-object -t tree /dev/null) || exit 2
fi
git diff-index --check --cached "$against" --
check_status=$?
if [ "$check_status" -ne 0 ]
then
printf '%s\n' 'Local whitespace check failed; inspect the diagnostics.' >&2
fi
exit "$check_status"
The initial branch selects the comparison tree. The check then inspects the cached, staged change. Its captured exit status becomes the hook's exit status; a failure cannot be hidden by the later diagnostic message. If creating the initial comparison value fails, the hook stops with a nonzero result rather than continuing with an invalid input.
Review the installed sample and the installed Git command behavior when adapting this file. The shipped default also contains other policy, including a filename check; this narrower example does not reproduce that entire sample or silently adopt all of its rules.
Save the file with line endings and an interpreter declaration that the chosen environment can execute. Enable its executable permission using that environment's file-permission mechanism. Git ignores hooks that are not executable, so a successful commit with an inactive file would not demonstrate that the check ran.
Do not add unrelated actions such as fetching remote data, changing branches, retrieving credentials or rewriting files. This hook reports a condition and returns a status. Any automatic correction would need its own reviewed behavior and preservation rules.
Verify accepted and rejected disposable changes
Use the ordinary commit path so Git invokes the hook. Do not use a bypass option during verification. Make the exercise's changes in the disposable repository only, without pushing them.
Start with a simple text file such as hook-check.txt. Confirm that the installed Git whitespace policy treats the chosen trailing-space fixture as an error; if the team's policy differs, choose an explicitly documented failing fixture instead of changing global settings.
Follow this sequence:
- Create a clean line, stage the file, and attempt an ordinary commit. Inspect whether the hook actually ran and record the commit result.
- Add a new line with deliberate trailing spaces, stage the change, and attempt another commit. The expected result is a nonzero check and no new commit from that attempt.
- Correct the line only in the working tree, leaving the staged bad version untouched. Attempt the commit again. The staged check should still reject the staged error.
- Stage the correction and retry. The expected result is acceptance of the corrected staged snapshot, subject to other applicable hooks or commit requirements.
Record actual results rather than copying the expected column:
| Case | Expected observation | What it establishes |
|---|---|---|
| Clean staged change | Hook check succeeds; ordinary commit can proceed | The accepted path is usable |
| Staged whitespace error | Diagnostics and nonzero result; commit attempt aborts | The chosen failing case is detected |
| Working-tree fix without restaging | Staged error remains rejected | The check examines the intended staged input |
| Corrected staged change | Check succeeds after restaging | The developer has a reproducible repair path |
For each case, retain the installed hook identity, staged content, diagnostic text, command result and commit state. A commit that fails because the author identity is missing or signing cannot complete is not evidence that the whitespace hook rejected it. Similarly, a commit that succeeds without the hook running is not evidence that its checker accepted the change.
The example has not produced those observations here. If the reader's actual result differs, preserve the discrepancy and diagnose it before expanding the hook.
Diagnose invocation, runtime and check failures separately
When a bad fixture is accepted, first confirm the active hook filename, effective location and executable permission. Check whether the client used the ordinary commit path or bypassed the hook. Inspect the staged content rather than assuming it matches the editor.
When the hook runs but fails unexpectedly, distinguish a quality finding from an environment failure. A missing shell, unavailable Git command or invalid comparison input is an operational problem. Repair the approved runtime or installation; do not turn a checker error into success merely to unblock commits.
If the same hook behaves differently between a terminal and an integrated development environment (IDE), compare their actual execution environments and inputs. The useful question is which command, interpreter and staged snapshot each used. Avoid assuming that a developer's interactive shell setup is present in every client.
Keep the check bounded. Slow or unpredictable local operations encourage developers to avoid the feedback path, and a hook that modifies unrelated files complicates both diagnosis and restoration. These are engineering reasons to separate fast local checks from broader build validation.
Preserve server merge controls and review generated hooks
Git explicitly permits bypassing pre-commit with its no-verify option. A developer can also lack the hook entirely. Do not interpret local success as proof that every contributor, automation account or checkout ran the same program.
Azure Repos branch policies can require reviews, build validation and status checks. Their configuration needs the relevant administrative or policy-edit permission, and a ready build or status-producing integration is a prerequisite for those respective controls. GitHub.com branch protection has plan and repository-visibility conditions; administrator or permitted-role bypass also needs examination.
Those platform controls require separate configuration and actor-based verification. This article does not install them or claim that a local hook creates them automatically. Pull Request Enforcement for Human and Copilot Changes covers that distinct outcome.
If artificial intelligence (AI) assistance such as GitHub Copilot drafts the hook, inspect its commands and dependencies before installation. Agentic surfaces have different permissions and execution environments. A generated statement that tests passed does not replace actual invocation, accepted/rejected fixtures and human review of the result.
Restore the prior hook and clean up safely
Before removing the test hook, verify that its current bytes are still the version installed for this exercise. If another owner changed it, stop and reconcile the change; do not overwrite their work with an old backup.
If a prior hook existed, restore its exact contents and executable permissions. If none existed, remove only this exercise's active pre-commit file. Leave sample files, other hooks and unrelated configuration intact. This procedure did not require changing core.hooksPath, so there is no reason to alter its setting during cleanup.
Confirm the effective location again and inspect the restored state. Retain the verification record and backup according to the owner's policy, then remove only owned disposable test content when it is no longer needed. Do not use broad repository cleanup or delete a shared hooks directory.
The resulting handoff should identify the installed check, observed good and bad cases, any unresolved runtime issue, and the restored hook state. That record explains the local feedback achieved while leaving merge enforcement with the repository's actual server controls.
Authoritative Sources
- Git hooks manual — hook locations, executable behavior, working directory, pre-commit contract, default checks and bypass.
- Set and manage branch policies — Azure Repos merge requirements and policy prerequisites.
- About protected branches — GitHub eligibility, requirements and bypass conditions.
- GitHub Copilot Agents application card — surface-specific limitations, review and responsible adoption.

