跳转到内容

CI/CD 集成

Claude Code 可以深度集成到 CI/CD 工作流中,从自动代码审查到发布说明生成。通过 headless 模式和 Unix 管道,你可以在自动化管道中充分利用 AI 能力。

Headless 模式

非交互式运行 Claude Code,适用于自动化脚本和 CI 环境。

Unix 管道

将任何命令输出通过管道传递给 Claude 进行分析和转换。

GitHub Actions

在 PR 审查、测试和发布流程中自动运行 Claude Code。

发布自动化

自动生成发布说明和变更日志。


使用 -p 标志在无交互提示的情况下运行 Claude Code:

Terminal window
# 基本 headless 执行
claude -p "Run the tests and report results"
# 带超时
claude -p --timeout 300 "Build the project"
# 指定模型
claude -p --model sonnet "Analyze code quality"

Claude Code 支持 Unix 管道操作,实现强大的 Shell 集成,用于自动化代码分析和转换。

Terminal window
# 将内容通过管道传递给 Claude
cat file.txt | claude -p 'analyze this code'
# 将命令输出传递给 Claude 分析
git diff | claude -p 'explain these changes'
# 将测试输出传递给 Claude
npm test 2>&1 | claude -p 'summarize test failures and suggest fixes'
Terminal window
# 自动审查 PR 差异
git diff main...feature-branch | claude -p 'Review this diff for security issues'

--output-format 标志控制 Claude 的响应格式:

格式用途示例
text人类可读输出(默认)claude -p 'explain' --output-format text
json机器可解析的结构化数据claude -p 'analyze' --output-format json
stream-json大输出的实时流式传输claude -p 'transform' --output-format stream-json
Terminal window
# 获取结构化 JSON 输出
git status --short | claude -p 'Categorize changes' --output-format json
# 结构化分析示例
git log --oneline -10 | claude -p 'Categorize commits by type' --output-format json
# 与 jq 结合处理 JSON
echo "const x = 1" | claude -p 'analyze' --output-format json | jq '.suggestions[]'
  1. 提示要具体

    Terminal window
    # 好:具体的任务
    git diff | claude -p 'List all function signature changes'
    # 不够好:模糊的请求
    git diff | claude -p 'analyze this'
  2. 限制输入大小

    Terminal window
    # 好:限定范围
    git diff --name-only | head -n 10 | xargs cat | claude -p 'review'
    # 风险:可能超出上下文
    cat entire-codebase/* | claude -p 'review'
  3. 自动化场景使用 -p 标志

    Terminal window
    cat file.txt | claude -p 'fix linting errors' > output.txt
  4. 结合 jq 处理 JSON 输出

    Terminal window
    echo "const x = 1" | claude -p 'analyze' --output-format json | jq '.suggestions[]'

package.json 中添加 Claude Code 命令:

{
"scripts": {
"claude-review": "git diff main | claude -p 'Review for security issues' --output-format json > review.json",
"claude-test-summary": "npm test 2>&1 | claude -p 'Summarize failures and suggest fixes'",
"claude-docs": "cat src/**/*.ts | claude -p 'Generate API documentation' > API.md",
"precommit-check": "git diff --cached | claude -p 'Check for secrets or anti-patterns' && git diff --cached | prettier --check"
}
}

将 Claude Code 集成到 Git Hooks 中,实现提交前和推送前的自动检查。

.git/hooks/pre-commit
#!/bin/bash
# 使用 Claude Code 验证提交消息
COMMIT_MSG=$(cat "$1")
claude -p "Is this commit message good? '$COMMIT_MSG'. Reply YES or NO with reason."

