fix: automate package versions and workspace validation
Validate ShrinkSDK Workspace / unity (push) Failing after 5s

This commit is contained in:
2026-09-05 06:32:13 +08:00
parent 6c90f9dc08
commit bb12b8d02d
12 changed files with 1548 additions and 109 deletions
+2 -2
View File
@@ -27,8 +27,8 @@ jobs:
git checkout --detach FETCH_HEAD
git submodule sync --recursive
git submodule update --init --recursive
test "$(git submodule status --recursive | wc -l | tr -d ' ')" = "21"
test -z "$(git submodule status --recursive | grep '^-')"
bash Tools/CI/Validate-Submodules.sh "$PWD"
node Tools/Release/update-shrinksdk-versions.mjs --check
- name: Run every standalone package EditMode host
shell: bash
+2 -4
View File
@@ -30,10 +30,8 @@ jobs:
git checkout --detach FETCH_HEAD
git submodule sync --recursive
git submodule update --init --recursive
module_count="$(git submodule status --recursive | wc -l | tr -d ' ')"
test "$module_count" = "21"
test -z "$(git submodule status --recursive | grep '^-')"
git submodule status --recursive
bash Tools/CI/Validate-Submodules.sh "$PWD"
node Tools/Release/update-shrinksdk-versions.mjs --check
- name: Compile Workspace and validate package graph
shell: bash
+140 -51
View File
@@ -2,9 +2,12 @@
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
@@ -13,30 +16,11 @@ namespace ShrinkSDK.WorkspaceValidation
{
public static class ShrinkSdkWorkspaceValidation
{
private static readonly ExpectedPackage[] ExpectedPackages =
{
new ExpectedPackage("ShrinkApp.Core", "com.cneicy.shrink-app-core", "0.1.4"),
new ExpectedPackage("ShrinkApp.Starter.Basic", "com.cneicy.shrink-app-starter-basic", "0.2.2"),
new ExpectedPackage("ShrinkCommand", "com.cneicy.shrink-command", "0.2.0"),
new ExpectedPackage("ShrinkCommand.Integration.App", "com.cneicy.shrink-command-integration-app", "0.1.3"),
new ExpectedPackage("ShrinkCommand.Integration.EventBus", "com.cneicy.shrink-command-integration-eventbus", "0.1.2"),
new ExpectedPackage("ShrinkCommand.Integration.Network", "com.cneicy.shrink-command-integration-network", "0.1.1"),
new ExpectedPackage("ShrinkContext.AppAdapter", "com.cneicy.shrink-context-app-adapter", "0.1.5"),
new ExpectedPackage("ShrinkContext.Core", "com.cneicy.shrink-context-core", "0.1.0"),
new ExpectedPackage("ShrinkContext.EventBusAdapter", "com.cneicy.shrink-context-eventbus-adapter", "0.1.1"),
new ExpectedPackage("ShrinkDataSaver", "com.cneicy.shrink-datasaver", "2.2.2"),
new ExpectedPackage("ShrinkDataSaver.Integration.App", "com.cneicy.shrink-datasaver-integration-app", "0.1.3"),
new ExpectedPackage("ShrinkDataSaver.Integration.EventBus", "com.cneicy.shrink-datasaver-integration-eventbus", "2.1.3"),
new ExpectedPackage("ShrinkEventBus", "com.cneicy.shrink-eventbus", "2.0.1"),
new ExpectedPackage("ShrinkEventBus.Entities", "com.cneicy.shrink-eventbus-entities", "0.1.1"),
new ExpectedPackage("ShrinkInstaller", "com.cneicy.shrink-installer", "0.2.4"),
new ExpectedPackage("ShrinkModFramework", "com.cneicy.shrink-mod-framework", "0.2.4"),
new ExpectedPackage("ShrinkNetwork", "com.cneicy.shrink-network", "0.2.1"),
new ExpectedPackage("ShrinkNetwork.Integration.App", "com.cneicy.shrink-network-integration-app", "0.1.3"),
new ExpectedPackage("ShrinkNetwork.Integration.EventBus", "com.cneicy.shrink-network-integration-eventbus", "0.1.3"),
new ExpectedPackage("ShrinkShared.CodeGen", "com.cneicy.shrink-shared-codegen", "0.1.0"),
new ExpectedPackage("ShrinkTutorial", "com.cneicy.shrink-tutorial", "0.1.4")
};
private const string InstallerPackageName = "com.cneicy.shrink-installer";
private const string InstallerCatalogTypeName = "ShrinkSDK.Installer.ShrinkSdkPackageCatalog";
private static readonly Regex SemanticVersion = new Regex(
@"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$",
RegexOptions.CultureInvariant);
public static void Run()
{
@@ -45,6 +29,7 @@ namespace ShrinkSDK.WorkspaceValidation
var workspaceRoot = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
var packages = ReadPackages(workspaceRoot);
ValidateGraph(packages);
ValidateInstallerCatalog(packages);
Debug.Log($"ShrinkSDK Workspace validation passed: packages={packages.Count}");
EditorApplication.Exit(0);
}
@@ -57,36 +42,97 @@ namespace ShrinkSDK.WorkspaceValidation
private static Dictionary<string, PackageDefinition> ReadPackages(string workspaceRoot)
{
var result = new Dictionary<string, PackageDefinition>(StringComparer.Ordinal);
foreach (var expected in ExpectedPackages)
var modulesRoot = Path.Combine(workspaceRoot, "Assets", "Modules");
if (!Directory.Exists(modulesRoot))
{
var manifestPath = Path.Combine(workspaceRoot, "Assets", "Modules", expected.Directory, "package.json");
throw new DirectoryNotFoundException($"Workspace package directory is missing: {modulesRoot}");
}
var declaredDirectories = ReadDeclaredPackageDirectories(workspaceRoot);
var manifestDirectories = Directory.EnumerateDirectories(modulesRoot)
.Where(directory => File.Exists(Path.Combine(directory, "package.json")))
.Select(Path.GetFullPath)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var undeclared = manifestDirectories
.Where(directory => !declaredDirectories.Contains(directory))
.OrderBy(directory => directory, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (undeclared.Length > 0)
{
throw new InvalidOperationException(
"Package directories are not declared as submodules: " + string.Join(", ", undeclared));
}
var result = new Dictionary<string, PackageDefinition>(StringComparer.Ordinal);
foreach (var directory in declaredDirectories.OrderBy(value => value, StringComparer.OrdinalIgnoreCase))
{
var manifestPath = Path.Combine(directory, "package.json");
if (!File.Exists(manifestPath))
{
throw new FileNotFoundException($"Required package manifest is missing: {expected.Directory}", manifestPath);
throw new FileNotFoundException("Declared package submodule has no package.json.", manifestPath);
}
var manifest = JObject.Parse(File.ReadAllText(manifestPath));
var packageName = manifest.Value<string>("name");
var version = manifest.Value<string>("version");
if (packageName == null || version == null || packageName.Length == 0 || version.Length == 0)
if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(version))
{
throw new InvalidOperationException($"{expected.Directory} has no valid package name or version.");
throw new InvalidOperationException($"{directory} has no valid package name or version.");
}
if (!string.Equals(packageName, expected.Name, StringComparison.Ordinal) ||
!string.Equals(version, expected.Version, StringComparison.Ordinal))
var validPackageName = packageName!;
var validVersion = version!;
if (!SemanticVersion.IsMatch(validVersion))
{
throw new InvalidOperationException(
$"{expected.Directory} must be {expected.Name}@{expected.Version}, found {packageName}@{version}.");
throw new InvalidOperationException($"{validPackageName} has an invalid semantic version: {validVersion}");
}
if (result.ContainsKey(packageName))
if (result.ContainsKey(validPackageName))
{
throw new InvalidOperationException($"Duplicate package manifest name: {packageName}");
throw new InvalidOperationException($"Duplicate package manifest name: {validPackageName}");
}
result.Add(packageName, new PackageDefinition(packageName, version, manifest));
result.Add(validPackageName, new PackageDefinition(validPackageName, validVersion, manifest));
}
return result;
}
private static HashSet<string> ReadDeclaredPackageDirectories(string workspaceRoot)
{
var gitModulesPath = Path.Combine(workspaceRoot, ".gitmodules");
if (!File.Exists(gitModulesPath))
{
throw new FileNotFoundException("Workspace .gitmodules is missing.", gitModulesPath);
}
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in File.ReadLines(gitModulesPath))
{
var match = Regex.Match(line, @"^\s*path\s*=\s*(?<path>.+?)\s*$", RegexOptions.CultureInvariant);
if (!match.Success)
{
continue;
}
var relativePath = match.Groups["path"].Value.Replace('\\', '/');
if (!relativePath.StartsWith("Assets/Modules/", StringComparison.Ordinal) ||
relativePath.Substring("Assets/Modules/".Length).Contains("/"))
{
continue;
}
var fullPath = Path.GetFullPath(Path.Combine(workspaceRoot, relativePath));
if (!result.Add(fullPath))
{
throw new InvalidOperationException($"Duplicate package submodule path: {relativePath}");
}
}
if (result.Count == 0)
{
throw new InvalidOperationException("No Assets/Modules package submodules are declared.");
}
return result;
@@ -158,6 +204,63 @@ namespace ShrinkSDK.WorkspaceValidation
}
}
private static void ValidateInstallerCatalog(IReadOnlyDictionary<string, PackageDefinition> packages)
{
var catalogType = AppDomain.CurrentDomain.GetAssemblies()
.Select(assembly => assembly.GetType(InstallerCatalogTypeName, false))
.FirstOrDefault(type => type != null)
?? throw new InvalidOperationException($"Installer catalog type was not loaded: {InstallerCatalogTypeName}");
var packagesField = catalogType.GetField("Packages", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("Installer catalog Packages field was not found.");
var catalogItems = packagesField.GetValue(null) as IEnumerable
?? throw new InvalidOperationException("Installer catalog Packages field is not enumerable.");
var catalog = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var item in catalogItems)
{
if (item == null)
{
throw new InvalidOperationException("Installer catalog contains a null package entry.");
}
var itemType = item.GetType();
var packageName = itemType.GetProperty("PackageName")?.GetValue(item) as string;
var version = itemType.GetProperty("Version")?.GetValue(item) as string;
if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(version))
{
throw new InvalidOperationException("Installer catalog contains an invalid package entry.");
}
var validPackageName = packageName!;
var validVersion = version!;
if (!catalog.TryAdd(validPackageName, validVersion))
{
throw new InvalidOperationException($"Installer catalog contains duplicate package: {validPackageName}");
}
}
var expectedNames = packages.Keys
.Where(name => !string.Equals(name, InstallerPackageName, StringComparison.Ordinal))
.ToHashSet(StringComparer.Ordinal);
var missing = expectedNames.Except(catalog.Keys).OrderBy(name => name, StringComparer.Ordinal).ToArray();
var unexpected = catalog.Keys.Except(expectedNames).OrderBy(name => name, StringComparer.Ordinal).ToArray();
if (missing.Length > 0 || unexpected.Length > 0)
{
throw new InvalidOperationException(
$"Installer catalog package set differs from Workspace. Missing=[{string.Join(", ", missing)}], " +
$"unexpected=[{string.Join(", ", unexpected)}]");
}
foreach (var packageName in expectedNames)
{
if (!string.Equals(catalog[packageName], packages[packageName].Version, StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"Installer catalog requires {packageName} {catalog[packageName]}, but the Workspace provides {packages[packageName].Version}.");
}
}
}
private sealed class PackageDefinition
{
public PackageDefinition(string name, string version, JObject manifest)
@@ -171,20 +274,6 @@ namespace ShrinkSDK.WorkspaceValidation
public string Version { get; }
public JObject Manifest { get; }
}
private readonly struct ExpectedPackage
{
public ExpectedPackage(string directory, string name, string version)
{
Directory = directory;
Name = name;
Version = version;
}
public string Directory { get; }
public string Name { get; }
public string Version { get; }
}
}
}
#endif
+27 -23
View File
@@ -65,7 +65,7 @@ ShrinkSDK 是以 Unity Package Manager 包为发布边界的 SDK Workspace,不
```text
ShrinkSDK Workspace/
|-- Assets/Modules/ 21 个同路径 Git submodule UPM 包
|-- Assets/Modules/ .gitmodules 声明的同路径 Git submodule UPM 包
|-- Assets/Modules/*.meta 根仓库追踪的 Unity 目录 GUID
|-- Assets/Scenes/ 示例与验收场景
|-- Assets/Resources/ 当前应用配置与组合 Profile
@@ -73,6 +73,7 @@ ShrinkSDK Workspace/
|-- GeneratedModSdk/ Mod SDK 导出物
|-- Packages/ 根 Unity 工程依赖
|-- Tools/UpmConsumerValidation/ 干净 UPM 消费工程验证
|-- Tools/Release/ 包版本、依赖与目录同步工具
|-- Tools/RepositoryMigration/ 子模块、发布仓库与独立宿主初始化脚本
|-- Docs/Archive/ 已完成迁移与过期地图,仅供追溯
|-- DESIGN.md 唯一当前架构文档
@@ -84,27 +85,28 @@ ShrinkSDK Workspace/
| 包 | 版本 | 职责 |
|---|---:|---|
| `com.cneicy.shrink-eventbus` | 2.0.1 | 单一事件模型、多 Bus、生成特性订阅、可选 MonoBehaviour 生命周期织入、UniTask 调度与零 GC 热路径 |
| `com.cneicy.shrink-eventbus-entities` | 0.1.1 | ShrinkEventBus 的 ECS/Burst NativeQueue writer 与 playback 适配 |
| `com.cneicy.shrink-datasaver` | 2.2.2 | 多槽位存档、设置、迁移、加密、原子写入与备份 |
| `com.cneicy.shrink-command` | 0.2.0 | 路径式命令、权限与同步/异步执行 |
| `com.cneicy.shrink-network` | 0.2.1 | 消息、RPC、权限、诊断、TCP/KCP/Loopback 与服务器生成 |
| `com.cneicy.shrink-mod-framework` | 0.2.4 | 模组发现、依赖、可逆生命周期、命名空间内容覆盖、外部 DLL revision 与 Harmony lease |
| `com.cneicy.shrink-tutorial` | 0.1.3 | 数据驱动引导、遮罩、锚点、触发与持久化 |
| `com.cneicy.shrink-context-core` | 0.1.0 | 可逆效应、coeffect、fiber、声明式 loader 与诊断 |
| `com.cneicy.shrink-app-core` | 0.1.4 | App 设置、服务门面、ClassicHost 兼容面与宿主协议 |
| `com.cneicy.shrink-app-starter-basic` | 0.2.2 | 默认 Context 组合根、配置资产和示例入口 |
| `com.cneicy.shrink-context-app-adapter` | 0.1.5 | ContextLoader 宿主、Profile/JSON、诊断与基准 |
| `com.cneicy.shrink-context-eventbus-adapter` | 0.1.1 | EventBus 生成绑定的可逆 EffectAttach 包装 |
| `com.cneicy.shrink-datasaver-integration-eventbus` | 2.1.3 | DataSaver 事件桥 |
| `com.cneicy.shrink-datasaver-integration-app` | 0.1.3 | DataSaver App installer/原生 Context 组件 |
| `com.cneicy.shrink-command-integration-eventbus` | 0.1.2 | 命令请求与生命周期事件桥 |
| `com.cneicy.shrink-command-integration-network` | 0.1.1 | `command/execute` RPC 桥 |
| `com.cneicy.shrink-command-integration-app` | 0.1.3 | Command App installer/原生 Context 组件 |
| `com.cneicy.shrink-network-integration-eventbus` | 0.1.3 | 网络事件广播、裁决结果与 delta 去重 |
| `com.cneicy.shrink-network-integration-app` | 0.1.3 | Network App installer/原生 Context 组件 |
| `com.cneicy.shrink-shared-codegen` | 0.1.0 | App、Command、Network 共用的 Editor-only IL 后处理注册表生成器 |
| `com.cneicy.shrink-installer` | 0.2.4 | UI Toolkit 包管理器:显示真实安装状态,按 Context 分层提供固定版本单包与推荐组合 |
| `com.cneicy.shrink-eventbus` | 2.1.0 | 单一事件模型、多 Bus、生成特性订阅、可选 MonoBehaviour 生命周期织入、UniTask 调度与零 GC 热路径 |
| `com.cneicy.shrink-eventbus-entities` | 0.1.2 | ShrinkEventBus 的 ECS/Burst NativeQueue writer 与 playback 适配 |
| `com.cneicy.shrink-datasaver` | 2.3.0 | 多槽位存档、设置、迁移、加密、原子写入与备份 |
| `com.cneicy.shrink-command` | 0.3.0 | 路径式命令、权限与同步/异步执行 |
| `com.cneicy.shrink-network` | 0.3.0 | 消息、RPC、权限、诊断、TCP/KCP/Loopback 与服务器生成 |
| `com.cneicy.shrink-mod-framework` | 0.3.0 | 模组发现、依赖、可逆生命周期、命名空间内容覆盖、外部 DLL revision 与 Harmony lease |
| `com.cneicy.shrink-tutorial` | 0.2.0 | 数据驱动引导、遮罩、锚点、触发与持久化 |
| `com.cneicy.shrink-context-core` | 0.2.0 | 可逆效应、coeffect、fiber、声明式 loader 与诊断 |
| `com.cneicy.shrink-app-core` | 0.2.0 | App 设置、服务门面、ClassicHost 兼容面与宿主协议 |
| `com.cneicy.shrink-app-starter-basic` | 0.3.0 | 默认 Context 组合根、配置资产和示例入口 |
| `com.cneicy.shrink-context-app-adapter` | 0.2.0 | ContextLoader 宿主、Profile/JSON、诊断与基准 |
| `com.cneicy.shrink-context-eventbus-adapter` | 0.2.0 | EventBus 生成绑定的可逆 EffectAttach 包装 |
| `com.cneicy.shrink-datasaver-integration-eventbus` | 2.2.0 | DataSaver 事件桥 |
| `com.cneicy.shrink-datasaver-integration-app` | 0.2.0 | DataSaver App installer/原生 Context 组件 |
| `com.cneicy.shrink-command-integration-eventbus` | 0.2.0 | 命令请求与生命周期事件桥 |
| `com.cneicy.shrink-command-integration-network` | 0.2.0 | `command/execute` RPC 桥 |
| `com.cneicy.shrink-command-integration-app` | 0.2.0 | Command App installer/原生 Context 组件 |
| `com.cneicy.shrink-network-integration-eventbus` | 0.2.0 | 网络事件广播、裁决结果与 delta 去重 |
| `com.cneicy.shrink-network-integration-app` | 0.2.0 | Network App installer/原生 Context 组件 |
| `com.cneicy.shrink-shared-codegen` | 0.1.1 | App、Command、Network 共用的 Editor-only IL 后处理注册表生成器 |
| `com.cneicy.shrink-runtime-abstractions` | 0.1.0 | Unity 与其他 .NET 宿主共用的平台服务合同 |
| `com.cneicy.shrink-installer` | 0.2.6 | UI Toolkit 包管理器:显示真实安装状态,按 Context 分层提供固定版本单包与推荐组合 |
`ShrinkShared.CodeGen` 不反向引用业务 asmdef,只按程序集名与类型全名读取 Cecil 元数据,因此业务包可以依赖它而不形成包循环。
@@ -225,7 +227,7 @@ Mono 中已加载程序集不能真正卸载。系统只回滚组件实例与效
1. 内部包图检查:全部 `com.cneicy.*` 依赖版本一致、无循环,普通主包不反向依赖 Integration 包。
2. Unity 编译:目标 asmdef 和根项目无编译错误。
3. EditMode 测试:功能测试、Context 生命周期、语义扫描和模板覆写保护。
4. 真实 UPM 消费:`Tools/UpmConsumerValidation/Validate-UpmConsumer.ps1` 在递归 submodule 初始化后的 Workspace 中创建仓库外形态的临时 Unity 工程,通过 `file:` 安装全部 21 个包,启用 testables,验证包注册、程序集加载并运行 EditMode 测试。发布后还必须分别验证 registry、精确 Git URL 和 Installer 三种空白消费者工程路径。
4. 真实 UPM 消费:`Tools/UpmConsumerValidation/Validate-UpmConsumer.ps1` 在递归 submodule 初始化后的 Workspace 中创建仓库外形态的临时 Unity 工程,通过 `file:` 安装全部包,启用 testables,验证包注册、程序集加载并运行 EditMode 测试。发布后还必须分别验证 registry、精确 Git URL 和 Installer 三种空白消费者工程路径。
5. 独立宿主:生成工程与 RuntimeSmoke 按变更范围构建或运行。
6. 涉及真实生命周期时,仍需在目标场景执行 Play Mode 验收;源码检查和 EditMode 不能替代该路径。
@@ -253,6 +255,8 @@ Mono 中已加载程序集不能真正卸载。系统只回滚组件实例与效
- 当前架构只更新本文。
- 包级使用方式和 API 示例放在各包 README。
- `Tools/Release/Update-ShrinkSdkVersions.ps1` 负责包版本递增,并同步受影响的精确依赖、对应 NuGet 项目、Installer 目录、本文版本表和 `Tools/Release/package-versions.json`;依赖清单变化会触发依赖方 patch 版本递增。
- `Tools/UpmConsumerValidation/published-upm-versions.json` 只记录已经发布且要接受真实消费验证的版本,不随未打标签的 Workspace 版本提前更新。
- 包源码、标签、独立开发宿主与包级 CI 位于 `https://git.crash.work/ShrinkSDK/<Package>`;发布版本只能由与 `package.json.version` 一致的 `vX.Y.Z` 标签产生。
- `NETWORK_PITFALLS.md` 记录实现经验,不描述当前模块清单。
- `Docs/Archive/CORDIS_MIGRATION.completed.md` 保存迁移论证、阶段记录和历史验收数据。
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -euo pipefail
workspace_root="${1:-$PWD}"
workspace_root="$(cd "$workspace_root" && pwd)"
cd "$workspace_root"
if [[ ! -f .gitmodules ]]; then
echo "Workspace .gitmodules was not found: $workspace_root" >&2
exit 1
fi
mapfile -t declared_paths < <(
git config --file .gitmodules --get-regexp '^submodule\..*\.path$' |
awk '{ print $2 }'
)
if [[ "${#declared_paths[@]}" -eq 0 ]]; then
echo "No submodules are declared in .gitmodules." >&2
exit 1
fi
mapfile -t top_level_status < <(git submodule status)
if [[ "${#top_level_status[@]}" -ne "${#declared_paths[@]}" ]]; then
echo "Submodule count mismatch: declared=${#declared_paths[@]} status=${#top_level_status[@]}" >&2
exit 1
fi
for relative_path in "${declared_paths[@]}"; do
if [[ ! -e "$relative_path/.git" ]]; then
echo "Declared submodule is not initialized: $relative_path" >&2
exit 1
fi
done
recursive_status="$(git submodule status --recursive)"
if grep -Eq '^[+-U]' <<<"$recursive_status"; then
echo "One or more submodules are missing, conflicted, or not at the recorded revision:" >&2
grep -E '^[+-U]' <<<"$recursive_status" >&2
exit 1
fi
printf '%s\n' "$recursive_status"
echo "Submodule validation passed: declared=${#declared_paths[@]}"
@@ -0,0 +1,44 @@
[CmdletBinding(DefaultParameterSetName = 'Check')]
param(
[Parameter(Mandatory, ParameterSetName = 'Check')]
[switch]$Check,
[Parameter(Mandatory, ParameterSetName = 'Bump')]
[Parameter(Mandatory, ParameterSetName = 'Version')]
[string]$Package,
[Parameter(Mandatory, ParameterSetName = 'Bump')]
[ValidateSet('major', 'minor', 'patch')]
[string]$Bump,
[Parameter(Mandatory, ParameterSetName = 'Version')]
[ValidatePattern('^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$')]
[string]$Version,
[Parameter(ParameterSetName = 'Bump')]
[Parameter(ParameterSetName = 'Version')]
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
$scriptPath = Join-Path $PSScriptRoot 'update-shrinksdk-versions.mjs'
$arguments = @($scriptPath)
if ($Check) {
$arguments += '--check'
} else {
$arguments += @('--package', $Package)
if ($PSCmdlet.ParameterSetName -eq 'Bump') {
$arguments += @('--bump', $Bump)
} else {
$arguments += @('--version', $Version)
}
if ($DryRun) {
$arguments += '--dry-run'
}
}
& node @arguments
if ($LASTEXITCODE -ne 0) {
throw "ShrinkSDK version tool failed with exit code $LASTEXITCODE."
}
+302
View File
@@ -0,0 +1,302 @@
{
"schemaVersion": 1,
"unityPackages": [
{
"directory": "ShrinkApp.Core",
"name": "com.cneicy.shrink-app-core",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkApp.Core.git",
"nugetPackages": [
{
"id": "ShrinkSDK.App.Core",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkApp.Core/DotNet~/ShrinkSDK.App.Core.csproj"
}
]
},
{
"directory": "ShrinkApp.Starter.Basic",
"name": "com.cneicy.shrink-app-starter-basic",
"version": "0.3.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkApp.Starter.Basic.git",
"nugetPackages": [
{
"id": "ShrinkSDK.App.Starter.Basic",
"version": "0.3.0",
"project": "Assets/Modules/ShrinkApp.Starter.Basic/DotNet~/ShrinkSDK.App.Starter.Basic.csproj"
}
]
},
{
"directory": "ShrinkCommand",
"name": "com.cneicy.shrink-command",
"version": "0.3.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkCommand.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Command",
"version": "0.3.0",
"project": "Assets/Modules/ShrinkCommand/DotNet~/ShrinkSDK.Command.csproj"
}
]
},
{
"directory": "ShrinkCommand.Integration.App",
"name": "com.cneicy.shrink-command-integration-app",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkCommand.Integration.App.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Command.Integration.App",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkCommand.Integration.App/DotNet~/ShrinkSDK.Command.Integration.App.csproj"
}
]
},
{
"directory": "ShrinkCommand.Integration.EventBus",
"name": "com.cneicy.shrink-command-integration-eventbus",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkCommand.Integration.EventBus.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Command.Integration.EventBus",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkCommand.Integration.EventBus/DotNet~/ShrinkSDK.Command.Integration.EventBus.csproj"
}
]
},
{
"directory": "ShrinkCommand.Integration.Network",
"name": "com.cneicy.shrink-command-integration-network",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkCommand.Integration.Network.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Command.Integration.Network",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkCommand.Integration.Network/DotNet~/ShrinkSDK.Command.Integration.Network.csproj"
}
]
},
{
"directory": "ShrinkContext.AppAdapter",
"name": "com.cneicy.shrink-context-app-adapter",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkContext.AppAdapter.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Context.AppAdapter",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkContext.AppAdapter/DotNet~/ShrinkSDK.Context.AppAdapter.csproj"
}
]
},
{
"directory": "ShrinkContext.Core",
"name": "com.cneicy.shrink-context-core",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkContext.Core.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Context.Core",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkContext.Core/DotNet~/ShrinkSDK.Context.Core.csproj"
}
]
},
{
"directory": "ShrinkContext.EventBusAdapter",
"name": "com.cneicy.shrink-context-eventbus-adapter",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkContext.EventBusAdapter.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Context.EventBusAdapter",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkContext.EventBusAdapter/DotNet~/ShrinkSDK.Context.EventBusAdapter.csproj"
}
]
},
{
"directory": "ShrinkDataSaver",
"name": "com.cneicy.shrink-datasaver",
"version": "2.3.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkDataSaver.git",
"nugetPackages": [
{
"id": "ShrinkSDK.DataSaver",
"version": "2.3.0",
"project": "Assets/Modules/ShrinkDataSaver/DotNet~/ShrinkSDK.DataSaver.csproj"
}
]
},
{
"directory": "ShrinkDataSaver.Integration.App",
"name": "com.cneicy.shrink-datasaver-integration-app",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkDataSaver.Integration.App.git",
"nugetPackages": [
{
"id": "ShrinkSDK.DataSaver.Integration.App",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkDataSaver.Integration.App/DotNet~/ShrinkSDK.DataSaver.Integration.App.csproj"
}
]
},
{
"directory": "ShrinkDataSaver.Integration.EventBus",
"name": "com.cneicy.shrink-datasaver-integration-eventbus",
"version": "2.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkDataSaver.Integration.EventBus.git",
"nugetPackages": [
{
"id": "ShrinkSDK.DataSaver.Integration.EventBus",
"version": "2.2.0",
"project": "Assets/Modules/ShrinkDataSaver.Integration.EventBus/DotNet~/ShrinkSDK.DataSaver.Integration.EventBus.csproj"
}
]
},
{
"directory": "ShrinkEventBus",
"name": "com.cneicy.shrink-eventbus",
"version": "2.1.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkEventBus.git",
"nugetPackages": [
{
"id": "ShrinkSDK.EventBus",
"version": "2.1.0",
"project": "Assets/Modules/ShrinkEventBus/DotNet~/ShrinkSDK.EventBus.csproj"
}
]
},
{
"directory": "ShrinkEventBus.Entities",
"name": "com.cneicy.shrink-eventbus-entities",
"version": "0.1.2",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkEventBus.Entities.git"
},
{
"directory": "ShrinkInstaller",
"name": "com.cneicy.shrink-installer",
"version": "0.2.6",
"repository": "https://git.crash.work/ShrinkSDK/Installer.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Godot.Installer",
"version": "0.1.3",
"project": "Assets/Modules/ShrinkInstaller/Godot~/ShrinkSDK.Godot.Installer.csproj"
}
]
},
{
"directory": "ShrinkModFramework",
"name": "com.cneicy.shrink-mod-framework",
"version": "0.3.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkModFramework.git",
"nugetPackages": [
{
"id": "ShrinkSDK.ModFramework",
"version": "0.3.0",
"project": "Assets/Modules/ShrinkModFramework/DotNet~/ShrinkSDK.ModFramework.csproj"
},
{
"id": "ShrinkSDK.ModFramework.Godot",
"version": "0.1.0",
"project": "Assets/Modules/ShrinkModFramework/Godot~/ShrinkSDK.ModFramework.Godot.csproj"
}
]
},
{
"directory": "ShrinkNetwork",
"name": "com.cneicy.shrink-network",
"version": "0.3.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkNetwork.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Network",
"version": "0.3.0",
"project": "Assets/Modules/ShrinkNetwork/DotNet~/ShrinkSDK.Network.csproj"
}
]
},
{
"directory": "ShrinkNetwork.Integration.App",
"name": "com.cneicy.shrink-network-integration-app",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkNetwork.Integration.App.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Network.Integration.App",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkNetwork.Integration.App/DotNet~/ShrinkSDK.Network.Integration.App.csproj"
}
]
},
{
"directory": "ShrinkNetwork.Integration.EventBus",
"name": "com.cneicy.shrink-network-integration-eventbus",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkNetwork.Integration.EventBus.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Network.Integration.EventBus",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkNetwork.Integration.EventBus/DotNet~/ShrinkSDK.Network.Integration.EventBus.csproj"
}
]
},
{
"directory": "ShrinkRuntime.Abstractions",
"name": "com.cneicy.shrink-runtime-abstractions",
"version": "0.1.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkRuntime.Abstractions.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Runtime.Abstractions",
"version": "0.1.0",
"project": "Assets/Modules/ShrinkRuntime.Abstractions/DotNet~/ShrinkSDK.Runtime.Abstractions.csproj"
}
]
},
{
"directory": "ShrinkShared.CodeGen",
"name": "com.cneicy.shrink-shared-codegen",
"version": "0.1.1",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkShared.CodeGen.git",
"nugetPackages": [
{
"id": "ShrinkSDK.CodeGen",
"version": "0.1.0",
"project": "Assets/Modules/ShrinkShared.CodeGen/DotNet~/ShrinkSDK.CodeGen.Task/ShrinkSDK.CodeGen.Task.csproj"
}
]
},
{
"directory": "ShrinkTutorial",
"name": "com.cneicy.shrink-tutorial",
"version": "0.2.0",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkTutorial.git",
"nugetPackages": [
{
"id": "ShrinkSDK.Tutorial",
"version": "0.2.0",
"project": "Assets/Modules/ShrinkTutorial/DotNet~/ShrinkSDK.Tutorial.csproj"
},
{
"id": "ShrinkSDK.Tutorial.Godot",
"version": "0.1.0",
"project": "Assets/Modules/ShrinkTutorial/Godot~/ShrinkSDK.Tutorial.Godot.csproj"
}
]
}
],
"standaloneNugetPackages": [
{
"id": "ShrinkSDK.Godot",
"version": "0.1.0",
"project": "Godot/Packages/ShrinkSDK.Godot/ShrinkSDK.Godot.csproj",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkGodot.git"
}
]
}
+867
View File
@@ -0,0 +1,867 @@
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
const workspaceRoot = path.resolve(scriptDirectory, '..', '..');
const packageCatalogPath = path.join(scriptDirectory, 'package-versions.json');
const installerPackageName = 'com.cneicy.shrink-installer';
const semanticVersionPattern = '(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?';
const semanticVersion = new RegExp(`^${semanticVersionPattern}$`);
function usage(message) {
if (message) {
console.error(message);
}
console.error('Usage:');
console.error(' node Tools/Release/update-shrinksdk-versions.mjs --check');
console.error(' node Tools/Release/update-shrinksdk-versions.mjs --package <name> --bump <major|minor|patch> [--dry-run]');
console.error(' node Tools/Release/update-shrinksdk-versions.mjs --package <name> --version <x.y.z> [--dry-run]');
process.exitCode = 2;
}
function parseArguments(argv) {
const options = { check: false, dryRun: false, package: null, bump: null, version: null };
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
switch (argument) {
case '--check':
options.check = true;
break;
case '--dry-run':
options.dryRun = true;
break;
case '--package':
options.package = argv[++index] ?? null;
break;
case '--bump':
options.bump = argv[++index] ?? null;
break;
case '--version':
options.version = argv[++index] ?? null;
break;
case '--help':
case '-h':
return { help: true };
default:
throw new Error(`Unknown argument: ${argument}`);
}
}
if (options.check) {
if (options.package || options.bump || options.version || options.dryRun) {
throw new Error('--check cannot be combined with update arguments.');
}
return options;
}
if (!options.package || Boolean(options.bump) === Boolean(options.version)) {
throw new Error('An update requires --package and exactly one of --bump or --version.');
}
if (options.bump && !['major', 'minor', 'patch'].includes(options.bump)) {
throw new Error(`Unsupported bump kind: ${options.bump}`);
}
if (options.version && !semanticVersion.test(options.version)) {
throw new Error(`Invalid semantic version: ${options.version}`);
}
return options;
}
function normalizeRelative(value) {
return value.replaceAll('\\', '/').replace(/^\.\//, '');
}
function relativeToWorkspace(absolutePath) {
return normalizeRelative(path.relative(workspaceRoot, absolutePath));
}
function escapeRegularExpression(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function readGitModules() {
const gitModulesPath = path.join(workspaceRoot, '.gitmodules');
if (!fs.existsSync(gitModulesPath)) {
throw new Error(`Workspace .gitmodules was not found: ${gitModulesPath}`);
}
const modules = [];
let current = null;
for (const line of fs.readFileSync(gitModulesPath, 'utf8').split(/\r?\n/)) {
const section = line.match(/^\s*\[submodule\s+"(.+)"\]\s*$/);
if (section) {
current = { section: section[1], path: null, url: null };
modules.push(current);
continue;
}
if (!current) {
continue;
}
const property = line.match(/^\s*(path|url)\s*=\s*(.*?)\s*$/);
if (property) {
current[property[1]] = property[1] === 'path' ? normalizeRelative(property[2]) : property[2];
}
}
const seenPaths = new Set();
for (const module of modules) {
if (!module.path || !module.url) {
throw new Error(`Incomplete .gitmodules entry: ${module.section}`);
}
const key = module.path.toLowerCase();
if (seenPaths.has(key)) {
throw new Error(`Duplicate .gitmodules path: ${module.path}`);
}
seenPaths.add(key);
}
return modules;
}
function walkFiles(directory, predicate) {
if (!fs.existsSync(directory)) {
return [];
}
const result = [];
const visit = current => {
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
if (entry.name === '.git' || entry.name === 'bin' || entry.name === 'obj' || entry.name === 'Development~') {
continue;
}
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
visit(fullPath);
} else if (entry.isFile() && predicate(fullPath)) {
result.push(fullPath);
}
}
};
visit(directory);
return result.sort((left, right) => left.localeCompare(right));
}
function xmlElement(text, name) {
return text.match(new RegExp(`<${name}>\\s*([^<]+?)\\s*</${name}>`, 'i'))?.[1]?.trim() ?? null;
}
function xmlAttribute(text, name) {
return text.match(new RegExp(`\\b${name}\\s*=\\s*"([^"]+)"`, 'i'))?.[1]?.trim() ?? null;
}
function readPackageReferences(text) {
const references = [];
const elementPattern = /<PackageReference\b[\s\S]*?(?:\/>|<\/PackageReference>)/gi;
for (const match of text.matchAll(elementPattern)) {
const include = xmlAttribute(match[0], 'Include');
const version = xmlAttribute(match[0], 'Version') ?? xmlElement(match[0], 'Version');
if (include && version) {
references.push({ id: include, version });
}
}
return references;
}
function readProject(projectPath, ownerModule, ownerUpmName) {
const text = fs.readFileSync(projectPath, 'utf8');
const id = xmlElement(text, 'PackageId');
const version = xmlElement(text, 'Version');
const isPackable = xmlElement(text, 'IsPackable');
if (!id || !version || String(isPackable).toLowerCase() === 'false') {
return null;
}
if (!semanticVersion.test(version)) {
throw new Error(`${relativeToWorkspace(projectPath)} has an invalid package version: ${version}`);
}
const relativeToOwner = normalizeRelative(path.relative(path.join(workspaceRoot, ownerModule.path), projectPath));
const segments = relativeToOwner.split('/');
return {
id,
version,
path: projectPath,
project: relativeToWorkspace(projectPath),
repository: ownerModule.url,
ownerModulePath: ownerModule.path,
ownerUpmName,
coupledToUpm: Boolean(ownerUpmName) && segments.length === 2 && segments[0] === 'DotNet~',
references: readPackageReferences(text)
};
}
function buildModel() {
const modules = readGitModules();
const upmModules = modules.filter(module => /^Assets\/Modules\/[^/]+$/.test(module.path));
const declaredPaths = new Set(upmModules.map(module => module.path.toLowerCase()));
const modulesDirectory = path.join(workspaceRoot, 'Assets', 'Modules');
const manifestDirectories = fs.readdirSync(modulesDirectory, { withFileTypes: true })
.filter(entry => entry.isDirectory() && fs.existsSync(path.join(modulesDirectory, entry.name, 'package.json')))
.map(entry => `Assets/Modules/${entry.name}`);
const undeclared = manifestDirectories.filter(directory => !declaredPaths.has(directory.toLowerCase()));
if (undeclared.length > 0) {
throw new Error(`Package directories are not declared in .gitmodules: ${undeclared.join(', ')}`);
}
const upmPackages = [];
const upmByName = new Map();
for (const module of upmModules) {
const packagePath = path.join(workspaceRoot, module.path);
const manifestPath = path.join(packagePath, 'package.json');
if (!fs.existsSync(manifestPath)) {
throw new Error(`Declared package submodule has no package.json: ${module.path}`);
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
if (typeof manifest.name !== 'string' || typeof manifest.version !== 'string' || !semanticVersion.test(manifest.version)) {
throw new Error(`${module.path}/package.json has no valid name and semantic version.`);
}
if (upmByName.has(manifest.name)) {
throw new Error(`Duplicate UPM package name: ${manifest.name}`);
}
const dependencies = Object.entries(manifest.dependencies ?? {})
.filter(([name]) => name.startsWith('com.cneicy.'))
.map(([name, version]) => ({ name, version: String(version) }));
const record = {
name: manifest.name,
displayName: typeof manifest.displayName === 'string' ? manifest.displayName : '',
version: manifest.version,
directory: path.posix.basename(module.path),
modulePath: module.path,
packagePath,
manifestPath,
repository: module.url,
dependencies,
nugetPackages: []
};
upmPackages.push(record);
upmByName.set(record.name, record);
}
const nugetPackages = [];
const nugetById = new Map();
const addProject = record => {
if (!record) {
return;
}
if (nugetById.has(record.id)) {
throw new Error(`Duplicate NuGet package id: ${record.id}`);
}
nugetPackages.push(record);
nugetById.set(record.id, record);
if (record.ownerUpmName) {
upmByName.get(record.ownerUpmName).nugetPackages.push(record);
}
};
for (const upmPackage of upmPackages) {
const ownerModule = upmModules.find(module => module.path === upmPackage.modulePath);
for (const area of ['DotNet~', 'Godot~']) {
const areaPath = path.join(upmPackage.packagePath, area);
for (const projectPath of walkFiles(areaPath, candidate => candidate.toLowerCase().endsWith('.csproj'))) {
addProject(readProject(projectPath, ownerModule, upmPackage.name));
}
}
}
for (const module of modules.filter(candidate => !declaredPaths.has(candidate.path.toLowerCase()))) {
const moduleRoot = path.join(workspaceRoot, module.path);
for (const projectPath of walkFiles(moduleRoot, candidate => candidate.toLowerCase().endsWith('.csproj'))) {
addProject(readProject(projectPath, module, null));
}
}
for (const upmPackage of upmPackages) {
const coupled = upmPackage.nugetPackages.filter(project => project.coupledToUpm);
if (coupled.length > 1) {
throw new Error(`${upmPackage.directory} has more than one directly coupled DotNet~ project.`);
}
}
const installer = upmByName.get(installerPackageName);
if (!installer) {
throw new Error(`Installer package was not found: ${installerPackageName}`);
}
const installerUpmCatalogPath = path.join(installer.packagePath, 'Editor', 'ShrinkSdkPackageCatalog.cs');
const installerNugetCatalogPath = path.join(installer.packagePath, 'Godot~', 'addons', 'shrinksdk', 'ShrinkProjectPackageEditor.cs');
return {
modules,
upmPackages: upmPackages.sort((left, right) => left.name.localeCompare(right.name)),
upmByName,
nugetPackages: nugetPackages.sort((left, right) => left.id.localeCompare(right.id)),
nugetById,
installer,
installerUpmCatalogPath,
installerNugetCatalogPath,
designPath: path.join(workspaceRoot, 'DESIGN.md')
};
}
function parseVersion(value) {
const match = value.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
if (!match) {
throw new Error(`Cannot parse semantic version: ${value}`);
}
return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), prerelease: match[4] ?? null };
}
function compareVersions(leftValue, rightValue) {
const left = parseVersion(leftValue);
const right = parseVersion(rightValue);
for (const key of ['major', 'minor', 'patch']) {
if (left[key] !== right[key]) {
return left[key] < right[key] ? -1 : 1;
}
}
if (left.prerelease === right.prerelease) {
return 0;
}
if (left.prerelease === null) {
return 1;
}
if (right.prerelease === null) {
return -1;
}
const leftParts = left.prerelease.split('.');
const rightParts = right.prerelease.split('.');
const length = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < length; index += 1) {
if (leftParts[index] === undefined) return -1;
if (rightParts[index] === undefined) return 1;
if (leftParts[index] === rightParts[index]) continue;
const leftNumeric = /^[0-9]+$/.test(leftParts[index]);
const rightNumeric = /^[0-9]+$/.test(rightParts[index]);
if (leftNumeric && rightNumeric) return Number(leftParts[index]) < Number(rightParts[index]) ? -1 : 1;
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
return leftParts[index].localeCompare(rightParts[index]);
}
return 0;
}
function bumpVersion(value, kind) {
const parsed = parseVersion(value);
if (parsed.prerelease) {
throw new Error(`Automatic ${kind} bump requires a stable version: ${value}`);
}
if (kind === 'major') return `${parsed.major + 1}.0.0`;
if (kind === 'minor') return `${parsed.major}.${parsed.minor + 1}.0`;
return `${parsed.major}.${parsed.minor}.${parsed.patch + 1}`;
}
function parseUpmCatalog(model) {
const text = fs.readFileSync(model.installerUpmCatalogPath, 'utf8');
const entries = new Map();
const pattern = new RegExp(`"(com\\.cneicy\\.[^"]+)"\\s*,\\s*"(${semanticVersionPattern})"\\s*,\\s*ShrinkSdkPackageLayer`, 'g');
for (const match of text.matchAll(pattern)) {
if (entries.has(match[1])) throw new Error(`Duplicate Installer UPM catalog entry: ${match[1]}`);
entries.set(match[1], match[2]);
}
return entries;
}
function parseNugetCatalog(model) {
const text = fs.readFileSync(model.installerNugetCatalogPath, 'utf8');
const entries = new Map();
const pattern = new RegExp(`\\["(ShrinkSDK\\.[^"]+)"\\]\\s*=\\s*"(${semanticVersionPattern})"`, 'g');
for (const match of text.matchAll(pattern)) {
if (entries.has(match[1])) throw new Error(`Duplicate Installer NuGet catalog entry: ${match[1]}`);
entries.set(match[1], match[2]);
}
return entries;
}
function parseDesignVersions(model) {
const text = fs.readFileSync(model.designPath, 'utf8');
const entries = new Map();
const pattern = new RegExp('^\\|\\s*`(com\\.cneicy\\.[^`]+)`\\s*\\|\\s*(' + semanticVersionPattern + ')\\s*\\|', 'gm');
for (const match of text.matchAll(pattern)) {
if (entries.has(match[1])) throw new Error(`Duplicate DESIGN.md package row: ${match[1]}`);
entries.set(match[1], match[2]);
}
return entries;
}
function finalUpmVersion(record, upmPlan = new Map()) {
return upmPlan.get(record.name) ?? record.version;
}
function finalNugetVersion(record, nugetPlan = new Map()) {
return nugetPlan.get(record.id) ?? record.version;
}
function generatePackageCatalog(model, upmPlan = new Map(), nugetPlan = new Map()) {
const unityPackages = model.upmPackages.map(record => {
const entry = {
directory: record.directory,
name: record.name,
version: finalUpmVersion(record, upmPlan),
repository: record.repository
};
if (record.nugetPackages.length > 0) {
entry.nugetPackages = record.nugetPackages
.map(project => ({ id: project.id, version: finalNugetVersion(project, nugetPlan), project: project.project }))
.sort((left, right) => left.id.localeCompare(right.id));
}
return entry;
});
const standaloneNugetPackages = model.nugetPackages
.filter(record => !record.ownerUpmName)
.map(record => ({
id: record.id,
version: finalNugetVersion(record, nugetPlan),
project: record.project,
repository: record.repository
}));
return `${JSON.stringify({ schemaVersion: 1, unityPackages, standaloneNugetPackages }, null, 2)}\n`;
}
function collectValidationErrors(model) {
const errors = [];
const upmCatalog = parseUpmCatalog(model);
const nugetCatalog = parseNugetCatalog(model);
const designVersions = parseDesignVersions(model);
for (const record of model.upmPackages) {
for (const dependency of record.dependencies) {
const target = model.upmByName.get(dependency.name);
if (!target) continue;
if (dependency.version !== target.version) {
errors.push(`${record.name} requires ${dependency.name} ${dependency.version}, Workspace has ${target.version}`);
}
const canDependOnIntegration = record.name.includes('-integration-') || record.name.includes('-starter-');
if (dependency.name.includes('-integration-') && !canDependOnIntegration) {
errors.push(`${record.name} must not depend on integration package ${dependency.name}`);
}
}
const coupled = record.nugetPackages.filter(project => project.coupledToUpm);
for (const project of coupled) {
if (project.version !== record.version) {
errors.push(`${project.project} version ${project.version} differs from ${record.name} ${record.version}`);
}
}
const designVersion = designVersions.get(record.name);
if (!designVersion) {
errors.push(`DESIGN.md is missing package ${record.name}`);
} else if (designVersion !== record.version) {
errors.push(`DESIGN.md lists ${record.name} ${designVersion}, Workspace has ${record.version}`);
}
}
const expectedCatalogNames = new Set(model.upmPackages
.filter(record => record.name !== installerPackageName)
.map(record => record.name));
for (const name of expectedCatalogNames) {
const record = model.upmByName.get(name);
if (!upmCatalog.has(name)) {
errors.push(`Installer UPM catalog is missing ${name}`);
} else if (upmCatalog.get(name) !== record.version) {
errors.push(`Installer UPM catalog lists ${name} ${upmCatalog.get(name)}, Workspace has ${record.version}`);
}
}
for (const name of upmCatalog.keys()) {
if (!expectedCatalogNames.has(name)) errors.push(`Installer UPM catalog has unknown package ${name}`);
}
for (const [id, version] of nugetCatalog) {
const record = model.nugetById.get(id);
if (!record) {
errors.push(`Installer NuGet catalog has unknown package ${id}`);
} else if (version !== record.version) {
errors.push(`Installer NuGet catalog lists ${id} ${version}, project has ${record.version}`);
}
}
for (const project of model.nugetPackages) {
for (const reference of project.references) {
const target = model.nugetById.get(reference.id);
if (target && reference.version !== target.version) {
errors.push(`${project.project} references ${reference.id} ${reference.version}, Workspace has ${target.version}`);
}
}
}
const dependencies = new Map(model.upmPackages.map(record => [
record.name,
new Set(record.dependencies.filter(dependency => model.upmByName.has(dependency.name)).map(dependency => dependency.name))
]));
const resolved = new Set();
let progress = true;
while (progress) {
progress = false;
for (const [name, values] of dependencies) {
if (!resolved.has(name) && [...values].every(dependency => resolved.has(dependency))) {
resolved.add(name);
progress = true;
}
}
}
if (resolved.size !== model.upmPackages.length) {
const blocked = [...dependencies]
.filter(([name]) => !resolved.has(name))
.map(([name, values]) => `${name} -> ${[...values].filter(value => !resolved.has(value)).join(', ')}`);
errors.push(`Circular UPM dependencies: ${blocked.join('; ')}`);
}
const expectedCatalog = generatePackageCatalog(model);
if (!fs.existsSync(packageCatalogPath)) {
errors.push(`Generated package catalog is missing: ${relativeToWorkspace(packageCatalogPath)}`);
} else {
const actualCatalog = fs.readFileSync(packageCatalogPath, 'utf8').replaceAll('\r\n', '\n');
if (actualCatalog !== expectedCatalog) {
errors.push(`${relativeToWorkspace(packageCatalogPath)} is out of date`);
}
}
return errors;
}
function resolveTarget(model, requested) {
const key = requested.toLowerCase();
const upmMatches = model.upmPackages.filter(record =>
[record.name, record.directory, record.displayName].some(value => value && value.toLowerCase() === key));
const nugetMatches = model.nugetPackages.filter(record => record.id.toLowerCase() === key);
const matches = [...upmMatches.map(record => ({ kind: 'upm', record })), ...nugetMatches.map(record => ({ kind: 'nuget', record }))];
if (matches.length === 0) {
throw new Error(`Package was not found: ${requested}`);
}
if (matches.length > 1) {
throw new Error(`Package name is ambiguous: ${requested}`);
}
return matches[0];
}
function createPlan(model, options) {
const upmPlan = new Map();
const nugetPlan = new Map();
const reasons = new Map();
const reasonKey = (kind, name) => `${kind}:${name}`;
const addReason = (kind, name, reason) => {
const key = reasonKey(kind, name);
const values = reasons.get(key) ?? [];
if (!values.includes(reason)) values.push(reason);
reasons.set(key, values);
};
const setUpm = (record, version, reason) => {
const existing = upmPlan.get(record.name);
if (existing && existing !== version) throw new Error(`Conflicting versions planned for ${record.name}: ${existing} and ${version}`);
addReason('upm', record.name, reason);
if (existing) return false;
upmPlan.set(record.name, version);
return true;
};
const setNuget = (record, version, reason) => {
const existing = nugetPlan.get(record.id);
if (existing && existing !== version) throw new Error(`Conflicting versions planned for ${record.id}: ${existing} and ${version}`);
addReason('nuget', record.id, reason);
if (existing) return false;
nugetPlan.set(record.id, version);
return true;
};
const ensureUpmPatch = (record, reason) => setUpm(record, bumpVersion(record.version, 'patch'), reason);
const ensureNugetPatch = (record, reason) => {
if (record.coupledToUpm) return ensureUpmPatch(model.upmByName.get(record.ownerUpmName), reason);
const changed = setNuget(record, bumpVersion(record.version, 'patch'), reason);
if (record.ownerUpmName) ensureUpmPatch(model.upmByName.get(record.ownerUpmName), `${record.id} content changed`);
return changed;
};
const target = resolveTarget(model, options.package);
const currentVersion = target.record.version;
const requestedVersion = options.version ?? bumpVersion(currentVersion, options.bump);
if (compareVersions(requestedVersion, currentVersion) <= 0) {
throw new Error(`Requested version must be newer than ${currentVersion}: ${requestedVersion}`);
}
if (target.kind === 'upm') {
setUpm(target.record, requestedVersion, 'requested update');
} else if (target.record.coupledToUpm) {
setUpm(model.upmByName.get(target.record.ownerUpmName), requestedVersion, `requested through ${target.record.id}`);
} else {
setNuget(target.record, requestedVersion, 'requested update');
if (target.record.ownerUpmName) {
ensureUpmPatch(model.upmByName.get(target.record.ownerUpmName), `${target.record.id} content changed`);
}
}
for (const record of model.upmPackages) {
for (const dependency of record.dependencies) {
const targetRecord = model.upmByName.get(dependency.name);
if (targetRecord && dependency.version !== targetRecord.version) {
ensureUpmPatch(record, `repair ${dependency.name} dependency`);
}
}
for (const project of record.nugetPackages.filter(candidate => candidate.coupledToUpm)) {
if (project.version !== record.version) ensureUpmPatch(record, `repair ${project.id} version`);
}
}
for (const project of model.nugetPackages) {
for (const reference of project.references) {
const targetRecord = model.nugetById.get(reference.id);
if (targetRecord && reference.version !== targetRecord.version) {
ensureNugetPatch(project, `repair ${reference.id} reference`);
}
}
}
const upmCatalog = parseUpmCatalog(model);
const nugetCatalog = parseNugetCatalog(model);
let changed = true;
while (changed) {
changed = false;
for (const record of model.upmPackages) {
if (!upmPlan.has(record.name)) continue;
for (const project of record.nugetPackages.filter(candidate => candidate.coupledToUpm)) {
changed = setNuget(project, upmPlan.get(record.name), `coupled to ${record.name}`) || changed;
}
}
for (const project of model.nugetPackages.filter(candidate => candidate.coupledToUpm && nugetPlan.has(candidate.id))) {
changed = setUpm(model.upmByName.get(project.ownerUpmName), nugetPlan.get(project.id), `coupled to ${project.id}`) || changed;
}
for (const record of model.upmPackages) {
for (const dependency of record.dependencies) {
const targetRecord = model.upmByName.get(dependency.name);
if (!targetRecord) continue;
const targetVersion = finalUpmVersion(targetRecord, upmPlan);
if (dependency.version !== targetVersion) {
changed = ensureUpmPatch(record, `${dependency.name} becomes ${targetVersion}`) || changed;
}
}
}
for (const project of model.nugetPackages) {
for (const reference of project.references) {
const targetRecord = model.nugetById.get(reference.id);
if (!targetRecord) continue;
const targetVersion = finalNugetVersion(targetRecord, nugetPlan);
if (reference.version !== targetVersion) {
changed = ensureNugetPatch(project, `${reference.id} becomes ${targetVersion}`) || changed;
}
}
}
for (const project of model.nugetPackages.filter(candidate => nugetPlan.has(candidate.id) && candidate.ownerUpmName && !candidate.coupledToUpm)) {
changed = ensureUpmPatch(model.upmByName.get(project.ownerUpmName), `${project.id} content changed`) || changed;
}
for (const record of model.upmPackages.filter(candidate => candidate.name !== installerPackageName)) {
if (upmCatalog.get(record.name) !== finalUpmVersion(record, upmPlan)) {
changed = ensureUpmPatch(model.installer, `${record.name} catalog changed`) || changed;
}
}
for (const [id, catalogVersion] of nugetCatalog) {
const project = model.nugetById.get(id);
if (project && catalogVersion !== finalNugetVersion(project, nugetPlan)) {
changed = ensureUpmPatch(model.installer, `${id} catalog changed`) || changed;
}
}
}
return { upmPlan, nugetPlan, reasons };
}
function replaceSingle(text, pattern, replacer, description) {
const countPattern = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
const matches = [...text.matchAll(countPattern)];
if (matches.length !== 1) {
throw new Error(`${description}: expected one match, found ${matches.length}`);
}
return text.replace(pattern, replacer);
}
function replaceManifestVersion(text, version, manifestPath) {
return replaceSingle(
text,
/^(\s*"version"\s*:\s*")([^"]+)(")/m,
`$1${version}$3`,
`${relativeToWorkspace(manifestPath)} top-level version`
);
}
function replaceJsonValue(text, name, version, filePath) {
const pattern = new RegExp(`("${escapeRegularExpression(name)}"\\s*:\\s*")([^"]+)(")`, 'g');
return replaceSingle(text, pattern, `$1${version}$3`, `${relativeToWorkspace(filePath)} ${name}`);
}
function replaceProjectVersion(text, version, projectPath) {
return replaceSingle(
text,
/(<Version>\s*)([^<]+?)(\s*<\/Version>)/i,
`$1${version}$3`,
`${relativeToWorkspace(projectPath)} Version`
);
}
function replacePackageReferenceVersion(text, id, version, projectPath) {
const elementPattern = /<PackageReference\b[\s\S]*?(?:\/>|<\/PackageReference>)/gi;
const elements = [...text.matchAll(elementPattern)].filter(match => xmlAttribute(match[0], 'Include') === id);
if (elements.length !== 1) {
throw new Error(`${relativeToWorkspace(projectPath)} ${id} reference: expected one match, found ${elements.length}`);
}
const original = elements[0][0];
let replacement;
if (/\bVersion\s*=\s*"[^"]+"/i.test(original)) {
replacement = original.replace(/(\bVersion\s*=\s*")([^"]+)(")/i, `$1${version}$3`);
} else {
replacement = replaceSingle(original, /(<Version>\s*)([^<]+?)(\s*<\/Version>)/i, `$1${version}$3`, `${id} nested Version`);
}
return `${text.slice(0, elements[0].index)}${replacement}${text.slice(elements[0].index + original.length)}`;
}
function buildUpdatedContents(model, plan) {
const contents = new Map();
const read = filePath => contents.get(filePath) ?? fs.readFileSync(filePath, 'utf8');
const write = (filePath, text) => contents.set(filePath, text);
for (const record of model.upmPackages.filter(candidate => plan.upmPlan.has(candidate.name))) {
let text = read(record.manifestPath);
text = replaceManifestVersion(text, plan.upmPlan.get(record.name), record.manifestPath);
for (const dependency of record.dependencies) {
const target = model.upmByName.get(dependency.name);
if (!target) continue;
const targetVersion = finalUpmVersion(target, plan.upmPlan);
if (dependency.version !== targetVersion) {
text = replaceJsonValue(text, dependency.name, targetVersion, record.manifestPath);
}
}
write(record.manifestPath, text);
}
for (const project of model.nugetPackages.filter(candidate => plan.nugetPlan.has(candidate.id))) {
let text = read(project.path);
text = replaceProjectVersion(text, plan.nugetPlan.get(project.id), project.path);
for (const reference of project.references) {
const target = model.nugetById.get(reference.id);
if (!target) continue;
const targetVersion = finalNugetVersion(target, plan.nugetPlan);
if (reference.version !== targetVersion) {
text = replacePackageReferenceVersion(text, reference.id, targetVersion, project.path);
}
}
write(project.path, text);
}
let upmCatalogText = read(model.installerUpmCatalogPath);
const upmCatalog = parseUpmCatalog(model);
for (const record of model.upmPackages.filter(candidate => candidate.name !== installerPackageName)) {
const version = finalUpmVersion(record, plan.upmPlan);
if (upmCatalog.get(record.name) !== version) {
const pattern = new RegExp(`("${escapeRegularExpression(record.name)}"\\s*,\\s*")([^"]+)(")`, 'g');
upmCatalogText = replaceSingle(upmCatalogText, pattern, `$1${version}$3`, `Installer UPM catalog ${record.name}`);
}
}
write(model.installerUpmCatalogPath, upmCatalogText);
let nugetCatalogText = read(model.installerNugetCatalogPath);
const nugetCatalog = parseNugetCatalog(model);
for (const [id, currentVersion] of nugetCatalog) {
const project = model.nugetById.get(id);
if (!project) continue;
const version = finalNugetVersion(project, plan.nugetPlan);
if (currentVersion !== version) {
const pattern = new RegExp(`(\\["${escapeRegularExpression(id)}"\\]\\s*=\\s*")([^"]+)(")`, 'g');
nugetCatalogText = replaceSingle(nugetCatalogText, pattern, `$1${version}$3`, `Installer NuGet catalog ${id}`);
}
}
write(model.installerNugetCatalogPath, nugetCatalogText);
let designText = read(model.designPath);
const designVersions = parseDesignVersions(model);
for (const record of model.upmPackages) {
const version = finalUpmVersion(record, plan.upmPlan);
if (!designVersions.has(record.name)) {
throw new Error(`DESIGN.md is missing package ${record.name}`);
}
if (designVersions.get(record.name) !== version) {
const pattern = new RegExp('^(\\|\\s*`' + escapeRegularExpression(record.name) + '`\\s*\\|\\s*)[^|]+?(\\s*\\|)', 'm');
designText = replaceSingle(designText, pattern, `$1${version}$2`, `DESIGN.md ${record.name}`);
}
}
write(model.designPath, designText);
write(packageCatalogPath, generatePackageCatalog(model, plan.upmPlan, plan.nugetPlan));
for (const [filePath, text] of [...contents]) {
if (fs.existsSync(filePath) && fs.readFileSync(filePath, 'utf8') === text) {
contents.delete(filePath);
}
}
return contents;
}
function printPlan(model, plan, contents, dryRun) {
console.log(dryRun ? 'Dry-run version plan:' : 'Applied version plan:');
for (const record of model.upmPackages.filter(candidate => plan.upmPlan.has(candidate.name))) {
const reasons = plan.reasons.get(`upm:${record.name}`) ?? [];
console.log(` UPM ${record.name}: ${record.version} -> ${plan.upmPlan.get(record.name)} (${reasons.join('; ')})`);
}
for (const record of model.nugetPackages.filter(candidate => plan.nugetPlan.has(candidate.id))) {
const reasons = plan.reasons.get(`nuget:${record.id}`) ?? [];
console.log(` NuGet ${record.id}: ${record.version} -> ${plan.nugetPlan.get(record.id)} (${reasons.join('; ')})`);
}
console.log('Files:');
for (const filePath of [...contents.keys()].sort((left, right) => left.localeCompare(right))) {
console.log(` ${relativeToWorkspace(filePath)}`);
}
}
function applyContents(contents) {
const originals = new Map();
try {
for (const [filePath, text] of contents) {
originals.set(filePath, fs.existsSync(filePath) ? fs.readFileSync(filePath) : null);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, text, 'utf8');
}
const refreshed = buildModel();
const errors = collectValidationErrors(refreshed);
if (errors.length > 0) {
throw new Error(`Post-update validation failed:\n${errors.map(error => ` - ${error}`).join('\n')}`);
}
} catch (error) {
for (const [filePath, original] of originals) {
if (original === null) fs.rmSync(filePath, { force: true });
else fs.writeFileSync(filePath, original);
}
throw error;
}
}
function main() {
let options;
try {
options = parseArguments(process.argv.slice(2));
} catch (error) {
usage(error.message);
return;
}
if (options.help) {
usage();
process.exitCode = 0;
return;
}
try {
const model = buildModel();
if (options.check) {
const errors = collectValidationErrors(model);
if (errors.length > 0) {
throw new Error(`ShrinkSDK version validation failed:\n${errors.map(error => ` - ${error}`).join('\n')}`);
}
console.log(`ShrinkSDK version validation passed: UPM=${model.upmPackages.length}, NuGet=${model.nugetPackages.length}`);
return;
}
const plan = createPlan(model, options);
const contents = buildUpdatedContents(model, plan);
printPlan(model, plan, contents, options.dryRun);
if (!options.dryRun) {
applyContents(contents);
}
} catch (error) {
console.error(error.stack ?? error.message);
process.exitCode = 1;
}
}
main();
@@ -5,6 +5,7 @@ workspace_root="${1:-$PWD}"
workspace_root="$(cd "$workspace_root" && pwd)"
unity_bin="${UNITY_EDITOR_PATH:-$(command -v unity-editor || command -v unity || command -v Unity || true)}"
consumer_root="$workspace_root/Temp/PublishedUpmConsumerValidation"
published_catalog="$workspace_root/Tools/UpmConsumerValidation/published-upm-versions.json"
if [[ ! -f "$workspace_root/ProjectSettings/ProjectVersion.txt" ]]; then
echo "Workspace ProjectVersion.txt was not found: $workspace_root" >&2
@@ -16,6 +17,39 @@ if [[ -z "$unity_bin" ]]; then
exit 1
fi
if [[ ! -f "$published_catalog" ]]; then
echo "Published package catalog was not found: $published_catalog" >&2
exit 1
fi
published_value() {
local package_name="$1"
local property_name="$2"
node --input-type=module - "$published_catalog" "$package_name" "$property_name" <<'NODE'
import { readFileSync } from 'node:fs';
const [, , catalogPath, packageName, propertyName] = process.argv;
const catalog = JSON.parse(readFileSync(catalogPath, 'utf8'));
const value = catalog.packages?.[packageName]?.[propertyName];
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`Published catalog value is missing: ${packageName}.${propertyName}`);
}
if (propertyName === 'version' && !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(value)) {
throw new Error(`Published catalog version is invalid: ${packageName}=${value}`);
}
process.stdout.write(value);
NODE
}
export SHRINKSDK_PUBLISHED_STARTER_VERSION="$(published_value com.cneicy.shrink-app-starter-basic version)"
export SHRINKSDK_PUBLISHED_CONTEXT_APP_VERSION="$(published_value com.cneicy.shrink-context-app-adapter version)"
export SHRINKSDK_PUBLISHED_CONTEXT_EVENTBUS_VERSION="$(published_value com.cneicy.shrink-context-eventbus-adapter version)"
export SHRINKSDK_PUBLISHED_MOD_VERSION="$(published_value com.cneicy.shrink-mod-framework version)"
export SHRINKSDK_PUBLISHED_TUTORIAL_VERSION="$(published_value com.cneicy.shrink-tutorial version)"
export SHRINKSDK_PUBLISHED_INSTALLER_VERSION="$(published_value com.cneicy.shrink-installer version)"
export SHRINKSDK_PUBLISHED_MOD_REPOSITORY="$(published_value com.cneicy.shrink-mod-framework repository)"
export SHRINKSDK_PUBLISHED_INSTALLER_REPOSITORY="$(published_value com.cneicy.shrink-installer repository)"
case "$consumer_root" in
"$workspace_root"/Temp/*) ;;
*) echo "Consumer project must stay under the workspace Temp directory." >&2; exit 1 ;;
@@ -42,19 +76,28 @@ public static class PublishedUpmConsumerValidator
{
private const string RegistryUrl = "https://git.crash.work/api/packages/ShrinkSDK/npm/";
private const string UniTaskUrl = "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b";
private static readonly string StarterVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_STARTER_VERSION");
private static readonly string ContextAppVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_CONTEXT_APP_VERSION");
private static readonly string ContextEventBusVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_CONTEXT_EVENTBUS_VERSION");
private static readonly string ModVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_MOD_VERSION");
private static readonly string TutorialVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_TUTORIAL_VERSION");
private static readonly string InstallerVersion = RequiredEnvironment("SHRINKSDK_PUBLISHED_INSTALLER_VERSION");
private static readonly string ModRepository = RequiredEnvironment("SHRINKSDK_PUBLISHED_MOD_REPOSITORY");
private static readonly string InstallerRepository = RequiredEnvironment("SHRINKSDK_PUBLISHED_INSTALLER_REPOSITORY");
public static void VerifyRegistry()
{
Run(() =>
{
VerifyPackage("com.cneicy.shrink-app-starter-basic", "0.2.2", "ShrinkApp.Starter.Basic.Runtime");
VerifyPackage("com.cneicy.shrink-context-app-adapter", "0.1.5", "ShrinkContext.AppAdapter.Runtime");
VerifyPackage("com.cneicy.shrink-context-eventbus-adapter", "0.1.1", "ShrinkContext.EventBusAdapter.Runtime");
VerifyPackage("com.cneicy.shrink-mod-framework", "0.2.4", "ShrinkModFramework.Runtime");
VerifyPackage("com.cneicy.shrink-tutorial", "0.1.3", "ShrinkTutorial.Runtime");
RequireManifestValue("com.cneicy.shrink-app-starter-basic", "0.2.2");
RequireManifestValue("com.cneicy.shrink-context-eventbus-adapter", "0.1.1");
RequireManifestValue("com.cneicy.shrink-mod-framework", "0.2.4");
RequireManifestValue("com.cneicy.shrink-tutorial", "0.1.3");
VerifyPackage("com.cneicy.shrink-app-starter-basic", StarterVersion, "ShrinkApp.Starter.Basic.Runtime");
VerifyPackage("com.cneicy.shrink-context-app-adapter", ContextAppVersion, "ShrinkContext.AppAdapter.Runtime");
VerifyPackage("com.cneicy.shrink-context-eventbus-adapter", ContextEventBusVersion, "ShrinkContext.EventBusAdapter.Runtime");
VerifyPackage("com.cneicy.shrink-mod-framework", ModVersion, "ShrinkModFramework.Runtime");
VerifyPackage("com.cneicy.shrink-tutorial", TutorialVersion, "ShrinkTutorial.Runtime");
RequireManifestValue("com.cneicy.shrink-app-starter-basic", StarterVersion);
RequireManifestValue("com.cneicy.shrink-context-eventbus-adapter", ContextEventBusVersion);
RequireManifestValue("com.cneicy.shrink-mod-framework", ModVersion);
RequireManifestValue("com.cneicy.shrink-tutorial", TutorialVersion);
RequireManifestValue("com.cysharp.unitask", UniTaskUrl);
RequireRegistry("com.cneicy", RegistryUrl);
});
@@ -64,10 +107,10 @@ public static class PublishedUpmConsumerValidator
{
Run(() =>
{
VerifyPackage("com.cneicy.shrink-mod-framework", "0.2.4", "ShrinkModFramework.Runtime");
VerifyPackage("com.cneicy.shrink-mod-framework", ModVersion, "ShrinkModFramework.Runtime");
RequireManifestValue(
"com.cneicy.shrink-mod-framework",
"https://git.crash.work/ShrinkSDK/ShrinkModFramework.git#v0.2.4");
ModRepository + "#v" + ModVersion);
RequireManifestValue("com.cysharp.unitask", UniTaskUrl);
RequireRegistry("com.cneicy", RegistryUrl);
});
@@ -77,10 +120,10 @@ public static class PublishedUpmConsumerValidator
{
try
{
VerifyPackage("com.cneicy.shrink-installer", "0.2.4", "ShrinkInstaller.Editor");
VerifyPackage("com.cneicy.shrink-installer", InstallerVersion, "ShrinkInstaller.Editor");
RequireManifestValue(
"com.cneicy.shrink-installer",
"https://git.crash.work/ShrinkSDK/Installer.git#v0.2.4");
InstallerRepository + "#v" + InstallerVersion);
var catalog = FindType("ShrinkSDK.Installer.ShrinkSdkPackageCatalog");
var starter = catalog.GetField("StarterBasic", BindingFlags.Static | BindingFlags.NonPublic)
@@ -94,7 +137,7 @@ public static class PublishedUpmConsumerValidator
roots.SetValue(starter, 0);
install.Invoke(null, new object[] { roots });
RequireManifestValue("com.cneicy.shrink-app-starter-basic", "0.2.2");
RequireManifestValue("com.cneicy.shrink-app-starter-basic", StarterVersion);
RequireManifestValue("com.cysharp.unitask", UniTaskUrl);
RequireRegistry("com.cneicy", RegistryUrl);
RequireRegistry("com.example", "https://registry.npmjs.org/");
@@ -110,10 +153,10 @@ public static class PublishedUpmConsumerValidator
{
Run(() =>
{
VerifyPackage("com.cneicy.shrink-installer", "0.2.4", "ShrinkInstaller.Editor");
VerifyPackage("com.cneicy.shrink-app-starter-basic", "0.2.2", "ShrinkApp.Starter.Basic.Runtime");
VerifyPackage("com.cneicy.shrink-context-app-adapter", "0.1.5", "ShrinkContext.AppAdapter.Runtime");
RequireManifestValue("com.cneicy.shrink-app-starter-basic", "0.2.2");
VerifyPackage("com.cneicy.shrink-installer", InstallerVersion, "ShrinkInstaller.Editor");
VerifyPackage("com.cneicy.shrink-app-starter-basic", StarterVersion, "ShrinkApp.Starter.Basic.Runtime");
VerifyPackage("com.cneicy.shrink-context-app-adapter", ContextAppVersion, "ShrinkContext.AppAdapter.Runtime");
RequireManifestValue("com.cneicy.shrink-app-starter-basic", StarterVersion);
RequireManifestValue("com.cysharp.unitask", UniTaskUrl);
RequireRegistry("com.cneicy", RegistryUrl);
RequireRegistry("com.example", "https://registry.npmjs.org/");
@@ -133,6 +176,12 @@ public static class PublishedUpmConsumerValidator
}
}
private static string RequiredEnvironment(string name)
{
return Environment.GetEnvironmentVariable(name)
?? throw new InvalidOperationException("Required environment variable is missing: " + name);
}
private static void VerifyPackage(string packageName, string version, string assemblyName)
{
var package = PackageInfo.GetAllRegisteredPackages()
@@ -261,7 +310,7 @@ rm -rf "$consumer_root"
mkdir -p "$consumer_root"
registry_project="$(prepare_consumer registry)"
write_manifest "$registry_project" '{
registry_manifest='{
"scopedRegistries": [
{
"name": "ShrinkSDK",
@@ -270,18 +319,23 @@ write_manifest "$registry_project" '{
}
],
"dependencies": {
"com.cneicy.shrink-app-starter-basic": "0.2.2",
"com.cneicy.shrink-context-eventbus-adapter": "0.1.1",
"com.cneicy.shrink-mod-framework": "0.2.4",
"com.cneicy.shrink-tutorial": "0.1.3",
"com.cneicy.shrink-app-starter-basic": "__STARTER_VERSION__",
"com.cneicy.shrink-context-eventbus-adapter": "__CONTEXT_EVENTBUS_VERSION__",
"com.cneicy.shrink-mod-framework": "__MOD_VERSION__",
"com.cneicy.shrink-tutorial": "__TUTORIAL_VERSION__",
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b",
"com.unity.nuget.newtonsoft-json": "3.2.2"
}
}'
registry_manifest="${registry_manifest//__STARTER_VERSION__/$SHRINKSDK_PUBLISHED_STARTER_VERSION}"
registry_manifest="${registry_manifest//__CONTEXT_EVENTBUS_VERSION__/$SHRINKSDK_PUBLISHED_CONTEXT_EVENTBUS_VERSION}"
registry_manifest="${registry_manifest//__MOD_VERSION__/$SHRINKSDK_PUBLISHED_MOD_VERSION}"
registry_manifest="${registry_manifest//__TUTORIAL_VERSION__/$SHRINKSDK_PUBLISHED_TUTORIAL_VERSION}"
write_manifest "$registry_project" "$registry_manifest"
run_unity "$registry_project" PublishedUpmConsumerValidator.VerifyRegistry "$registry_project/registry.log" false
git_project="$(prepare_consumer git-tag)"
write_manifest "$git_project" '{
git_manifest='{
"scopedRegistries": [
{
"name": "ShrinkSDK",
@@ -290,15 +344,18 @@ write_manifest "$git_project" '{
}
],
"dependencies": {
"com.cneicy.shrink-mod-framework": "https://git.crash.work/ShrinkSDK/ShrinkModFramework.git#v0.2.4",
"com.cneicy.shrink-mod-framework": "__MOD_REPOSITORY__#v__MOD_VERSION__",
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b",
"com.unity.nuget.newtonsoft-json": "3.2.2"
}
}'
git_manifest="${git_manifest//__MOD_REPOSITORY__/$SHRINKSDK_PUBLISHED_MOD_REPOSITORY}"
git_manifest="${git_manifest//__MOD_VERSION__/$SHRINKSDK_PUBLISHED_MOD_VERSION}"
write_manifest "$git_project" "$git_manifest"
run_unity "$git_project" PublishedUpmConsumerValidator.VerifyGitTag "$git_project/git-tag.log" false
installer_project="$(prepare_consumer installer)"
write_manifest "$installer_project" '{
installer_manifest='{
"scopedRegistries": [
{
"name": "Existing Registry",
@@ -307,11 +364,14 @@ write_manifest "$installer_project" '{
}
],
"dependencies": {
"com.cneicy.shrink-installer": "https://git.crash.work/ShrinkSDK/Installer.git#v0.2.4",
"com.cneicy.shrink-installer": "__INSTALLER_REPOSITORY__#v__INSTALLER_VERSION__",
"com.unity.nuget.newtonsoft-json": "3.2.2",
"com.unity.test-framework": "1.1.33"
}
}'
installer_manifest="${installer_manifest//__INSTALLER_REPOSITORY__/$SHRINKSDK_PUBLISHED_INSTALLER_REPOSITORY}"
installer_manifest="${installer_manifest//__INSTALLER_VERSION__/$SHRINKSDK_PUBLISHED_INSTALLER_VERSION}"
write_manifest "$installer_project" "$installer_manifest"
run_unity "$installer_project" PublishedUpmConsumerValidator.ApplyInstaller "$installer_project/installer-apply.log" false
run_unity "$installer_project" PublishedUpmConsumerValidator.VerifyInstallerResult "$installer_project/installer-result.log" false
@@ -0,0 +1,31 @@
{
"schemaVersion": 1,
"packages": {
"com.cneicy.shrink-app-starter-basic": {
"version": "0.3.0",
"assembly": "ShrinkApp.Starter.Basic.Runtime"
},
"com.cneicy.shrink-context-app-adapter": {
"version": "0.2.0",
"assembly": "ShrinkContext.AppAdapter.Runtime"
},
"com.cneicy.shrink-context-eventbus-adapter": {
"version": "0.2.0",
"assembly": "ShrinkContext.EventBusAdapter.Runtime"
},
"com.cneicy.shrink-mod-framework": {
"version": "0.3.0",
"assembly": "ShrinkModFramework.Runtime",
"repository": "https://git.crash.work/ShrinkSDK/ShrinkModFramework.git"
},
"com.cneicy.shrink-tutorial": {
"version": "0.2.0",
"assembly": "ShrinkTutorial.Runtime"
},
"com.cneicy.shrink-installer": {
"version": "0.2.5",
"assembly": "ShrinkInstaller.Editor",
"repository": "https://git.crash.work/ShrinkSDK/Installer.git"
}
}
}