661 lines
35 KiB
TypeScript
661 lines
35 KiB
TypeScript
// Mock Gitea for tests: the API endpoints Peppa uses plus OAuth token exchange. Repos are
|
|
// local bare git repositories, so clone/push against `clone_url` really works.
|
|
// CI (PEP-57): pull requests, commit statuses, Actions secrets, runner tokens, webhooks
|
|
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
|
|
import { execFileSync } from "node:child_process";
|
|
import { createHmac } from "node:crypto";
|
|
import { mkdirSync, mkdtempSync, renameSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
import { join } from "node:path";
|
|
|
|
/** PEP-191: the fields of Gitea's branch protection Peppa uses. */
|
|
export interface MockProtection {
|
|
rule_name: string;
|
|
enable_push: boolean;
|
|
enable_push_whitelist: boolean;
|
|
push_whitelist_usernames: string[];
|
|
push_whitelist_deploy_keys: boolean;
|
|
enable_merge_whitelist: boolean;
|
|
merge_whitelist_usernames: string[];
|
|
required_approvals: number;
|
|
}
|
|
|
|
interface MockRepo {
|
|
id: number;
|
|
owner: string;
|
|
name: string;
|
|
path: string;
|
|
collaborators: Record<string, string>;
|
|
admins: Set<string>;
|
|
private: boolean;
|
|
pulls: MockPull[];
|
|
statuses: Map<string, Array<{ context: string; status: string; target_url?: string; description?: string }>>;
|
|
secrets: Record<string, string>;
|
|
hooks: Array<{ id: number; url: string; secret: string; events: string[] }>;
|
|
tags: Array<{ name: string; target: string }>;
|
|
issues: MockIssue[];
|
|
/** PEP-191: branch protection rules by branch name (like Gitea's `branch_protections`). */
|
|
protections: Map<string, MockProtection>;
|
|
}
|
|
|
|
/** PEP-46: an issue with its comments (by login). */
|
|
export interface MockIssue {
|
|
number: number;
|
|
title: string;
|
|
body: string;
|
|
state: "open" | "closed";
|
|
author: string;
|
|
comments: Array<{ body: string; author: string }>;
|
|
}
|
|
|
|
export interface MockPull {
|
|
number: number;
|
|
head: string;
|
|
base: string;
|
|
title: string;
|
|
body: string;
|
|
state: "open" | "closed";
|
|
merged: boolean;
|
|
mergeable: boolean;
|
|
/** PEP-278: the commit the merge put on the base branch. */
|
|
mergeSha?: string;
|
|
}
|
|
|
|
export interface MockGiteaUser {
|
|
id: number;
|
|
login: string;
|
|
token: string;
|
|
orgs?: string[];
|
|
}
|
|
|
|
export class MockGitea {
|
|
readonly repos = new Map<string, MockRepo>();
|
|
/** Every request answers 500, like Gitea being down (PEP-127). */
|
|
down = false;
|
|
/** PEP-191: the branch_protections API answers 500 (a failed setup must not break projects). */
|
|
protectionDown = false;
|
|
readonly users = new Map<string, MockGiteaUser>();
|
|
readonly oauthCodes = new Map<string, string>(); // code → token
|
|
readonly runnerTokens: Array<{ scope: string; token: string }> = [];
|
|
/** PEP-4: old `owner/name` → current one, like Gitea's redirects after a transfer. */
|
|
readonly redirects = new Map<string, string>();
|
|
private seq = 1;
|
|
private server: Server | null = null;
|
|
url = "";
|
|
private readonly dir: string;
|
|
|
|
constructor(dir: string) {
|
|
this.dir = dir;
|
|
mkdirSync(dir, { recursive: true });
|
|
}
|
|
|
|
async start(): Promise<this> {
|
|
this.server = createServer((req, res) => {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", () => {
|
|
let r: { status: number; body?: unknown; text?: string };
|
|
try {
|
|
r = this.down ? { status: 500, body: { message: "mock-gitea: down" } } : this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {});
|
|
} catch (e) {
|
|
r = { status: 422, body: { message: `mock-gitea: ${(e as Error).message.split("\n")[0]}` } };
|
|
}
|
|
if (r.text !== undefined) {
|
|
res.writeHead(r.status, { "Content-Type": "text/plain; charset=utf-8" });
|
|
res.end(r.text);
|
|
return;
|
|
}
|
|
res.writeHead(r.status, { "Content-Type": "application/json" });
|
|
res.end(r.body === undefined ? "" : JSON.stringify(r.body));
|
|
});
|
|
});
|
|
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
|
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
|
return this;
|
|
}
|
|
|
|
stop() {
|
|
return new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
|
}
|
|
|
|
private isOrg(name: string) {
|
|
return [...this.users.values()].some((u) => u.orgs?.includes(name));
|
|
}
|
|
|
|
addUser(u: MockGiteaUser) {
|
|
this.users.set(u.token, u);
|
|
return u;
|
|
}
|
|
|
|
/** Creates a bare repo, optionally with an initial commit of `files`. */
|
|
addRepo(owner: string, name: string, opts: { admins?: string[]; files?: Record<string, string>; private?: boolean } = {}): MockRepo {
|
|
const path = join(this.dir, `${owner}-${name}-${this.seq}.git`);
|
|
execFileSync("git", ["init", "-q", "--bare", "-b", "main", path]);
|
|
if (opts.files) {
|
|
const work = `${path}-work`;
|
|
execFileSync("git", ["init", "-q", "-b", "main", work]);
|
|
for (const [f, text] of Object.entries(opts.files)) {
|
|
mkdirSync(join(work, f, ".."), { recursive: true });
|
|
execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text });
|
|
}
|
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm init && git push -q ${JSON.stringify(path)} main`]);
|
|
}
|
|
const repo: MockRepo = {
|
|
id: this.seq++,
|
|
owner,
|
|
name,
|
|
path,
|
|
collaborators: {},
|
|
admins: new Set(opts.admins ?? [owner]),
|
|
pulls: [],
|
|
statuses: new Map(),
|
|
secrets: {},
|
|
hooks: [],
|
|
tags: [],
|
|
issues: [],
|
|
protections: new Map(),
|
|
private: opts.private ?? true,
|
|
};
|
|
this.repos.set(`${owner}/${name}`, repo);
|
|
return repo;
|
|
}
|
|
|
|
/** Files on the default branch of a repo (empty if no commits). */
|
|
files(owner: string, name: string): string[] {
|
|
const r = this.repos.get(`${owner}/${name}`);
|
|
if (!r || this.isEmpty(r)) return [];
|
|
return execFileSync("git", ["--git-dir", r.path, "ls-tree", "-r", "--name-only", "main"], { encoding: "utf8" }).trim().split("\n");
|
|
}
|
|
|
|
show(owner: string, name: string, file: string): string {
|
|
const r = this.repos.get(`${owner}/${name}`)!;
|
|
return execFileSync("git", ["--git-dir", r.path, "show", `main:${file}`], { encoding: "utf8" });
|
|
}
|
|
|
|
repo(owner: string, name: string): MockRepo {
|
|
const r = this.repos.get(`${owner}/${name}`);
|
|
if (!r) throw new Error(`mock-gitea: no repo ${owner}/${name}`);
|
|
return r;
|
|
}
|
|
|
|
/** SHA of a branch (or any rev) in the repo. */
|
|
sha(owner: string, name: string, rev: string): string {
|
|
return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "rev-parse", rev], { encoding: "utf8" }).trim();
|
|
}
|
|
|
|
/** Files on any rev. */
|
|
filesAt(owner: string, name: string, rev: string): string[] {
|
|
return execFileSync("git", ["--git-dir", this.repo(owner, name).path, "ls-tree", "-r", "--name-only", rev], { encoding: "utf8" }).trim().split("\n");
|
|
}
|
|
|
|
/** Pushes `files` as a new commit on `branch` (created from main if missing); returns its SHA. */
|
|
commit(owner: string, name: string, branch: string, files: Record<string, string>, message = "change"): string {
|
|
const r = this.repo(owner, name);
|
|
const work = `${r.path}-c${this.seq++}`;
|
|
execFileSync("git", ["clone", "-q", r.path, work]);
|
|
const has = execFileSync("git", ["-C", work, "ls-remote", "--heads", "origin", branch], { encoding: "utf8" }).trim();
|
|
execFileSync("git", ["-C", work, "checkout", "-q", "-B", branch, ...(has ? [`origin/${branch}`] : [])]);
|
|
for (const [f, text] of Object.entries(files)) {
|
|
mkdirSync(join(work, f, ".."), { recursive: true });
|
|
execFileSync("bash", ["-c", `cat > ${JSON.stringify(join(work, f))}`], { input: text });
|
|
}
|
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git add -A && git -c user.name=t -c user.email=t@t commit -qm ${JSON.stringify(message)} && git push -q origin ${branch}`]);
|
|
return this.sha(owner, name, branch);
|
|
}
|
|
|
|
/** A PR from `head` into main, as an agent would open it. */
|
|
openPull(owner: string, name: string, head: string, title = head, body = ""): MockPull {
|
|
const r = this.repo(owner, name);
|
|
const pr: MockPull = { number: r.pulls.length + 1, head, base: "main", title, body, state: "open", merged: false, mergeable: true };
|
|
r.pulls.push(pr);
|
|
return pr;
|
|
}
|
|
|
|
/** An issue opened by `author` (numbers start at 100: apart from PR numbers). */
|
|
addIssue(owner: string, name: string, title: string, author: string, body = ""): MockIssue {
|
|
const r = this.repo(owner, name);
|
|
const i: MockIssue = { number: 100 + r.issues.length, title, body, state: "open", author, comments: [] };
|
|
r.issues.push(i);
|
|
return i;
|
|
}
|
|
|
|
issueJson(r: MockRepo, i: MockIssue) {
|
|
return { number: i.number, title: i.title, body: i.body, state: i.state, html_url: `${this.url}/${r.owner}/${r.name}/issues/${i.number}`, user: { login: i.author } };
|
|
}
|
|
|
|
/** Records a commit status, like a CI job does. */
|
|
setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) {
|
|
const r = this.repo(owner, name);
|
|
const list = (r.statuses.get(sha) ?? []).filter((s) => s.context !== context);
|
|
list.push({ context, status, ...extra });
|
|
r.statuses.set(sha, list);
|
|
}
|
|
|
|
/** Sends a webhook event to every hook of the repo subscribed to it; returns HTTP statuses. */
|
|
async deliver(owner: string, name: string, event: string, payload: object): Promise<number[]> {
|
|
const r = this.repo(owner, name);
|
|
const out: number[] = [];
|
|
for (const h of r.hooks.filter((h) => h.events.includes(event) || h.events.includes(event.split("_")[0]!))) {
|
|
const body = JSON.stringify(payload);
|
|
const res = await fetch(h.url, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", "X-Gitea-Event": event, "X-Gitea-Signature": createHmac("sha256", h.secret).update(body).digest("hex") },
|
|
body,
|
|
});
|
|
out.push(res.status);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
private tryGit(r: MockRepo, args: string[]): string {
|
|
try {
|
|
return execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
} catch {
|
|
return "";
|
|
}
|
|
}
|
|
|
|
/** `POST /pulls/{n}/update`: the base branch merged into the PR branch; false on a conflict. */
|
|
updateBranch(r: MockRepo, p: MockPull): boolean {
|
|
const work = `${r.path}-u${this.seq++}`;
|
|
execFileSync("git", ["clone", "-q", r.path, work]);
|
|
try {
|
|
execFileSync("bash", ["-c", `cd ${JSON.stringify(work)} && git checkout -q ${p.head} && git -c user.name=t -c user.email=t@t merge -q --no-edit origin/${p.base} && git push -q origin ${p.head}`], { stdio: "ignore" });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
pullJson(r: MockRepo, p: MockPull) {
|
|
let sha = "";
|
|
try {
|
|
sha = this.sha(r.owner, r.name, p.head);
|
|
} catch {}
|
|
return {
|
|
number: p.number,
|
|
state: p.state,
|
|
title: p.title,
|
|
body: p.body,
|
|
html_url: `${this.url}/${r.owner}/${r.name}/pulls/${p.number}`,
|
|
merged: p.merged,
|
|
mergeable: p.mergeable,
|
|
head: { ref: p.head, sha, repo: { full_name: `${r.owner}/${r.name}` } },
|
|
base: { ref: p.base, sha: this.tryGit(r, ["rev-parse", p.base]) },
|
|
merge_base: this.tryGit(r, ["merge-base", p.base, p.head]),
|
|
merge_commit_sha: p.mergeSha ?? null,
|
|
};
|
|
}
|
|
|
|
private combined(r: MockRepo, ref: string) {
|
|
let sha = ref;
|
|
try {
|
|
sha = this.sha(r.owner, r.name, ref);
|
|
} catch {}
|
|
const statuses = r.statuses.get(sha) ?? [];
|
|
const st = statuses.map((s) => s.status);
|
|
const state = !st.length ? "" : st.some((s) => s === "failure" || s === "error") ? "failure" : st.some((s) => s === "pending") ? "pending" : "success";
|
|
return { state, sha, statuses };
|
|
}
|
|
|
|
/** PEP-205: how many times a closed PR was reopened (`owner/repo#n`). */
|
|
reopens = new Map<string, number>();
|
|
|
|
ahead(r: MockRepo, base: string, head: string): number {
|
|
return Number(execFileSync("git", ["--git-dir", r.path, "rev-list", "--count", `${base}..${head}`], { encoding: "utf8" }).trim());
|
|
}
|
|
|
|
private merge(r: MockRepo, p: MockPull) {
|
|
const g = (...a: string[]) => execFileSync("git", ["--git-dir", r.path, ...a], { encoding: "utf8" }).trim();
|
|
const head = g("rev-parse", p.head);
|
|
const base = g("rev-parse", p.base);
|
|
let isAncestor = true;
|
|
try {
|
|
g("merge-base", "--is-ancestor", base, head);
|
|
} catch {
|
|
isAncestor = false;
|
|
}
|
|
const target = isAncestor ? head : g("-c", "user.name=t", "-c", "user.email=t@t", "commit-tree", `${head}^{tree}`, "-p", base, "-p", head, "-m", `Merge pull request #${p.number}`);
|
|
g("update-ref", `refs/heads/${p.base}`, target);
|
|
p.mergeSha = target;
|
|
p.merged = true;
|
|
p.state = "closed";
|
|
}
|
|
|
|
/** PEP-191: may `login` push to / merge into `branch`? (open when there is no rule). */
|
|
mayWrite(r: MockRepo, branch: string, login: string, what: "push" | "merge"): boolean {
|
|
const rule = r.protections.get(branch);
|
|
if (!rule) return true;
|
|
if (what === "push") return !rule.enable_push || (rule.enable_push_whitelist && rule.push_whitelist_usernames.includes(login));
|
|
return rule.enable_merge_whitelist ? rule.merge_whitelist_usernames.includes(login) : true;
|
|
}
|
|
|
|
private isEmpty(r: MockRepo) {
|
|
return execFileSync("git", ["--git-dir", r.path, "for-each-ref"], { encoding: "utf8" }).trim() === "";
|
|
}
|
|
|
|
private json(r: MockRepo, as: MockGiteaUser) {
|
|
return {
|
|
id: r.id,
|
|
name: r.name,
|
|
full_name: `${r.owner}/${r.name}`,
|
|
owner: { login: r.owner },
|
|
empty: this.isEmpty(r),
|
|
private: r.private,
|
|
default_branch: "main",
|
|
clone_url: r.path,
|
|
html_url: `${this.url}/${r.owner}/${r.name}`,
|
|
permissions: { admin: r.admins.has(as.login), push: true, pull: true },
|
|
};
|
|
}
|
|
|
|
private handle(method: string, url: string, auth: string, body: Record<string, unknown>): { status: number; body?: unknown; text?: string } {
|
|
const path = url.split("?")[0]!;
|
|
if (method === "POST" && path === "/login/oauth/access_token") {
|
|
const token = this.oauthCodes.get(String(body.code));
|
|
if (!token) return { status: 400, body: { error: "invalid_grant" } };
|
|
this.oauthCodes.delete(String(body.code));
|
|
return { status: 200, body: { access_token: token, refresh_token: `r-${token}`, expires_in: 3600 } };
|
|
}
|
|
const me = this.users.get(auth.replace(/^token /, ""));
|
|
if (!me) return { status: 401, body: { message: "unauthorized" } };
|
|
let m: RegExpMatchArray | null;
|
|
if (method === "GET" && path === "/api/v1/user") return { status: 200, body: { id: me.id, login: me.login, full_name: me.login, email: `${me.login}@x`, avatar_url: "" } };
|
|
if (method === "GET" && path === "/api/v1/user/orgs") return { status: 200, body: (me.orgs ?? []).map((o, i) => ({ id: 1000 + i, username: o })) };
|
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) {
|
|
if (!this.isOrg(decodeURIComponent(m[2]!))) return { status: 404, body: { message: "org does not exist" } };
|
|
return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } };
|
|
}
|
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/orgs\/([^/]+)$/))) {
|
|
const name = decodeURIComponent(m[1]!);
|
|
return this.isOrg(name) ? { status: 200, body: { id: 2000, username: name } } : { status: 404, body: { message: "org does not exist" } };
|
|
}
|
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators$/))) {
|
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
return { status: 200, body: Object.keys(r.collaborators).map((login, i) => ({ id: 3000 + i, login })) };
|
|
}
|
|
if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)$/))) {
|
|
const want = decodeURIComponent(m[1]!).toLowerCase();
|
|
const u = [...this.users.values()].find((x) => x.login.toLowerCase() === want);
|
|
return u ? { status: 200, body: { id: u.id, login: u.login, full_name: u.login } } : { status: 404, body: { message: "user does not exist" } };
|
|
}
|
|
if (method === "GET" && path === "/api/v1/user/actions/runners/registration-token") {
|
|
const token = `mock-runner-token-${me.login}-${this.seq++}`;
|
|
this.runnerTokens.push({ scope: `user:${me.login}`, token });
|
|
return { status: 200, body: { token } };
|
|
}
|
|
if (method === "POST" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/transfer$/))) {
|
|
// Gitea: repo admin only; unknown namespace → 404; name taken there → 422; the doer may
|
|
// create repos in the target → moved at once (202), otherwise the transfer stays pending (201).
|
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
|
|
const to = String(body.new_owner ?? "");
|
|
const users = [...this.users.values()];
|
|
if (!this.isOrg(to) && !users.some((u) => u.login === to)) return { status: 404, body: { message: "new owner does not exist" } };
|
|
if (this.repos.has(`${to}/${r.name}`)) return { status: 422, body: { message: "The repository with the same name already exists." } };
|
|
if (!(to === me.login || (me.orgs ?? []).includes(to))) return { status: 201, body: this.json(r, me) };
|
|
const old = `${r.owner}/${r.name}`;
|
|
const path2 = join(this.dir, to, `${r.name}.git`);
|
|
mkdirSync(join(this.dir, to), { recursive: true });
|
|
renameSync(r.path, path2);
|
|
this.repos.delete(old);
|
|
Object.assign(r, { owner: to, path: path2, admins: new Set([to, ...users.filter((u) => u.orgs?.includes(to)).map((u) => u.login)]) });
|
|
this.repos.set(`${to}/${r.name}`, r);
|
|
for (const [k, v] of this.redirects) if (v === old) this.redirects.set(k, `${to}/${r.name}`);
|
|
this.redirects.delete(`${to}/${r.name}`);
|
|
this.redirects.set(old, `${to}/${r.name}`);
|
|
return { status: 202, body: this.json(r, me) };
|
|
}
|
|
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/(.+)$/))) {
|
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
const res = this.handleRepo(r, me, method, m[3]!, url, body);
|
|
if (res) return res;
|
|
}
|
|
if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) {
|
|
const full = `${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`;
|
|
// A moved repo answers GET by its old address too (Gitea redirects, fetch follows).
|
|
const r = this.repos.get(full) ?? (method === "GET" ? this.repos.get(this.redirects.get(full) ?? "") : undefined);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
if (method === "DELETE") return this.repos.delete(`${r.owner}/${r.name}`), { status: 204 };
|
|
if (method === "PATCH") {
|
|
// Gitea: only repo admins (owner, org owners, admin collaborators) may edit settings.
|
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "token does not have at least one of required scope(s): [write:repository]" } };
|
|
if (typeof body.private === "boolean") r.private = body.private;
|
|
return { status: 200, body: this.json(r, me) };
|
|
}
|
|
return { status: 200, body: this.json(r, me) };
|
|
}
|
|
if (method === "POST" && (path === "/api/v1/user/repos" || (m = path.match(/^\/api\/v1\/orgs\/([^/]+)\/repos$/)))) {
|
|
const owner = path === "/api/v1/user/repos" ? me.login : decodeURIComponent(m![1]!);
|
|
if (this.repos.has(`${owner}/${body.name}`)) return { status: 409, body: { message: "repository already exists" } };
|
|
return { status: 201, body: this.json(this.addRepo(owner, String(body.name), { admins: [me.login], private: body.private !== false }), me) };
|
|
}
|
|
if (method === "PUT" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) {
|
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
|
|
r.collaborators[decodeURIComponent(m[3]!)] = String(body.permission);
|
|
return { status: 204 };
|
|
}
|
|
if (method === "DELETE" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) {
|
|
const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`);
|
|
if (!r) return { status: 404, body: { message: "not found" } };
|
|
if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } };
|
|
delete r.collaborators[decodeURIComponent(m[3]!)];
|
|
return { status: 204 };
|
|
}
|
|
return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } };
|
|
}
|
|
|
|
private handleRepo(r: MockRepo, me: MockGiteaUser, method: string, sub: string, url: string, body: Record<string, unknown>): { status: number; body?: unknown; text?: string } | null {
|
|
const isAdmin = r.admins.has(me.login);
|
|
const canWrite = isAdmin || r.owner === me.login || r.collaborators[me.login] === "write" || r.collaborators[me.login] === "admin";
|
|
const q = new URLSearchParams(url.split("?")[1] ?? "");
|
|
let m: RegExpMatchArray | null = null;
|
|
if (method === "GET" && sub === "actions/runners/registration-token") {
|
|
if (!isAdmin) return { status: 403, body: { message: "forbidden" } };
|
|
const token = `mock-runner-token-${r.owner}-${r.name}-${this.seq++}`;
|
|
this.runnerTokens.push({ scope: `repo:${r.owner}/${r.name}`, token });
|
|
return { status: 200, body: { token } };
|
|
}
|
|
if (this.protectionDown && /^branch_protections/.test(sub)) return { status: 500, body: { message: "mock-gitea: branch protection down" } };
|
|
if (method === "GET" && (m = sub.match(/^branch_protections\/([^/]+)$/))) {
|
|
if (!isAdmin) return { status: 403, body: { message: "forbidden" } };
|
|
const rule = r.protections.get(decodeURIComponent(m[1]!));
|
|
return rule ? { status: 200, body: rule } : { status: 404, body: { message: "branch protection does not exist" } };
|
|
}
|
|
if ((method === "POST" && sub === "branch_protections") || (method === "PATCH" && (m = sub.match(/^branch_protections\/([^/]+)$/)))) {
|
|
if (!isAdmin) return { status: 403, body: { message: "forbidden" } };
|
|
const name = method === "POST" ? String(body.rule_name ?? body.branch_name) : decodeURIComponent(m![1]!);
|
|
const cur = r.protections.get(name);
|
|
if (method === "POST" && cur) return { status: 403, body: { message: "branch protection already exists" } };
|
|
if (method === "PATCH" && !cur) return { status: 404, body: { message: "branch protection does not exist" } };
|
|
const b = body as Partial<MockProtection>;
|
|
const rule: MockProtection = {
|
|
rule_name: name,
|
|
enable_push: b.enable_push ?? cur?.enable_push ?? false,
|
|
enable_push_whitelist: b.enable_push_whitelist ?? cur?.enable_push_whitelist ?? false,
|
|
push_whitelist_usernames: b.push_whitelist_usernames ?? cur?.push_whitelist_usernames ?? [],
|
|
push_whitelist_deploy_keys: b.push_whitelist_deploy_keys ?? cur?.push_whitelist_deploy_keys ?? false,
|
|
enable_merge_whitelist: b.enable_merge_whitelist ?? cur?.enable_merge_whitelist ?? false,
|
|
merge_whitelist_usernames: b.merge_whitelist_usernames ?? cur?.merge_whitelist_usernames ?? [],
|
|
required_approvals: b.required_approvals ?? cur?.required_approvals ?? 0,
|
|
};
|
|
r.protections.set(name, rule);
|
|
return { status: method === "POST" ? 201 : 200, body: rule };
|
|
}
|
|
if (method === "PUT" && (m = sub.match(/^actions\/secrets\/([^/]+)$/))) {
|
|
if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } };
|
|
r.secrets[decodeURIComponent(m[1]!)] = String(body.data);
|
|
return { status: 201 };
|
|
}
|
|
if (method === "GET" && sub === "hooks") return { status: 200, body: r.hooks.map((h) => ({ id: h.id, type: "gitea", active: true, events: h.events, config: { url: h.url, content_type: "json" } })) };
|
|
if ((method === "POST" && sub === "hooks") || (method === "PATCH" && (m = sub.match(/^hooks\/(\d+)$/)))) {
|
|
if (!isAdmin && r.owner !== me.login) return { status: 403, body: { message: "forbidden" } };
|
|
const cfg = body.config as { url: string; secret: string };
|
|
const events = body.events as string[];
|
|
let h = m ? r.hooks.find((x) => x.id === Number(m![1])) : undefined;
|
|
if (h) Object.assign(h, { url: cfg.url, secret: cfg.secret, events });
|
|
else r.hooks.push((h = { id: this.seq++, url: cfg.url, secret: cfg.secret, events }));
|
|
return { status: m ? 200 : 201, body: { id: h.id, type: "gitea", active: true, events, config: { url: h.url, content_type: "json" } } };
|
|
}
|
|
if (method === "POST" && sub === "pulls") {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
return { status: 201, body: this.pullJson(r, this.openPull(r.owner, r.name, String(body.head), String(body.title), String(body.body ?? ""))) };
|
|
}
|
|
if (method === "GET" && sub === "pulls") {
|
|
const state = q.get("state") ?? "open";
|
|
return { status: 200, body: r.pulls.filter((p) => state === "all" || p.state === state).map((p) => this.pullJson(r, p)) };
|
|
}
|
|
if (method === "GET" && (m = sub.match(/^pulls\/(\d+)\.diff$/))) {
|
|
const p = r.pulls.find((x) => x.number === Number(m![1]));
|
|
if (!p) return { status: 404, body: { message: "pull not found" } };
|
|
return { status: 200, text: execFileSync("git", ["--git-dir", r.path, "diff", `${p.base}...${p.head}`], { encoding: "utf8" }) };
|
|
}
|
|
if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge|\/update)?$/))) {
|
|
const p = r.pulls.find((x) => x.number === Number(m![1]));
|
|
if (!p) return { status: 404, body: { message: "pull not found" } };
|
|
if (method === "GET" && !m[2]) return { status: 200, body: this.pullJson(r, p) };
|
|
if (method === "PATCH" && !m[2]) {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
if (body.state === "open" && p.state === "closed") this.reopens.set(`${r.owner}/${r.name}#${p.number}`, (this.reopens.get(`${r.owner}/${r.name}#${p.number}`) ?? 0) + 1);
|
|
if (body.state === "closed" || body.state === "open") p.state = body.state;
|
|
return { status: 201, body: this.pullJson(r, p) };
|
|
}
|
|
if (method === "GET" && m[2] === "/files") {
|
|
const out = execFileSync("git", ["--git-dir", r.path, "diff", "--name-only", `${p.base}...${p.head}`], { encoding: "utf8" }).trim();
|
|
return { status: 200, body: out ? out.split("\n").map((filename) => ({ filename })) : [] };
|
|
}
|
|
if (method === "POST" && m[2] === "/update") {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
if (!p.mergeable || !this.updateBranch(r, p)) return { status: 409, body: { message: "merge conflict" } };
|
|
return { status: 200 };
|
|
}
|
|
if (method === "POST" && m[2] === "/merge") {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
if (!this.mayWrite(r, p.base, me.login, "merge")) return { status: 403, body: { message: "user not allowed to merge PR" } };
|
|
if (p.merged) return { status: 405, body: { message: "already merged" } };
|
|
if (!p.mergeable) return { status: 405, body: { message: "Please try again later: merge conflict" } };
|
|
if (body.head_commit_id && body.head_commit_id !== this.sha(r.owner, r.name, p.head)) return { status: 409, body: { message: "head out of date" } };
|
|
// Like Gitea: a PR with nothing to merge (head already in base) is refused.
|
|
if (this.ahead(r, p.base, p.head) === 0) return { status: 405, body: { message: "Please try again later" } };
|
|
this.merge(r, p);
|
|
return { status: 200 };
|
|
}
|
|
}
|
|
if (method === "POST" && (m = sub.match(/^statuses\/([0-9a-f]+)$/))) {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
this.setStatus(r.owner, r.name, m[1]!, String(body.context), String(body.state), { target_url: body.target_url as string, description: body.description as string });
|
|
return { status: 201, body: {} };
|
|
}
|
|
if (method === "GET" && (m = sub.match(/^compare\/(.+)\.\.\.(.+)$/))) {
|
|
// Like Gitea 1.22: branch names only — a commit SHA is "not found".
|
|
const [base, head] = [decodeURIComponent(m[1]!), decodeURIComponent(m[2]!)];
|
|
if ([base, head].some((x) => /^[0-9a-f]{40}$/.test(x))) return { status: 404, body: { message: "The target couldn't be found." } };
|
|
const n = this.ahead(r, base, head);
|
|
return { status: 200, body: { total_commits: n, commits: [], files: [] } };
|
|
}
|
|
if (method === "GET" && (m = sub.match(/^commits\/([^/]+)\/status$/))) return { status: 200, body: this.combined(r, decodeURIComponent(m[1]!)) };
|
|
if (method === "GET" && sub === "branches") {
|
|
const out = execFileSync("git", ["--git-dir", r.path, "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(authorname)%09%(committerdate:iso-strict)%09%(contents:subject)", "refs/heads"], { encoding: "utf8" }).trim();
|
|
return {
|
|
status: 200,
|
|
body: out ? out.split("\n").map((l) => {
|
|
const [name, id, author, timestamp, message] = l.split("\t");
|
|
return { name, commit: { id, message, timestamp, author: { name: author } } };
|
|
}) : [],
|
|
};
|
|
}
|
|
if (method === "GET" && sub === "commits") {
|
|
const ref = q.get("sha") ?? "main";
|
|
let out = "";
|
|
try {
|
|
out = execFileSync("git", ["--git-dir", r.path, "log", `-${Number(q.get("limit") ?? 30)}`, "--format=%H%x09%an%x09%aI%x09%s", ref], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
} catch {
|
|
return { status: 404, body: { message: "ref not found" } };
|
|
}
|
|
return {
|
|
status: 200,
|
|
body: out ? out.split("\n").map((l) => {
|
|
const [sha, name, date, message] = l.split("\t");
|
|
return { sha, html_url: `${this.url}/${r.owner}/${r.name}/commit/${sha}`, commit: { message, author: { name, date } }, author: null };
|
|
}) : [],
|
|
};
|
|
}
|
|
if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) {
|
|
try {
|
|
const spec = `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`;
|
|
const text = execFileSync("git", ["--git-dir", r.path, "show", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
const sha = execFileSync("git", ["--git-dir", r.path, "rev-parse", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64", sha } };
|
|
} catch {
|
|
return { status: 404, body: { message: "not found" } };
|
|
}
|
|
}
|
|
if ((method === "POST" || method === "PUT") && (m = sub.match(/^contents\/(.+)$/))) {
|
|
// Gitea's create (POST, file must not exist) / update (PUT, `sha` = current blob) — one commit on `branch`.
|
|
const path = decodeURIComponent(m[1]!);
|
|
const branch = String(body.branch ?? "main");
|
|
if (!this.mayWrite(r, branch, me.login, "push")) return { status: 403, body: { message: `Branch protected: ${branch}` } };
|
|
const git = (args: string[], env?: NodeJS.ProcessEnv, input?: string) =>
|
|
execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", input, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "ignore"] }).trim();
|
|
let parent: string | null = null;
|
|
try {
|
|
parent = git(["rev-parse", `refs/heads/${branch}`]);
|
|
} catch {}
|
|
let current: string | null = null;
|
|
try {
|
|
current = parent ? git(["rev-parse", `${parent}:${path}`]) : null;
|
|
} catch {}
|
|
if (method === "POST" && current) return { status: 422, body: { message: "repository file already exists" } };
|
|
if (method === "PUT" && current !== body.sha) return { status: 409, body: { message: `sha does not match [given: ${body.sha}, expected: ${current}]` } };
|
|
const blob = git(["hash-object", "-w", "--stdin"], undefined, Buffer.from(String(body.content), "base64").toString("utf8"));
|
|
const index = join(mkdtempSync(join(tmpdir(), "mock-gitea-idx-")), "index");
|
|
const author = (body.author ?? {}) as { name?: string; email?: string };
|
|
const env = { GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: String(author.name ?? me.login), GIT_AUTHOR_EMAIL: String(author.email ?? "mock@example.invalid"), GIT_COMMITTER_NAME: me.login, GIT_COMMITTER_EMAIL: "mock@example.invalid" };
|
|
if (parent) git(["read-tree", parent], env);
|
|
git(["update-index", "--add", "--cacheinfo", `100644,${blob},${path}`], env);
|
|
const tree = git(["write-tree"], env);
|
|
const commit = git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", String(body.message ?? "update")], env);
|
|
git(["update-ref", `refs/heads/${branch}`, commit]);
|
|
return { status: method === "POST" ? 201 : 200, body: { content: { sha: blob, path }, commit: { sha: commit, html_url: `${this.url}/${r.owner}/${r.name}/commit/${commit}` } } };
|
|
}
|
|
if (method === "GET" && sub === "issues") {
|
|
const page = Number(q.get("page") ?? 1);
|
|
const limit = Number(q.get("limit") ?? 30);
|
|
const list = r.issues.filter((i) => (q.get("state") ?? "open") === "all" || i.state === (q.get("state") ?? "open"));
|
|
return { status: 200, body: list.slice((page - 1) * limit, page * limit).map((i) => this.issueJson(r, i)) };
|
|
}
|
|
if ((m = sub.match(/^issues\/(\d+)(\/comments)?$/))) {
|
|
const n = Number(m[1]);
|
|
const i = r.issues.find((x) => x.number === n);
|
|
const isPull = r.pulls.some((p) => p.number === n);
|
|
if (!i && !isPull) return { status: 404, body: { message: "issue not found" } };
|
|
if (method === "POST" && m[2]) {
|
|
const c = { body: String(body.body), author: me.login };
|
|
if (i) i.comments.push(c);
|
|
return { status: 201, body: { id: this.seq++, body: c.body, user: { login: me.login } } };
|
|
}
|
|
if (method === "PATCH" && !m[2] && i) {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
if (body.state === "closed" || body.state === "open") i.state = body.state;
|
|
return { status: 201, body: this.issueJson(r, i) };
|
|
}
|
|
if (method === "GET" && !m[2] && i) return { status: 200, body: this.issueJson(r, i) };
|
|
}
|
|
if (method === "POST" && sub === "tags") {
|
|
if (!canWrite) return { status: 403, body: { message: "forbidden" } };
|
|
const target = this.sha(r.owner, r.name, String(body.target));
|
|
execFileSync("git", ["--git-dir", r.path, "tag", String(body.tag_name), target]);
|
|
r.tags.push({ name: String(body.tag_name), target });
|
|
return { status: 201, body: { name: body.tag_name, commit: { sha: target } } };
|
|
}
|
|
return null;
|
|
}
|
|
}
|