.github/workflows/claude-review.yml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p "Review the changes in this PR. \
Focus on security, performance, and code quality. \
Output as markdown."
.github/workflows/claude-review.yml
name: AI Code Review
on: [pull_request]
jobs:
claude-review:
runs-on: ubuntu-latest
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 }}
run: |
git diff origin/main...HEAD | \
claude -p 'Review this PR diff for security issues, performance problems, and code quality. Format as JSON.' \
--output-format json > review.json
- name: Comment on PR
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## Claude Code Review\n\n${review.summary}`
});

当 GitHub Actions 失败时,使用 gh CLI 在终端中进行调查:

Terminal window
# 列出最近的工作流运行
gh run list --limit 10
# 查看特定运行详情
gh run view <run-id>
# 查看失败运行的日志
gh run view <run-id> --log-failed
# 下载日志进行详细分析
gh run download <run-id>

常用调试命令

命令用途
gh run list --workflow=test.yml按工作流文件过滤
gh run view --job=<job-id>查看特定 job 详情
gh run watch实时监控当前运行
gh run rerun <run-id>重试失败的运行
gh run rerun <run-id> --failed仅重试失败的 job

结合 Claude 自动分析

Terminal window
# 获取最近失败的运行
FAILED_RUN=$(gh run list --status failure --limit 1 --json databaseId --jq '.[0].databaseId')
# 查看失败详情
gh run view $FAILED_RUN --log-failed
# 让 Claude 分析
gh run view $FAILED_RUN --log-failed | claude -p "Analyze this CI failure and suggest fixes"

在创建 PR 之前,确保所有本地检查通过。这可以避免浪费 CI 周期和审查时间。

Build ✓ → Lint ✓ → Test ✓ → Type-check ✓ → 然后创建 PR

创建 .claude/commands/complete-task.md

# Complete Task
运行完整的验证门然后创建 PR:
1. **Build**: 运行 `pnpm build` - 必须成功
2. **Lint**: 运行 `pnpm lint` - 必须零错误
3. **Test**: 运行 `pnpm test` - 所有测试必须通过
4. **Type-check**: 运行 `pnpm typecheck` - 无类型错误
如果任何步骤失败:
- 立即停止
- 报告什么失败了以及原因
- 建议修复方案
- 不要继续创建 PR
如果所有步骤通过:
- 使用 `gh pr create` 创建 PR
- 使用 `gh pr checks --watch` 等待 CI
- 如果 CI 失败,获取反馈并自动修复
- 循环直到可合并或被阻塞
┌─────────────────────────────────────┐
│ 验证门 + 自动修复 │
├─────────────────────────────────────┤
│ │
│ 本地检查 (build/lint/test) │
│ │ │
│ ▼ 失败? │
│ ┌─────────┐ │
│ │ 自动修复 │ ──► 重新运行检查 │
│ └─────────┘ │
│ │ │
│ ▼ 通过 │
│ 创建 PR │
│ │ │
│ ▼ │
│ 等待 CI (gh pr checks --watch) │
│ │ │
│ ▼ 失败? │
│ ┌───────────────┐ │
│ │ 获取 CI 反馈 │ │
│ │ (CodeRabbit等) │ │
│ └───────────────┘ │
│ │ │
│ ▼ │
│ 自动修复 + 推送 + 循环 │
│ │ │
│ ▼ │
│ PR 可合并 或 被阻塞(请求人工介入) │
│ │
└─────────────────────────────────────┘

使用 GitHub GraphQL API 获取 PR 审查状态和评论:

Terminal window
# 获取 PR 审查状态和评论
gh api graphql -f query='
query($pr: Int!) {
repository(owner: "OWNER", name: "REPO") {
pullRequest(number: $pr) {
reviewDecision
reviewThreads(first: 100) {
nodes {
isResolved
comments(first: 1) {
nodes { body }
}
}
}
}
}
}' -F pr=$PR_NUMBER

使用 Claude Code 自动化发布说明和变更日志生成。

一致格式

确保每次发布的格式统一。

技术细节

从提交中捕获技术细节。

多版本输出

技术日志、GitHub Release、用户公告一次生成。

