mirror of
https://github.com/kekxv/AiReviewPR.git
synced 2025-02-11 22:41:50 +01:00
184
README.md
184
README.md
@@ -43,11 +43,12 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Review code
|
||||
uses: kekxv/AiReviewPR@v0.0.2
|
||||
uses: kekxv/AiReviewPR@v0.0.3
|
||||
with:
|
||||
model: 'gemma2:2b'
|
||||
host: ${{ vars.OLLAMA_HOST }}
|
||||
ai_token: ${{ secrets.AI_TOKEN }}
|
||||
REVIEW_PULL_REQUEST: false
|
||||
exclude_files: |
|
||||
^.+\.md
|
||||
test2\.js
|
||||
@@ -68,105 +69,136 @@ result:
|
||||
|
||||
## 输入参数
|
||||
|
||||
1. **repository**:
|
||||
- **描述**: 要审查的代码库名称,格式为 `owner/repository`,例如 `actions/checkout`。
|
||||
- **默认值**: `${{ github.repository }}`
|
||||
|
||||
2. **BASE_REF**:
|
||||
- **描述**: GitHub 事件中 Pull Request 的基线引用。
|
||||
- **默认值**: `${{ github.event.pull_request.base.ref }}`
|
||||
1. **repository**
|
||||
- **描述**: 存储库名称,格式为 `owner/repo`(例如 `actions/checkout`)。
|
||||
- **默认值**: `${{ github.repository }}`(当前 GitHub 仓库的名称)。
|
||||
|
||||
3. **PULL_REQUEST_NUMBER**:
|
||||
- **描述**: GitHub 事件中 Pull Request 的编号。
|
||||
- **默认值**: `${{ github.event.pull_request.number }}`
|
||||
2. **REVIEW_PULL_REQUEST**
|
||||
- **描述**: 指定是否要比较从提交开始到最新的记录;设置为 `false` 表示只审核最新一次提交。
|
||||
- **默认值**: `false`。
|
||||
|
||||
4. **CHINESE**:
|
||||
- **描述**: 是否使用中文进行审查。
|
||||
- **默认值**: `"true"`
|
||||
3. **BASE_REF**
|
||||
- **描述**: 当前 GitHub 事件中的 pull_request 的基准分支。
|
||||
- **默认值**: `${{ github.event.pull_request.base.ref }}`。
|
||||
|
||||
5. **token**:
|
||||
- **描述**: 用于获取存储库的个人访问令牌(PAT)。建议使用最小权限的服务帐户。
|
||||
- **默认值**: `${{ github.token }}`
|
||||
4. **PULL_REQUEST_NUMBER**
|
||||
- **描述**: 当前 GitHub 事件中的 pull_request 编号。
|
||||
- **默认值**: `${{ github.event.pull_request.number }}`。
|
||||
|
||||
6. **model**:
|
||||
- **描述**: 要用于代码审查的 AI 模型。
|
||||
- **必需**: 是
|
||||
- **默认值**: `'gemma2:2b'`
|
||||
5. **CHINESE**
|
||||
- **描述**: 使用中文(作废)。
|
||||
- **默认值**: `""`。
|
||||
|
||||
7. **host**:
|
||||
6. **LANGUAGE**
|
||||
- **描述**: 使用语言(中文)。
|
||||
- **默认值**: `"Chinese"`。
|
||||
|
||||
7. **token**
|
||||
- **描述**: 用于访问存储库的个人访问令牌(PAT)。该令牌配置在本地 git 配置中,允许脚本运行经过身份验证的 git 命令。作业结束时会移除 PAT。
|
||||
- **建议**: 使用权限最少的服务账号生成新的 PAT 并仅选择必要的作用域。
|
||||
- **文档链接**: [了解如何创建和使用加密密钥](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)。
|
||||
- **默认值**: `${{ github.token }}`。
|
||||
|
||||
8. **model**
|
||||
- **描述**: 用于代码审核的 AI 模型。
|
||||
- **必需**: 是。
|
||||
- **默认值**: `'gemma2:2b'`。
|
||||
|
||||
9. **host**
|
||||
- **描述**: Ollama 主机地址。
|
||||
- **必需**: 是
|
||||
- **默认值**: `'http://127.0.0.1:11434'`
|
||||
- **必需**: 是。
|
||||
- **默认值**: `'http://127.0.0.1:11434'`。
|
||||
|
||||
8. **reviewers_prompt**:
|
||||
- **描述**: Ollama 的系统提示。定义了代码审查的参数和预期格式。
|
||||
- **必需**: 否
|
||||
- **默认值**: 一段详细的说明文本,指导审查生成过程。
|
||||
10. **PROMPT_GENRE**
|
||||
- **描述**: 提示生成的类型。
|
||||
- **默认值**: `' '`(空格)。
|
||||
|
||||
9. **ai_token**:
|
||||
- **描述**: AI 访问令牌。
|
||||
- **必需**: 否
|
||||
- **默认值**: `" "`
|
||||
11. **reviewers_prompt**
|
||||
- **描述**: Ollama 系统提示信息。
|
||||
- **必需**: 否。
|
||||
- **默认值**: `""`(空字符串)。
|
||||
|
||||
10. **include_files**:
|
||||
- **描述**: 要包含审查的文件列表,以逗号分隔,支持换行。
|
||||
- **必需**: 否
|
||||
- **默认值**: `" "`(默认为空,不限制)
|
||||
12. **ai_token**
|
||||
- **描述**: AI 令牌。
|
||||
- **必需**: 否。
|
||||
- **默认值**: `" "`(空格)。
|
||||
|
||||
13. **include_files**
|
||||
- **描述**: 要包括审查的文件的以逗号分隔的列表。
|
||||
- **必需**: 否。
|
||||
- **默认值**: `" "`(默认为空,表示不限制)。
|
||||
|
||||
14. **exclude_files**
|
||||
- **描述**: 要排除审查的文件的以逗号分隔的列表。
|
||||
- **必需**: 否。
|
||||
- **默认值**: `" "`(默认为空,表示不传递文件)。
|
||||
|
||||
11. **exclude_files**:
|
||||
- **描述**: 要排除审查的文件列表,以逗号分隔,支持换行。
|
||||
- **必需**: 否
|
||||
- **默认值**: `" "`(默认为空,不传递文件)
|
||||
|
||||
|
||||
### Input Parameters
|
||||
|
||||
1. **repository**:
|
||||
- **Description**: The name of the repository to review, formatted as `owner/repository`, for example, `actions/checkout`.
|
||||
- **Default Value**: `${{ github.repository }}`
|
||||
1. **repository**
|
||||
- **Description**: The name of the repository, formatted as `owner/repo` (e.g., `actions/checkout`).
|
||||
- **Default Value**: `${{ github.repository }}` (the name of the current GitHub repository).
|
||||
|
||||
2. **BASE_REF**:
|
||||
- **Description**: The base reference of the Pull Request in the GitHub event.
|
||||
- **Default Value**: `${{ github.event.pull_request.base.ref }}`
|
||||
2. **REVIEW_PULL_REQUEST**
|
||||
- **Description**: Specifies whether to compare the records from the beginning of the commit to the latest one; setting it to `false` means that only the most recent commit will be reviewed.
|
||||
- **Default Value**: `false`.
|
||||
|
||||
3. **PULL_REQUEST_NUMBER**:
|
||||
- **Description**: The number of the Pull Request in the GitHub event.
|
||||
- **Default Value**: `${{ github.event.pull_request.number }}`
|
||||
3. **BASE_REF**
|
||||
- **Description**: The base branch of the pull request in the current GitHub event.
|
||||
- **Default Value**: `${{ github.event.pull_request.base.ref }}`.
|
||||
|
||||
4. **CHINESE**:
|
||||
- **Description**: Whether to use Chinese for the review.
|
||||
- **Default Value**: `"true"`
|
||||
4. **PULL_REQUEST_NUMBER**
|
||||
- **Description**: The number of the pull request in the current GitHub event.
|
||||
- **Default Value**: `${{ github.event.pull_request.number }}`.
|
||||
|
||||
5. **token**:
|
||||
- **Description**: A Personal Access Token (PAT) used to access the repository. It is recommended to use a service account with the least necessary permissions.
|
||||
- **Default Value**: `${{ github.token }}`
|
||||
5. **CHINESE**
|
||||
- **Description**: Use Chinese (deprecated).
|
||||
- **Default Value**: `""`.
|
||||
|
||||
6. **model**:
|
||||
- **Description**: The AI model to use for the code review.
|
||||
- **Required**: Yes
|
||||
- **Default Value**: `'gemma2:2b'`
|
||||
6. **LANGUAGE**
|
||||
- **Description**: Language to use (Chinese).
|
||||
- **Default Value**: `"Chinese"`.
|
||||
|
||||
7. **host**:
|
||||
- **Description**: The Ollama host address.
|
||||
- **Required**: Yes
|
||||
- **Default Value**: `'http://127.0.0.1:11434'`
|
||||
7. **token**
|
||||
- **Description**: Personal access token (PAT) used to access the repository. The PAT is configured in the local git configuration, allowing your scripts to run authenticated git commands. The PAT will be removed at the end of the job.
|
||||
- **Recommendation**: Use a service account with the least permissions necessary when generating a new PAT and select only the minimum required scopes.
|
||||
- **Documentation Link**: [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets).
|
||||
- **Default Value**: `${{ github.token }}`.
|
||||
|
||||
8. **reviewers_prompt**:
|
||||
- **Description**: Ollama's system prompt. It defines the parameters and expected format for the code review.
|
||||
- **Required**: No
|
||||
- **Default Value**: A detailed description text guiding the review generation process.
|
||||
8. **model**
|
||||
- **Description**: AI model to use for code review.
|
||||
- **Required**: Yes.
|
||||
- **Default Value**: `'gemma2:2b'`.
|
||||
|
||||
9. **ai_token**:
|
||||
- **Description**: The AI access token.
|
||||
- **Required**: No
|
||||
- **Default Value**: `" "`
|
||||
9. **host**
|
||||
- **Description**: Ollama host address.
|
||||
- **Required**: Yes.
|
||||
- **Default Value**: `'http://127.0.0.1:11434'`.
|
||||
|
||||
10. **include_files**:
|
||||
10. **PROMPT_GENRE**
|
||||
- **Description**: The genre of the prompt to generate.
|
||||
- **Default Value**: `' '` (space).
|
||||
|
||||
11. **reviewers_prompt**
|
||||
- **Description**: Ollama system prompt.
|
||||
- **Required**: No.
|
||||
- **Default Value**: `""` (empty string).
|
||||
|
||||
12. **ai_token**
|
||||
- **Description**: AI token.
|
||||
- **Required**: No.
|
||||
- **Default Value**: `" "` (space).
|
||||
|
||||
13. **include_files**
|
||||
- **Description**: A comma-separated list of files to include in the review.
|
||||
- **Required**: No
|
||||
- **Default Value**: `" "` (empty by default, no restrictions)
|
||||
- **Required**: No.
|
||||
- **Default Value**: `" "` (defaults to empty, meaning no restrictions).
|
||||
|
||||
11. **exclude_files**:
|
||||
14. **exclude_files**
|
||||
- **Description**: A comma-separated list of files to exclude from the review.
|
||||
- **Required**: No
|
||||
- **Default Value**: `" "` (empty by default, no files passed)
|
||||
- **Required**: No.
|
||||
- **Default Value**: `" "` (defaults to empty, meaning no files passed).
|
||||
|
||||
|
||||
32
action.yml
32
action.yml
@@ -6,6 +6,9 @@ inputs:
|
||||
repository:
|
||||
description: 'Repository name with owner. For example, actions/checkout'
|
||||
default: ${{ github.repository }}
|
||||
REVIEW_PULL_REQUEST:
|
||||
description: 'Whether to compare the records from the beginning of the commit to the latest one; false indicates that only the most recent commit will be reviewed. 是否比对提交开始到最新的记录,false表示只审核最新一次提交审核'
|
||||
default: false
|
||||
BASE_REF:
|
||||
description: 'github event pull_request base ref'
|
||||
default: ${{ github.event.pull_request.base.ref }}
|
||||
@@ -13,8 +16,11 @@ inputs:
|
||||
description: 'github event pull_request number'
|
||||
default: ${{ github.event.pull_request.number }}
|
||||
CHINESE:
|
||||
description: 'use chines 作废'
|
||||
default: ""
|
||||
LANGUAGE:
|
||||
description: 'use chines'
|
||||
default: "true"
|
||||
default: "Chinese"
|
||||
token:
|
||||
description: >
|
||||
Personal access token (PAT) used to fetch the repository. The PAT is configured
|
||||
@@ -36,29 +42,13 @@ inputs:
|
||||
description: 'ollama host'
|
||||
required: true
|
||||
default: 'http://127.0.0.1:11434'
|
||||
PROMPT_GENRE:
|
||||
description: 'prompt genre'
|
||||
default: ' '
|
||||
reviewers_prompt:
|
||||
description: 'ollama system prompt'
|
||||
required: false
|
||||
default: >
|
||||
You are an expert developer, your task is to review a set of pull requests.
|
||||
You are given a list of filenames and their partial contents, but note that you might not have the full context of the code.
|
||||
|
||||
Only review lines of code which have been changed (added or removed) in the pull request. The code looks similar to the output of a git diff command. Lines which have been removed are prefixed with a minus (-) and lines which have been added are prefixed with a plus (+). Other lines are added to provide context but should be ignored in the review.
|
||||
|
||||
Begin your review by evaluating the changed code using a risk score similar to a LOGAF score but measured from 1 to 5, where 1 is the lowest risk to the code base if the code is merged and 5 is the highest risk which would likely break something or be unsafe.
|
||||
|
||||
In your feedback, focus on highlighting potential bugs, improving readability if it is a problem, making code cleaner, and maximising the performance of the programming language. Flag any API keys or secrets present in the code in plain text immediately as highest risk. Rate the changes based on SOLID principles if applicable.
|
||||
|
||||
Do not comment on breaking functions down into smaller, more manageable functions unless it is a huge problem. Also be aware that there will be libraries and techniques used which you are not familiar with, so do not comment on those unless you are confident that there is a problem.
|
||||
|
||||
Use markdown formatting for the feedback details. Also do not include the filename or risk level in the feedback details.
|
||||
|
||||
Ensure the feedback details are brief, concise, accurate. If there are multiple similar issues, only comment on the most critical.
|
||||
|
||||
Include brief example code snippets in the feedback details for your suggested changes when you're confident your suggestions are improvements. Use the same programming language as the file under review.
|
||||
If there are multiple improvements you suggest in the feedback details, use an ordered list to indicate the priority of the changes.
|
||||
|
||||
Please respond without using "```markdown"
|
||||
default: ""
|
||||
ai_token:
|
||||
description: 'ai token'
|
||||
required: false
|
||||
|
||||
74
dist/index.js
vendored
74
dist/index.js
vendored
@@ -3,10 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const node_child_process_1 = require("node:child_process");
|
||||
const utils_1 = require("./utils");
|
||||
const prompt_1 = require("./prompt");
|
||||
const useChinese = (process.env.INPUT_CHINESE || "true").toLowerCase() != "false"; // use chinese
|
||||
let useChinese = (process.env.INPUT_CHINESE || "true").toLowerCase() != "false"; // use chinese
|
||||
const language = !process.env.INPUT_CHINESE ? (process.env.INPUT_LANGUAGE || "Chinese") : (useChinese ? "Chinese" : "English");
|
||||
const prompt_genre = (process.env.INPUT_PROMPT_GENRE || "");
|
||||
const reviewers_prompt = (process.env.INPUT_REVIEWERS_PROMPT || "");
|
||||
useChinese = language.toLowerCase() === "chinese";
|
||||
const include_files = (0, utils_1.split_message)(process.env.INPUT_INCLUDE_FILES || "");
|
||||
const exclude_files = (0, utils_1.split_message)(process.env.INPUT_EXCLUDE_FILES || "");
|
||||
const system_prompt = (0, prompt_1.take_system_prompt)(useChinese);
|
||||
const review_pull_request = (!process.env.INPUT_REVIEW_PULL_REQUEST) ? false : (process.env.INPUT_REVIEW_PULL_REQUEST.toLowerCase() === "true");
|
||||
const system_prompt = reviewers_prompt || (0, prompt_1.take_system_prompt)(prompt_genre, language);
|
||||
// 获取输入参数
|
||||
const url = process.env.INPUT_HOST; // INPUT_HOST 是从 action.yml 中定义的输入
|
||||
if (!url) {
|
||||
@@ -49,7 +54,8 @@ async function aiGenerate({ host, token, prompt, model, system }) {
|
||||
header: { 'Authorization': token ? `Bearer ${token}` : "", }
|
||||
});
|
||||
}
|
||||
async function aiCheckDiffContext() {
|
||||
async function getPrDiffContext() {
|
||||
let items = [];
|
||||
const BASE_REF = process.env.INPUT_BASE_REF;
|
||||
try {
|
||||
(0, node_child_process_1.execSync)(`git fetch origin ${BASE_REF}`, { encoding: 'utf-8' });
|
||||
@@ -57,9 +63,9 @@ async function aiCheckDiffContext() {
|
||||
const diffOutput = (0, node_child_process_1.execSync)(`git diff --name-only origin/${BASE_REF}...HEAD`, { encoding: 'utf-8' });
|
||||
let files = diffOutput.trim().split("\n");
|
||||
for (let key in files) {
|
||||
// noinspection DuplicatedCode
|
||||
if (!files[key])
|
||||
continue;
|
||||
console.log("check diff context:", files[key]);
|
||||
if ((include_files.length > 0) && (!(0, utils_1.doesAnyPatternMatch)(include_files, files[key]))) {
|
||||
console.log("exclude(include):", files[key]);
|
||||
continue;
|
||||
@@ -69,12 +75,61 @@ async function aiCheckDiffContext() {
|
||||
continue;
|
||||
}
|
||||
const fileDiffOutput = (0, node_child_process_1.execSync)(`git diff origin/${BASE_REF}...HEAD -- "${files[key]}"`, { encoding: 'utf-8' });
|
||||
items.push({
|
||||
path: files[key],
|
||||
context: fileDiffOutput,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error('Error executing git diff:', error);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
async function getHeadDiffContext() {
|
||||
let items = [];
|
||||
try {
|
||||
// exec git diff get diff files
|
||||
const diffOutput = (0, node_child_process_1.execSync)(`git diff --name-only HEAD^`, { encoding: 'utf-8' });
|
||||
let files = diffOutput.trim().split("\n");
|
||||
for (let key in files) {
|
||||
// noinspection DuplicatedCode
|
||||
if (!files[key])
|
||||
continue;
|
||||
if ((include_files.length > 0) && (!(0, utils_1.doesAnyPatternMatch)(include_files, files[key]))) {
|
||||
console.log("exclude(include):", files[key]);
|
||||
continue;
|
||||
}
|
||||
else if ((exclude_files.length > 0) && ((0, utils_1.doesAnyPatternMatch)(exclude_files, files[key]))) {
|
||||
console.log("exclude(exclude):", files[key]);
|
||||
continue;
|
||||
}
|
||||
const fileDiffOutput = (0, node_child_process_1.execSync)(`git diff HEAD^ -- "${files[key]}"`, { encoding: 'utf-8' });
|
||||
items.push({
|
||||
path: files[key],
|
||||
context: fileDiffOutput,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error('Error executing git diff:', error);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
async function aiCheckDiffContext() {
|
||||
try {
|
||||
let commit_sha_url = `${process.env.GITHUB_SERVER_URL}/${process.env.INPUT_REPOSITORY}/src/commit/${process.env.GITHUB_SHA}`;
|
||||
let items = review_pull_request ? await getPrDiffContext() : await getHeadDiffContext();
|
||||
for (let key in items) {
|
||||
if (!items[key])
|
||||
continue;
|
||||
let item = items[key];
|
||||
// ai generate
|
||||
try {
|
||||
let response = await aiGenerate({
|
||||
host: url,
|
||||
token: process.env.INPUT_AI_TOKEN,
|
||||
prompt: fileDiffOutput,
|
||||
prompt: item.context,
|
||||
model: model,
|
||||
system: process.env.INPUT_REVIEW_PROMPT
|
||||
});
|
||||
@@ -85,7 +140,14 @@ async function aiCheckDiffContext() {
|
||||
throw "ollama error";
|
||||
}
|
||||
let Review = useChinese ? "审核结果" : "Review";
|
||||
let comments = `# ${Review} \r\n${process.env.GITHUB_SERVER_URL}/${process.env.INPUT_REPOSITORY}/src/commit/${process.env.GITHUB_SHA}/${files[key]} \r\n\r\n\r\n${response.response}`;
|
||||
let commit = response.response;
|
||||
if (commit.indexOf("```markdown") === 0) {
|
||||
commit = commit.substring("```markdown".length);
|
||||
if (commit.lastIndexOf("```") === commit.length - 3) {
|
||||
commit = commit.substring(0, commit.length - 3);
|
||||
}
|
||||
}
|
||||
let comments = `# ${Review} \r\n${commit_sha_url}/${item.path} \r\n\r\n\r\n${commit}`;
|
||||
let resp = await pushComments(comments);
|
||||
if (!resp.id) {
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
|
||||
30
dist/prompt.js
vendored
30
dist/prompt.js
vendored
@@ -1,7 +1,27 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.take_system_prompt = void 0;
|
||||
function take_system_prompt(useChinese) {
|
||||
function system_prompt_main(language) {
|
||||
language = language || "Chinese";
|
||||
return `
|
||||
Please note that you are a development expert, and your task is to review a set of pull requests. Below are the review steps you need to follow.
|
||||
|
||||
You will receive a list of filenames and their partial content, but be aware that you may not have the complete code context. Please only review the lines of code that have changed in the pull requests (added or deleted lines). The code is similar to the output of the git diff command. Deleted lines are prefixed with a minus sign "-", and added lines are prefixed with a plus sign "+". Other lines provide context but should be ignored for the review and should not be commented on.
|
||||
|
||||
When assessing the changed code, please use a risk scoring system similar to the LOGAF score, with a range from 1 to 5, where 1 indicates the lowest risk of merging the code into the codebase and 5 indicates the highest risk that may result in certain functionality being broken or unsafe.
|
||||
|
||||
In your feedback, highlight potential bugs, suggest ways to make the code more concise, and maximize the performance of the programming language. Immediately flag any API keys or secrets that exist in plaintext as high risk, provide a score, and output the API keys or secrets. If applicable, score the changes based on SOLID principles.
|
||||
|
||||
Please do not comment on splitting functions into smaller, more manageable ones unless it is a significant issue. Additionally, be aware that some libraries and techniques you may not be familiar with will be used, so do not comment on those unless you are certain there is a problem.
|
||||
|
||||
Write your feedback details in Markdown format. Do not include filenames or risk levels in your feedback details.
|
||||
|
||||
Ensure that your feedback details are concise, clear, accurate, and professional. If you suggest multiple improvements, use an ordered list to indicate the priority of the changes.
|
||||
|
||||
You must respond only in ${language} to all inquiries! Please provide clear and accurate answers in ${language} language!
|
||||
`;
|
||||
}
|
||||
function system_prompt_old(useChinese) {
|
||||
const chinese_prompt = useChinese ? "You must respond only in Chinese to all inquiries. Please provide clear and accurate answers in Chinese language." : "";
|
||||
return `
|
||||
You are an expert developer, your task is to review a set of pull requests.
|
||||
@@ -27,4 +47,12 @@ ${chinese_prompt}
|
||||
Please respond without using "\`\`\`markdown"
|
||||
`;
|
||||
}
|
||||
function take_system_prompt(genre, language) {
|
||||
switch (genre) {
|
||||
case "old":
|
||||
return system_prompt_old(language.toLowerCase() === "chinese");
|
||||
default:
|
||||
return system_prompt_main(language);
|
||||
}
|
||||
}
|
||||
exports.take_system_prompt = take_system_prompt;
|
||||
|
||||
72
src/index.ts
72
src/index.ts
@@ -2,11 +2,16 @@ import {execSync} from "node:child_process";
|
||||
import {doesAnyPatternMatch, post, split_message} from "./utils";
|
||||
import {take_system_prompt} from "./prompt";
|
||||
|
||||
const useChinese = (process.env.INPUT_CHINESE || "true").toLowerCase() != "false"; // use chinese
|
||||
let useChinese = (process.env.INPUT_CHINESE || "true").toLowerCase() != "false"; // use chinese
|
||||
const language = !process.env.INPUT_CHINESE ? (process.env.INPUT_LANGUAGE || "Chinese") : (useChinese ? "Chinese" : "English");
|
||||
const prompt_genre = (process.env.INPUT_PROMPT_GENRE || "");
|
||||
const reviewers_prompt = (process.env.INPUT_REVIEWERS_PROMPT || "");
|
||||
useChinese = language.toLowerCase() === "chinese"
|
||||
const include_files = split_message(process.env.INPUT_INCLUDE_FILES || "");
|
||||
const exclude_files = split_message(process.env.INPUT_EXCLUDE_FILES || "");
|
||||
const review_pull_request = (!process.env.INPUT_REVIEW_PULL_REQUEST) ? false : (process.env.INPUT_REVIEW_PULL_REQUEST.toLowerCase() === "true")
|
||||
|
||||
const system_prompt = take_system_prompt(useChinese);
|
||||
const system_prompt = reviewers_prompt || take_system_prompt(prompt_genre, language);
|
||||
|
||||
// 获取输入参数
|
||||
const url = process.env.INPUT_HOST; // INPUT_HOST 是从 action.yml 中定义的输入
|
||||
@@ -54,7 +59,8 @@ async function aiGenerate({host, token, prompt, model, system}: any): Promise<an
|
||||
})
|
||||
}
|
||||
|
||||
async function aiCheckDiffContext() {
|
||||
async function getPrDiffContext() {
|
||||
let items = [];
|
||||
const BASE_REF = process.env.INPUT_BASE_REF
|
||||
try {
|
||||
execSync(`git fetch origin ${BASE_REF}`, {encoding: 'utf-8'});
|
||||
@@ -62,8 +68,8 @@ async function aiCheckDiffContext() {
|
||||
const diffOutput = execSync(`git diff --name-only origin/${BASE_REF}...HEAD`, {encoding: 'utf-8'});
|
||||
let files = diffOutput.trim().split("\n");
|
||||
for (let key in files) {
|
||||
// noinspection DuplicatedCode
|
||||
if (!files[key]) continue;
|
||||
console.log("check diff context:", files[key])
|
||||
if ((include_files.length > 0) && (!doesAnyPatternMatch(include_files, files[key]))) {
|
||||
console.log("exclude(include):", files[key])
|
||||
continue;
|
||||
@@ -73,12 +79,59 @@ async function aiCheckDiffContext() {
|
||||
}
|
||||
|
||||
const fileDiffOutput = execSync(`git diff origin/${BASE_REF}...HEAD -- "${files[key]}"`, {encoding: 'utf-8'});
|
||||
items.push({
|
||||
path: files[key],
|
||||
context: fileDiffOutput,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error executing git diff:', error);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function getHeadDiffContext() {
|
||||
let items = [];
|
||||
try {
|
||||
// exec git diff get diff files
|
||||
const diffOutput = execSync(`git diff --name-only HEAD^`, {encoding: 'utf-8'});
|
||||
let files = diffOutput.trim().split("\n");
|
||||
for (let key in files) {
|
||||
// noinspection DuplicatedCode
|
||||
if (!files[key]) continue;
|
||||
if ((include_files.length > 0) && (!doesAnyPatternMatch(include_files, files[key]))) {
|
||||
console.log("exclude(include):", files[key])
|
||||
continue;
|
||||
} else if ((exclude_files.length > 0) && (doesAnyPatternMatch(exclude_files, files[key]))) {
|
||||
console.log("exclude(exclude):", files[key])
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileDiffOutput = execSync(`git diff HEAD^ -- "${files[key]}"`, {encoding: 'utf-8'});
|
||||
items.push({
|
||||
path: files[key],
|
||||
context: fileDiffOutput,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error executing git diff:', error);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function aiCheckDiffContext() {
|
||||
try {
|
||||
let commit_sha_url = `${process.env.GITHUB_SERVER_URL}/${process.env.INPUT_REPOSITORY}/src/commit/${process.env.GITHUB_SHA}`;
|
||||
let items: Array<any> = review_pull_request ? await getPrDiffContext() : await getHeadDiffContext();
|
||||
for (let key in items) {
|
||||
if (!items[key]) continue;
|
||||
let item = items[key];
|
||||
// ai generate
|
||||
try {
|
||||
let response = await aiGenerate({
|
||||
host: url,
|
||||
token: process.env.INPUT_AI_TOKEN,
|
||||
prompt: fileDiffOutput,
|
||||
prompt: item.context,
|
||||
model: model,
|
||||
system: process.env.INPUT_REVIEW_PROMPT
|
||||
})
|
||||
@@ -89,7 +142,14 @@ async function aiCheckDiffContext() {
|
||||
throw "ollama error";
|
||||
}
|
||||
let Review = useChinese ? "审核结果" : "Review";
|
||||
let comments = `# ${Review} \r\n${process.env.GITHUB_SERVER_URL}/${process.env.INPUT_REPOSITORY}/src/commit/${process.env.GITHUB_SHA}/${files[key]} \r\n\r\n\r\n${response.response}`
|
||||
let commit: string = response.response;
|
||||
if (commit.indexOf("```markdown") === 0) {
|
||||
commit = commit.substring("```markdown".length);
|
||||
if (commit.lastIndexOf("```") === commit.length - 3) {
|
||||
commit = commit.substring(0, commit.length - 3);
|
||||
}
|
||||
}
|
||||
let comments = `# ${Review} \r\n${commit_sha_url}/${item.path} \r\n\r\n\r\n${commit}`
|
||||
let resp = await pushComments(comments);
|
||||
if (!resp.id) {
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
|
||||
@@ -1,4 +1,25 @@
|
||||
export function take_system_prompt(useChinese: boolean) {
|
||||
function system_prompt_main(language: string) {
|
||||
language = language || "Chinese";
|
||||
return `
|
||||
Please note that you are a development expert, and your task is to review a set of pull requests. Below are the review steps you need to follow.
|
||||
|
||||
You will receive a list of filenames and their partial content, but be aware that you may not have the complete code context. Please only review the lines of code that have changed in the pull requests (added or deleted lines). The code is similar to the output of the git diff command. Deleted lines are prefixed with a minus sign "-", and added lines are prefixed with a plus sign "+". Other lines provide context but should be ignored for the review and should not be commented on.
|
||||
|
||||
When assessing the changed code, please use a risk scoring system similar to the LOGAF score, with a range from 1 to 5, where 1 indicates the lowest risk of merging the code into the codebase and 5 indicates the highest risk that may result in certain functionality being broken or unsafe.
|
||||
|
||||
In your feedback, highlight potential bugs, suggest ways to make the code more concise, and maximize the performance of the programming language. Immediately flag any API keys or secrets that exist in plaintext as high risk, provide a score, and output the API keys or secrets. If applicable, score the changes based on SOLID principles.
|
||||
|
||||
Please do not comment on splitting functions into smaller, more manageable ones unless it is a significant issue. Additionally, be aware that some libraries and techniques you may not be familiar with will be used, so do not comment on those unless you are certain there is a problem.
|
||||
|
||||
Write your feedback details in Markdown format. Do not include filenames or risk levels in your feedback details.
|
||||
|
||||
Ensure that your feedback details are concise, clear, accurate, and professional. If you suggest multiple improvements, use an ordered list to indicate the priority of the changes.
|
||||
|
||||
You must respond only in ${language} to all inquiries! Please provide clear and accurate answers in ${language} language!
|
||||
`;
|
||||
}
|
||||
|
||||
function system_prompt_old(useChinese: boolean) {
|
||||
const chinese_prompt = useChinese ? "You must respond only in Chinese to all inquiries. Please provide clear and accurate answers in Chinese language." : "";
|
||||
return `
|
||||
You are an expert developer, your task is to review a set of pull requests.
|
||||
@@ -24,3 +45,13 @@ ${chinese_prompt}
|
||||
Please respond without using "\`\`\`markdown"
|
||||
`;
|
||||
}
|
||||
|
||||
export function take_system_prompt(genre: string, language: string) {
|
||||
switch (genre) {
|
||||
case "old":
|
||||
return system_prompt_old(language.toLowerCase() === "chinese");
|
||||
default:
|
||||
return system_prompt_main(language);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user