// CI for factory projects (PEP-57): Gitea Actions on Peppa's act_runner (label // `peppa-trusted`, docker.sock of the host). The runner is registered only for project repos: // once for peppa-bot's own repos (scripts/ci-runner-register.sh) and per repo for projects in // someone else's namespace. Workflow files come from the shared template. import { m } from "@peppa/shared/i18n"; import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { giteaForBot, PeppaError, projectHookSecret, type GiteaClient, type Project } from "@peppa/core"; import type { Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { repoAdmins } from "./share.ts"; import { git, run, templateRepoUrl } from "./git.ts"; /** Files of the CI contract, copied from the template into project repos. */ export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"]; /** Starting points copied only when the project has none yet (the project owns them after). */ export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"]; export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; /** Events the project webhook gets: PRs and pushes (PEP-57), issues, comments, reviews (PEP-46). */ export const GITEA_HOOK_EVENTS = ["pull_request", "push", "issues", "issue_comment", "pull_request_comment", "pull_request_review"]; /** Where Gitea webhooks and CI reports reach Peppa. */ export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`; const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot"; /** * Registers an act_runner for one scope. Default: `docker exec` into the peppa-act-runner * container (infra/act-runner); PEPPA_CI_REGISTER_BIN replaces it (tests: a mock script). * The token goes through the environment, never the command line. */ export async function registerCiRunner(name: string, token: string): Promise { const env = { ...process.env, PEPPA_RUNNER_TOKEN: token }; const bin = process.env.PEPPA_CI_REGISTER_BIN; if (bin) await run(bin, [name], { env }); else await run("docker", ["exec", "-e", "PEPPA_RUNNER_TOKEN", process.env.PEPPA_CI_RUNNER_CONTAINER ?? "peppa-act-runner", "peppa-runner-register", name], { env }); } /** Runs `fn` with the first repo admin client that succeeds. */ async function asAdmin(clients: GiteaClient[], what: string, fn: (c: GiteaClient) => Promise): Promise { let last: unknown; for (const c of clients) { try { return await fn(c); } catch (e) { last = e; } } throw new PeppaError(`${what}: ${(last as Error | undefined)?.message ?? m("нет доступа к коду проекта")}`); } export interface CiSetup { /** "bot" — covered by the runner of peppa-bot's repos; "repo" — registered for this repo. */ runner: "bot" | "repo"; } /** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */ export async function setupCi(db: Db, project: Project): Promise { const clients = await repoAdmins(db, project); if (!clients.length) throw new PeppaError(m("Нет доступа к коду проекта")); let runner: CiSetup["runner"] = "bot"; if (project.giteaOwner !== botLogin()) { const token = await asAdmin(clients, m("Подключение проверок"), (c) => c.runnerRegistrationToken(project.giteaOwner, project.giteaRepo)); await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token); runner = "repo"; } const secret = projectHookSecret(project.id); await asAdmin(clients, m("Секрет {name}", { name: CI_SECRET_NAME }), (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret)); // PR and push events (preview stands, merges) — signed with the same secret. await asAdmin(clients, m("Вебхук"), (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, GITEA_HOOK_EVENTS)); return { runner }; } export interface ConnectCiResult extends CiSetup { /** PR with the workflow files; null when the default branch already has them. */ prUrl: string | null; } /** * "Connect CI" for an existing project: runner + secret, then a PR from Peppa that adds the * workflow files from the template and an empty `checks` in .peppa/project.json. */ export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void } = {}): Promise { const log = o.log ?? (() => {}); log("runner + secret"); const setup = await setupCi(db, project); const bot = giteaForBot(); const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo); if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${project.giteaOwner}/${project.giteaRepo}` })); const base = project.defaultBranch; const work = mkdtempSync(join(tmpdir(), "peppa-ci-")); try { log("clone"); const dest = join(work, "repo"); const tpl = join(work, "tpl"); await git(work, "clone", "-q", repo.clone_url, dest); await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl); await git(dest, "checkout", "-q", "-B", CI_BRANCH, `origin/${base}`); for (const f of [...CI_FILES, ...CD_SCAFFOLD.filter((f) => !existsSync(join(dest, f)))]) { mkdirSync(dirname(join(dest, f)), { recursive: true }); cpSync(join(tpl, f), join(dest, f)); } const pf = join(dest, ".peppa/project.json"); const data = existsSync(pf) ? (JSON.parse(readFileSync(pf, "utf8")) as Record) : { slug: project.slug, key: project.key, name: project.name, peppaUrl: loadEnv().PEPPA_WEB_URL }; if (!data.checks) { data.checks = {}; mkdirSync(dirname(pf), { recursive: true }); writeFileSync(pf, `${JSON.stringify(data, null, 2)}\n`); } await git(dest, "add", "-A"); const { stdout: staged } = await git(dest, "diff", "--cached", "--name-only"); if (!staged.trim()) return { ...setup, prUrl: null }; log("push"); await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", "Подключить CI Peppa FACTORY (Gitea Actions)"); await git(dest, "push", "-q", "-f", "origin", `HEAD:refs/heads/${CI_BRANCH}`); const open = await bot.openPullForBranch(project.giteaOwner, project.giteaRepo, CI_BRANCH); const pr = open ?? (await bot.createPullRequest(project.giteaOwner, project.giteaRepo, { head: CI_BRANCH, base, title: "Подключить CI Peppa FACTORY", body: [ "PR от Peppa FACTORY (PEP-57): проверки на каждый PR через Gitea Actions.", "", `- ${CI_FILES.map((f) => `\`${f}\``).join(", ")} — из шаблона, под стек не меняются;`, "- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.", "- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.", "", "Заполнить `checks` — первая стори агента в проекте. Изменение конвейера требует ревью PM.", ].join("\n"), })); return { ...setup, prUrl: pr.html_url }; } finally { rmSync(work, { recursive: true, force: true }); } }