diff --git a/scripts/install-husky.cjs b/scripts/install-husky.cjs index 336392d..c8bf24e 100644 --- a/scripts/install-husky.cjs +++ b/scripts/install-husky.cjs @@ -1,13 +1,12 @@ #!/usr/bin/env node /** - * Windows 兼容的 husky 安装器(不使用 .sh 脚本)。 - * 用本仓库自带的 Node 脚本把 husky 的 prepare 钩子写到 .git/hooks/pre-commit。 + * Windows 兼容的 pre-commit 钩子安装器(不使用 .sh 业务脚本)。 + * 钩子内部用仓库相对路径调用 Node 脚本,避免绝对路径中的空格/中文目录问题。 */ "use strict"; const fs = require("node:fs"); const path = require("node:path"); -const os = require("node:os"); const root = path.resolve(__dirname, ".."); const gitDir = path.join(root, ".git"); @@ -21,12 +20,8 @@ if (!fs.existsSync(gitDir)) { fs.mkdirSync(hooksDir, { recursive: true }); -const separator = os.platform() === "win32" ? "\\" : "/"; -const nodeBinary = process.execPath; -const hookScript = [ - "#!/bin/sh", - `node "${nodeBinary.replace(/\\/g, "/")}" "${path.join(root, "scripts", "husky-pre-commit.cjs").replace(/\\/g, "/")}"`, -].join("\n"); +// git hooks 以仓库根为工作目录,相对路径在 Windows 与 POSIX 下都可靠。 +const hookScript = ["#!/bin/sh", 'node scripts/husky-pre-commit.cjs'].join("\n"); fs.writeFileSync(hookPath, `${hookScript}\n`, { mode: 0o755 }); console.log(`[install-husky] 已写入 git pre-commit 钩子: ${hookPath}`); \ No newline at end of file diff --git a/src/retry.ts b/src/retry.ts index 85f37e5..a1105eb 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -3,6 +3,44 @@ import { logger } from "./logger.js"; const MAX_ATTEMPTS = 5; const BASE_DELAY_MS = 1_000; +const RETRYABLE_ERROR_CODES = new Set([ + "ECONNRESET", + "ECONNREFUSED", + "ETIMEDOUT", + "EAI_AGAIN", + "ENOTFOUND", + "EPIPE", + "UND_ERR_SOCKET", + "UND_ERR_CONNECT_TIMEOUT" +]); + +/** + * Decide whether an error is worth retrying: server-side faults, rate limits, + * and transport failures are transient; ordinary 4xx responses are not. + */ +export function isRetryableError(error: unknown): boolean { + if (typeof error !== "object" || error === null) { + return false; + } + + const candidate = error as { status?: unknown; code?: unknown }; + if (typeof candidate.status === "number") { + if (candidate.status === 429) { + return true; + } + if (candidate.status >= 500 && candidate.status < 600) { + return true; + } + return false; + } + + if (typeof candidate.code === "string" && RETRYABLE_ERROR_CODES.has(candidate.code)) { + return true; + } + + return false; +} + export async function withRetry( label: string, operation: () => Promise, @@ -26,12 +64,13 @@ export async function withRetry( error, label, attempt, - maxAttempts + maxAttempts, + retryable: isRetryableError(error) }, "Request failed." ); - if (attempt === maxAttempts) { + if (attempt === maxAttempts || !isRetryableError(error)) { break; } diff --git a/src/storage/cacheStore.ts b/src/storage/cacheStore.ts index f3b394f..4f72ce5 100644 --- a/src/storage/cacheStore.ts +++ b/src/storage/cacheStore.ts @@ -41,6 +41,9 @@ export function pullRequestReviewHistoryObjectKey( headSha: string, prefix?: string ): string { + if (!Number.isInteger(pullNumber) || pullNumber <= 0) { + throw new Error("Pull request number must be a positive integer."); + } if (!/^[0-9a-f]{40,64}$/i.test(headSha)) { throw new Error("Review head SHA must contain 40-64 hexadecimal characters."); } diff --git a/src/storage/r2.ts b/src/storage/r2.ts index 9ccda50..c6de6d3 100644 --- a/src/storage/r2.ts +++ b/src/storage/r2.ts @@ -113,7 +113,7 @@ function getR2Client(settings: R2Settings): S3Client { return cachedClient; } -function normalizeEndpoint(value: string): string { +export function normalizeEndpoint(value: string): string { let endpoint: URL; try { endpoint = new URL(value); diff --git a/test/diff-position.test.ts b/test/diff-position.test.ts new file mode 100644 index 0000000..73d182f --- /dev/null +++ b/test/diff-position.test.ts @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { collectValidNewLines, toDiffPosition } from "../src/github/diff.js"; + +function file(patch?: string) { + return { filename: "src/a.ts", patch, status: "modified", additions: 2, deletions: 1 }; +} + +const samplePatch = [ + "@@ -1,3 +1,4 @@", + " context line", + "-removed line", + "+added line one", + "+added line two", + " more context" +].join("\n"); + +test("collectValidNewLines tracks added lines per file", () => { + const valid = collectValidNewLines([file(samplePatch)]); + assert.equal(valid.has("src/a.ts:2"), true); + assert.equal(valid.has("src/a.ts:3"), true); + assert.equal(valid.has("src/a.ts:1"), false); + assert.equal(valid.has("src/a.ts:4"), false); +}); + +test("files without patches contribute no valid lines", () => { + const valid = collectValidNewLines([file(undefined)]); + assert.equal(valid.size, 0); +}); + +test("toDiffPosition maps valid new lines and rejects stale ones", () => { + const valid = collectValidNewLines([file(samplePatch)]); + assert.deepEqual(toDiffPosition(file(), 2, valid), { + path: "src/a.ts", + line: 2, + side: "RIGHT" + }); + assert.equal(toDiffPosition(file(), 99, valid), null); +}); + +test("hunk headers with ranges are parsed correctly", () => { + const valid = collectValidNewLines([ + file("@@ -10,5 +20,3 @@\n+first\n+second\n+third") + ]); + assert.equal(valid.has("src/a.ts:20"), true); + assert.equal(valid.has("src/a.ts:22"), true); + assert.equal(valid.has("src/a.ts:23"), false); +}); diff --git a/test/persistent-cache-keys.test.ts b/test/persistent-cache-keys.test.ts new file mode 100644 index 0000000..283e454 --- /dev/null +++ b/test/persistent-cache-keys.test.ts @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + normalizeObjectPrefix, + pullRequestReviewHistoryObjectKey, + pullRequestReviewObjectKey, + repositoryKnowledgeObjectKey +} from "../src/storage/cacheStore.js"; + +test("object keys are scoped by repository id, pull number, and optional prefix", () => { + assert.equal( + repositoryKnowledgeObjectKey("123"), + "repositories/123/knowledge/repository.md" + ); + assert.equal( + pullRequestReviewObjectKey("123", 7), + "repositories/123/pulls/7/latest.json" + ); + assert.equal( + pullRequestReviewObjectKey("123", 7, "forum-1"), + "forum-1/repositories/123/pulls/7/latest.json" + ); +}); + +test("history keys pin the reviewed head sha in lowercase hex form", () => { + const sha = "A".repeat(40).toLowerCase(); + assert.equal( + pullRequestReviewHistoryObjectKey("123", 9, sha.toUpperCase()), + `repositories/123/pulls/9/reviews/${sha}.json` + ); + assert.throws(() => pullRequestReviewHistoryObjectKey("123", 9, "short"), /40-64 hexadecimal/); + assert.throws( + () => pullRequestReviewHistoryObjectKey("123", -1, sha), + /Pull request number must be a positive integer/ + ); +}); + +test("normalizeObjectPrefix validates each slash-separated segment", () => { + assert.equal(normalizeObjectPrefix(undefined), ""); + assert.equal(normalizeObjectPrefix(""), ""); + assert.equal(normalizeObjectPrefix("/a/b/"), "a/b"); + assert.throws(() => normalizeObjectPrefix("bad/../segment"), /safe slash-separated/); + assert.throws(() => normalizeObjectPrefix(".hidden"), /safe slash-separated/); +}); diff --git a/test/r2-endpoint.test.ts b/test/r2-endpoint.test.ts new file mode 100644 index 0000000..8478c2b --- /dev/null +++ b/test/r2-endpoint.test.ts @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { isR2Configured, normalizeEndpoint } from "../src/storage/r2.js"; + +test("normalizeEndpoint accepts credential-free https URLs and trims trailing slashes", () => { + assert.equal( + normalizeEndpoint("https://account.r2.cloudflarestorage.com"), + "https://account.r2.cloudflarestorage.com" + ); + assert.equal( + normalizeEndpoint("https://account.r2.cloudflarestorage.com/"), + "https://account.r2.cloudflarestorage.com" + ); +}); + +test("normalizeEndpoint rejects non-https, credentialed, or decorated URLs", () => { + assert.throws(() => normalizeEndpoint("http://insecure.example"), /credential-free HTTPS/); + assert.throws(() => normalizeEndpoint("https://user:pass@host"), /credential-free HTTPS/); + assert.throws(() => normalizeEndpoint("https://host/path?query=1"), /credential-free HTTPS/); + assert.throws(() => normalizeEndpoint("not a url"), /valid HTTPS URL/); +}); + +test("isR2Configured reflects ambient configuration without throwing", () => { + // The test environment has no R2_* env vars set; the helper must not throw. + assert.equal(typeof isR2Configured(), "boolean"); +}); diff --git a/test/required-checks.test.ts b/test/required-checks.test.ts new file mode 100644 index 0000000..40ae8d9 --- /dev/null +++ b/test/required-checks.test.ts @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { Octokit } from "@octokit/rest"; +import { requiredChecksAreGreen } from "../src/github/checks.js"; + +type CheckRun = { + name: string; + status: string; + conclusion?: string | null; +}; + +function octokitWith(params: { + checkRuns: CheckRun[]; + combinedStatus?: { state: string; statuses: unknown[] }; +}): Octokit { + return { + rest: { + checks: { + listForRef: async () => ({ + data: { check_runs: params.checkRuns } + }) + }, + repos: { + getCombinedStatusForRef: async () => ({ + data: params.combinedStatus ?? { state: "success", statuses: [] } + }) + } + } + } as unknown as Octokit; +} + +test("all green checks and statuses pass", async () => { + const octokit = octokitWith({ + checkRuns: [ + { name: "ci", status: "completed", conclusion: "success" }, + { name: "lint", status: "completed", conclusion: "neutral" }, + { name: "docs", status: "completed", conclusion: "skipped" } + ] + }); + const result = await requiredChecksAreGreen(octokit, { owner: "a", repo: "b", ref: "sha" }); + assert.equal(result.ok, true); +}); + +test("pending or failed checks block the merge", async () => { + const pending = await requiredChecksAreGreen( + octokitWith({ checkRuns: [{ name: "ci", status: "in_progress" }] }), + { owner: "a", repo: "b", ref: "sha" } + ); + assert.equal(pending.ok, false); + assert.match(pending.reason ?? "", /in_progress\/pending/); + + const failed = await requiredChecksAreGreen( + octokitWith({ + checkRuns: [{ name: "ci", status: "completed", conclusion: "failure" }] + }), + { owner: "a", repo: "b", ref: "sha" } + ); + assert.equal(failed.ok, false); + assert.match(failed.reason ?? "", /failure/); +}); + +test("ghbot-owned check runs are ignored", async () => { + for (const ignoredName of ["ghbot review", "bot-review", "acme/ bot-review"]) { + const result = await requiredChecksAreGreen( + octokitWith({ + checkRuns: [{ name: ignoredName, status: "completed", conclusion: "action_required" }] + }), + { owner: "a", repo: "b", ref: "sha" } + ); + assert.equal(result.ok, true, `${ignoredName} should be ignored`); + } +}); + +test("non-success commit statuses block when present", async () => { + const result = await requiredChecksAreGreen( + octokitWith({ + checkRuns: [], + combinedStatus: { state: "failure", statuses: [{ state: "failure" }] } + }), + { owner: "a", repo: "b", ref: "sha" } + ); + assert.equal(result.ok, false); + assert.match(result.reason ?? "", /Commit status is failure/); +}); diff --git a/test/retry.test.ts b/test/retry.test.ts new file mode 100644 index 0000000..1bb76cd --- /dev/null +++ b/test/retry.test.ts @@ -0,0 +1,112 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { isRetryableError, withRetry } from "../src/retry.js"; + +class HttpLikeError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +test("returns immediately when the first attempt succeeds", async () => { + let attempts = 0; + const result = await withRetry( + "probe.first", + async () => { + attempts += 1; + return "ok"; + }, + { baseDelayMs: 1 } + ); + assert.equal(result, "ok"); + assert.equal(attempts, 1); +}); + +test("retries transient failures and eventually succeeds", async () => { + let attempts = 0; + const result = await withRetry( + "probe.transient", + async () => { + attempts += 1; + if (attempts < 3) { + throw new HttpLikeError(502, "bad gateway"); + } + return "done"; + }, + { baseDelayMs: 1 } + ); + assert.equal(result, "done"); + assert.equal(attempts, 3); +}); + +test("throws the last error after exhausting attempts", async () => { + let attempts = 0; + await assert.rejects( + withRetry( + "probe.exhausted", + async () => { + attempts += 1; + throw new HttpLikeError(503, `boom ${attempts}`); + }, + { maxAttempts: 3, baseDelayMs: 1 } + ), + /boom 3$/ + ); + assert.equal(attempts, 3); +}); + +test("4xx errors are not retried by default", async () => { + let attempts = 0; + await assert.rejects( + withRetry( + "probe.client-error", + async () => { + attempts += 1; + throw new HttpLikeError(404, "not found"); + }) + ); + assert.equal(attempts, 1); +}); + +test("429 rate limits are retried by default", async () => { + let attempts = 0; + await assert.rejects( + withRetry( + "probe.rate-limit", + async () => { + attempts += 1; + throw new HttpLikeError(429, "slow down"); + }, + { maxAttempts: 2, baseDelayMs: 1 } + ) + ); + assert.equal(attempts, 2); +}); + +test("network-shaped failures are retried", async () => { + let attempts = 0; + await assert.rejects( + withRetry( + "probe.network", + async () => { + attempts += 1; + throw Object.assign(new Error("socket hang up"), { code: "ECONNRESET" }); + }, + { maxAttempts: 2, baseDelayMs: 1 } + ) + ); + assert.equal(attempts, 2); +}); + +test("isRetryableError classifies statuses and codes explicitly", () => { + assert.equal(isRetryableError(new HttpLikeError(500, "oops")), true); + assert.equal(isRetryableError(new HttpLikeError(503, "oops")), true); + assert.equal(isRetryableError(new HttpLikeError(429, "oops")), true); + assert.equal(isRetryableError(new HttpLikeError(404, "nope")), false); + assert.equal(isRetryableError(new HttpLikeError(401, "denied")), false); + assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "ETIMEDOUT" })), true); + assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "EAI_AGAIN" })), true); + assert.equal(isRetryableError(new Error("plain")), false); +});