import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const WALK_LIMIT = 50; const CI_GATE = ['test (node 22)', 'test (node 24)', 'published runtime (node 22.12.0)']; const VERSION_FILES = ['packages/stim-cli/package.json', '.github/next-version']; function latestRun(checkRuns, name) { return checkRuns.filter((run) => run.name === name).toSorted((a, b) => b.id - a.id)[0]; } function gatePassed(checkRuns) { const passed = (name) => latestRun(checkRuns, name)?.conclusion === 'success'; return passed('merge gate') || CI_GATE.every(passed); } function gateState(checkRuns) { return CI_GATE.map((name) => { const run = latestRun(checkRuns, name); return `${name}: ${run ? (run.conclusion ?? run.status) : 'no run'}`; }).join(', '); } const output = (line) => process.env.GITHUB_OUTPUT && appendFileSync(process.env.GITHUB_OUTPUT, `${line}\n`); const commitStamp = (date) => new Date(date).toISOString().replace(/\D/g, '').slice(0, 14); async function selectNextCommit({ commits, checkRunsAt, nextVersion, log = () => {} }) { const next = nextVersion?.match(/-next\.(\d{14})\.g([0-9a-f]{7})$/); const bySha = new Map(commits.map((commit) => [commit.sha, commit])); const chain = []; for (let commit = commits[0]; commit && chain.length < WALK_LIMIT; commit = bySha.get(commit.parents[0])) { chain.push(commit); } const nextIndex = next ? chain.findIndex((commit) => commit.sha.startsWith(next[2])) : -1; for (const [index, commit] of chain.entries()) { const checkRuns = await checkRunsAt(commit.sha); if (gatePassed(checkRuns)) { if (next && nextIndex === -1 && commitStamp(commit.date) <= next[1]) { return { reason: `${commit.sha} passed its gate but is not newer than next (${nextVersion})` }; } return { sha: commit.sha }; } if (index === nextIndex) { return { reason: `next already carries ${commit.sha} and no newer commit on main passed its gate` }; } log(`${commit.sha} has not passed its gate (${gateState(checkRuns)})`); } return { reason: `none of the newest ${chain.length} commits on main passed its gate` }; } function versionFilesProblem(head, selected) { const version = (files) => JSON.parse(files[VERSION_FILES[0]]).version; if (version(head).includes('-')) { return `main carries the release candidate ${version(head)}, which owns the next dist-tag`; } if (version(head) !== version(selected)) { return `main moved from ${version(selected)} to ${version(head)} after the selected commit, and that change has not passed its gate`; } if (head[VERSION_FILES[1]] !== selected[VERSION_FILES[1]]) { return `${VERSION_FILES[1]} changed after the selected commit, and that change has not passed its gate`; } return null; } async function main() { const repo = process.env.GITHUB_REPOSITORY; const api = async (path) => { const res = await fetch(`${process.env.GITHUB_API_URL ?? 'https://api.github.com'}/repos/${repo}/${path}`, { headers: { accept: 'application/vnd.github+json', authorization: `Bearer ${process.env.GH_TOKEN}` }, }); if (res.status === 404) return null; if (!res.ok) throw new Error(`GET ${path}: HTTP ${res.status} ${await res.text()}`); return res.json(); }; const checkRunsAt = async (sha) => { const runs = []; for (let page = 1; ; page += 1) { const { check_runs } = await api(`commits/${sha}/check-runs?per_page=100&page=${page}`); runs.push(...check_runs); if (check_runs.length < 100) return runs; } }; const versionFilesAt = async (sha) => { const files = {}; for (const path of VERSION_FILES) { const file = await api(`contents/${path}?ref=${sha}`); files[path] = file && Buffer.from(file.content, 'base64').toString(); } return files; }; const skip = (reason) => { console.log(`::notice::${reason}; not publishing`); output('skip=true'); }; const head = process.env.HEAD_SHA; const page = new Map((await api(`commits?sha=${head}&per_page=${WALK_LIMIT}`)).map((c) => [c.sha, c])); const commits = []; for (let sha = head; sha && commits.length < WALK_LIMIT;) { const c = page.get(sha) ?? (await api(`commits/${sha}`)); commits.push({ sha: c.sha, parents: c.parents.map((p) => p.sha), date: c.commit.committer.date }); sha = commits.at(-1).parents[0]; } console.log(`head of main: ${head}; next: ${process.env.NEXT_VERSION || 'none'}`); const selected = await selectNextCommit({ commits, checkRunsAt, nextVersion: process.env.NEXT_VERSION, log: console.log, }); if (!selected.sha) return skip(selected.reason); const problem = selected.sha === head ? null : versionFilesProblem(await versionFilesAt(head), await versionFilesAt(selected.sha)); if (problem) return skip(problem); console.log(`${selected.sha} is the newest commit on main that passed its gate`); output(`sha=${selected.sha}`); } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { await main(); } export { selectNextCommit, versionFilesProblem, WALK_LIMIT };