// Gitea API client: as a user (OAuth token) or as peppa-bot (GITEA_TOKEN). import { PeppaError } from "./errors.ts"; export interface GiteaUser { id: number; login: string; full_name?: string; email?: string; avatar_url?: string; is_admin?: boolean; } export interface GiteaOrg { id: number; username: string; full_name?: string; } export interface GiteaRepo { id: number; name: string; full_name: string; owner: { login: string }; empty: boolean; private: boolean; default_branch: string; clone_url: string; html_url: string; permissions?: { admin: boolean; push: boolean; pull: boolean }; } export interface GiteaPull { number: number; state: "open" | "closed"; title: string; body?: string; html_url: string; merged: boolean; mergeable: boolean; head: { ref: string; sha: string; repo?: { full_name: string } | null }; base: { ref: string; sha?: string }; /** Common ancestor of the head and the base branch; ≠ base.sha — the branch is behind the base. */ merge_base?: string; } export interface GiteaBranch { name: string; commit: { id: string; message: string; timestamp: string; author?: { name: string } }; } export interface GiteaCommit { sha: string; html_url: string; commit: { message: string; author: { name: string; date: string } }; author?: { login: string } | null; } export interface GiteaCommitStatus { context: string; status: "pending" | "success" | "error" | "failure" | "warning"; target_url?: string; description?: string; updated_at?: string; } export interface GiteaCombinedStatus { state: "" | "pending" | "success" | "error" | "failure" | "warning"; sha: string; statuses: GiteaCommitStatus[] | null; } export interface GiteaIssue { number: number; title: string; body?: string; state: "open" | "closed"; html_url: string; user?: { login: string }; pull_request?: unknown; } export interface GiteaBranchProtection { rule_name?: string; branch_name?: string; enable_push: boolean; enable_push_whitelist: boolean; push_whitelist_usernames: string[] | null; push_whitelist_deploy_keys?: boolean; enable_merge_whitelist: boolean; merge_whitelist_usernames: string[] | null; } export interface GiteaHook { id: number; type: string; active: boolean; events: string[]; config: { url: string; content_type: string }; } export interface OAuthTokens { access_token: string; refresh_token?: string; expires_in?: number; } export class GiteaError extends PeppaError { readonly status: number; constructor(status: number, message: string) { super(message); this.status = status; } } export class GiteaClient { readonly baseUrl: string; private readonly token: string; constructor(baseUrl: string, token: string) { this.baseUrl = baseUrl; this.token = token; } async request(method: string, path: string, body?: unknown): Promise { const res = await fetch(`${this.baseUrl}/api/v1${path}`, { method, headers: { Authorization: `token ${this.token}`, "Content-Type": "application/json", Accept: "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000), }); if (res.status === 204) return undefined as T; const text = await res.text(); if (!res.ok) { let msg = text; try { msg = (JSON.parse(text) as { message?: string }).message ?? text; } catch {} throw new GiteaError(res.status, `Gitea ${method} ${path}: ${res.status} ${msg}`.slice(0, 400)); } return (text ? JSON.parse(text) : undefined) as T; } me() { return this.request("GET", "/user"); } /** Orgs where the user may create repositories. */ async orgsWithRepoCreate(login: string): Promise { const orgs = await this.request("GET", "/user/orgs?limit=50"); const out: GiteaOrg[] = []; for (const o of orgs) { const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(o.username)}/permissions`).catch(() => null); if (p?.can_create_repository) out.push(o); } return out; } async getRepo(owner: string, name: string): Promise { try { return await this.request("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`); } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } /** Creates a repo (private unless `isPrivate` is false); `asUser` = in the token owner's own namespace. */ createRepo(owner: string, asUser: boolean, name: string, description: string, isPrivate = true) { const body = { name, description, private: isPrivate, default_branch: "main", auto_init: false }; return this.request("POST", asUser ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, body); } /** Changes repo visibility (needs admin rights on the repo). */ setRepoPrivate(owner: string, name: string, isPrivate: boolean) { return this.request("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate }); } /** * Moves a repo to another namespace (PEP-4). Gitea moves it at once only when the token owner * may create repos there; otherwise the transfer stays pending — check where the repo is after. */ transferRepo(owner: string, name: string, newOwner: string) { return this.request("POST", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/transfer`, { new_owner: newOwner }); } /** True if the token owner `login` may create repos in `namespace` (own account or an org with that right). */ async canCreateIn(login: string, namespace: string): Promise { if (namespace.toLowerCase() === login.toLowerCase()) return true; try { const p = await this.request<{ can_create_repository: boolean }>("GET", `/users/${encodeURIComponent(login)}/orgs/${encodeURIComponent(namespace)}/permissions`); return !!p?.can_create_repository; } catch (e) { if (e instanceof GiteaError && (e.status === 404 || e.status === 403)) return false; throw e; } } /** True if `name` is an organization (false for a user account). */ async isOrg(name: string): Promise { try { await this.request("GET", `/orgs/${encodeURIComponent(name)}`); return true; } catch (e) { if (e instanceof GiteaError && e.status === 404) return false; throw e; } } listCollaborators(owner: string, repo: string) { return this.request("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators?limit=50`); } addCollaborator(owner: string, repo: string, login: string, permission: "read" | "write" | "admin") { return this.request("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission }); } removeCollaborator(owner: string, repo: string, login: string) { return this.request("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`); } /** A Gitea account by login (null if there is none). */ async getUserByLogin(login: string): Promise { try { return await this.request("GET", `/users/${encodeURIComponent(login)}`); } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } private repoPath(owner: string, repo: string) { return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`; } createPullRequest(owner: string, repo: string, pr: { head: string; base: string; title: string; body?: string }) { return this.request("POST", `${this.repoPath(owner, repo)}/pulls`, pr); } getPullRequest(owner: string, repo: string, n: number) { return this.request("GET", `${this.repoPath(owner, repo)}/pulls/${n}`); } /** Open pull requests, newest first. */ listOpenPulls(owner: string, repo: string) { return this.request("GET", `${this.repoPath(owner, repo)}/pulls?state=open&sort=recentupdate&limit=50`); } async openPullForBranch(owner: string, repo: string, branch: string): Promise { const pulls = await this.listOpenPulls(owner, repo); return pulls.find((p) => p.head.ref === branch) ?? null; } /** * PEP-209: the newest PR of a branch in any state — a merged one too (`openPullForBranch` sees * only open ones). A story whose `pr_url` was never saved is found by its branch `task/`. */ async pullForBranch(owner: string, repo: string, branch: string | RegExp): Promise { const pulls = await this.request("GET", `${this.repoPath(owner, repo)}/pulls?state=all&sort=recentupdate&limit=50`); const mine = pulls.filter((p) => (typeof branch === "string" ? p.head.ref === branch : branch.test(p.head.ref))); return mine.find((p) => p.state === "open") ?? mine.find((p) => p.merged) ?? mine[0] ?? null; } listBranches(owner: string, repo: string) { return this.request("GET", `${this.repoPath(owner, repo)}/branches?limit=50`); } /** Latest commits of `ref` (no diffs, no stats). */ listCommits(owner: string, repo: string, ref: string, limit = 10) { return this.request("GET", `${this.repoPath(owner, repo)}/commits?sha=${encodeURIComponent(ref)}&limit=${limit}&stat=false&verification=false&files=false`); } /** README of `ref` (README.md, then other common names); null if there is none. */ async readme(owner: string, repo: string, ref: string): Promise<{ path: string; text: string } | null> { for (const path of ["README.md", "readme.md", "README", "README.txt"]) { const text = await this.fileText(owner, repo, path, ref); if (text !== null) return { path, text }; } return null; } /** Paths changed by a pull request. */ async pullFiles(owner: string, repo: string, n: number): Promise { const files = await this.request>("GET", `${this.repoPath(owner, repo)}/pulls/${n}/files?limit=100`); return files.map((f) => f.filename); } /** Unified diff of a pull request (text, not JSON). */ async pullDiff(owner: string, repo: string, n: number): Promise { const path = `${this.repoPath(owner, repo)}/pulls/${n}.diff`; const res = await fetch(`${this.baseUrl}/api/v1${path}`, { headers: { Authorization: `token ${this.token}` }, signal: AbortSignal.timeout(30_000) }); const text = await res.text(); if (!res.ok) throw new GiteaError(res.status, `Gitea GET ${path}: ${res.status} ${text}`.slice(0, 400)); return text; } /** Merges a PR; `sha` guards against merging a head that changed since the checks. */ mergePullRequest(owner: string, repo: string, n: number, sha?: string) { return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true }); } /** Commits `head` has that `base` hasn't (0: nothing to merge — already in base). */ async commitsAhead(owner: string, repo: string, base: string, head: string): Promise { const r = await this.request<{ total_commits?: number; commits?: unknown[] }>("GET", `${this.repoPath(owner, repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`); return r.total_commits ?? r.commits?.length ?? 0; } /** PEP-127: brings the base branch into the PR branch (a merge commit by the token's user); fails on a conflict. */ updatePullBranch(owner: string, repo: string, n: number) { return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/update?style=merge`); } closePullRequest(owner: string, repo: string, n: number) { return this.request("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "closed" }); } /** PEP-205: reopens a closed PR — Gitea starts the pull_request workflows again (the way to re-run a job that fell before the checks). */ reopenPullRequest(owner: string, repo: string, n: number) { return this.request("PATCH", `${this.repoPath(owner, repo)}/pulls/${n}`, { state: "open" }); } combinedStatus(owner: string, repo: string, ref: string) { return this.request("GET", `${this.repoPath(owner, repo)}/commits/${encodeURIComponent(ref)}/status`); } /** A file at `ref` as text (null if absent). */ async fileText(owner: string, repo: string, path: string, ref: string): Promise { try { const f = await this.request<{ content: string }>("GET", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`); return Buffer.from(f.content, "base64").toString("utf8"); } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } /** A file at `ref` with its blob sha (for an update), or null if absent. */ async fileWithSha(owner: string, repo: string, path: string, ref: string): Promise<{ text: string; sha: string } | null> { try { const f = await this.request<{ content: string; sha: string }>("GET", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`); return { text: Buffer.from(f.content, "base64").toString("utf8"), sha: f.sha }; } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } /** Creates (no `sha`) or updates (with the current blob `sha`) a file with one commit on `branch`. */ writeFile(owner: string, repo: string, path: string, o: { text: string; branch: string; message: string; sha?: string; author?: { name: string; email: string } }) { const body = { content: Buffer.from(o.text, "utf8").toString("base64"), branch: o.branch, message: o.message, ...(o.sha ? { sha: o.sha } : {}), ...(o.author ? { author: o.author, committer: o.author } : {}) }; return this.request<{ commit: { sha: string; html_url: string } }>(o.sha ? "PUT" : "POST", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, body); } /** PEP-191: the protection rule of `branch`, null when there is none. */ async getBranchProtection(owner: string, repo: string, branch: string): Promise { try { return await this.request("GET", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`); } catch (e) { if (e instanceof GiteaError && e.status === 404) return null; throw e; } } /** * PEP-191: only `users` push to and merge into `branch` (deploy keys do not push; no approvals * required — Peppa merges after green checks). Creates the rule or updates the existing one. */ async protectBranch(owner: string, repo: string, branch: string, o: { users: string[] }): Promise { const body = { rule_name: branch, enable_push: true, enable_push_whitelist: true, push_whitelist_usernames: o.users, push_whitelist_deploy_keys: false, enable_merge_whitelist: true, merge_whitelist_usernames: o.users, required_approvals: 0, }; if (await this.getBranchProtection(owner, repo, branch)) return this.request("PATCH", `${this.repoPath(owner, repo)}/branch_protections/${encodeURIComponent(branch)}`, body); return this.request("POST", `${this.repoPath(owner, repo)}/branch_protections`, body); } setActionsSecret(owner: string, repo: string, name: string, data: string) { return this.request("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data }); } /** act_runner registration token: for one repo, or (no args) for the token owner's repos. */ async runnerRegistrationToken(owner?: string, repo?: string): Promise { const path = owner && repo ? `${this.repoPath(owner, repo)}/actions/runners/registration-token` : "/user/actions/runners/registration-token"; return (await this.request<{ token: string }>("GET", path)).token; } listHooks(owner: string, repo: string) { return this.request("GET", `${this.repoPath(owner, repo)}/hooks`); } /** Creates the webhook for `url`, or updates the existing one (secret, events). */ async upsertHook(owner: string, repo: string, url: string, secret: string, events: string[]): Promise { const body = { type: "gitea", active: true, events, branch_filter: "*", config: { url, content_type: "json", secret } }; const existing = (await this.listHooks(owner, repo)).find((h) => h.config.url === url); if (existing) return this.request("PATCH", `${this.repoPath(owner, repo)}/hooks/${existing.id}`, body); return this.request("POST", `${this.repoPath(owner, repo)}/hooks`, body); } /** Open issues (not pull requests), oldest first. */ async listOpenIssues(owner: string, repo: string): Promise { const out: GiteaIssue[] = []; for (let page = 1; page <= 10; page++) { const batch = await this.request("GET", `${this.repoPath(owner, repo)}/issues?state=open&type=issues&limit=50&page=${page}`); out.push(...batch.filter((i) => !i.pull_request)); if (batch.length < 50) break; } return out.sort((a, b) => a.number - b.number); } commentIssue(owner: string, repo: string, n: number, body: string) { return this.request<{ id: number }>("POST", `${this.repoPath(owner, repo)}/issues/${n}/comments`, { body }); } closeIssue(owner: string, repo: string, n: number) { return this.request("PATCH", `${this.repoPath(owner, repo)}/issues/${n}`, { state: "closed" }); } createTag(owner: string, repo: string, tag: string, target: string, message?: string) { return this.request<{ name: string }>("POST", `${this.repoPath(owner, repo)}/tags`, { tag_name: tag, target, message }); } deleteRepo(owner: string, repo: string) { return this.request("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`); } } async function oauthToken(baseUrl: string, body: Record): Promise { const res = await fetch(`${baseUrl}/login/oauth/access_token`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000), }); const data = (await res.json().catch(() => ({}))) as OAuthTokens & { error?: string; error_description?: string }; if (!res.ok || !data.access_token) throw new GiteaError(res.status, `OAuth: ${data.error_description ?? data.error ?? res.status}`); return data; } export function oauthAuthorizeUrl(baseUrl: string, clientId: string, redirectUri: string, state: string): string { const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: "code", state }); return `${baseUrl}/login/oauth/authorize?${q}`; } export function exchangeOAuthCode(baseUrl: string, clientId: string, clientSecret: string, code: string, redirectUri: string) { return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, code, grant_type: "authorization_code", redirect_uri: redirectUri }); } export function refreshOAuthToken(baseUrl: string, clientId: string, clientSecret: string, refreshToken: string) { return oauthToken(baseUrl, { client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" }); }