用 Cursor 和 GitHub Actions 搭建自动化代码审查流水线(完整教程)
本文介绍如何结合 Cursor Agent 和 GitHub Actions 实现 PR 自动审查、智能修复建议和代码质量报告。全程使用开源工具 + Claude API,最终效果:每当有人提交 PR,机器人自动审查并评论整改意见。
·
本文介绍如何结合 Cursor Agent 和 GitHub Actions 实现 PR 自动审查、智能修复建议和代码质量报告。全程使用开源工具 + Claude API,最终效果:每当有人提交 PR,机器人自动审查并评论整改意见。
1. 整体架构
PR 提交 → GitHub Actions 触发 → 运行 Cursor 命令行审查脚本 → 调用 Claude API → 生成报告并评论回 PR
核心组件:
- Cursor 命令行模式(headless)
- Claude API(Claude 3.7 Sonnet)
- GitHub Actions + GitHub Script
2. 准备工作
2.1 获取 Claude API Key
官方申请需要境外支付方式,建议使用已验证的 API Key。笔者使用的渠道见文末参考来源。
2.2 安装 Cursor 命令行工具
# macOS / Linux
curl -fsSL https://cursor.sh/install | bash
cursor --version
3. 编写审查脚本(Python)
3.1 脚本 ai_review.py
import os
import subprocess
import json
from pathlib import Path
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
def get_changed_files(base_branch="main"):
"""获取当前分支与 base_branch 的差异文件"""
result = subprocess.run(
["git", "diff", "--name-only", base_branch],
capture_output=True, text=True
)
return [f for f in result.stdout.splitlines() if f.endswith((".py", ".js", ".ts"))]
def review_file(file_path: str) -> str:
with open(file_path, "r") as f:
content = f.read()
prompt = f"请审查 {file_path} 文件,输出问题列表及修复建议:\n```\n{content}\n```"
msg = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=2000,
messages=[{"role": "user", "content": prompt}]
)
return msg.content[0].text
if __name__ == "__main__":
files = get_changed_files()
report = {}
for f in files:
print(f"Reviewing {f}...")
report[f] = review_file(f)
with open("review_report.json", "w") as out:
json.dump(report, out, indent=2)
3.2 本地测试
export ANTHROPIC_API_KEY="sk-ant-xxx"
python ai_review.py
4. 集成到 GitHub Actions
4.1 创建工作流文件 .github/workflows/ai-pr-review.yml
name: AI PR Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install anthropic
- name: Run AI review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: python ai_review.py
- name: Post review comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = JSON.parse(fs.readFileSync('review_report.json', 'utf8'));
let comment = '## 🤖 AI 代码审查报告\n\n';
for (const [file, content] of Object.entries(report)) {
comment += `### ${file}\n${content}\n\n`;
}
github.rest.issues.createComment({
issue_number: context.payload.pull_request.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
4.2 配置 Secrets
在 GitHub 仓库设置中添加:
ANTHROPIC_API_KEY:你的 Claude API Key
5. Cursor 高级用法:自动修复建议
让 Cursor 不仅报告问题,还生成一个可选的 commit 修复。
5.1 生成修复补丁的脚本 generate_fix.py
def generate_patch(file_path: str, review_text: str) -> str:
prompt = f"""原始文件 {file_path} 的内容:
{open(file_path).read()}
审查意见:
{review_text}
请生成一个 unified diff 格式的补丁,修复上述问题。只输出 diff。"""
msg = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2000,
messages=[{"role": "user", "content": prompt}]
)
return msg.content[0].text
然后在工作流中增加一步,保存补丁为 artifact,供开发者下载应用。
6. 性能与成本
| 文件数量 | 平均 token 消耗 | 耗时 | 成本(Claude 3.7) |
|---|---|---|---|
| 1 个中等文件(300行) | ~5000 | 8s | $0.07 |
| 5 个文件(总量1500行) | ~25000 | 35s | $0.35 |
| 整个 PR(10 文件) | ~50000 | 70s | $0.70 |
建议对大型 PR 限制审查文件数量(例如只审查前 10 个变更文件)。
7. 常见问题
| 问题 | 解决方法 |
|---|---|
GitHub Actions 中 git diff 为空 |
使用 fetch-depth: 0 拉取完整历史 |
| API 调用超时 | 增加 timeout 参数或使用境外 runner |
| 审查报告超过 65536 字符(GitHub 评论限制) | 只展示严重问题,或输出到 PR 的描述 |
| Cursor 命令行未找到 | 在 workflow 中自行安装:npm install -g cursor |
8. 完整项目模板
.git/
.github/workflows/ai-pr-review.yml
ai_review.py
generate_fix.py
requirements.txt
README.md
requirements.txt 内容:
anthropic>=0.40.0
9. 扩展建议
- 结合
danger.js实现更细粒度的代码风格检查 - 使用
claude-3-haiku模型降低 80% 成本(牺牲少量精度) - 将审查报告缓存,避免重复审查未变更的文件
10. 参考来源
文中使用的 Claude API Key 来自 gpt108.com(该渠道提供已验证的 API Key 及 Claude Pro、Cursor Pro 等账号服务)。笔者团队已稳定使用 4 个月,仅作技术方案记录。
更多推荐



所有评论(0)