// PEP-4: `peppa project transfer ` — the project's repo moves to another Gitea // namespace and the project keeps working there (address, origin, CI runner, secret, webhook). // Tests are named after the scenarios of openspec/specs/project-provisioning. import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { after, before, describe, test } from "node:test"; import { eq } from "drizzle-orm"; import { events, projects } from "@peppa/db"; import { core, db, runner, teardown } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); const TMP = mkdtempSync(join(tmpdir(), "peppa-transfer-")); process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(TMP, "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-transfer-bot", orgs: ["mock-acme"] }; const ORG = "mock-acme"; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); }); after(async () => { await gitea.stop(); await teardown(); }); /** A project with a repo in peppa-bot's namespace and a cloned working copy. */ async function project(slug: string, key: string) { const repo = gitea.addRepo(BOT.login, slug, { files: { "README.md": `# ${slug}\n` } }); const ws = join(TMP, "ws", slug); execFileSync("git", ["clone", "-q", repo.path, ws]); return core.createProject(db, { slug, key, name: key, giteaOwner: BOT.login, workspacePath: ws, ownerId: null }); } async function cli(...a: string[]) { try { const r = await promisify(execFile)(join(ROOT, "packages/cli/bin/peppa"), ["project", "transfer", ...a], { encoding: "utf8", env: process.env }); return { code: 0, out: r.stdout + r.stderr }; } catch (e) { const x = e as { code?: number; stdout?: string; stderr?: string }; return { code: x.code ?? 1, out: `${x.stdout ?? ""}${x.stderr ?? ""}` }; } } const origin = (ws: string) => execFileSync("git", ["-C", ws, "remote", "get-url", "origin"], { encoding: "utf8" }).trim(); const reload = async (id: number) => (await db.select().from(projects).where(eq(projects.id, id)))[0]!; const registrations = () => { const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl"); return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string }) : []; }; describe("project transfer (PEP-4)", () => { let demoId = 0; test("Перенос в организацию", async () => { const p = await project("mock-demo", "MTDEMO"); demoId = p.id; const r = await cli("MTDEMO", ORG); assert.equal(r.code, 0, r.out); assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo\n/); assert.ok(gitea.repos.has(`${ORG}/mock-demo`)); assert.ok(!gitea.repos.has("peppa-bot/mock-demo")); const now = await reload(p.id); assert.equal(now.giteaOwner, ORG); const repo = await runner.describeRepo(db, now, { fresh: true }); assert.equal(repo.fullName, `${ORG}/mock-demo`); // what the project page links to assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`), origin(p.workspacePath)); execFileSync("git", ["-C", p.workspacePath, "fetch", "-q", "origin"]); const ev = (await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred"); assert.equal(ev.length, 1); assert.deepEqual(ev[0]!.payload, { from: "peppa-bot/mock-demo", to: `${ORG}/mock-demo` }); }); test("CI после переноса", async () => { // The bot-level runner no longer covers the repo: it gets its own, plus the report secret and the webhook. const repo = gitea.repo(ORG, "mock-demo"); assert.ok(registrations().some((x) => x.name === `repo-${ORG}--mock-demo`), JSON.stringify(registrations())); assert.equal(repo.secrets[runner.CI_SECRET_NAME], core.projectHookSecret(demoId)); assert.equal(repo.hooks.length, 1); assert.equal(repo.hooks[0]!.url, runner.giteaHookUrl()); assert.deepEqual(repo.hooks[0]!.events, runner.GITEA_HOOK_EVENTS); }); test("Повторный запуск", async () => { // Peppa's side lost: the repo is already in the org, the project and origin still point to the old place. const p = await reload(demoId); await db.update(projects).set({ giteaOwner: BOT.login }).where(eq(projects.id, demoId)); execFileSync("git", ["-C", p.workspacePath, "remote", "set-url", "origin", join(TMP, "gone", "peppa-bot", "mock-demo.git")]); const id = gitea.repo(ORG, "mock-demo").id; const r = await cli("MTDEMO", ORG); assert.equal(r.code, 0, r.out); assert.match(r.out, /MTDEMO: peppa-bot\/mock-demo → mock-acme\/mock-demo \(репозиторий уже там\)/); assert.equal(gitea.repo(ORG, "mock-demo").id, id); assert.equal((await reload(demoId)).giteaOwner, ORG); assert.ok(origin(p.workspacePath).endsWith(`/${ORG}/mock-demo.git`)); // …and once more, with nothing left to fix. const again = await cli("MTDEMO", ORG); assert.equal(again.code, 0, again.out); }); test("Пространства нет или нет прав", async () => { const p = await project("mock-stay", "MTSTAY"); const before = origin(p.workspacePath); const r = await cli("MTSTAY", "mock-nope"); assert.equal(r.code, 1, r.out); assert.match(r.out, /Пространство mock-nope не найдено или у peppa-bot нет прав создавать в нём репозитории/); assert.ok(gitea.repos.has("peppa-bot/mock-stay")); assert.equal((await reload(p.id)).giteaOwner, BOT.login); assert.equal(origin(p.workspacePath), before); }); test("В пространстве уже есть такой репозиторий", async () => { const p = await project("mock-twin", "MTTWIN"); gitea.addRepo(ORG, "mock-twin", { files: { "README.md": "# other\n" } }); const r = await cli("MTTWIN", ORG); assert.equal(r.code, 1, r.out); assert.match(r.out, /Репозиторий mock-acme\/mock-twin уже существует/); assert.ok(gitea.repos.has("peppa-bot/mock-twin")); assert.equal((await reload(p.id)).giteaOwner, BOT.login); assert.equal((await db.select().from(events).where(eq(events.projectId, p.id))).filter((e) => e.type === "repo_transferred").length, 0); }); test("mock-gitea: перенос без права создавать в пространстве остаётся ожидающим", async () => { gitea.addUser({ id: 72, login: "mock-other", token: "mock-token-transfer-other" }); gitea.addRepo(BOT.login, "mock-pending", { files: { "README.md": "# x\n" } }); const bot = core.giteaForBot(); await bot.transferRepo(BOT.login, "mock-pending", "mock-other"); assert.ok(gitea.repos.has("peppa-bot/mock-pending")); assert.equal(await bot.getRepo("mock-other", "mock-pending"), null); await assert.rejects(bot.transferRepo(BOT.login, "mock-pending", "mock-nobody"), /404/); }); });