Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ The hook automatically stages the updated README.md if changes are detected, ens

### Syncing Source Code

To sync a code example with a source file, add a comment before your code block:
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:

````markdown
<!-- source: examples/demo.php -->
Expand All @@ -47,6 +47,8 @@ To sync a code example with a source file, add a comment before your code block:
```
````

The hook supports a wide range of file extensions including `.php`, `.graphql`, `.gql`, `.js`, `.ts`, `.json`, `.yml`, `.yaml`, `.sql`, and many more.

### Syncing Output (Optional)

To show the output of executing a PHP file, use:
Expand Down
40 changes: 38 additions & 2 deletions src/SyncReadmeExamples.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ private function syncReadmeWithExamples(string $readme, string $repositoryRoot,
// Check for source comment
if (preg_match('/^<!-- source: (.+) -->$/', trim($line), $matches)) {
$sourceFile = $matches[1];
$language = $this->getLanguageFromExtension($sourceFile);
$result[] = $line; // Keep the source comment
++$i;

// Process the code block
if ($i < count($lines) && preg_match('/^```php\s*$/', $lines[$i])) {
$result[] = $lines[$i]; // Keep ```php
if ($i < count($lines) && preg_match('/^```\w*\s*$/', $lines[$i])) {
$result[] = '```' . $language; // Use inferred language
++$i;

// Skip old code content until closing ```
Expand Down Expand Up @@ -262,4 +263,39 @@ private function normalizeOutput(string $output) : string

return implode("\n", $lines);
}

/**
* Infer the language identifier from file extension
*/
private function getLanguageFromExtension(string $filePath) : string
{
$extension = pathinfo($filePath, PATHINFO_EXTENSION);

return match ($extension) {
'php' => 'php',
'graphql', 'gql' => 'graphql',
'js', 'mjs', 'cjs' => 'javascript',
'ts', 'mts', 'cts' => 'typescript',
'json' => 'json',
'yml', 'yaml' => 'yaml',
'xml' => 'xml',
'sql' => 'sql',
'sh', 'bash' => 'bash',
'py' => 'python',
'rb' => 'ruby',
'go' => 'go',
'rs' => 'rust',
'java' => 'java',
'c' => 'c',
'cpp', 'cc', 'cxx' => 'cpp',
'cs' => 'csharp',
'swift' => 'swift',
'kt', 'kts' => 'kotlin',
'md', 'markdown' => 'markdown',
'html', 'htm' => 'html',
'css' => 'css',
'scss', 'sass' => 'scss',
default => '',
};
}
}