Skip to content

Commit a816b35

Browse files
author
siquanlv
committed
ai review test
1 parent 2ba2ee9 commit a816b35

File tree

4 files changed

+135
-103
lines changed

4 files changed

+135
-103
lines changed

.github/scripts/ai_code_review.py renamed to .github/scripts/ai_review.py

Lines changed: 64 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
import os
2-
import requests
32
import openai
3+
from github import Github
44

5-
def load_event():
6-
event_path = os.environ["GITHUB_EVENT_PATH"]
7-
with open(event_path, "r") as f:
8-
return json.load(f)
95

10-
def get_pr_diff(diff_url, github_token):
11-
response = requests.get(diff_url, headers={
12-
"Authorization": f"token {github_token}",
13-
"Accept": "application/vnd.github.v3.diff"
14-
})
15-
response.raise_for_status()
16-
return response.text
6+
# def load_event():
7+
# event_path = os.environ["GITHUB_EVENT_PATH"]
8+
# with open(event_path, "r") as f:
9+
# return json.load(f)
10+
#
11+
# def get_pr_diff(diff_url, github_token):
12+
# response = requests.get(diff_url, headers={
13+
# "Authorization": f"token {github_token}",
14+
# "Accept": "application/vnd.github.v3.diff"
15+
# })
16+
# response.raise_for_status()
17+
# return response.text
1718

1819

1920
# def load_diff(file_path="pr.diff"):
@@ -24,20 +25,41 @@ def get_pr_diff(diff_url, github_token):
2425
# with open(file_path, "r", encoding="utf-8") as f:
2526
# return f.read()
2627

27-
def call_gpt(diff_text):
28+
OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
29+
OPENAI_API_ENDPOINT = os.environ.get('OPENAI_API_ENDPOINT')
30+
GITHUB_TOKEN = os.environ['GITHUB_TOKEN']
31+
PR_NUMBER = int(os.environ['PR_NUMBER'])
32+
REPO_NAME = os.environ['REPO']
33+
34+
def call_gpt():
2835
"""Call AI to review the diff."""
29-
api_key = os.environ.get("OPENAI_API_KEY")
36+
api_key = OPENAI_API_KEY
3037
if not api_key:
3138
raise ValueError("❌ OPENAI_API_KEY is not set.")
3239

33-
api_endpoint = os.environ.get("OPENAI_API_ENDPOINT")
40+
api_endpoint = OPENAI_API_ENDPOINT
3441

3542
client = openai.OpenAI(
3643
api_key=api_key,
3744
base_url=api_endpoint,
3845
default_headers={"api-key": api_key},
3946
)
4047

