Files
plan2code/scripts/install-ref-fixtures.mjs
T

234 lines
11 KiB
JavaScript
Raw Permalink Normal View History

// Local git-ref fixtures for the install/update tests: bare repositories in
// temp dirs, built with one `git fast-import` stream each, so no network, no
// working tree and no dozens of slow per-object git spawns are ever involved.
// A fixture carries the ref shape the installer and launcher reason about:
//
// - lightweight and annotated `vX.Y.Z` release tags on `main` commits
// (annotated ones produce peeled `^{}` lines in ls-remote output),
// - synthetic `install-vX.Y.Z` tags on slim payload commits, the shape the
// release workflow publishes (phase 5 builds the real publisher),
// - a `release` branch at the newest synthetic tip, or absent,
// - feature branches and a non-release tag the parsers must ignore,
// - older rollback versions, with and without a synthetic ref.
//
// Everything runs under the scrubbed git environment of
// scripts/skill-script-helpers.mjs (importing it here is what the failure log
// requires of fixture-building tests), and Node built-ins only.
//
// import { createInstallRefFixture } from "./install-ref-fixtures.mjs";
// const fx = createInstallRefFixture();
// fx.snapshotText(); // `git ls-remote --tags --heads`-style text
// fx.refs.tags["v3.1.2"]; // shas, per ref name
// fx.cleanup(); // idempotent
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { scrubbedEnv } from "./skill-script-helpers.mjs";
import { compareVersions } from "../src/web-console/update-check.mjs";
/**
* The default release ladder: a lightweight rollback with no synthetic ref, a
* rollback with one, and an annotated newest release with one. Exactly the
* matrix the rollback and fallback tests need; pass `releases` to vary it.
* Per release: `annotated` makes the v* tag annotated, `installTag` adds a
* synthetic `install-v*` ref, `files` replaces the full-source tree, and
* `installFiles` replaces the slim synthetic tree.
*/
export const DEFAULT_RELEASES = [
{ version: "1.0.0" },
{ version: "2.0.0", installTag: true },
{ version: "3.1.2", annotated: true, installTag: true },
];
/** The files of one full-source commit on main for `version` (docs/ included: the heavy tree). */
function fullTreeFiles(version) {
return {
"install.js": `// install.js for v${version}\n`,
"package.json": `${JSON.stringify({ name: "plan2code", version }, null, 2)}\n`,
"version.json": `${JSON.stringify({ version, releaseDate: "2026-01-01" }, null, 2)}\n`,
"src/web-console/update-check.mjs": `// update-check for v${version}\n`,
"docs/promo.md": `# heavy docs for v${version}\n`,
};
}
/** The slim runtime payload of a synthetic install commit: the full tree minus what the spec excludes. */
function slimTreeFiles(version, sourceCommitMark) {
const files = fullTreeFiles(version);
delete files["docs/promo.md"];
files[".plan2code-install-ref.json"] = `${JSON.stringify({ releaseRef: `v${version}`, sourceCommit: `mark-${sourceCommitMark}` }, null, 2)}\n`;
return files;
}
// fast-import streams are length-delimited: `data <n>` plus exactly n bytes.
// Strings are UTF-8; Buffers stay byte-exact, so a real binary runtime file can
// ride in a fixture without being corrupted.
function dataBlock(content) {
const body = Buffer.isBuffer(content) ? content : Buffer.from(String(content), "utf8");
return Buffer.concat([Buffer.from(`data ${body.length}\n`, "utf8"), body]);
}
const textBlock = (text) => Buffer.from(String(text), "utf8");
const person = (who, ts) => `${who} Fixture <fixture@example.com> ${ts} +0000`;
/** One commit command with its whole tree inline (`M ... inline` needs no blob commands or index), as byte parts. */
function commitCommand(ref, mark, message, files, ts, fromMark) {
const parts = [textBlock(`commit ${ref}\nmark :${mark}\n${person("author", ts)}\n${person("committer", ts)}\n`), dataBlock(message)];
if (fromMark) parts.push(textBlock(`from :${fromMark}\n`));
for (const [name, content] of Object.entries(files)) parts.push(textBlock(`M 100644 inline ${name}\n`), dataBlock(content));
return parts;
}
export function createInstallRefFixture({
releases = DEFAULT_RELEASES,
releaseBranch = true,
releaseVersion = null,
featureBranches = ["feature/demo"],
extraTags = ["nightly"],
mainBranch = "main",
} = {}) {
if (!Array.isArray(releases) || releases.length === 0) throw new Error("createInstallRefFixture: releases must be a non-empty array");
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-install-refs-"));
const dir = path.join(root, "origin.git");
const env = scrubbedEnv();
const git = (args, options = {}) => execFileSync("git", ["--git-dir", dir, ...args], { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], env, ...options }).trim();
execFileSync("git", ["init", "-q", "--bare", "-b", mainBranch, dir], { env, stdio: "pipe" });
// Newest-first ordering is derived numerically, never lexically: 3.10.0
// must outrank 3.9.0 for the release branch and `newest` to be right.
const ordered = [...releases].sort((a, b) => compareVersions(a.version, b.version) ?? 0);
// The whole repository as one stream: main commits auto-parent per ref, the
// synthetic chain rides on refs/heads/release for the same reason, and
// resets pin the lightweight tags, feature branches and extra tags. Three
// git processes build a fixture (init, fast-import, for-each-ref) where the
// plumbing equivalent needs dozens — on Windows that is seconds each.
const stream = [];
const push = (text) => stream.push(textBlock(text));
const pushCommit = (...args) => stream.push(...commitCommand(...args));
let mark = 0;
let ts = 1700000000;
const versions = [];
let mainMark = null;
let syntheticMark = null;
for (const release of ordered) {
const { version, annotated = false, installTag = false } = release;
mainMark = ++mark;
ts += 60;
const fullFiles = release.files || fullTreeFiles(version);
pushCommit(`refs/heads/${mainBranch}`, mainMark, `release ${version}\n`, fullFiles, ts);
const entry = { version, annotated, install: null, mainMark };
if (annotated) {
push(`tag v${version}\nfrom :${mainMark}\n${person("tagger", ts)}\n`);
stream.push(dataBlock(`release ${version}\n`));
} else {
push(`reset refs/tags/v${version}\nfrom :${mainMark}\n`);
}
if (installTag) {
syntheticMark = ++mark;
entry.install = { mark: syntheticMark };
pushCommit("refs/heads/release", syntheticMark, `install payload ${version}\n`, release.installFiles || slimTreeFiles(version, mainMark), ts);
push(`reset refs/tags/install-v${version}\nfrom :${syntheticMark}\n`);
}
versions.push(entry);
}
const newest = ordered[ordered.length - 1].version;
for (const branch of featureBranches) push(`reset refs/heads/${branch}\nfrom :${mainMark}\n`);
for (const name of extraTags) push(`reset refs/tags/${name}\nfrom :${mainMark}\n`);
// The published shape: the release branch tip is a synthetic slim commit.
// It already is (the chain built it there) unless the fixture pins a stale
// tip or no synthetic ref exists at all, where it is a legacy full-source
// tip on main instead.
let releaseTipMark = null;
if (releaseBranch) {
const pinned = releaseVersion ? versions.find((v) => v.version === releaseVersion) : null;
if (releaseVersion && !pinned) throw new Error(`createInstallRefFixture: releaseVersion ${releaseVersion} is not one of the releases`);
if (pinned) releaseTipMark = pinned.install ? pinned.install.mark : pinned.mainMark;
else if (!syntheticMark) releaseTipMark = mainMark;
if (releaseTipMark) push(`reset refs/heads/release\nfrom :${releaseTipMark}\n`);
}
git(["fast-import", "--quiet"], { input: Buffer.concat(stream) });
if (!releaseBranch) git(["update-ref", "-d", "refs/heads/release"]);
// The shas fast-import wrote, in one process: objecttype names the annotated
// tag objects, and %(*objectname) peels them to their commits.
const listing = git(["for-each-ref", "--format", "%(refname) %(objectname) %(objecttype) %(*objectname)"]);
const refs = { heads: {}, tags: {}, peeled: {} };
for (const line of listing.split("\n")) {
if (!line) continue;
const [ref, sha, type, peeled] = line.split(" ");
if (ref.startsWith("refs/heads/")) refs.heads[ref.slice("refs/heads/".length)] = sha;
else if (ref.startsWith("refs/tags/")) {
refs.tags[ref.slice("refs/tags/".length)] = sha;
if (type === "tag" && peeled) refs.peeled[ref.slice("refs/tags/".length)] = peeled;
}
}
for (const entry of versions) {
// The commit a release tag names: its peeled target when annotated, the ref target otherwise.
entry.commit = refs.peeled[`v${entry.version}`] || refs.tags[`v${entry.version}`];
if (entry.install) entry.install.commit = refs.tags[`install-v${entry.version}`];
}
/**
* `git ls-remote`-style snapshot text, derived from the refs recorded at
* build time: one `<sha>\t<ref>` line per ref, sorted by ref name the way
* git sorts them, with a peeled `^{}` line immediately after each annotated
* tag. Matches real ls-remote output byte for byte for these fixtures (the
* test file asserts exactly that), so it can seed PLAN2CODE_LS_REMOTE_FILE
* without spawning anything.
*/
function snapshotText({ tags = true, heads = true } = {}) {
const entries = [];
if (heads) for (const [name, sha] of Object.entries(refs.heads)) entries.push([`refs/heads/${name}`, sha, null]);
if (tags) {
for (const [name, sha] of Object.entries(refs.tags)) entries.push([`refs/tags/${name}`, sha, refs.peeled[name] || null]);
}
entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
let out = "";
for (const [ref, sha, peel] of entries) {
out += `${sha}\t${ref}\n`;
if (peel) out += `${peel}\t${ref}^{}\n`;
}
return out;
}
/** The real thing: `git ls-remote` against the bare repo on disk. Local-path transport, so offline. */
function lsRemote({ tags = true, heads = true } = {}) {
const args = ["ls-remote"];
if (tags) args.push("--tags");
if (heads) args.push("--heads");
return execFileSync("git", [...args, dir], { encoding: "utf8", env });
}
/**
* A real local fetch of one ref into `dest`, laid out like an npx package
* rather than a working clone: the payload is complete, and `.git` is gone.
* The transport is the fixture's local path, so no network or credentials.
*/
function checkout(ref, dest) {
fs.rmSync(dest, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(path.dirname(dest), { recursive: true });
execFileSync("git", ["clone", "--quiet", "--depth", "1", "--branch", ref, dir, dest], { encoding: "utf8", env, stdio: ["ignore", "pipe", "pipe"] });
fs.rmSync(path.join(dest, ".git"), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
return dest;
}
let cleaned = false;
function cleanup() {
if (cleaned) return;
cleaned = true;
// maxRetries for Windows, where a just-exited git can hold a pack file
// for a beat; read-only object files are chmodded away by rm itself.
fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
return { dir, root, refs, versions, newest, mainBranch, snapshotText, lsRemote, checkout, cleanup };
}