9 Commits

Author SHA1 Message Date
caesar
68bae31202 update doc 2025-01-16 20:24:55 +08:00
caesar
628739dac0 Optimize internal logic. 2025-01-16 20:15:19 +08:00
caesar
a51f65540d update input language 2025-01-16 19:02:25 +08:00
kekxv
149be95c11 Create LICENSE 2025-01-16 09:43:56 +08:00
caesar
327c45551f update doc 2025-01-16 09:25:48 +08:00
caesar
ef9245d7d5 update doc 2025-01-16 09:25:24 +08:00
caesar
a5b330c5bf fix include exclude 2025-01-16 09:20:36 +08:00
caesar
484116be5c fix 2025-01-16 09:06:11 +08:00
caesar
5348ca237b fix 2025-01-15 22:38:01 +08:00
14 changed files with 4375 additions and 220 deletions

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

187
README.md
View File

@@ -43,11 +43,15 @@ jobs:
with:
fetch-depth: 0
- name: Review code
uses: kekxv/AiReviewPR@v0.0.1
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
```
效果如下:
@@ -65,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).

View File

@@ -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

89
dist/index.js vendored
View File

@@ -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,27 +63,73 @@ 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;
if (include_files.length > 0) {
if (!(0, utils_1.doesAnyPatternMatch)(include_files, files[key])) {
console.log("exclude(include):", files[key]);
continue;
}
if ((include_files.length > 0) && (!(0, utils_1.doesAnyPatternMatch)(include_files, files[key]))) {
console.log("exclude(include):", files[key]);
continue;
}
if (exclude_files.length > 0) {
if ((0, utils_1.doesAnyPatternMatch)(exclude_files, files[key])) {
console.log("exclude(exclude):", 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 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
});
@@ -88,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
View File

@@ -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;

18
dist/utils.js vendored
View File

@@ -7,15 +7,19 @@ exports.post = exports.doesAnyPatternMatch = exports.split_message = void 0;
const http_1 = __importDefault(require("http"));
const https_1 = __importDefault(require("https"));
function split_message(files) {
console.log("files debug:", files);
files = files || "";
let n = files.includes('\n') || files.includes('\r');
files = files.trim();
if (!files) {
let t = files.split("\n");
if (t.length > 0)
return t.map(str => str.trim());
return files.split(",").map(str => str.trim());
let res = [];
if (files) {
if (n) {
res = files.split(/[\r\n]/);
}
else {
res = files.split(",");
}
}
return [];
return res.map(str => str.trim()).filter(item => item !== null && item !== undefined && item !== "");
}
exports.split_message = split_message;
function doesAnyPatternMatch(patterns, str) {

4
jest.config.js Normal file
View File

@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};

3854
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,9 +6,10 @@
"build": "tsc"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"@types/node": "^22.10.6",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"typescript": "^4.5.4"
},
"dependencies": {
}
}

View File

@@ -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,26 +68,70 @@ 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;
if (include_files.length > 0) {
if (!doesAnyPatternMatch(include_files, files[key])) {
console.log("exclude(include):", files[key])
continue;
}
}
if (exclude_files.length > 0) {
if (doesAnyPatternMatch(exclude_files, files[key])) {
console.log("exclude(exclude):", 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 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
})
@@ -92,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

View File

@@ -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);
}
}

View File

@@ -1,15 +1,19 @@
import http from "http";
import https from "https";
export function split_message(files: string) {
console.log("files debug:",files)
export function split_message(files: string): string[] {
files = files || "";
let n = files.includes('\n') || files.includes('\r');
files = files.trim()
if (!files) {
let t = files.split("\n");
if (t.length > 0) return t.map(str => str.trim());
return files.split(",").map(str => str.trim())
let res: string[] = [];
if (files) {
if (n) {
res = files.split(/[\r\n]/);
} else {
res = files.split(",")
}
}
return []
return res.map(str => str.trim()).filter(item => item !== null && item !== undefined && item !== "")
}
export function doesAnyPatternMatch(patterns: Array<string>, str: string) {

View File

@@ -0,0 +1,30 @@
// split_message.test.ts
import {doesAnyPatternMatch, split_message} from '../src/utils';
describe('split_message', () => {
it('include readme.md', () => {
const testString = `^.+\\.md
test2\\.js
dist/.*
`;
expect(doesAnyPatternMatch(split_message(testString), "readme.md")).toBe(true);
expect(doesAnyPatternMatch(split_message(testString), "dist/index.js")).toBe(true);
expect(doesAnyPatternMatch(split_message(testString), "dist/prompt.js")).toBe(true);
expect(doesAnyPatternMatch(split_message(testString), "src/index.js")).toBe(false);
});
});
describe('split_message', () => {
it('include readme.md', () => {
const testString = `^.+\\.md
test2\\.js
dist/.*
`;
let file = "README.md";
let include_files = split_message(testString);
console.log("check diff context:", file)
expect(((include_files.length > 0) && (doesAnyPatternMatch(include_files, file)))).toBe(true);
});
});

View File

@@ -5,7 +5,8 @@
"node_modules/@types"
],
"types": [
"node"
"node",
"jest"
],
"target": "ES2020",
// 编译目标