Use a standalone PHP updater with release compatibility rules
This commit is contained in:
+205
-47
@@ -5,10 +5,25 @@ declare(strict_types=1);
|
||||
|
||||
final class LaySiteUpdater
|
||||
{
|
||||
private const UPDATESCRIPT_VERSION = '1.0.0';
|
||||
private const HOST = 'https://git.laysense.com';
|
||||
private const PROJECT = '/laysense/laysite';
|
||||
private const MAP_PATH = self::PROJECT . '/raw/branch/main/updatescript_map.json';
|
||||
private const RELEASES_PATH = '/api/v1/repos' . self::PROJECT . '/releases';
|
||||
private const TAG = '/^v(\d+\.\d+\.\d+)$/D';
|
||||
|
||||
// These two releases shipped with 1.4.0 in VERSION. Identify their original files when updating old installations.
|
||||
private const LEGACY_VERSIONS = [
|
||||
'1.4.2' => [
|
||||
'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26',
|
||||
'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635',
|
||||
],
|
||||
'1.4.1' => [
|
||||
'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a',
|
||||
],
|
||||
];
|
||||
private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f'];
|
||||
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|composer\.(?:json|lock)|start\.php)$/D';
|
||||
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D';
|
||||
private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
|
||||
private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
@@ -16,46 +31,160 @@ final class LaySiteUpdater
|
||||
{
|
||||
}
|
||||
|
||||
public function check(): void
|
||||
public function execute(?string $target, ?string $backup): void
|
||||
{
|
||||
$current = $this->version();
|
||||
$latest = null;
|
||||
$map = self::remoteJson(self::MAP_PATH, 65536, 10000);
|
||||
$rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null;
|
||||
if (!is_object($rule)) {
|
||||
throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。');
|
||||
}
|
||||
$from = self::parseRange($rule->from ?? null);
|
||||
$to = self::parseRange($rule->to ?? null);
|
||||
$releases = self::releases();
|
||||
$latest = array_key_first($releases);
|
||||
$latestVersion = $latest === null ? null : substr($latest, 1);
|
||||
if (!self::inRange($current, $from, $latestVersion)) {
|
||||
throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。");
|
||||
}
|
||||
$eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool {
|
||||
$version = substr($tag, 1);
|
||||
|
||||
return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion);
|
||||
}, ARRAY_FILTER_USE_KEY);
|
||||
printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n",
|
||||
self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to);
|
||||
|
||||
if ($target === 'check') {
|
||||
if ($latest !== null) {
|
||||
printf("上游最新正式发布 %s\n", $latest);
|
||||
}
|
||||
echo $eligible === [] ? "暂无可升级的正式发布版本。\n"
|
||||
: '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL;
|
||||
return;
|
||||
}
|
||||
if ($target === null) {
|
||||
$target = self::chooseRelease($eligible);
|
||||
if ($target === null) {
|
||||
return;
|
||||
}
|
||||
} elseif ($target === 'v' . $current) {
|
||||
printf("当前已安装 %s。\n", $target);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isset($eligible[$target])) {
|
||||
throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 "
|
||||
. ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。'));
|
||||
}
|
||||
$this->update($current, $target, $backup);
|
||||
}
|
||||
|
||||
private static function parseRange(mixed $value): array
|
||||
{
|
||||
if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts)
|
||||
|| (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) {
|
||||
throw new RuntimeException('更新器兼容表中的版本范围无效。');
|
||||
}
|
||||
|
||||
return [$parts[1], $parts[2] ?? null];
|
||||
}
|
||||
|
||||
private static function inRange(string $version, array $range, ?string $latest): bool
|
||||
{
|
||||
[$minimum, $maximum] = $range;
|
||||
$maximum ??= $latest;
|
||||
|
||||
return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<='));
|
||||
}
|
||||
|
||||
private static function releases(): array
|
||||
{
|
||||
$result = [];
|
||||
$deadline = hrtime(true) + 10_000_000_000;
|
||||
for ($page = 1; ; $page++) {
|
||||
$timeout = (int) (($deadline - hrtime(true)) / 1_000_000);
|
||||
if ($timeout <= 0) {
|
||||
throw new RuntimeException('查询 LaySite 发布列表超时。');
|
||||
}
|
||||
$stream = fopen('php://temp', 'w+b');
|
||||
try {
|
||||
self::download('/api/v1/repos' . self::PROJECT . "/tags?limit=50&page=$page", $stream, 262144, $timeout);
|
||||
rewind($stream);
|
||||
$tags = json_decode(stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
if (!is_array($tags)) {
|
||||
$entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout);
|
||||
if (!is_array($entries)) {
|
||||
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||
}
|
||||
foreach ($tags as $tag) {
|
||||
$name = $tag->name ?? null;
|
||||
if (!is_string($name)) {
|
||||
foreach ($entries as $entry) {
|
||||
if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) {
|
||||
throw new RuntimeException('LaySite 发布列表格式无效。');
|
||||
}
|
||||
if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match)
|
||||
&& ($latest === null || version_compare($match[1], $latest, '>'))) {
|
||||
$latest = $match[1];
|
||||
if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) {
|
||||
$result[$entry->tag_name] = $entry;
|
||||
}
|
||||
}
|
||||
if (count($tags) < 50) {
|
||||
if (count($entries) < 50) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1)));
|
||||
|
||||
printf("当前版本 v%s\n%s\n", $current, $latest === null ? '上游暂无发布版本。' : '最新发布版本 v' . $latest);
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function update(string $target, string $backup): void
|
||||
private static function remoteJson(string $path, int $limit, int $timeout): mixed
|
||||
{
|
||||
$stream = fopen('php://temp', 'w+b');
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException('无法创建更新查询缓冲区。');
|
||||
}
|
||||
try {
|
||||
self::download($path, $stream, $limit, $timeout);
|
||||
rewind($stream);
|
||||
|
||||
return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
|
||||
private static function chooseRelease(array $releases): ?string
|
||||
{
|
||||
if ($releases === []) {
|
||||
echo "暂无可升级的正式发布版本。\n";
|
||||
return null;
|
||||
}
|
||||
$tags = array_keys($releases);
|
||||
foreach ($tags as $index => $tag) {
|
||||
$release = $releases[$tag];
|
||||
$title = self::terminalText($release->name ?? '');
|
||||
$details = self::terminalText($release->body ?? '');
|
||||
printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title));
|
||||
echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
echo "\n请选择版本编号或输入标签,回车取消\n> ";
|
||||
$selection = trim((string) fgets(STDIN));
|
||||
if ($selection === '' || strtolower($selection) === 'q') {
|
||||
return null;
|
||||
}
|
||||
if (isset($releases[$selection])) {
|
||||
return $selection;
|
||||
}
|
||||
if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) {
|
||||
return $tags[(int) $selection - 1];
|
||||
}
|
||||
echo "请输入列表中的编号或版本。\n";
|
||||
}
|
||||
}
|
||||
|
||||
private static function terminalText(mixed $value): string
|
||||
{
|
||||
if (!is_string($value)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? '');
|
||||
}
|
||||
|
||||
private function update(string $current, string $target, ?string $backup): void
|
||||
{
|
||||
$runtime = $this->root . '/runtime';
|
||||
self::makeDirectory($runtime);
|
||||
@@ -69,20 +198,17 @@ final class LaySiteUpdater
|
||||
if (file_exists($pending) || is_link($pending)) {
|
||||
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
|
||||
}
|
||||
$current = $this->version();
|
||||
$comparison = version_compare(substr($target, 1), $current);
|
||||
if ($comparison === 0) {
|
||||
printf("当前已安装 %s。\n", $target);
|
||||
return;
|
||||
}
|
||||
if ($comparison < 0) {
|
||||
throw new RuntimeException('更新目标必须高于已安装版本。');
|
||||
if ($this->version() !== $current) {
|
||||
throw new RuntimeException('站点版本已经变更,请重新选择更新目标。');
|
||||
}
|
||||
$backup = $this->backupPath($backup, $current, $target);
|
||||
|
||||
if (!mkdir($work, 0700)) {
|
||||
throw new RuntimeException('无法建立更新暂存目录。');
|
||||
}
|
||||
$base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip');
|
||||
// Accept the VERSION file already identified above, including the old release numbering.
|
||||
$base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION');
|
||||
$release = $this->archive($target, substr($target, 1), $work . '/release.zip');
|
||||
$plan = $this->plan($base, $release, $backup);
|
||||
$php = getenv('LAYSITE_PHP') ?: PHP_BINARY;
|
||||
@@ -101,6 +227,25 @@ final class LaySiteUpdater
|
||||
}
|
||||
}
|
||||
|
||||
private function backupPath(?string $path, string $current, string $target): string
|
||||
{
|
||||
if ($path === null) {
|
||||
$directory = $this->root . '/storage/backups';
|
||||
self::makeDirectory($directory);
|
||||
$path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4)));
|
||||
} elseif (!str_starts_with($path, '/')) {
|
||||
$path = $this->root . '/' . $path;
|
||||
}
|
||||
$directory = realpath(dirname($path));
|
||||
if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) {
|
||||
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
|
||||
}
|
||||
$path = $directory . '/' . basename($path);
|
||||
printf("站点备份将写入 %s\n", $path);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function version(): string
|
||||
{
|
||||
$version = trim((string) @file_get_contents($this->root . '/VERSION'));
|
||||
@@ -108,6 +253,16 @@ final class LaySiteUpdater
|
||||
throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。');
|
||||
}
|
||||
|
||||
if ($version === '1.4.0') {
|
||||
foreach (self::LEGACY_VERSIONS as $tag => $files) {
|
||||
foreach ($files as $path => $hash) {
|
||||
if (@hash_file('sha256', $this->root . '/' . $path) === $hash) {
|
||||
return $tag;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
@@ -131,7 +286,7 @@ final class LaySiteUpdater
|
||||
}
|
||||
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
if ($status !== 200) {
|
||||
throw new RuntimeException("无法读取 LaySite 发布文件 $path(HTTP $status)。");
|
||||
throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,8 +333,17 @@ final class LaySiteUpdater
|
||||
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
|
||||
}
|
||||
}
|
||||
if (trim((string) file_get_contents($files['VERSION']['uri'])) !== $version) {
|
||||
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
|
||||
$embedded = trim((string) file_get_contents($files['VERSION']['uri']));
|
||||
if ($embedded !== $version) {
|
||||
if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) {
|
||||
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
|
||||
}
|
||||
$canonical = $path . '.version';
|
||||
$contents = $version . "\n";
|
||||
if (file_put_contents($canonical, $contents) !== strlen($contents)) {
|
||||
throw new RuntimeException('无法暂存发布版本号。');
|
||||
}
|
||||
$files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644];
|
||||
}
|
||||
|
||||
return $files;
|
||||
@@ -394,23 +558,17 @@ final class LaySiteUpdater
|
||||
}
|
||||
}
|
||||
|
||||
$target = $argv[1] ?? null;
|
||||
$backup = $argv[2] ?? null;
|
||||
if ($argc > 3 || ($target === 'check' && $backup !== null)
|
||||
|| ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) {
|
||||
fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
umask(0027);
|
||||
try {
|
||||
$updater = new LaySiteUpdater(getcwd());
|
||||
$target = $argv[1] ?? 'check';
|
||||
if ($target === 'check' && $argc <= 2) {
|
||||
$updater->check();
|
||||
} elseif ($argc === 3 && preg_match('/^v\d+\.\d+\.\d+$/D', $target)) {
|
||||
$backup = str_starts_with($argv[2], '/') ? $argv[2] : getcwd() . '/' . $argv[2];
|
||||
$directory = realpath(dirname($backup));
|
||||
if ($directory === false || !str_ends_with($backup, '.tar') || file_exists($backup) || is_link($backup)) {
|
||||
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
|
||||
}
|
||||
$updater->update($target, $directory . '/' . basename($backup));
|
||||
} else {
|
||||
fwrite(STDERR, "Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar\n");
|
||||
exit(2);
|
||||
}
|
||||
(new LaySiteUpdater(getcwd()))->execute($target, $backup);
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
exec "${LAYSITE_PHP:-php}" bin/update.php "$@"
|
||||
Reference in New Issue
Block a user