Skip to content

Instantly share code, notes, and snippets.

@divinity76
Created July 20, 2020 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divinity76/2fee2b158517476b0009fa60fbf4dc96 to your computer and use it in GitHub Desktop.
Save divinity76/2fee2b158517476b0009fa60fbf4dc96 to your computer and use it in GitHub Desktop.
newline fixer
<?php
declare(strict_types = 1);
function replaceRecursive(string $dir, array $replaces, array $ext_whitelist = [], array $ext_blacklist = [], array $name_blacklist = [], bool $onlytext = false): void
{
$dir = rtrim($dir, DIRECTORY_SEPARATOR);
$files = glob($dir . DIRECTORY_SEPARATOR . '*');
foreach ($files as $file) {
if (in_array(strtolower(basename($file)), $name_blacklist, true)) {
continue;
}
if (is_dir($file)) {
replaceRecursive($file, $replaces, $ext_whitelist, $ext_blacklist, $name_blacklist, $onlytext);
continue;
}
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $ext_blacklist, true) || (! empty($ext_whitelist) && ! in_array($ext, $ext_whitelist, true))) {
continue;
}
if ($onlytext) {
$isText = shell_exec("file --brief " . escapeshellarg(realpath($file)));
$isText = (false !== stripos($isText, "text"));
if (! $isText) {
continue;
}
}
$original = file_get_contents($file);
$replaced = strtr($original, $replaces);
if ($original !== $replaced) {
var_dump($file);
file_put_contents($file, $replaced, LOCK_EX);
}
}
}
replaceRecursive("dir",["\r\n"=>"\n"],[],[],[".git"],true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment