把 AI 代码审查集成到 CI/CD 流水线——每次 PR 自动审查代码质量
之前做了独立的 AI 代码审查 CLI。这篇更进一步——把它嵌入 CI/CD,每次提交 PR 自动审查,发现问题直接评论在 PR 上。
GitHub Actions 集成
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
ai-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: pip install openai
- name: AI Code Review
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
run: |
python -c "
import os, subprocess, json
from openai import OpenAI
client = OpenAI(api_key=os.environ['DEEPSEEK_API_KEY'], base_url='https://api.deepseek.com/v1')
diff = subprocess.run(['git', 'diff', 'origin/main...HEAD'], capture_output=True, text=True).stdout
if not diff.strip(): exit(0)
resp = client.chat.completions.create(model='deepseek-chat', messages=[{
'role': 'system', 'content': f'''你是代码审查专家。审查以下 diff,找出:
1. 🔴 安全风险 2. 🟡 性能问题 3. 🔵 代码质量
输出 Markdown 格式,每条标注文件、行号和严重程度。\n\n{diff[:15000]}'''}], temperature=0.2)
review = resp.choices[0].message.content
with open('/tmp/review.md', 'w') as f: f.write(review)
# 发布 PR 评论
import requests
headers = {'Authorization': f'token {os.environ[\"GITHUB_TOKEN\"]}', 'Accept': 'application/vnd.github.v3+json'}
pr_url = os.environ['GITHUB_API_URL'] + '/repos/' + os.environ['GITHUB_REPOSITORY'] + '/issues/' + os.environ['GITHUB_REF_NAME'].split('/')[0] + '/comments'
with open('/tmp/review.md') as f:
requests.post(pr_url, headers=headers, json={'body': f'## 🤖 AI Code Review\n\n{f.read()}'})
"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_API_URL: ${{ github.api_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GitLab CI 集成
# .gitlab-ci.yml
ai-review:
stage: review
image: python:3.11-slim
before_script:
- pip install openai
script:
- python -c "
import os, subprocess
from openai import OpenAI
client = OpenAI(api_key=os.environ['DEEPSEEK_KEY'], base_url='https://api.deepseek.com/v1')
diff = subprocess.run(['git', 'diff', 'origin/main...HEAD'], capture_output=True, text=True).stdout
if not diff: exit(0)
resp = client.chat.completions.create(model='deepseek-chat', messages=[{'role':'system','content':f'审查代码diff:\\n{diff[:10000]}'}], temperature=0.2)
print(resp.choices[0].message.content)
"
only:
- merge_requests
本地 pre-commit hook
```bash
!/bin/bash
.git/hooks/pre-commit
echo "🤖 AI 正在审查代码..."
diff=$(git diff --cached)
if [ -z "$diff" ]; then
echo "✅ 没有改动"
exit 0
fi
review=$(python3 -c "
import os, sys
from openai import OpenAI
client = OpenAI(api_key=os.environ.get('DEEPSEEK_KEY',''), base_url='https://api.deepseek.com/v1')
resp = client.chat.completions.create(model='deepseek-chat', messages=[{'role':'system','content':f'审查以下代码改动,只报告严重问题(安全漏洞、明显bug)。改动很小或没问题就说\"✅\"。\n\n{sys.stdin.read()[:8000]}'}], temperature=0.2)
print(resp.choices[0].message.content)
" 本文由 Zyentor(智元界)原创发布