peppa/packages/runner/src/platform-build.ts
peppa-bot df565fa515
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 36с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1658с
peppa-ci / ci (pull_request) Successful in 29m48s
PEP-319: в сообщении о версии — только задачи, чьи коммиты в неё вошли
Список задач версии собирался из всего текста коммитов между версиями: задача, названная в
описании чужого коммита, попадала в сообщение канала как выпущенная (27.11.2026 — дважды).
Теперь считается только ключ в начале заголовка коммита или названия слитого PR.

Тест: коммит с упоминанием другой задачи в тексте и «Merge branch» — в списке только задачи версии;
до правки падали оба теста.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 16:56:28 +05:00

111 lines
5.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// New builds of FORGE (PEP-60). The watchdog checks the commit it runs about once a minute; a
// commit that differs from the last announced one and belongs to `main` is a release: posted to
// the platform channel with the stories its commits belong to (`storiesIn`).
//
// PEP-292: the platform runs from a Docker image without `.git` (PEP-230), so `git` is not called
// there. The commit is what the deploy built the image from (`PEPPA_COMMIT`, the full SHA behind
// `$PEPPA_HOME/platform.tag`); "is it on main" and the stories of the release come from the
// history of the main branch in Gitea. `git rev-parse` is used only next to a real `.git` (a
// working copy on the Mac).
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { announcePlatformBuild, getPlatformBuild, giteaForBot, headCommit, peppaVersion, platformProjectKey } from "@peppa/core";
import type { GiteaCommit } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
const PAGE = 50;
const PAGES = 4;
const RETRY_MS = 10 * 60_000;
/** The commit this platform runs: the deploy's build-arg, else HEAD of a real checkout; null when unknown. */
export function deployedCommit(root: string, env = process.env.PEPPA_COMMIT): string | null {
const c = env?.trim();
if (c && c !== "unknown") return c;
return existsSync(join(root, ".git")) ? headCommit(root) : null;
}
/**
* Platform stories of a release, sorted by number: the keys a commit's subject starts with —
* «PEP-318: …», «PEP-284, PEP-285: …» — or the title of the pull request in Gitea's merge commit
* («Merge pull request 'PEP-318: …' (#302) …»). PEP-319: a story only mentioned in the text of a
* commit («… отложенное по PEP-127», «PEP-318: вместе с PEP-317», «Merge branch 'main' into
* task/pep-314») is not released by it — on 27.11.2026 the channel twice named stories that had
* shipped earlier.
*/
export function storiesIn(messages: string[], key = platformProjectKey()): string[] {
const one = `${key}-(\\d+)`;
const lead = new RegExp(`^\\s*(?:Merge pull request ['"«])?\\s*(${key}-\\d+(?:\\s*(?:,|\\+|&|и|and)\\s*${key}-\\d+)*)(?=\\s*:|\\s|['"»]|$)`, "i");
const nums = new Set<number>();
for (const msg of messages) {
const head = (msg.split("\n", 1)[0] ?? "").match(lead)?.[1];
if (head) for (const m of head.matchAll(new RegExp(one, "gi"))) nums.add(Number(m[1]));
}
return [...nums].sort((a, b) => a - b).map((n) => `${key}-${n}`);
}
const same = (a: string, b: string) => a.length >= 7 && b.length >= 7 && (a.startsWith(b) || b.startsWith(a));
/**
* Where `commit` sits on main in Gitea: its full SHA and the commits from it down to `prev`
* (exclusive; the whole window when `prev` is older). null — not on main within the window.
*/
export async function mainHistory(commit: string, prev: string | null): Promise<{ sha: string; between: GiteaCommit[] } | null> {
const [owner, repo] = loadEnv().GITEA_PLATFORM_REPO.split("/") as [string, string];
const branch = process.env.PEPPA_MAIN_BRANCH || "main";
const gitea = giteaForBot();
const window: GiteaCommit[] = [];
let at = -1;
for (let page = 1; page <= PAGES; page++) {
const list = await gitea.listCommits(owner, repo, branch, PAGE, page);
window.push(...list);
if (at < 0) at = window.findIndex((c) => same(c.sha, commit));
if (at >= 0 && (!prev || window.slice(at).some((c) => same(c.sha, prev)))) break;
if (list.length < PAGE) break;
}
if (at < 0) return null;
const rest = window.slice(at);
const end = prev ? rest.findIndex((c) => same(c.sha, prev)) : -1;
return { sha: window[at]!.sha, between: end >= 0 ? rest.slice(0, end) : rest };
}
let lastCheck = 0;
/** Commit → when it may be asked about again (not on main, or Gitea failed). */
const skipUntil = new Map<string, number>();
/** Watchdog: announces a new build of FORGE once (first run only remembers it). */
export async function platformBuildTick(
db: Db,
o: { root?: string; commit?: string; now?: Date; force?: boolean; log?: (m: string) => void } = {},
): Promise<boolean> {
const nowMs = (o.now ?? new Date()).getTime();
if (!o.force && Math.abs(nowMs - lastCheck) < 60_000) return false;
lastCheck = nowMs;
const root = o.root ?? process.env.PEPPA_ROOT ?? ROOT;
const commit = o.commit ?? deployedCommit(root);
if (!commit) return false;
const prev = await getPlatformBuild(db);
if (prev && same(prev.commit, commit)) return false;
if (!o.force && (skipUntil.get(commit) ?? 0) > nowMs) return false;
let history: Awaited<ReturnType<typeof mainHistory>>;
try {
history = await mainHistory(commit, prev?.commit ?? null);
} catch (e) {
skipUntil.set(commit, nowMs + RETRY_MS);
o.log?.(`platform build ${commit.slice(0, 7)}: Gitea history unavailable (${(e as Error).message}), retry later`);
return false;
}
if (!history) {
skipUntil.set(commit, nowMs + RETRY_MS);
return false;
}
skipUntil.delete(commit);
const tasks = prev ? storiesIn(history.between.map((c) => c.commit.message)) : [];
const posted = await announcePlatformBuild(db, { version: peppaVersion(root), commit: history.sha, tasks }, { now: o.now });
o.log?.(`platform build ${history.sha.slice(0, 7)}${tasks.length ? ` (${tasks.join(", ")})` : ""}${posted ? " → channel" : ""}`);
return posted;
}