First fully working recursive bundler

This commit is contained in:
Tim 2025-03-18 22:15:38 +01:00
parent 08d014713a
commit c4845ed7c6
3 changed files with 51 additions and 24 deletions

View File

@ -6,36 +6,58 @@ function line(string $text): void
echo $text . PHP_EOL; echo $text . PHP_EOL;
} }
if (count($argv) < 2) { if (count($argv) < 3) {
line('Usage: bundle.php <file>'); line('Usage: bundle.php <inFile> <outFile>');
exit(1); exit(1);
} }
$targetFile = $argv[1]; $fromFile = $argv[1];
if (!file_exists($targetFile)) { if (!file_exists($fromFile)) {
line('File not found: ' . $targetFile); line('File not found: ' . $fromFile);
exit(1);
}
$toFile = $argv[2];
if (file_exists($toFile)) {
line('File already exists: ' . $toFile);
exit(1); exit(1);
} }
function getIncludes(string $file): array function getLineIncludeFile(string $line): false|string
{ {
$content = file_get_contents($file); if (str_starts_with($line, 'include')) {
$files = []; preg_match("/include\s+'([^']+)'/", $line, $matches);
foreach (explode("\n", $content) as $line) { return $matches[1];
if (str_starts_with($line, 'include')) { }
$line = "include 'test.include.php';"; return false;
preg_match("/include\s+'([^']+)'/", $line, $matches); }
$files[] = $matches[1];
function getAllLines(string $file): iterable
{
$handle = fopen($file, 'r');
while (!feof($handle)) {
yield fgets($handle);
}
fclose($handle);
}
function replaceIncludes(string $file, int $depth = 0): iterable
{
foreach (getAllLines($file) as $line) {
$includeFile = getLineIncludeFile($line);
if ($includeFile) {
yield from replaceIncludes($includeFile, $depth + 1);
} else {
if ($depth > 0 && str_starts_with($line, '<?php')) continue;
if (empty(trim($line))) continue;
yield $line;
} }
} }
return $files;
} }
var_dump(getIncludes($targetFile)); $lines = replaceIncludes($fromFile);
$toFileHandle = fopen($toFile, 'w');
function buildIncludeTree(string $file): array foreach ($lines as $line) {
{ fwrite($toFileHandle, $line);
$includes = getIncludes($file); chmod($toFile, 0755);
foreach ($includes as $include) {
}
} }
fwrite($toFileHandle, PHP_EOL);
fclose($toFileHandle);

View File

@ -1,3 +1,5 @@
<?php <?php
include 'test2.include.php';
echo 'test.include' . PHP_EOL; echo 'test.include' . PHP_EOL;

3
test2.include.php Normal file
View File

@ -0,0 +1,3 @@
<?php
echo 'test2.include' . PHP_EOL;