peppa/packages/core/src/gitea.ts

307 lines
12 KiB
TypeScript

// 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;
}
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 };
}
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 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<T>(method: string, path: string, body?: unknown): Promise<T> {
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<GiteaUser>("GET", "/user");
}
/** Orgs where the user may create repositories. */
async orgsWithRepoCreate(login: string): Promise<GiteaOrg[]> {
const orgs = await this.request<GiteaOrg[]>("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<GiteaRepo | null> {
try {
return await this.request<GiteaRepo>("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<GiteaRepo>("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<GiteaRepo>("PATCH", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { private: isPrivate });
}
/** True if `name` is an organization (false for a user account). */
async isOrg(name: string): Promise<boolean> {
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<GiteaUser[]>("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators?limit=50`);
}
addCollaborator(owner: string, repo: string, login: string, permission: "read" | "write" | "admin") {
return this.request<void>("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission });
}
removeCollaborator(owner: string, repo: string, login: string) {
return this.request<void>("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`);
}
/** A Gitea account by login (null if there is none). */
async getUserByLogin(login: string): Promise<GiteaUser | null> {
try {
return await this.request<GiteaUser>("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<GiteaPull>("POST", `${this.repoPath(owner, repo)}/pulls`, pr);
}
getPullRequest(owner: string, repo: string, n: number) {
return this.request<GiteaPull>("GET", `${this.repoPath(owner, repo)}/pulls/${n}`);
}
/** Open pull requests, newest first. */
listOpenPulls(owner: string, repo: string) {
return this.request<GiteaPull[]>("GET", `${this.repoPath(owner, repo)}/pulls?state=open&sort=recentupdate&limit=50`);
}
async openPullForBranch(owner: string, repo: string, branch: string): Promise<GiteaPull | null> {
const pulls = await this.listOpenPulls(owner, repo);
return pulls.find((p) => p.head.ref === branch) ?? null;
}
listBranches(owner: string, repo: string) {
return this.request<GiteaBranch[]>("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<GiteaCommit[]>("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<string[]> {
const files = await this.request<Array<{ filename: string }>>("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<string> {
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<void>("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true });
}
combinedStatus(owner: string, repo: string, ref: string) {
return this.request<GiteaCombinedStatus>("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<string | null> {
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;
}
}
setActionsSecret(owner: string, repo: string, name: string, data: string) {
return this.request<void>("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<string> {
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<GiteaHook[]>("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<GiteaHook> {
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<GiteaHook>("PATCH", `${this.repoPath(owner, repo)}/hooks/${existing.id}`, body);
return this.request<GiteaHook>("POST", `${this.repoPath(owner, repo)}/hooks`, body);
}
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<void>("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
}
}
async function oauthToken(baseUrl: string, body: Record<string, string>): Promise<OAuthTokens> {
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" });
}