Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

scripts/release/prepare.ts

Raw
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { ROOT } from "../build/build.ts";
import { treeDigest } from "../build/release.ts";
import { isReleaseVersion } from "../extensions.ts";

export interface ReleaseRequest {
	sourceCommit: string;
	targetBranch: string;
	version: string;
}

interface Provenance {
	sourceCommit: string;
	requestCommit: string;
	requestDigest: string;
	targetBranch: string;
	version: string;
	releaseManifestSha256: string;
	checks: string[];
}

export interface PrepareOptions {
	root?: string;
	remote?: string;
	runTask?: (task: string, args: string[], root: string) => void;
	beforePush?: () => void;
}

const REQUEST_PATH = ".ci/release-request.json";
const PROVENANCE_PATH = "release-provenance.json";
const CHECKS = ["//:release-all", "//:verify-packages"];

function fail(message: string): never {
	throw new Error(`release preparation: ${message}`);
}

function sha256(value: string | Buffer): string {
	return createHash("sha256").update(value).digest("hex");
}

export function parseRequest(text: string): ReleaseRequest {
	let value: unknown;
	try {
		value = JSON.parse(text);
	} catch {
		fail("request is not JSON");
	}
	if (!value || typeof value !== "object" || Array.isArray(value))
		fail("request must be an object");
	const request = value as Record<string, unknown>;
	const keys = ["sourceCommit", "targetBranch", "version"];
	if (
		Object.keys(request).length !== keys.length ||
		!keys.every((key) => key in request)
	)
		fail("request must contain only sourceCommit, targetBranch, and version");
	if (!keys.every((key) => typeof request[key] === "string"))
		fail("request values must be strings");
	const parsed = request as unknown as ReleaseRequest;
	if (!/^[0-9a-f]{40}$/u.test(parsed.sourceCommit))
		fail("sourceCommit must be a full lowercase Git commit ID");
	if (!isReleaseVersion(parsed.version)) fail("version must be valid semver");
	if (parsed.targetBranch !== `release/v${parsed.version}`)
		fail("targetBranch must be release/v<version>");
	return parsed;
}

function withVersion(
	text: string,
	version: string,
	lock = false,
): Record<string, unknown> {
	const value = JSON.parse(text) as Record<string, unknown>;
	value["version"] = version;
	if (lock) {
		const packages = value["packages"];
		if (!packages || typeof packages !== "object" || !("" in packages))
			fail("source lockfile has no root package entry");
		const root = (packages as Record<string, Record<string, unknown>>)[""];
		if (!root || typeof root !== "object")
			fail("source lockfile root package is invalid");
		root["version"] = version;
	}
	return value;
}

function sameJson(left: unknown, right: unknown): boolean {
	return JSON.stringify(left) === JSON.stringify(right);
}