48+
gh = Github(GITHUB_TOKEN)
49+
repo = gh.get_repo(REPO_NAME)
50+
pr = repo.get_pull(PR_NUMBER)
51+
52+
diff = pr.patch_url
53+
files = pr.get_files()
54+
changed_files = []
55+
for f in files:
56+
if f.status != "removed":
57+
file_content = f"File: {f.filename}\nPatch:\n{f.patch}\n"
58+
changed_files.append(file_content)
59+
60+
diff_text = "\n\n".join(changed_files)
61+
62+
4163
prompt = f"""
4264
You are a senior Java code reviewer.
4365
@@ -76,36 +98,33 @@ def call_gpt(diff_text):
7698
],
7799
temperature=0.2,
78100
)
79-
return response.choices[0].message.content
80-
81-
82-
def post_pr_comment(review_text):
83-
"""Post review result as a comment on the PR."""
84-
repo = os.getenv("GITHUB_REPOSITORY")
85-
pr_number = os.getenv("PR_NUMBER")
86-
token = os.getenv("GITHUB_TOKEN")
87-
88-
url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments"
89-
headers = {
90-
"Authorization": f"token {token}",
91-
"Accept": "application/vnd.github.v3+json",
92-
}
93-
payload = {"body": review_text}
94-
95-
print("📝 Posting review comment to PR...")
96-
response = requests.post(url, headers=headers, json=payload)
97-
if response.status_code != 201:
98-
print(f"❌ Failed to post comment: {response.status_code}")
99-
print(response.text)
100-
else:
101-
print("✅ Review comment posted successfully.")
102-
103-
def post_comment(comment_url, body, github_token):
104-
response = requests.post(comment_url, headers={
105-
"Authorization": f"token {github_token}",
106-
"Accept": "application/vnd.github.v3+json"
107-
}, json={"body": body})
108-
response.raise_for_status()
101+
review_comment = response.choices[0].message.content
102+
pr.create_issue_comment(f"🤖 **AI Code Review:**\n\n{review_comment}")
103+
print("✅ Review comment posted.")
104+
105+
106+
107+
# def post_pr_comment(review_text):
108+
# """Post review result as a comment on the PR."""
109+
# repo = os.getenv("GITHUB_REPOSITORY")
110+
# pr_number = os.getenv("PR_NUMBER")
111+
# token = os.getenv("GITHUB_TOKEN")
112+
#
113+
# url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments"
114+
# headers = {
115+
# "Authorization": f"token {token}",
116+
# "Accept": "application/vnd.github.v3+json",
117+
# }
118+
# payload = {"body": review_text}
119+
#
120+
# print("📝 Posting review comment to PR...")
121+
# response = requests.post(url, headers=headers, json=payload)
122+
# if response.status_code != 201:
123+
# print(f"❌ Failed to post comment: {response.status_code}")
124+
# print(response.text)
125+
# else:
126+
# print("✅ Review comment posted successfully.")
127+
109128

110129
def main():
111130
# diff = load_diff()

.github/workflows/ai_code_review.yml

Lines changed: 0 additions & 58 deletions
This file was deleted.

.github/workflows/ai_review.yml

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
name: AI Code Review on PR
2+
3+
on:
4+
pull_request:
5+
types: [labeled]
6+
7+
permissions:
8+
contents: read
9+
pull-requests: write
10+
11+
jobs:
12+
AI-Review:
13+
if: github.event.label.name == 'pending-ai-review'
14+
runs-on: ubuntu-latest
15+
16+
steps:
17+
- name: 🔍 Debug workspace structure
18+
run: ls -R .github
19+
20+
- name: 🐍 Set up Python
21+
uses: actions/setup-python@v5
22+
with:
23+
python-version: '3.10'
24+
25+
- name: 📦 Install dependencies
26+
run: pip install openai PyGithub
27+
28+
- name: ✅ Checkout the default branch
29+
uses: actions/checkout@v4
30+
with:
31+
ref: ${{ github.event.pull_request.head.ref }}
32+
repository: ${{ github.event.pull_request.head.repo.full_name }}
33+
34+
# - name: 🧾 Download PR diff via GitHub API
35+
# id: pr_diff
36+
# env:
37+
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
38+
# GITHUB_REPOSITORY: ${{ github.repository }}
39+
# PR_NUMBER: ${{ github.event.pull_request.number }}
40+
# run: |
41+
# # 确保 GITHUB_TOKEN 有权限读取 PR
42+
# PR_DIFF=$(gh pr view ${{ github.event.number }} --json files --jq '.files | map(.patch) | join("\n")')
43+
# # 将 diff 输出设置为一个环境变量
44+
# echo "PR_DIFF<<EOF" >> $GITHUB_ENV
45+
# echo "$PR_DIFF" >> $GITHUB_ENV
46+
# echo "EOF" >> $GITHUB_ENV
47+
48+
- name: 🤖 Run AI code review
49+
env:
50+
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
51+
OPENAI_API_ENDPOINT: ${{ secrets.OPENAI_API_ENDPOINT }}
52+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
53+
GITHUB_REPOSITORY: ${{ github.repository }}
54+
PR_NUMBER: ${{ github.event.pull_request.number }}
55+
REPO: ${{ github.repository }}
56+
run: python .github/scripts/ai_review.py

.github/workflows/pr-label.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
name: Mark PR for AI Review
2+
3+
on:
4+
pull_request:
5+
types: [opened, synchronize]
6+
7+
jobs:
8+
add-label:
9+
runs-on: ubuntu-latest
10+
steps:
11+
- name: Add 'pending-ai-review' label
12+
uses: actions-ecosystem/action-add-labels@v1
13+
with:
14+
github_token: ${{ secrets.GITHUB_TOKEN }}
15+
labels: pending-ai-review

0 commit comments

Comments
 (0)