143 lines
7.3 KiB
TypeScript
143 lines
7.3 KiB
TypeScript
// PEP-57: CI for factory projects — runner registration, Actions secret, "connect CI" PR,
|
|
// and the template's check step (.gitea/peppa-check.sh) against mock Gitea.
|
|
import assert from "node:assert/strict";
|
|
import { execFile, execFileSync } from "node:child_process";
|
|
import { existsSync, mkdirSync, 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 { core, db, runner, teardown } from "./helpers.ts";
|
|
import { CHECK_NAMES } from "@peppa/shared";
|
|
import { MockGitea } from "../src/mock-gitea.ts";
|
|
|
|
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
|
const TMP = mkdtempSync(join(tmpdir(), "peppa-ci-"));
|
|
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
|
|
|
const gitea = new MockGitea(join(TMP, "gitea"));
|
|
const BOT = { id: 61, login: "peppa-bot", token: "mock-token-bot" };
|
|
const OWNER = { id: 62, login: "mock-dana", token: "mock-token-dana" };
|
|
let templateUrl = "";
|
|
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
let seq = 0;
|
|
|
|
before(async () => {
|
|
await gitea.start();
|
|
process.env.GITEA_URL = gitea.url;
|
|
process.env.GITEA_TOKEN = BOT.token;
|
|
gitea.addUser(BOT);
|
|
gitea.addUser(OWNER);
|
|
const tpl = gitea.addRepo("peppa-bot", "template");
|
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
|
|
templateUrl = tpl.path;
|
|
owner = await core.upsertUserFromGitea(db, OWNER, { access_token: OWNER.token });
|
|
});
|
|
after(async () => {
|
|
await gitea.stop();
|
|
await teardown();
|
|
});
|
|
|
|
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; token: string }) : [];
|
|
};
|
|
|
|
/** A project whose repo (with an initial commit) lives in mock Gitea under `ns`. */
|
|
async function ciProject(ns: string, files: Record<string, string> = {}) {
|
|
const key = `CI${String.fromCharCode(65 + seq++)}`;
|
|
const slug = key.toLowerCase();
|
|
gitea.addRepo(ns, slug, {
|
|
admins: [ns],
|
|
files: { "README.md": "# x\n", ".peppa/project.json": JSON.stringify({ slug, key, name: key, peppaUrl: "http://peppa.test" }), ...files },
|
|
});
|
|
if (ns !== BOT.login) gitea.repo(ns, slug).collaborators[BOT.login] = "write";
|
|
const p = await core.createProject(db, { slug, key, name: key, giteaOwner: ns, workspacePath: join(TMP, "ws", slug), ownerId: ns === BOT.login ? null : owner.id });
|
|
return p;
|
|
}
|
|
|
|
describe("CI: connect a project", () => {
|
|
test("peppa-bot's repo: covered by the bot runner, secret set, PR with the workflow and empty checks", async () => {
|
|
const p = await ciProject(BOT.login);
|
|
const before = registrations().length;
|
|
const r = await runner.connectCi(db, p, { templateUrl });
|
|
assert.equal(r.runner, "bot");
|
|
assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos");
|
|
const repo = gitea.repo(BOT.login, p.giteaRepo);
|
|
assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
|
|
assert.ok(r.prUrl?.endsWith("/pulls/1"));
|
|
const pr = repo.pulls[0]!;
|
|
assert.equal(pr.head, runner.CI_BRANCH);
|
|
const files = gitea.filesAt(BOT.login, p.giteaRepo, pr.head);
|
|
for (const f of runner.CI_FILES) assert.ok(files.includes(f), f);
|
|
const pj = JSON.parse(execFileSync("git", ["--git-dir", repo.path, "show", `${pr.head}:.peppa/project.json`], { encoding: "utf8" }));
|
|
assert.deepEqual(pj.checks, {});
|
|
assert.equal(pj.key, p.key, "the project's own fields are kept");
|
|
|
|
// Running again re-uses the open PR; after the merge there is nothing to connect.
|
|
assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, r.prUrl);
|
|
await core.giteaForBot().mergePullRequest(BOT.login, p.giteaRepo, 1);
|
|
assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, null);
|
|
});
|
|
|
|
test("repo in the owner's namespace: per-repo runner registered with the owner's token", async () => {
|
|
const p = await ciProject(OWNER.login);
|
|
const r = await runner.connectCi(db, p, { templateUrl });
|
|
assert.equal(r.runner, "repo");
|
|
const reg = registrations().at(-1)!;
|
|
assert.equal(reg.name, `repo-${OWNER.login}--${p.giteaRepo}`);
|
|
assert.ok(gitea.runnerTokens.some((t) => t.token === reg.token && t.scope === `repo:${OWNER.login}/${p.giteaRepo}`));
|
|
assert.equal(gitea.repo(OWNER.login, p.giteaRepo).secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
|
|
});
|
|
|
|
test("template workflow: trusted runner, no fork PRs, every check as its own step", () => {
|
|
const wf = readFileSync(join(ROOT, "template/.gitea/workflows/ci.yml"), "utf8");
|
|
assert.match(wf, /runs-on: peppa-trusted/);
|
|
assert.match(wf, /head\.repo\.full_name == github\.repository/);
|
|
for (const c of ["install", ...CHECK_NAMES]) assert.match(wf, new RegExp(`peppa-check\\.sh ${c}\\b`));
|
|
});
|
|
});
|
|
|
|
describe("CI: check step (.gitea/peppa-check.sh)", () => {
|
|
const script = join(ROOT, "template/.gitea/peppa-check.sh");
|
|
function workdir(checks: Record<string, string>) {
|
|
const d = mkdtempSync(join(TMP, "job-"));
|
|
mkdirSync(join(d, ".peppa"));
|
|
writeFileSync(join(d, ".peppa/project.json"), JSON.stringify({ slug: "x", key: "X", name: "x", peppaUrl: "", checks }));
|
|
return d;
|
|
}
|
|
// Async: the script talks to mock Gitea, which runs in this process.
|
|
const step = (cwd: string, check: string, env: Record<string, string> = {}) =>
|
|
new Promise<{ status: number; stdout: string }>((done) => {
|
|
execFile("bash", [script, check], { cwd, encoding: "utf8", env: { ...process.env, GITHUB_ACTIONS: "", ...env } }, (err, stdout) =>
|
|
done({ status: err ? Number((err as { code?: number }).code ?? 1) : 0, stdout }),
|
|
);
|
|
});
|
|
|
|
test("locally: runs the command, keeps its exit code; a missing command is skipped", async () => {
|
|
const d = workdir({ test: "echo testing; exit 3", lint: "echo fine" });
|
|
const t = await step(d, "test");
|
|
assert.equal(t.status, 3);
|
|
assert.match(t.stdout, /testing/);
|
|
assert.equal((await step(d, "lint")).status, 0);
|
|
const b = await step(d, "build");
|
|
assert.equal(b.status, 0);
|
|
assert.match(b.stdout, /не настроена/);
|
|
});
|
|
|
|
test("in CI: writes the commit status peppa/<check> to Gitea", async () => {
|
|
const p = await ciProject(BOT.login);
|
|
const sha = gitea.sha(BOT.login, p.giteaRepo, "main");
|
|
const d = workdir({ test: "exit 1", build: "true" });
|
|
const env = { GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${BOT.login}/${p.giteaRepo}`, GITHUB_RUN_NUMBER: "7", PEPPA_SHA: sha, GITEA_TOKEN: BOT.token };
|
|
assert.equal((await step(d, "test", env)).status, 1);
|
|
assert.equal((await step(d, "build", env)).status, 0);
|
|
const st = await core.giteaForBot().combinedStatus(BOT.login, p.giteaRepo, sha);
|
|
assert.equal(st.state, "failure");
|
|
const byCtx = Object.fromEntries(st.statuses!.map((s) => [s.context, s]));
|
|
assert.equal(byCtx["peppa/test"]?.status, "failure");
|
|
assert.equal(byCtx["peppa/build"]?.status, "success");
|
|
assert.equal(byCtx["peppa/test"]?.target_url, `/${BOT.login}/${p.giteaRepo}/actions/runs/7`);
|
|
});
|
|
});
|