feat(v3): Tool package refactor (#1200)

This commit is contained in:
Jerry Ma
2026-07-06 21:59:44 +08:00
committed by GitHub
43 changed files with 566 additions and 182 deletions

View File

@@ -104,7 +104,7 @@ echo '<?php echo "Hello world!\n";' > a.php
## 直接下载 ## 直接下载
如果你暂时不想构建,或只想先测试,可以从 [Actions](https://github.com/static-php/static-php-cli-hosted/actions/workflows/build-php-bulk.yml) 下载示例预编译产物,或从自托管服务器下载。 如果你暂时不想构建,或只想先测试,可以从 [Actions](https://github.com/static-php/hosted/actions/workflows/build-php-bulk.yml) 下载示例预编译产物,或从自托管服务器下载。
我们为每个 PHP 版本提供 2 种扩展集合: 我们为每个 PHP 版本提供 2 种扩展集合:

View File

@@ -104,7 +104,7 @@ see <https://static-php.dev>.
## Direct Download ## Direct Download
If you do not want to build yet or just want to test first, you can download example pre-compiled artifacts from [Actions](https://github.com/static-php/static-php-cli-hosted/actions/workflows/build-php-bulk.yml) or from a self-hosted server. If you do not want to build yet or just want to test first, you can download example pre-compiled artifacts from [Actions](https://github.com/static-php/hosted/actions/workflows/build-php-bulk.yml) or from a self-hosted server.
We offer 2 types of extension sets for each PHP version: We offer 2 types of extension sets for each PHP version:

View File

@@ -17,7 +17,6 @@ openssl:
- zlib - zlib
depends@windows: depends@windows:
- zlib - zlib
- jom
headers: headers:
- openssl - openssl
static-libs@unix: static-libs@unix:
@@ -26,3 +25,6 @@ openssl:
static-libs@windows: static-libs@windows:
- libssl.lib - libssl.lib
- libcrypto.lib - libcrypto.lib
tools@windows:
- jom
- strawberry-perl

View File

@@ -10,10 +10,8 @@ frankenphp:
license: MIT license: MIT
depends: depends:
- php-embed - php-embed
- go-xcaddy
depends@windows: depends@windows:
- php-embed - php-embed
- go-win
- pthreads4w - pthreads4w
suggests@unix: suggests@unix:
- brotli - brotli
@@ -24,3 +22,7 @@ frankenphp:
- frankenphp - frankenphp
static-bins@windows: static-bins@windows:
- frankenphp.exe - frankenphp.exe
tools:
- go-xcaddy
tools@windows:
- go-win

View File

@@ -1,9 +0,0 @@
pkg-config:
type: target
artifact:
source: 'https://dl.static-php.dev/static-php-cli/deps/pkg-config/pkg-config-0.29.2.tar.gz'
binary:
linux-x86_64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-x86_64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
linux-aarch64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-aarch64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-x86_64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-x86_64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-aarch64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-aarch64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }

View File

@@ -1,4 +0,0 @@
zig:
type: target
artifact:
binary: custom

View File

@@ -1,5 +1,9 @@
7za-win: 7za-win:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/v3/tools/7zip/7za.exe', extract: '{pkg_root_path}/bin/7za.exe' } windows-x86_64: { type: url, url: 'https://dl.static-php.dev/v3/tools/7zip/7za.exe', extract: '{pkg_root_path}/bin/7za.exe' }
tool:
provides:
- 7za.exe
binary-subdir: bin

View File

@@ -1,5 +1,5 @@
go-win: go-win:
type: target type: tool
artifact: artifact:
binary: custom binary: custom
env: env:
@@ -8,3 +8,8 @@ go-win:
GOPATH: '{pkg_root_path}/go-win/go' GOPATH: '{pkg_root_path}/go-win/go'
path@windows: path@windows:
- '{pkg_root_path}/go-win/bin' - '{pkg_root_path}/go-win/bin'
tool:
provides:
- go.exe
- gofmt.exe
binary-subdir: go-win/bin

View File

@@ -1,5 +1,5 @@
go-xcaddy: go-xcaddy:
type: target type: tool
artifact: artifact:
binary: custom binary: custom
env: env:
@@ -8,5 +8,8 @@ go-xcaddy:
GOPATH: '{pkg_root_path}/go-xcaddy/go' GOPATH: '{pkg_root_path}/go-xcaddy/go'
path@unix: path@unix:
- '{pkg_root_path}/go-xcaddy/bin' - '{pkg_root_path}/go-xcaddy/bin'
static-bins: tool:
- xcaddy provides:
- go
- gofmt
binary-subdir: go-xcaddy/bin

View File

@@ -1,7 +1,11 @@
jom: jom:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://download.qt.io/official_releases/jom/jom.zip', extract: '{pkg_root_path}/jom' } windows-x86_64: { type: url, url: 'https://download.qt.io/official_releases/jom/jom.zip', extract: '{pkg_root_path}/jom' }
path@windows: path@windows:
- '{pkg_root_path}\jom' - '{pkg_root_path}\jom'
tool:
provides:
- jom.exe
binary-subdir: jom

View File

@@ -1,5 +1,10 @@
nasm: nasm:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{pkg_root_path}/bin/nasm.exe', ndisasm.exe: '{pkg_root_path}/bin/ndisasm.exe' } } windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{pkg_root_path}/bin/nasm.exe', ndisasm.exe: '{pkg_root_path}/bin/ndisasm.exe' } }
tool:
provides:
- nasm.exe
- ndisasm.exe
binary-subdir: bin

View File

@@ -0,0 +1,13 @@
pkg-config:
type: tool
artifact:
source: 'https://dl.static-php.dev/static-php-cli/deps/pkg-config/pkg-config-0.29.2.tar.gz'
binary:
linux-x86_64: { type: ghrel, repo: static-php/hosted, match: pkg-config-x86_64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
linux-aarch64: { type: ghrel, repo: static-php/hosted, match: pkg-config-aarch64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-x86_64: { type: ghrel, repo: static-php/hosted, match: pkg-config-x86_64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-aarch64: { type: ghrel, repo: static-php/hosted, match: pkg-config-aarch64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
tool:
provides:
- pkg-config
binary-subdir: bin

View File

@@ -1,8 +1,12 @@
protoc: protoc:
type: target type: tool
artifact: artifact:
binary: binary:
linux-x86_64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-x86_64\.zip', extract: '{pkg_root_path}/protoc' } linux-x86_64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-x86_64\.zip', extract: '{pkg_root_path}/protoc' }
linux-aarch64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-aarch_64\.zip', extract: '{pkg_root_path}/protoc' } linux-aarch64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-aarch_64\.zip', extract: '{pkg_root_path}/protoc' }
path: path:
- '{pkg_root_path}/protoc/bin' - '{pkg_root_path}/protoc/bin'
tool:
provides:
- protoc
binary-subdir: protoc/bin

View File

@@ -1,5 +1,9 @@
strawberry-perl: strawberry-perl:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://github.com/StrawberryPerl/Perl-Dist-Strawberry/releases/download/SP_5380_5361/strawberry-perl-5.38.0.1-64bit-portable.zip', extract: '{pkg_root_path}/strawberry-perl' } windows-x86_64: { type: url, url: 'https://github.com/StrawberryPerl/Perl-Dist-Strawberry/releases/download/SP_5380_5361/strawberry-perl-5.38.0.1-64bit-portable.zip', extract: '{pkg_root_path}/strawberry-perl' }
tool:
provides:
- perl.exe
binary-subdir: strawberry-perl/perl/bin

View File

@@ -1,7 +1,13 @@
upx: upx:
type: target type: tool
artifact: artifact:
binary: binary:
linux-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-amd64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } } linux-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-amd64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } }
linux-aarch64: { type: ghrel, repo: upx/upx, match: upx.+-arm64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } } linux-aarch64: { type: ghrel, repo: upx/upx, match: upx.+-arm64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } }
windows-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-win64\.zip, extract: { upx.exe: '{pkg_root_path}/bin/upx.exe' } } windows-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-win64\.zip, extract: { upx.exe: '{pkg_root_path}/bin/upx.exe' } }
tool:
provides:
- upx
provides@windows:
- upx.exe
binary-subdir: bin

