Convert reviewer to GitHub Actions workflow
This commit is contained in:
1 parent
9d40d7850f
commit
50d0ae5be9
18 files changed
+541
-2641
No files matched your search
@@ -0,0 +1,138 @@
|
||||
import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
import { createGitHubClient } from "../github/client.js";
|
||||
import { logger } from "../logger.js";
|
||||
import {
|
||||
processLenientCheckComment,
|
||||
processPullRequest,
|
||||
processPullRequestReviewApproval
|
||||
} from "../review/processor.js";
|
||||
|
||||
type GitHubRepository = {
|
||||
name: string;
|
||||
owner: {
|
||||
login: string;
|
||||
};
|
||||
full_name: string;
|
||||
};
|
||||
|
||||
type PullRequestPayload = {
|
||||
action: string;
|
||||
pull_request: {
|
||||
number: number;
|
||||
draft: boolean;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type IssueCommentPayload = {
|
||||
action: string;
|
||||
issue: {
|
||||
number: number;
|
||||
pull_request?: {
|
||||
url: string;
|
||||
};
|
||||
};
|
||||
comment: {
|
||||
body: string;
|
||||
user: {
|
||||
login: string;
|
||||
};
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type PullRequestReviewPayload = {
|
||||
action: string;
|
||||
review: {
|
||||
state: string;
|
||||
commit_id: string;
|
||||
user?: {
|
||||
login?: string;
|
||||
};
|
||||
};
|
||||
pull_request: {
|
||||
number: number;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const eventName = process.env.GITHUB_EVENT_NAME;
|
||||
const eventPath = process.env.GITHUB_EVENT_PATH;
|
||||
|
||||
if (!eventName || !eventPath) {
|
||||
throw new Error("GITHUB_EVENT_NAME and GITHUB_EVENT_PATH are required.");
|
||||
}
|
||||
|
||||
const payload = JSON.parse(fs.readFileSync(eventPath, "utf8")) as PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload;
|
||||
const octokit = createGitHubClient();
|
||||
|
||||
logger.info({ eventName }, "Handling GitHub Actions review event.");
|
||||
|
||||
if (eventName === "pull_request_target") {
|
||||
const prPayload = payload as PullRequestPayload;
|
||||
if (prPayload.action === "opened") {
|
||||
await octokit.rest.issues.createComment({
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
issue_number: prPayload.pull_request.number,
|
||||
body: "Automated review has started. I am checking this pull request now."
|
||||
});
|
||||
}
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
pullNumber: prPayload.pull_request.number
|
||||
},
|
||||
"strict"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventName === "issue_comment") {
|
||||
const commentPayload = payload as IssueCommentPayload;
|
||||
if (!commentPayload.issue.pull_request) {
|
||||
logger.info({ issueNumber: commentPayload.issue.number }, "Skipping issue comment because it is not on a pull request.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processLenientCheckComment(octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventName === "pull_request_review") {
|
||||
const reviewPayload = payload as PullRequestReviewPayload;
|
||||
const reviewerLogin = reviewPayload.review.user?.login;
|
||||
if (!reviewerLogin) {
|
||||
logger.warn({ pullNumber: reviewPayload.pull_request.number }, "Skipping review event without reviewer login.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processPullRequestReviewApproval(octokit, {
|
||||
owner: reviewPayload.repository.owner.login,
|
||||
repo: reviewPayload.repository.name,
|
||||
pullNumber: reviewPayload.pull_request.number,
|
||||
reviewerLogin,
|
||||
state: reviewPayload.review.state,
|
||||
commitId: reviewPayload.review.commit_id
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warn({ eventName }, "Unhandled GitHub Actions event.");
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
logger.error({ error, botName: config.botName }, "GitHub Actions review run failed.");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+42
-13
@@ -1,30 +1,58 @@
|
||||
import "dotenv/config";
|
||||
import { z } from "zod";
|
||||
|
||||
const optionalString = z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.string().optional());
|
||||
|
||||
const optionalNonEmptyString = z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.string().min(1).optional());
|
||||
|
||||
const envBoolean = z.preprocess((value) => {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
|
||||
switch (value.toLowerCase()) {
|
||||
case "true":
|
||||
case "1":
|
||||
case "yes":
|
||||
case "on":
|
||||
return true;
|
||||
case "false":
|
||||
case "0":
|
||||
case "no":
|
||||
case "off":
|
||||
return false;
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}, z.boolean());
|
||||
|
||||
const configSchema = z.object({
|
||||
port: z.coerce.number().int().positive().default(3000),
|
||||
webhookSecret: z.string().min(1),
|
||||
githubAppId: z.coerce.number().int().positive(),
|
||||
githubPrivateKey: z.string().min(1).transform((value) => value.replace(/\\n/g, "\n")),
|
||||
githubToken: z.string().min(1),
|
||||
openAiApiKey: z.string().min(1),
|
||||
openAiBaseUrl: z.string().url().optional(),
|
||||
openAiModel: z.string().min(1).default("gpt-4.1"),
|
||||
openAiReasoningEffort: z.enum(["default", "low", "medium", "high"]).optional().transform((value) => {
|
||||
openAiBaseUrl: optionalString.pipe(z.string().url().optional()),
|
||||
openAiModel: optionalNonEmptyString.default("gpt-4.1"),
|
||||
openAiReasoningEffort: z.preprocess((value) => {
|
||||
return value === "" ? undefined : value;
|
||||
}, z.enum(["default", "low", "medium", "high"]).optional()).transform((value) => {
|
||||
return value === "default" ? undefined : value;
|
||||
}),
|
||||
botName: z.string().min(1).default("ghbot"),
|
||||
lenientApprovalUser: z.string().min(1).default("lezi-fun"),
|
||||
autoMerge: z.coerce.boolean().default(false),
|
||||
autoMerge: envBoolean.default(false),
|
||||
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
|
||||
requireChecks: z.coerce.boolean().default(true),
|
||||
maxPatchChars: z.coerce.number().int().positive().default(120_000)
|
||||
requireChecks: envBoolean.default(true),
|
||||
maxPatchChars: z.coerce.number().int().positive().default(120_000),
|
||||
logLevel: z.string().min(1).default("info")
|
||||
});
|
||||
|
||||
export const config = configSchema.parse({
|
||||
port: process.env.PORT,
|
||||
webhookSecret: process.env.WEBHOOK_SECRET,
|
||||
githubAppId: process.env.GITHUB_APP_ID,
|
||||
githubPrivateKey: process.env.GITHUB_PRIVATE_KEY,
|
||||
githubToken: process.env.GITHUB_TOKEN,
|
||||
openAiApiKey: process.env.OPENAI_API_KEY,
|
||||
openAiBaseUrl: process.env.OPENAI_BASE_URL,
|
||||
openAiModel: process.env.OPENAI_MODEL,
|
||||
@@ -34,5 +62,6 @@ export const config = configSchema.parse({
|
||||
autoMerge: process.env.AUTO_MERGE,
|
||||
mergeMethod: process.env.MERGE_METHOD,
|
||||
requireChecks: process.env.REQUIRE_CHECKS,
|
||||
maxPatchChars: process.env.MAX_PATCH_CHARS
|
||||
maxPatchChars: process.env.MAX_PATCH_CHARS,
|
||||
logLevel: process.env.LOG_LEVEL
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import { createAppAuth } from "@octokit/auth-app";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { config } from "../config.js";
|
||||
|
||||
export async function getInstallationOctokit(installationId: number): Promise<Octokit> {
|
||||
const auth = createAppAuth({
|
||||
appId: config.githubAppId,
|
||||
privateKey: config.githubPrivateKey,
|
||||
installationId
|
||||
});
|
||||
|
||||
const installationAuthentication = await auth({ type: "installation" });
|
||||
|
||||
return new Octokit({
|
||||
auth: installationAuthentication.token
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
|
||||
const IGNORED_CHECK_RUN_NAMES = new Set(["ghbot review", "bot-review"]);
|
||||
|
||||
export async function requiredChecksAreGreen(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
@@ -22,6 +24,10 @@ export async function requiredChecksAreGreen(
|
||||
]);
|
||||
|
||||
const failedCheck = checks.data.check_runs.find((check) => {
|
||||
if (IGNORED_CHECK_RUN_NAMES.has(check.name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
check.status !== "completed" ||
|
||||
!["success", "neutral", "skipped"].includes(check.conclusion ?? "")
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { config } from "../config.js";
|
||||
|
||||
export function createGitHubClient(): Octokit {
|
||||
return new Octokit({
|
||||
auth: config.githubToken
|
||||
});
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Webhooks } from "@octokit/webhooks";
|
||||
import { config } from "../config.js";
|
||||
import { getInstallationOctokit } from "./app.js";
|
||||
import { logger } from "../logger.js";
|
||||
import {
|
||||
isLenientCheckAction,
|
||||
processLenientCheckRunAction,
|
||||
processPullRequest,
|
||||
processPullRequestReviewApproval
|
||||
} from "../review/processor.js";
|
||||
|
||||
export function createGitHubWebhooks(): Webhooks {
|
||||
const webhooks = new Webhooks({
|
||||
secret: config.webhookSecret
|
||||
});
|
||||
|
||||
webhooks.on(
|
||||
["pull_request.opened", "pull_request.synchronize", "pull_request.reopened", "pull_request.ready_for_review"],
|
||||
async ({ payload }) => {
|
||||
const installationId = payload.installation?.id;
|
||||
if (!installationId) {
|
||||
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping PR without installation id.");
|
||||
return;
|
||||
}
|
||||
|
||||
const octokit = await getInstallationOctokit(installationId);
|
||||
await processPullRequest(octokit, {
|
||||
owner: payload.repository.owner.login,
|
||||
repo: payload.repository.name,
|
||||
pullNumber: payload.pull_request.number
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
webhooks.on("check_run.requested_action", async ({ payload }) => {
|
||||
const actionIdentifier = payload.requested_action?.identifier;
|
||||
if (!actionIdentifier || !isLenientCheckAction(actionIdentifier)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const installationId = payload.installation?.id;
|
||||
if (!installationId) {
|
||||
logger.warn({ repository: payload.repository.full_name, checkRun: payload.check_run.id }, "Skipping check action without installation id.");
|
||||
return;
|
||||
}
|
||||
|
||||
const octokit = await getInstallationOctokit(installationId);
|
||||
await processLenientCheckRunAction(octokit, {
|
||||
owner: payload.repository.owner.login,
|
||||
repo: payload.repository.name,
|
||||
headSha: payload.check_run.head_sha
|
||||
});
|
||||
});
|
||||
|
||||
webhooks.on("pull_request_review.submitted", async ({ payload }) => {
|
||||
const reviewerLogin = payload.review.user?.login;
|
||||
if (!reviewerLogin) {
|
||||
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without reviewer login.");
|
||||
return;
|
||||
}
|
||||
|
||||
const installationId = payload.installation?.id;
|
||||
if (!installationId) {
|
||||
logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without installation id.");
|
||||
return;
|
||||
}
|
||||
|
||||
const octokit = await getInstallationOctokit(installationId);
|
||||
await processPullRequestReviewApproval(octokit, {
|
||||
owner: payload.repository.owner.login,
|
||||
repo: payload.repository.name,
|
||||
pullNumber: payload.pull_request.number,
|
||||
reviewerLogin,
|
||||
state: payload.review.state,
|
||||
commitId: payload.review.commit_id
|
||||
});
|
||||
});
|
||||
|
||||
webhooks.onError((error) => {
|
||||
logger.error({ error }, "Webhook handler failed.");
|
||||
});
|
||||
|
||||
return webhooks;
|
||||
}
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
import pino from "pino";
|
||||
import { config } from "./config.js";
|
||||
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL ?? "info"
|
||||
level: config.logLevel
|
||||
});
|
||||
@@ -14,6 +14,10 @@ export function formatReviewBody(decision: ReviewDecision, unpostedFindings: Rev
|
||||
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
|
||||
];
|
||||
|
||||
if (mode === "strict" && !decision.safeToMerge && !decision.shouldClosePullRequest) {
|
||||
lines.push("", "Need a narrower pass? Comment `/lenient-check` on this PR.");
|
||||
}
|
||||
|
||||
if (unpostedFindings.length > 0) {
|
||||
lines.push("", "Findings that could not be attached inline:");
|
||||
for (const finding of unpostedFindings) {
|
||||
|
||||
+214
-44
@@ -9,8 +9,9 @@ import { OpenAiReviewer } from "./openaiReviewer.js";
|
||||
import { compactFilesForReview } from "./prompt.js";
|
||||
|
||||
const reviewer = new OpenAiReviewer();
|
||||
const LENIENT_ACTION_IDENTIFIER = "lenient_check";
|
||||
const CHECK_RUN_NAME = "ghbot review";
|
||||
export const LENIENT_COMMENT_COMMAND = "/lenient-check";
|
||||
const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise<void> {
|
||||
const { owner, repo, pullNumber } = ref;
|
||||
@@ -130,6 +131,81 @@ export async function processPullRequestReviewApproval(
|
||||
});
|
||||
}
|
||||
|
||||
export async function processLenientCheckComment(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
commenterLogin: string;
|
||||
commentBody: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
if (!isLenientCheckComment(params.commentBody)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const adminRecentlyResponded = await hasRecentAdminResponse(octokit, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber
|
||||
});
|
||||
|
||||
const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
username: params.commenterLogin
|
||||
});
|
||||
|
||||
const allowedPermissions = adminRecentlyResponded
|
||||
? new Set(["admin"])
|
||||
: new Set(["admin", "maintain", "write"]);
|
||||
|
||||
if (!allowedPermissions.has(permission.permission)) {
|
||||
logger.info(
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commenterLogin: params.commenterLogin,
|
||||
permission: permission.permission,
|
||||
adminRecentlyResponded
|
||||
},
|
||||
"Ignoring lenient check comment because commenter does not meet the current permission threshold."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commenterLogin: params.commenterLogin,
|
||||
adminRecentlyResponded,
|
||||
permission: permission.permission
|
||||
},
|
||||
"Processing lenient check comment command."
|
||||
);
|
||||
|
||||
await octokit.rest.issues.createComment({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
issue_number: params.pullNumber,
|
||||
body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.`
|
||||
});
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber
|
||||
},
|
||||
"lenient"
|
||||
);
|
||||
}
|
||||
|
||||
async function maybeMergePullRequest(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
@@ -232,37 +308,6 @@ async function hasCurrentHeadApprovalFrom(
|
||||
});
|
||||
}
|
||||
|
||||
export async function processLenientCheckRunAction(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
headSha: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const pulls = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
commit_sha: params.headSha
|
||||
});
|
||||
|
||||
const pullRequest = pulls.data.find((pull) => pull.state === "open");
|
||||
if (!pullRequest) {
|
||||
logger.warn(params, "No open pull request found for lenient check action.");
|
||||
return;
|
||||
}
|
||||
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
{
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: pullRequest.number
|
||||
},
|
||||
"lenient"
|
||||
);
|
||||
}
|
||||
|
||||
async function listPullRequestFiles(
|
||||
octokit: Octokit,
|
||||
owner: string,
|
||||
@@ -297,6 +342,13 @@ async function submitReview(
|
||||
mode: ReviewMode;
|
||||
}
|
||||
): Promise<void> {
|
||||
await dismissExistingBotReviews(octokit, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
commitId: params.commitId
|
||||
});
|
||||
|
||||
const validLines = collectValidNewLines(params.files);
|
||||
const filesByPath = new Map(params.files.map((file) => [file.filename, file]));
|
||||
const unpostedFindings: ReviewFinding[] = [];
|
||||
@@ -371,21 +423,12 @@ async function upsertReviewCheckRun(
|
||||
? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}`
|
||||
: params.decision.summary
|
||||
},
|
||||
actions:
|
||||
params.mode === "strict" && conclusion === "action_required"
|
||||
? [
|
||||
{
|
||||
label: "Lenient check",
|
||||
description: "Run only critical runtime checks.",
|
||||
identifier: LENIENT_ACTION_IDENTIFIER
|
||||
}
|
||||
]
|
||||
: undefined
|
||||
details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}`
|
||||
});
|
||||
}
|
||||
|
||||
export function isLenientCheckAction(identifier: string): boolean {
|
||||
return identifier === LENIENT_ACTION_IDENTIFIER;
|
||||
export function isLenientCheckComment(body: string): boolean {
|
||||
return body.trim().startsWith(LENIENT_COMMENT_COMMAND);
|
||||
}
|
||||
|
||||
async function closeMaliciousPullRequest(
|
||||
@@ -439,3 +482,130 @@ async function waitForMergeable(
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
async function dismissExistingBotReviews(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
commitId: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
for (const review of reviews) {
|
||||
if (review.user?.login !== config.botName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (review.commit_id !== params.commitId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!review.id || review.state === "DISMISSED") {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await octokit.rest.pulls.dismissReview({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
review_id: review.id,
|
||||
message: "Superseded by a newer automated review run."
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
reviewId: review.id
|
||||
},
|
||||
"Failed to dismiss existing bot review."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function hasRecentAdminResponse(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pullNumber: number;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
const threshold = Date.now() - ADMIN_RESPONSE_WINDOW_MS;
|
||||
|
||||
const [comments, reviews] = await Promise.all([
|
||||
octokit.paginate(octokit.rest.issues.listComments, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
issue_number: params.pullNumber,
|
||||
per_page: 100
|
||||
}),
|
||||
octokit.paginate(octokit.rest.pulls.listReviews, {
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pull_number: params.pullNumber,
|
||||
per_page: 100
|
||||
})
|
||||
]);
|
||||
|
||||
const actors = new Map<string, number>();
|
||||
|
||||
for (const comment of comments) {
|
||||
const login = comment.user?.login;
|
||||
const createdAt = comment.created_at ? Date.parse(comment.created_at) : NaN;
|
||||
if (!login || Number.isNaN(createdAt) || createdAt < threshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
actors.set(login, Math.max(actors.get(login) ?? 0, createdAt));
|
||||
}
|
||||
|
||||
for (const review of reviews) {
|
||||
const login = review.user?.login;
|
||||
const submittedAt = review.submitted_at ? Date.parse(review.submitted_at) : NaN;
|
||||
if (!login || Number.isNaN(submittedAt) || submittedAt < threshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
actors.set(login, Math.max(actors.get(login) ?? 0, submittedAt));
|
||||
}
|
||||
|
||||
for (const login of actors.keys()) {
|
||||
try {
|
||||
const { data: permission } = await octokit.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
username: login
|
||||
});
|
||||
|
||||
if (permission.permission === "admin") {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
pullNumber: params.pullNumber,
|
||||
login
|
||||
},
|
||||
"Failed to resolve collaborator permission while checking for recent admin response."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import express from "express";
|
||||
import pinoHttpModule from "pino-http";
|
||||
import { config } from "./config.js";
|
||||
import { createGitHubWebhooks } from "./github/webhookHandler.js";
|
||||
import { logger } from "./logger.js";
|
||||
|
||||
const app = express();
|
||||
const webhooks = createGitHubWebhooks();
|
||||
const pinoHttp = pinoHttpModule.default ?? pinoHttpModule;
|
||||
|
||||
app.use(pinoHttp({ logger }));
|
||||
app.get("/healthz", (_request, response) => {
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/webhooks/github", express.raw({ type: "application/json" }), async (request, response) => {
|
||||
const id = request.header("x-github-delivery");
|
||||
const name = request.header("x-github-event");
|
||||
const signature = request.header("x-hub-signature-256");
|
||||
|
||||
if (!id || !name || !signature) {
|
||||
response.status(400).json({ error: "Missing GitHub webhook headers." });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await webhooks.verifyAndReceive({
|
||||
id,
|
||||
name,
|
||||
signature,
|
||||
payload: request.body.toString("utf8")
|
||||
});
|
||||
response.status(202).json({ ok: true });
|
||||
} catch (error) {
|
||||
logger.error({ error }, "Failed to handle webhook.");
|
||||
response.status(400).json({ error: "Invalid or failed webhook." });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(config.port, () => {
|
||||
logger.info({ port: config.port }, "GitHub bot is listening.");
|
||||
});
|
||||
Reference in new issue
Block a user