Обновление проектов на ядре: точки расширения, версия, Core\Updater и core:* команды

Событие http.responded и слоты каркаса (layout.head/layout.topbar) — чтобы
частым нуждам проекта не приходилось патчить framework/ напрямую. Версия
ядра (framework/VERSION, мажор.минор.патч) и core:bump — вручную, не хуком
на каждый коммит: версия размечает точку для синхронизации, а не сами
коммиты. Core\Updater поверх контрольных сумм (framework/.checksums.json)
вместо археологии по git log: core:check/diff/sync — что взять безопасно,
что мержить руками, что ядро удалило и не сломает ли это app/config/routes/
resources/views. core:latest и --remote у diff/sync — версия, changelog и
файлы ядра прямо с GitHub/Gitea через HttpClient, без git clone.

На живой симуляции переноса поймал и починил два реальных бага: markSynced()
не давал недомерженному патчу тихо стать новой доверенной базой, а
brokenReferences() не путает магическую ::class и унаследованные от Model
методы с настоящей поломкой.
This commit is contained in:
rsgrinko committed 2026-09-18 20:13:20 +03:00
1 parent 887575b375
commit c96150b48a
25 files changed
+1904 -153

No files matched your search

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
/**
* бампает версию ядра — руками, не хуком на каждый коммит: версия размечает
* точку, к которой имеет смысл синхронизировать другой проект, не коммиты.
*/
final class CoreBumpCommand extends Command
{
public function name(): string
{
return 'core:bump';
}
public function description(): string
{
return 'бампает версию ядра (по умолчанию — патч) и дописывает docs/CHANGELOG.md';
}
public function usage(): string
{
return 'core:bump [patch|minor|major] [--note="..."] [--breaking]';
}
public function run(): int
{
$level = $this->arg(0, 'patch');
if (!in_array($level, ['patch', 'minor', 'major'], true)) {
$this->fail('Уровень — patch, minor или major, не "' . $level . '"');
return 1;
}
$updater = new Updater(APP_ROOT);
$before = $updater->localVersion();
$note = (string) $this->option('note', '');
$after = $updater->bump($level, $note, $this->hasOption('breaking'));
$this->ok($before . ' → ' . $after);
if ($note === '') {
$this->line('Запись в docs/CHANGELOG.md не добавлена — не передан --note');
}
return 0;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
/**
* проверяет framework/ на локальные правки в обход правила «ядро не патчим».
*/
final class CoreCheckCommand extends Command
{
public function name(): string
{
return 'core:check';
}
public function description(): string
{
return 'сверяет framework/ со своей последней синхронизацией; --baseline фиксирует текущее состояние как доверенное';
}
public function usage(): string
{
return 'core:check [--baseline]';
}
public function run(): int
{
$updater = new Updater(APP_ROOT);
if ($this->hasOption('baseline')) {
$updater->saveBaseline();
$this->ok('Текущее состояние framework/ сохранено как доверенное (framework/.checksums.json)');
return 0;
}
if ($updater->storedBaseline() === []) {
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
return 1;
}
$changed = $updater->check();
if ($changed === []) {
$this->ok('framework/ не менялся с последней синхронизации');
return 0;
}
$this->fail('Локально изменены (в обход правила «не трогать ядро руками»):');
foreach ($changed as $path) {
$this->line(' ' . $path);
}
return 1;
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
/**
* что можно взять из ядра, что требует ручного слияния, что ядро больше не
* содержит — только смотрит, ничего не пишет.
*/
final class CoreDiffCommand extends Command
{
public function name(): string
{
return 'core:diff';
}
public function description(): string
{
return 'план обновления ядра: что скопировать, что мержить руками, что удалено (--path=<каталог> или --remote)';
}
public function usage(): string
{
return 'core:diff --path=<каталог с ядром рядом> | --remote';
}
public function run(): int
{
$updater = new Updater(APP_ROOT);
if ($updater->storedBaseline() === []) {
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
return 1;
}
$path = $this->option('path', '');
$temporary = null;
if ($path === null || $path === '') {
if (!$this->hasOption('remote')) {
$this->fail('Нужен --path=<каталог> или --remote');
return 1;
}
try {
$path = $temporary = $updater->downloadRemote(
(string) Config::get('core.repo'),
(string) Config::get('core.branch')
);
} catch (ProtonException $e) {
$this->fail($e->getMessage());
return 1;
}
}
$report = $updater->diff($path);
if ($temporary !== null) {
$updater->cleanupRemote($temporary);
}
$this->printReport($report);
return 0;
}
/**
* @param array{version_local: string, version_core: string, safe: array<int, string>, manual: array<int, string>, removed: array<int, string>, broken: array<string, array<int, string>>} $report
*/
private function printReport(array $report): void
{
$this->line('Ядро сейчас: ' . $report['version_core'] . ' (у вас: ' . $report['version_local'] . ')');
$this->line();
$this->line('Можно взять безопасно:');
$this->printList($report['safe'], 'пусто');
$this->line();
$this->line('Требуют ручного слияния:');
$this->printList($report['manual'], 'пусто');
$this->line();
$this->line('Ядро больше не содержит:');
$this->printList($report['removed'], 'пусто');
if ($report['broken'] !== []) {
$this->line();
$this->line('Ссылки в вашем коде, которые могут сломаться после sync:');
foreach ($report['broken'] as $symbol => $locations) {
$this->line(' ' . $symbol);
foreach ($locations as $location) {
$this->line(' ' . $location);
}
}
}
}
/**
* @param array<int, string> $items
*/
private function printList(array $items, string $whenEmpty): void
{
if ($items === []) {
$this->line(' — (' . $whenEmpty . ')');
return;
}
foreach ($items as $item) {
$this->line(' ' . $item);
}
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
use Rsgrinko\Proton\Support\Config;
/**
* версия и changelog ядра прямо из репозитория — два GET-запроса, без
* авторизации и без похода в API (см. docs/CORE_UPDATES.md).
*/
final class CoreLatestCommand extends Command
{
public function name(): string
{
return 'core:latest';
}
public function description(): string
{
return 'версия и changelog ядра из PROTON_CORE_REPO — с чем сравнить свою';
}
public function run(): int
{
$repo = (string) Config::get('core.repo');
$branch = (string) Config::get('core.branch');
$updater = new Updater(APP_ROOT);
$local = $updater->localVersion();
$remote = $updater->remoteVersion($repo, $branch);
if ($remote === '') {
$this->fail('Не удалось прочитать версию ядра из ' . $repo . '@' . $branch);
return 1;
}
$this->line('У вас: ' . $local);
$this->line('В ' . $repo . '@' . $branch . ': ' . $remote);
$cmp = version_compare($remote, $local);
if ($cmp <= 0) {
$this->ok('Вы на актуальной версии или свежее.');
return 0;
}
$this->line();
$changelog = Updater::changelogSince($updater->remoteChangelog($repo, $branch), $local);
if ($changelog !== '') {
$this->line($changelog);
} else {
$this->line('Отстаёте, но docs/CHANGELOG.md в ядре не прочитать или в нём нет записей новее вашей версии.');
}
return 0;
}
}
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
/**
* копирует из ядра то, что безопасно копировать. Без --apply — тот же план,
* что у core:diff, ничего не пишется: цена ошибки здесь выше, чем у migrate.
*/
final class CoreSyncCommand extends Command
{
public function name(): string
{
return 'core:sync';
}
public function description(): string
{
return 'копирует безопасную часть обновления ядра; без --apply — только план (--path=<каталог> или --remote)';
}
public function usage(): string
{
return 'core:sync --path=<каталог с ядром рядом> | --remote [--apply]';
}
public function run(): int
{
$updater = new Updater(APP_ROOT);
if ($updater->storedBaseline() === []) {
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
return 1;
}
$path = $this->option('path', '');
$temporary = null;
if ($path === null || $path === '') {
if (!$this->hasOption('remote')) {
$this->fail('Нужен --path=<каталог> или --remote');
return 1;
}
try {
$path = $temporary = $updater->downloadRemote(
(string) Config::get('core.repo'),
(string) Config::get('core.branch')
);
} catch (ProtonException $e) {
$this->fail($e->getMessage());
return 1;
}
}
$report = $updater->diff($path);
$apply = $this->hasOption('apply');
if (!$apply) {
$this->line('Только план — для записи добавьте --apply. Что было бы скопировано:');
$this->printList($report['safe']);
} else {
$copied = $updater->copyFiles($path, $report['safe']);
$updater->markSynced($copied);
$this->ok('Скопировано файлов: ' . count($copied));
$this->printList($copied);
}
if ($report['manual'] !== []) {
$this->line();
$this->line('Требуют ручного слияния (не тронуты):');
$this->printList($report['manual']);
}
if ($report['broken'] !== []) {
$this->line();
$this->line('Возможно сломается в вашем коде — проверьте после слияния:');
foreach (array_keys($report['broken']) as $symbol) {
$this->line(' ' . $symbol);
}
}
if ($temporary !== null) {
$updater->cleanupRemote($temporary);
}
if ($apply) {
$this->line();
$this->line('Дальше: php bin/proton test, затем php bin/proton core:bump, когда список ручного слияния разобран.');
}
return 0;
}
/**
* @param array<int, string> $items
*/
private function printList(array $items): void
{
if ($items === []) {
$this->line(' — (пусто)');
return;
}
foreach ($items as $item) {
$this->line(' ' . $item);
}
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Core\Updater;
/**
* версия ядра, на которой сидит проект.
*/
final class CoreVersionCommand extends Command
{
public function name(): string
{
return 'core:version';
}
public function description(): string
{
return 'версия ядра, на которой сидит проект (framework/VERSION)';
}
public function run(): int
{
$this->line((new Updater(APP_ROOT))->localVersion());
return 0;
}
}