A PHP script that automatically syncs code examples in your README.md with actual source files. This ensures your documentation always shows up-to-date, working code examples.
composer require --dev ruudk/readme-examples-sync-hookRun the script from your project root:
vendor/bin/readme-examples-syncThe easiest way to automatically sync your README on commit is using Lefthook:
-
Install Lefthook (if not already installed):
# macOS brew install lefthook -
Create a
lefthook.ymlfile in your project root:pre-commit: parallel: false commands: sync-readme-examples: glob: - "*.php" - "*.md" run: vendor/bin/readme-examples-sync stage_fixed: true
-
Install the hooks:
lefthook install
That's it! Now your README will automatically sync whenever you commit changes to PHP or Markdown files.
If you prefer not to use Lefthook, you can manually create a .git/hooks/pre-commit file:
#!/bin/bash
vendor/bin/readme-examples-syncDon't forget to make the hook executable:
chmod +x .git/hooks/pre-commitThis script scans your README.md file for special HTML comments that mark code examples:
- Source code sync: Updates code blocks marked with
<!-- source: ... -->with the actual content from source files - Output sync (optional): When you add
<!-- output: ... -->comments, the script executes PHP files and captures their output to display results
The script automatically stages the updated README.md if changes are detected (when run in a git repository), ensuring your documentation stays in sync with your code.
To sync a code example with a source file, add a comment before your code block. The language identifier (e.g., php, graphql, javascript) is automatically inferred from the file extension:
<!-- source: examples/demo.php -->
```php
// This code will be replaced with content from examples/demo.php
```The hook supports a wide range of file extensions including .php, .graphql, .gql, .js, .ts, .json, .yml, .yaml, .sql, and many more.
To show the output of executing a PHP file, use:
<!-- output: examples/demo.php -->
```php
// This will be replaced with the output from executing examples/demo.php
```Here's how it looks in practice: ruudk/code-generator.
Love this tool? Help me keep building awesome open source software!
Your sponsorship helps me dedicate more time to maintaining and improving this project. Every contribution, no matter the size, makes a difference!
I welcome contributions! Whether it's a bug fix, new feature, or documentation improvement, I'd love to see your PRs.
MIT License – Free to use in your projects! If you're using this and finding value, please consider sponsoring to support continued development.