Compare commits

...

79 commits
v0.4 ... main

Author SHA1 Message Date
vandanafuletra
5f5f9bdc32
Merge pull request #41 from ingress-it-solutions/dev
Fixed issue
2023-12-25 02:41:03 +05:30
Palzin
4dd06053c1 Fixed issue 2023-12-25 02:39:59 +05:30
vandanafuletra
e556ff6977
Merge pull request #40 from ingress-it-solutions/dev
Fixed issue
2023-12-24 23:32:41 +05:30
Palzin
051f393777 Fixed issue 2023-12-24 23:30:36 +05:30
vandanafuletra
6214dcc4b2
Merge pull request #39 from ingress-it-solutions/dev
Fixed issue
2023-12-24 21:14:40 +05:30
Palzin
364a45cd88 Fixed issue 2023-12-24 21:13:28 +05:30
vandanafuletra
252a3bca62
Merge pull request #38 from ingress-it-solutions/dev
Laravel Specific
2023-12-24 03:21:07 +05:30
Palzin
75cce8d916 Laravel Specific 2023-12-24 03:20:31 +05:30
vandanafuletra
be18a2bc3e
Merge pull request #37 from ingress-it-solutions/dev
Laravel Specific
2023-12-24 03:04:14 +05:30
Palzin
35136c692a Laravel Specific 2023-12-24 03:03:44 +05:30
vandanafuletra
2e341dc40b
Merge pull request #36 from ingress-it-solutions/dev
Laravel Specific
2023-12-24 03:00:40 +05:30
Palzin
821c27694a Laravel Specific 2023-12-24 02:53:52 +05:30
vandanafuletra
25b8f474bf
Merge pull request #35 from ingress-it-solutions/dev
Fixed Summary
2023-05-12 00:55:27 +05:30
Bhavik MacBook PRO 16
516838857f Fixed Summary 2023-05-12 00:52:45 +05:30
vandanafuletra
c29eccff0d
Merge pull request #34 from ingress-it-solutions/dev
Dev
2023-05-12 00:52:38 +05:30
Bhavik MacBook PRO 16
4343cd8199 Fixed Summary 2023-05-12 00:47:23 +05:30
Bhavik MacBook PRO 16
dd021fad57 Fixed Summary 2023-05-12 00:45:49 +05:30
Bhavik MacBook PRO 16
d4a62d85e9 Add more clear summary 2023-05-12 00:28:05 +05:30
Bhavik MacBook PRO 16
7ec1de5dbb Add more clear summary 2023-05-12 00:22:30 +05:30
Bhavik MacBook PRO 16
675e4b4581 Add more clear summary 2023-05-12 00:16:03 +05:30
Bhavik MacBook PRO 16
1f559fdb0c Resolved COnflict 2023-05-12 00:13:13 +05:30
Bhavik MacBook PRO 16
22776a9570 Added more descriptive summary for OpenAI 2023-05-12 00:09:19 +05:30
Bhavik MacBook PRO 16
b5d09bfea3 Added Joke and summary in bullet point 2023-05-07 06:40:58 +05:30
vandanafuletra
054efac0f9
Merge pull request #28 from ingress-it-solutions/dev
Dev
2023-05-07 06:28:40 +05:30
Bhavik MacBook PRO 16
179983f8bc Added Joke and summary in bullet point 2023-05-07 06:25:21 +05:30
Bhavik MacBook PRO 16
9f57ed91c6 Added Joke and summary in bullet point 2023-05-07 06:23:03 +05:30
Bhavik MacBook PRO 16
2d91f8d6ba Added Joke and summary in bullet point 2023-05-07 06:20:28 +05:30
Bhavik MacBook PRO 16
0d2c101877 Added Joke and summary in bullet point 2023-05-07 06:18:45 +05:30
vandanafuletra
bac2279d61
Merge pull request #24 from ingress-it-solutions/dev
Fixed issue with Comment on Gitea
2023-04-23 19:34:43 +05:30
Bhavik MacBook PRO 16
015e6a0826 Fixed issue with Comment on Gitea 2023-04-23 19:34:08 +05:30
vandanafuletra
9d0ca9add3
Merge pull request #23 from ingress-it-solutions/dev
Fixed issue with Comment on Gitea
2023-04-23 19:18:49 +05:30
Bhavik MacBook PRO 16
ba5b9a6177 Fixed issue with Comment on Gitea 2023-04-23 19:18:20 +05:30
vandanafuletra
e080dfe7b5
Merge pull request #22 from ingress-it-solutions/dev
Dev
2023-04-23 19:03:22 +05:30
Bhavik MacBook PRO 16
b540e7ba2a Fixed issue with Comment on Gitea 2023-04-23 19:02:59 +05:30
Bhavik MacBook PRO 16
9c01da5f63 Fixed issue with Comment on Gitea 2023-04-23 19:02:18 +05:30
vandanafuletra
12c0cbad46
Merge pull request #21 from ingress-it-solutions/dev
Fixed issue with Comment on Gitea
2023-04-23 18:52:34 +05:30
Bhavik MacBook PRO 16
c6fb986f1e Fixed issue with Comment on Gitea 2023-04-23 18:50:43 +05:30
vandanafuletra
376bf7cd52
Merge pull request #20 from ingress-it-solutions/dev
Fixed issue with Comment on Gitea
2023-04-23 18:34:37 +05:30
Bhavik MacBook PRO 16
8543fc0e11 Fixed issue with Comment on Gitea 2023-04-23 18:33:34 +05:30
vandanafuletra
08e8c7bc72
Merge pull request #19 from ingress-it-solutions/dev
Fixed issue with Gitea Pull Request URL
2023-04-23 17:58:12 +05:30
Bhavik MacBook PRO 16
7a961911b3 Fixed issue with Gitea Pull Request URL 2023-04-23 17:56:53 +05:30
vandanafuletra
70ff4bd5f9
Merge pull request #18 from ingress-it-solutions/dev
Adeed test message
2023-04-23 17:19:20 +05:30
Bhavik MacBook PRO 16
d05920d493 Adeed test message 2023-04-23 17:17:59 +05:30
vandanafuletra
e8de4e326c
Merge pull request #17 from ingress-it-solutions/dev
Adeed test message
2023-04-23 17:17:11 +05:30
Bhavik MacBook PRO 16
7867b54c0d Fixed code base 2023-04-23 17:16:59 +05:30
Bhavik MacBook PRO 16
e6bc0a5e37 Adeed test message 2023-04-23 17:14:41 +05:30
vandanafuletra
24425a1668
Merge pull request #16 from ingress-it-solutions/dev
Removed comment from ReadMe
2023-04-23 17:14:12 +05:30
Bhavik MacBook PRO 16
144f8250d1 Fixed code base 2023-04-23 17:14:01 +05:30
Bhavik MacBook PRO 16
696b91dabc Removed comment from ReadMe 2023-04-23 17:11:22 +05:30
vandanafuletra
90bab48974
Merge pull request #15 from ingress-it-solutions/dev
Removed comment from ReadMe
2023-04-23 17:10:54 +05:30
Bhavik MacBook PRO 16
f18c541e29 Removed comment from ReadMe 2023-04-23 17:10:34 +05:30
Bhavik MacBook PRO 16
1fd15b539d Removed comment from ReadMe 2023-04-23 17:05:28 +05:30
vandanafuletra
d9cb89612a
Merge pull request #14 from ingress-it-solutions/dev
Fixed issue with Github job
2023-04-23 17:04:42 +05:30
Bhavik MacBook PRO 16
246b510381 Fixed issue with Github job 2023-04-23 17:04:17 +05:30
vandanafuletra
a7d158edbd
Merge pull request #13 from ingress-it-solutions/dev
Added code for Gitea
2023-04-23 17:03:51 +05:30
Bhavik MacBook PRO 16
afa79b554e Added code for Gitea 2023-04-23 17:02:51 +05:30
Bhavik MacBook PRO 16
dd1b960277 Added code for Gitea 2023-04-23 16:53:30 +05:30
vandanafuletra
6cbe295593
Merge pull request #12 from ingress-it-solutions/dev
Dev
2023-04-23 16:53:07 +05:30
Bhavik MacBook PRO 16
4d9329e59e Added code for Gitea 2023-04-23 16:52:46 +05:30
Bhavik MacBook PRO 16
6344cae339 Added code for Gitea 2023-04-23 16:49:26 +05:30
Bhavik MacBook PRO 16
c6912e4ece Added code for Gitea 2023-04-23 16:46:49 +05:30
vandanafuletra
7d61ccc420
Merge pull request #11 from ingress-it-solutions/dev
FIXED ISSUE FOR GITHUB
2023-04-23 16:39:58 +05:30
Bhavik MacBook PRO 16
be1c0ee191 FIXED ISSUE FOR GITHUB 2023-04-23 16:38:33 +05:30
Bhavik MacBook PRO 16
45e0c32b09 FIXED ISSUE FOR GITHUB 2023-04-23 16:33:58 +05:30
vandanafuletra
3f83c62925
Merge pull request #10 from ingress-it-solutions/dev
Dev
2023-04-06 10:40:26 +05:30
Bhavik MacBook PRO 16
990db6e3da Fixed issue with Gitea 2023-04-06 10:39:08 +05:30
Bhavik MacBook PRO 16
878a6fded8 Fixed issue with Gitea 2023-04-06 10:38:31 +05:30
vandanafuletra
24a1488f89
Merge pull request #9 from ingress-it-solutions/dev
Fixed issue with Gitea
2023-04-06 10:35:07 +05:30
Bhavik MacBook PRO 16
eb1fb70e05 Fixed issue with Gitea 2023-04-06 10:20:21 +05:30
vandanafuletra
00ddd9adf0
Merge pull request #8 from ingress-it-solutions/dev
Dev
2023-04-06 10:15:00 +05:30
Bhavik MacBook PRO 16
f05ffb4a9d Fixed issue with Gitea 2023-04-06 10:11:17 +05:30
Bhavik MacBook PRO 16
7af7c49a6e Fixed issue with Gitea 2023-04-06 10:07:03 +05:30
Bhavik MacBook PRO 16
52b842f210 Using @actions/github 2023-04-05 23:51:03 +05:30
Bhavik MacBook PRO 16
7d5b853474 Fixed issue with comment 2023-04-05 23:19:13 +05:30
vandanafuletra
5dc467894a
Merge pull request #6 from ingress-it-solutions/dev
Fixed issue with comment
2023-04-05 23:18:37 +05:30
Bhavik MacBook PRO 16
c9909464d7 Fixed issue with comment 2023-04-05 23:16:04 +05:30
Bhavik MacBook PRO 16
b0064e3282 Fixed issue with comment 2023-04-05 23:13:12 +05:30
vandanafuletra
0355093e71
Merge pull request #5 from ingress-it-solutions/dev
Fixed issue with comment
2023-04-05 18:34:30 +05:30
Bhavik MacBook PRO 16
99d8e69a4f Fixed issue with comment 2023-04-05 18:33:32 +05:30
6 changed files with 424 additions and 236 deletions

