mdbook-validator
An mdBook preprocessor that validates code examples against live Docker containers during documentation builds. Catch documentation drift before it reaches your users.
The Problem
Documentation code examples rot:
- SQL queries reference tables that were renamed
- Config files have typos that were never tested
- Examples break when the tool updates
- Code runs but produces wrong output
You only find out when a user complains.
The Solution
mdbook-validator validates your code examples against real tools during mdbook build. If an example doesn't work, your build fails—just like a broken test.
Key insight: Documentation examples often need setup code (CREATE TABLE, test data) or surrounding context (full config file) that readers don't need to see. This tool lets you include that context for validation while showing only the relevant portion to readers.
Features
- Container-based validation - Run examples against real tools (osquery, SQLite, etc.)
- Hidden setup blocks - Include setup code that's validated but not shown to readers
- Hidden context lines - Show partial configs while validating complete ones
- Output assertions - Verify row counts, check for specific content
- Expected output matching - Regression testing for deterministic queries
- Clean output - All validation markers stripped from rendered documentation
Installation
# From crates.io (once published)
# From source
Requirements:
- Docker running (containers provide validation environments)
jqinstalled on host (used by validator scripts for JSON parsing)
Quick Start
- Add to your
book.toml:
[]
= "mdbook-validator"
[]
= "keinos/sqlite3:3.47.2"
= "validators/validate-sqlite.sh"
- Write validated examples in your markdown:
```sql validator=sqlite
SELECT name FROM users WHERE id = 1;
```
- Build your book:
Reader sees:
SELECT name FROM users WHERE id = 1;
Validator tests: Complete query with setup and assertions.
Markers
Block Markers
| Marker | Purpose |
|---|---|
<!--SETUP--> |
Shell command(s) run in container before the query (e.g., sqlite3 /tmp/test.db "CREATE TABLE...") |
<!--ASSERT--> |
Output validation rules |
<!--EXPECT--> |
Exact output matching (JSON) |
Line Prefix: @@
Lines starting with @@ are sent to the validator but hidden from readers. Use this to show only relevant portions of a config while validating the complete file.
```toml validator=config-check
@@base_path = "/var/data"
@@log_level = "info"
@@
[feature]
enabled = true
max_items = 100
@@
@@[advanced]
@@timeout_secs = 30
```
Reader sees:
[]
= true
= 100
Validator receives: Complete, valid config.
Examples
SQLite with Setup
```sql validator=sqlite
SELECT status, COUNT(*) as count FROM orders GROUP BY status;
```
osquery (validates against real system)
```sql validator=osquery
SELECT uid, username FROM users WHERE username = 'root'
```
osquery Config (JSON)
```json validator=osquery-config
{
"options": {
},
"schedule": {
}
}
```
Expected Output (Regression Testing)
```sql validator=sqlite
SELECT COUNT(*) as total FROM test
```
Bash Script Execution
Validate bash scripts run correctly and produce expected results:
```bash validator=bash-exec
echo "Hello from bash"
exit 0
```
Scripts must exit 0 by default. Use exit_code assertion for non-zero:
```bash validator=bash-exec
exit 42
```
Check file creation and content:
```bash validator=bash-exec
mkdir -p /tmp/myapp
echo "config=value" > /tmp/myapp/settings.conf
```
Skip Validation
```sql validator=sqlite skip
-- This intentionally broken example shows what NOT to do
SELECT * FROM nonexistent_table;
```
Assertions
SQL Validators (osquery, sqlite)
| Assertion | Example | Description |
|---|---|---|
rows = N |
rows = 5 |
Exact row count |
rows >= N |
rows >= 1 |
Minimum row count |
contains "str" |
contains "alice" |
Output contains string |
matches "regex" |
matches "user.*" |
Regex pattern match |
Bash Execution (bash-exec)
| Assertion | Example | Description |
|---|---|---|
exit_code = N |
exit_code = 0 |
Script must exit with code N (default: 0) |
stdout_contains "str" |
stdout_contains "success" |
Stdout must contain string |
file_exists /path |
file_exists /tmp/config |
File must exist after script |
dir_exists /path |
dir_exists /tmp/mydir |
Directory must exist after script |
file_contains /path "str" |
file_contains /tmp/cfg "key=val" |
File must contain string |
Configuration
[]
= "My Documentation"
[]
= "mdbook-validator"
= true # Stop on first failure (default: true)
# SQLite validator
[]
= "keinos/sqlite3:3.47.2"
= "validators/validate-sqlite.sh"
# osquery SQL validator
[]
= "osquery/osquery:5.17.0-ubuntu22.04"
= "validators/validate-osquery.sh"
# osquery config validator (JSON, not TOML!)
[]
= "osquery/osquery:5.17.0-ubuntu22.04"
= "validators/validate-osquery-config.sh"
# ShellCheck static analysis
[]
= "koalaman/shellcheck-alpine:stable"
= "validators/validate-shellcheck.sh"
# Bash execution with assertions
[]
= "ubuntu:22.04"
= "validators/validate-bash-exec.sh"
# Python syntax validation
[]
= "python:3.12-slim"
= "validators/validate-python.sh"
Custom Docker Images
You can use locally-built or private registry images without pushing to a public registry.
Local Images
Build once, reference by name:
# Build your custom validator image
[]
= "my-validator:latest" # Local image, no registry needed
= "validators/validate-custom.sh"
testcontainers-rs uses local images if they exist, no pulling required.
Private Registry
For team sharing:
[]
= "registry.mycompany.com/my-validator:latest"
= "validators/validate-custom.sh"
Docker uses your logged-in credentials (docker login).
Example: pyproject.toml Validator
validators/pyproject/Dockerfile:
FROM python:3.12-slim-bookworm
RUN pip install --no-cache-dir 'validate-pyproject[all]' jq
COPY validate.sh /validate.sh
RUN chmod +x /validate.sh
validators/pyproject/validate.sh:
#!/bin/bash
INPUT=
CONTENT=
TMPFILE=
Build and use:
[]
= "pyproject-validator:latest"
= "validators/validate-custom.sh"
Writing Custom Validators
Validators are shell scripts that run on the host (not in containers). They receive:
- stdin: JSON output from the container execution (e.g.,
[{"id": 1, "name": "test"}]) - VALIDATOR_ASSERTIONS env var: Assertion rules, newline-separated
- VALIDATOR_EXPECT env var: Expected output for exact matching (optional)
- CONTAINER_STDERR env var: stderr from container execution (for warning detection)
The preprocessor handles SETUP and query execution in the container—validators only validate the output.
Exit 0 for success, non-zero for failure. Write errors to stderr.
Example validator:
#!/bin/bash
# Read JSON output from container (stdin)
JSON_OUTPUT=
# Validate JSON is parseable
| || {
}
# Check assertions if provided
if [; then
ROW_COUNT=
# Example: check "rows >= N"
if ; then
expected=
if [; then
fi
fi
fi
# Check expected output if provided
if [; then
actual=
expected=
if [; then
fi
fi
See validators/validate-template.sh for a comprehensive template with all assertion patterns.
Known Limitations
- Container startup overhead - First validation takes 10-20 seconds per validator type
- No container reuse between builds - Each
mdbook buildstarts fresh containers - Marker collision - If your code contains
-->, it may break marker parsing - No line numbers in errors - Error messages show file but not exact line
How It Works
- mdBook calls the preprocessor with chapter content
- Preprocessor finds code blocks with
validator=attribute - Extracts markers (
<!--SETUP-->,<!--ASSERT-->,<!--EXPECT-->) and@@lines - Starts the specified container via testcontainers
- Runs SETUP shell command in container (if any)
- Runs the visible content via
exec_commandin container → captures JSON output - Runs validator script on HOST with JSON output as stdin, assertions/expect as env vars
- On success: strips all markers, returns clean content to mdBook
- On failure: exits with error, build fails
License
Apache2
Contributing
Contributions welcome! Please open an issue to discuss before submitting large changes.