fix: 发布一致性校验、日志轮转与构建脚本对齐
PR 审核 / 后端编译 (pull_request) Canceled after 0s
PR 审核 / 后端自检 (pull_request) Canceled after 0s
PR 审核 / 前端检查(Flutter) (pull_request) Canceled after 0s
PR 审核 / 安全扫描 (pull_request) Canceled after 0s
PR 审核 / 审核汇总 (pull_request) Canceled after 0s

- 新增发布校验脚本(buildsh/lib/verify_release.py + release.sh),核对 tag/清单/资产
  三者的 sha256 与体积,并复验清单签名;接入 ./build.sh release-verify 与
  .gitea/workflows/release-verify.yml(手动触发)
- GcLog 改为常驻 StreamWriter + 按天轮转 + 14 天/64MB 保留策略,避免高峰期反复
  开关文件句柄;只清理本模块生成的 gc-*.log,不碰用户文件
- 修复 Applier 验签逻辑:无效签名永远拒绝,仅「未签名」在调用方不强制时放行
- 新增应用器测试(GC.Savedog.Tests):整目录替换、.GC/bin 合并、启动失败回滚、
  路径穿越防护、验签;接入 pr-check.yml
- GC.Tests 增加日志用例(写入/轮转/清理/用户文件保护)
- 同步 PowerShell 打包脚本与 buildsh 一致:GCL 命名、单顶层目录、守护进程收进
  .GC/bin、启动器与守护进程压缩单文件、不预置 .GC、prune/strip 对齐、签名
  keyId 改为 gc-2026-12、新增 release-verify 与应用器测试任务
This commit is contained in:
Morris committed 2026-11-19 00:05:16 +08:00
1 parent a5fcaeb658
commit 59a66c8fa8
15 files changed
+981 -93

No files matched your search

