405 lines
23 KiB
C#
405 lines
23 KiB
C#
// 配方包冒烟:验证导出/检查/导入的往返一致性、覆盖归档与改名建议,以及篡改包、越界路径、清单外文件和体积骗局的拒绝行为。
|
||
|
||
using System.IO.Compression;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.Recipes;
|
||
|
||
internal static class Program
|
||
{
|
||
private static string Root = "";
|
||
|
||
[STAThread]
|
||
public static int Main()
|
||
{
|
||
Root = Path.Combine(Path.GetTempPath(), "recipe-package-smoke-" + Guid.NewGuid().ToString("N"));
|
||
Directory.CreateDirectory(Root);
|
||
try
|
||
{
|
||
Run();
|
||
Console.WriteLine("RecipePackage smoke:全部检查通过");
|
||
return 0;
|
||
}
|
||
catch (Exception error)
|
||
{
|
||
Console.Error.WriteLine("FAIL: " + error.Message);
|
||
return 1;
|
||
}
|
||
finally
|
||
{
|
||
// 只清理本次测试自建目录,不触碰任何程序数据。
|
||
if (Path.GetFileName(Root).StartsWith("recipe-package-smoke-") && Directory.Exists(Root)) Directory.Delete(Root, true);
|
||
}
|
||
}
|
||
|
||
/// <summary>验证配方覆盖保存及替换失败后的临时文件清理。</summary>
|
||
private static void AtomicYamlSave()
|
||
{
|
||
var folder = Directory.CreateDirectory(Path.Combine(Root, "atomic-save")).FullName;
|
||
var path = Path.Combine(folder, "atomic.yaml");
|
||
var config = new SopConfig();
|
||
config.Sop.Name = "原配方";
|
||
SopConfigLoader.Save(config, path);
|
||
config.Sop.Name = "新配方";
|
||
if (OperatingSystem.IsWindows())
|
||
{
|
||
// 独占打开正式配方,确保替换失败时旧内容仍可读。
|
||
using (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
|
||
{
|
||
try
|
||
{
|
||
SopConfigLoader.Save(config, path);
|
||
throw new Exception("文件被占用时应拒绝替换");
|
||
}
|
||
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
|
||
}
|
||
Check(SopConfigLoader.Load(path).Sop.Name == "原配方", "原子替换失败时保留原配方");
|
||
}
|
||
Check(SopConfigLoader.Save(config, path).Sop.Name == "新配方"
|
||
&& SopConfigLoader.Load(path).Sop.Name == "新配方", "原子保存可覆盖原配方并返回重载结果");
|
||
Check(Directory.GetFiles(folder, "atomic.yaml.*.tmp").Length == 0, "原子保存不残留临时文件");
|
||
}
|
||
|
||
private static void Run()
|
||
{
|
||
AtomicYamlSave();
|
||
LegacyWorkspace();
|
||
CompletionImageRoundNumbering();
|
||
RoundTrip();
|
||
OverwriteAndRename();
|
||
RejectedPackages();
|
||
MissingStandardVideo();
|
||
}
|
||
|
||
/// <summary>用固定时间验证同秒、重启、并发换号以及跨日和跨配方从零计数。</summary>
|
||
private static void CompletionImageRoundNumbering()
|
||
{
|
||
var workspace = new RecipeWorkspace(Path.Combine(Root, "round-numbering"));
|
||
const string recipe = "轮次检测";
|
||
var startedAt = new DateTime(2026, 12, 4, 15, 30, 25);
|
||
var archive = Path.Combine(workspace.DirectoryFor(recipe), "completion-images");
|
||
Directory.CreateDirectory(Path.Combine(archive, "20261204-153025-123"));
|
||
Directory.CreateDirectory(Path.Combine(archive, "2026-12-04_notes-99"));
|
||
Directory.CreateDirectory(Path.Combine(archive, "2026-12-03_15-30-25-99"));
|
||
|
||
var first = workspace.CreateCompletionImageRound(recipe, startedAt);
|
||
Check(first == Path.Combine(archive, "2026-12-04_15-30-25-0") && Directory.Exists(first),
|
||
"当天首轮使用规定的日期时间格式并从 0 开始");
|
||
var reopened = new RecipeWorkspace(workspace.Root);
|
||
Check(Path.GetFileName(reopened.CreateCompletionImageRound(recipe, startedAt)) == "2026-12-04_15-30-25-1",
|
||
"重新打开工作区后,同秒启动仍从当天现有目录续号");
|
||
|
||
var sameDay = new string[12];
|
||
Parallel.For(0, sameDay.Length, i =>
|
||
{
|
||
var path = reopened.CreateCompletionImageRound(recipe, startedAt.AddSeconds(i + 1));
|
||
sameDay[i] = Path.GetFileName(path);
|
||
});
|
||
Check(sameDay.Select(name => int.Parse(name[(name.LastIndexOf('-') + 1)..])).Order().SequenceEqual(Enumerable.Range(2, 12)),
|
||
"同配方并发建目录时,日序号连续且没有重复");
|
||
|
||
var tomorrow = startedAt.Date.AddDays(1);
|
||
Check(Path.GetFileName(reopened.CreateCompletionImageRound(recipe, tomorrow)) == "2026-12-05_00-00-00-0",
|
||
"跨过本地午夜后新一天从 0 开始");
|
||
Check(Path.GetFileName(reopened.CreateCompletionImageRound("其他配方", startedAt)) == "2026-12-04_15-30-25-0",
|
||
"每个配方各自按天编号");
|
||
}
|
||
|
||
/// <summary>旧训练文件即使已损坏,也不应阻塞配方和标准视频迁移。</summary>
|
||
private static void LegacyWorkspace()
|
||
{
|
||
const string name = "旧配方";
|
||
var source = new RecipeWorkspace(Path.Combine(Root, "legacy"));
|
||
var target = new RecipeWorkspace(Path.Combine(Root, "migrated"));
|
||
var standard = Path.Combine(source.Root, "workspace", "training", name, "sop_stand");
|
||
var history = Path.Combine(Path.GetDirectoryName(standard)!, "parts", "project.json");
|
||
var configs = Path.Combine(source.Root, "configs");
|
||
Directory.CreateDirectory(standard);
|
||
Directory.CreateDirectory(Path.GetDirectoryName(history)!);
|
||
Directory.CreateDirectory(configs);
|
||
File.WriteAllText(history, "旧标注文件内容,即使不是有效 JSON 也保留");
|
||
File.WriteAllBytes(Path.Combine(standard, "sop.avi"), [1, 2, 3]);
|
||
File.WriteAllText(Path.Combine(configs, name + ".yaml"), """
|
||
sop:
|
||
name: 旧配方
|
||
model: { path: old.onnx }
|
||
parts: [支架]
|
||
steps:
|
||
- id: 1
|
||
description: 放好支架
|
||
completion_image_directory: done
|
||
must_keep: [支架]
|
||
detection: { method: object_present, target_object: 支架 }
|
||
""");
|
||
source.Initialize(configs);
|
||
var config = SopConfigLoader.Load(source.ConfigPath(name));
|
||
Check(config.Warnings.Any(w => w.Contains("已移除或不支持")) && config.Sop.Steps[0].MustKeep.SequenceEqual(new[] { "支架" }),
|
||
"旧物体条件继续提示迁移并保留物料描述");
|
||
Check(!File.ReadAllText(source.ConfigPath(name)).Contains("model:") &&
|
||
File.Exists(Path.Combine(source.DirectoryFor(name), "sop_stand", "sop.avi")) &&
|
||
!Directory.Exists(Path.Combine(source.DirectoryFor(name), "parts")) && File.Exists(history),
|
||
"散放旧配方只迁移标准视频,历史标注文件保留在原处");
|
||
|
||
var oldCompletion = Path.Combine(source.DirectoryFor(name), "done");
|
||
Directory.CreateDirectory(oldCompletion);
|
||
File.WriteAllText(Path.Combine(oldCompletion, "historical.png"), "旧结束图");
|
||
var archivedRecord = Path.Combine(source.DirectoryFor(name), "recipe-training.json");
|
||
File.WriteAllText(archivedRecord, "历史文件按字节复制");
|
||
target.ImportFrom(source.Root);
|
||
target.Initialize();
|
||
Check(!File.ReadAllText(target.ConfigPath(name)).Contains("completion_image_directory") &&
|
||
File.ReadAllBytes(Path.Combine(target.DirectoryFor(name), "recipe-training.json")).SequenceEqual(File.ReadAllBytes(archivedRecord)) &&
|
||
File.Exists(Path.Combine(target.DirectoryFor(name), "done", "historical.png")),
|
||
"整目录导入时清理旧结束图设置并保留已有图片和历史文件");
|
||
}
|
||
|
||
/// <summary>验证配方包往返保留步骤和保存开关,并清理临时文件。</summary>
|
||
private static void RoundTrip()
|
||
{
|
||
var source = new RecipeWorkspace(Path.Combine(Root, "source"));
|
||
var target = new RecipeWorkspace(Path.Combine(Root, "target"));
|
||
const string name = "装配";
|
||
Seed(source, name);
|
||
|
||
// 目标路径缺扩展名时补 .bwsrecipe,现场直接按扩展名识别配方包。
|
||
var package = RecipePackage.Export(source, name, Path.Combine(Root, name)).Path;
|
||
Check(Path.GetExtension(package) == RecipePackage.Extension, "导出自动补上配方包扩展名");
|
||
Check(File.Exists(package) && !File.Exists(package + ".tmp"), "导出原子落位且不留下临时包");
|
||
Check(Directory.EnumerateFileSystemEntries(source.DirectoryFor(name)).All(entry => !Path.GetFileName(entry).Contains("export-")),
|
||
"导出不在配方目录留下临时文件");
|
||
Check(!Directory.EnumerateFiles(Root, "*.yaml").Any(), "导出不残留临时配方文件");
|
||
|
||
var info = RecipePackage.Inspect(package);
|
||
Check(info.RecipeName == name && info.FileCount == 3 && info.HasStandardVideo && info.TotalBytes > 0, "包摘要给出配方名、文件数、体积与标准视频");
|
||
Check(info.ExportedAt is not null && !string.IsNullOrWhiteSpace(info.ApplicationVersion), "包记录导出时间和导出程序版本");
|
||
|
||
var imported = RecipePackage.Import(target, package, name, false);
|
||
Check(imported.Name == name && !imported.Overwrote && imported.ArchivedPath is null, "首次导入不声明覆盖也没有归档");
|
||
Check(File.Exists(target.ConfigPath(name)), "导入生成配方配置文件");
|
||
Check(Directory.GetDirectories(target.RecipesDirectory).Single() == target.DirectoryFor(name), "导入不留暂存目录");
|
||
Check(Directory.GetFileSystemEntries(target.DirectoryFor(name)).Length == 2
|
||
&& Directory.Exists(Path.Combine(target.DirectoryFor(name), "done")) == false, "导入目录只包含包内文件,不创建空目录");
|
||
Check(File.ReadAllText(Path.Combine(target.DirectoryFor(name), "sop_stand", "sop.avi")) == "fake-avi"
|
||
&& File.Exists(Path.Combine(target.DirectoryFor(name), "sop_stand", "duration.json")), "标准 SOP 视频与时长时间缓存一起随包迁移");
|
||
|
||
var migrated = SopConfigLoader.Load(target.ConfigPath(name));
|
||
Check(migrated.Sop.Name == name && migrated.Sop.Steps.Count == 2 && migrated.Sop.Regions.ContainsKey("取料"), "导入保留步骤、区域和配方名");
|
||
Check(migrated.Sop.Steps[0].Description.Contains("握住物料") && migrated.Sop.Steps[1].Detection!.Method == ConditionMethod.TimeElapsed,
|
||
"步骤说明与判定方法逐字迁移,不经界面重写");
|
||
Check(migrated.Sop.Steps[0].SaveCompletionImage && !migrated.Sop.Steps[1].SaveCompletionImage,
|
||
"配方包保留各步骤的结束图保存开关");
|
||
|
||
var reimported = RecipePackage.Export(target, name, Path.Combine(Root, "re-export")).Path;
|
||
var second = RecipePackage.Inspect(reimported);
|
||
Check(second.FileCount == 3 && second.HasStandardVideo, "导入后的配方可再次导出");
|
||
}
|
||
|
||
/// <summary>覆盖导入的归档行为、改名导入和改名建议。</summary>
|
||
private static void OverwriteAndRename()
|
||
{
|
||
var source = new RecipeWorkspace(Path.Combine(Root, "source2"));
|
||
var target = new RecipeWorkspace(Path.Combine(Root, "target2"));
|
||
const string name = "装配";
|
||
Seed(source, name);
|
||
var package = RecipePackage.Export(source, name, Path.Combine(Root, "pack2")).Path;
|
||
|
||
var renamed = RecipePackage.Import(target, package, "装配二", false);
|
||
Check(renamed.Name == "装配二" && File.Exists(target.ConfigPath("装配二")) && SopConfigLoader.Load(target.ConfigPath("装配二")).Sop.Name == "装配二",
|
||
"改名导入同时改写目录名、文件名和 sop.name");
|
||
Check(Directory.GetFiles(target.DirectoryFor("装配二"), "*.yaml").Single().EndsWith("装配二.yaml"), "改名导入不留下包内旧文件名");
|
||
|
||
File.WriteAllText(Path.Combine(target.DirectoryFor("装配二"), "marker.txt"), "旧现场数据");
|
||
var refused = Catch(() => RecipePackage.Import(target, package, "装配二", false));
|
||
Check(refused is IOException && refused.Message.Contains("已存在"), "同名配方未选择覆盖时拒绝导入");
|
||
Check(File.Exists(Path.Combine(target.DirectoryFor("装配二"), "marker.txt")), "被拒绝的覆盖导入不动已有配方");
|
||
|
||
var overwritten = RecipePackage.Import(target, package, "装配二", true);
|
||
Check(overwritten.Overwrote && overwritten.ArchivedPath is not null && overwritten.Warnings.Any(w => w.Contains("归档")),
|
||
"覆盖导入报告归档位置");
|
||
Check(!File.Exists(Path.Combine(target.DirectoryFor("装配二"), "marker.txt")) && File.Exists(target.ConfigPath("装配二")),
|
||
"覆盖导入用包内容替换配方目录");
|
||
Check(Directory.GetFiles(overwritten.ArchivedPath!, "marker.txt", SearchOption.AllDirectories).Length == 1, "旧配方数据完整保留在归档目录");
|
||
Check(Directory.GetDirectories(target.RecipesDirectory).Select(Path.GetFileName).SequenceEqual(new[] { "装配二" }), "覆盖导入不产生额外配方目录");
|
||
|
||
Check(RecipePackage.SuggestName(target, name) == name, "名称未被占用时建议原名");
|
||
Check(RecipePackage.SuggestName(target, "装配二") == "装配二-2", "已有同名配方时建议追加 -2");
|
||
Directory.CreateDirectory(target.DirectoryFor("装配二-2"));
|
||
File.WriteAllText(target.ConfigPath("装配二-2"), "x");
|
||
Check(RecipePackage.SuggestName(target, "装配二") == "装配二-3", "连续占用时建议下一个可用名称");
|
||
|
||
var stray = Path.Combine(target.RecipesDirectory, "散目录");
|
||
Directory.CreateDirectory(stray);
|
||
var strayError = Catch(() => RecipePackage.Import(target, package, "散目录", true));
|
||
Check(strayError is IOException && strayError.Message.Contains("不是有效配方"), "同名散目录不会被导入静默吞掉");
|
||
}
|
||
|
||
/// <summary>损坏包、非配方包、越界路径、清单外文件和高版本包全部拒绝,且不写入配方目录。</summary>
|
||
private static void RejectedPackages()
|
||
{
|
||
var source = new RecipeWorkspace(Path.Combine(Root, "source3"));
|
||
var target = new RecipeWorkspace(Path.Combine(Root, "target3"));
|
||
Seed(source, "装配");
|
||
var package = RecipePackage.Export(source, "装配", Path.Combine(Root, "pack3")).Path;
|
||
|
||
var tampered = Tamper(package, keepLength: true);
|
||
var hashError = Catch(() => RecipePackage.Import(target, tampered, "装配", false));
|
||
Check(hashError is InvalidDataException && hashError.Message.Contains("散列"), "包内配方文件被改写后散列校验拒绝导入");
|
||
Check(!Directory.Exists(target.DirectoryFor("装配")) && !Directory.EnumerateDirectories(target.RecipesDirectory).Any(dir => dir.Contains(".importing-")),
|
||
"散列校验失败不留半成品配方目录");
|
||
|
||
var resized = Tamper(package, keepLength: false);
|
||
var sizeError = Catch(() => RecipePackage.Inspect(resized));
|
||
Check(sizeError is InvalidDataException && sizeError.Message.Contains("大小不一致"), "包内文件与清单大小不符时检查阶段就拒绝");
|
||
|
||
var extra = AddEntry(package, "extra/notes.txt", "夹带文件");
|
||
var extraError = Catch(() => RecipePackage.Import(target, extra, "装配", false));
|
||
Check(extraError is InvalidDataException && extraError.Message.Contains("清单之外"), "清单外的夹带文件拒绝导入");
|
||
|
||
var noManifest = Craft("非配方包", null, ("说明.txt", "随手压的 zip"));
|
||
Check(Catch(() => RecipePackage.Inspect(noManifest)).Message!.Contains("package.json"), "缺少清单的普通 zip 判定为非配方包");
|
||
|
||
var future = Craft("高版本包", Manifest("新装配", RecipePackage.FormatVersion + 99, ("recipe/新装配.yaml", 2, Sha("ab"))), ("recipe/新装配.yaml", "ab"));
|
||
Check(Catch(() => RecipePackage.Inspect(future)).Message!.Contains("更新版本"), "更高格式版本的包要求先升级程序");
|
||
|
||
var traversal = Craft("越界包", Manifest("越界", 1, ("../../evil.txt", 4, Sha("evil"))), ("../../evil.txt", "evil"));
|
||
var traversalError = Catch(() => RecipePackage.Inspect(traversal));
|
||
Check(traversalError is InvalidDataException && traversalError.Message.Contains("路径不安全"), "包含 .. 越界路径的包被拒绝");
|
||
Check(!File.Exists(Path.Combine(target.RecipesDirectory, "..", "..", "evil.txt")), "越界包没有写出配方目录之外的文件");
|
||
|
||
var absolute = Craft("绝对路径包", Manifest("越界", 1, ("C:/windows/evil.txt", 4, Sha("evil"))), ("C:/windows/evil.txt", "evil"));
|
||
Check(Catch(() => RecipePackage.Inspect(absolute)).Message!.Contains("路径不安全"), "包含盘符绝对路径的包被拒绝");
|
||
|
||
var nested = Craft("深层路径包", Manifest("越界", 1, ("recipe/sub/a.yaml", 2, Sha("ab"))), ("recipe/sub/a.yaml", "ab"));
|
||
Check(Catch(() => RecipePackage.Inspect(nested)).Message!.Contains("路径不安全"), "超出约定布局的深层条目被拒绝");
|
||
}
|
||
|
||
/// <summary>未录制标准 SOP 的配方也能成包,并明确提醒导入后需要重录。</summary>
|
||
private static void MissingStandardVideo()
|
||
{
|
||
var source = new RecipeWorkspace(Path.Combine(Root, "source4"));
|
||
var target = new RecipeWorkspace(Path.Combine(Root, "target4"));
|
||
Directory.CreateDirectory(source.DirectoryFor("无视频"));
|
||
var config = new SopConfig(); config.Sop.Name = "无视频";
|
||
config.Sop.Steps = [new StepDef { Id = 1, Name = "计时", Description = "步骤说明:等待两秒", Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }];
|
||
SopConfigLoader.Save(config, source.ConfigPath("无视频"));
|
||
|
||
var info = RecipePackage.Inspect(RecipePackage.Export(source, "无视频", Path.Combine(Root, "pack4")).Path);
|
||
Check(info.FileCount == 1 && !info.HasStandardVideo && info.Warnings.Any(w => w.Contains("标准 SOP 视频")), "缺标准视频的配方包明确提醒");
|
||
Check(File.Exists(target.ConfigPath("无视频")) == false && RecipePackage.Import(target, Path.Combine(Root, "pack4.bwsrecipe"), "无视频", false).Name == "无视频",
|
||
"缺标准视频的配方包仍可正常导入");
|
||
Check(SopConfigLoader.Load(target.ConfigPath("无视频")).Sop.Steps.Single().Name == "计时", "导入后的步骤内容一致");
|
||
}
|
||
|
||
/// <summary>写入带有标准视频及不同结束图开关状态的测试配方。</summary>
|
||
private static void Seed(RecipeWorkspace workspace, string name)
|
||
{
|
||
Directory.CreateDirectory(workspace.DirectoryFor(name));
|
||
var config = new SopConfig();
|
||
config.Sop.Name = name;
|
||
config.Sop.Regions["取料"] = new RegionDef { X1 = 10, Y1 = 20, X2 = 320, Y2 = 240, Name = "取料", Description = "料盒上方" };
|
||
config.Sop.Steps =
|
||
[
|
||
new StepDef { Id = 1, Name = "取料", Description = "步骤说明:手在取料区握住物料", Detection = new StepCondition { Method = ConditionMethod.HandInRegion, Region = "取料" } },
|
||
new StepDef { Id = 2, Name = "放置", Description = "步骤说明:物料放入放置区并保持稳定", SaveCompletionImage = false, Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }
|
||
];
|
||
SopConfigLoader.Save(config, workspace.ConfigPath(name));
|
||
var stand = Path.Combine(workspace.DirectoryFor(name), "sop_stand");
|
||
Directory.CreateDirectory(stand);
|
||
File.WriteAllText(Path.Combine(stand, "sop.avi"), "fake-avi");
|
||
File.WriteAllText(Path.Combine(stand, "duration.json"), "{\"seconds\":3.5}");
|
||
}
|
||
|
||
/// <summary>改写包内配方文件副本:keepLength 时长度不变只命中散列校验,否则改变长度命中清单大小校验。</summary>
|
||
private static string Tamper(string package, bool keepLength)
|
||
{
|
||
var copy = Copy(package);
|
||
string text;
|
||
// Update 模式下同一条目不能重复打开,先只读取出内容,再重开写入。
|
||
using (var read = ZipFile.OpenRead(copy))
|
||
{
|
||
using var stream = read.GetEntry("recipe/装配.yaml")!.Open();
|
||
text = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
|
||
}
|
||
var replacement = keepLength ? ReplaceOneCharacter(text) : text + "\n";
|
||
using var archive = ZipFile.Open(copy, ZipArchiveMode.Update);
|
||
using var write = archive.GetEntry("recipe/装配.yaml")!.Open();
|
||
write.SetLength(0);
|
||
write.Write(Encoding.UTF8.GetBytes(replacement));
|
||
return copy;
|
||
}
|
||
|
||
private static string AddEntry(string package, string entryName, string body)
|
||
{
|
||
var copy = Copy(package);
|
||
using var archive = ZipFile.Open(copy, ZipArchiveMode.Update);
|
||
using var stream = archive.CreateEntry(entryName).Open();
|
||
stream.Write(Encoding.UTF8.GetBytes(body));
|
||
return copy;
|
||
}
|
||
|
||
private static string Copy(string package)
|
||
{
|
||
var copy = package + "." + Guid.NewGuid().ToString("N") + ".bwsrecipe";
|
||
File.Copy(package, copy);
|
||
return copy;
|
||
}
|
||
|
||
private static string ReplaceOneCharacter(string text)
|
||
{
|
||
var index = text.IndexOf('x');
|
||
return index < 0 ? text + " " : text[..index] + "y" + text[(index + 1)..];
|
||
}
|
||
|
||
/// <summary>构造任意配方的包,用于喂入损坏、越界和高版本清单。manifestJson 为空表示不写清单。</summary>
|
||
private static string Craft(string label, string? manifestJson, params (string Entry, string Body)[] entries)
|
||
{
|
||
var path = Path.Combine(Root, label + "-" + Guid.NewGuid().ToString("N") + ".bwsrecipe");
|
||
using var archive = new ZipArchive(File.Create(path), ZipArchiveMode.Create);
|
||
foreach (var (entry, body) in entries)
|
||
{
|
||
using var stream = archive.CreateEntry(entry).Open();
|
||
stream.Write(Encoding.UTF8.GetBytes(body));
|
||
}
|
||
if (manifestJson is not null)
|
||
{
|
||
using var manifest = archive.CreateEntry("package.json").Open();
|
||
manifest.Write(Encoding.UTF8.GetBytes(manifestJson));
|
||
}
|
||
return path;
|
||
}
|
||
|
||
private static string Manifest(string recipeName, int version, params (string Path, long Bytes, string Sha)[] files) =>
|
||
JsonSerializer.Serialize(new
|
||
{
|
||
format = RecipePackage.FormatId,
|
||
version,
|
||
recipeName,
|
||
exportedAt = DateTimeOffset.UtcNow,
|
||
applicationVersion = "smoke",
|
||
files = files.Select(file => new { path = file.Path, bytes = file.Bytes, sha256 = file.Sha })
|
||
});
|
||
|
||
private static string Sha(string body) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(body))).ToLowerInvariant();
|
||
|
||
private static Exception Catch(Action action)
|
||
{
|
||
try
|
||
{
|
||
action();
|
||
throw new Exception("预期失败但没有抛出");
|
||
}
|
||
catch (Exception error) when (!(error is InvalidOperationException && error.Message == "预期失败但没有抛出"))
|
||
{
|
||
return error;
|
||
}
|
||
}
|
||
|
||
private static void Check(bool value, string message)
|
||
{
|
||
if (!value) throw new Exception(message);
|
||
Console.WriteLine("PASS: " + message);
|
||
}
|
||
}
|