基于 OpenCodeReview 的 webhook 服务:监听 Gitea 的 push 与 Pull Request 事件, 调用 OCR 审查 diff,把结果发布回 Gitea,并按阻断阈值决定是否自动合并。 主要能力: - Push / PR 事件触发,支持分支 glob 过滤与 PR-only / push-only 范围 - PR 内联评论(按 diff 行号定位)、汇总评论、Issue 生命周期、提交状态 - 可配置阻断阈值(严重级别 / 类别 / 任意意见) - 无阻断问题时自动合并,审查覆盖不完整时拒绝合并 - 内置 Web 后台:仓库配置、任务日志、失败重跑、连通性自检 - SQLite 持久化,worker 重启回收卡死任务,失败自动重试 实现为独立服务而非 Gitea Action:本机 act_runner 指向的实例不可达, 且后台配置与任务历史需要独立进程承载。
268 lines
9.1 KiB
JavaScript
268 lines
9.1 KiB
JavaScript
/** Minimal Gitea REST client (no external dependencies). */
|
|
|
|
export class GiteaError extends Error {
|
|
constructor(message, { status, body, method, url } = {}) {
|
|
super(message);
|
|
this.name = "GiteaError";
|
|
this.status = status;
|
|
this.body = body;
|
|
this.method = method;
|
|
this.url = url;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Normalize a Gitea base URL to the server root.
|
|
* Accepts `http://host`, `http://host/`, or `http://host/api/v1` and always
|
|
* returns the root form, because every request path already carries the
|
|
* `/api/v1` prefix.
|
|
*/
|
|
export function normalizeBaseUrl(input) {
|
|
const trimmed = String(input || "").trim().replace(/\/+$/, "");
|
|
if (!trimmed) throw new Error("Gitea base URL is required");
|
|
return trimmed.replace(/\/api\/v1$/, "");
|
|
}
|
|
|
|
export class GiteaClient {
|
|
constructor({ baseUrl, token, timeoutMs = 60000, userAgent = "gitea-codereview" }) {
|
|
this.baseUrl = normalizeBaseUrl(baseUrl);
|
|
this.token = token;
|
|
this.timeoutMs = timeoutMs;
|
|
this.userAgent = userAgent;
|
|
}
|
|
|
|
async request(method, path, { body, query, raw = false, headers = {}, timeoutMs } = {}) {
|
|
const url = new URL(this.baseUrl + path);
|
|
if (query) {
|
|
for (const [k, v] of Object.entries(query)) {
|
|
if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
|
|
}
|
|
}
|
|
const init = {
|
|
method,
|
|
headers: {
|
|
Accept: raw ? "text/plain, application/json" : "application/json",
|
|
"User-Agent": this.userAgent,
|
|
...headers,
|
|
},
|
|
signal: AbortSignal.timeout(timeoutMs ?? this.timeoutMs),
|
|
};
|
|
if (this.token) init.headers.Authorization = `token ${this.token}`;
|
|
if (body !== undefined) {
|
|
init.headers["Content-Type"] = "application/json";
|
|
init.body = JSON.stringify(body);
|
|
}
|
|
|
|
let res;
|
|
try {
|
|
res = await fetch(url, init);
|
|
} catch (err) {
|
|
throw new GiteaError(`Gitea request failed: ${method} ${url.pathname}: ${err.message}`, {
|
|
method, url: url.toString(),
|
|
});
|
|
}
|
|
|
|
const text = await res.text();
|
|
if (!res.ok) {
|
|
let parsed = null;
|
|
try { parsed = JSON.parse(text); } catch { /* keep raw text */ }
|
|
const detail = parsed?.message || text.slice(0, 400) || res.statusText;
|
|
throw new GiteaError(
|
|
`Gitea ${method} ${url.pathname} -> ${res.status}: ${detail}`,
|
|
{ status: res.status, body: parsed ?? text, method, url: url.toString() },
|
|
);
|
|
}
|
|
if (raw) return text;
|
|
if (!text) return null;
|
|
try { return JSON.parse(text); } catch { return text; }
|
|
}
|
|
|
|
get(path, options) { return this.request("GET", path, options); }
|
|
post(path, body, options) { return this.request("POST", path, { ...options, body }); }
|
|
patch(path, body, options) { return this.request("PATCH", path, { ...options, body }); }
|
|
put(path, body, options) { return this.request("PUT", path, { ...options, body }); }
|
|
del(path, options) { return this.request("DELETE", path, options); }
|
|
|
|
/** Verify the token and return the authenticated user. */
|
|
async getCurrentUser() {
|
|
return this.get("/api/v1/user");
|
|
}
|
|
|
|
async getVersion() {
|
|
return this.get("/api/v1/version");
|
|
}
|
|
|
|
async getRepo(owner, repo) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}`);
|
|
}
|
|
|
|
async listRepoBranches(owner, repo, limit = 100) {
|
|
const out = [];
|
|
for (let page = 1; page <= 20; page += 1) {
|
|
const batch = await this.get(`/api/v1/repos/${owner}/${repo}/branches`, {
|
|
query: { limit, page },
|
|
});
|
|
if (!Array.isArray(batch) || batch.length === 0) break;
|
|
out.push(...batch);
|
|
if (batch.length < limit) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async getBranch(owner, repo, branch) {
|
|
return this.get(`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/branches/${encodeURIComponent(branch)}`);
|
|
}
|
|
|
|
async getIssue(owner, repo, index) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/issues/${index}`);
|
|
}
|
|
|
|
async listIssues(owner, repo, query = {}) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/issues`, { query });
|
|
}
|
|
|
|
async createIssue(owner, repo, { title, body, labels, assignees }) {
|
|
const payload = { title, body };
|
|
if (labels?.length) payload.labels = labels;
|
|
if (assignees?.length) payload.assignees = assignees;
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/issues`, payload);
|
|
}
|
|
|
|
async updateIssue(owner, repo, index, patch) {
|
|
return this.patch(`/api/v1/repos/${owner}/${repo}/issues/${index}`, patch);
|
|
}
|
|
|
|
async listIssueComments(owner, repo, index, limit = 100) {
|
|
const out = [];
|
|
for (let page = 1; page <= 20; page += 1) {
|
|
const batch = await this.get(`/api/v1/repos/${owner}/${repo}/issues/${index}/comments`, {
|
|
query: { limit, page },
|
|
});
|
|
if (!Array.isArray(batch) || batch.length === 0) break;
|
|
out.push(...batch);
|
|
if (batch.length < limit) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async createIssueComment(owner, repo, index, body) {
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/issues/${index}/comments`, { body });
|
|
}
|
|
|
|
async updateIssueComment(owner, repo, commentId, body) {
|
|
return this.patch(`/api/v1/repos/${owner}/${repo}/issues/comments/${commentId}`, { body });
|
|
}
|
|
|
|
async createCommitStatus(owner, repo, sha, { state, context, description, targetUrl }) {
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/statuses/${sha}`, {
|
|
state,
|
|
context,
|
|
description: description?.slice(0, 255) ?? "",
|
|
target_url: targetUrl ?? "",
|
|
});
|
|
}
|
|
|
|
async getCommitStatuses(owner, repo, ref) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/commits/${ref}/statuses`);
|
|
}
|
|
|
|
async getPullRequest(owner, repo, index) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/pulls/${index}`);
|
|
}
|
|
|
|
async listPullRequests(owner, repo, query = {}) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/pulls`, { query });
|
|
}
|
|
|
|
async listPullRequestFiles(owner, repo, index) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/pulls/${index}/files`);
|
|
}
|
|
|
|
async listPullRequestCommits(owner, repo, index) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/pulls/${index}/commits`);
|
|
}
|
|
|
|
/**
|
|
* Create a review with optional inline comments.
|
|
* `comments` entries use { path, body, newPosition, oldPosition }.
|
|
*/
|
|
async createPullReview(owner, repo, index, { event = "COMMENT", body = "", commitId, comments = [] }) {
|
|
const payload = { event, body };
|
|
if (commitId) payload.commit_id = commitId;
|
|
if (comments.length) {
|
|
payload.comments = comments.map((c) => {
|
|
const entry = { path: c.path, body: c.body };
|
|
if (c.newPosition) entry.new_position = c.newPosition;
|
|
else if (c.oldPosition) entry.old_position = c.oldPosition;
|
|
return entry;
|
|
});
|
|
}
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/pulls/${index}/reviews`, payload);
|
|
}
|
|
|
|
async listPullReviews(owner, repo, index, limit = 50) {
|
|
const out = [];
|
|
for (let page = 1; page <= 20; page += 1) {
|
|
const batch = await this.get(`/api/v1/repos/${owner}/${repo}/pulls/${index}/reviews`, {
|
|
query: { limit, page },
|
|
});
|
|
if (!Array.isArray(batch) || batch.length === 0) break;
|
|
out.push(...batch);
|
|
if (batch.length < limit) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async mergePullRequest(owner, repo, index, { style = "squash", title, message, deleteBranch, headCommitId, mergeWhenChecksSucceed = false } = {}) {
|
|
const payload = { do: style };
|
|
if (title) payload.merge_title_field = title;
|
|
if (message) payload.merge_message_field = message;
|
|
if (deleteBranch !== undefined) payload.delete_branch_after_merge = Boolean(deleteBranch);
|
|
if (headCommitId) payload.head_commit_id = headCommitId;
|
|
if (mergeWhenChecksSucceed) payload.merge_when_checks_succeed = true;
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/pulls/${index}/merge`, payload);
|
|
}
|
|
|
|
async listRepoLabels(owner, repo) {
|
|
return this.get(`/api/v1/repos/${owner}/${repo}/labels`, { query: { limit: 100 } });
|
|
}
|
|
|
|
async createRepoLabel(owner, repo, { name, color = "#1f6feb", description = "" }) {
|
|
return this.post(`/api/v1/repos/${owner}/${repo}/labels`, { name, color, description });
|
|
}
|
|
|
|
/**
|
|
* Resolve label names to repository label IDs, creating missing labels.
|
|
* Gitea's issue API takes label IDs, not names.
|
|
* @returns {Promise<number[]>} label IDs that could be resolved.
|
|
*/
|
|
async ensureLabels(owner, repo, names) {
|
|
if (!names?.length) return [];
|
|
let existing = [];
|
|
try {
|
|
existing = (await this.listRepoLabels(owner, repo)) ?? [];
|
|
} catch {
|
|
existing = [];
|
|
}
|
|
const byName = new Map(existing.map((l) => [l.name, l.id]));
|
|
for (const name of names) {
|
|
if (byName.has(name)) continue;
|
|
try {
|
|
const created = await this.createRepoLabel(owner, repo, { name });
|
|
if (created?.id) byName.set(name, created.id);
|
|
} catch {
|
|
// Label creation is best-effort; issue creation still proceeds.
|
|
}
|
|
}
|
|
return names.map((n) => byName.get(n)).filter((id) => Number.isInteger(id));
|
|
}
|
|
|
|
async getUser(login) {
|
|
return this.get(`/api/v1/users/${encodeURIComponent(login)}`);
|
|
}
|
|
}
|
|
|
|
/** Derive the repository web URL from an API base URL. */
|
|
export function webBaseUrl(apiBaseUrl) {
|
|
return normalizeBaseUrl(apiBaseUrl);
|
|
} |