// PEP-242: the project template reaches Gitea by itself (deploy + watchdog check), and existing // projects get only the missing secrets block in their deploy script. Tests are named after the // scenarios of openspec/changes/pep-242-template-sync/specs/project-template. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { cpSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import { like } from "drizzle-orm"; import { telegramOutbox } from "@peppa/db"; import { stripAsIs } from "@peppa/shared/i18n"; import { core, db, runner, superadmin, teardown } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-tpl-sync-")); process.env.PEPPA_SECRET = "mock-secret-for-tests"; process.env.PEPPA_WORKSPACES = join(TMP, "workspaces"); const gitea = new MockGitea(join(TMP, "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-tpl-bot" }; const TEMPLATE = readFileSync(join(ROOT, "template/.gitea/peppa-deploy.sh"), "utf8"); let tplRepo = ""; /** A copy of template/ the tests edit (the real one stays as it is). */ const DIR = join(TMP, "template"); before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); tplRepo = gitea.addRepo("peppa-bot", "template", { files: { "RULES.md": "# old rules\n" } }).path; cpSync(join(ROOT, "template"), DIR, { recursive: true }); await superadmin(); }); after(async () => { await gitea.stop(); await teardown(); }); const alerts = async (prefix: string) => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => stripAsIs(String(r.params.text))); const show = (...args: string[]) => execFileSync("git", ["--git-dir", tplRepo, "show", ...args], { encoding: "utf8" }); describe("Шаблон проектов уходит в Gitea с выкаткой", () => { test("Сценарий: Выкатка с изменённым шаблоном", async () => { const deploy = readFileSync(join(ROOT, "scripts/platform-deploy.sh"), "utf8"); execFileSync("bash", ["-n", join(ROOT, "scripts/platform-deploy.sh")]); const push = deploy.indexOf("push_template ||"); assert.match(deploy, /push_template\(\) \{ docker exec peppa-watchdog peppa template push --alert; \}/); assert.ok(push > deploy.indexOf('echo "$SHORT" >"$PREV_FILE"'), "the template goes after the deploy is checked and recorded"); assert.ok(push < deploy.indexOf('say "ГОТОВО')); assert.doesNotMatch(deploy.slice(push, deploy.indexOf("\n", push)), /die|rollback/, "a failed push does not roll the deploy back"); const r = await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo, commit: "abcdef1234" }); assert.equal(r.state, "pushed"); assert.match(show("main", "--format=%s", "--no-patch"), /^Update Peppa template \(abcdef1\)/); assert.equal(show("main:RULES.md"), readFileSync(join(ROOT, "template/RULES.md"), "utf8")); assert.equal(show("main:.gitea/peppa-deploy.sh"), TEMPLATE); }); test("Сценарий: Шаблон не изменился", async () => { const head = show("main", "--format=%H", "--no-patch"); assert.equal((await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo })).state, "unchanged"); assert.equal(show("main", "--format=%H", "--no-patch"), head); }); test("Сценарий: Gitea недоступна при отправке", async () => { const r = await runner.pushTemplateOrAlert(db, { dir: DIR, templateUrl: join(TMP, "no-such-repo.git") }); assert.equal(r, null); const sent = await alerts("template:push:"); assert.equal(sent.length, 1); assert.match(sent[0]!, /Шаблон проектов не отправлен в Gitea/); }); }); describe("Сверка шаблона в вачдоге", () => { test("Сценарий: Шаблон совпадает", async () => { process.env.PEPPA_TEMPLATE_SYNC = "on"; try { const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T10:00:00Z") }); assert.equal(r?.state, "unchanged"); assert.equal((await alerts("template:drift:")).length, 0); } finally { process.env.PEPPA_TEMPLATE_SYNC = "off"; } }); test("Сценарий: Шаблон отстаёт", async () => { process.env.PEPPA_TEMPLATE_SYNC = "on"; try { writeFileSync(join(DIR, "RULES.md"), `${readFileSync(join(DIR, "RULES.md"), "utf8")}\n## Новое правило\n`); const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:00:00Z") }); assert.equal(r?.state, "behind"); assert.deepEqual(r?.changed, ["RULES.md"]); // An hour later — the same commit, no second message; within the hour — not even checked. assert.equal(await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:30:00Z") }), null); assert.equal((await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T13:01:00Z") }))?.state, "behind"); const sent = await alerts("template:drift:"); assert.equal(sent.length, 1); assert.match(sent[0]!, /Шаблон проектов в Gitea отстаёт.*RULES\.md/); // The check never pushes by itself. assert.doesNotMatch(show("main:RULES.md"), /Новое правило/); } finally { process.env.PEPPA_TEMPLATE_SYNC = "off"; } }); }); /** The template's deploy script as it was before PEP-112: no block, no override, no call — plus a project's own line. */ function oldProjectScript(): string { const lines = TEMPLATE.split("\n"); const start = lines.findIndex((l) => l.startsWith("# PEP-112: секреты проекта из ")); const end = lines.findIndex((l, i) => i > start && l === "}"); lines.splice(start, end - start + 2); const out = lines .filter((l) => l !== "project_secrets" && !l.includes('local files=(-f "$compose")') && !l.includes('files+=(-f "$override")')) .map((l) => l.replace('docker compose -p "$project" "${files[@]}" "$@"', 'docker compose -p "$project" -f "$compose" "$@"')); out.splice(out.indexOf("report deploying"), 0, 'echo "custom step"'); return out.join("\n"); } describe("Блок секретов без затирания доработок", () => { test("Сценарий: Скрипт проекта с доработками", async () => { const old = oldProjectScript(); assert.doesNotMatch(old, /project_secrets|override/); const r = runner.addSecretsBlock(old, TEMPLATE); assert.equal(r.state, "added"); if (r.state !== "added") return; // Every old line stays, in order; the added ones are the block, the call and the override in dc. const next = r.script.split("\n"); let at = 0; for (const l of old.split("\n")) { const found = next.indexOf(l.replace('-f "$compose" "$@"', '-f "$compose" ${override:+-f "$override"} "$@"'), at); assert.ok(found >= at, `line kept: ${l}`); at = found + 1; } assert.match(r.script, /^project_secrets\(\) \{/m); assert.match(r.script, /^report deploying\nproject_secrets\n/m); assert.match(r.script, /echo "custom step"/); execFileSync("bash", ["-n"], { input: r.script }); // The override word disappears when there are no secrets and becomes `-f ` with them. const args = (override: string) => execFileSync("bash", ["-c", `compose=c.yml override=${JSON.stringify(override)}; printf '[%s]' -f "$compose" \${override:+-f "$override"}`], { encoding: "utf8" }); assert.equal(args(""), "[-f][c.yml]"); assert.equal(args("/tmp/p env"), "[-f][c.yml][-f][/tmp/p env]"); }); test("Сценарий: Блок уже есть", () => { assert.deepEqual(runner.addSecretsBlock(TEMPLATE, TEMPLATE), { state: "present" }); }); test("Сценарий: Скрипт без функции dc", () => { const r = runner.addSecretsBlock(oldProjectScript().replace("dc() {", "compose_run() {"), TEMPLATE); assert.equal(r.state, "unsupported"); const trap = runner.addSecretsBlock(`trap 'rm -f x' EXIT\n${oldProjectScript()}`, TEMPLATE); assert.equal(trap.state, "unsupported", "the project's own EXIT trap would be replaced"); }); test("ci connect --secrets-only: PR только с блоком, остальные файлы не тронуты", async () => { const old = oldProjectScript(); gitea.addRepo(BOT.login, "tplsec", { admins: [BOT.login], files: { "README.md": "# x\n", ".gitea/peppa-deploy.sh": old, ".peppa/project.json": JSON.stringify({ slug: "tplsec", key: "TPS", name: "TPS", peppaUrl: "http://peppa.test" }) }, }); const p = await core.createProject(db, { slug: "tplsec", key: "TPS", name: "TPS", giteaOwner: BOT.login, workspacePath: join(TMP, "ws", "tplsec"), ownerId: null }); const r = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true }); assert.equal(r.secrets, "added"); assert.ok(r.prUrl?.endsWith("/pulls/1")); const repo = gitea.repo(BOT.login, "tplsec"); assert.equal(repo.pulls[0]!.head, runner.SECRETS_BRANCH); const git = (...a: string[]) => execFileSync("git", ["--git-dir", repo.path, ...a], { encoding: "utf8" }); assert.equal(git("diff", "--name-only", "main", runner.SECRETS_BRANCH).trim(), ".gitea/peppa-deploy.sh"); const script = git("show", `${runner.SECRETS_BRANCH}:.gitea/peppa-deploy.sh`); assert.match(script, /echo "custom step"/); assert.match(script, /^project_secrets$/m); assert.equal(repo.secrets.PEPPA_CI_SECRET, undefined, "secrets-only does not touch CI setup"); // Merged — the block is there, nothing more to add. await core.giteaForBot().mergePullRequest(BOT.login, "tplsec", 1); const again = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true }); assert.deepEqual([again.secrets, again.prUrl], ["present", null]); }); });