On this page
The short answerWhat pre-commit runsCreate a small project and hookDemonstrate a missed code-only changeRun the project-wide check on commitsAccount for bypasses and local setupAdd a fuller scanChoose settings deliberatelyTriage failures and skipped workWhat belongs in the hook and what belongs in CILayer local and CI checksThe sources we checkedFAQThe short answer
Use a fast local hook for immediate feedback, run the same hooks across all files in CI, and run fuller documentation checks in CI or on a schedule. By default, pre-commit selects staged files, so a hook restricted to Markdown can miss an API-only change that breaks examples. In engine 0.6.3, DocsAlive is not a pre-commit hook and does not read .pre-commit-config.yaml. For this project it scans docs/ plus the root README, runs Python and pycon examples, parses JSON, and does not parse YAML.
The example below builds a small local check for Python syntax, short doctest sessions and JSON. It demonstrates the missed code-only change, then changes the hook so the script chooses its documentation files on every commit. The package acme-version is illustrative and is not a published package.
What pre-commit runs
After installation, pre-commit places hook scripts in the repository’s Git hooks directory. By default, a run selects staged files. A hook’s files pattern and type filters narrow the files it receives; exclude, types_or and exclude_types can further change selection. A hook reports a problem by exiting nonzero or by modifying files; a check that only prints a warning and exits zero passes.
A repo: local hook can invoke a script in your own repository. always_run: true runs it even when no files match, and pass_filenames: false prevents pre-commit from appending selected file names. Together those settings let a project-wide documentation check choose its own inputs even when a commit changes only implementation code.
The unsupported language name is used from pre-commit 4.4.0 onward for what was formerly called system. This kind of hook receives no virtual environment from pre-commit: developers must install its dependencies themselves. The old name still worked in the verified pre-commit 4.7.0 run, but its alias is intended for removal in a future version.
pre-commit run --all-files runs hooks against all files and is useful in CI. The --from-ref and --to-ref options instead select files changed between two references. Hooks can be confined to stages such as pre-commit or pre-push, and the corresponding hook type must be installed for that stage. --show-diff-on-failure can help show modifications made by a hook.
Create a small project and hook
The setup below is illustrative. It creates an environment, installs pre-commit and the local project, and installs the Git hook. Each clone needs its own hook installation.
python3 -m venv .venv
. .venv/bin/activate
pip install pre-commit
pip install -e .
pre-commit install
The install reports the location of the Git hook:
pre-commit installed at .git/hooks/pre-commit
The illustrative package configuration makes acme installable in the local environment.
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "acme-version"
version = "1.0.0"
requires-python = ">=3.10"
[tool.setuptools]
packages = ["acme"]
The implementation parses a version string. The project also exposes the function from its package so the examples can import it.
def parse_version(text):
"""Return the three numbers in a version string such as "2.4.1"."""
parts = [int(p) for p in text.strip().split(".")]
if len(parts) != 3:
raise ValueError(f"not a version: {text}")
return tuple(parts)
The illustrative documentation contains a Python fence, a pycon session and a JSON fence. They need different checks: compilation can find Python syntax errors, a doctest can execute the prompted session, and a JSON parser can check the JSON text.
# Usage
Parse a version string:
```python
from acme import parse_version
major, minor, patch = parse_version("2.4.1")
print(minor)
```
The same call in a session:
```pycon
>>> from acme import parse_version
>>> parse_version("2.4.1")
(2, 4, 1)
```
The settings file the CLI reads:
```json
{"strict": true, "parts": 3}
```
The following local script makes those checks. With no file names, it selects Markdown under docs/ and the root README. Python fences are compiled only; pycon sessions run with the locally installed Python and packages. The script is a compact starting point for this example, not a general Markdown parser.
"""Fast checks for code blocks in Markdown files, for a pre-commit hook.
python fences are compiled (syntax only), json fences are parsed, and pycon
sessions are run with doctest, so the package must be importable.
With no file names it checks docs/ and README.md.
"""
import doctest
import json
import re
import sys
from pathlib import Path
FENCE = re.compile(r"^```(\w*)[^\n]*\n(.*?)^```\s*$", re.M | re.S)
def check(path):
text = path.read_text(encoding="utf-8")
errors = 0
for m in FENCE.finditer(text):
lang, code = m.group(1).lower(), m.group(2)
line = text.count("\n", 0, m.start()) + 1
try:
if lang in ("python", "py"):
compile(code, f"{path}:{line}", "exec")
elif lang == "json":
json.loads(code)
elif lang == "pycon":
test = doctest.DocTestParser().get_doctest(code, {}, str(path), str(path), line)
runner = doctest.DocTestRunner(optionflags=doctest.ELLIPSIS)
runner.run(test, out=sys.stderr.write)
if runner.failures:
raise ValueError("doctest failed")
else:
continue
except (SyntaxError, ValueError) as exc:
print(f"{path}:{line}: {lang}: {exc}")
errors += 1
return errors
files = [Path(f) for f in sys.argv[1:]] or [*Path("docs").rglob("*.md"), Path("README.md")]
sys.exit(1 if sum(check(f) for f in files if f.exists()) else 0)
The first hook configuration selects staged Markdown files. It is intentionally narrow so the next test can show what happens when only code changes.
repos:
- repo: local
hooks:
- id: doc-blocks
name: check code blocks in Markdown
entry: python3 tools/check_doc_blocks.py
language: unsupported
files: \.md$
Demonstrate a missed code-only change
The next commands are broken on purpose in the verified project: the function had been renamed in the implementation and package export, but the documentation still used the old name. Only the implementation files were staged.
git add acme
git commit -m "rename parse_version to parse"
No staged file matched the Markdown pattern, so the hook was skipped and the commit went through:
check code blocks in Markdown........................(no files to check)Skipped
This is a selection failure, not evidence that the documentation remains correct. An API change can invalidate examples without touching a documentation page. Conversely, a Markdown-only check can be useful for a fast formatting or syntax task when its limited trigger is understood.
Run the hooks across all files to expose this particular stale import:
pre-commit run --all-files
The verified run exited with status 1. Between the hook header and the last line, the doctest report showed the failed import of parse_version; that report is left out here, and the rest of the result was:
check code blocks in Markdown............................................Failed
- hook id: doc-blocks
- exit code: 1
docs/usage.md:14: pycon: doctest failed
The Python fence alone would not have caught the rename: this script compiles that fence but does not execute its import. The pycon session runs, so its import exposed the stale name. Python doctest finds examples from prompts, and expected output ends at the first blank line or next prompt. Keep sessions short and deterministic enough for a fast local check.
Run the project-wide check on commits
The verified adjustment removes the Markdown-only selection and lets the script choose its own files. With this configuration, the same rename commit was refused because the pycon session failed.
language: unsupported
- files: \.md$
+ always_run: true
+ pass_filenames: false
This increases the work performed on each commit, so keep the local check fast and offline. It is appropriate when changes anywhere in the package can affect the selected examples. It does not make the script comprehensive: the script’s own file discovery and supported fence types still define its coverage.
A malformed JSON fence also caused the verified hook to refuse a commit. This example message came from adding a trailing comma:
docs/usage.md:22: json: Illegal trailing comma before end of object: line 1 column 28 (char 27)
Parsing confirms that the text is accepted as JSON by the parser in use. It does not prove that the settings are valid for a particular application or schema. Keep application-specific validation separate where those guarantees matter.
Account for bypasses and local setup
Both commands below allowed the intentionally broken rename through in the verification. The first skips the named hook; the second bypasses Git’s pre-commit and commit-msg hooks.
SKIP=doc-blocks git commit -m "rename parse_version to parse"
git commit --no-verify -m "rename parse_version to parse"
A clone where pre-commit install was never run has a similar coverage gap. These mechanisms can be useful in exceptional situations, but they mean a local hook cannot be the only gate. Run the same hooks in CI with --all-files, where the job installs the needed dependencies and checks the full intended repository scope.
The script uses the Python and packages available locally because language: unsupported provides no environment. Install the package in each developer environment and in CI. A missing package may otherwise look like a documentation failure. A doctest that needs network access or credentials will fail locally; keep that work out of a fast offline hook or provide a separate appropriate check.
Add a fuller scan
The following command plans a scan; execution requires the CLI’s execution option. In the verified execution, the plain-project scope covered two pages and five blocks. With the package installed and network disabled, the README install block was skipped, while the Python, pycon and JSON checks passed. After the rename, the README Python block, usage Python block and pycon session all failed as API drift.
docsalive scan .
That result includes a Python fence the local script only compiled. The two layers answer different questions: compilation checks syntax quickly, while running an example can expose a stale import. In the engine, printed output is compared only for Python pycon or python-repl sessions. JSON is parsed; YAML is not parsed, even though a YAML block can receive a passing status with a detail saying the parser was skipped. Use a YAML parser or linter in your own CI for those blocks.
The sample hook script has a narrow scope. It understands python or py, pycon and json fences, and only backtick fences at the start of a line. It does not understand tabs, includes or MDX. It does not check YAML or shell blocks. Its Python fences are compiled, not run. Its pycon sessions use whatever Python and packages are installed locally. Treat each of those as a coverage boundary when choosing additional checks.
Choose settings deliberately
| pre-commit setting | What it does | Effect on docs checks |
|---|---|---|
files |
Filters matching file paths | A Markdown pattern can skip a code-only change |
types, types_or, exclude_types |
Filter by identified file types | Can narrow or exclude inputs independently of the path pattern |
always_run |
Runs even when no files match | Lets a project-wide check respond to code-only commits |
pass_filenames |
Controls whether selected names are passed | When false, the script must choose its own inputs |
repo: local |
Defines a hook from the local repository | Can invoke the project’s documentation-check script |
language: unsupported |
Runs without a pre-commit-managed environment | Python and packages must already be installed |
stages |
Restricts the hook to selected hook stages | Requires the relevant hook type to be installed |
fail_fast and require_serial |
Control failure handling and serial execution | Can affect feedback order and concurrency for checks |
The default files pattern is empty, the default exclude pattern matches nothing, types defaults to files, always_run defaults to false and pass_filenames defaults to true. Review the complete configuration rather than assuming one pattern is the only filter. pre-commit autoupdate updates revisions for configured hooks; review resulting changes and rerun checks.
Triage failures and skipped work
| Finding | Likely cause | What to do |
|---|---|---|
| Hook says no files to check | Staged paths do not match its filters | Decide whether code changes should trigger a project-wide check |
| Python fence compiles but an import is stale | Compilation did not execute the import | Run the example in a suitable environment |
| Doctest cannot import the package | The API changed or the local package is not installed | Check the intended API and the environment before changing the docs |
| JSON parsing fails | The block is not accepted by the parser | Correct the example and rerun the hook |
| CI fails after a local commit passed | Hook was skipped, absent, or saw a different file set or environment | Compare installation, filters, dependencies and the CI all-files run |
| YAML appears green in the engine | The parser was skipped | Run a YAML parser or linter separately |
| The scan skips a README install line | The network was off for that run | Install the package with a setup step, or run with the network on where that is acceptable |
Read skipped blocks with their reasons as well as failures. A skip is not a pass: it means that block was not checked in that run. A successful status for the checks that ran is useful evidence, but it is not evidence for material the tool did not check.
What belongs in the hook and what belongs in CI
A commit hook runs on a developer's machine, in the middle of their work, every time they commit. That shapes what belongs in it. The table below is advice drawn from the verified project, not a pre-commit rule.
| Check | Fast hook | CI on every change | CI on a schedule or release |
|---|---|---|---|
| Python syntax of fences | Yes, compile only | Yes, through the same hook | Not needed separately |
| JSON parsing of fences | Yes | Yes, through the same hook | Not needed separately |
| Short offline pycon sessions | Yes, if the package is installed locally | Yes | Yes |
| Running every example in a clean environment | No | Yes, with a docs scan | Yes, to catch drift in dependencies |
| Examples that need network or credentials | No | Only where the job has safe test access | Where the job has safe test access |
| YAML and application-specific config | Only a fast parser if one is installed | Yes, with a parser or schema check | Yes |
The deciding question for each row is cost and determinism. A hook that takes a long time, needs the network or fails because of something outside the change encourages people to reach for SKIP or --no-verify, which removes the check entirely. A short, reliable hook is more likely to stay installed and enabled.
The --from-ref and --to-ref options are another useful tool in CI. Running the hooks over the files changed between the base branch and the pull request keeps a large repository's job short. For a project-wide documentation check configured with always_run: true and pass_filenames: false, the script still chooses its own files, so the run covers every page it is written to read regardless of which files changed.
Layer local and CI checks
Use a fast hook for syntax, JSON parsing and short offline pycon sessions. When implementation changes can break documentation, configure the hook to run without relying solely on staged Markdown paths. Run the same hooks in CI with pre-commit run --all-files; that covers local bypasses and clones without an installed hook.
Add full example runs in CI or on a schedule for behavior that the fast hook does not exercise. Record setup and package versions so a failure can be reproduced. The guides for GitHub Actions and GitLab CI discuss the CI layer, while the docs testing checklist helps map broader coverage.
[ ] Install the Git hook in each working clone.
[ ] Install the package and hook dependencies in the local environment.
[ ] Check whether code-only commits trigger the docs hook.
[ ] Keep local syntax, JSON and pycon checks fast and offline.
[ ] Run the same hooks in CI against all files.
[ ] Run fuller example checks in CI or on a schedule.
[ ] Parse YAML separately and validate application-specific config.
[ ] Review skipped blocks and unsupported labels as coverage gaps.
[ ] Reproduce failures against the intended package version.
DocsAlive fits the fuller scan and triage layer. It is not itself the local hook shown here, and it does not interpret the pre-commit configuration. Use its findings alongside the hook and CI results to distinguish likely documentation bugs from context, environment and runner limits. See /docs/findings/ and /docs/cli/ for the report and run controls. Plans that include pull-request checks are on pricing; the health check runs the engine on up to 40 docs pages of a public repository you maintain and emails the report.
The sources we checked
These sources were read on November 15, 2026. Engine behavior was checked against engine 0.6.3 on the same day.
| Source | What it covers |
|---|---|
| pre-commit documentation | Hook selection, configuration, stages and commands |
| Git commit documentation | The --no-verify bypass |
| Python doctest documentation | Prompted examples and expected output |
FAQ
Why did a Markdown hook skip a broken API change?
By default pre-commit selects staged files. If only implementation files are staged, a hook filtered to Markdown has no matching files. A project-wide check can use always_run and choose its own inputs.
Is DocsAlive a pre-commit hook?
No. In engine 0.6.3 it does not read the pre-commit configuration. For this project it scans docs plus the root README, runs Python and pycon blocks, parses JSON and does not parse YAML.
Why run hooks in CI if developers have them locally?
A local hook can be skipped with SKIP or bypassed with Git's no-verify option, and a clone may never have installed it. Running the same hooks against all files in CI provides another check with a defined environment.
Does compiling a Python example verify its imports?
No. Compilation checks syntax without executing the import. Run the example or a suitable doctest to check whether the documented import works in the intended environment.
What does language unsupported provide?
It runs without a pre-commit-managed environment. The user or CI job must install Python and the packages the hook needs. The previous name was system.
Does a passing JSON check validate the application configuration?
Parsing checks the JSON text, not whether keys or values satisfy an application's schema. Add a schema or application-specific check when that guarantee is needed.




