868 lines
34 KiB
JavaScript
868 lines
34 KiB
JavaScript
#!/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();
|