View File

@@ -1,5 +1,9 @@
vswhere: vswhere:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://github.com/microsoft/vswhere/releases/download/3.1.7/vswhere.exe', extract: '{pkg_root_path}/bin/vswhere.exe' } windows-x86_64: { type: url, url: 'https://github.com/microsoft/vswhere/releases/download/3.1.7/vswhere.exe', extract: '{pkg_root_path}/bin/vswhere.exe' }
tool:
provides:
- vswhere.exe
binary-subdir: bin

14
config/pkg/tool/zig.yml Normal file
View File

@@ -0,0 +1,14 @@
zig:
type: tool
artifact:
binary: custom
tool:
provides:
- zig
- zig-cc
- zig-c++
- zig-ar
- zig-ld.lld
- zig-ranlib
- zig-objcopy
binary-subdir: zig

View File

@@ -10,6 +10,7 @@ package:
- config/pkg/lib/ - config/pkg/lib/
- config/pkg/target/ - config/pkg/target/
- config/pkg/ext/ - config/pkg/ext/
- config/pkg/tool/
artifact: artifact:
config: config:
- config/artifact/ - config/artifact/

View File

@@ -32,12 +32,15 @@ class xlswriter extends PhpExtensionPackage
#[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')] #[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')]
public function patchBeforeMakeForWindows(): void public function patchBeforeMakeForWindows(): void
{ {
$source_dir = $this->getSourceDir();
$theme_file = "{$source_dir}/library/libxlsx/src/theme.c";
// fix windows build with openssl extension duplicate symbol bug // fix windows build with openssl extension duplicate symbol bug
SourcePatcher::patchFile('spc_fix_xlswriter_win32.patch', $this->getSourceDir()); SourcePatcher::patchFile('spc_fix_xlswriter_win32.patch', $source_dir);
$content = file_get_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c'); $content = file_get_contents($theme_file);
$bom = pack('CCC', 0xEF, 0xBB, 0xBF); $bom = pack('CCC', 0xEF, 0xBB, 0xBF);
if (!str_starts_with($content, $bom)) { if (!str_starts_with($content, $bom)) {
file_put_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c', $bom . $content); file_put_contents($theme_file, $bom . $content);
} }
} }
} }

View File

@@ -255,9 +255,11 @@ class php extends TargetPackage
$installer->addBuildPackage('php-embed'); $installer->addBuildPackage('php-embed');
} }
// UPX compression: ensure the upx binary package is installed when requested // UPX compression: ensure the upx tool package is installed when requested.
// upx is a ToolPackage now, so it's installed directly rather than added as a
// library dependency (tool packages bypass the DependencyResolver graph).
if ($package->getBuildOption('with-upx-pack')) { if ($package->getBuildOption('with-upx-pack')) {
$additional_packages[] = 'upx'; $installer->addInstallPackage('upx');
} }
return [...$extensions_pkg, ...$additional_packages]; return [...$extensions_pkg, ...$additional_packages];

View File

