Files
labuh/src/gitlab.ts

344 lines
18 KiB
TypeScript

// GitLab access through the `glab` CLI, so Labuh never handles the token itself in M0.
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { lstatSync, unlinkSync } from 'node:fs';
import path from 'node:path';
import type { ReleaseChanges } from './store.ts';
const run = promisify(execFile);
export async function api<T = any>(path: string): Promise<T> {
const { stdout } = await run('glab', ['api', path], { maxBuffer: 64 * 1024 * 1024 });
return JSON.parse(stdout);
}
export async function apiAll<T = any>(path: string): Promise<T[]> {
const out: T[] = [];
for (let page = 1; page <= 20; page++) {
const sep = path.includes('?') ? '&' : '?';
const batch = await api<T[]>(`${path}${sep}per_page=100&page=${page}`);
out.push(...batch);
if (batch.length < 100) break;
}
return out;
}
export type MrRef = { host: string; projectPath: string; iid: number };
export function parseMrUrl(url: string): MrRef {
const m = url.match(/^https:\/\/([^/]+)\/(.+?)\/-\/merge_requests\/(\d+)/);
if (!m) throw new Error(`Not a merge request URL: ${url}`);
if (m[1] !== 'gitlab.com') throw new Error('M0 supports gitlab.com only');
return { host: m[1], projectPath: m[2], iid: Number(m[3]) };
}
export type MrInfo = {
projectId: number;
projectPath: string;
webUrl: string;
sshUrl: string;
httpUrl: string;
iid: number;
title: string;
description: string;
author: string;
sourceBranch: string;
targetBranch: string;
sha: string;
state: string;
labels: string[];
pipeline: { id: number; status: string; webUrl: string } | null;
pipelineIds: number[];
commits: Array<{ sha: string; title: string; branches: string[] }>;
diffs: Array<{ old_path: string; new_path: string; diff: string; new_file: boolean; deleted_file: boolean; renamed_file: boolean }>;
};
// `sha` replays the MR as it was at an earlier push (an MR version), for golden-set runs.
// GitLab Free keeps no history of the description, and teams often rewrite it after a review
// with the very findings being tested, so a replay drops the description entirely.
export async function loadMr(ref: MrRef, sha?: string): Promise<MrInfo> {
const pid = encodeURIComponent(ref.projectPath);
const [project, mr] = await Promise.all([api(`projects/${pid}`), api(`projects/${pid}/merge_requests/${ref.iid}`)]);
let diffs: any[], commitList: any[];
const pipelines = await apiAll(`projects/${project.id}/merge_requests/${ref.iid}/pipelines`);
if (sha) {
const versions = await apiAll(`projects/${project.id}/merge_requests/${ref.iid}/versions`);
const v = versions.find((x: any) => x.head_commit_sha.startsWith(sha));
if (!v) throw new Error(`No version of !${ref.iid} has head ${sha}. Versions: ${versions.map((x: any) => x.head_commit_sha.slice(0, 8)).join(', ')}`);
const full = await api(`projects/${project.id}/merge_requests/${ref.iid}/versions/${v.id}`);
diffs = full.diffs;
commitList = full.commits;
mr.sha = v.head_commit_sha;
mr.description = '(not available when replaying an earlier version)';
const atSha = pipelines.find((p: any) => p.sha === v.head_commit_sha);
mr.head_pipeline = atSha ? { id: atSha.id, status: atSha.status, web_url: atSha.web_url } : null;
} else {
[diffs, commitList] = await Promise.all([
apiAll(`projects/${project.id}/merge_requests/${ref.iid}/diffs`),
apiAll(`projects/${project.id}/merge_requests/${ref.iid}/commits`),
]);
}
// Which branches already hold each commit, so the reviewer can check release order (R5).
const commits = await Promise.all(
commitList.slice(0, 30).map(async (c: any) => {
const refs = await api(`projects/${project.id}/repository/commits/${c.id}/refs?type=branch&per_page=100`).catch(() => []);
return { sha: c.short_id as string, title: c.title as string, branches: (refs as any[]).map((r) => r.name) };
}),
);
const head = mr.head_pipeline;
return {
projectId: project.id,
projectPath: project.path_with_namespace,
webUrl: project.web_url,
sshUrl: project.ssh_url_to_repo,
httpUrl: project.http_url_to_repo,
iid: mr.iid,
title: mr.title,
description: mr.description ?? '',
author: mr.author?.name ?? mr.author?.username ?? 'unknown',
sourceBranch: mr.source_branch,
targetBranch: mr.target_branch,
sha: mr.sha,
state: mr.state,
labels: mr.labels ?? [],
pipeline: head ? { id: head.id, status: head.status, webUrl: head.web_url } : null,
pipelineIds: pipelines.map((p: any) => p.id),
commits,
diffs: diffs as MrInfo['diffs'],
};
}
export async function loadJob(projectId: number, jobId: number): Promise<{ id: number; pipelineId: number; name: string; status: string; webUrl: string } | null> {
try {
const j = await api(`projects/${projectId}/jobs/${jobId}`);
return { id: j.id, pipelineId: j.pipeline?.id, name: j.name, status: j.status, webUrl: j.web_url };
} catch {
return null;
}
}
// A shallow clone of exactly the reviewed commit, read-only for the reviewer. Symlinks are
// checked out as plain files holding their target, so an MR cannot add a link that makes
// `cat` or a glob read something outside the checkout.
// A laptop fetches over SSH with the operator's key. A server has no key: with GITLAB_TOKEN set,
// git fetches over HTTPS and gets the token through its environment, so the token is never
// written into the checkout the reviewer reads.
function gitAccess(mr: MrInfo): { url: string; env: NodeJS.ProcessEnv } {
const token = process.env.GITLAB_TOKEN;
if (!token) return { url: mr.sshUrl, env: process.env };
const header = `Authorization: Basic ${Buffer.from(`oauth2:${token}`).toString('base64')}`;
return { url: mr.httpUrl, env: { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'http.extraHeader', GIT_CONFIG_VALUE_0: header, GIT_TERMINAL_PROMPT: '0' } };
}
export async function checkout(mr: MrInfo, dir: string) {
const access = gitAccess(mr);
// Git must never walk up from the checkout: an empty folder inside another repository (a
// LABUH_HOME that is itself a git checkout) would otherwise send init, set-url and
// `checkout --force` to that outer repository.
const env = { ...access.env, GIT_CEILING_DIRECTORIES: path.dirname(path.resolve(dir)) };
const git = (...args: string[]) => run('git', args, { cwd: dir, env, maxBuffer: 16 * 1024 * 1024 });
try {
const { stdout } = await git('rev-parse', 'HEAD');
if (stdout.trim() === mr.sha) {
await flattenSymlinks(dir, git);
return;
}
} catch {
await run('mkdir', ['-p', dir]);
await git('init', '-q');
await git('remote', 'add', 'origin', access.url);
}
await git('remote', 'set-url', 'origin', access.url);
await git('config', 'core.symlinks', 'false');
await git('fetch', '-q', '--depth=50', 'origin', `refs/merge-requests/${mr.iid}/head`);
try {
await git('cat-file', '-e', `${mr.sha}^{commit}`);
} catch {
await git('fetch', '-q', '--depth=1', 'origin', mr.sha);
}
await git('-c', 'advice.detachedHead=false', 'checkout', '-q', '--force', mr.sha);
await flattenSymlinks(dir, git);
}
// Checkouts made before core.symlinks=false may still hold real links; rewrite them.
async function flattenSymlinks(dir: string, git: (...args: string[]) => Promise<{ stdout: string }>) {
await git('config', 'core.symlinks', 'false');
const { stdout } = await git('ls-files', '-s', '-z');
const links = stdout.split('\0').filter((l) => l.startsWith('120000 ')).map((l) => l.slice(l.indexOf('\t') + 1));
const real = links.filter((p) => lstatSync(path.join(dir, p), { throwIfNoEntry: false })?.isSymbolicLink());
for (const p of real) unlinkSync(path.join(dir, p));
if (real.length) await git('checkout', '-q', '--', ...real);
}
// ---- Hub (M1) ----
// `mergeSha`, `mergeStatus` and `pipelineStatus` come only from the single-MR endpoint (`mrSummary`).
export type MrSummary = {
projectPath: string; iid: number; sha: string; state: string; title: string; webUrl: string; labels: string[]; author: string; targetBranch: string;
mergeSha?: string | null; mergeStatus?: string | null; pipelineStatus?: string | null;
};
const summary = (projectPath: string, m: any): MrSummary => ({
projectPath, iid: m.iid, sha: m.sha, state: m.state, title: m.title, webUrl: m.web_url, labels: m.labels ?? [], author: m.author?.username ?? '', targetBranch: m.target_branch ?? '',
mergeSha: m.merge_commit_sha ?? m.squash_commit_sha ?? null, mergeStatus: m.detailed_merge_status ?? null, pipelineStatus: m.head_pipeline?.status ?? null,
});
export async function listLabelledMrs(projectPath: string, label: string): Promise<MrSummary[]> {
const pid = encodeURIComponent(projectPath);
const mrs = await apiAll(`projects/${pid}/merge_requests?state=opened&labels=${encodeURIComponent(label)}&per_page=100`);
return mrs.map((m) => summary(projectPath, m));
}
export async function mrSummary(ref: MrRef): Promise<MrSummary> {
return summary(ref.projectPath, await api(`projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}`));
}
export type Note = { id: number; body: string; author: string; system: boolean; createdAt: string };
// Notes newer than `afterId`, oldest first. Reads newest first and stops at the first page
// that reaches `afterId`, so a quiet MR costs one small request per poll.
export async function listNotes(ref: MrRef, afterId: number): Promise<Note[]> {
const base = `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}/notes?sort=desc&order_by=created_at`;
const perPage = afterId ? 20 : 100;
const fresh: any[] = [];
for (let page = 1; page <= 20; page++) {
const batch = await api<any[]>(`${base}&per_page=${perPage}&page=${page}`);
fresh.push(...batch.filter((n) => n.id > afterId));
if (batch.length < perPage || batch.some((n) => n.id <= afterId)) break;
}
return fresh
.sort((a, b) => a.id - b.id)
.map((n) => ({ id: n.id, body: n.body ?? '', author: n.author?.username ?? '', system: !!n.system, createdAt: n.created_at }));
}
// The latest pipeline on `ref`, limited to `sha` when given (a tag's pipeline needs no sha).
export async function pipelineFor(projectPath: string, sha: string | null, ref: string): Promise<{ id: number; status: string; webUrl: string } | null> {
const list = await api<any[]>(`projects/${encodeURIComponent(projectPath)}/pipelines?${sha ? `sha=${sha}&` : ''}ref=${encodeURIComponent(ref)}&per_page=5`);
const p = list[0];
return p ? { id: p.id, status: p.status, webUrl: p.web_url } : null;
}
// For repos that deploy from release tags: the oldest tag whose commit holds `mergeSha`.
export async function releaseTagFor(projectPath: string, mergeSha: string): Promise<{ name: string; sha: string } | null> {
const pid = encodeURIComponent(projectPath);
const merged = Date.parse((await api(`projects/${pid}/repository/commits/${mergeSha}`)).committed_date);
const tags = (await api<any[]>(`projects/${pid}/repository/tags?order_by=updated&sort=desc&per_page=20`))
.filter((t) => Date.parse(t.commit?.committed_date ?? 0) >= merged)
.sort((a, b) => Date.parse(a.commit.committed_date) - Date.parse(b.commit.committed_date));
for (const t of tags) {
const base = await api(`projects/${pid}/repository/merge_base?refs%5B%5D=${mergeSha}&refs%5B%5D=${t.commit.id}`).catch(() => null);
if (base?.id === mergeSha) return { name: t.name, sha: t.commit.id };
}
return null;
}
// Where a release would start: the branch head and the release-shaped tags (newest version first).
export async function releaseBase(projectPath: string, branch: string): Promise<{ head: string; tags: Array<{ name: string; sha: string }> }> {
const pid = encodeURIComponent(projectPath);
const b = await api(`projects/${pid}/repository/branches/${encodeURIComponent(branch)}`);
const tags = await api<any[]>(`projects/${pid}/repository/tags?order_by=version&sort=desc&per_page=100`);
return { head: b.commit.id, tags: tags.map((t) => ({ name: t.name, sha: t.commit?.id ?? '' })) };
}
// What `to` adds since `from`, as the branch saw it: its first-parent commits, each either the
// merge of an MR into `branch` or a commit pushed straight to it.
export async function releaseChanges(projectPath: string, branch: string, from: string | null, to: string): Promise<ReleaseChanges> {
const pid = encodeURIComponent(projectPath);
const range = encodeURIComponent(from ? `${from}..${to}` : to);
const commits = await apiAll(`projects/${pid}/repository/commits?ref_name=${range}&first_parent=true`);
const out: ReleaseChanges = { mrs: [], commits: [] };
for (const c of commits.slice(0, 200).reverse()) {
const mrs = await api<any[]>(`projects/${pid}/repository/commits/${c.id}/merge_requests`).catch(() => []);
const mr = mrs.find((m) => m.state === 'merged' && m.target_branch === branch && [m.merge_commit_sha, m.squash_commit_sha, m.sha].includes(c.id));
if (mr) out.mrs.push({ iid: mr.iid, title: mr.title, author: mr.author?.username ?? '' });
else out.commits.push({ sha: c.id, title: c.title });
}
return out;
}
// Two tokens besides the reader's: the bot (comments only) and the merge account (used only
// after Gas). Each comes from its environment variable, or else from its macOS Keychain item,
// and is handed to glab through its environment. Labuh never stores, logs or prints them.
type TokenKind = 'bot' | 'merge';
const TOKENS: Record<TokenKind, { env: string; keychain: string }> = {
bot: { env: 'LABUH_BOT_TOKEN', keychain: 'labuh-bot-token' },
merge: { env: 'LABUH_MERGE_TOKEN', keychain: 'labuh-merge-token' },
};
const cachedTokens: Partial<Record<TokenKind, string>> = {};
async function token(kind: TokenKind): Promise<string> {
if (cachedTokens[kind]) return cachedTokens[kind]!;
const { env, keychain } = TOKENS[kind];
let value = process.env[env] ?? '';
if (!value) {
try {
value = (await run('security', ['find-generic-password', '-s', keychain, '-w'])).stdout.trim();
} catch {
throw new Error(`no ${kind} token: set ${env} or the Keychain item ${keychain}`);
}
}
if (!value) throw new Error(`the ${kind} token is empty`);
return (cachedTokens[kind] = value);
}
async function tokenApi(kind: TokenKind, method: 'GET' | 'POST' | 'PUT', endpoint: string, fields: Record<string, string> = {}): Promise<any> {
const args = ['api', '--method', method, endpoint, ...Object.entries(fields).flatMap(([k, v]) => ['--raw-field', `${k}=${v}`])];
try {
const { stdout } = await run('glab', args, { env: { ...process.env, GITLAB_TOKEN: await token(kind) }, maxBuffer: 16 * 1024 * 1024 });
return JSON.parse(stdout);
} catch (e: any) {
// glab's error text is the HTTP status and message; never the token.
throw new Error(`${kind} ${method} ${endpoint.split('?')[0]} failed: ${String(e?.stderr || e?.message || e).trim().slice(0, 200)}`);
}
}
const botApi = (method: 'GET' | 'POST' | 'PUT', endpoint: string, body?: string) => tokenApi('bot', method, endpoint, body === undefined ? {} : { body });
// Read-only identity check: who a token is, and its role on each project.
export async function tokenCheck(kind: TokenKind, projects: string[]): Promise<{ username: string; name: string; bot: boolean; access: Array<{ project: string; level: number | null }> }> {
const me = await tokenApi(kind, 'GET', 'user');
const access = [];
for (const project of projects) {
const m = await tokenApi(kind, 'GET', `projects/${encodeURIComponent(project)}/members/all/${me.id}`).catch(() => null);
access.push({ project, level: m?.access_level ?? null });
}
return { username: me.username, name: me.name, bot: !!me.bot, access };
}
export const botCheck = (projects: string[]) => tokenCheck('bot', projects);
// GitLab computes mergeability lazily and leaves it `unchecked` until someone asks; only a
// Developer or above may ask, so this runs as the merge account. The answer usually lands a
// few seconds later, so callers read the MR again on their next pass.
export async function recheckMergeStatus(ref: MrRef): Promise<string | null> {
const m = await tokenApi('merge', 'GET', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}?with_merge_status_recheck=true`);
return m.detailed_merge_status ?? null;
}
// Merges exactly `sha`: GitLab refuses when the head moved, so Gas never merges an unreviewed commit.
export async function mergeMr(ref: MrRef, sha: string): Promise<{ mergeSha: string | null; state: string }> {
const m = await tokenApi('merge', 'PUT', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}/merge`, { sha });
return { mergeSha: m.merge_commit_sha ?? m.squash_commit_sha ?? null, state: m.state };
}
// An annotated tag on exactly `sha`, made by the merge account (release tags are Maintainer-only).
export async function createTag(projectPath: string, name: string, sha: string, message: string): Promise<{ name: string; sha: string }> {
const t = await tokenApi('merge', 'POST', `projects/${encodeURIComponent(projectPath)}/repository/tags`, { tag_name: name, ref: sha, message });
return { name: t.name, sha: t.commit?.id ?? sha };
}
// Closes an MR the approver rejected; the merge account can, the bot (Reporter) cannot.
export async function closeMr(ref: MrRef): Promise<{ state: string }> {
const m = await tokenApi('merge', 'PUT', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}`, { state_event: 'close' });
return { state: m.state };
}
export async function postNote(ref: MrRef, body: string): Promise<number> {
const n = await botApi('POST', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}/notes`, body);
return n.id;
}
export async function updateNote(ref: MrRef, noteId: number, body: string): Promise<void> {
await botApi('PUT', `projects/${encodeURIComponent(ref.projectPath)}/merge_requests/${ref.iid}/notes/${noteId}`, body);
}