Files
speedBB/app/Console/Commands/VersionFetch.php
tracer 16e0444fa3
All checks were successful
CI/CD Pipeline / deploy (push) Successful in 24s
CI/CD Pipeline / promote_stable (push) Successful in 2s
modified version handling
2026-02-24 19:29:04 +01:00

132 lines
3.3 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Setting;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
class VersionFetch extends Command
{
protected $signature = 'version:fetch';
protected $description = 'Sync version/build metadata into settings using composer.json version and git build count.';
public function handle(): int
{
$version = $this->resolveComposerVersion();
$build = $this->resolveBuildCount();
if ($version === null) {
$this->error('Unable to determine version from composer.json.');
return self::FAILURE;
}
if ($build === null) {
$this->error('Unable to determine build number from git.');
return self::FAILURE;
}
Setting::updateOrCreate(
['key' => 'version'],
['value' => $version],
);
Setting::updateOrCreate(
['key' => 'build'],
['value' => (string) $build],
);
if (!$this->syncComposerBuild($build)) {
$this->error('Failed to sync version/build to composer.json.');
return self::FAILURE;
}
$this->info("Version/build synced: {$version} (build {$build}).");
return self::SUCCESS;
}
private function resolveComposerVersion(): ?string
{
$composerPath = base_path('composer.json');
if (!is_file($composerPath) || !is_readable($composerPath)) {
return null;
}
$raw = file_get_contents($composerPath);
if ($raw === false) {
return null;
}
$data = json_decode($raw, true);
if (!is_array($data)) {
return null;
}
$version = trim((string) ($data['version'] ?? ''));
if ($version === '') {
return null;
}
if (!preg_match('/^\d+\.\d+(?:\.\d+)?(?:[-._][0-9A-Za-z.-]+)?$/', $version)) {
return null;
}
return $version;
}
private function resolveBuildCount(): ?int
{
$commands = [
['git', 'rev-list', '--count', 'master'],
['git', 'rev-list', '--count', 'HEAD'],
];
foreach ($commands as $command) {
$process = new Process($command, base_path());
$process->run();
if ($process->isSuccessful()) {
$output = trim($process->getOutput());
if (is_numeric($output)) {
return (int) $output;
}
}
}
return null;
}
private function syncComposerBuild(int $build): bool
{
$composerPath = base_path('composer.json');
if (!is_file($composerPath) || !is_readable($composerPath)) {
return false;
}
$raw = file_get_contents($composerPath);
if ($raw === false) {
return false;
}
$data = json_decode($raw, true);
if (!is_array($data)) {
return false;
}
$data['build'] = (string) $build;
$encoded = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($encoded === false) {
return false;
}
$encoded .= "\n";
return file_put_contents($composerPath, $encoded) !== false;
}
}