|
| 1 | +<?php |
| 2 | + |
| 3 | +$readMeFilepath = __DIR__ . '/README.md'; |
| 4 | +$readMeFile = new SplFileObject($readMeFilepath); |
| 5 | +$readMeFile->setFlags(SplFileObject::DROP_NEW_LINE); |
| 6 | + |
| 7 | +$cliRedBackground = "\033[37;41m"; |
| 8 | +$cliReset = "\033[0m"; |
| 9 | +$exitStatus = 0; |
| 10 | + |
| 11 | +$indentationSteps = 3; |
| 12 | +$manIndex = 0; |
| 13 | +$linesWithSpaces = []; |
| 14 | +$tableOfContentsStarted = null; |
| 15 | +$currentTableOfContentsChapters = []; |
| 16 | +$chaptersFound = []; |
| 17 | +foreach ($readMeFile as $lineNumber => $line) { |
| 18 | + if (preg_match('/\s$/', $line)) { |
| 19 | + $linesWithSpaces[] = sprintf('%5s: %s', 1 + $lineNumber, $line); |
| 20 | + } |
| 21 | + if (preg_match('/^(?<depth>##+)\s(?<title>.+)/', $line, $matches)) { |
| 22 | + if (null === $tableOfContentsStarted) { |
| 23 | + $tableOfContentsStarted = true; |
| 24 | + continue; |
| 25 | + } |
| 26 | + $tableOfContentsStarted = false; |
| 27 | + |
| 28 | + $chaptersFound[] = sprintf('%s [%s](#%s)', |
| 29 | + strlen($matches['depth']) === 2 |
| 30 | + ? sprintf(' %s.', ++$manIndex) |
| 31 | + : ' *' |
| 32 | + , |
| 33 | + $matches['title'], |
| 34 | + preg_replace(['/ /', '/[^-\w]+/'], ['-', ''], strtolower($matches['title'])) |
| 35 | + ); |
| 36 | + } |
| 37 | + if ($tableOfContentsStarted === true && isset($line[0])) { |
| 38 | + $currentTableOfContentsChapters[] = $line; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +if (count($linesWithSpaces)) { |
| 43 | + fwrite(STDERR, sprintf("${cliRedBackground}The following lines end with a space character:${cliReset}\n%s\n\n", |
| 44 | + implode(PHP_EOL, $linesWithSpaces) |
| 45 | + )); |
| 46 | + $exitStatus = 1; |
| 47 | +} |
| 48 | + |
| 49 | +$currentTableOfContentsChaptersFilename = __DIR__ . '/current-chapters'; |
| 50 | +$chaptersFoundFilename = __DIR__ . '/chapters-found'; |
| 51 | + |
| 52 | +file_put_contents($currentTableOfContentsChaptersFilename, implode(PHP_EOL, $currentTableOfContentsChapters)); |
| 53 | +file_put_contents($chaptersFoundFilename, implode(PHP_EOL, $chaptersFound)); |
| 54 | + |
| 55 | +$tableOfContentsDiff = shell_exec(sprintf('diff --unified %s %s', |
| 56 | + escapeshellarg($currentTableOfContentsChaptersFilename), |
| 57 | + escapeshellarg($chaptersFoundFilename) |
| 58 | +)); |
| 59 | + |
| 60 | +@ unlink($currentTableOfContentsChaptersFilename); |
| 61 | +@ unlink($chaptersFoundFilename); |
| 62 | + |
| 63 | +if (!empty($tableOfContentsDiff)) { |
| 64 | + fwrite(STDERR, sprintf("${cliRedBackground}The table of contents is not aligned:${cliReset}\n%s\n\n", |
| 65 | + $tableOfContentsDiff |
| 66 | + )); |
| 67 | + $exitStatus = 1; |
| 68 | +} |
| 69 | + |
| 70 | +exit($exitStatus); |
0 commit comments