@@ -2,17 +2,17 @@
declare(strict_types=1); declare(strict_types=1);
namespace Package\Target; namespace Package\Tool;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\InitPackage; use StaticPHP\Attribute\Package\InitPackage;
use StaticPHP\Attribute\Package\Target; use StaticPHP\Attribute\Package\Tool;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
#[Target('pkg-config')] #[Tool('pkg-config')]
class pkgconfig class pkgconfig
{ {
#[InitPackage] #[InitPackage]
@@ -23,7 +23,7 @@ class pkgconfig
#[BuildFor('Linux')] #[BuildFor('Linux')]
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
public function build(TargetPackage $package, ToolchainInterface $toolchain): void public function build(ToolPackage $package, ToolchainInterface $toolchain): void
{ {
UnixAutoconfExecutor::create($package) UnixAutoconfExecutor::create($package)
->appendEnv([ ->appendEnv([

View File

@@ -26,6 +26,7 @@ use StaticPHP\Exception\DownloaderException;
use StaticPHP\Exception\ExecutionException; use StaticPHP\Exception\ExecutionException;
use StaticPHP\Exception\ValidationException; use StaticPHP\Exception\ValidationException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\ToolVersionRegistry;
use StaticPHP\Registry\ArtifactLoader; use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
@@ -346,12 +347,32 @@ class ArtifactDownloader
} }
} }
public function checkUpdate(string $artifact_name, bool $prefer_source = false, bool $bare = false): CheckUpdateResult public function checkUpdate(string $artifact_name, bool $prefer_source = false, bool $bare = false, bool $use_installed = false): CheckUpdateResult
{ {
$artifact = ArtifactLoader::getArtifactInstance($artifact_name); $artifact = ArtifactLoader::getArtifactInstance($artifact_name);
if ($artifact === null) { if ($artifact === null) {
throw new WrongUsageException("Artifact '{$artifact_name}' not found, please check the name."); throw new WrongUsageException("Artifact '{$artifact_name}' not found, please check the name.");
} }
// --installed: prefer the version actually installed on disk (tool packages only) as the
// baseline, instead of the download cache. Falls back to the normal cache/bare logic below
// if this artifact has no recorded installed version (not a tool package, or not installed
// via the package installer yet).
if ($use_installed) {
$installed_version = ToolVersionRegistry::get($artifact_name);
if ($installed_version !== null) {
[$first, $second] = $prefer_source
? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name, $installed_version), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name, $installed_version)]
: [fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name, $installed_version), fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name, $installed_version)];
$result = $first() ?? $second();
if ($result !== null) {
return $result;
}
return new CheckUpdateResult(old: $installed_version, new: null, needUpdate: false, unsupported: true);
}
logger()->warning("Artifact '{$artifact_name}' has no recorded installed version (not a tool package, or not installed yet); falling back to download-cache based check.");
}
if ($bare) { if ($bare) {
[$first, $second] = $prefer_source [$first, $second] = $prefer_source
? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name)] ? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name)]
@@ -403,16 +424,17 @@ class ArtifactDownloader
* @param bool $prefer_source Whether to prefer source over binary * @param bool $prefer_source Whether to prefer source over binary
* @param bool $bare Check without requiring artifact to be downloaded first * @param bool $bare Check without requiring artifact to be downloaded first
* @param null|callable $onResult Called immediately with (string $name, CheckUpdateResult) as each result arrives * @param null|callable $onResult Called immediately with (string $name, CheckUpdateResult) as each result arrives
* @param bool $use_installed Prefer the installed (on-disk) version over the download cache (tool packages only)
* @return array<string, CheckUpdateResult> Results keyed by artifact name * @return array<string, CheckUpdateResult> Results keyed by artifact name
*/ */
public function checkUpdates(array $artifact_names, bool $prefer_source = false, bool $bare = false, ?callable $onResult = null): array public function checkUpdates(array $artifact_names, bool $prefer_source = false, bool $bare = false, ?callable $onResult = null, bool $use_installed = false): array
{ {
if ($this->parallel > 1 && count($artifact_names) > 1) { if ($this->parallel > 1 && count($artifact_names) > 1) {
return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult); return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult, $use_installed);
} }
$results = []; $results = [];
foreach ($artifact_names as $name) { foreach ($artifact_names as $name) {
$result = $this->checkUpdate($name, $prefer_source, $bare); $result = $this->checkUpdate($name, $prefer_source, $bare, $use_installed);
$results[$name] = $result; $results[$name] = $result;
if ($onResult !== null) { if ($onResult !== null) {
($onResult)($name, $result); ($onResult)($name, $result);
@@ -436,7 +458,7 @@ class ArtifactDownloader
return $this->options[$name] ?? $default; return $this->options[$name] ?? $default;
} }
private function checkUpdatesWithConcurrency(array $artifact_names, bool $prefer_source, bool $bare, ?callable $onResult): array private function checkUpdatesWithConcurrency(array $artifact_names, bool $prefer_source, bool $bare, ?callable $onResult, bool $use_installed = false): array
{ {
$results = []; $results = [];
$fiber_pool = []; $fiber_pool = [];
@@ -451,8 +473,8 @@ class ArtifactDownloader
// fill pool // fill pool
while (count($fiber_pool) < $this->parallel && !empty($remaining)) { while (count($fiber_pool) < $this->parallel && !empty($remaining)) {
$name = array_shift($remaining); $name = array_shift($remaining);
$fiber = new \Fiber(function () use ($name, $prefer_source, $bare) { $fiber = new \Fiber(function () use ($name, $prefer_source, $bare, $use_installed) {
return [$name, $this->checkUpdate($name, $prefer_source, $bare)]; return [$name, $this->checkUpdate($name, $prefer_source, $bare, $use_installed)];
}); });
$fiber->start(); $fiber->start();
$fiber_pool[$name] = $fiber; $fiber_pool[$name] = $fiber;
@@ -491,12 +513,12 @@ class ArtifactDownloader
return $results; return $results;
} }
private function probeSourceCheckUpdate(Artifact $artifact, string $artifact_name): ?CheckUpdateResult private function probeSourceCheckUpdate(Artifact $artifact, string $artifact_name, ?string $old_version = null): ?CheckUpdateResult
{ {
if (($callback = $artifact->getCustomSourceCheckUpdateCallback()) !== null) { if (($callback = $artifact->getCustomSourceCheckUpdateCallback()) !== null) {
return ApplicationContext::invoke($callback, [ return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this, ArtifactDownloader::class => $this,
'old_version' => null, 'old_version' => $old_version,
]); ]);
} }
$config = $artifact->getDownloadConfig('source'); $config = $artifact->getDownloadConfig('source');
@@ -509,16 +531,16 @@ class ArtifactDownloader
} }
/** @var CheckUpdateInterface $dl */ /** @var CheckUpdateInterface $dl */
$dl = new $cls(); $dl = new $cls();
return $dl->checkUpdate($artifact_name, $config, null, $this); return $dl->checkUpdate($artifact_name, $config, $old_version, $this);
} }
private function probeBinaryCheckUpdate(Artifact $artifact, string $artifact_name): ?CheckUpdateResult private function probeBinaryCheckUpdate(Artifact $artifact, string $artifact_name, ?string $old_version = null): ?CheckUpdateResult
{ {
// custom binary callback takes precedence over config-based binary // custom binary callback takes precedence over config-based binary
if (($callback = $artifact->getCustomBinaryCheckUpdateCallback()) !== null) { if (($callback = $artifact->getCustomBinaryCheckUpdateCallback()) !== null) {
return ApplicationContext::invoke($callback, [ return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this, ArtifactDownloader::class => $this,
'old_version' => null, 'old_version' => $old_version,
]); ]);
} }
$binary_config = $artifact->getDownloadConfig('binary'); $binary_config = $artifact->getDownloadConfig('binary');
@@ -532,7 +554,7 @@ class ArtifactDownloader
} }
/** @var CheckUpdateInterface $dl */ /** @var CheckUpdateInterface $dl */
$dl = new $cls(); $dl = new $cls();
return $dl->checkUpdate($artifact_name, $platform_config, null, $this); return $dl->checkUpdate($artifact_name, $platform_config, $old_version, $this);
} }
private function downloadWithType(Artifact $artifact, int $current, int $total, bool $parallel = false): int private function downloadWithType(Artifact $artifact, int $current, int $total, bool $parallel = false): int

View File