View file

@ -25,3 +25,4 @@ jobs:
FULL_REVIEW_COMMENT: 'openai' FULL_REVIEW_COMMENT: 'openai'
OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
SOURCE_AT: 'github'

View file

@ -2,7 +2,7 @@
# OpenAI Code Review # OpenAI Code Review
A Gitea Action that uses OpenAI to analyze code in pull request comments. A Gitea Action that uses OpenAI to analyze code in pull request comments. Test message from Bhavik.
## Usage ## Usage
@ -106,11 +106,8 @@ ${file:dist/index.js}
## Screenshots ## Screenshots
## More Examples ## More Examples
## License ## License
The code in this repository is licensed under the MIT license. See `LICENSE` for more information. The code in this repository is licensed under the MIT license. See `LICENSE` for more information.

View file

@ -22,21 +22,86 @@ inputs:
description: 'The maximum code length for the pull request to be sent to OpenAI.' description: 'The maximum code length for the pull request to be sent to OpenAI.'
default: 6000 default: 6000
type: int type: int
SOURCE_AT:
description: 'Where is the source code located'
default: 'github'
PROMPT_TEMPLATE: PROMPT_TEMPLATE:
description: 'The template for the FULL_REVIEW_COMMENT prompt.' description: 'The template for the FULL_REVIEW_COMMENT prompt.'
default: 'Please analyze the pull request''s code and inform me whether it requires optimization, and provide an explanation for your decision: default: 'Your task is to act as a code reviewer and review a pull request by summarizing the changes made, identifying potential issues related to logic and runtime, and creating a bullet list of action items needed before the change can be approved. The output should focus on items mentioned in the given code review checklist.
Instructions:
- Review the output of git diff for the pull request
- Identify potential issues related to logic and runtime
- You will only mention the checklist item when it violates the check. If there is nothing found you wont need to mention about checklist. Instead you can say "Raktbeej couldnt find any failed check."
- Output as a markdown document, with the following sections:
### Overall Summary:
- Each bullet point should provide the summary on what this Pull request does. Each point shouldnt exceed more than 14 words.
### Issues & Action Items:
- Title of the check that it violated and a one liner guideline to user on how it can be fixed.
- TODO List with the name of the file, violating policy and line no where you think it was violated.
### APPROVE / DISAPPROVE this PR:
- Tell me if this Pull request can be approved or not. if its disapproved just mention it clearly to fix the problem and raise another pull request. If its approved then appreciate everyone and say it can be approved.
- If there are no issues, output "None"
- If there are no action items, output "None"
- Create a bullet list of action items needed before the change can be approved
- The response sentences are no longer than 16 words each
- Keep the response sentences as short as possible
- Below code is for laravel framework then you need to check for N+1 query detection in the pull request. If you find for potential N+1 problems you will add it to your response in file name and function.
- Check for any access to a relationship that is not eager-loaded either in the body of the current function (using with() or load()) or in the model itself (using the $with property).
- Check for any call to DB functions in the loop such as DB::table()
- Check for any call to static Model functions in the loop such as Product::find()
- Check for any call to Model functions in the loop such as $product->save()
- Check if a pull request shows push an HTTP resource class you will check if pull request code used the whenLoaded() helper provided by Laravel. It is a great way to avoid N+1 and performance issues.
- Check if a pull request code push a migration we check if it has added any kind of index to new columns. The full path has to include migration in order to trigger this check.
- Check if a pull request code push a migration we check if it has a down method and it is not empty. The full path has to include migration in order to trigger this check.
- Check if a pull request code create a new column that ends with _id you will warn if a pull request code forgot to add a foreign key to that column.
- Check if a pull request code push an HTTP request we check if it has an authorize method and it is not return true. The filename must end with Request.php or the full path has to include Requests in order to trigger this check.
- Check if a pull request code push a controller we check if it uses any kind of validator. Usually, it is a better idea to move this logic to a Request class. The filename must end with Controller.php or the full path has to include Controllers in order to trigger this check.
- Check if a pull request code added a new key to one of the config file we check if a pull request code also included it in the .env.example file
- Check if a pull request code contains an env() call anywhere outside of a config file it needs to be warn. It is a best practice to only use env() in config files.
- Check if a pull request code contains a Cache::rememberForever() call It needs to be warn.
- Check for Validation with reference to Request that has non nullable database table column in migration.
- Check for Incorrect dependencies as there are different layers in every Laravel application. Layers such as: HTTP, Business Logic, Database, etc. Each layer has its own dependencies. For example, the database layer should not depend on the HTTP layer. If it does, it should warn.
Here are what counts as an incorrect dependency:
- This class -> Depends on these
- Model -> HTTP, Job, Command, Checker
- Job -> HTTP
- Command -> HTTP
- Mail/Notification -> HTTP, Job, Command
- Service -> HTTP
- Repository -> HTTP, Job, Command
- Check for Complex data object as there are some typical classes that should not contain too much business logic since their main purpose is to hold data. These classes are:
- Resources
- Livewire
- Requests
- DataTransferObjects (DTO)
- Value Objects
- Mail
- Notification
- Event
- Listener
- Check for cyclomatic complexity if a class that contains too much business logic, it needs to be warn. "Too much" means that the cyclomatic complexity of the class is larger than 3.
- Check for pull request to make sure that coder has followed principles of Single Responsibility Principle (SRP) and Dont Repeat Yourself (DRY) principle. If not explain where the user needs to make changes.
- Check for naming conventions, if a pull request code is violating the naming convention it needs to be warn.
- Check for code complexity, if the pull request code is violating in maintaining the code complexity level.
- Check for Error handling in the pull request, if pull request code has a proper error handling in the below scenarios.
- Are all error scenarios covered in the code?
- Are the error messages clear and helpful?
- Is the code handling errors gracefully?
- Check for Security
- Are sensitive data and credentials stored securely?
- Are all external libraries and packages up-to-date?
- Is the code protected against common security vulnerabilities such as SQL injection and cross-site scripting (XSS)?
\`\`\` \`\`\`
${code} ${code}
\`\`\`' \`\`\`'
ANSWER_TEMPLATE: ANSWER_TEMPLATE:
description: 'The template for the answer sent to the GitHub comment.' description: 'The template for the answer sent to the GitHub comment.'
default: 'AI Code Review: default: 'Raktbeej Code Review:
## Summary:
${answer}' ${answer}'
runs: runs:
using: 'node16' using: 'node16'
main: 'dist/index.js' main: 'dist/index.js'

288
dist/index.js vendored
View file

@ -39201,116 +39201,179 @@ function configWithProxy(config) {
return c; return c;
} }
async function run() { async function run() {
try { try {
// Get input values // Get input values
const programmingLanguage = core.getInput('PROGRAMMING_LANGUAGE'); const programmingLanguage = core.getInput('PROGRAMMING_LANGUAGE');
const openaiToken = core.getInput('OPENAI_TOKEN'); const openaiToken = core.getInput('OPENAI_TOKEN');
const fullReviewComment = core.getInput('FULL_REVIEW_COMMENT'); const fullReviewComment = core.getInput('FULL_REVIEW_COMMENT');
const reviewCommentPrefix = core.getInput('REVIEW_COMMENT_PREFIX'); const reviewCommentPrefix = core.getInput('REVIEW_COMMENT_PREFIX');
const githubToken = core.getInput('GITHUB_TOKEN'); const githubToken = core.getInput('GITHUB_TOKEN');
const githubBaseURL = core.getInput('GITHUB_BASE_URL') || process.env.GITHUB_API_URL; const githubBaseURL = core.getInput('GITHUB_BASE_URL') || process.env.GITHUB_API_URL;
const promptTemplate = core.getInput('PROMPT_TEMPLATE'); const promptTemplate = core.getInput('PROMPT_TEMPLATE');
const maxCodeLength = core.getInput('MAX_CODE_LENGTH'); const maxCodeLength = core.getInput('MAX_CODE_LENGTH');
const answerTemplate = core.getInput('ANSWER_TEMPLATE'); const answerTemplate = core.getInput('ANSWER_TEMPLATE');
const giteaToken = core.getInput('GITHUB_TOKEN');
const sourceAt = core.getInput('SOURCE_AT');
core.debug(`programmingLanguage: ${programmingLanguage}`); core.debug(`programmingLanguage: ${programmingLanguage}`);
core.debug(`openaiToken length: ${openaiToken.length}`); core.debug(`openaiToken length: ${openaiToken.length}`);
core.debug(`fullReviewComment: ${fullReviewComment}`); core.debug(`fullReviewComment: ${fullReviewComment}`);
core.debug(`reviewCommentPrefix: ${reviewCommentPrefix}`); core.debug(`reviewCommentPrefix: ${reviewCommentPrefix}`);
core.debug(`githubToken length: ${githubToken.length}`); core.debug(`githubToken length: ${githubToken.length}`);
core.debug(`githubBaseURL: ${githubBaseURL}`); core.debug(`githubBaseURL: ${githubBaseURL}`);
core.debug(`promptTemplate: ${promptTemplate}`); core.debug(`promptTemplate: ${promptTemplate}`);
core.debug(`maxCodeLength: ${maxCodeLength}`); core.debug(`maxCodeLength: ${maxCodeLength}`);
core.debug(`answerTemplate: ${answerTemplate}`); core.debug(`answerTemplate: ${answerTemplate}`);
core.debug(`SourceAt: ${sourceAt}`);
// Get information about the pull request review // Get information about the pull request review
const comment = github.context.payload.comment; const comment = github.context.payload.comment;
const repoName = github.context.payload.repository.name; const repoName = github.context.payload.repository.name;
const repoOwner = github.context.payload.repository.owner.login; const repoOwner = github.context.payload.repository.owner.login;
const prNumber = github.context.payload.number || github.context.payload.issue.number; // get number from a pull request event or comment event const prNumber = github.context.payload.number || github.context.payload.issue.number; // get number from a pull request event or comment event
// Get the code to analyze from the review comment // Get the code to analyze from the review comment
var content = comment && comment.body || ""; var content = comment && comment.body || '';
const url = `${githubBaseURL}/${repoOwner}/${repoName}/pulls/${prNumber}`; if(sourceAt === 'github') {
core.debug(`diff url: ${url}`);
var response = await axios.get(url, {
headers: {
Authorization: `Bearer ${githubToken}`,
Accept: 'application/vnd.github.diff'
}
});
const code = response.data;
core.debug(`diff code: ${code}`);
const files = parsePullRequestDiff(code);
core.debug(`diff files: ${files}`);
if (!content || content == fullReviewComment) { const url = `${githubBaseURL}/repos/${repoOwner}/${repoName}/pulls/${prNumber}`;
// Extract the code from the pull request content console.log(`diff url: ${url}`);
content = promptTemplate.replace('${code}', code); var response = await axios.get(url, {
} else { headers: {
content = content.substring(reviewCommentPrefix.length); Authorization: `token ${githubToken}`,
content = content.replace('${code}', code); Accept: 'application/vnd.github.diff'
const fileNames = findFileNames(content); }
core.debug(`found files name in commment: ${fileNames}`); });
for (const fileName of fileNames) { const code = response.data;
for (const key of Object.keys(files)) { core.debug(`diff code: ${code}`);
if (key.includes(fileName)) { const files = parsePullRequestDiff(code);
core.debug(`replace \${file:${fileName}} with ${key}'s diff`); core.debug(`diff files: ${files}`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break; if (!content || content == fullReviewComment) {
// Extract the code from the pull request content
content = promptTemplate.replace('${code}', code);
} else {
content = content.substring(reviewCommentPrefix.length);
content = content.replace('${code}', code);
const fileNames = findFileNames(content);
core.debug(`found files name in commment: ${fileNames}`);
for (const fileName of fileNames) {
for (const key of Object.keys(files)) {
if (key.includes(fileName)) {
core.debug(`replace \${file:${fileName}} with ${key}'s diff`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break;
}
}
} }
} }
content = content.substring(0, maxCodeLength);
} }
else if(sourceAt === 'gitea')
{
const url = `${githubBaseURL}/api/v1/repos/${repoOwner}/${repoName}/pulls/${prNumber}.diff`;
console.log(`diff url: ${url}`);
var response = await axios.get(url, {
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/vnd.github.diff'
}
});
const code = response.data;
core.debug(`diff code: ${code}`);
const files = parsePullRequestDiff(code);
core.debug(`diff files: ${files}`);
if (!content || content == fullReviewComment) {
// Extract the code from the pull request content
content = promptTemplate.replace('${code}', code);
} else {
content = content.substring(reviewCommentPrefix.length);
content = content.replace('${code}', code);
const fileNames = findFileNames(content);
core.debug(`found files name in commment: ${fileNames}`);
for (const fileName of fileNames) {
for (const key of Object.keys(files)) {
if (key.includes(fileName)) {
core.debug(`replace \${file:${fileName}} with ${key}'s diff`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break;
}
}
}
}
content = content.substring(0, maxCodeLength);
}
// Determine the programming language if it was not provided
if (programmingLanguage == 'auto') {
const detectedLanguage = detect(code);
core.debug(`Detected programming language: ${detectedLanguage}`);
programmingLanguage = detectedLanguage;
}
var messages = [{
role: "system",
content: `You are a master of programming language ${programmingLanguage}`
}, {
role: "user",
content: content
}];
core.debug(`content: ${content}`);
// Call the OpenAI ChatGPT API to analyze the code
response = await axios.post('https://api.openai.com/v1/chat/completions', {
"model": "gpt-3.5-turbo",
"messages": messages
}, configWithProxy({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaiToken}`
}
}));
const answer = response.data.choices[0].message.content;
core.debug(`openai response: ${answer}`);
if(sourceAt === 'github') {
// Reply to the review comment with the OpenAI response
const octokit = new github.getOctokit(githubToken, {
baseUrl: githubBaseURL
});
await octokit.rest.issues.createComment({
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
body: answerTemplate.replace('${answer}', answer)
});
} else if (sourceAt === 'gitea')
{
// Make a POST request to create a comment on a pull request
const comment = answerTemplate.replace('${answer}', answer);
const url = `${githubBaseURL}/api/v1/repos/${repoOwner}/${repoName}/issues/${prNumber}/comments`;
const headers = { 'Content-Type': 'application/json', 'Authorization': `token ${githubToken}` };
const data = { 'body': `${comment}`};
core.debug(`url: ${url}`);
core.debug(`githubToken: ${githubToken}`);
core.debug(`data.body: ${data.body}`);
var response = await axios.post(url, data, {
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/json'
}
});
}
} catch (error) {
core.setFailed(error.message);
} }
content = content.substring(0, maxCodeLength);
// Determine the programming language if it was not provided
if (programmingLanguage == 'auto') {
const detectedLanguage = detect(code);
core.debug(`Detected programming language: ${detectedLanguage}`);
programmingLanguage = detectedLanguage;
}
var messages = [{
role: "system",
content: `You are a master of programming language ${programmingLanguage}`
}, {
role: "user",
content: content
}];
core.debug(`content: ${content}`);
// Call the OpenAI ChatGPT API to analyze the code
response = await axios.post('https://api.openai.com/v1/chat/completions', {
"model": "gpt-3.5-turbo",
"messages": messages
}, configWithProxy({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaiToken}`
}
}));
const answer = response.data.choices[0].message.content;
core.debug(`openai response: ${answer}`);
// Reply to the review comment with the OpenAI response
const octokit = github.getOctokit(githubToken, {
baseUrl: githubBaseURL
});
await octokit.rest.issues.createComment({
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
body: answerTemplate.replace('${answer}', answer)
// in_reply_to: comment.id
});
} catch (error) {
core.setFailed(error.message);
}
} }
function parsePullRequestDiff(diffContent) { function parsePullRequestDiff(diffContent) {
@ -39321,22 +39384,22 @@ function parsePullRequestDiff(diffContent) {
let currentLines = []; let currentLines = [];
for (const line of diffLines) { for (const line of diffLines) {
if (line.startsWith('diff --git')) { if (line.startsWith('diff --git')) {
// Start of a new file // Start of a new file
if (currentFile) { if (currentFile) {
files[currentFile] = currentLines.join('\n'); files[currentFile] = currentLines.join('\n');
}
currentFile = line.substring('diff --git'.length + 1);
currentLines = [line];
} else {
// Add the line to the current file's diff
currentLines.push(line);
} }
currentFile = line.substring('diff --git'.length + 1);
currentLines = [line];
} else {
// Add the line to the current file's diff
currentLines.push(line);
}
} }
// Add the last file's diff // Add the last file's diff
if (currentFile) { if (currentFile) {
files[currentFile] = currentLines.join('\n'); files[currentFile] = currentLines.join('\n');
} }
return files; return files;
@ -39347,13 +39410,12 @@ function findFileNames(str) {
const matches = str.matchAll(pattern); const matches = str.matchAll(pattern);
const names = []; const names = [];
for (const match of matches) { for (const match of matches) {
names.push(match[1]); names.push(match[1]);
} }
return names; return names;
} }
run(); run();
})(); })();
module.exports = __webpack_exports__; module.exports = __webpack_exports__;

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

