目录

在 gitlab 中使用 chatgpt 做 code review

文章简介:介绍在 gitlab 中使用 chatgpt 做 code review 的方法和代码

最近 chatgpt 非常火暴,实际体验感受了一下,其在作为辅助工具上还是可以使用的.

当前 chatgpt apitoken 接入在国内是可以直接访问的.

准备

首先,我们需要一些魔法手段获得一个账号以及生成一个 chatgpt 的 apitoken.

当前使用的 prompt

1
2
Bellow is the code patch, please help me do a brief code review, if any bug risk and improvement suggestion are welcome
%s

除此之外,还有很多好玩有用的 prompt 见 这里

开始制作 code review 脚本

CI 中使用 chatgpt 做 code review 的主要实现思路是:

  1. 使用 git diff 生成当前 mr 的 patch
  2. 向我的后端转发服务器发送 patch, 返回 code review 的结果
  3. 向当前 mr 创建评论,评论内容为 code review 的结果

如下是我们自动 code review 脚本,其中 http://1.1.1.1:5151/ 是我开发的一个后端服务,将的请求代理到 chatgpt中.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
git fetch
git diff origin/${CI_MERGE_REQUEST_TARGET_BRANCH_NAME:-"main"}...origin/${CI_COMMIT_REF_NAME} | tee mr.patch

echo "patch"
CHATBODY=$(jq --null-input --arg category "code_review" --arg prompt "$(cat mr.patch)" '{"category": $category, "prompt": $prompt}')

echo "code reviews"
curl -X 'POST' 'http://1.1.1.1:5151/api/v1/chat/conversation' -H 'accept: text/plain' -H 'Content-Type: application/json'  -d "${CHATBODY}" | tee code_review.txt

# echo "comments"
NOTES=$(jq --null-input --arg body "$(cat code_review.txt)" '{"body": $body}')
curl --location --request POST --header "PRIVATE-TOKEN: $ADMIN_ACCESS_TOKEN" --header "Content-Type: application/json" "https://git.example.com/api/v4/projects/$CI_MERGE_REQUEST_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes" -d "$NOTES" -k

实际发送的 prompt 见如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
Bellow is the code patch, please help me do a brief code review, if any bug risk and improvement suggestion are welcome

diff --git a/content/posts/ai/gitlab-chatgpt-mr-code-review.md b/content/posts/ai/gitlab-chatgpt-mr-code-review.md
index 0f3a990..dab4d0b 100644
--- a/content/posts/ai/gitlab-chatgpt-mr-code-review.md
+++ b/content/posts/ai/gitlab-chatgpt-mr-code-review.md
@@ -18,6 +18,15 @@ date: 2023-02-28T08:50:33+08:00
 
 首先,我们需要一些魔法手段获得一个账号以及生成一个 chatgpt 的 apitoken.
 
+## 当前使用的 prompt
+
+```txt
+Bellow is the code patch, please help me do a brief code review, if any bug risk and improvement suggestion are welcome
+%s
+```
+
+除此之外,还有很多好玩有用的 prompt 见 [这里](https://github.com/f/awesome-chatgpt-prompts)
+
 ## 开始制作 code review 脚本
 
 CI 中使用 chatgpt 做 code review 的主要实现思路是:

我的 chatgpt code review 计划在提交 mr 以及 mr 的每次 commit 的时候执行。

.gitlab.yaml 文件部分内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
chatgpt:
  stage: check
  image: alpine:edge
  script:
    - apk add git curl
    - ci/chatgpt.sh
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
    - when: never

/media/img/ai/gitlab-chatgpt-mr-code-review/image-20230227135358028.png