@@ -23,6 +23,7 @@ class CheckUpdateCommand extends BaseCommand
$this->addArgument('artifact', InputArgument::OPTIONAL, 'The name of the artifact(s) to check for updates, comma-separated (default: all downloaded artifacts)'); $this->addArgument('artifact', InputArgument::OPTIONAL, 'The name of the artifact(s) to check for updates, comma-separated (default: all downloaded artifacts)');
$this->addOption('json', null, null, 'Output result in JSON format'); $this->addOption('json', null, null, 'Output result in JSON format');
$this->addOption('bare', null, null, 'Check update without requiring the artifact to be downloaded first (old version will be null)'); $this->addOption('bare', null, null, 'Check update without requiring the artifact to be downloaded first (old version will be null)');
$this->addOption('installed', null, null, 'Compare against the version actually installed on disk (tool packages only) instead of the download cache; falls back to normal behavior for artifacts with no recorded installed version');
$this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10); $this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10);
// --with-php option for checking updates with a specific PHP version context // --with-php option for checking updates with a specific PHP version context
@@ -45,8 +46,9 @@ class CheckUpdateCommand extends BaseCommand
try { try {
$downloader = new ArtifactDownloader($this->input->getOptions()); $downloader = new ArtifactDownloader($this->input->getOptions());
$bare = (bool) $this->getOption('bare'); $bare = (bool) $this->getOption('bare');
$use_installed = (bool) $this->getOption('installed');
if ($this->getOption('json')) { if ($this->getOption('json')) {
$results = $downloader->checkUpdates($artifacts, bare: $bare); $results = $downloader->checkUpdates($artifacts, bare: $bare, use_installed: $use_installed);
$outputs = []; $outputs = [];
foreach ($results as $artifact => $result) { foreach ($results as $artifact => $result) {
$outputs[$artifact] = [ $outputs[$artifact] = [
@@ -59,7 +61,7 @@ class CheckUpdateCommand extends BaseCommand
$this->output->writeln(json_encode($outputs, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); $this->output->writeln(json_encode($outputs, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
return static::OK; return static::OK;
} }
$downloader->checkUpdates($artifacts, bare: $bare, onResult: function (string $artifact, CheckUpdateResult $result) { $downloader->checkUpdates($artifacts, bare: $bare, use_installed: $use_installed, onResult: function (string $artifact, CheckUpdateResult $result) {
if ($result->unsupported) { if ($result->unsupported) {
$this->output->writeln("Artifact <info>{$artifact}</info> does not support update checking, <comment>skipped</comment>"); $this->output->writeln("Artifact <info>{$artifact}</info> does not support update checking, <comment>skipped</comment>");
} elseif (!$result->needUpdate) { } elseif (!$result->needUpdate) {

View File

@@ -54,8 +54,8 @@ class DumpCapabilitiesCommand extends BaseCommand
{ {
$result = []; $result = [];
// library / target / virtual-target // library / target / virtual-target / tool
foreach (PackageLoader::getPackages(['library', 'target', 'virtual-target']) as $name => $pkg) { foreach (PackageLoader::getPackages(['library', 'target', 'virtual-target', 'tool']) as $name => $pkg) {
$installable = []; $installable = [];
$artifact = $pkg->getArtifact(); $artifact = $pkg->getArtifact();
if ($artifact !== null) { if ($artifact !== null) {

View File

@@ -13,7 +13,7 @@ class DoctorCommand extends BaseCommand
{ {
public function configure(): void public function configure(): void
{ {
$this->addOption('auto-fix', null, InputOption::VALUE_OPTIONAL, 'Automatically fix failed items (if possible)', false); $this->addOption('auto-fix', 'y', InputOption::VALUE_OPTIONAL, 'Automatically fix failed items (if possible)', false);
} }
public function handle(): int public function handle(): int

View File

@@ -23,7 +23,7 @@ class InstallPackageCommand extends BaseCommand
'The package to install (name or path)', 'The package to install (name or path)',
suggestedValues: function (CompletionInput $input) { suggestedValues: function (CompletionInput $input) {
$packages = []; $packages = [];
foreach (PackageLoader::getPackages(['target', 'virtual-target']) as $name => $_) { foreach (PackageLoader::getPackages(['target', 'virtual-target', 'tool']) as $name => $_) {
$packages[] = $name; $packages[] = $name;
} }
$val = $input->getCompletionValue(); $val = $input->getCompletionValue();

View File

@@ -24,6 +24,10 @@ class ConfigValidator
'lang' => ConfigType::STRING, 'lang' => ConfigType::STRING,
'frameworks' => ConfigType::LIST_ARRAY, // @ 'frameworks' => ConfigType::LIST_ARRAY, // @
// build-time tool dependency declaration (resolved independently of the library
// dependency graph, see PackageInstaller::collectRequiredTools())
'tools' => ConfigType::LIST_ARRAY, // @
// php-extension type fields // php-extension type fields
'php-extension' => ConfigType::ASSOC_ARRAY, 'php-extension' => ConfigType::ASSOC_ARRAY,
'zend-extension' => ConfigType::BOOL, 'zend-extension' => ConfigType::BOOL,
@@ -63,6 +67,9 @@ class ConfigValidator
'lang' => false, 'lang' => false,
'frameworks' => false, // @ 'frameworks' => false, // @
// build-time tool dependency declaration
'tools' => false, // @
// php-extension type fields // php-extension type fields
'php-extension' => false, 'php-extension' => false,

View File

@@ -32,7 +32,10 @@ use StaticPHP\Command\SPCConfigCommand;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Registry\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Registry\Registry; use StaticPHP\Registry\Registry;
use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Application; use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleApplication extends Application class ConsoleApplication extends Application
{ {
@@ -104,4 +107,15 @@ class ConsoleApplication extends Application
{ {
self::$additional_commands = array_merge(self::$additional_commands, $additional_commands); self::$additional_commands = array_merge(self::$additional_commands, $additional_commands);
} }
/**
* Hook Symfony's doRun() to inject the real input/output into InteractiveTerm before
* any command executes. From this point forward, InteractiveTerm uses the configured
* Console (respecting --no-ansi, --verbose, etc.) instead of the lazy STDERR fallback.
*/
public function doRun(InputInterface $input, OutputInterface $output): int
{
InteractiveTerm::init($input, $output);
return parent::doRun($input, $output);
}
} }

View File

@@ -113,60 +113,6 @@ class LibraryPackage extends Package
} }
} }
/**
* Get extra CFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_CFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_CFLAGS.
*/
public function getLibExtraCFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CFLAGS') ?: '';
// get default c flags
$arch_c_flags = getenv('SPC_DEFAULT_CFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CFLAGS')) && !str_contains($env, $arch_c_flags)) {
$env .= ' ' . $arch_c_flags;
}
return trim($env);
}
/**
* Get extra CXXFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_CXXFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_CXXFLAGS.
*/
public function getLibExtraCxxFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CXXFLAGS') ?: '';
// get default cxx flags
$arch_cxx_flags = getenv('SPC_DEFAULT_CXXFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CXXFLAGS')) && !str_contains($env, $arch_cxx_flags)) {
$env .= ' ' . $arch_cxx_flags;
}
return trim($env);
}
/**
* Get extra LDFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_LDFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_LDFLAGS.
*/
public function getLibExtraLdFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_LDFLAGS') ?: '';
// get default ld flags
$arch_ld_flags = getenv('SPC_DEFAULT_LDFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_LDFLAGS')) && !str_contains($env, $arch_ld_flags)) {
$env .= ' ' . $arch_ld_flags;
}
return trim($env);
}
/** /**
* Patch pkgconfig file prefix, exec_prefix, libdir, includedir for correct build. * Patch pkgconfig file prefix, exec_prefix, libdir, includedir for correct build.
* *
@@ -364,17 +310,6 @@ class LibraryPackage extends Package
return $res['libs']; return $res['libs'];
} }
/**
* Get extra LIBS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_LIBS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_LIBS.
*/
public function getLibExtraLibs(): string
{
return getenv($this->getSnakeCaseName() . '_LIBS') ?: '';
}
/** /**
* Get tar compress options from suffix * Get tar compress options from suffix
* *

View File

@@ -284,6 +284,71 @@ abstract class Package
return $this->getArtifact()?->hasPlatformBinary() ?? false; return $this->getArtifact()?->hasPlatformBinary() ?? false;
} }
/**
* Get extra CFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_CFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_CFLAGS.
*/
public function getLibExtraCFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CFLAGS') ?: '';
// get default c flags
$arch_c_flags = getenv('SPC_DEFAULT_CFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CFLAGS')) && !str_contains($env, $arch_c_flags)) {
$env .= ' ' . $arch_c_flags;
}
return trim($env);
}
/**
* Get extra CXXFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_CXXFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_CXXFLAGS.
*/
public function getLibExtraCxxFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CXXFLAGS') ?: '';
// get default cxx flags
$arch_cxx_flags = getenv('SPC_DEFAULT_CXXFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CXXFLAGS')) && !str_contains($env, $arch_cxx_flags)) {
$env .= ' ' . $arch_cxx_flags;
}
return trim($env);
}
/**
* Get extra LDFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_LDFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_LDFLAGS.
*/
public function getLibExtraLdFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_LDFLAGS') ?: '';
// get default ld flags
$arch_ld_flags = getenv('SPC_DEFAULT_LDFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_LDFLAGS')) && !str_contains($env, $arch_ld_flags)) {
$env .= ' ' . $arch_ld_flags;
}
return trim($env);
}
/**
* Get extra LIBS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_LIBS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_LIBS.
*/
public function getLibExtraLibs(): string
{
return getenv($this->getSnakeCaseName() . '_LIBS') ?: '';
}
/** /**
* Get the snake_case name of the package. * Get the snake_case name of the package.
*/ */

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use StaticPHP\Artifact\ArtifactCache;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\SPCException; use StaticPHP\Exception\SPCException;
@@ -39,8 +40,8 @@ class PackageBuilder
public function buildPackage(Package $package, bool $force = false): int public function buildPackage(Package $package, bool $force = false): int
{ {
// init build dirs // init build dirs
if (!$package instanceof LibraryPackage) { if (!$package instanceof LibraryPackage && !$package instanceof ToolPackage) {
throw new SPCInternalException('Please, never try to build non-library packages directly.'); throw new SPCInternalException('Please, never try to build non-library, non-tool packages directly.');
} }
FileSystem::createDir($package->getBuildRootPath()); FileSystem::createDir($package->getBuildRootPath());
FileSystem::createDir($package->getIncludeDir()); FileSystem::createDir($package->getIncludeDir());
@@ -78,6 +79,14 @@ class PackageBuilder
$this->installLicense($package, $license); $this->installLicense($package, $license);
} }
} }
// Record the installed version for tool packages built from source, so
// `check-update --installed` reflects what's actually on disk (mirrors the
// binary-install recording in PackageInstaller::installBinary()).
if ($package instanceof ToolPackage) {
$source_info = ApplicationContext::get(ArtifactCache::class)->getSourceInfo($package->getName());
ToolVersionRegistry::record($package->getName(), $source_info['version'] ?? null);
}
} catch (SPCException $e) { } catch (SPCException $e) {
// Ensure package information is bound if not already // Ensure package information is bound if not already
if ($e->getPackageInfo() === null) { if ($e->getPackageInfo() === null) {

View File

@@ -168,9 +168,6 @@ class PackageInstaller
// Early validation: check if packages can be built or installed before downloading // Early validation: check if packages can be built or installed before downloading
$this->validatePackagesBeforeBuild(); $this->validatePackagesBeforeBuild();
// Check that all required tools are installed before proceeding
$this->ensureRequiredTools();
// check download // check download
if ($this->download) { if ($this->download) {
$downloaderOptions = DownloaderOptions::extractFromConsoleOptions($this->options, 'dl'); $downloaderOptions = DownloaderOptions::extractFromConsoleOptions($this->options, 'dl');
@@ -178,7 +175,7 @@ class PackageInstaller
// These must always download binary (not source), regardless of global prefer-source setting. // These must always download binary (not source), regardless of global prefer-source setting.
$binary_only_packages = array_filter( $binary_only_packages = array_filter(
$this->packages, $this->packages,
fn ($p) => $p instanceof LibraryPackage fn ($p) => ($p instanceof LibraryPackage || $p instanceof ToolPackage)
&& !$this->isBuildPackage($p) && !$this->isBuildPackage($p)
&& !$p->hasStage('build') && !$p->hasStage('build')
&& ($p->getArtifact()?->hasPlatformBinary() ?? false) && ($p->getArtifact()?->hasPlatformBinary() ?? false)
@@ -216,8 +213,8 @@ class PackageInstaller
$builder = ApplicationContext::get(PackageBuilder::class); $builder = ApplicationContext::get(PackageBuilder::class);
foreach ($this->packages as $package) { foreach ($this->packages as $package) {
$is_to_build = $this->isBuildPackage($package); $is_to_build = $this->isBuildPackage($package);
$has_build_stage = $package instanceof LibraryPackage && $package->hasStage('build'); $has_build_stage = ($package instanceof LibraryPackage || $package instanceof ToolPackage) && $package->hasStage('build');
$should_use_binary = $package instanceof LibraryPackage && ($package->getArtifact()?->shouldUseBinary() ?? false); $should_use_binary = ($package instanceof LibraryPackage || $package instanceof ToolPackage) && ($package->getArtifact()?->shouldUseBinary() ?? false);
$has_source = $package->hasSource(); $has_source = $package->hasSource();
if (!$is_to_build && $should_use_binary) { if (!$is_to_build && $should_use_binary) {
// install binary // install binary
@@ -280,6 +277,11 @@ class PackageInstaller
// perform after-install actions and emit post-install events // perform after-install actions and emit post-install events
$this->emitPostInstallEvents(); $this->emitPostInstallEvents();
// Final verification: declared build-time tools should have been auto-installed by the
// pipeline above (they were merged into $this->packages in resolvePackages()). This only
// throws if a tool genuinely failed to become available (e.g. no artifact for this platform).
$this->ensureRequiredTools();
} }
public function isBuildPackage(Package|string $package): bool public function isBuildPackage(Package|string $package): bool
@@ -357,12 +359,16 @@ class PackageInstaller
} }
// Fallback: if the download cache is missing (e.g. download failed or cache was cleared), // Fallback: if the download cache is missing (e.g. download failed or cache was cleared),
// still check whether the files are physically present in buildroot. // still check whether the files are physically present in buildroot.
// Note: TargetPackage extends LibraryPackage, but target packages (e.g. zig) have no // Note: TargetPackage extends LibraryPackage, but target packages have no
// static-libs/headers configured, so isInstalled() would trivially return true for them. // static-libs/headers configured, so isInstalled() would trivially return true for them.
// Only apply this fallback to pure library packages. // Only apply this fallback to pure library packages.
if ($package instanceof LibraryPackage && !($package instanceof TargetPackage)) { if ($package instanceof LibraryPackage && !($package instanceof TargetPackage)) {
return $package->isInstalled(); return $package->isInstalled();
} }
// Tool packages: fall back to checking their provided binaries directly on disk.
if ($package instanceof ToolPackage) {
return $package->isInstalled();
}
return false; return false;
} }
@@ -511,6 +517,16 @@ class PackageInstaller
} }
$status = $extractor->extract($artifact); $status = $extractor->extract($artifact);
// Record the installed version for tool packages, so `check-update --installed` can
// compare against what's actually on disk instead of only the download cache (which
// only reflects the last download and may be stale or cleared). Recorded regardless of
// $status so the registry self-heals if it was deleted separately from the install dir.
if ($package instanceof ToolPackage) {
$cache_info = ApplicationContext::get(ArtifactCache::class)->getBinaryInfo($artifact->getName(), SystemTarget::getCurrentPlatformString());
ToolVersionRegistry::record($artifact->getName(), $cache_info['version'] ?? null);
}
if ($status === SPC_STATUS_ALREADY_EXTRACTED) { if ($status === SPC_STATUS_ALREADY_EXTRACTED) {
return SPC_STATUS_ALREADY_INSTALLED; return SPC_STATUS_ALREADY_INSTALLED;
} }
@@ -661,8 +677,8 @@ class PackageInstaller
*/ */
private function validatePackageArtifact(Package $package): void private function validatePackageArtifact(Package $package): void
{ {
// target and library must have at least source or platform binary // target, library and tool packages must have at least source or platform binary
if (in_array($package->getType(), ['library', 'target']) && !$package->getArtifact()?->hasSource() && !$package->getArtifact()?->hasPlatformBinary()) { if (in_array($package->getType(), ['library', 'target', 'tool']) && !$package->getArtifact()?->hasSource() && !$package->getArtifact()?->hasPlatformBinary()) {
throw new WrongUsageException("Validation failed: Target package '{$package->getName()}' has no source or current platform (" . SystemTarget::getCurrentPlatformString() . ') binary defined.'); throw new WrongUsageException("Validation failed: Target package '{$package->getName()}' has no source or current platform (" . SystemTarget::getCurrentPlatformString() . ') binary defined.');
} }
} }
@@ -695,6 +711,32 @@ class PackageInstaller
$this->packages[$pkg_name] = PackageLoader::getPackage($pkg_name); $this->packages[$pkg_name] = PackageLoader::getPackage($pkg_name);
} }
// Merge in build-time tool packages declared via 'tools'/'tools@platform' fields on the
// packages resolved above. Tools are intentionally NOT part of the library dependency graph
// (DependencyResolver), but still need to ride the normal download/extract/install pipeline
// so they get auto-installed like any other package.
//
// Tools are prepended so they install BEFORE any package that declares them — otherwise a
// library that invokes e.g. jom.exe during its build stage would fail because the tool
// hasn't been extracted yet (tools were appended after the dependency graph in insertion
// order, which is also the build-loop iteration order).
$tool_packages = [];
foreach ($this->collectRequiredTools() as $tool_name) {
if (isset($this->packages[$tool_name])) {
continue;
}
try {
$tool = PackageLoader::getPackage($tool_name);
} catch (WrongUsageException) {
continue; // will be reported as missing by ensureRequiredTools()
}
if ($tool instanceof ToolPackage) {
$tool_packages[$tool_name] = $tool;
}
}
// Prepend: tools first, then the dependency-resolved packages.
$this->packages = [...$tool_packages, ...$this->packages];
foreach ($this->packages as $package) { foreach ($this->packages as $package) {
$this->injectPackageEnvs($package); $this->injectPackageEnvs($package);
} }
@@ -703,8 +745,12 @@ class PackageInstaller
/** /**
* Ensure all required tools are installed, throwing if any are missing. * Ensure all required tools are installed, throwing if any are missing.
* *
* Called early in the build pipeline (before download/extract). * Called at the end of run(), after the normal download/extract/build/install pipeline
* When tools are missing, lists them with install hints. * has had a chance to auto-install any tool package merged in resolvePackages(). This is
* a final safety net: it only throws if a declared tool still isn't available afterward
* (e.g. no artifact defined for the current platform, or the tool name doesn't resolve to
* a registered ToolPackage). "General" tools not declared via any package's 'tools' field
* (e.g. zig, musl-toolchain) are not covered here and remain purely Doctor-driven.
*/ */
private function ensureRequiredTools(): void private function ensureRequiredTools(): void
{ {

View File

@@ -5,8 +5,8 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalPathTrait;
/** /**
* Represents a build-time tool package. * Represents a build-time tool package.
@@ -26,6 +26,11 @@ use StaticPHP\Util\GlobalPathTrait;
* provides: [nasm.exe, ndisasm.exe] # executables this tool installs * provides: [nasm.exe, ndisasm.exe] # executables this tool installs
* binary-subdir: '' # subdirectory under install root (default: '') * binary-subdir: '' # subdirectory under install root (default: '')
* min-version: '2.16' # minimum required version (optional) * min-version: '2.16' # minimum required version (optional)
*
* Fields nested under 'tool' support the same '@windows'/'@unix'/'@macos'/'@linux' suffix
* overrides as top-level package fields (e.g. 'provides@windows' overrides 'provides' when
* building on Windows), useful when a tool provides differently-named binaries per OS
* (e.g. upx vs upx.exe).
* artifact: * artifact:
* binary: * binary:
* windows-x86_64: * windows-x86_64:
@@ -36,7 +41,44 @@ use StaticPHP\Util\GlobalPathTrait;
*/ */
class ToolPackage extends Package class ToolPackage extends Package
{ {
use GlobalPathTrait; /**
* Get the build root ('--prefix') for a tool that builds from source.
*
* Unlike LibraryPackage (which installs into BUILD_ROOT_PATH), tool packages that build
* from source (e.g. pkg-config, via UnixAutoconfExecutor/UnixCMakeExecutor) install into
* their own install root (PKG_ROOT_PATH by default), consistent with pre-built tool binaries.
*/
public function getBuildRootPath(): string
{
return $this->getInstallRoot();
}
/**
* Tool packages don't produce headers for other packages to consume. Kept self-contained
* under the tool's own install root so a from-source build never accidentally picks up
* unrelated headers from BUILD_ROOT_PATH.
*/
public function getIncludeDir(): string
{
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . 'include';
}
/**
* Tool packages don't produce libraries for other packages to consume. Kept self-contained
* under the tool's own install root (see getIncludeDir()).
*/
public function getLibDir(): string
{
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . 'lib';
}
/**
* Where this tool's own executables live, i.e. {install-root}/{binary-subdir}.
*/
public function getBinDir(): string
{
return $this->getBinaryDir();
}
/** /**
* Get the install root directory for this tool. * Get the install root directory for this tool.
@@ -50,7 +92,7 @@ class ToolPackage extends Package
if ($root = getenv($env_var)) { if ($root = getenv($env_var)) {
return $root; return $root;
} }
$config_root = $this->getToolConfig()['install-root'] ?? null; $config_root = $this->getToolField('install-root');
if ($config_root !== null) { if ($config_root !== null) {
return FileSystem::replacePathVariable((string) $config_root); return FileSystem::replacePathVariable((string) $config_root);
} }
@@ -65,7 +107,7 @@ class ToolPackage extends Package
*/ */
public function getBinaryDir(): string public function getBinaryDir(): string
{ {
$subdir = $this->getToolConfig()['binary-subdir'] ?? ''; $subdir = $this->getToolField('binary-subdir') ?? '';
if ($subdir === '') { if ($subdir === '') {
return $this->getInstallRoot(); return $this->getInstallRoot();
} }
@@ -75,14 +117,15 @@ class ToolPackage extends Package
/** /**
* Get the list of executables this tool provides. * Get the list of executables this tool provides.
* *
* Reads from YAML 'tool.provides' field. Each entry is a bare filename * Reads from YAML 'tool.provides' field (with '@windows'/'@unix'/'@macos'/'@linux'
* (e.g. 'nasm.exe'), resolved relative to getBinaryDir(). * suffix override support). Each entry is a bare filename (e.g. 'nasm.exe'), resolved
* relative to getBinaryDir().
* *
* @return string[] Bare executable names (not full paths) * @return string[] Bare executable names (not full paths)
*/ */
public function getProvides(): array public function getProvides(): array
{ {
return $this->getToolConfig()['provides'] ?? []; return $this->getToolField('provides') ?? [];
} }
/** /**
@@ -112,6 +155,20 @@ class ToolPackage extends Package
return array_all($this->getProvides(), fn ($binary) => file_exists($this->getBinary($binary))); return array_all($this->getProvides(), fn ($binary) => file_exists($this->getBinary($binary)));
} }
/**
* Get the version currently installed on disk, as recorded by ToolVersionRegistry when this
* tool's binary was last (re-)installed via PackageInstaller::installBinary().
*
* Returns null if the tool was never installed through the package installer (e.g. installed
* manually, or not installed at all), or if its artifact doesn't expose a version string.
* This reflects what's actually on disk, unlike the download cache which only reflects the
* last download and may be stale or cleared.
*/
public function getInstalledVersion(): ?string
{
return ToolVersionRegistry::get($this->name);
}
/** /**
* Get the minimum required version for this tool, if specified. * Get the minimum required version for this tool, if specified.
* *
@@ -119,7 +176,7 @@ class ToolPackage extends Package
*/ */
public function getMinVersion(): ?string public function getMinVersion(): ?string
{ {
$version = $this->getToolConfig()['min-version'] ?? null; $version = $this->getToolField('min-version');
return $version !== null ? (string) $version : null; return $version !== null ? (string) $version : null;
} }
@@ -148,4 +205,29 @@ class ToolPackage extends Package
} }
return $config['tool']; return $config['tool'];
} }
/**
* Get a field from the nested 'tool' config block, honoring the same
* '@windows'/'@unix'/'@macos'/'@linux'/'@bsd'/'@freebsd' suffix override priority
* that PackageConfig::get() applies to top-level fields. This lets a tool declare a
* per-OS override, e.g. 'provides' + 'provides@windows', without needing platform-
* specific package config files.
*/
private function getToolField(string $field): mixed
{
$tool = $this->getToolConfig();
$suffixes = match (SystemTarget::getTargetOS()) {
'Windows' => ['@windows', ''],
'Darwin' => ['@macos', '@unix', ''],
'Linux' => ['@linux', '@unix', ''],
'BSD' => ['@freebsd', '@bsd', '@unix', ''],
};
foreach ($suffixes as $suffix) {
$key = "{$field}{$suffix}";
if (isset($tool[$key])) {
return $tool[$key];
}
}
return null;
}
} }

View File

@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Package;
use StaticPHP\Runtime\SystemTarget;
/**
* Tracks the version actually installed on disk for tool packages (PKG_ROOT_PATH), separate from
* the download cache (ArtifactCache). Tools are installed once and reused across many builds, so
* the download cache (which only reflects the last download) can drift from what's really on disk
* (e.g. cache cleared, or installed a long time ago via `doctor`). This registry is the source of
* truth for "what version is currently installed", used by ToolPackage::getInstalledVersion() and
* the `check-update --installed` flag.
*
* Backed by a small JSON file at PKG_ROOT_PATH/.spc-tool-versions.json, mirroring the same
* read-once/write-through pattern used by StaticPHP\Artifact\ArtifactCache.
*/
class ToolVersionRegistry
{
/** @var null|array<string, array{version: null|string, platform: string, installed_at: string}> */
private static ?array $data = null;
/**
* Get the recorded installed version for a tool, or null if never recorded (not a tool
* package, not installed yet, or the artifact doesn't expose a version).
*/
public static function get(string $tool_name): ?string
{
self::load();
return self::$data[$tool_name]['version'] ?? null;
}
/**
* Record the version currently installed for a tool. Called after a tool package's binary
* has been (re-)installed, regardless of whether extraction actually ran (keeps the registry
* self-healing if it was deleted separately from the installed files).
*/
public static function record(string $tool_name, ?string $version): void
{
self::load();
self::$data[$tool_name] = [
'version' => $version,
'platform' => SystemTarget::getCurrentPlatformString(),
'installed_at' => date('c'),
];
self::save();
}
private static function getPath(): string
{
return PKG_ROOT_PATH . '/.spc-tool-versions.json';
}
private static function load(): void
{
if (self::$data !== null) {
return;
}
$path = self::getPath();
if (!file_exists($path)) {
self::$data = [];
return;
}
$content = file_get_contents($path);
self::$data = is_string($content) ? (json_decode($content, true) ?: []) : [];
}
private static function save(): void
{
$path = self::getPath();
$dir = dirname($path);
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
file_put_contents($path, json_encode(self::$data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}

View File

@@ -5,12 +5,13 @@ declare(strict_types=1);
namespace StaticPHP\Runtime\Executor; namespace StaticPHP\Runtime\Executor;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\ToolPackage;
abstract class Executor abstract class Executor
{ {
public function __construct(protected LibraryPackage $package) {} public function __construct(protected LibraryPackage|ToolPackage $package) {}
public static function create(LibraryPackage $package): static public static function create(LibraryPackage|ToolPackage $package): static
{ {
return new static($package); return new static($package);
} }

View File

@@ -10,6 +10,7 @@ use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\UnixShell; use StaticPHP\Runtime\Shell\UnixShell;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use ZM\Logger\ConsoleColor; use ZM\Logger\ConsoleColor;
@@ -22,7 +23,7 @@ class UnixAutoconfExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package, ?PackageInstaller $installer = null) public function __construct(protected LibraryPackage|ToolPackage $package, ?PackageInstaller $installer = null)
{ {
parent::__construct($package); parent::__construct($package);
if ($installer !== null) { if ($installer !== null) {

View File

@@ -11,6 +11,7 @@ use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\UnixShell; use StaticPHP\Runtime\Shell\UnixShell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
@@ -40,7 +41,7 @@ class UnixCMakeExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package, ?PackageInstaller $installer = null) public function __construct(protected LibraryPackage|ToolPackage $package, ?PackageInstaller $installer = null)
{ {
parent::__construct($package); parent::__construct($package);
if ($installer !== null) { if ($installer !== null) {

View File

@@ -9,6 +9,7 @@ use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\WindowsCmd; use StaticPHP\Runtime\Shell\WindowsCmd;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
@@ -35,7 +36,7 @@ class WindowsCMakeExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package) public function __construct(protected LibraryPackage|ToolPackage $package)
{ {
parent::__construct($this->package); parent::__construct($this->package);
$this->builder = ApplicationContext::get(PackageBuilder::class); $this->builder = ApplicationContext::get(PackageBuilder::class);

View File

@@ -6,6 +6,7 @@ namespace StaticPHP\Runtime\Shell;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use ZM\Logger\ConsoleColor; use ZM\Logger\ConsoleColor;
@@ -40,9 +41,9 @@ class UnixShell extends Shell
/** /**
* Init the environment variable that common build will be used. * Init the environment variable that common build will be used.
* *
* @param LibraryPackage $library Library package * @param LibraryPackage|ToolPackage $library Library or tool package
*/ */
public function initializeEnv(LibraryPackage $library): UnixShell public function initializeEnv(LibraryPackage|ToolPackage $library): UnixShell
{ {
$this->setEnv([ $this->setEnv([
'CFLAGS' => $library->getLibExtraCFlags(), 'CFLAGS' => $library->getLibExtraCFlags(),

View File

@@ -174,7 +174,7 @@ class FileSystem
public static function convertWinPathToMinGW(string $path): string public static function convertWinPathToMinGW(string $path): string
{ {
if (preg_match('/^[A-Za-z]:/', $path)) { if (preg_match('/^[A-Za-z]:/', $path)) {
$path = '/' . strtolower($path[0]) . '/' . str_replace('\\', '/', substr($path, 2)); $path = '/' . strtolower($path[0]) . '/' . str_replace('\\', '/', ltrim(substr($path, 2), '\/'));
} }
return $path; return $path;
} }

View File

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace StaticPHP\Util; namespace StaticPHP\Util;
use StaticPHP\DI\ApplicationContext;
use Symfony\Component\Console\Helper\ProgressIndicator; use Symfony\Component\Console\Helper\ProgressIndicator;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\ConsoleOutput;
@@ -15,10 +14,31 @@ class InteractiveTerm
{ {
private static ?ProgressIndicator $indicator = null; private static ?ProgressIndicator $indicator = null;
private static ?OutputInterface $output = null;
private static ?bool $noAnsi = null;
/**
* Initialize with a real Symfony Console input/output (called from ConsoleApplication::doRun()).
* After this call, all output goes through the configured Console, and noAnsi reflects
* the user's --no-ansi flag.
*/
public static function init(InputInterface $input, OutputInterface $output): void
{
self::$output = $output;
try {
self::$noAnsi = (bool) $input->getOption('no-ansi');
} catch (\InvalidArgumentException) {
// Symfony hasn't bound the application-level input definition yet
// (e.g. ArgvInput passed directly to doRun() on some versions).
self::$noAnsi = false;
}
}
public static function notice(string $message, bool $indent = false): void public static function notice(string $message, bool $indent = false): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
logger()->notice(strip_ansi_colors($message)); logger()->notice(strip_ansi_colors($message));
} else { } else {
@@ -29,8 +49,8 @@ class InteractiveTerm
public static function success(string $message, bool $indent = false): void public static function success(string $message, bool $indent = false): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message)); logger()->info(strip_ansi_colors($message));
} else { } else {
@@ -41,8 +61,8 @@ class InteractiveTerm
public static function plain(string $message, string $level = 'info'): void public static function plain(string $message, string $level = 'info'): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
match ($level) { match ($level) {
'debug' => logger()->debug(strip_ansi_colors($message)), 'debug' => logger()->debug(strip_ansi_colors($message)),
@@ -59,8 +79,8 @@ class InteractiveTerm
public static function info(string $message): void public static function info(string $message): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if (!$output->isVerbose()) { if (!$output->isVerbose()) {
$output->writeln(($no_ansi ? 'strip_ansi_colors' : 'strval')(ConsoleColor::green('▶ ') . $message)); $output->writeln(($no_ansi ? 'strip_ansi_colors' : 'strval')(ConsoleColor::green('▶ ') . $message));
} }
@@ -69,8 +89,8 @@ class InteractiveTerm
public static function error(string $message, bool $indent = true): void public static function error(string $message, bool $indent = true): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
logger()->error(strip_ansi_colors($message)); logger()->error(strip_ansi_colors($message));
} else { } else {
@@ -86,16 +106,16 @@ class InteractiveTerm
public static function setMessage(string $message): void public static function setMessage(string $message): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
self::$indicator?->setMessage(($no_ansi ? 'strip_ansi_colors' : 'strval')($message)); self::$indicator?->setMessage(($no_ansi ? 'strip_ansi_colors' : 'strval')($message));
logger()->debug(strip_ansi_colors($message)); logger()->debug(strip_ansi_colors($message));
} }
public static function finish(string $message, bool $status = true): void public static function finish(string $message, bool $status = true): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$message = $no_ansi ? strip_ansi_colors($message) : $message; $message = $no_ansi ? strip_ansi_colors($message) : $message;
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
if ($status) { if ($status) {
logger()->info($message); logger()->info($message);
@@ -116,8 +136,8 @@ class InteractiveTerm
public static function indicateProgress(string $message): void public static function indicateProgress(string $message): void
{ {
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi'); $no_ansi = self::noAnsi();
$output = ApplicationContext::get(OutputInterface::class); $output = self::output();
if ($output->isVerbose()) { if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message)); logger()->info(strip_ansi_colors($message));
return; return;
@@ -131,11 +151,41 @@ class InteractiveTerm
logger()->debug(strip_ansi_colors($message)); logger()->debug(strip_ansi_colors($message));
// if no ansi, use a dot instead of spinner // if no ansi, use a dot instead of spinner
if ($no_ansi) { if ($no_ansi) {
self::$indicator = new ProgressIndicator(ApplicationContext::get(OutputInterface::class), 'verbose', 100, [' •', ' •']); self::$indicator = new ProgressIndicator(self::output(), 'verbose', 100, [' •', ' •']);
self::$indicator->start(strip_ansi_colors($message)); self::$indicator->start(strip_ansi_colors($message));
return; return;
} }
self::$indicator = new ProgressIndicator(ApplicationContext::get(OutputInterface::class), 'verbose', 100, [' ⠏', ' ⠛', ' ⠹', ' ⢸', ' ⣰', ' ⣤', ' ⣆', ' ⡇']); self::$indicator = new ProgressIndicator(self::output(), 'verbose', 100, [' ⠏', ' ⠛', ' ⠹', ' ⢸', ' ⣰', ' ⣤', ' ⣆', ' ⡇']);
self::$indicator->start($message); self::$indicator->start($message);
} }
/**
* Lazy default initialization used when init() was never called (early-boot errors,
* tests, programmatic usage). Creates a plain STDERR output so error messages are
* visible without depending on the Symfony Console lifecycle.
*/
private static function initDefault(): void
{
if (self::$output !== null) {
return;
}
self::$output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, false);
self::$noAnsi = false;
}
private static function noAnsi(): bool
{
if (self::$output === null) {
self::initDefault();
}
return self::$noAnsi ?? false;
}
private static function output(): OutputInterface
{
if (self::$output === null) {
self::initDefault();
}
return self::$output;
}
} }

View File

@@ -45,12 +45,16 @@ class SourcePatcher
file_put_contents(SOURCE_PATH . "/{$filename}", file_get_contents($patch_file)); file_put_contents(SOURCE_PATH . "/{$filename}", file_get_contents($patch_file));
$patch_str = FileSystem::convertPath(SOURCE_PATH . "/{$filename}"); $patch_str = FileSystem::convertPath(SOURCE_PATH . "/{$filename}");
} }
$patch_cwd = FileSystem::convertPath($cwd);
$patch_arg = $patch_str;
// Detect if patch is already applied (reverse detection) // Detect if patch is already applied (reverse detection)
$detect_reverse = !$reverse; $detect_reverse = !$reverse;
$detect_cmd = 'cd ' . escapeshellarg($cwd) . ' && ' $cd_cmd = (PHP_OS_FAMILY === 'Windows' ? 'cd /d ' : 'cd ') . escapeshellarg($patch_cwd);
. (PHP_OS_FAMILY === 'Windows' ? 'type' : 'cat') . ' ' . escapeshellarg($patch_str) $detect_cmd = $cd_cmd
. ' | patch --dry-run -p1 -s -f ' . ($detect_reverse ? '-R' : '') . ' && patch --binary --dry-run -p1 -s -f'
. ($detect_reverse ? ' -R' : '')
. ' < ' . escapeshellarg($patch_arg)
. ' > ' . (PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null') . ' 2>&1'; . ' > ' . (PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null') . ' 2>&1';
exec($detect_cmd, $output, $detect_status); exec($detect_cmd, $output, $detect_status);
@@ -60,9 +64,10 @@ class SourcePatcher
} }
// Apply patch // Apply patch
$apply_cmd = 'cd ' . escapeshellarg($cwd) . ' && ' $apply_cmd = $cd_cmd
. (PHP_OS_FAMILY === 'Windows' ? 'type' : 'cat') . ' ' . escapeshellarg($patch_str) . ' && patch --binary -p1'
. ' | patch -p1 ' . ($reverse ? '-R' : ''); . ($reverse ? ' -R' : '')
. ' < ' . escapeshellarg($patch_arg);
exec($apply_cmd, $apply_output, $apply_status); exec($apply_cmd, $apply_output, $apply_status);
if ($apply_status !== 0) { if ($apply_status !== 0) {

View File

@@ -1,7 +1,7 @@
diff --git a/library/libxlsxwriter/third_party/md5/md5.c b/library/libxlsxwriter/third_party/md5/md5.c diff --git a/library/libxlsx/third_party/md5/md5.c b/library/libxlsx/third_party/md5/md5.c
index b235e17..ce98e18 100644 index b235e17..ce98e18 100644
--- a/library/libxlsxwriter/third_party/md5/md5.c --- a/library/libxlsx/third_party/md5/md5.c
+++ b/library/libxlsxwriter/third_party/md5/md5.c +++ b/library/libxlsx/third_party/md5/md5.c
@@ -35,7 +35,11 @@ @@ -35,7 +35,11 @@
* compile-time configuration. * compile-time configuration.
*/ */
@@ -15,10 +15,10 @@ index b235e17..ce98e18 100644
#include <string.h> #include <string.h>
diff --git a/library/libxlsxwriter/third_party/md5/md5.h b/library/libxlsxwriter/third_party/md5/md5.h diff --git a/library/libxlsx/third_party/md5/md5.h b/library/libxlsx/third_party/md5/md5.h
index 2da44bf..3cb0a98 100644 index 2da44bf..3cb0a98 100644
--- a/library/libxlsxwriter/third_party/md5/md5.h --- a/library/libxlsx/third_party/md5/md5.h
+++ b/library/libxlsxwriter/third_party/md5/md5.h +++ b/library/libxlsx/third_party/md5/md5.h
@@ -23,7 +23,7 @@ @@ -23,7 +23,7 @@
* See md5.c for more information. * See md5.c for more information.
*/ */