Skip to content

Instantly share code, notes, and snippets.

@wouterj

wouterj/fix.php Secret

Forked from jderusse/fix.php
Last active February 20, 2021 12:54
Show Gist options
  • Save wouterj/6bf693f097ed523a51e9ca6e7dc98c11 to your computer and use it in GitHub Desktop.
Save wouterj/6bf693f097ed523a51e9ca6e7dc98c11 to your computer and use it in GitHub Desktop.
<?php
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath(__DIR__.'/..')));
$reg = new RegexIterator($dir, '/\.rst$/i', RecursiveRegexIterator::GET_MATCH);
foreach ($reg as $file => $opts) {
$content = file_get_contents($file);
if (strpos($content, '.. code-block:: diff') === false) {
continue;
}
$newContent = [];
$inDiff = false;
$inDiffPatched = false;
$indentSize = 0;
foreach (explode("\n", $content) as $line) {
if ($inDiff) {
if ($line === '') {
$newContent[] = $line;
continue;
}
if (!$inDiffPatched) {
$newContent[] = $line;
$inDiffPatched = true;
continue;
}
if (substr($line, 0, $indentSize) === str_repeat(' ', $indentSize)) {
if ($line[$indentSize] === '+' || $line[$indentSize] === '-') {
if (' ' !== ($line[$indentSize+1] ?? ' ')) {
throw new \Exception(sprintf('Bad line indent in %s for %s', $file, $line));
}
$newContent[] = $line;
} else {
$newContent[] = ' '.$line;
}
continue;
}
$inDiff = false;
$inDiffPatched = false;
}
$newContent[] = $line;
if (false === $pos = strpos($line, '.. code-block:: diff')) {
continue;
}
$inDiff = true;
$indentSize = $pos + 4;
}
file_put_contents($file, implode("\n", $newContent));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment