Files
git-codereview/app/lib/gitea.js
T
kgod 34f2897888 fix: 自动安装 Webhook、修正 PR 审查范围与分支匹配语义
三个导致「提交了新 PR 但没有任何反应」的独立问题:

1. 从不创建 Webhook
   服务只被动接收事件,但配置仓库时不会去 Gitea 里建 Webhook,
   结果仓库永远收不到 push / PR 事件,看起来和坏掉一样。
   - 保存仓库时自动创建或更新 Webhook(POST /repos 返回值带 webhook 结果)
   - 新增 GET/POST /api/repos/:id/webhook 查询与修复
   - 仓库列表新增 Webhook 列,未配置可一键「修复 Webhook」
   - 新增 CR_WEBHOOK_URL,留空则推导为「Gitea 主机名 + 本服务端口」

2. 审查范围用了错的分支做基准
   resolveRange 优先取 managed_branch 而不是 job.base_ref,
   于是 PR 被拿去和一个无关分支比较;当两者内容相同就报
   「base and head resolve to the same commit」直接跳过。
   改为优先用该改动实际要合入的分支(PR 的目标分支),
   仅 push 事件回退到 managed_branch。

3. 检查分支的匹配语义反了
   原先要求 PR 的 head(功能分支)出现在 check_branches 里,
   而用户配置的是「要保护的目标分支」(如 prd/test),
   功能分支永远不会被列出,所以 PR 一律被过滤掉。
   新增 pullRequestMatches:PR 的 base 命中检查分支即审查,
   head 命中仍保留支持。这样「审查所有合入 prd/test 的改动」成立。

验证:PR offerpai/offerpai_h5#2 重跑通过,7 条内联评论、
2 条阻断、commit status failure、Issue #3 创建。
2026-09-20 14:44:26 +08:00

330 lines
11 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}`);
}
/** Repositories visible to the token, across pages. */
async listAccessibleRepos(limit = 50, maxPages = 40) {
const out = [];
const seen = new Set();
for (let page = 1; page <= maxPages; page += 1) {
let batch;
try {
batch = await this.get("/api/v1/user/repos", { query: { limit, page } });
} catch (err) {
if (page === 1) throw err;
break;
}
if (!Array.isArray(batch) || batch.length === 0) break;
for (const r of batch) {
if (r?.full_name && !seen.has(r.full_name)) {
seen.add(r.full_name);
out.push(r);
}
}
if (batch.length < limit) break;
}
return out;
}
async listRepoWebhooks(owner, repo) {
return this.get(`/api/v1/repos/${owner}/${repo}/hooks`);
}
/**
* Create (or update) the review webhook for a repository.
* Returns { created: boolean, id }.
*/
async ensureRepoWebhook(owner, repo, { url, secret, events = ["push", "pull_request"] }) {
const desired = {
type: "gitea",
active: true,
name: "gitea-codereview",
events,
config: { url, content_type: "json", ...(secret ? { secret } : {}) },
};
let existing = [];
try {
existing = (await this.listRepoWebhooks(owner, repo)) ?? [];
} catch {
existing = [];
}
const match = existing.find((h) => h.config?.url === url) ?? existing.find((h) => h.name === desired.name);
if (match) {
await this.patch(`/api/v1/repos/${owner}/${repo}/hooks/${match.id}`, desired);
return { created: false, id: match.id };
}
const created = await this.post(`/api/v1/repos/${owner}/${repo}/hooks`, desired);
return { created: true, id: created?.id ?? null };
}
/** Create a branch, optionally from another branch/tag/commit. */
async createBranch(owner, repo, { newBranch, fromBranch }) {
const payload = { new_branch_name: newBranch };
if (fromBranch) payload.old_ref_name = fromBranch;
return this.post(`/api/v1/repos/${owner}/${repo}/branches`, payload);
}
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);
}