feat: add --installed flag to check-update, improve CLI and InteractiveTerm

- Add --installed option to check-update command to compare against on-disk version (tool packages)
- Support use_installed parameter in ArtifactDownloader::checkUpdate/checkUpdates
- Add -y shorthand for --auto-fix in doctor command
- Hook InteractiveTerm::init() in ConsoleApplication::doRun() to properly inject Symfony input/output
This commit is contained in:
crazywhalecc
2026-07-06 15:10:52 +08:00
parent dd1e70a394
commit d9c41a73da
5 changed files with 122 additions and 34 deletions

View File

@@ -26,6 +26,7 @@ use StaticPHP\Exception\DownloaderException;
use StaticPHP\Exception\ExecutionException;
use StaticPHP\Exception\ValidationException;
use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\ToolVersionRegistry;
use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Runtime\Shell\Shell;
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);
if ($artifact === null) {
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) {
[$first, $second] = $prefer_source
? [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 $bare Check without requiring artifact to be downloaded first
* @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
*/
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) {
return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult);
return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult, $use_installed);
}
$results = [];
foreach ($artifact_names as $name) {
$result = $this->checkUpdate($name, $prefer_source, $bare);
$result = $this->checkUpdate($name, $prefer_source, $bare, $use_installed);
$results[$name] = $result;
if ($onResult !== null) {
($onResult)($name, $result);
@@ -436,7 +458,7 @@ class ArtifactDownloader
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 = [];
$fiber_pool = [];
@@ -451,8 +473,8 @@ class ArtifactDownloader
// fill pool
while (count($fiber_pool) < $this->parallel && !empty($remaining)) {
$name = array_shift($remaining);
$fiber = new \Fiber(function () use ($name, $prefer_source, $bare) {
return [$name, $this->checkUpdate($name, $prefer_source, $bare)];
$fiber = new \Fiber(function () use ($name, $prefer_source, $bare, $use_installed) {
return [$name, $this->checkUpdate($name, $prefer_source, $bare, $use_installed)];
});
$fiber->start();
$fiber_pool[$name] = $fiber;
@@ -491,12 +513,12 @@ class ArtifactDownloader
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) {
return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this,
'old_version' => null,
'old_version' => $old_version,
]);
}
$config = $artifact->getDownloadConfig('source');
@@ -509,16 +531,16 @@ class ArtifactDownloader
}
/** @var CheckUpdateInterface $dl */
$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
if (($callback = $artifact->getCustomBinaryCheckUpdateCallback()) !== null) {
return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this,
'old_version' => null,
'old_version' => $old_version,
]);
}
$binary_config = $artifact->getDownloadConfig('binary');
@@ -532,7 +554,7 @@ class ArtifactDownloader
}
/** @var CheckUpdateInterface $dl */
$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

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->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('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);
// --with-php option for checking updates with a specific PHP version context
@@ -45,8 +46,9 @@ class CheckUpdateCommand extends BaseCommand
try {
$downloader = new ArtifactDownloader($this->input->getOptions());
$bare = (bool) $this->getOption('bare');
$use_installed = (bool) $this->getOption('installed');
if ($this->getOption('json')) {
$results = $downloader->checkUpdates($artifacts, bare: $bare);
$results = $downloader->checkUpdates($artifacts, bare: $bare, use_installed: $use_installed);
$outputs = [];
foreach ($results as $artifact => $result) {
$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));
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) {
$this->output->writeln("Artifact <info>{$artifact}</info> does not support update checking, <comment>skipped</comment>");
} elseif (!$result->needUpdate) {

View File

@@ -13,7 +13,7 @@ class DoctorCommand extends BaseCommand
{
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

View File

@@ -32,7 +32,10 @@ use StaticPHP\Command\SPCConfigCommand;
use StaticPHP\Package\TargetPackage;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Registry\Registry;
use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleApplication extends Application
{
@@ -104,4 +107,15 @@ class ConsoleApplication extends Application
{
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

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace StaticPHP\Util;
use StaticPHP\DI\ApplicationContext;
use Symfony\Component\Console\Helper\ProgressIndicator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
@@ -15,10 +14,31 @@ class InteractiveTerm
{
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
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if ($output->isVerbose()) {
logger()->notice(strip_ansi_colors($message));
} else {
@@ -29,8 +49,8 @@ class InteractiveTerm
public static function success(string $message, bool $indent = false): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message));
} else {
@@ -41,8 +61,8 @@ class InteractiveTerm
public static function plain(string $message, string $level = 'info'): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if ($output->isVerbose()) {
match ($level) {
'debug' => logger()->debug(strip_ansi_colors($message)),
@@ -59,8 +79,8 @@ class InteractiveTerm
public static function info(string $message): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if (!$output->isVerbose()) {
$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
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if ($output->isVerbose()) {
logger()->error(strip_ansi_colors($message));
} else {
@@ -86,16 +106,16 @@ class InteractiveTerm
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));
logger()->debug(strip_ansi_colors($message));
}
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;
$output = ApplicationContext::get(OutputInterface::class);
$output = self::output();
if ($output->isVerbose()) {
if ($status) {
logger()->info($message);
@@ -116,8 +136,8 @@ class InteractiveTerm
public static function indicateProgress(string $message): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = self::noAnsi();
$output = self::output();
if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message));
return;
@@ -131,11 +151,41 @@ class InteractiveTerm
logger()->debug(strip_ansi_colors($message));
// if no ansi, use a dot instead of spinner
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));
return;
}
self::$indicator = new ProgressIndicator(ApplicationContext::get(OutputInterface::class), 'verbose', 100, [' ⠏', ' ⠛', ' ⠹', ' ⢸', ' ⣰', ' ⣤', ' ⣆', ' ⡇']);
self::$indicator = new ProgressIndicator(self::output(), 'verbose', 100, [' ⠏', ' ⠛', ' ⠹', ' ⢸', ' ⣰', ' ⣤', ' ⣆', ' ⡇']);
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;
}
}