repackage

This commit is contained in:
Ville Saukkonen 2023-07-31 18:24:34 +03:00
parent d3abad1bc9
commit 2821669598
2 changed files with 175 additions and 256 deletions

429
dist/index.js vendored

@ -6,88 +6,41 @@ require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap
"use strict"; "use strict";
var __createBinding = var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
(this && this.__createBinding) || if (k2 === undefined) k2 = k;
(Object.create var desc = Object.getOwnPropertyDescriptor(m, k);
? function (o, m, k, k2) { if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
if (k2 === undefined) k2 = k; desc = { enumerable: true, get: function() { return m[k]; } };
var desc = Object.getOwnPropertyDescriptor(m, k); }
if ( Object.defineProperty(o, k2, desc);
!desc || }) : (function(o, m, k, k2) {
("get" in desc ? !m.__esModule : desc.writable || desc.configurable) if (k2 === undefined) k2 = k;
) { o[k2] = m[k];
desc = { }));
enumerable: true, var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
get: function () { Object.defineProperty(o, "default", { enumerable: true, value: v });
return m[k]; }) : function(o, v) {
}, o["default"] = v;
}; });
} var __importStar = (this && this.__importStar) || function (mod) {
Object.defineProperty(o, k2, desc);
}
: function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault =
(this && this.__setModuleDefault) ||
(Object.create
? function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}
: function (o, v) {
o["default"] = v;
});
var __importStar =
(this && this.__importStar) ||
function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
__setModuleDefault(result, mod); __setModuleDefault(result, mod);
return result; return result;
}; };
var __awaiter = var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
(this && this.__awaiter) || function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
function (thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P
? value
: new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
try { function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
step(generator.next(value)); function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
} catch (e) { step((generator = generator.apply(thisArg, _arguments || [])).next());
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done
? resolve(result.value)
: adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importDefault = var __importDefault = (this && this.__importDefault) || function (mod) {
(this && this.__importDefault) || return (mod && mod.__esModule) ? mod : { "default": mod };
function (mod) { };
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const fs_1 = __nccwpck_require__(7147); const fs_1 = __nccwpck_require__(7147);
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
@ -97,79 +50,76 @@ const parse_diff_1 = __importDefault(__nccwpck_require__(4833));
const minimatch_1 = __importDefault(__nccwpck_require__(2002)); const minimatch_1 = __importDefault(__nccwpck_require__(2002));
const GITHUB_TOKEN = core.getInput("GITHUB_TOKEN"); const GITHUB_TOKEN = core.getInput("GITHUB_TOKEN");
const OPENAI_API_KEY = core.getInput("OPENAI_API_KEY"); const OPENAI_API_KEY = core.getInput("OPENAI_API_KEY");
const OPENAI_API_MODEL = core.getInput("OPENAI_API_MODEL");
const octokit = new rest_1.Octokit({ auth: GITHUB_TOKEN }); const octokit = new rest_1.Octokit({ auth: GITHUB_TOKEN });
const configuration = new openai_1.Configuration({ const configuration = new openai_1.Configuration({
apiKey: OPENAI_API_KEY, apiKey: OPENAI_API_KEY,
}); });
const openai = new openai_1.OpenAIApi(configuration); const openai = new openai_1.OpenAIApi(configuration);
function getPRDetails() { function getPRDetails() {
var _a, _b; var _a, _b;
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const { repository, number } = JSON.parse( const { repository, number } = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH || "", "utf8"));
(0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH || "", "utf8") const prResponse = yield octokit.pulls.get({
); owner: repository.owner.login,
const prResponse = yield octokit.pulls.get({ repo: repository.name,
owner: repository.owner.login, pull_number: number,
repo: repository.name, });
pull_number: number, return {
owner: repository.owner.login,
repo: repository.name,
pull_number: number,
title: (_a = prResponse.data.title) !== null && _a !== void 0 ? _a : "",
description: (_b = prResponse.data.body) !== null && _b !== void 0 ? _b : "",
};
}); });
return {
owner: repository.owner.login,
repo: repository.name,
pull_number: number,
title: (_a = prResponse.data.title) !== null && _a !== void 0 ? _a : "",
description:
(_b = prResponse.data.body) !== null && _b !== void 0 ? _b : "",
};
});
} }
function getDiff(owner, repo, pull_number) { function getDiff(owner, repo, pull_number) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const response = yield octokit.pulls.get({ const response = yield octokit.pulls.get({
owner, owner,
repo, repo,
pull_number, pull_number,
mediaType: { format: "diff" }, mediaType: { format: "diff" },
});
// @ts-expect-error - response.data is a string
return response.data;
}); });
// @ts-expect-error - response.data is a string
return response.data;
});
} }
function analyzeCode(parsedDiff, prDetails) { function analyzeCode(parsedDiff, prDetails) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const comments = []; const comments = [];
for (const file of parsedDiff) { for (const file of parsedDiff) {
if (file.to === "/dev/null") continue; // Ignore deleted files if (file.to === "/dev/null")
for (const chunk of file.chunks) { continue; // Ignore deleted files
const prompt = createPrompt(file, chunk, prDetails); for (const chunk of file.chunks) {
const aiResponse = yield getAIResponse(prompt); const prompt = createPrompt(file, chunk, prDetails);
if (aiResponse) { const aiResponse = yield getAIResponse(prompt);
const newComments = createComment(file, chunk, aiResponse); if (aiResponse) {
if (newComments) { const newComments = createComment(file, chunk, aiResponse);
comments.push(...newComments); if (newComments) {
} comments.push(...newComments);
}
}
}
} }
} return comments;
} });
return comments;
});
} }
function getBaseAndHeadShas(owner, repo, pull_number) { function getBaseAndHeadShas(owner, repo, pull_number) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const prResponse = yield octokit.pulls.get({ const prResponse = yield octokit.pulls.get({
owner, owner,
repo, repo,
pull_number, pull_number,
});
return {
baseSha: prResponse.data.base.sha,
headSha: prResponse.data.head.sha,
};
}); });
return {
baseSha: prResponse.data.base.sha,
headSha: prResponse.data.head.sha,
};
});
} }
function createPrompt(file, chunk, prDetails) { function createPrompt(file, chunk, prDetails) {
return `Your task is to review pull requests. Instructions: return `Your task is to review pull requests. Instructions:
- Provide the response in following JSON format: [{"lineNumber": <line_number>, "reviewComment": "<review comment>"}] - Provide the response in following JSON format: [{"lineNumber": <line_number>, "reviewComment": "<review comment>"}]
- Do not give positive comments or compliments. - Do not give positive comments or compliments.
- Provide comments and suggestions ONLY if there is something to improve, otherwise return an empty array. - Provide comments and suggestions ONLY if there is something to improve, otherwise return an empty array.
@ -177,9 +127,7 @@ function createPrompt(file, chunk, prDetails) {
- Use the given description only for the overall context and only comment the code. - Use the given description only for the overall context and only comment the code.
- IMPORTANT: NEVER suggest adding comments to the code. - IMPORTANT: NEVER suggest adding comments to the code.
Review the following code diff in the file "${ Review the following code diff in the file "${file.to}" and take the pull request title and description into account when writing the response.
file.to
}" and take the pull request title and description into account when writing the response.
Pull request title: ${prDetails.title} Pull request title: ${prDetails.title}
Pull request description: Pull request description:
@ -193,140 +141,111 @@ Git diff to review:
\`\`\`diff \`\`\`diff
${chunk.content} ${chunk.content}
${chunk.changes ${chunk.changes
// @ts-expect-error - ln and ln2 exists where needed // @ts-expect-error - ln and ln2 exists where needed
.map((c) => `${c.ln ? c.ln : c.ln2} ${c.content}`) .map((c) => `${c.ln ? c.ln : c.ln2} ${c.content}`)
.join("\n")} .join("\n")}
\`\`\` \`\`\`
`; `;
} }
function getAIResponse(prompt) { function getAIResponse(prompt) {
var _a, _b; var _a, _b;
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const queryConfig = { const queryConfig = {
model: OPENAI_API_MODEL, model: "gpt-4",
temperature: 0.2, temperature: 0.2,
max_tokens: 700, max_tokens: 700,
top_p: 1, top_p: 1,
frequency_penalty: 0, frequency_penalty: 0,
presence_penalty: 0, presence_penalty: 0,
}; };
try { try {
const response = yield openai.createChatCompletion( const response = yield openai.createChatCompletion(Object.assign(Object.assign({}, queryConfig), { messages: [
Object.assign(Object.assign({}, queryConfig), { {
messages: [ role: "system",
{ content: prompt,
role: "system", },
content: prompt, ] }));
}, const res = ((_b = (_a = response.data.choices[0].message) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.trim()) || "[]";
], return JSON.parse(res);
}) }
); catch (error) {
const res = console.error("Error:", error);
((_b = return null;
(_a = response.data.choices[0].message) === null || _a === void 0 }
? void 0 });
: _a.content) === null || _b === void 0
? void 0
: _b.trim()) || "[]";
return JSON.parse(res);
} catch (error) {
console.error("Error:", error);
return null;
}
});
} }
function createComment(file, chunk, aiResponses) { function createComment(file, chunk, aiResponses) {
return aiResponses.flatMap((aiResponse) => { return aiResponses.flatMap((aiResponse) => {
if (!file.to) { if (!file.to) {
return []; return [];
} }
return { return {
body: aiResponse.reviewComment, body: aiResponse.reviewComment,
path: file.to, path: file.to,
line: Number(aiResponse.lineNumber), line: Number(aiResponse.lineNumber),
}; };
}); });
} }
function createReviewComment(owner, repo, pull_number, comments) { function createReviewComment(owner, repo, pull_number, comments) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
yield octokit.pulls.createReview({ yield octokit.pulls.createReview({
owner, owner,
repo, repo,
pull_number, pull_number,
comments, comments,
event: "COMMENT", event: "COMMENT",
});
}); });
});
} }
function main() { function main() {
var _a; var _a;
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const prDetails = yield getPRDetails(); const prDetails = yield getPRDetails();
let diff; let diff;
const eventData = JSON.parse( const eventData = JSON.parse((0, fs_1.readFileSync)((_a = process.env.GITHUB_EVENT_PATH) !== null && _a !== void 0 ? _a : "", "utf8"));
(0, fs_1.readFileSync)( if (eventData.action === "opened") {
(_a = process.env.GITHUB_EVENT_PATH) !== null && _a !== void 0 diff = yield getDiff(prDetails.owner, prDetails.repo, prDetails.pull_number);
? _a }
: "", else if (eventData.action === "synchronize") {
"utf8" const newBaseSha = eventData.before;
) const newHeadSha = eventData.after;
); const response = yield octokit.repos.compareCommits({
if (eventData.action === "opened") { owner: prDetails.owner,
diff = yield getDiff( repo: prDetails.repo,
prDetails.owner, base: newBaseSha,
prDetails.repo, head: newHeadSha,
prDetails.pull_number });
); diff = response.data.diff_url
} else if (eventData.action === "synchronize") { ? yield octokit
const newBaseSha = eventData.before; .request({ url: response.data.diff_url })
const newHeadSha = eventData.after; .then((res) => res.data)
const response = yield octokit.repos.compareCommits({ : null;
owner: prDetails.owner, }
repo: prDetails.repo, else {
base: newBaseSha, console.log("Unsupported event:", process.env.GITHUB_EVENT_NAME);
head: newHeadSha, return;
}); }
diff = response.data.diff_url if (!diff) {
? yield octokit console.log("No diff found");
.request({ url: response.data.diff_url }) return;
.then((res) => res.data) }
: null; const parsedDiff = (0, parse_diff_1.default)(diff);
} else { const excludePatterns = core
console.log("Unsupported event:", process.env.GITHUB_EVENT_NAME); .getInput("exclude")
return; .split(",")
} .map((s) => s.trim());
if (!diff) { const filteredDiff = parsedDiff.filter((file) => {
console.log("No diff found"); return !excludePatterns.some((pattern) => { var _a; return (0, minimatch_1.default)((_a = file.to) !== null && _a !== void 0 ? _a : "", pattern); });
return; });
} const comments = yield analyzeCode(filteredDiff, prDetails);
const parsedDiff = (0, parse_diff_1.default)(diff); if (comments.length > 0) {
const excludePatterns = core yield createReviewComment(prDetails.owner, prDetails.repo, prDetails.pull_number, comments);
.getInput("exclude") }
.split(",")
.map((s) => s.trim());
const filteredDiff = parsedDiff.filter((file) => {
return !excludePatterns.some((pattern) => {
var _a;
return (0, minimatch_1.default)(
(_a = file.to) !== null && _a !== void 0 ? _a : "",
pattern
);
});
}); });
const comments = yield analyzeCode(filteredDiff, prDetails);
if (comments.length > 0) {
yield createReviewComment(
prDetails.owner,
prDetails.repo,
prDetails.pull_number,
comments
);
}
});
} }
main().catch((error) => { main().catch((error) => {
console.error("Error:", error); console.error("Error:", error);
process.exit(1); process.exit(1);
}); });

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long