289
index.js
View file

@ -15,116 +15,179 @@ function configWithProxy(config) {
return c; return c;
} }
async function run() { async function run() {
try { try {
// Get input values // Get input values
const programmingLanguage = core.getInput('PROGRAMMING_LANGUAGE'); const programmingLanguage = core.getInput('PROGRAMMING_LANGUAGE');
const openaiToken = core.getInput('OPENAI_TOKEN'); const openaiToken = core.getInput('OPENAI_TOKEN');
const fullReviewComment = core.getInput('FULL_REVIEW_COMMENT'); const fullReviewComment = core.getInput('FULL_REVIEW_COMMENT');
const reviewCommentPrefix = core.getInput('REVIEW_COMMENT_PREFIX'); const reviewCommentPrefix = core.getInput('REVIEW_COMMENT_PREFIX');
const githubToken = core.getInput('GITHUB_TOKEN'); const githubToken = core.getInput('GITHUB_TOKEN');
const githubBaseURL = core.getInput('GITHUB_BASE_URL') || process.env.GITHUB_API_URL; const githubBaseURL = core.getInput('GITHUB_BASE_URL') || process.env.GITHUB_API_URL;
const promptTemplate = core.getInput('PROMPT_TEMPLATE'); const promptTemplate = core.getInput('PROMPT_TEMPLATE');
const maxCodeLength = core.getInput('MAX_CODE_LENGTH'); const maxCodeLength = core.getInput('MAX_CODE_LENGTH');
const answerTemplate = core.getInput('ANSWER_TEMPLATE'); const answerTemplate = core.getInput('ANSWER_TEMPLATE');
const giteaToken = core.getInput('GITHUB_TOKEN');
const sourceAt = core.getInput('SOURCE_AT');
core.debug(`programmingLanguage: ${programmingLanguage}`); core.debug(`programmingLanguage: ${programmingLanguage}`);
core.debug(`openaiToken length: ${openaiToken.length}`); core.debug(`openaiToken length: ${openaiToken.length}`);
core.debug(`fullReviewComment: ${fullReviewComment}`); core.debug(`fullReviewComment: ${fullReviewComment}`);
core.debug(`reviewCommentPrefix: ${reviewCommentPrefix}`); core.debug(`reviewCommentPrefix: ${reviewCommentPrefix}`);
core.debug(`githubToken length: ${githubToken.length}`); core.debug(`githubToken length: ${githubToken.length}`);
core.debug(`githubBaseURL: ${githubBaseURL}`); core.debug(`githubBaseURL: ${githubBaseURL}`);
core.debug(`promptTemplate: ${promptTemplate}`); core.debug(`promptTemplate: ${promptTemplate}`);
core.debug(`maxCodeLength: ${maxCodeLength}`); core.debug(`maxCodeLength: ${maxCodeLength}`);
core.debug(`answerTemplate: ${answerTemplate}`); core.debug(`answerTemplate: ${answerTemplate}`);
core.debug(`SourceAt: ${sourceAt}`);
// Get information about the pull request review // Get information about the pull request review
const comment = github.context.payload.comment; const comment = github.context.payload.comment;
const repoName = github.context.payload.repository.name; const repoName = github.context.payload.repository.name;
const repoOwner = github.context.payload.repository.owner.login; const repoOwner = github.context.payload.repository.owner.login;
const prNumber = github.context.payload.number || github.context.payload.issue.number; // get number from a pull request event or comment event const prNumber = github.context.payload.number || github.context.payload.issue.number; // get number from a pull request event or comment event
// Get the code to analyze from the review comment // Get the code to analyze from the review comment
var content = comment && comment.body || ""; var content = comment && comment.body || '';
const url = `${githubBaseURL}/${repoOwner}/${repoName}/pulls/${prNumber}`; if(sourceAt === 'github') {
core.debug(`diff url: ${url}`);
var response = await axios.get(url, {
headers: {
Authorization: `Bearer ${githubToken}`,
Accept: 'application/vnd.github.diff'
}
});
const code = response.data;
core.debug(`diff code: ${code}`);
const files = parsePullRequestDiff(code);
core.debug(`diff files: ${files}`);
if (!content || content == fullReviewComment) { const url = `${githubBaseURL}/repos/${repoOwner}/${repoName}/pulls/${prNumber}`;
// Extract the code from the pull request content console.log(`diff url: ${url}`);
content = promptTemplate.replace('${code}', code); var response = await axios.get(url, {
} else { headers: {
content = content.substring(reviewCommentPrefix.length); Authorization: `token ${githubToken}`,
content = content.replace('${code}', code); Accept: 'application/vnd.github.diff'
const fileNames = findFileNames(content); }
core.debug(`found files name in commment: ${fileNames}`); });
for (const fileName of fileNames) { const code = response.data;
for (const key of Object.keys(files)) { core.debug(`diff code: ${code}`);
if (key.includes(fileName)) { const files = parsePullRequestDiff(code);
core.debug(`replace \${file:${fileName}} with ${key}'s diff`); core.debug(`diff files: ${files}`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break; if (!content || content == fullReviewComment) {
// Extract the code from the pull request content
content = promptTemplate.replace('${code}', code);
} else {
content = content.substring(reviewCommentPrefix.length);
content = content.replace('${code}', code);
const fileNames = findFileNames(content);
core.debug(`found files name in commment: ${fileNames}`);
for (const fileName of fileNames) {
for (const key of Object.keys(files)) {
if (key.includes(fileName)) {
core.debug(`replace \${file:${fileName}} with ${key}'s diff`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break;
}
}
} }
} }
content = content.substring(0, maxCodeLength);
} }
else if(sourceAt === 'gitea')
{
const url = `${githubBaseURL}/api/v1/repos/${repoOwner}/${repoName}/pulls/${prNumber}.diff`;
console.log(`diff url: ${url}`);
var response = await axios.get(url, {
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/vnd.github.diff'
}
});
const code = response.data;
core.debug(`diff code: ${code}`);
const files = parsePullRequestDiff(code);
core.debug(`diff files: ${files}`);
if (!content || content == fullReviewComment) {
// Extract the code from the pull request content
content = promptTemplate.replace('${code}', code);
} else {
content = content.substring(reviewCommentPrefix.length);
content = content.replace('${code}', code);
const fileNames = findFileNames(content);
core.debug(`found files name in commment: ${fileNames}`);
for (const fileName of fileNames) {
for (const key of Object.keys(files)) {
if (key.includes(fileName)) {
core.debug(`replace \${file:${fileName}} with ${key}'s diff`);
content = content.replace(`\${file:${fileName}}`, files[key]);
break;
}
}
}
}
content = content.substring(0, maxCodeLength);
}
// Determine the programming language if it was not provided
if (programmingLanguage == 'auto') {
const detectedLanguage = detect(code);
core.debug(`Detected programming language: ${detectedLanguage}`);
programmingLanguage = detectedLanguage;
}
var messages = [{
role: "system",
content: `You are a master of programming language ${programmingLanguage}`
}, {
role: "user",
content: content
}];
core.debug(`content: ${content}`);
// Call the OpenAI ChatGPT API to analyze the code
response = await axios.post('https://api.openai.com/v1/chat/completions', {
"model": "gpt-3.5-turbo",
"messages": messages
}, configWithProxy({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaiToken}`
}
}));
const answer = response.data.choices[0].message.content;
core.debug(`openai response: ${answer}`);
if(sourceAt === 'github') {
// Reply to the review comment with the OpenAI response
const octokit = new github.getOctokit(githubToken, {
baseUrl: githubBaseURL
});
await octokit.rest.issues.createComment({
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
body: answerTemplate.replace('${answer}', answer)
});
} else if (sourceAt === 'gitea')
{
// Make a POST request to create a comment on a pull request
const comment = answerTemplate.replace('${answer}', answer);
const url = `${githubBaseURL}/api/v1/repos/${repoOwner}/${repoName}/issues/${prNumber}/comments`;
const headers = { 'Content-Type': 'application/json', 'Authorization': `token ${githubToken}` };
const data = { 'body': `${comment}`};
core.debug(`url: ${url}`);
core.debug(`githubToken: ${githubToken}`);
core.debug(`data.body: ${data.body}`);
var response = await axios.post(url, data, {
headers: {
Authorization: `token ${githubToken}`,
Accept: 'application/json'
}
});
}
} catch (error) {
core.setFailed(error.message);
} }
content = content.substring(0, maxCodeLength);
// Determine the programming language if it was not provided
if (programmingLanguage == 'auto') {
const detectedLanguage = detect(code);
core.debug(`Detected programming language: ${detectedLanguage}`);
programmingLanguage = detectedLanguage;
}
var messages = [{
role: "system",
content: `You are a master of programming language ${programmingLanguage}`
}, {
role: "user",
content: content
}];
core.debug(`content: ${content}`);
// Call the OpenAI ChatGPT API to analyze the code
response = await axios.post('https://api.openai.com/v1/chat/completions', {
"model": "gpt-3.5-turbo",
"messages": messages
}, configWithProxy({
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaiToken}`
}
}));
const answer = response.data.choices[0].message.content;
core.debug(`openai response: ${answer}`);
// Reply to the review comment with the OpenAI response
const octokit = github.getOctokit(githubToken, {
baseUrl: githubBaseURL
});
await octokit.rest.issues.createComment({
owner: repoOwner,
repo: repoName,
issue_number: prNumber,
body: answerTemplate.replace('${answer}', answer)
// in_reply_to: comment.id
});
} catch (error) {
core.setFailed(error.message);
}
} }
function parsePullRequestDiff(diffContent) { function parsePullRequestDiff(diffContent) {
@ -135,22 +198,22 @@ function parsePullRequestDiff(diffContent) {
let currentLines = []; let currentLines = [];
for (const line of diffLines) { for (const line of diffLines) {
if (line.startsWith('diff --git')) { if (line.startsWith('diff --git')) {
// Start of a new file // Start of a new file
if (currentFile) { if (currentFile) {
files[currentFile] = currentLines.join('\n'); files[currentFile] = currentLines.join('\n');
}
currentFile = line.substring('diff --git'.length + 1);
currentLines = [line];
} else {
// Add the line to the current file's diff
currentLines.push(line);
} }
currentFile = line.substring('diff --git'.length + 1);
currentLines = [line];
} else {
// Add the line to the current file's diff
currentLines.push(line);
}
} }
// Add the last file's diff // Add the last file's diff
if (currentFile) { if (currentFile) {
files[currentFile] = currentLines.join('\n'); files[currentFile] = currentLines.join('\n');
} }
return files; return files;
@ -161,9 +224,9 @@ function findFileNames(str) {
const matches = str.matchAll(pattern); const matches = str.matchAll(pattern);
const names = []; const names = [];
for (const match of matches) { for (const match of matches) {
names.push(match[1]); names.push(match[1]);
} }
return names; return names;
} }
run(); run();