Skip to content

Instantly share code, notes, and snippets.

@xorik
Created December 30, 2021 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xorik/8d8e69482976d579baa90b8116f7a9ca to your computer and use it in GitHub Desktop.
Save xorik/8d8e69482976d579baa90b8116f7a9ca to your computer and use it in GitHub Desktop.
Restore empty lines after rector
<?php
declare(strict_types=1);
exec('git diff', $diff);
$currentFile = $chunkStart = null;
$fileChanged = false;
$chunkOffset = 0;
$fileLines = [];
foreach ($diff as $line) {
if (str_starts_with($line, '---')) {
if ($fileChanged) {
updateFile($currentFile, $fileLines);
}
$currentFile = str_replace('--- a/', '', $line);
$fileLines = explode("\n", file_get_contents($currentFile));
$fileChanged = false;
continue;
}
if (str_starts_with($line, '@@')) {
preg_match('/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/', $line, $matches);
$chunkStart = (int) $matches[3];
$chunkOffset = 0;
continue;
}
if (str_starts_with($line, '-')) {
// Empty line removed
if ($line === '-') {
array_splice($fileLines, $chunkStart + $chunkOffset - 1, 0, '');
++$chunkOffset;
$fileChanged = true;
}
} else {
++$chunkOffset;
continue;
}
}
if ($fileChanged) {
updateFile($currentFile, $fileLines);
}
function updateFile($file, $lines): void
{
file_put_contents($file, implode("\n", $lines));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment