hanli/build-phar.php
2025-12-01 18:13:15 +08:00

111 lines
2.5 KiB
PHP

<?php
/**
* PHAR 打包脚本
* 运行: php -d phar.readonly=0 build-phar.php
*/
// 检查 phar.readonly 设置
if (ini_get('phar.readonly')) {
echo "错误: phar.readonly 已启用\n";
echo "请使用: php -d phar.readonly=0 build-phar.php\n";
exit(1);
}
$pharFile = __DIR__ . '/build/hanli-idle.phar';
$buildDir = __DIR__ . '/build';
// 创建构建目录
if (!is_dir($buildDir)) {
mkdir($buildDir, 0755, true);
}
// 删除旧文件
if (file_exists($pharFile)) {
unlink($pharFile);
}
echo "开始打包...\n";
// 创建 PHAR
$phar = new Phar($pharFile);
$phar->startBuffering();
// 添加文件的辅助函数
function addDirectory(Phar $phar, string $dir, string $localPath = ''): int {
$count = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$filePath = $file->getPathname();
$relativePath = $localPath . '/' . $iterator->getSubPathname();
$phar->addFile($filePath, ltrim($relativePath, '/'));
$count++;
}
}
return $count;
}
// 添加 src 目录
echo "添加 src/...\n";
$count = addDirectory($phar, __DIR__ . '/src', 'src');
echo " 添加了 $count 个文件\n";
// 添加 vendor 目录
echo "添加 vendor/...\n";
$count = addDirectory($phar, __DIR__ . '/vendor', 'vendor');
echo " 添加了 $count 个文件\n";
// 添加 bin/game
if (file_exists(__DIR__ . '/bin/game')) {
$phar->addFile(__DIR__ . '/bin/game', 'bin/game');
echo "添加 bin/game\n";
}
// 创建启动脚本
$stub = <<<'STUB'
#!/usr/bin/env php
<?php
Phar::mapPhar('hanli-idle.phar');
// 设置包含路径
set_include_path('phar://hanli-idle.phar' . PATH_SEPARATOR . get_include_path());
require 'phar://hanli-idle.phar/vendor/autoload.php';
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Game\Core\Game;
// 设置 UTF-8
if (function_exists('mb_internal_encoding')) {
mb_internal_encoding('UTF-8');
}
$input = new ArgvInput();
$output = new ConsoleOutput();
$game = new Game($input, $output);
$game->run();
__HALT_COMPILER();
STUB;
$phar->setStub($stub);
$phar->stopBuffering();
// 压缩
echo "压缩中...\n";
$phar->compressFiles(Phar::GZ);
// 设置可执行权限
chmod($pharFile, 0755);
$size = round(filesize($pharFile) / 1024, 2);
echo "\n打包完成!\n";
echo "文件: $pharFile\n";
echo "大小: {$size} KB\n";
echo "运行: php build/hanli-idle.phar\n";