节省时间

每次发布节省 30-60 分钟。

创建 .claude/commands/release-notes.md

# Generate Release Notes
分析自上次发布以来的 git 提交并生成发布说明。
## 流程
1. **获取提交**
git log $(git describe --tags --abbrev=0)..HEAD --oneline
2. **读取完整提交详情**:包含提交消息、文件变更、PR 编号
3. **分类变更**
- Features - 新功能
- Bug Fixes - 问题修复
- Performance - 性能改进
- Security - 安全补丁
- Documentation - 文档更新
- Maintenance - 重构、依赖更新
- Breaking Changes - API 变更(突出标注)
4. **生成三个版本**
A. CHANGELOG.md 格式(技术向,面向开发者)
B. GitHub Release Notes(平衡,技术+上下文)
C. 用户公告(非技术向,聚焦收益)
5. **输出文件**
- 前置到 CHANGELOG.md
- 保存到 release-notes-[version].md
.github/workflows/release.yml
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # 完整历史用于变更日志
- name: Generate Release Notes
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# 从标签获取版本
VERSION=${GITHUB_REF#refs/tags/}
# 使用 Claude 生成
claude -p "Generate release notes for $VERSION. \
Analyze commits since last tag. \
Output in GitHub Release format. \
Save to release-notes.md"
# 创建 GitHub Release
gh release create $VERSION \
--title "Release $VERSION" \
--notes-file release-notes.md
- name: Update CHANGELOG.md
run: |
cat release-notes.md CHANGELOG.md > CHANGELOG.tmp
mv CHANGELOG.tmp CHANGELOG.md
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add CHANGELOG.md
git commit -m "docs: update changelog for $VERSION"
git push
Terminal window
# 1. 启动 Claude Code
claude
# 2. 请求生成发布说明
You: "Generate release notes for v2.0.0"
# 3. Claude 会:
# - 运行 git log 获取提交
# - 询问澄清问题:
# - "这是主要/次要/补丁版本吗?"
# - "有任何用户应该知道的破坏性变更吗?"
# 4. 审查和改进
You: "Add more detail to the authentication feature"
# 5. 最终确认
You: "Save these notes and update CHANGELOG.md"

给定以下提交:

feat: add user avatar upload (PR #123)
fix: resolve login timeout issue (PR #124)
perf: optimize database queries by 40% (PR #125)
BREAKING: change API endpoint from /api/v1 to /v2 (PR #126)

Claude 生成三种格式:

## [2.0.0] - 2025-01-10
### Added
- User avatar upload functionality (#123)
### Fixed
- Login timeout issue affecting mobile users (#124)
### Performance
- Optimized database queries, reducing load time by 40% (#125)
### Breaking Changes
- **API Endpoints**: Migrated from `/api/v1/*` to `/v2/*`
- Update client code: replace `/api/v1/` with `/v2/`
- Old endpoints will return 410 Gone after 2025-02-01
- Migration guide: docs/migration-v2.md (#126)
  • 确保提交遵循 Conventional Commits 格式
  • 所有 PR 已合并
  • 版本号已确定(语义化版本)
问题解决方案
发布说明太技术化在提示中指定受众:“Generate for non-technical users”
Claude 遗漏破坏性变更在提示中明确列出破坏性变更,或在提交消息中使用 “BREAKING:” 前缀
生成的说明太笼统提供更多上下文:“This release focuses on mobile performance”
提交消息混乱生成前清理提交历史(交互式 rebase),或使用 Git Hooks 强制提交消息格式

始终使用 -p 标志

在 CI/CD 管道中始终使用 -p 标志进行非交互式运行。

控制输入大小

限制管道输入的大小,避免超出上下文 token 限制。

结构化输出

在自动化场景中使用 --output-format json 获取可解析的结构化输出。

安全凭据

使用 GitHub Secrets 存储 API 密钥,永远不要在代码中硬编码。