diff --git a/README.md b/README.md index d231aee..1bd3617 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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: diff --git a/src/SyncReadmeExamples.php b/src/SyncReadmeExamples.php index 9a68546..c8ea0ef 100644 --- a/src/SyncReadmeExamples.php +++ b/src/SyncReadmeExamples.php @@ -62,12 +62,13 @@ private function syncReadmeWithExamples(string $readme, string $repositoryRoot, // Check for source comment if (preg_match('/^$/', 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 ``` @@ -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 => '', + }; + } }