refactor: extract event router and bump version to v1.2.0 (7.1)
Decouple Actions event dispatching from runReview.ts into a pluggable EventRouter with independent handlers for pull_request_target, issues, issue_comment, pull_request_review, and schedule. Add unit tests. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
9ad6b58398
commit
db53296d78
5 files changed
+464
-254
No files matched your search
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ghbot",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ghbot",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.864.0",
|
||||
"@octokit/auth-app": "^8.2.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ghbot",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import { config } from "../config.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import { processPullRequestChat } from "../chat/processor.js";
|
||||
import { processIssueTriage, processPullRequestTriage } from "../triage/processor.js";
|
||||
import { deleteLocalReviewCache } from "../review/cache.js";
|
||||
import {
|
||||
beginCommitReviewProgress,
|
||||
finishCommitReviewProgress,
|
||||
processConflictComment,
|
||||
processRecheckComment,
|
||||
processPullRequest,
|
||||
processScheduledPendingMerges,
|
||||
processPullRequestReviewApproval,
|
||||
shouldReviewPullRequest
|
||||
} from "../review/processor.js";
|
||||
|
||||
export type EventContext = {
|
||||
eventName: string;
|
||||
action?: string;
|
||||
payload: Record<string, unknown>;
|
||||
octokit: Octokit;
|
||||
gitToken?: string;
|
||||
};
|
||||
|
||||
export type EventHandler = {
|
||||
name: string;
|
||||
canHandle: (eventName: string, action?: string) => boolean;
|
||||
handle: (context: EventContext) => Promise<void>;
|
||||
};
|
||||
|
||||
export class EventRouter {
|
||||
private readonly handlers: EventHandler[] = [];
|
||||
|
||||
register(handler: EventHandler): this {
|
||||
this.handlers.push(handler);
|
||||
return this;
|
||||
}
|
||||
|
||||
async dispatch(context: EventContext): Promise<{ handled: boolean; handlerName?: string }> {
|
||||
for (const handler of this.handlers) {
|
||||
if (handler.canHandle(context.eventName, context.action)) {
|
||||
logger.info(
|
||||
{ eventName: context.eventName, action: context.action, handler: handler.name },
|
||||
"Dispatching event to registered handler."
|
||||
);
|
||||
await handler.handle(context);
|
||||
return { handled: true, handlerName: handler.name };
|
||||
}
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
{ eventName: context.eventName, action: context.action },
|
||||
"No registered handler matched the event."
|
||||
);
|
||||
return { handled: false };
|
||||
}
|
||||
}
|
||||
|
||||
type GitHubRepository = {
|
||||
id?: number;
|
||||
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: {
|
||||
id: number;
|
||||
body: string;
|
||||
user: {
|
||||
login: string;
|
||||
type?: string;
|
||||
};
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type IssuePayload = {
|
||||
action: string;
|
||||
issue: {
|
||||
number: number;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type PullRequestReviewPayload = {
|
||||
action: string;
|
||||
review: {
|
||||
state: string;
|
||||
commit_id: string;
|
||||
user?: {
|
||||
login?: string;
|
||||
};
|
||||
};
|
||||
pull_request: {
|
||||
number: number;
|
||||
};
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type ScheduledPayload = {
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
export function buildDefaultEventRouter(): EventRouter {
|
||||
const router = new EventRouter();
|
||||
|
||||
// 1. Pull Request Target
|
||||
router.register({
|
||||
name: "pull-request-target",
|
||||
canHandle: (eventName) => eventName === "pull_request_target",
|
||||
handle: async (ctx) => {
|
||||
const prPayload = ctx.payload as unknown as PullRequestPayload;
|
||||
const ref = {
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
pullNumber: prPayload.pull_request.number
|
||||
};
|
||||
|
||||
if (["opened", "edited", "reopened"].includes(prPayload.action)) {
|
||||
try {
|
||||
await processPullRequestTriage(ctx.octokit, {
|
||||
owner: ref.owner,
|
||||
repo: ref.repo,
|
||||
pullNumber: ref.pullNumber
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ error, ...ref },
|
||||
"Pull request triage failed; continuing with code review."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await shouldReviewPullRequest(ctx.octokit, ref))) {
|
||||
await deleteLocalReviewCache(ref.pullNumber);
|
||||
logger.info({ ...ref }, "Skipping pull request event outside REVIEW_BRANCHES.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (prPayload.action === "opened") {
|
||||
await withRetry("github.issues.createComment.started", async () => {
|
||||
return ctx.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."
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const progress =
|
||||
prPayload.action === "synchronize"
|
||||
? await beginCommitReviewProgress(ctx.octokit, ref).catch((progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review start progress; continuing review."
|
||||
);
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
try {
|
||||
await processPullRequest(
|
||||
ctx.octokit,
|
||||
ref,
|
||||
config.reviewStrictness === "strict" ? "strict" : "normal",
|
||||
ctx.gitToken
|
||||
);
|
||||
} catch (error) {
|
||||
if (progress) {
|
||||
await finishCommitReviewProgress(ctx.octokit, {
|
||||
...ref,
|
||||
...progress,
|
||||
failed: true
|
||||
}).catch((progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review failure progress."
|
||||
);
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (progress) {
|
||||
await finishCommitReviewProgress(ctx.octokit, { ...ref, ...progress }).catch(
|
||||
(progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review completion progress."
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Issues
|
||||
router.register({
|
||||
name: "issues-triage",
|
||||
canHandle: (eventName) => eventName === "issues",
|
||||
handle: async (ctx) => {
|
||||
const issuePayload = ctx.payload as unknown as IssuePayload;
|
||||
if (["opened", "edited", "reopened"].includes(issuePayload.action)) {
|
||||
await processIssueTriage(ctx.octokit, {
|
||||
owner: issuePayload.repository.owner.login,
|
||||
repo: issuePayload.repository.name,
|
||||
issueNumber: issuePayload.issue.number
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Issue Comment
|
||||
router.register({
|
||||
name: "issue-comment",
|
||||
canHandle: (eventName) => eventName === "issue_comment",
|
||||
handle: async (ctx) => {
|
||||
const commentPayload = ctx.payload as unknown 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;
|
||||
}
|
||||
|
||||
if (commentPayload.comment.user?.type === "Bot") {
|
||||
logger.info(
|
||||
{ issueNumber: commentPayload.issue.number, login: commentPayload.comment.user.login },
|
||||
"Skipping bot-authored comment to prevent automation loops."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const commentTasks: Array<[string, () => Promise<void>]> = [
|
||||
[
|
||||
"recheck",
|
||||
() =>
|
||||
processRecheckComment(ctx.octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body,
|
||||
gitToken: ctx.gitToken
|
||||
})
|
||||
],
|
||||
[
|
||||
"conflict",
|
||||
() =>
|
||||
processConflictComment(ctx.octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body,
|
||||
gitToken: ctx.gitToken
|
||||
})
|
||||
],
|
||||
[
|
||||
"chat",
|
||||
() =>
|
||||
processPullRequestChat(ctx.octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body
|
||||
})
|
||||
]
|
||||
];
|
||||
|
||||
const results = await Promise.allSettled(commentTasks.map(([, run]) => run()));
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === "rejected") {
|
||||
const [label] = commentTasks[index]!;
|
||||
logger.error(
|
||||
{ error: result.reason, task: label, issueNumber: commentPayload.issue.number },
|
||||
"Comment command handler failed; other handlers still ran."
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const rejectedResults = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected"
|
||||
);
|
||||
if (rejectedResults.length > 0) {
|
||||
throw new AggregateError(
|
||||
rejectedResults.map((result) => result.reason),
|
||||
"One or more issue comment handlers failed; GitHub Actions should retry this delivery."
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 4. Pull Request Review
|
||||
router.register({
|
||||
name: "pull-request-review-approval",
|
||||
canHandle: (eventName: string) => eventName === "pull_request_review",
|
||||
handle: async (ctx: EventContext) => {
|
||||
const reviewPayload = ctx.payload as unknown 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(ctx.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
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 5. Schedule
|
||||
router.register({
|
||||
name: "schedule-pending-merges",
|
||||
canHandle: (eventName: string) => eventName === "schedule",
|
||||
handle: async (ctx: EventContext) => {
|
||||
const scheduledPayload = ctx.payload as unknown as ScheduledPayload;
|
||||
await processScheduledPendingMerges(ctx.octokit, {
|
||||
owner: scheduledPayload.repository.owner.login,
|
||||
repo: scheduledPayload.repository.name
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
+23
-251
@@ -2,22 +2,9 @@ import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
import { createGitHubCredentials } from "../github/client.js";
|
||||
import { createEventLogger, logger } from "../logger.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import { processPullRequestChat } from "../chat/processor.js";
|
||||
import { processIssueTriage, processPullRequestTriage } from "../triage/processor.js";
|
||||
import { deleteLocalReviewCache } from "../review/cache.js";
|
||||
import { loadRepositoryKnowledge } from "../repository/knowledge.js";
|
||||
import {
|
||||
beginCommitReviewProgress,
|
||||
finishCommitReviewProgress,
|
||||
processConflictComment,
|
||||
processRecheckComment,
|
||||
processPullRequest,
|
||||
processScheduledPendingMerges,
|
||||
processPullRequestReviewApproval,
|
||||
shouldReviewPullRequest
|
||||
} from "../review/processor.js";
|
||||
import { restorePersistentCache, savePersistentCache } from "../storage/cacheStore.js";
|
||||
import { buildDefaultEventRouter } from "./router.js";
|
||||
|
||||
type GitHubRepository = {
|
||||
id?: number;
|
||||
@@ -83,6 +70,13 @@ type ScheduledPayload = {
|
||||
repository: GitHubRepository;
|
||||
};
|
||||
|
||||
type GitHubEventPayload =
|
||||
| PullRequestPayload
|
||||
| IssuePayload
|
||||
| IssueCommentPayload
|
||||
| PullRequestReviewPayload
|
||||
| ScheduledPayload;
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const workflowCallEventName = process.env.GHBOT_EVENT_NAME;
|
||||
const payload = workflowCallEventName
|
||||
@@ -141,216 +135,19 @@ async function main(): Promise<void> {
|
||||
|
||||
let eventFailed = false;
|
||||
try {
|
||||
if (eventName === "pull_request_target") {
|
||||
const prPayload = payload as PullRequestPayload;
|
||||
const ref = {
|
||||
owner: prPayload.repository.owner.login,
|
||||
repo: prPayload.repository.name,
|
||||
pullNumber: prPayload.pull_request.number
|
||||
};
|
||||
const router = buildDefaultEventRouter();
|
||||
const action = "action" in payload ? payload.action : undefined;
|
||||
const dispatchResult = await router.dispatch({
|
||||
eventName,
|
||||
action,
|
||||
payload: payload as unknown as Record<string, unknown>,
|
||||
octokit,
|
||||
gitToken: github.token
|
||||
});
|
||||
|
||||
if (["opened", "edited", "reopened"].includes(prPayload.action)) {
|
||||
try {
|
||||
await processPullRequestTriage(octokit, {
|
||||
owner: ref.owner,
|
||||
repo: ref.repo,
|
||||
pullNumber: ref.pullNumber
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ error, ...ref },
|
||||
"Pull request triage failed; continuing with code review."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await shouldReviewPullRequest(octokit, ref))) {
|
||||
await deleteLocalReviewCache(ref.pullNumber);
|
||||
logger.info({ ...ref }, "Skipping pull request event outside REVIEW_BRANCHES.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (prPayload.action === "opened") {
|
||||
await withRetry("github.issues.createComment.started", async () => {
|
||||
return 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."
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const progress =
|
||||
prPayload.action === "synchronize"
|
||||
? await beginCommitReviewProgress(octokit, ref).catch((progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review start progress; continuing review."
|
||||
);
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
try {
|
||||
await processPullRequest(
|
||||
octokit,
|
||||
ref,
|
||||
config.reviewStrictness === "strict" ? "strict" : "normal",
|
||||
github.token
|
||||
);
|
||||
} catch (error) {
|
||||
if (progress) {
|
||||
await finishCommitReviewProgress(octokit, { ...ref, ...progress, failed: true }).catch(
|
||||
(progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review failure progress."
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (progress) {
|
||||
await finishCommitReviewProgress(octokit, { ...ref, ...progress }).catch(
|
||||
(progressError: unknown) => {
|
||||
logger.warn(
|
||||
{ error: progressError, ...ref },
|
||||
"Failed to publish review completion progress."
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
return;
|
||||
if (!dispatchResult.handled) {
|
||||
logger.warn({ eventName }, "Unhandled GitHub Actions event.");
|
||||
}
|
||||
|
||||
if (eventName === "issues") {
|
||||
const issuePayload = payload as IssuePayload;
|
||||
if (["opened", "edited", "reopened"].includes(issuePayload.action)) {
|
||||
await processIssueTriage(octokit, {
|
||||
owner: issuePayload.repository.owner.login,
|
||||
repo: issuePayload.repository.name,
|
||||
issueNumber: issuePayload.issue.number
|
||||
});
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
if (commentPayload.comment.user?.type === "Bot") {
|
||||
logger.info(
|
||||
{ issueNumber: commentPayload.issue.number, login: commentPayload.comment.user.login },
|
||||
"Skipping bot-authored comment to prevent automation loops."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// The three comment commands are independent features; one failing or
|
||||
// not matching must not prevent the others from running.
|
||||
const commentTasks: Array<[string, () => Promise<void>]> = [
|
||||
[
|
||||
"recheck",
|
||||
() =>
|
||||
processRecheckComment(octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body,
|
||||
gitToken: github.token
|
||||
})
|
||||
],
|
||||
[
|
||||
"conflict",
|
||||
() =>
|
||||
processConflictComment(octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body,
|
||||
gitToken: github.token
|
||||
})
|
||||
],
|
||||
[
|
||||
"chat",
|
||||
() =>
|
||||
processPullRequestChat(octokit, {
|
||||
owner: commentPayload.repository.owner.login,
|
||||
repo: commentPayload.repository.name,
|
||||
pullNumber: commentPayload.issue.number,
|
||||
commentId: commentPayload.comment.id,
|
||||
commenterLogin: commentPayload.comment.user.login,
|
||||
commentBody: commentPayload.comment.body
|
||||
})
|
||||
]
|
||||
];
|
||||
|
||||
const results = await Promise.allSettled(commentTasks.map(([, run]) => run()));
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === "rejected") {
|
||||
const [label] = commentTasks[index]!;
|
||||
logger.error(
|
||||
{ error: result.reason, task: label, issueNumber: commentPayload.issue.number },
|
||||
"Comment command handler failed; other handlers still ran."
|
||||
);
|
||||
}
|
||||
});
|
||||
const rejectedResults = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected"
|
||||
);
|
||||
if (rejectedResults.length > 0) {
|
||||
throw new AggregateError(
|
||||
rejectedResults.map((result) => result.reason),
|
||||
"One or more issue comment handlers failed; GitHub Actions should retry this delivery."
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
if (eventName === "schedule") {
|
||||
const scheduledPayload = payload as ScheduledPayload;
|
||||
await processScheduledPendingMerges(octokit, {
|
||||
owner: scheduledPayload.repository.owner.login,
|
||||
repo: scheduledPayload.repository.name
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warn({ eventName }, "Unhandled GitHub Actions event.");
|
||||
} catch (error) {
|
||||
eventFailed = true;
|
||||
throw error;
|
||||
@@ -381,15 +178,7 @@ async function main(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function getPullNumberForCache(
|
||||
eventName: string,
|
||||
payload:
|
||||
| PullRequestPayload
|
||||
| IssuePayload
|
||||
| IssueCommentPayload
|
||||
| PullRequestReviewPayload
|
||||
| ScheduledPayload
|
||||
): number | undefined {
|
||||
function getPullNumberForCache(eventName: string, payload: GitHubEventPayload): number | undefined {
|
||||
if (eventName === "pull_request_target") {
|
||||
return (payload as PullRequestPayload).pull_request.number;
|
||||
}
|
||||
@@ -403,33 +192,16 @@ function getPullNumberForCache(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readPayloadFromGitHubEventPath():
|
||||
| PullRequestPayload
|
||||
| IssuePayload
|
||||
| IssueCommentPayload
|
||||
| PullRequestReviewPayload
|
||||
| ScheduledPayload {
|
||||
function readPayloadFromGitHubEventPath(): GitHubEventPayload {
|
||||
const eventPath = process.env.GITHUB_EVENT_PATH;
|
||||
if (!eventPath) {
|
||||
throw new Error("GITHUB_EVENT_PATH is required when workflow_call inputs are not provided.");
|
||||
}
|
||||
|
||||
return JSON.parse(fs.readFileSync(eventPath, "utf8")) as
|
||||
| PullRequestPayload
|
||||
| IssuePayload
|
||||
| IssueCommentPayload
|
||||
| PullRequestReviewPayload
|
||||
| ScheduledPayload;
|
||||
return JSON.parse(fs.readFileSync(eventPath, "utf8")) as GitHubEventPayload;
|
||||
}
|
||||
|
||||
function buildPayloadFromWorkflowCallEnv(
|
||||
eventName: string
|
||||
):
|
||||
| PullRequestPayload
|
||||
| IssuePayload
|
||||
| IssueCommentPayload
|
||||
| PullRequestReviewPayload
|
||||
| ScheduledPayload {
|
||||
function buildPayloadFromWorkflowCallEnv(eventName: string): GitHubEventPayload {
|
||||
const action = process.env.GHBOT_EVENT_ACTION;
|
||||
const owner = process.env.GHBOT_REPOSITORY_OWNER;
|
||||
const repo = process.env.GHBOT_REPOSITORY_NAME;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
import { EventRouter, type EventContext, type EventHandler } from "../src/actions/router.js";
|
||||
|
||||
const dummyOctokit = {} as Octokit;
|
||||
|
||||
test("EventRouter registers and dispatches matching events", async () => {
|
||||
const router = new EventRouter();
|
||||
const handledEvents: string[] = [];
|
||||
|
||||
const prHandler: EventHandler = {
|
||||
name: "pull-request-handler",
|
||||
canHandle: (eventName) => eventName === "pull_request_target",
|
||||
handle: async (ctx) => {
|
||||
handledEvents.push(`${ctx.eventName}:${ctx.action}`);
|
||||
}
|
||||
};
|
||||
|
||||
router.register(prHandler);
|
||||
|
||||
const context: EventContext = {
|
||||
eventName: "pull_request_target",
|
||||
action: "opened",
|
||||
payload: { pull_request: { number: 1 } },
|
||||
octokit: dummyOctokit
|
||||
};
|
||||
|
||||
const result = await router.dispatch(context);
|
||||
assert.equal(result.handled, true);
|
||||
assert.equal(result.handlerName, "pull-request-handler");
|
||||
assert.deepEqual(handledEvents, ["pull_request_target:opened"]);
|
||||
});
|
||||
|
||||
test("EventRouter returns handled=false when no handler matches", async () => {
|
||||
const router = new EventRouter();
|
||||
const context: EventContext = {
|
||||
eventName: "unknown_event",
|
||||
payload: {},
|
||||
octokit: dummyOctokit
|
||||
};
|
||||
|
||||
const result = await router.dispatch(context);
|
||||
assert.equal(result.handled, false);
|
||||
assert.equal(result.handlerName, undefined);
|
||||
});
|
||||
|
||||
test("EventRouter respects handler registration order", async () => {
|
||||
const router = new EventRouter();
|
||||
const order: string[] = [];
|
||||
|
||||
router.register({
|
||||
name: "first-handler",
|
||||
canHandle: (name) => name === "issue_comment",
|
||||
handle: async () => {
|
||||
order.push("first");
|
||||
}
|
||||
});
|
||||
|
||||
router.register({
|
||||
name: "second-handler",
|
||||
canHandle: (name) => name === "issue_comment",
|
||||
handle: async () => {
|
||||
order.push("second");
|
||||
}
|
||||
});
|
||||
|
||||
const result = await router.dispatch({
|
||||
eventName: "issue_comment",
|
||||
payload: {},
|
||||
octokit: dummyOctokit
|
||||
});
|
||||
|
||||
assert.equal(result.handled, true);
|
||||
assert.equal(result.handlerName, "first-handler");
|
||||
assert.deepEqual(order, ["first"]);
|
||||
});
|
||||
Reference in new issue
Block a user