Обновление ядра: база от ядра, core:resolve, --remote через codeload, версия при sync
This commit is contained in:
1 parent
99e1d9431c
commit
470db48bce
14 files changed
+647
-191
No files matched your search
@@ -18,7 +18,7 @@
|
||||
"framework/Backup/ShipBackupJob.php": "7c5335c364047aa112390687df851b20fa20db62854861f5efe5fb732587f017",
|
||||
"framework/Cache/Cache.php": "1c76084f0927fb5124c4a14a6abe2cec62d880152b48dcc729bfc35fc8933902",
|
||||
"framework/Comments/Comment.php": "3fb1ec10d80abfe4a0827a4cfd44c63b2cc1b89afb389ca9f571025f8e7eeae0",
|
||||
"framework/Console/Application.php": "fdc8d699b0471449b847d364d723b1269b5197e191ec16c1cacdfeb8c6e62ff4",
|
||||
"framework/Console/Application.php": "68d9fe3de51cc35c6960bfeaa7f2ca90f315bdffbaabde12d10be43c1b3d96f9",
|
||||
"framework/Console/Command.php": "449e19ad971587ed34f55a2013b9eb0032388f75ccb345c230680c44ecea123c",
|
||||
"framework/Console/Commands/AppKeyCommand.php": "ad39058182e7da24283b75cf99528f31f0e6a1aa5b0015683dc1858c4aee75f4",
|
||||
"framework/Console/Commands/BackupCreateCommand.php": "6932450ceabf5ae45d72a25d33874a22365199d491d980a3a3664850e9a06f5e",
|
||||
@@ -27,10 +27,11 @@
|
||||
"framework/Console/Commands/BackupShipCommand.php": "701b6bd17c41939152c15d0f682fbea73ff7bb4a31037a75c5e056a2b2b36b20",
|
||||
"framework/Console/Commands/CacheClearCommand.php": "82539fb29a78e9933d9aee3d8f6839b12fbe3010e349bed1684894565200ba38",
|
||||
"framework/Console/Commands/CoreBumpCommand.php": "290760072c3f9e89b2be62cf309c8957ede0cbc97f76e45e2c8015ce9424bc89",
|
||||
"framework/Console/Commands/CoreCheckCommand.php": "0f5556a9e997c96f0a3ebc13e458ce5a6ea4c115c6b74cfcb5da533db707b866",
|
||||
"framework/Console/Commands/CoreDiffCommand.php": "088353b584cfe7987098eeaa0229bc84f9ab40fc5a05548ebbd946b38ed63124",
|
||||
"framework/Console/Commands/CoreCheckCommand.php": "4052f8a467ce09a787a798ac1e2ada1f478d9f555a3ecbe2a4ba1166d9f826d0",
|
||||
"framework/Console/Commands/CoreDiffCommand.php": "a3042630ad6ce311676e974aa21556d477691dc97afe2945e57b553d2e54e091",
|
||||
"framework/Console/Commands/CoreLatestCommand.php": "09b5158fcc50854a281d337056af5d3c22984fb81e66b309688a98dd5fe3e70f",
|
||||
"framework/Console/Commands/CoreSyncCommand.php": "8e94d3a473c54273abfa4db46b884533c36762b00354cea97ad8beef88f87d50",
|
||||
"framework/Console/Commands/CoreResolveCommand.php": "6b72a37ec4fcf2e7c8c78b2fcc3e75f2b31598ec3ca53bebd022bfc94d6897fa",
|
||||
"framework/Console/Commands/CoreSyncCommand.php": "0b9296a91f480c1b22f0efc11131d2d7c3a583e04f7dbf55b6936cfafdc93abd",
|
||||
"framework/Console/Commands/CoreVersionCommand.php": "52320c2ed0fb05e2ba7eeee6706fddc1ad67ec2d6cddd17ef9eb8148c208080e",
|
||||
"framework/Console/Commands/DownCommand.php": "a55f0e5574167497a7bea0484f617a7da8097c70e9c998581a72bc30c593891a",
|
||||
"framework/Console/Commands/FilesOrphansCommand.php": "bb770d53a4566f0cb7d8359798b8cb5f4ed54589e1d6d034d91e6d7ec2ce4e5f",
|
||||
@@ -70,11 +71,12 @@
|
||||
"framework/Console/Commands/UserDeleteCommand.php": "2ebf37654e31451c9cf53fc07de4f8497b44de4fc6a5ebf24362a8d624dce6ae",
|
||||
"framework/Console/Commands/UserListCommand.php": "f15db6058c9732e31b3551f9a58d9dc83ca2e846d93e6d9a9a5f0948c09a5822",
|
||||
"framework/Console/Commands/UserPasswordCommand.php": "5dad76885c0fed8bd729eb9229dd66346e7f14e0c1933645174f627198d60415",
|
||||
"framework/Console/Commands/UsesCoreSource.php": "e60ee69c26ab38156d1ff68e3b46f150f1099fc90c5f6949a3ad1f70096615e6",
|
||||
"framework/Console/Commands/WebhookListCommand.php": "51c2119666c2cf8af57a66606580748a9b28ed8c0e52c47aa7bb1dca90bbdf4d",
|
||||
"framework/Console/Commands/WebhookTestCommand.php": "925abbb8310176cb7102f619adbdb581be761ced2315eb9517019d56d5780881",
|
||||
"framework/Console/Commands/WorkerCommand.php": "6dfba8c8aa752a8420bd78a2df425214b8e632f09cd461b0a541f76849dcf94a",
|
||||
"framework/Console/Commands/WorkerRestartCommand.php": "b877813d5fe43703e12f11a0ccde3f326d75aa66d44ed70a51e3680e9e2ee266",
|
||||
"framework/Core/Updater.php": "dd815e25a902175257deaf2e6e125133bceddbb45774df6ac7d155b0384c4f23",
|
||||
"framework/Core/Updater.php": "47532d4cef3c2bcf17db2adffc3964b3a402d6974e9349791249a53d7442d77f",
|
||||
"framework/Database/Connection.php": "b349a7aa5217c98af77eddac9de7ceeef744af980eda02b989d17837a16bfe4b",
|
||||
"framework/Database/DatabaseException.php": "d43ac6cf2a17680cde24923676e0a91dfddefa645cc97c129dd44c64960e41df",
|
||||
"framework/Database/Lock.php": "b2b793af798d59b9fcc5bcdd2db09ea9645796e658a0fb6c6000539484283f3e",
|
||||
|
||||
@@ -90,6 +90,7 @@ final class Application
|
||||
Commands\CoreCheckCommand::class,
|
||||
Commands\CoreDiffCommand::class,
|
||||
Commands\CoreSyncCommand::class,
|
||||
Commands\CoreResolveCommand::class,
|
||||
Commands\CoreLatestCommand::class,
|
||||
],
|
||||
];
|
||||
|
||||
@@ -8,10 +8,12 @@ use Rsgrinko\Proton\Console\Command;
|
||||
use Rsgrinko\Proton\Core\Updater;
|
||||
|
||||
/**
|
||||
* проверяет framework/ на локальные правки в обход правила «ядро не патчим».
|
||||
* показывает, чем framework/ отличается от ядра последней синхронизации.
|
||||
*/
|
||||
final class CoreCheckCommand extends Command
|
||||
{
|
||||
use UsesCoreSource;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'core:check';
|
||||
@@ -19,12 +21,12 @@ final class CoreCheckCommand extends Command
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'сверяет framework/ со своей последней синхронизацией; --baseline фиксирует текущее состояние как доверенное';
|
||||
return 'сверяет framework/ с ядром последней синхронизации; --baseline заводит базу (от ядра через --path/--remote)';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return 'core:check [--baseline]';
|
||||
return 'core:check [--baseline [--path=<ядро той версии, от которой заведён проект> | --remote]]';
|
||||
}
|
||||
|
||||
public function run(): int
|
||||
@@ -32,14 +34,11 @@ final class CoreCheckCommand extends Command
|
||||
$updater = new Updater(APP_ROOT);
|
||||
|
||||
if ($this->hasOption('baseline')) {
|
||||
$updater->saveBaseline();
|
||||
$this->ok('Текущее состояние framework/ сохранено как доверенное (framework/.checksums.json)');
|
||||
|
||||
return 0;
|
||||
return $this->baseline($updater);
|
||||
}
|
||||
|
||||
if ($updater->storedBaseline() === []) {
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline --path=<ядро>');
|
||||
|
||||
return 1;
|
||||
}
|
||||
@@ -47,12 +46,12 @@ final class CoreCheckCommand extends Command
|
||||
$changed = $updater->check();
|
||||
|
||||
if ($changed === []) {
|
||||
$this->ok('framework/ не менялся с последней синхронизации');
|
||||
$this->ok('framework/ совпадает с ядром последней синхронизации');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
$this->fail('Локально изменены (в обход правила «не трогать ядро руками»):');
|
||||
$this->fail('Отличаются от ядра (свои правки или неразобранное ручное слияние):');
|
||||
|
||||
foreach ($changed as $path) {
|
||||
$this->line(' ' . $path);
|
||||
@@ -60,4 +59,31 @@ final class CoreCheckCommand extends Command
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private function baseline(Updater $updater): int
|
||||
{
|
||||
if (!$this->hasOption('path') && !$this->hasOption('remote')) {
|
||||
$updater->saveBaseline();
|
||||
$this->ok('База — текущий framework/ (framework/.checksums.json)');
|
||||
$this->line('Верно, только если в framework/ нет своих правок: иначе они станут невидимы');
|
||||
$this->line('и следующее обновление ядра их затрёт. С правками — --path=<ядро той же версии>.');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
$path = $this->coreSource($updater);
|
||||
|
||||
if ($path === null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
try {
|
||||
$updater->saveBaseline($path);
|
||||
$this->ok('База — ядро ' . $updater->readVersion($path) . ' (framework/.checksums.json)');
|
||||
} finally {
|
||||
$this->releaseCoreSource($updater);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ 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;
|
||||
|
||||
/**
|
||||
* что можно взять из ядра, что требует ручного слияния, что ядро больше не
|
||||
@@ -15,6 +13,8 @@ use Rsgrinko\Proton\Support\ProtonException;
|
||||
*/
|
||||
final class CoreDiffCommand extends Command
|
||||
{
|
||||
use UsesCoreSource;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'core:diff';
|
||||
@@ -35,37 +35,21 @@ final class CoreDiffCommand extends Command
|
||||
$updater = new Updater(APP_ROOT);
|
||||
|
||||
if ($updater->storedBaseline() === []) {
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline --path=<ядро>');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$path = $this->option('path', '');
|
||||
$temporary = null;
|
||||
$path = $this->coreSource($updater);
|
||||
|
||||
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;
|
||||
}
|
||||
if ($path === null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
$report = $updater->diff($path);
|
||||
|
||||
if ($temporary !== null) {
|
||||
$updater->cleanupRemote($temporary);
|
||||
try {
|
||||
$report = $updater->diff($path);
|
||||
} finally {
|
||||
$this->releaseCoreSource($updater);
|
||||
}
|
||||
|
||||
$this->printReport($report);
|
||||
@@ -88,6 +72,10 @@ final class CoreDiffCommand extends Command
|
||||
$this->line('Требуют ручного слияния:');
|
||||
$this->printList($report['manual'], 'пусто');
|
||||
|
||||
if ($report['manual'] !== []) {
|
||||
$this->line(' слили руками — php bin/proton core:resolve <файл> с тем же --path/--remote');
|
||||
}
|
||||
|
||||
$this->line();
|
||||
$this->line('Ядро больше не содержит:');
|
||||
$this->printList($report['removed'], 'пусто');
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Console\Commands;
|
||||
|
||||
use Rsgrinko\Proton\Console\Command;
|
||||
use Rsgrinko\Proton\Core\Updater;
|
||||
|
||||
/**
|
||||
* отмечает файлы из ручного слияния разобранными: предком для них становится
|
||||
* версия ядра, и diff перестаёт их показывать, пока ядро не поменяет файл снова.
|
||||
*/
|
||||
final class CoreResolveCommand extends Command
|
||||
{
|
||||
use UsesCoreSource;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'core:resolve';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'отмечает файлы ручного слияния разобранными (--path=<каталог> или --remote)';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return 'core:resolve <файл> [<файл>...] --path=<каталог с ядром рядом> | --remote';
|
||||
}
|
||||
|
||||
public function run(): int
|
||||
{
|
||||
$files = [];
|
||||
|
||||
for ($i = 0; $this->arg($i) !== ''; $i++) {
|
||||
$files[] = $this->arg($i);
|
||||
}
|
||||
|
||||
if ($files === []) {
|
||||
$this->fail('Укажите файлы из списка ручного слияния: core:resolve framework/Support/Csv.php --path=../proton');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$updater = new Updater(APP_ROOT);
|
||||
$path = $this->coreSource($updater);
|
||||
|
||||
if ($path === null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
try {
|
||||
$unknown = $updater->resolve($path, $files);
|
||||
|
||||
foreach ($unknown as $file) {
|
||||
$this->fail('Нет ни в ядре, ни в базе, пропущен: ' . $file);
|
||||
}
|
||||
|
||||
$manual = $updater->diff($path)['manual'];
|
||||
|
||||
if ($manual !== []) {
|
||||
$this->line('Ещё ждут ручного слияния:');
|
||||
|
||||
foreach ($manual as $file) {
|
||||
$this->line(' ' . $file);
|
||||
}
|
||||
|
||||
return $unknown === [] ? 0 : 1;
|
||||
}
|
||||
|
||||
$this->ok('Ручное слияние разобрано, версия ядра: ' . $updater->adoptVersion($path));
|
||||
$this->line('Дальше: php bin/proton test');
|
||||
|
||||
return $unknown === [] ? 0 : 1;
|
||||
} finally {
|
||||
$this->releaseCoreSource($updater);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ 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 — тот же план,
|
||||
@@ -15,6 +13,8 @@ use Rsgrinko\Proton\Support\ProtonException;
|
||||
*/
|
||||
final class CoreSyncCommand extends Command
|
||||
{
|
||||
use UsesCoreSource;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'core:sync';
|
||||
@@ -35,42 +35,34 @@ final class CoreSyncCommand extends Command
|
||||
$updater = new Updater(APP_ROOT);
|
||||
|
||||
if ($updater->storedBaseline() === []) {
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline');
|
||||
$this->fail('Доверенного состояния ещё нет — сначала: php bin/proton core:check --baseline --path=<ядро>');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$path = $this->option('path', '');
|
||||
$temporary = null;
|
||||
$path = $this->coreSource($updater);
|
||||
|
||||
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;
|
||||
}
|
||||
if ($path === null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->sync($updater, $path, $this->hasOption('apply'));
|
||||
} finally {
|
||||
$this->releaseCoreSource($updater);
|
||||
}
|
||||
}
|
||||
|
||||
private function sync(Updater $updater, string $path, bool $apply): int
|
||||
{
|
||||
$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);
|
||||
$updater->markSynced($path, $report['manual']);
|
||||
|
||||
$this->ok('Скопировано файлов: ' . count($copied));
|
||||
$this->printList($copied);
|
||||
@@ -82,6 +74,12 @@ final class CoreSyncCommand extends Command
|
||||
$this->printList($report['manual']);
|
||||
}
|
||||
|
||||
if ($report['removed'] !== []) {
|
||||
$this->line();
|
||||
$this->line('Ядро больше не содержит (не удалены, решать вам):');
|
||||
$this->printList($report['removed']);
|
||||
}
|
||||
|
||||
if ($report['broken'] !== []) {
|
||||
$this->line();
|
||||
$this->line('Возможно сломается в вашем коде — проверьте после слияния:');
|
||||
@@ -91,13 +89,18 @@ final class CoreSyncCommand extends Command
|
||||
}
|
||||
}
|
||||
|
||||
if ($temporary !== null) {
|
||||
$updater->cleanupRemote($temporary);
|
||||
if (!$apply) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ($apply) {
|
||||
$this->line();
|
||||
$this->line('Дальше: php bin/proton test, затем php bin/proton core:bump, когда список ручного слияния разобран.');
|
||||
$this->line();
|
||||
|
||||
if ($report['manual'] === []) {
|
||||
$this->ok('Версия ядра: ' . $updater->adoptVersion($path));
|
||||
$this->line('Дальше: php bin/proton test');
|
||||
} else {
|
||||
$this->line('Версия осталась ' . $updater->localVersion() . ' — станет ' . $report['version_core']
|
||||
. ', когда core:resolve отметит последний файл из ручного слияния.');
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Console\Commands;
|
||||
|
||||
use Rsgrinko\Proton\Core\Updater;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
/**
|
||||
* Откуда взять ядро для сверки: --path=<каталог> или --remote (архив ветки
|
||||
* из PROTON_CORE_REPO). Скачанное убирает releaseCoreSource() — звать его
|
||||
* из finally, иначе при ошибке в var/tmp копятся распакованные архивы.
|
||||
*/
|
||||
trait UsesCoreSource
|
||||
{
|
||||
private ?string $downloadedCore = null;
|
||||
|
||||
/** Путь к ядру или null, если причину отказа уже напечатали */
|
||||
private function coreSource(Updater $updater): ?string
|
||||
{
|
||||
$path = (string) $this->option('path', '');
|
||||
|
||||
if ($path !== '') {
|
||||
if (!is_dir(rtrim($path, '/\\') . '/framework')) {
|
||||
$this->fail('В ' . $path . ' нет каталога framework/');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
if (!$this->hasOption('remote')) {
|
||||
$this->fail('Нужен --path=<каталог> или --remote');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->downloadedCore = $updater->downloadRemote(
|
||||
(string) Config::get('core.repo'),
|
||||
(string) Config::get('core.branch')
|
||||
);
|
||||
} catch (ProtonException $e) {
|
||||
$this->fail($e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function releaseCoreSource(Updater $updater): void
|
||||
{
|
||||
if ($this->downloadedCore !== null) {
|
||||
$updater->cleanupRemote($this->downloadedCore);
|
||||
$this->downloadedCore = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+159
-55
@@ -131,12 +131,23 @@ final class Updater
|
||||
}
|
||||
|
||||
/**
|
||||
* Фиксирует нынешнее состояние framework/ как доверенное — разово, сразу
|
||||
* после того, как проект завели от ядра, или один раз сейчас задним числом.
|
||||
* База — суммы ядра, от которого проект сейчас отсчитывается (общий
|
||||
* предок для трёхсторонней сверки), а не снимок своего framework/. Без
|
||||
* $corePath берётся свой framework/ — верно только пока в нём нет правок:
|
||||
* иначе патч попадёт в базу, станет невидим, и следующая правка этого
|
||||
* файла в ядре затрёт его как «безопасная».
|
||||
*/
|
||||
public function saveBaseline(): void
|
||||
public function saveBaseline(?string $corePath = null): void
|
||||
{
|
||||
$sums = $this->checksums($this->root);
|
||||
$this->writeBaseline($this->checksums($corePath ?? $this->root));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $sums
|
||||
*/
|
||||
private function writeBaseline(array $sums): void
|
||||
{
|
||||
ksort($sums);
|
||||
|
||||
file_put_contents(
|
||||
$this->root . '/' . self::BASELINE_FILE,
|
||||
@@ -159,38 +170,92 @@ final class Updater
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновляет доверенное состояние только для перечисленных файлов — а не
|
||||
* пересчитывает всё дерево заново. Файл из списка «требует ручного
|
||||
* слияния» не копировался и своей старой доверенной суммы лишиться не
|
||||
* должен: пересчёт всего дерева тихо принял бы его текущий (патченный)
|
||||
* вид за новую базу, и следующий диф перестал бы видеть в нём патч —
|
||||
* следующее обновление ядра тогда затёрло бы его как будто «безопасный» файл.
|
||||
* После sync база становится новым ядром — кроме файлов, которые ещё
|
||||
* ждут ручного слияния. У них остаётся старый предок: иначе недомерженный
|
||||
* файл выглядел бы как «ядро его не трогало, это свой патч», и правка
|
||||
* ядра в нём потерялась бы молча. Такой файл переводит на новое ядро
|
||||
* только resolve(), когда слияние сделано.
|
||||
*
|
||||
* @param array<int, string> $paths
|
||||
* @param array<int, string> $pending diff()['manual']
|
||||
*/
|
||||
public function markSynced(array $paths): void
|
||||
public function markSynced(string $corePath, array $pending): void
|
||||
{
|
||||
$baseline = $this->storedBaseline();
|
||||
$current = $this->checksums($this->root);
|
||||
$old = $this->storedBaseline();
|
||||
$new = $this->checksums($corePath);
|
||||
$local = $this->checksums($this->root);
|
||||
|
||||
foreach ($paths as $path) {
|
||||
if (isset($current[$path])) {
|
||||
$baseline[$path] = $current[$path];
|
||||
foreach ($pending as $path) {
|
||||
if (isset($old[$path])) {
|
||||
$new[$path] = $old[$path];
|
||||
} else {
|
||||
unset($new[$path]);
|
||||
}
|
||||
}
|
||||
|
||||
ksort($baseline);
|
||||
// Удалённое ядром, но ещё лежащее у нас, держим в базе — иначе оно
|
||||
// выпадет из списка «ядро больше не содержит» раньше, чем его уберут
|
||||
foreach (array_keys($local) as $path) {
|
||||
if (!isset($new[$path]) && isset($old[$path])) {
|
||||
$new[$path] = $old[$path];
|
||||
}
|
||||
}
|
||||
|
||||
file_put_contents(
|
||||
$this->root . '/' . self::BASELINE_FILE,
|
||||
json_encode($baseline, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"
|
||||
);
|
||||
$this->writeBaseline($new);
|
||||
}
|
||||
|
||||
/**
|
||||
* Файлы framework/, изменившиеся с последней сохранённой базы, — без
|
||||
* похода к ядру вообще, чистая локальная проверка «ничего не поправили
|
||||
* в обход правила с последнего раза».
|
||||
* Отмечает файлы из ручного слияния разобранными: предком для них
|
||||
* становится версия ядра. Разница между своим файлом и ядром с этого
|
||||
* момента считается своим патчем, и следующий diff покажет файл снова,
|
||||
* только если ядро поменяет его ещё раз.
|
||||
*
|
||||
* @param array<int, string> $paths "framework/..." или путь внутри framework/
|
||||
*
|
||||
* @return array<int, string> пути, которых нет ни в ядре, ни в базе, — не тронуты
|
||||
*/
|
||||
public function resolve(string $corePath, array $paths): array
|
||||
{
|
||||
$baseline = $this->storedBaseline();
|
||||
$core = $this->checksums($corePath);
|
||||
$unknown = [];
|
||||
|
||||
foreach ($paths as $path) {
|
||||
$path = str_replace('\\', '/', ltrim($path, './\\'));
|
||||
|
||||
if (!str_starts_with($path, 'framework/')) {
|
||||
$path = 'framework/' . $path;
|
||||
}
|
||||
|
||||
if (isset($core[$path])) {
|
||||
$baseline[$path] = $core[$path];
|
||||
} elseif (isset($baseline[$path])) {
|
||||
unset($baseline[$path]); // ядро файл удалило — решение принято, предка больше нет
|
||||
} else {
|
||||
$unknown[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
$this->writeBaseline($baseline);
|
||||
|
||||
return $unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ставит себе версию ядра — только когда ручное слияние разобрано
|
||||
* целиком. Иначе версия врала бы: файлы ещё от старого ядра.
|
||||
*/
|
||||
public function adoptVersion(string $corePath): string
|
||||
{
|
||||
$version = $this->readVersion($corePath);
|
||||
|
||||
file_put_contents($this->root . '/' . self::VERSION_FILE, $version . "\n");
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Файлы framework/, отличающиеся от ядра последней синхронизации: свои
|
||||
* патчи и неразобранное ручное слияние. К ядру не ходит — сверка с базой.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
@@ -210,8 +275,10 @@ final class Updater
|
||||
}
|
||||
|
||||
/**
|
||||
* Три списка вместо одного диффа: «менялось у ядра» и «менялось у нас» —
|
||||
* два независимых вопроса, а не одна ось.
|
||||
* Трёхсторонняя сверка: база (ядро прошлой синхронизации) — общий предок,
|
||||
* «менялось в ядре» и «менялось у нас» считаются от него независимо.
|
||||
* Файл без предка, который у нас отличается от ядра, уходит в ручное
|
||||
* слияние: откуда он взялся, неизвестно, а затереть его нельзя.
|
||||
*
|
||||
* @return array{
|
||||
* version_local: string, version_core: string,
|
||||
@@ -229,29 +296,34 @@ final class Updater
|
||||
$manual = [];
|
||||
|
||||
foreach ($core as $path => $hash) {
|
||||
$ancestor = $baseline[$path] ?? null;
|
||||
|
||||
if (!isset($local[$path])) {
|
||||
$safe[] = $path; // новый файл ядра — своего аналога нет, патчить нечего
|
||||
if ($ancestor === null) {
|
||||
$safe[] = $path; // новый файл ядра
|
||||
} elseif ($ancestor !== $hash) {
|
||||
$manual[] = $path; // проект файл удалил, а ядро его с тех пор поменяло
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($local[$path] === $hash) {
|
||||
continue; // не изменилось
|
||||
if ($local[$path] === $hash || $ancestor === $hash) {
|
||||
continue; // совпадает с ядром или ядро файл не трогало — свой патч остаётся
|
||||
}
|
||||
|
||||
$patchedLocally = isset($baseline[$path]) && $baseline[$path] !== $local[$path];
|
||||
|
||||
if ($patchedLocally) {
|
||||
$manual[] = $path;
|
||||
} else {
|
||||
if ($ancestor === $local[$path]) {
|
||||
$safe[] = $path;
|
||||
} else {
|
||||
$manual[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
// Только то, что было в ядре, — свои файлы в framework/ ядро не удаляло
|
||||
$removed = [];
|
||||
|
||||
foreach ($local as $path => $hash) {
|
||||
if (!isset($core[$path])) {
|
||||
if (!isset($core[$path]) && isset($baseline[$path])) {
|
||||
$removed[] = $path;
|
||||
}
|
||||
}
|
||||
@@ -545,30 +617,49 @@ final class Updater
|
||||
*/
|
||||
public function downloadRemote(string $repo, string $branch): string
|
||||
{
|
||||
$response = (new HttpClient(30))->get($this->archiveUrl($repo, $branch));
|
||||
$url = $this->archiveUrl($repo, $branch);
|
||||
$response = (new HttpClient(30))->get($url);
|
||||
|
||||
if ($response['status'] !== 200 || $response['body'] === '') {
|
||||
throw new ProtonException('Не удалось скачать архив ядра (код ' . $response['status'] . '): ' . $this->archiveUrl($repo, $branch));
|
||||
throw new ProtonException('Не удалось скачать архив ядра (код ' . $response['status'] . '): ' . $url);
|
||||
}
|
||||
|
||||
// gzip разжимаем сами: PharData на .tar.gz пишет промежуточный файл в
|
||||
// sys_temp_dir, и если того каталога нет (частая история на Windows),
|
||||
// падает с «unable to create temporary file». Голый .tar читается на месте.
|
||||
$tar = @gzdecode($response['body']);
|
||||
|
||||
if ($tar === false) {
|
||||
throw new ProtonException('Архив ядра не разжимается как gzip: ' . $url);
|
||||
}
|
||||
|
||||
$dir = $this->root . '/var/tmp/core-sync-' . bin2hex(random_bytes(6));
|
||||
mkdir($dir, 0777, true);
|
||||
|
||||
$archive = $dir . '/core.tar.gz';
|
||||
file_put_contents($archive, $response['body']);
|
||||
$archive = $dir . '/core.tar';
|
||||
file_put_contents($archive, $tar);
|
||||
|
||||
(new \PharData($archive))->extractTo($dir);
|
||||
unlink($archive);
|
||||
try {
|
||||
(new \PharData($archive))->extractTo($dir);
|
||||
} catch (\Throwable $e) {
|
||||
$this->removeTree($dir);
|
||||
|
||||
// Архив распаковывается в подкаталог вида <repo>-<ветка>/
|
||||
$entries = array_values(array_diff(scandir($dir) ?: [], ['.', '..']));
|
||||
$extracted = $entries[0] ?? '';
|
||||
|
||||
if ($extracted === '' || !is_dir($dir . '/' . $extracted . '/framework')) {
|
||||
throw new ProtonException('Архив ядра распаковался, но framework/ внутри не нашёлся');
|
||||
throw new ProtonException('Архив ядра не распаковался: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
return $dir . '/' . $extracted;
|
||||
unlink($archive);
|
||||
|
||||
// Архив распаковывается в подкаталог вида <repo>-<ветка>/; рядом
|
||||
// может лежать служебный pax_global_header, поэтому ищем по содержимому
|
||||
foreach (array_diff(scandir($dir) ?: [], ['.', '..']) as $entry) {
|
||||
if (is_dir($dir . '/' . $entry . '/framework')) {
|
||||
return $dir . '/' . $entry;
|
||||
}
|
||||
}
|
||||
|
||||
$this->removeTree($dir);
|
||||
|
||||
throw new ProtonException('Архив ядра распаковался, но framework/ внутри не нашёлся');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -584,8 +675,13 @@ final class Updater
|
||||
return;
|
||||
}
|
||||
|
||||
$this->removeTree($tmp);
|
||||
}
|
||||
|
||||
private function removeTree(string $dir): void
|
||||
{
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
|
||||
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
|
||||
@@ -593,7 +689,7 @@ final class Updater
|
||||
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
|
||||
}
|
||||
|
||||
rmdir($tmp);
|
||||
rmdir($dir);
|
||||
}
|
||||
|
||||
private function rawUrl(string $repo, string $branch, string $path): string
|
||||
@@ -610,12 +706,20 @@ final class Updater
|
||||
return "{$repo}/raw/branch/{$branch}/{$path}";
|
||||
}
|
||||
|
||||
private function archiveUrl(string $repo, string $branch): string
|
||||
/**
|
||||
* GitHub на github.com/.../archive/... отвечает 302 на codeload, а
|
||||
* HttpClient по редиректам нарочно не ходит — поэтому сразу codeload.
|
||||
*/
|
||||
public function archiveUrl(string $repo, string $branch): string
|
||||
{
|
||||
$repo = rtrim($repo, '/');
|
||||
|
||||
return str_contains($repo, 'github.com')
|
||||
? "{$repo}/archive/refs/heads/{$branch}.tar.gz"
|
||||
: "{$repo}/archive/{$branch}.tar.gz";
|
||||
if (str_contains($repo, 'github.com')) {
|
||||
$ownerRepo = trim((string) parse_url($repo, PHP_URL_PATH), '/');
|
||||
|
||||
return "https://codeload.github.com/{$ownerRepo}/tar.gz/refs/heads/{$branch}";
|
||||
}
|
||||
|
||||
return "{$repo}/archive/{$branch}.tar.gz";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user