export function prepareRelease(options: PrepareOptions = {}): void {
	const root = options.root ?? ROOT;
	const remote =
		options.remote ??
		process.env["PI_EXT_RELEASE_REMOTE"] ??
		fail("PI_EXT_RELEASE_REMOTE is required from approved branch-limited auth");
	const run = (command: string, args: string[], capture = false): string => {
		const result = spawnSync(command, args, {
			cwd: root,
			encoding: "utf8",
			stdio: capture ? ["ignore", "pipe", "pipe"] : "inherit",
		});
		if (result.error || result.status !== 0)
			fail(`${command === "git" ? "Git operation" : command} failed`);
		return result.stdout ?? "";
	};
	const git = (args: string[], capture = false) => run("git", args, capture);
	const show = (revision: string, path: string) =>
		git(["show", `${revision}:${path}`], true);
	const remoteHead = (): string | undefined => {
		const output = git(
			["ls-remote", "--heads", remote, `refs/heads/${request.targetBranch}`],
			true,
		).trim();
		if (!output) return undefined;
		const [commit, ref] = output.split(/\s+/u);
		if (
			!/^[0-9a-f]{40}$/u.test(commit ?? "") ||
			ref !== `refs/heads/${request.targetBranch}`
		)
			fail("remote returned an invalid release branch ref");
		return commit;
	};
	const requestText = readFileSync(join(root, REQUEST_PATH), "utf8");
	const request = parseRequest(requestText);
	const requestDigest = sha256(requestText);
	const requestCommit = git(["rev-parse", "HEAD"], true).trim();
	if (git(["status", "--porcelain"], true).trim())
		fail("coordinator checkout must be clean");
	if (!existsSync(join(root, ".git")))
		fail("coordinator must be a Git checkout");
	const existing = remoteHead();
	if (existing) {
		git(["fetch", "--no-tags", remote, existing]);
		const provenanceText = show(existing, PROVENANCE_PATH);
		let provenance: Provenance;
		try {
			provenance = JSON.parse(provenanceText) as Provenance;
		} catch {
			fail("existing release branch has no valid provenance");
		}
		if (
			provenance.sourceCommit !== request.sourceCommit ||
			provenance.requestCommit !== requestCommit ||
			provenance.version !== request.version ||
			provenance.targetBranch !== request.targetBranch ||
			provenance.requestDigest !== requestDigest ||
			!sameJson(provenance.checks, CHECKS)
		)
			fail("existing release branch conflicts with this request");
		const manifest = show(existing, "release-manifest.json");
		if (sha256(manifest) !== provenance.releaseManifestSha256)
			fail("existing release branch manifest digest differs from provenance");
		if (
			git(["rev-parse", `${existing}^`], true).trim() !== request.sourceCommit
		)
			fail("existing release branch does not directly follow requested source");
		const sourcePackage = withVersion(
			show(request.sourceCommit, "package.json"),
			request.version,
		);
		const sourceLock = withVersion(
			show(request.sourceCommit, "package-lock.json"),
			request.version,
			true,
		);
		if (
			!sameJson(JSON.parse(show(existing, "package.json")), sourcePackage) ||
			!sameJson(JSON.parse(show(existing, "package-lock.json")), sourceLock)
		)
			fail("existing release branch changes non-version metadata");
		const changed = git(
			["diff-tree", "--no-commit-id", "--name-only", "-r", existing],
			true,
		)
			.trim()
			.split("\n")
			.filter(Boolean);
		const allowed = new Set([
			"package.json",
			"package-lock.json",
			"release-manifest.json",
			PROVENANCE_PATH,
		]);
		if (
			!changed.includes("release-manifest.json") ||
			!changed.includes(PROVENANCE_PATH) ||
			changed.some((path) => !allowed.has(path))
		)
			fail("existing release branch contains unverified changes");
		if (remoteHead() !== existing)
			fail("release branch moved during idempotency check");
		writeFileSync(join(root, "release-manifest.json"), manifest);
		writeFileSync(join(root, PROVENANCE_PATH), provenanceText);
		console.log(
			`OK release branch ${request.targetBranch} already prepared: ${existing}`,
		);
		return;
	}
	git(["fetch", "--no-tags", remote, request.sourceCommit]);
	if (
		git(["rev-parse", `${request.sourceCommit}^{commit}`], true).trim() !==
		request.sourceCommit
	)
		fail("requested source commit is unavailable or does not match");
	const sourceMise = show(request.sourceCommit, "mise.toml");
	for (const task of ["release-version", "release-all", "verify-packages"])
		if (!sourceMise.includes(`[tasks.${task}]`))
			fail(`requested source lacks ${task} automation`);
	git(["checkout", "--detach", request.sourceCommit]);
	const runTask =
		options.runTask ??
		((task: string, args: string[], cwd: string) => {
			const result = spawnSync("mise", ["run", task, ...args], {
				cwd,
				encoding: "utf8",
				stdio: "inherit",
			});
			if (result.error || result.status !== 0) fail(`Mise task ${task} failed`);
		});
	runTask("//:release-version", [request.version], root);
	runTask("//:release-all", [], root);
	runTask("//:verify-packages", [], root);
	const manifest = JSON.parse(
		readFileSync(join(root, "release-manifest.json"), "utf8"),
	) as { extensions?: Array<{ extension: string; digest: string }> };
	if (!Array.isArray(manifest.extensions) || !manifest.extensions.length)
		fail("release manifest has no extension digests");
	for (const receipt of manifest.extensions) {
		if (
			!receipt ||
			typeof receipt.extension !== "string" ||
			typeof receipt.digest !== "string" ||
			treeDigest(join(root, "dist", receipt.extension)) !== receipt.digest
		)
			fail("verified package bytes differ from release manifest");
	}
	const provenance: Provenance = {
		sourceCommit: request.sourceCommit,
		requestCommit,
		requestDigest,
		targetBranch: request.targetBranch,
		version: request.version,
		releaseManifestSha256: sha256(
			readFileSync(join(root, "release-manifest.json")),
		),
		checks: CHECKS,
	};
	writeFileSync(
		join(root, PROVENANCE_PATH),
		`${JSON.stringify(provenance, null, "\t")}\n`,
	);
	git(["add", "package.json", "package-lock.json", PROVENANCE_PATH]);
	git(["add", "-f", "release-manifest.json"]);
	git([
		"-c",
		"user.name=pi-ext release preparation",
		"-c",
		"user.email=release@invalid",
		"commit",
		"-m",
		`release: prepare v${request.version}`,
	]);
	options.beforePush?.();
	const lease = `--force-with-lease=refs/heads/${request.targetBranch}:`;
	run("git", [
		"push",
		"--porcelain",
		lease,
		remote,
		`HEAD:refs/heads/${request.targetBranch}`,
	]);
	console.log(
		`OK prepared ${request.targetBranch}; review release-provenance.json and release-manifest.json`,
	);
}