Claude Code 提供了 GitHub Actions 集成,让你在 CI/CD 流水线中调用 AI 能力:自动审查 PR、生成测试、修复代码质量问题,全部在 GitHub 工作流中完成。
核心能力
- PR 自动审查:每次 PR 创建或更新时,自动进行 AI 代码审查
- 测试生成:自动为新代码生成单元测试
- 代码质量检查:在合并前发现潜在问题
- 文档更新:代码更改时自动更新相关文档
- Issue 分析:分析 Bug 报告并提出修复建议
快速开始
添加 API Key 到 GitHub Secrets
GitHub 仓库 -> Settings -> Secrets and variables -> Actions
添加 Secret: ANTHROPIC_API_KEY = your_api_key
基础工作流:PR 代码审查
创建 .github/workflows/claude-review.yml:
yaml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run Claude Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
claude --print \
--allowedTools "Read,Write,Bash" \
"审查这个 PR 的代码变更,重点关注:
1. 潜在的 Bug 或逻辑错误
2. 安全漏洞
3. 性能问题
4. 代码风格一致性
以 GitHub PR 评论格式输出结果"自动生成测试
yaml
name: Generate Tests
on:
pull_request:
paths:
- 'src/**/*.js'
- 'src/**/*.ts'
jobs:
generate-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Generate Missing Tests
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | while read file; do
testfile=$(echo $file | sed 's/src/tests/')
if [ ! -f "$testfile" ]; then
claude --print --allowedTools "Read,Write" \
"为 $file 生成完整的 Jest 单元测试,保存到 $testfile"
fi
done
- name: Commit Generated Tests
run: |
git config --global user.email "claude-bot@example.com"
git config --global user.name "Claude Bot"
git add tests/
git diff --staged --quiet || git commit -m "feat: auto-generate tests by Claude"
git push--print 模式
GitHub Actions 中通常使用 --print 模式(非交互模式):
bash
claud --print "任务描述" # 执行并打印结果
claud --print --allowedTools "Read,Write" "..." # 指定允许的工具
claud --print --output-format json "..." # JSON 格式输出--print 模式关键特性:
- 非交互,适合 CI 环境
- 执行完成后自动退出
- 返回码反映任务成功/失败
权限配置
不同任务所需的 GitHub Actions 权限:
| 任务 | 所需权限 |
|---|---|
| 读取代码 | contents: read |
| 创建 PR 评论 | pull-requests: write |
| 提交代码 | contents: write |
| 创建 Issues | issues: write |
成本控制
GitHub Actions 中每次 Claude 调用都会消耗 API token,建议:
yaml
# 只在特定标签的 PR 上运行
on:
pull_request:
types: [labeled]
# 只有打了 ai-review 标签的 PR 才触发
jobs:
review:
if: contains(github.event.pull_request.labels.*.name, 'ai-review')或限制运行频率:
yaml
on:
pull_request:
types: [opened] # 只在 PR 首次创建时运行,而非每次 push与官方 Claude Code Action 结合
Anthropic 提供官方 GitHub Action:
yaml
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
task: "审查代码并创建 PR 评论"原文整理自:Claude Code GitHub Actions | 来源:Anthropic 官方文档