223 lines
12 KiB
TypeScript
223 lines
12 KiB
TypeScript
// 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 { ensureBranchProtection } from "./branch-protection.ts";
|
||
import { repoAdmins } from "./share.ts";
|
||
import { git, run, templateRepoUrl } from "./git.ts";
|
||
import { addSecretsBlock } from "./template-sync.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";
|
||
/** PEP-242: branch of the «only the secrets block» PR. */
|
||
export const SECRETS_BRANCH = "peppa/secrets";
|
||
const DEPLOY_SCRIPT = ".gitea/peppa-deploy.sh";
|
||
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<void> {
|
||
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<T>(clients: GiteaClient[], what: string, fn: (c: GiteaClient) => Promise<T>): Promise<T> {
|
||
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";
|
||
}
|
||
|
||
/**
|
||
* The act_runner registration that covers the project's repo (idempotent): peppa-bot's repos —
|
||
* the user-level runner `peppa-bot` (as scripts/ci-runner-register.sh), others — `repo-<owner>--<repo>`.
|
||
* PEP-248: also called when a job of the repo waits while the executor takes other repos' jobs.
|
||
*/
|
||
export async function ensureCiRunner(db: Db, project: Project, clients?: GiteaClient[]): Promise<CiSetup["runner"]> {
|
||
if (project.giteaOwner === botLogin()) {
|
||
await registerCiRunner(botLogin(), await giteaForBot().runnerRegistrationToken());
|
||
return "bot";
|
||
}
|
||
const admins = clients ?? (await repoAdmins(db, project));
|
||
if (!admins.length) throw new PeppaError(m("Нет доступа к коду проекта"));
|
||
const token = await asAdmin(admins, m("Подключение проверок"), (c) => c.runnerRegistrationToken(project.giteaOwner, project.giteaRepo));
|
||
await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token);
|
||
return "repo";
|
||
}
|
||
|
||
/** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */
|
||
export async function setupCi(db: Db, project: Project): Promise<CiSetup> {
|
||
const clients = await repoAdmins(db, project);
|
||
if (!clients.length) throw new PeppaError(m("Нет доступа к коду проекта"));
|
||
let runner: CiSetup["runner"] = "bot";
|
||
if (project.giteaOwner !== botLogin()) runner = await ensureCiRunner(db, project, clients);
|
||
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;
|
||
/** PEP-242, secretsOnly: what happened to the project's deploy script. */
|
||
secrets?: "added" | "replaced" | "present";
|
||
}
|
||
|
||
/**
|
||
* "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; secretsOnly?: boolean } = {}): Promise<ConnectCiResult> {
|
||
const log = o.log ?? (() => {});
|
||
if (o.secretsOnly) return connectSecretsBlock(project, o);
|
||
log("runner + secret");
|
||
const setup = await setupCi(db, project);
|
||
// PEP-191: the same command also puts the default branch protection back.
|
||
log("protect branch");
|
||
await ensureBranchProtection(db, project, { log });
|
||
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<string, unknown>) : { 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 FORGE (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 FORGE",
|
||
body: [
|
||
"PR от FORGE (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 });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* PEP-242: `peppa ci connect <KEY> --secrets-only` — the project's deploy script gets only the
|
||
* missing secrets block (addSecretsBlock), its own changes stay. A script equal to an older template
|
||
* (or none) is not needed here: the plain `ci connect` replaces it whole. No runner, Actions secret or
|
||
* webhook changes — those are already in place for a deploying project.
|
||
*/
|
||
async function connectSecretsBlock(project: Project, o: { templateUrl?: string; log?: (s: string) => void }): Promise<ConnectCiResult> {
|
||
const log = o.log ?? (() => {});
|
||
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", SECRETS_BRANCH, `origin/${base}`);
|
||
const file = join(dest, DEPLOY_SCRIPT);
|
||
const template = readFileSync(join(tpl, DEPLOY_SCRIPT), "utf8");
|
||
let secrets: "added" | "replaced";
|
||
if (!existsSync(file)) {
|
||
mkdirSync(dirname(file), { recursive: true });
|
||
writeFileSync(file, template, { mode: 0o755 });
|
||
secrets = "replaced";
|
||
} else {
|
||
const r = addSecretsBlock(readFileSync(file, "utf8"), template);
|
||
if (r.state === "present") return { runner: "bot", prUrl: null, secrets: "present" };
|
||
// glossary-ignore: отказ читает администратор платформы в CLI
|
||
if (r.state === "unsupported") throw new PeppaError(m("Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.", { key: project.key, reason: r.reason }));
|
||
writeFileSync(file, r.script);
|
||
secrets = "added";
|
||
}
|
||
await git(dest, "add", "-A");
|
||
log("push");
|
||
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", "Секреты проекта в выкладке (PEP-112)");
|
||
await git(dest, "push", "-q", "-f", "origin", `HEAD:refs/heads/${SECRETS_BRANCH}`);
|
||
const open = await bot.openPullForBranch(project.giteaOwner, project.giteaRepo, SECRETS_BRANCH);
|
||
const pr =
|
||
open ??
|
||
(await bot.createPullRequest(project.giteaOwner, project.giteaRepo, {
|
||
head: SECRETS_BRANCH,
|
||
base,
|
||
title: "Секреты проекта в выкладке",
|
||
body: [
|
||
"PR от Peppa FACTORY (PEP-242): скрипт выкладки берёт секреты проекта у Peppa FACTORY («⋯ Настройки проекта → Секреты») и передаёт их сервису как переменные окружения (PEP-112).",
|
||
"",
|
||
`В \`${DEPLOY_SCRIPT}\` добавлен только блок секретов: функция \`project_secrets\`, её файл в \`docker compose\` внутри \`dc()\` и вызов после \`report deploying\`. Остальные строки скрипта не менялись.`,
|
||
].join("\n"),
|
||
}));
|
||
return { runner: "bot", prUrl: pr.html_url, secrets };
|
||
} finally {
|
||
rmSync(work, { recursive: true, force: true });
|
||
}
|
||
}
|