From 50d6e75e7109669f72d81067816f74b898338c3d Mon Sep 17 00:00:00 2001 From: sunxyw Date: Sat, 31 Dec 2022 23:57:56 +0800 Subject: [PATCH] add phar compression --- src/ZM/Command/BuildCommand.php | 29 ++++++++++++++++++++++------- src/ZM/Command/Command.php | 2 +- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/ZM/Command/BuildCommand.php b/src/ZM/Command/BuildCommand.php index d338e7fe..fa5456a5 100644 --- a/src/ZM/Command/BuildCommand.php +++ b/src/ZM/Command/BuildCommand.php @@ -18,8 +18,9 @@ class BuildCommand extends Command */ protected function configure() { - $this->setHelp('此功能将会把整个项目打包为 Phar'); + $this->setHelp('此功能将会把整个项目打包为 Phar' . PHP_EOL . '默认会启用压缩功能,通过去除文件中的注释和空格,以减小文件大小,但可能增加构建耗时'); $this->addOption('target', 'D', InputOption::VALUE_REQUIRED, '指定输出文件位置', 'zm.phar'); + $this->addOption('no-compress', null, InputOption::VALUE_NONE, '是否不压缩文件,以减小构建耗时'); } protected function handle(): int @@ -33,9 +34,17 @@ class BuildCommand extends Command $this->ensureTargetWritable($target); $this->comment("目标文件:{$target}"); + if (file_exists($target)) { + $this->comment('目标文件已存在,正在删除...'); + unlink($target); + } + $this->info('正在构建 Phar 包'); - $this->build($target, LOAD_MODE === LOAD_MODE_VENDOR ? 'src/entry.php' : 'vendor/zhamao/framework/src/entry.php'); + $this->build( + $target, + LOAD_MODE === LOAD_MODE_VENDOR ? 'src/entry.php' : 'vendor/zhamao/framework/src/entry.php', + ); $this->info('Phar 包构建完成'); @@ -80,14 +89,20 @@ class BuildCommand extends Command $phar->startBuffering(); $files = FileSystem::scanDirFiles(SOURCE_ROOT_DIR, true, true); - $files = array_filter($files, function ($x) { - $dirs = preg_match('/(^(bin|config|resources|src|vendor)\\/|^(composer\\.json|README\\.md)$)/', $x); - return !($dirs !== 1); + // 只打包 bin / config / resources / src / vendor + $files = array_filter($files, function ($file) { + return preg_match('#^(bin|config|resources|src|vendor)/#', $file); }); sort($files); - foreach ($this->progress()->iterate($files) as $file) { - $phar->addFile($file, $file); + if ($this->input->getOption('no-compress')) { + foreach ($this->progress()->iterate($files) as $file) { + $phar->addFile($file, $file); + } + } else { + foreach ($this->progress()->iterate($files) as $file) { + $phar->addFromString($file, php_strip_whitespace($file)); + } } $phar->setStub( diff --git a/src/ZM/Command/Command.php b/src/ZM/Command/Command.php index 93144cb8..df329755 100644 --- a/src/ZM/Command/Command.php +++ b/src/ZM/Command/Command.php @@ -165,7 +165,7 @@ abstract class Command extends \Symfony\Component\Console\Command\Command $progress->setEmptyBarCharacter('⚬'); $progress->setProgressCharacter('➤'); $progress->setFormat( - "%current%/%max% [%bar%] %percent:3s%%\n🪅 %estimated:-20s% %memory:20s%" + "%current%/%max% [%bar%] %percent:3s%%\n🪅 %estimated:-20s% %memory:20s%" . PHP_EOL ); return $progress; }