+4 -1
View File
@@ -57,9 +57,12 @@ jobs:
with:
dotnet-version: '8.0.x'
- name: 运行 GC.Tests(含离屏渲染 / 清单校验)
- name: 运行 GC.Tests(含离屏渲染 / 清单校验 / 日志用例)
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
- name: 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)
run: dotnet run --project GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj -c Release
frontend:
name: 前端检查(Flutter)
runs-on: ubuntu-latest
+50
View File
@@ -0,0 +1,50 @@
# ---------------------------------------------------------------------------
# 发布一致性核对(Gitea Actions)
#
# 触发:仅手动。发布前跑一次确认「tag / 清单 / 资产」互相对得上,发布后再跑一次
# 确认线上资产就是清单里那两份。
#
# 为什么不用 pull_request 触发:这里要下载几百 MB 的发布包,PR 阶段跑太贵;
# 需要时点 Run workflow 即可,本地也有等价命令:./build.sh release-verify <tag>
# ---------------------------------------------------------------------------
name: 发布核对
on:
workflow_dispatch:
inputs:
tag:
description: '要核对的 tag(如 1.1.0)'
required: true
skip_download:
description: '只比对体积、不下载校验 sha256(快,输入 1 开启)'
required: false
default: ''
env:
DOTNET_NOLOGO: '1'
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
jobs:
verify:
name: 核对 Release 与清单
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 安装 .NET 8
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: 核对
env:
GC_GITEA_TOKEN: ${{ secrets.GC_GITEA_TOKEN }}
run: |
set -eu
EXTRA=""
if [ -n "${{ github.event.inputs.skip_download }}" ]; then
EXTRA="--skip-download"
fi
chmod +x buildsh/lib/verify_release.py
./build.sh release-verify "${{ github.event.inputs.tag }}" $EXTRA
+10 -1
View File
@@ -84,12 +84,21 @@ internal sealed class Applier
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
var verification = ManifestSignature.Verify(manifestText, require);
if (verification.IsRejected)
// 签名不对(被改过 / 密钥不认识)永远拒绝;仅「没有签名」在明确不强制时放行。
// 之前这里不看 require:即使调用方声明 requireSignature=false(开发态、测试),
// 未签名清单也会被当成验签失败直接拒掉。
var hostile = verification.Trust == ManifestTrust.Invalid;
if (hostile || (verification.IsRejected && require))
{
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}",
$"Manifest signature check failed ({verification.Trust}): {verification.Error}");
return Refuse(updateDir, request, verification);
}
if (verification.IsRejected)
{
_log.Warn($"清单未签名,按调用方要求放行:{verification.Error}",
$"Manifest is unsigned; continuing as requested: {verification.Error}");
}
_log.Info($"清单可信度:{verification.Trust}" +
(verification.KeyId != null ? $"({verification.KeyId})" : ""),
$"Manifest trust: {verification.Trust}" +
+5
View File
@@ -37,6 +37,11 @@
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<!-- 应用器测试要直接构造 Applier(internal):只对测试程序集放开可见性 -->
<InternalsVisibleTo Include="GC.Savedog.Tests" />
</ItemGroup>
<ItemGroup>
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
+124 -12
View File
@@ -1,4 +1,5 @@
using System;
using System.Globalization;
using System.IO;
using System.Text;
@@ -15,15 +16,30 @@ namespace GC.Services;
/// 中英分开而不是写在一个文件里:用户排查时不用在一行里找自己看得懂的那半句;
/// 也给反馈问题时直接发对应语言的文件即可。
///
/// 写入方式:常驻 <see cref="StreamWriter"/>(<c>AutoFlush</c> 打开,崩溃也不丢最后几行),
/// 不再每行 open/append/close 一遍 —— 那条路径每写一行要开两个文件句柄,
/// 在下载 / 启动高峰期会明显拖慢调用方。
///
/// 保留策略:<see cref="RetentionDays"/> 天之前的日志在初始化与跨天滚动时删除;
/// 总量超过 <see cref="MaxTotalBytes"/> 时从最旧的开始删。日志目录不会无限长。
///
/// 日志失败绝不影响主流程(磁盘满、只读目录都只是少一份日志)。
/// </summary>
public static class GcLog
{
/// <summary>日志保留天数。</summary>
public const int RetentionDays = 14;
/// <summary>日志目录总量上限(中英两份合计)。</summary>
public const long MaxTotalBytes = 64L * 1024 * 1024;
private static readonly object Gate = new();
private const string FilePrefix = "gc-";
private static string? _dir;
private static string _day = "";
private static string _zhPath = "";
private static string _enPath = "";
private static StreamWriter? _zh;
private static StreamWriter? _en;
public static bool Enabled
{
@@ -45,8 +61,10 @@ public static class GcLog
lock (Gate)
{
CloseWriters();
_dir = dir;
_day = "";
PruneOldFiles(dir);
}
}
@@ -58,10 +76,8 @@ public static class GcLog
{
var now = DateTime.Now;
var prefix = $"{now:yyyy-MM-dd HH:mm:ss} [{level}] ";
var lineZh = prefix + zh;
var lineEn = prefix + en;
try { Console.WriteLine(lineZh); } catch { /* 无控制台 */ }
try { Console.WriteLine(prefix + zh); } catch { /* 无控制台 */ }
lock (Gate)
{
@@ -70,25 +86,121 @@ public static class GcLog
var day = now.ToString("yyyyMMdd");
if (day != _day)
{
// 跨天换文件;顺便清一次旧日志,长时间挂机的进程也不会攒满磁盘
CloseWriters();
_day = day;
_zhPath = Path.Combine(_dir, $"gc-{day}.log");
_enPath = Path.Combine(_dir, $"gc-{day}.en.log");
PruneOldFiles(_dir);
}
Append(_zhPath, lineZh);
Append(_enPath, lineEn);
if (_zh == null)
{
_zh = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.log"));
_en = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.en.log"));
}
Append(_zh, prefix + zh);
Append(_en, prefix + en);
}
}
private static void Append(string path, string line)
private static StreamWriter? OpenWriter(string path)
{
try
{
File.AppendAllText(path, line + Environment.NewLine, new UTF8Encoding(false));
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
}
catch
{
// 日志失败不能影响程序
// 写不了就不写;下一次跨天会再试一次
return null;
}
}
private static void Append(StreamWriter? writer, string line)
{
if (writer == null) return;
try
{
writer.WriteLine(line);
}
catch
{
// 磁盘满 / 文件被删:关掉写入器,下次跨天重建
try { writer.Dispose(); } catch { }
if (ReferenceEquals(writer, _zh)) _zh = null; else _en = null;
}
}
private static void CloseWriters()
{
try { _zh?.Dispose(); } catch { }
try { _en?.Dispose(); } catch { }
_zh = null;
_en = null;
}
/// <summary>
/// 清理过期与超量日志。只动本模块自己写的 <c>gc-YYYYMMDD[.en].log</c>,
/// 目录里用户放的其他文件一概不碰。
/// </summary>
private static void PruneOldFiles(string dir)
{
try
{
var files = new DirectoryInfo(dir).GetFiles(FilePrefix + "*.log");
if (files.Length == 0) return;
var cutoff = DateTime.Now.Date.AddDays(-RetentionDays);
var alive = new System.Collections.Generic.List<FileInfo>(files.Length);
foreach (var file in files)
{
if (!TryReadDate(file.Name, out var date))
{
// 名字不是我们的格式,忽略(既不删也不计入配额)
continue;
}
if (date < cutoff)
{
try { file.Delete(); } catch { }
continue;
}
alive.Add(file);
}
long total = 0;
foreach (var file in alive) total += file.Length;
if (total <= MaxTotalBytes) return;
alive.Sort((a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
foreach (var file in alive)
{
if (total <= MaxTotalBytes) break;
try
{
total -= file.Length;
file.Delete();
}
catch { }
}
}
catch
{
// 清理失败不影响写日志
}
}
private static bool TryReadDate(string name, out DateTime date)
{
date = default;
// gc-20261118.log / gc-20261118.en.log
if (!name.StartsWith(FilePrefix, StringComparison.Ordinal)) return false;
var rest = name.Substring(FilePrefix.Length);
var dot = rest.IndexOf('.');
if (dot != 8) return false;
return DateTime.TryParseExact(rest.Substring(0, 8), "yyyyMMdd",
CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
}
@@ -0,0 +1,293 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GC.Savedog;
namespace GC.Savedog.Tests;
/// <summary>
/// GC-SAVEDOG 的应用器测试:更新真正落盘的那一段(整目录替换 / .GC/bin 合并 / 失败回滚)。
///
/// 为什么单独一个工程:<c>GC.Tests</c> 引用的是启动器程序集,而 GC-SAVEDOG 为了保持
/// 「安全逻辑只有一份实现」把 <c>GC/src/Security</c> 与 <c>Json.cs</c> 以源码链接的方式
/// 编进了自己 —— 两个程序集里存在同名类型。同一个测试工程里同时引用两者会撞类型,
/// 所以应用器测试单独放这里,只引用守护进程。
///
/// 为什么需要这组用例:<c>--update-test</c> 覆盖的是「怎么判断该不该更新」,
/// <see cref="Applier"/> 才是会动用户安装目录的代码 —— 它出错就是用户目录被删空。
/// 全部在临时目录里跑,不碰真实安装、不联网。
/// </summary>
internal static class ApplierTests
{
private static int _failed;
private static string _root = "";
public static int Main()
{
_root = Path.Combine(Path.GetTempPath(), "gc-applier-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_root);
Console.WriteLine("Applier 测试目录: " + _root);
try
{
CaseRefusesTraversalPackageName();
CaseRefusesShaMismatch();
CaseRefusesSourceTree();
CaseDryRunKeepsInstallUntouched();
CaseRollbackRestoresOldFiles();
CaseSuccessMergesGcBinAndKeepsUserData();
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine(_failed == 0
? "Applier 测试全部通过"
: $"Applier 测试失败 {_failed} 项");
return _failed == 0 ? 0 : 1;
}
// ------------------------------------------------------------------ 用例
/// <summary>包名带 ../ 时必须拒绝(路径穿越的第一道闸)。</summary>
private static void CaseRefusesTraversalPackageName()
{
var (install, update) = Sandbox("traversal");
WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "../evil.exe", sha: null);
var code = Apply(update, install, dryRun: true);
Check("路径穿越的包名被拒绝", code == 3, $"exit={code}(期望 3)");
}
/// <summary>zip 内容与清单 sha256 不符时必须丢弃。</summary>
private static void CaseRefusesShaMismatch()
{
var (install, update) = Sandbox("sha");
WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", sha: new string('a', 64));
var code = Apply(update, install, dryRun: true);
Check("sha256 不符的包被丢弃", code == 5, $"exit={code}(期望 5)");
}
/// <summary>安装目录里有 GC.sln 时拒绝替换 —— 防止误在源码树里跑更新。</summary>
private static void CaseRefusesSourceTree()
{
var (install, update) = Sandbox("srctree");
File.WriteAllText(Path.Combine(install, "GC.sln"), "fake solution");
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false);
Check("源码目录被拒绝替换", code == 4, $"exit={code}(期望 4)");
Check("源码目录里的文件没被动过",
File.ReadAllText(Path.Combine(install, "GC.sln")) == "fake solution",
"GC.sln 内容变了");
}
/// <summary>dry-run 只校验不落盘:安装目录必须一个字节都不变。</summary>
private static void CaseDryRunKeepsInstallUntouched()
{
var (install, update) = Sandbox("dryrun");
File.WriteAllText(Path.Combine(install, "GCL-1.0.0-test-amd64.exe"), "old");
File.WriteAllText(Path.Combine(install, "only-in-old.txt"), "keep me");
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "new",
["GC-UI.exe"] = "ui"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: true);
var names = Directory.GetFileSystemEntries(install).Select(Path.GetFileName).OrderBy(n => n).ToArray();
Check("dry-run 返回 0", code == 0, $"exit={code}");
Check("dry-run 不改安装目录",
names.SequenceEqual(new[] { "GCL-1.0.0-test-amd64.exe", "only-in-old.txt" }),
"安装目录变成: " + string.Join(", ", names));
}
/// <summary>
/// 新版本启动不健康 → 回滚:旧文件原样回来,新包独有的文件被删掉,zip 与申请被清理。
/// </summary>
private static void CaseRollbackRestoresOldFiles()
{
var (install, update) = Sandbox("rollback");
var oldExe = Path.Combine(install, "GCL-1.0.0-test-amd64.exe");
var oldOnly = Path.Combine(install, "only-in-old.txt");
File.WriteAllText(oldExe, "old-binary");
File.WriteAllText(oldOnly, "old-only");
// 新版什么都不做直接退出:健康标记不会出现,必然回滚
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = "#!/bin/sh\nexit 1\n",
["only-in-new.txt"] = "new-only"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false, timeoutSeconds: 5);
Check("启动失败后回滚(exit=8)", code == 8, $"exit={code}(期望 8)");
Check("旧启动器被还原",
File.Exists(oldExe) && File.ReadAllText(oldExe) == "old-binary",
"旧启动器没回来");
Check("旧版独有文件被还原",
File.Exists(oldOnly) && File.ReadAllText(oldOnly) == "old-only",
"旧版独有文件没回来");
Check("新包独有文件被删除", !File.Exists(Path.Combine(install, "only-in-new.txt")),
"only-in-new.txt 残留");
Check("更新包与申请已清理",
!File.Exists(Path.Combine(update, "package.zip")) &&
!File.Exists(Path.Combine(update, "apply-request.json")),
"update 目录里还有残留");
}
/// <summary>正常路径:新文件就位、.GC/bin 被合并、.GC 下的用户数据原地不动。</summary>
private static void CaseSuccessMergesGcBinAndKeepsUserData()
{
var (install, update) = Sandbox("success");
var updateDirFull = Path.GetFullPath(update);
// 用户数据:设置、模型、守护进程源文件
Directory.CreateDirectory(Path.Combine(install, ".GC", "config"));
Directory.CreateDirectory(Path.Combine(install, ".GC", "model", "earth-rotation"));
Directory.CreateDirectory(Path.Combine(install, ".GC", "bin"));
File.WriteAllText(Path.Combine(install, ".GC", "config", "settings.json"), "{\"theme\":\"dark\"}");
File.WriteAllText(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin"), "model");
File.WriteAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe"), "old-savedog");
// 假启动器:写健康标记后退出,模拟「新版本起来了」
var launcher =
"#!/bin/sh\n" +
"cat > '" + Path.Combine(updateDirFull, "health.json") + "' <<'JSON'\n" +
"{\"version\":\"9.9.9\",\"pid\":4242,\"at\":\"2026-01-01T00:00:00Z\",\"ok\":true}\n" +
"JSON\n" +
"exit 0\n";
var zip = WritePackage(update, new Dictionary<string, string>
{
["GCL-9.9.9-test-amd64.exe"] = launcher,
[".GC/bin/GC-SAVEDOG.exe"] = "new-savedog",
["GC-UI.exe"] = "ui"
});
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
var code = Apply(update, install, dryRun: false, timeoutSeconds: 10);
Check("启动健康后更新成功(exit=0)", code == 0, $"exit={code}");
Check("新启动器就位",
File.Exists(Path.Combine(install, "GCL-9.9.9-test-amd64.exe")), "新启动器缺失");
Check("新前端就位", File.Exists(Path.Combine(install, "GC-UI.exe")), "GC-UI.exe 缺失");
Check(".GC/bin 被合并",
File.ReadAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe")) == "new-savedog",
".GC/bin/GC-SAVEDOG.exe 没被替换");
Check("用户设置原样保留",
File.ReadAllText(Path.Combine(install, ".GC", "config", "settings.json")) == "{\"theme\":\"dark\"}",
"settings.json 被覆盖");
Check("模型目录原样保留",
File.Exists(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin")),
"模型文件被删除");
}
// ------------------------------------------------------------------ 辅助
private static int Apply(string updateDir, string installDir, bool dryRun, int timeoutSeconds = 10)
{
var log = new Log(Path.Combine(updateDir, "logs"));
var applier = new Applier(new ApplyOptions
{
UpdateDir = updateDir,
InstallDir = installDir,
DryRun = dryRun,
TimeoutSeconds = timeoutSeconds,
RequireSignature = false, // 用例不生成签名清单;验签本身由 --update-test 覆盖
Force = false
}, log);
return applier.Run();
}
private static (string Install, string Update) Sandbox(string name)
{
var baseDir = Path.Combine(_root, name);
var install = Path.Combine(baseDir, "app");
var update = Path.Combine(baseDir, "update");
Directory.CreateDirectory(install);
Directory.CreateDirectory(update);
File.WriteAllText(Path.Combine(update, "version.json"), "{\"launcher\":{\"version\":\"9.9.9\"}}");
return (install, update);
}
private static string WritePackage(string updateDir, IDictionary<string, string> files)
{
var zipPath = Path.Combine(updateDir, "package.zip");
try { File.Delete(zipPath); } catch { }
using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
foreach (var (name, text) in files)
{
var entry = archive.CreateEntry(name.Replace('\\', '/'), CompressionLevel.Fastest);
using var stream = entry.Open();
var bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}
return zipPath;
}
/// <summary>手写申请文件:不引用 Json 序列化助手(同名类型在两个程序集里都有)。</summary>
private static void WriteRequest(string updateDir, string packageName, string? sha)
{
var zipPath = Path.Combine(updateDir, "package.zip");
var size = File.Exists(zipPath) ? new FileInfo(zipPath).Length : 0;
var json = new StringBuilder()
.Append("{\n")
.Append(" \"schema\": 1,\n")
.Append(" \"version\": \"9.9.9\",\n")
.Append(" \"rid\": \"test-amd64\",\n")
.Append(" \"platformLabel\": \"test-amd64\",\n")
.Append(" \"packageName\": ").Append(Quote(packageName)).Append(",\n")
.Append(" \"payloadDir\": \"payload\",\n")
.Append(" \"installRelative\": \"../app\",\n")
.Append(" \"manifestPath\": \"version.json\",\n")
.Append(" \"packageZip\": \"package.zip\",\n")
.Append(" \"packageSha256\": ").Append(sha == null ? "null" : Quote(sha)).Append(",\n")
.Append(" \"packageSize\": ").Append(size).Append(",\n")
.Append(" \"requireSignature\": false\n")
.Append("}\n")
.ToString();
File.WriteAllText(Path.Combine(updateDir, "apply-request.json"), json);
}
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
private static string Sha256File(string path)
{
using var stream = File.OpenRead(path);
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
}
private static void Check(string label, bool ok, string detail)
{
if (ok)
{
Console.WriteLine(" ✓ " + label);
return;
}
_failed++;
Console.WriteLine($" ✗ {label} —— {detail}");
}
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
应用器测试:只引用 GC-SAVEDOG。
不并入 GC.Tests 的原因见 ApplierTests.cs 顶部注释 —— 守护进程把 GC/src/Security
以源码链接编进了自己,与启动器程序集存在同名类型,同一工程内同时引用会撞类型。
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<RootNamespace>GC.Savedog.Tests</RootNamespace>
<AssemblyName>GC.Savedog.Tests</AssemblyName>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../../../../GC-SAVEDOG/GC-SAVEDOG.csproj" />
</ItemGroup>
</Project>
+67
View File
@@ -0,0 +1,67 @@
using System;
using System.IO;
using System.Linq;
using GC.Services;
namespace GC.Tests;
/// <summary>
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
///
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
/// </summary>
internal static class LogTests
{
private static int _failed;
public static int Run()
{
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(dir);
try
{
// 过期日志(2000 年)+ 用户自己的文件
var oldZh = Path.Combine(dir, "gc-20000101.log");
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
var userFile = Path.Combine(dir, "keep-me.txt");
File.WriteAllText(oldZh, "old");
File.WriteAllText(oldEn, "old");
File.WriteAllText(userFile, "user data");
GcLog.Init(dir);
GcLog.Info("测试中文", "test english");
var day = DateTime.Now.ToString("yyyyMMdd");
var zhPath = Path.Combine(dir, $"gc-{day}.log");
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
Check("日志目录只剩当天两份 + 用户文件",
names.Length == 3, "目录内容: " + string.Join(", ", names));
}
finally
{
try { Directory.Delete(dir, true); } catch { }
}
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
return _failed;
}
private static void Check(string label, bool ok, string detail)
{
if (ok)
{
Console.WriteLine(" ✓ " + label);
return;
}
_failed++;
Console.WriteLine($" ✗ {label} —— {detail}");
}
}
+3 -1
View File
@@ -51,7 +51,9 @@ internal static class Program
RenderPages(services);
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
return 0;
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
return LogTests.Run() == 0 ? 0 : 1;
}
/// <summary>
+4 -2
View File
@@ -59,9 +59,11 @@ mkdir -p "$ROOT_DIR/build/logs"
. "$ROOT_DIR/buildsh/build.sh"
. "$ROOT_DIR/buildsh/check.sh"
. "$ROOT_DIR/buildsh/tools.sh"
. "$ROOT_DIR/buildsh/release.sh"
case "$TASK" in
build) bs_build "$ROOT_DIR" ;;
check) bs_check "$ROOT_DIR" ;;
build) bs_build "$ROOT_DIR" ;;
check) bs_check "$ROOT_DIR" ;;
release-verify) bs_verify_release "$ROOT_DIR" "$@" ;;
*) bs_tools "$ROOT_DIR" "$TASK" ;;
esac
+6 -1
View File
@@ -6,7 +6,12 @@ function Invoke-BuildTool {
'pack-models' { Build-Models; Pack-Models }
'pack-launcher'{ Pack-Launcher }
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
'test' {
& dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots')
if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" }
# 与 pr-check.yml 一致:应用器测试单独跑(它与启动器有同名类型,不能并入 GC.Tests)
Invoke-SavedogTests
}
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
'clean' {
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
+7 -5
View File
@@ -1,7 +1,7 @@
param(
[Parameter(Position = 0)]
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
'run','test','update-test','clean','doctor','dist')]
'release-verify','run','test','update-test','clean','doctor','dist')]
[string]$Task = 'build',
[string]$Version = ''
)
@@ -23,7 +23,8 @@ try {
if (-not $Version) { $Version = '1.0.0' }
$script:BuildVersion = $Version
if ($PSBoundParameters.ContainsKey('Version')) {
# release-verify 的 -Version 是「要核对的 tag」,不是改版本号:绝不能改写清单
if ($PSBoundParameters.ContainsKey('Version') -and $Task -ne 'release-verify') {
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
$versionNode.InnerText = $Version
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
@@ -37,9 +38,10 @@ try {
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
switch ($Task) {
'build' { Invoke-FullBuild }
'check' { Invoke-BuildCheck }
default { Invoke-BuildTool $Task }
'build' { Invoke-FullBuild }
'check' { Invoke-BuildCheck }
'release-verify' { Invoke-ReleaseVerify -Tag $Version }
default { Invoke-BuildTool $Task }
}
}
finally {
+134 -70
View File
@@ -18,7 +18,9 @@ function Invoke-ManifestSign {
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
return
}
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' }
# 与 buildsh/lib/build_funcs.sh 保持一致:当前生效的密钥是 gc-2026-12。
# gc-2026-11 的私钥没有留存,用它签出来的清单客户端永远验不过。
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-12' }
Write-Host "==> 签名 version.json ($keyId)"
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
@@ -78,44 +80,41 @@ function Prepare-RuntimeLayout {
$destination = Join-Path $script:BuildRoot $RelativePath
if (-not (Test-Path $destination)) { return }
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null
Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @'
模型库目录(.GC/model/)
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
运行目录:
<可执行文件>
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
.GC/model/ 本目录(下载的模型)
.GC/cache/ 下载暂存
.GC/update/ 待下次启动应用的启动器更新
'@
$settingsPath = Join-Path $destination '.GC/config/settings.json'
if (-not (Test-Path $settingsPath)) {
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
{
"language": "auto",
"theme": "light",
"renderFps": 30,
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"requireSignedManifest": true,
"updateRepository": "https://gitcode.com/Morris_1/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
"launcherVersion": "",
"pendingLauncherVersion": "",
"lastUpdateCheck": "",
"sources": [],
"recentModels": []
# 与 buildsh/lib/build_funcs.sh 一致:发布目录只放程序本体,不预置 .GC。
# .GC(config / model / cache / update / safedog / logs)一律在首次启动时
# 由 AppPaths.EnsureCreated + RuntimeLayout 创建,压缩包里只有 GC 本体。
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples'), (Join-Path $destination '.GC') -Recurse -Force -ErrorAction SilentlyContinue
Write-Host " 运行目录 -> $RelativePath(首次启动后生成 .GC/:config model cache update safedog logs)"
}
'@
function Prune-Package {
param(
[Parameter(Mandatory)][string]$Destination,
[Parameter(Mandatory)][ValidateSet('win', 'linux')][string]$Platform
)
if (-not (Test-Path $Destination)) { return }
$junk = @(
'mscordaccore.dll', 'mscordbi.dll', 'web.config',
'aspnetcorev2_inprocess.dll',
'Microsoft.AspNetCore.Server.IIS.dll',
'Microsoft.AspNetCore.Server.IISIntegration.dll',
'Microsoft.AspNetCore.Server.HttpSys.dll',
'Microsoft.DiaSymReader.Native.dll'
)
if ($Platform -eq 'win') {
# 后端已编入启动器,ProjectReference 残留的独立 exe / runtimeconfig 没有用
$junk += @('GC.UI.Server.exe', 'GC.UI.Server.dll', 'GC.UI.Server.deps.json', 'GC.UI.Server.runtimeconfig.json')
$junk += @('Avalonia.X11.dll', 'Avalonia.Native.dll', 'Avalonia.FreeDesktop.dll', 'Tmds.DBus.Protocol.dll')
}
Write-Host " 运行目录 -> $RelativePath/.GC"
else {
$junk += @('Avalonia.Win32.dll', 'Avalonia.Win32.Automation.dll')
}
foreach ($name in $junk) {
Get-ChildItem $Destination -Filter $name -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
}
# mscordaccore*.dll / Microsoft.DiaSymReader.Native*.dll 是带版本号通配的
Get-ChildItem $Destination -Filter 'mscordaccore*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
Get-ChildItem $Destination -Filter 'Microsoft.DiaSymReader.Native*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
}
function Publish-Rid {
@@ -132,18 +131,22 @@ function Publish-Rid {
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
"-p:EnableCompressionInSingleFile=$singleValue",
'-p:PublishTrimmed=false', '-o', $outputPath
)
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
# 更新守护进程:与主程序同目录(裁剪 + 压缩单文件,70MB -> 14MB)
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)。
# EnableCompressionInSingleFile:守护进程不常驻,只在更新时跑一次,
# 解压一次换来更小的包,对「只在更新时下载」的场景很划算。
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
if (Test-Path $savedogProj) {
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)"
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪 + 压缩单文件)"
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
'-p:EnableCompressionInSingleFile=true',
'-p:PublishTrimmed=true', '-p:TrimMode=full',
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
)
@@ -178,35 +181,60 @@ function Pack-Models {
function Pack-Launcher {
$dist = Join-Path $script:BuildRoot 'dist'
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
Write-Host "==> 生成启动器产物(GCL-$script:BuildVersion-<系统>-<架构>)"
# 与 buildsh/lib/build_funcs.sh 的 pack_launcher 对齐:
# 1) 包名统一 GCL- 前缀;
# 2) zip 内只有一个顶层目录(GCL-<版本>-<平台>),不散落一屏 dll;
# 3) 非本体文件(守护进程)收进 .GC/bin,安装目录根只留 GC 本体;
# 4) 剔除调试 / 无关平台的组件(prune)。
# --- Windows:启动器 + 守护进程 + 前端,整目录打进单顶层目录 ---
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
# 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致
$sourceDir = Join-Path $dist $platform.Label
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
if (-not (Test-Path $sourceDir)) { continue }
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
$executable = Get-ChildItem $sourceDir -Filter '*.exe' |
Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1
if ($null -eq $executable) { continue }
# 启动器固定是 GC.exe;后端与前端是可选的随包产物,不能当成启动器
$exe = Join-Path $sourceDir 'GC.exe'
if (-not (Test-Path $exe)) {
$exe = (Get-ChildItem $sourceDir -Filter '*.exe' | Where-Object {
$_.Name -notlike 'GC-SAVEDOG*' -and $_.Name -notlike 'GC.UI.Server*' -and $_.Name -notlike 'GC-UI*'
} | Select-Object -First 1).FullName
}
if (-not $exe) { continue }
$pkgName = "GCL-$script:BuildVersion-$($platform.Label)"
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
$pkg = Join-Path $temp $pkgName
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $temp | Out-Null
Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force
$savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe'
if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force }
New-Item -ItemType Directory -Force -Path $pkg | Out-Null
Get-ChildItem $sourceDir -Force | Where-Object { $_.Extension -ne '.zip' } | Copy-Item -Destination $pkg -Recurse -Force
Prune-Package -Destination $pkg -Platform 'win'
Move-Item (Join-Path $pkg (Split-Path $exe -Leaf)) (Join-Path $pkg "$pkgName.exe") -Force
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $pkg "$pkgName.exe") 2>$null }
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
$savedogExe = Join-Path $pkg 'GC-SAVEDOG.exe'
if (Test-Path $savedogExe) {
$binDir = Join-Path $pkg '.GC/bin'
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
Move-Item $savedogExe (Join-Path $binDir 'GC-SAVEDOG.exe') -Force
}
else {
Write-Host " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
}
$zipPath = Join-Path $dist "$($platform.Label)/$pkgName.zip"
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
Compress-Archive -Path $pkg -DestinationPath $zipPath -CompressionLevel Optimal
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
Write-Host " -> dist/$($platform.Label)/$pkgName.zip"
}
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist + 守护进程入 .GC/bin) ---
$macApp = Join-Path $dist 'mac-arm64/GC.app'
if (Test-Path $macApp) {
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
$finalApp = Join-Path $dist "GCL-$script:BuildVersion-mac-arm64.app"
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
Move-Item $macApp $finalApp
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
@@ -216,20 +244,25 @@ function Pack-Launcher {
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
}
# 非本体文件收进 .GC/bin(与 Windows 布局一致):.GC 位置不变,仍在 .app/Contents/MacOS/
$savedog = Join-Path $finalApp 'Contents/MacOS/GC-SAVEDOG'
if (Test-Path $savedog) {
$binDir = Join-Path $finalApp 'Contents/MacOS/.GC/bin'
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
Move-Item $savedog (Join-Path $binDir 'GC-SAVEDOG') -Force
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $binDir 'GC-SAVEDOG') 2>$null }
}
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
}
# Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
$label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", ''
# --- 统一压缩:.app -> 同名 .zip,放进平台目录 ---
Get-ChildItem $dist | Where-Object { $_.Name -like "GCL-$script:BuildVersion-*.app" } | ForEach-Object {
$label = $_.BaseName -replace "^GCL-$([regex]::Escape($script:BuildVersion))-", ''
$targetDir = Join-Path $dist $label
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
if ($_.PSIsContainer) {
Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
}
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
if (Get-Command ditto -ErrorAction SilentlyContinue) {
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
}
@@ -239,26 +272,26 @@ function Pack-Launcher {
Write-Host " -> dist/$label/$($_.BaseName).zip"
}
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
# 原始产物(.exe / .app 目录)不再保留:只发布 zip(移入暂存区,不做递归删除)
$trash = Join-Path $script:BuildRoot 'build/trash'
New-Item -ItemType Directory -Force -Path $trash | Out-Null
Get-ChildItem $dist -Force | Where-Object {
$_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app"
$_.Name -like "GCL-$script:BuildVersion-*.exe" -or $_.Name -like "GCL-$script:BuildVersion-*.app"
} | ForEach-Object {
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
}
Remove-IntermediateDirectories
Invoke-VersionStamp -LauncherOnly
Write-Host '==> dist 可发布 zip:'
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
Get-ChildItem $dist -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
function Remove-IntermediateDirectories {
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64', 'linux-arm64', 'linux-x64')) {
$dir = Join-Path $script:BuildRoot "dist/$name"
if (-not (Test-Path $dir)) { continue }
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } |
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GCL-$script:BuildVersion-*.zip" } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
@@ -314,6 +347,36 @@ function New-MacAppBundle {
Write-Host "==> 已打包 $app"
}
function Invoke-SavedogTests {
$proj = Join-Path $script:BuildRoot 'GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj'
Write-Host '==> 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)'
& dotnet run --project $proj -c Debug
if ($LASTEXITCODE -ne 0) { throw "应用器测试失败,退出码 $LASTEXITCODE" }
}
function Invoke-ReleaseVerify {
param([string]$Tag = '')
$root = $script:BuildRoot
$verifyTag = if ($Tag) { $Tag } else { $script:BuildVersion }
$work = Join-Path $root 'build/release-verify'
New-Item -ItemType Directory -Force -Path $work | Out-Null
Write-Host "==> 核对 Release $verifyTag"
$dump = Join-Path $work "$verifyTag.json"
& python3 (Join-Path $root 'buildsh/lib/verify_release.py') `
--tag $verifyTag `
--manifest (Join-Path $root 'version.json') `
--dump-manifest $dump
if ($LASTEXITCODE -ne 0) { throw "发布一致性核对未通过(tag $verifyTag)" }
Write-Host ''
Write-Host '==> 校验 tag 清单签名'
& dotnet run --project (Join-Path $root 'GC-SAVEDOG/GC-SAVEDOG.csproj') -c Release -- `
verify --manifest $dump
if ($LASTEXITCODE -ne 0) { throw '清单签名校验未通过,客户端会拒绝这次更新' }
Write-Host '结论: 签名可信,可以发布 / 已经发布正确'
}
function Invoke-FullBuild {
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
try {
@@ -323,9 +386,10 @@ function Invoke-FullBuild {
Complete-BuildStep
Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; Complete-BuildStep
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $false; Complete-BuildStep
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $false; Complete-BuildStep
# 与 buildsh 一致:启动器与守护进程都发布为压缩单文件,非本体文件在打包时收进 .GC/bin
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $true; Complete-BuildStep
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
Start-BuildStep '运行骨架'
New-MacAppBundle
@@ -337,7 +401,7 @@ function Invoke-FullBuild {
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
Start-BuildStep '收尾'; Complete-BuildStep
Write-Host '==> 完成,产物:'
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
}
finally { Complete-BuildProgress }
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""核对「仓库清单 ↔ Release 资产」是否对得上。
为什么需要它:清单里的 sha256 是客户端验证下载包的唯一依据。一旦 Release 上的资产
和清单不是同一份(换过一次构建、上传了别的产物、tag 指到了旧提交),客户端会验签
失败或直接回滚 —— 用户看到的是「更新失败了」,而服务端一切正常。
检查项:
1. tag 指向的 version.json 里的 launcher.version 等于 tag 名;
2. 清单里带 sha256 的平台,Release 上有同名资产,且体积 / sha256 完全一致;
3. 清单里没有 sha256 的平台(本次没构建)不要求有资产,但会列出;
4. Release 上多出来的资产(清单里没有)单独提示;
5. 本地清单与 tag 上的清单是否字节一致。
只用标准库,Linux / macOS / Windows 上都能跑。
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
import urllib.error
import urllib.request
DEFAULT_BASE = os.environ.get("GC_GITEA_URL", "https://git.xhmcl.com")
DEFAULT_REPO = os.environ.get("GC_GITEA_REPO", "Morris/GC")
def log(msg: str = "") -> None:
print(msg, flush=True)
def http_json(url: str, token: str | None) -> dict:
req = urllib.request.Request(url)
req.add_header("Accept", "application/json")
if token:
req.add_header("Authorization", "token " + token)
with urllib.request.urlopen(req, timeout=60) as resp:
return json.loads(resp.read().decode("utf-8"))
def download_sha256(url: str, token: str | None, dest: str) -> tuple[int, str]:
req = urllib.request.Request(url)
if token:
req.add_header("Authorization", "token " + token)
digest = hashlib.sha256()
size = 0
with urllib.request.urlopen(req, timeout=600) as resp, open(dest, "wb") as out:
while True:
chunk = resp.read(1 << 20)
if not chunk:
break
size += len(chunk)
digest.update(chunk)
out.write(chunk)
return size, digest.hexdigest()
def main() -> int:
parser = argparse.ArgumentParser(description="核对清单与 Release 资产")
parser.add_argument("--tag", required=True, help="要核对的 tag,例如 1.1.0")
parser.add_argument("--manifest", default="version.json", help="本地清单路径(用于对比)")
parser.add_argument("--base-url", default=DEFAULT_BASE)
parser.add_argument("--repo", default=DEFAULT_REPO)
parser.add_argument("--token", default=os.environ.get("GC_GITEA_TOKEN"))
parser.add_argument("--workdir", default=None, help="下载临时目录(默认系统临时目录)")
parser.add_argument("--skip-download", action="store_true",
help="只核对清单体积与资产列表,不下载算哈希")
parser.add_argument("--dump-manifest", default=None,
help="把 tag 上的清单原样写到这个路径(供 GC-SAVEDOG verify 验签)")
args = parser.parse_args()
tag = args.tag.strip()
if tag.startswith("v"):
tag = tag[1:]
api = f"{args.base_url}/api/v1/repos/{args.repo}"
workdir = args.workdir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "build", "release-verify")
workdir = os.path.abspath(workdir)
os.makedirs(workdir, exist_ok=True)
failures: list[str] = []
warnings: list[str] = []
# ---- 1. tag 上的清单 ----
try:
remote = http_json(f"{api}/raw/version.json?ref={tag}", args.token)
except urllib.error.HTTPError as exc:
log(f"!! 取不到 tag {tag} 的 version.json(HTTP {exc.code})")
return 1
if args.dump_manifest:
os.makedirs(os.path.dirname(os.path.abspath(args.dump_manifest)), exist_ok=True)
with open(args.dump_manifest, "w", encoding="utf-8") as fh:
json.dump(remote, fh, ensure_ascii=False, indent=2)
launcher = remote.get("launcher") or {}
remote_version = str(launcher.get("version") or "")
log(f"tag : {tag}")
log(f"清单版本 : {remote_version or '(空)'}")
if remote_version != tag:
failures.append(f"tag 指向的清单版本是 {remote_version!r},与 tag {tag} 不一致")
# 签名状态:交给 GC-SAVEDOG verify 判定(这里只提示有没有签名段)
if not remote.get("signature"):
failures.append("tag 上的清单没有签名段")
else:
log(f"清单签名 : {remote['signature'].get('keyId', '?')}")
# ---- 2. Release 与资产 ----
try:
release = http_json(f"{api}/releases/tags/{tag}", args.token)
except urllib.error.HTTPError as exc:
log(f"!! 取不到 Release {tag}(HTTP {exc.code})")
return 1
assets = {a["name"]: a for a in release.get("assets") or []}
log(f"Release : id={release.get('id')} prerelease={release.get('prerelease')}")
log(f"资产数量 : {len(assets)}")
packages = launcher.get("packages") or {}
declared: set[str] = set()
log("")
log(f"{'平台':<12} {'包':<32} {'结果'}")
log("-" * 78)
for rid, pkg in packages.items():
name = str(pkg.get("name") or "")
want_sha = str(pkg.get("sha256") or "")
want_size = int(pkg.get("size") or 0)
if not name:
warnings.append(f"{rid}: 清单条目没有 name")
continue
declared.add(name)
asset = assets.get(name)
if not want_sha:
log(f"{rid:<12} {name:<32} 未构建(清单无 sha256)")
if asset:
warnings.append(f"{rid}: 清单没记录哈希,但 Release 上有 {name}")
continue
if not asset:
log(f"{rid:<12} {name:<32} ✗ 资产缺失")
failures.append(f"{rid}: Release 上找不到 {name}")
continue
if int(asset.get("size") or 0) != want_size:
log(f"{rid:<12} {name:<32} ✗ 体积不符 {asset.get('size')} != {want_size}")
failures.append(f"{rid}: {name} 体积 {asset.get('size')},清单 {want_size}")
continue
if args.skip_download:
log(f"{rid:<12} {name:<32} ✓ 体积一致(未下载)")
continue
url = asset.get("browser_download_url") or f"{args.base_url}/{args.repo}/releases/download/{tag}/{name}"
dest = os.path.join(workdir, name)
try:
size, sha = download_sha256(url, args.token, dest)
os.remove(dest)
except Exception as exc: # noqa: BLE001 - 下载失败一律按失败上报
log(f"{rid:<12} {name:<32} ✗ 下载失败: {exc}")
failures.append(f"{rid}: 下载 {name} 失败: {exc}")
continue
if size != want_size or sha != want_sha:
log(f"{rid:<12} {name:<32} ✗ sha256 不符")
log(f" 期望 {want_sha}")
log(f" 实际 {sha}")
failures.append(f"{rid}: {name} sha256 与清单不符")
else:
log(f"{rid:<12} {name:<32} ✓ {size:,} B sha {sha[:16]}…")
extra = sorted(set(assets) - declared)
if extra:
warnings.append("Release 上有清单未声明的资产: " + ", ".join(extra))
# ---- 3. 本地清单对比 ----
if os.path.isfile(args.manifest):
with open(args.manifest, "rb") as fh:
local_raw = fh.read()
local = json.loads(local_raw.decode("utf-8"))
local_packages = (local.get("launcher") or {}).get("packages") or {}
if local_packages != packages:
warnings.append("本地清单的 packages 与 tag 上的不一致(本地可能是未发布的构建)")
else:
log("")
log("本地清单与 tag 上的 packages 一致")
# ---- 汇总 ----
log("")
for w in warnings:
log("警告: " + w)
if failures:
for f in failures:
log("失败: " + f)
log("")
log("结论: 不一致 —— 客户端会拒绝或回滚这次更新")
return 1
log("结论: 一致 —— 清单、tag、资产三者对得上")
return 0
if __name__ == "__main__":
sys.exit(main())
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# buildsh/release.sh —— 发布一致性核对
#
# ./build.sh release-verify # 核对当前版本号对应的 tag
# ./build.sh release-verify 1.1.0 # 核对指定 tag
# ./build.sh release-verify 1.1.0 --skip-download # 只看体积,不下载
#
# 检查的是「tag 指向的清单 / Release 上的资产 / 清单里的 sha256」三者是否互相对得上。
# 客户端的升级判断完全依赖这三者:任何一处错位,用户侧就是验签失败或安全回滚。
bs_verify_release() {
ROOT_DIR="$1"; shift
TAG="${1:-$VERSION}"
if [ "$#" -gt 0 ]; then shift; fi
WORK="$ROOT_DIR/build/release-verify"
mkdir -p "$WORK"
echo "==> 核对 Release ${TAG}"
rc=0
python3 "$ROOT_DIR/buildsh/lib/verify_release.py" \
--tag "$TAG" \
--manifest "$ROOT_DIR/version.json" \
--dump-manifest "$WORK/$TAG.json" \
"$@" || rc=$?
if [ "$rc" -ne 0 ]; then
return "$rc"
fi
# 资产对得上还不够:清单本身必须是我签的,否则客户端一样会拒
echo ""
echo "==> 校验 tag 清单签名"
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
verify --manifest "$WORK/$TAG.json"; then
echo "结论: 签名可信,可以发布 / 已经发布正确"
return 0
fi
echo "!! 签名校验未通过,客户端会拒绝这次更新"
return 1
}