ai-codereviewer/src/main.ts

218 lines
5.1 KiB
TypeScript
Raw Normal View History

2023-03-22 23:16:13 +02:00
import { readFileSync } from "fs";
import * as core from "@actions/core";
import { Configuration, OpenAIApi } from "openai";
import { Octokit } from "@octokit/rest";
import parseDiff, { Chunk, File } from "parse-diff";
import minimatch from "minimatch";
import { parse } from "csv-parse/sync";
2023-03-22 23:16:13 +02:00
const GITHUB_TOKEN: string = core.getInput("GITHUB_TOKEN");
const OPENAI_API_KEY: string = core.getInput("OPENAI_API_KEY");
const octokit = new Octokit({ auth: GITHUB_TOKEN });
const configuration = new Configuration({
apiKey: OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
interface PRDetails {
owner: string;
repo: string;
pull_number: number;
title: string;
2023-03-23 00:58:11 +02:00
description: string;
2023-03-22 23:16:13 +02:00
}
async function getPRDetails(): Promise<PRDetails> {
const { repository, number } = JSON.parse(
readFileSync(process.env.GITHUB_EVENT_PATH || "", "utf8")
);
2023-03-23 00:58:11 +02:00
const prResponse = await octokit.pulls.get({
owner: repository.owner.login,
repo: repository.name,
pull_number: number,
});
2023-03-22 23:16:13 +02:00
return {
owner: repository.owner.login,
repo: repository.name,
pull_number: number,
title: prResponse.data.title ?? "",
2023-03-23 00:58:11 +02:00
description: prResponse.data.body ?? "",
2023-03-22 23:16:13 +02:00
};
}
async function getDiff(
owner: string,
repo: string,
pull_number: number
): Promise<string | null> {
const response = await octokit.pulls.get({
owner,
repo,
pull_number,
mediaType: { format: "diff" },
});
// @ts-expect-error - response.data is a string
return response.data;
}
async function analyzeCode(
2023-03-23 00:58:11 +02:00
parsedDiff: File[],
prDetails: PRDetails
2023-03-22 23:16:13 +02:00
): Promise<Array<{ body: string; path: string; line: number }>> {
const comments: Array<{ body: string; path: string; line: number }> = [];
for (const file of parsedDiff) {
for (const chunk of file.chunks) {
const prompt = createPrompt(file, chunk, prDetails);
2023-03-22 23:16:13 +02:00
const aiResponse = await getAIResponse(prompt);
if (aiResponse) {
const newComments = createComment(file, chunk, aiResponse);
if (newComments) {
comments.concat(newComments);
2023-03-22 23:16:13 +02:00
}
}
}
}
return comments;
}
function createPrompt(file: File, chunk: Chunk, prDetails: PRDetails): string {
return `Review the following code diff in the file "${
2023-03-22 23:16:13 +02:00
file.to
}" and take the pull request title and description into account when writing the response.
2023-03-23 00:58:11 +02:00
Title: ${prDetails.title}
2023-03-23 00:58:11 +02:00
Description:
---
${prDetails.description}
2023-03-23 00:58:11 +02:00
---
Please provide comments and suggestions ONLY if there is something to improve, write the answer in Github markdown. Don't give positive comments. Use the description only for the overall context and only comment the code.
2023-03-22 23:16:13 +02:00
Diff to review:
\`\`\`diff
2023-03-22 23:16:13 +02:00
${chunk.content}
${chunk.changes.map((c) => c.content).join("\n")}
\`\`\`
Give the answer in following TSV format:
line_number\treview_comment
2023-03-22 23:16:13 +02:00
`;
}
async function getAIResponse(prompt: string): Promise<Array<{
line_number: string;
review_comment: string;
}> | null> {
2023-03-22 23:16:13 +02:00
const queryConfig = {
model: "gpt-4",
temperature: 0.2,
max_tokens: 700,
2023-03-22 23:16:13 +02:00
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
};
try {
const response = await openai.createChatCompletion({
...queryConfig,
messages: [
{
role: "system",
content: prompt,
},
],
});
const res = response.data.choices[0].message?.content?.trim() || "";
return parse(res, {
delimiter: "\t",
columns: ["line_number", "review_comment"],
skip_empty_lines: true,
2023-03-23 19:24:43 +02:00
relax_quotes: true,
});
2023-03-22 23:16:13 +02:00
} catch (error) {
console.error("Error:", error);
return null;
}
}
function createComment(
file: File,
chunk: Chunk,
aiResponses: Array<{
line_number: string;
review_comment: string;
}>
): Array<{ body: string; path: string; line: number }> {
return aiResponses.flatMap((aiResponse) => {
if (!file.to) {
return [];
}
2023-03-22 23:16:13 +02:00
return {
body: aiResponse.review_comment,
2023-03-22 23:16:13 +02:00
path: file.to,
line: Number(aiResponse.line_number),
2023-03-22 23:16:13 +02:00
};
});
2023-03-22 23:16:13 +02:00
}
async function createReviewComment(
owner: string,
repo: string,
pull_number: number,
comments: Array<{ body: string; path: string; line: number }>
): Promise<void> {
await octokit.pulls.createReview({
owner,
repo,
pull_number,
comments,
event: "COMMENT",
});
}
(async function main() {
const prDetails = await getPRDetails();
const diff = await getDiff(
prDetails.owner,
prDetails.repo,
prDetails.pull_number
);
if (!diff) {
console.log("No diff found");
return;
}
const parsedDiff = parseDiff(diff);
const excludePatterns = core
.getInput("exclude")
.split(",")
.map((s) => s.trim());
const filteredDiff = parsedDiff.filter((file) => {
return !excludePatterns.some((pattern) =>
minimatch(file.to ?? "", pattern)
);
});
const comments = await analyzeCode(filteredDiff, prDetails);
2023-03-22 23:16:13 +02:00
if (comments.length > 0) {
await createReviewComment(
prDetails.owner,
prDetails.repo,
prDetails.pull_number,
comments
);
}
})().catch((error) => {
console.error("Error:", error);
process.exit(1);
});