Compare commits

..
5 changed files with 609 additions and 62 deletions
+13 -6
View File
@@ -109,17 +109,24 @@ php bin/backup.php export /srv/backups/laysite-2026-11.tar
php bin/backup.php import /srv/backups/laysite-2026-11.tar --replace php bin/backup.php import /srv/backups/laysite-2026-11.tar --replace
``` ```
可在「账户 → 关于系统」点击「检查更新」,比较本机版本与 `git.laysense.com/laysense/laysite` 的最新 `vX.Y.Z` 发布标签。已合并但尚未打标签的版本不会出现在检查结果里。检查结果缓存 5 分钟。 可在「账户 → 关于系统」点击「检查更新」,比较本机版本和 LaySite 仓库的最新正式发布。检查结果缓存 5 分钟。维护者发版时,先更新 `VERSION`,再用该提交创建同版本标签与正式 Release。
维护者发布新版本时,在发布提交上创建并推送与 `VERSION` 对应的标签,例如 `v1.4.0`。 独立更新器 `bin/update.php` 可从已安装站点的根目录运行。它先读取官方主分支的 [更新器兼容表](updatescript_map.json),按内置的更新器版本选择起始和目标范围,再从 Gitea 的 Release 列表查找可用版本。范围包含两端,`v1.1.0-latest` 上限为当前最新正式发布。可通过兼容表收紧旧更新器的适用范围。
使用 Git 标签选择部署版本。更新命令先备份,再检出所选版本、安装锁定依赖并运行 SQLite 初始化或迁移。更新时暂停 Webman,更新结束后重新启动。保持源代码工作区干净,并将备份放到部署路径之外。
```sh ```sh
bin/update.sh check php bin/update.php
bin/update.sh v1.1.0 /srv/backups/pre-update.tar php bin/update.php check
php bin/update.php v1.4.2 /srv/backups/pre-update.tar
# 从旧安装运行单独下载的更新器
php /path/to/update.php v1.4.2
``` ```
无参数时会显示可选版本及发布说明,选择编号或标签后开始更新。指定版本会直接检查并执行。省略备份路径时会写入 `storage/backups/`。原 `bin/update.sh` 入口已停用。
更新前请暂停 Webman。脚本从 LaySite 上游下载所选标签的 ZIP,通过 PHP 的 Phar 和 zlib 读取。它先比较当前发布包、新发布包和本地文件,再备份站点、按需安装 Composer 依赖、替换程序文件并运行 SQLite 迁移。
站点设置、SQLite、媒体和站点新增的文件保留原位。对于本地与上游都改过的同一文件,脚本会在替换前列出冲突路径。处理这些定制后再更新。
从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。 从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。
从 v1.1.0 更新画布功能时,更新脚本会添加样式字段,并将已有页头和页脚迁到「网站页面」,保留页面引用和已有认证配置。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。 从 v1.1.0 更新画布功能时,更新脚本会添加样式字段,并将已有页头和页脚迁到「网站页面」,保留页面引用和已有认证配置。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。
+15 -15
View File
@@ -10,7 +10,7 @@ use RuntimeException;
final class Updates final class Updates
{ {
public const REPOSITORY = 'https://git.laysense.com/laysense/laysite'; public const REPOSITORY = 'https://git.laysense.com/laysense/laysite';
private const TAGS = 'https://git.laysense.com/api/v1/repos/laysense/laysite/tags'; private const RELEASES = 'https://git.laysense.com/api/v1/repos/laysense/laysite/releases';
public static function current(): string public static function current(): string
{ {
@@ -44,7 +44,7 @@ final class Updates
$record = self::cached($path); $record = self::cached($path);
if (($record['until'] ?? 0) <= time()) { if (($record['until'] ?? 0) <= time()) {
try { try {
$record = ['latest' => self::latestTag(), 'until' => time() + 300]; $record = ['latest' => self::latestRelease(), 'until' => time() + 300];
} catch (RuntimeException $exception) { } catch (RuntimeException $exception) {
$record = ['error' => $exception->getMessage(), 'until' => time() + 30]; $record = ['error' => $exception->getMessage(), 'until' => time() + 30];
} }
@@ -97,7 +97,7 @@ final class Updates
} }
} }
private static function latestTag(): ?string private static function latestRelease(): ?string
{ {
$latest = null; $latest = null;
$deadline = hrtime(true) + 3_000_000_000; $deadline = hrtime(true) + 3_000_000_000;
@@ -107,25 +107,25 @@ final class Updates
if ($remaining <= 0) { if ($remaining <= 0) {
throw new RuntimeException('读取上游版本超时,请稍后重试。'); throw new RuntimeException('读取上游版本超时,请稍后重试。');
} }
$tags = self::tags($page++, $remaining); $releases = self::releases($page++, $remaining);
foreach ($tags as $tag) { foreach ($releases as $release) {
$name = $tag['name'] ?? null; $name = $release['tag_name'] ?? null;
if (!is_string($name)) { if (!is_string($name) || !is_bool($release['draft'] ?? null) || !is_bool($release['prerelease'] ?? null)) {
throw new RuntimeException('上游仓库返回的版本列表无效。'); throw new RuntimeException('上游仓库返回的版本列表无效。');
} }
if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match) if (!$release['draft'] && !$release['prerelease'] && preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match)
&& ($latest === null || version_compare($match[1], $latest, '>'))) { && ($latest === null || version_compare($match[1], $latest, '>'))) {
$latest = $match[1]; $latest = $match[1];
} }
} }
} while (count($tags) === 50); } while (count($releases) === 50);
return $latest; return $latest;
} }
private static function tags(int $page, int $timeout): array private static function releases(int $page, int $timeout): array
{ {
$curl = curl_init(self::TAGS . '?limit=50&page=' . $page); $curl = curl_init(self::RELEASES . '?limit=50&page=' . $page);
if ($curl === false) { if ($curl === false) {
throw new RuntimeException('无法连接上游仓库,请稍后重试。'); throw new RuntimeException('无法连接上游仓库,请稍后重试。');
} }
@@ -138,7 +138,7 @@ final class Updates
CURLOPT_HTTPHEADER => ['Accept: application/json'], CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_USERAGENT => 'LaySite version check', CURLOPT_USERAGENT => 'LaySite version check',
CURLOPT_WRITEFUNCTION => static function (CurlHandle $handle, string $chunk) use (&$body, &$overflow): int { CURLOPT_WRITEFUNCTION => static function (CurlHandle $handle, string $chunk) use (&$body, &$overflow): int {
if (strlen($body) + strlen($chunk) > 256 * 1024) { if (strlen($body) + strlen($chunk) > 1024 * 1024) {
$overflow = true; $overflow = true;
return 0; return 0;
} }
@@ -155,11 +155,11 @@ final class Updates
if ($status !== 200) { if ($status !== 200) {
throw new RuntimeException('上游版本列表暂不可用(HTTP ' . $status . ')。'); throw new RuntimeException('上游版本列表暂不可用(HTTP ' . $status . ')。');
} }
$tags = json_decode($body); $releases = json_decode($body);
if (!is_array($tags) || !array_is_list($tags)) { if (!is_array($releases) || !array_is_list($releases)) {
throw new RuntimeException('上游仓库返回的版本列表无效。'); throw new RuntimeException('上游仓库返回的版本列表无效。');
} }
return array_map(static fn ($tag): array => is_object($tag) ? get_object_vars($tag) : [], $tags); return array_map(static fn ($release): array => is_object($release) ? get_object_vars($release) : [], $releases);
} }
} }
+575
View File
@@ -0,0 +1,575 @@
#!/usr/bin/env php
<?php
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|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;
public function __construct(private readonly string $root)
{
}
public function execute(?string $target, ?string $backup): void
{
$current = $this->version();
$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 发布列表超时。');
}
$entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout);
if (!is_array($entries)) {
throw new RuntimeException('LaySite 发布列表格式无效。');
}
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 (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) {
$result[$entry->tag_name] = $entry;
}
}
if (count($entries) < 50) {
break;
}
}
uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1)));
return $result;
}
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);
$lock = fopen($runtime . '/release-update.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
throw new RuntimeException('无法取得 LaySite 更新锁。');
}
$pending = $runtime . '/release-update-pending';
$work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8));
try {
if (file_exists($pending) || is_link($pending)) {
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
}
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;
self::run([$php, 'bin/backup.php', 'export', $backup], $this->root);
$vendor = $this->stageDependencies($work, $plan, $release);
if ($plan !== $this->plan($base, $release, $backup)) {
throw new RuntimeException('准备更新期间,站点文件发生了变化。');
}
$this->apply($work, $pending, $plan, $release, $vendor, $php);
printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target);
} finally {
if (is_dir($work) && !is_file($pending)) {
self::removeDirectory($work);
}
fclose($lock);
}
}
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'));
if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) {
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;
}
private static function download(string $path, $stream, int $limit, int $timeout): void
{
$curl = curl_init(self::HOST . $path);
$bytes = 0;
curl_setopt_array($curl, [
CURLOPT_USERAGENT => 'LaySite release updater',
CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout),
CURLOPT_TIMEOUT_MS => $timeout,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int {
$bytes += strlen($chunk);
return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk);
},
]);
if (curl_exec($curl) === false) {
throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl)));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。");
}
}
private function archive(string $ref, string $version, string $path): array
{
$stream = fopen($path, 'xb');
if ($stream === false) {
throw new RuntimeException('无法写入发布 ZIP。');
}
try {
self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000);
} finally {
fclose($stream);
}
$archive = new PharData($path);
$files = [];
$size = 0;
$prefix = 'phar://' . $path . '/laysite/';
foreach (new RecursiveIteratorIterator($archive) as $entry) {
$uri = $entry->getPathname();
if (!str_starts_with($uri, $prefix)) {
throw new RuntimeException('发布 ZIP 的目录结构无效。');
}
$name = substr($uri, strlen($prefix));
if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\')
|| preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) {
throw new RuntimeException('发布 ZIP 包含无效的文件路径。');
}
$size += $entry->getSize();
if ($size > self::MAX_EXPANDED_BYTES) {
throw new RuntimeException('发布 ZIP 解压后的大小超过限制。');
}
if (!preg_match(self::MANAGED, $name)) {
continue;
}
$hash = hash_file('sha256', $uri);
if ($hash === false || isset($files[$name])) {
throw new RuntimeException('发布 ZIP 文件损坏。');
}
$files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777];
}
foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) {
if (!isset($files[$required])) {
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
}
}
$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;
}
private function plan(array $base, array $release, string $backup): array
{
clearstatcache();
require_once $this->root . '/vendor/autoload.php';
$database = App\Content\Database::path();
$media = App\Content\Media::directory();
$protected = array_unique([
$database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup,
]);
$plan = [];
$conflicts = [];
foreach (array_keys($base + $release) as $name) {
$old = $base[$name]['hash'] ?? null;
$next = $release[$name]['hash'] ?? null;
if ($old === $next) {
continue;
}
try {
$path = $this->managedPath($name);
foreach ($protected as $reserved) {
if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/')
|| str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) {
throw new RuntimeException('更新路径与站点数据重叠。');
}
}
$local = is_file($path) ? hash_file('sha256', $path) : null;
if ($local === $next) {
continue;
}
if ($local !== $old) {
$conflicts[] = $name;
continue;
}
$plan[] = $name;
} catch (RuntimeException) {
$conflicts[] = $name;
}
}
if ($conflicts !== []) {
sort($conflicts);
throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts));
}
if (array_intersect(['composer.json', 'composer.lock'], $plan)) {
$vendor = $this->root . '/vendor';
foreach ($protected as $reserved) {
if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) {
throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。');
}
}
}
return $plan;
}
private function managedPath(string $name): string
{
$path = $this->root;
$parts = explode('/', $name);
$leaf = array_pop($parts);
foreach ($parts as $part) {
$path .= '/' . $part;
if (is_link($path) || (file_exists($path) && !is_dir($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
}
$path .= '/' . $leaf;
if (is_link($path) || (file_exists($path) && !is_file($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
return $path;
}
private function stageDependencies(string $work, array $plan, array $release): ?string
{
if (!array_intersect(['composer.json', 'composer.lock'], $plan)) {
return null;
}
$dependencies = $work . '/dependencies';
self::makeDirectory($dependencies);
foreach (['composer.json', 'composer.lock'] as $name) {
$source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name;
if (!copy($source, $dependencies . '/' . $name)) {
throw new RuntimeException('无法准备 Composer 依赖。');
}
}
$vendor = $dependencies . '/vendor';
self::run([
getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist',
'--no-interaction', '--no-scripts', '--no-plugins',
], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor]));
if (!is_file($vendor . '/autoload.php')) {
throw new RuntimeException('Composer 没有在暂存目录生成依赖。');
}
return $vendor;
}
private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void
{
$staged = [];
foreach ($plan as $name) {
$staged[$name] = null;
if (isset($release[$name])) {
$file = $work . '/files/' . $name;
self::makeDirectory(dirname($file));
$mode = $release[$name]['mode'] & 0755;
if ($name === 'bin/update.sh') {
$mode |= 0100;
}
if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) {
throw new RuntimeException('无法暂存文件 ' . $name);
}
$staged[$name] = $file;
}
}
if ($vendor !== null) {
if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) {
throw new RuntimeException('站点的 vendor 目录需要手动更新。');
}
$staged['vendor'] = $vendor;
}
$marker = fopen($pending, 'x');
if ($marker === false) {
throw new RuntimeException('无法写入更新记录。');
}
$record = $work . PHP_EOL;
$written = fwrite($marker, $record);
fclose($marker);
if ($written !== strlen($record)) {
unlink($pending);
throw new RuntimeException('无法写入完整的更新记录。');
}
$applied = [];
try {
foreach ($staged as $name => $source) {
$destination = $this->root . '/' . $name;
$previous = $work . '/previous/' . $name;
if (file_exists($destination)) {
self::makeDirectory(dirname($previous));
self::move($destination, $previous);
}
$applied[] = $name;
if ($source !== null) {
self::makeDirectory(dirname($destination));
self::move($source, $destination);
}
}
self::run([$php, 'bin/install.php'], $this->root);
} catch (Throwable $error) {
try {
foreach (array_reverse($applied) as $name) {
$path = $this->root . '/' . $name;
if (file_exists($path)) {
$discard = $work . '/discard/' . $name;
self::makeDirectory(dirname($discard));
self::move($path, $discard);
}
$previous = $work . '/previous/' . $name;
if (file_exists($previous)) {
self::move($previous, $path);
}
}
unlink($pending);
} catch (Throwable $rollback) {
throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error);
}
throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error);
}
unlink($pending);
}
private static function move(string $from, string $to): void
{
if (!rename($from, $to)) {
throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to);
}
}
private static function run(array $command, string $directory, ?array $environment = null): void
{
$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment);
if (!is_resource($process) || proc_close($process) !== 0) {
throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2)));
}
}
private static function makeDirectory(string $path): void
{
if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) {
throw new RuntimeException('无法建立目录 ' . $path);
}
}
private static function removeDirectory(string $path): void
{
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST);
foreach ($entries as $entry) {
if ($entry->isDir() && !$entry->isLink()) {
rmdir($entry->getPathname());
} else {
unlink($entry->getPathname());
}
}
rmdir($path);
}
}
$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 {
(new LaySiteUpdater(getcwd()))->execute($target, $backup);
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
}
-41
View File
@@ -1,41 +0,0 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
php_bin=${LAYSITE_PHP:-php}
composer_bin=${LAYSITE_COMPOSER:-composer}
target=${1:-check}
if [ "$target" = check ]; then
git fetch origin --tags
git describe --tags --always
git tag --list 'v[0-9]*' --sort=-version:refname | awk '/^v[0-9]+\.[0-9]+\.[0-9]+$/'
exit 0
fi
if ! printf '%s\n' "$target" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || [ "$#" -ne 2 ]; then
printf '%s\n' 'Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar' >&2
exit 2
fi
if [ -n "$(git status --porcelain)" ]; then
printf '%s\n' 'Commit or set aside local source changes before updating.' >&2
exit 1
fi
git fetch origin --tags
current=$(git rev-parse HEAD)
next=$(git rev-parse --verify "refs/tags/$target^{commit}")
git merge-base --is-ancestor "$current" "$next"
"$php_bin" bin/backup.php export "$2"
if git switch --detach "$next" &&
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts &&
"$php_bin" bin/install.php
then
printf 'Updated to %s. Start Webman with the original site environment.\n' "$target"
else
git switch --detach "$current"
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts
printf 'Update failed. The prior source version is checked out and the backup is at %s.\n' "$2" >&2
exit 1
fi
+6
View File
@@ -0,0 +1,6 @@
{
"1.0.0": {
"from": "v1.1.0-latest",
"to": "v1.1.0-latest"
}
}