|
| 1 | +<?php |
| 2 | + |
| 3 | +$rootDir = __DIR__ . '/../..'; |
| 4 | +$it = new RecursiveIteratorIterator( |
| 5 | + new RecursiveDirectoryIterator($rootDir), |
| 6 | + RecursiveIteratorIterator::LEAVES_ONLY |
| 7 | +); |
| 8 | + |
| 9 | +$excludes = [ |
| 10 | + 'ext/bcmath/libbcmath/', |
| 11 | + 'ext/date/lib/', |
| 12 | + 'ext/fileinfo/data_file.c', |
| 13 | + 'ext/fileinfo/libmagic/', |
| 14 | + 'ext/gd/libgd/', |
| 15 | + 'ext/hash/sha3/', |
| 16 | + 'ext/hash/hash_whirlpool.c', |
| 17 | + 'ext/hash/php_hash_whirlpool_tables.h', |
| 18 | + 'ext/mbstring/libmbfl/', |
| 19 | + 'ext/mbstring/unicode_data.h', |
| 20 | + 'ext/pcre/pcre2lib/', |
| 21 | + 'ext/xmlrpc/libxmlrpc/', |
| 22 | + 'sapi/cli/php_http_parser.c', |
| 23 | + 'sapi/cli/php_http_parser.h', |
| 24 | + 'sapi/litespeed/', |
| 25 | +]; |
| 26 | + |
| 27 | +foreach ($it as $file) { |
| 28 | + if (!$file->isFile()) { |
| 29 | + continue; |
| 30 | + } |
| 31 | + |
| 32 | + $path = $file->getPathName(); |
| 33 | + foreach ($excludes as $exclude) { |
| 34 | + if (strpos($path, $exclude) !== false) { |
| 35 | + continue 2; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + $lang = getLanguageFromExtension($file->getExtension()); |
| 40 | + if ($lang === null) { |
| 41 | + continue; |
| 42 | + } |
| 43 | + |
| 44 | + $origCode = $code = file_get_contents($path); |
| 45 | + if ($lang === 'c') { |
| 46 | + $code = stripTrailingWhitespace($code); |
| 47 | + $code = reindentToTabs($code); |
| 48 | + } |
| 49 | + if ($origCode !== $code) { |
| 50 | + file_put_contents($path, $code); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +function stripTrailingWhitespace(string $code): string { |
| 55 | + return preg_replace('/\h+$/m', '', $code); |
| 56 | +} |
| 57 | + |
| 58 | +function reindentToTabs(string $code): string { |
| 59 | + return preg_replace_callback('/^ +/m', function(array $matches) { |
| 60 | + $tabSize = 4; |
| 61 | + $spaces = strlen($matches[0]); |
| 62 | + $tabs = intdiv($spaces, $tabSize); |
| 63 | + $spaces -= $tabs * $tabSize; |
| 64 | + return str_repeat("\t", $tabs) . str_repeat(" ", $spaces); |
| 65 | + }, $code); |
| 66 | +} |
| 67 | + |
| 68 | +function getLanguageFromExtension(string $ext): ?string { |
| 69 | + switch ($ext) { |
| 70 | + case 'c': |
| 71 | + case 'h': |
| 72 | + case 'cpp': |
| 73 | + case 'y': |
| 74 | + case 'l': |
| 75 | + case 're': |
| 76 | + return 'c'; |
| 77 | + default: |
| 78 | + return null; |
| 79 | + } |
| 80 | +} |
0 commit comments