Headless 模式
非交互式运行 Claude Code,适用于自动化脚本和 CI 环境。
Claude Code 可以深度集成到 CI/CD 工作流中,从自动代码审查到发布说明生成。通过 headless 模式和 Unix 管道,你可以在自动化管道中充分利用 AI 能力。
Headless 模式
非交互式运行 Claude Code,适用于自动化脚本和 CI 环境。
Unix 管道
将任何命令输出通过管道传递给 Claude 进行分析和转换。
GitHub Actions
在 PR 审查、测试和发布流程中自动运行 Claude Code。
发布自动化
自动生成发布说明和变更日志。
使用 -p 标志在无交互提示的情况下运行 Claude Code:
# 基本 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 集成,用于自动化代码分析和转换。
# 将内容通过管道传递给 Claudecat file.txt | claude -p 'analyze this code'
# 将命令输出传递给 Claude 分析git diff | claude -p 'explain these changes'
# 将测试输出传递给 Claudenpm test 2>&1 | claude -p 'summarize test failures and suggest fixes'# 自动审查 PR 差异git diff main...feature-branch | claude -p 'Review this diff for security issues'# 分析应用日志tail -n 100 /var/log/app.log | claude -p 'Find the root cause of errors'# 解析测试输出npm test 2>&1 | claude -p 'Create a summary of failing tests with priority order'# 生成 API 文档cat src/api/*.ts | claude -p 'Generate API documentation in Markdown'# 批量文件分析find . -name "*.js" -exec cat {} \; | claude -p 'Identify unused dependencies'--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 |
# 获取结构化 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 结合处理 JSONecho "const x = 1" | claude -p 'analyze' --output-format json | jq '.suggestions[]'提示要具体
# 好:具体的任务git diff | claude -p 'List all function signature changes'
# 不够好:模糊的请求git diff | claude -p 'analyze this'限制输入大小
# 好:限定范围git diff --name-only | head -n 10 | xargs cat | claude -p 'review'
# 风险:可能超出上下文cat entire-codebase/* | claude -p 'review'自动化场景使用 -p 标志
cat file.txt | claude -p 'fix linting errors' > output.txt结合 jq 处理 JSON 输出
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 中,实现提交前和推送前的自动检查。
#!/bin/bash# 使用 Claude Code 验证提交消息COMMIT_MSG=$(cat "$1")claude -p "Is this commit message good? '$COMMIT_MSG'. Reply YES or NO with reason."#!/bin/bash# 推送前安全检查claude -p "Scan staged files for secrets and security issues. Exit 1 if found."EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then echo "发现安全问题,推送被阻止。" exit 1finame: 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."name: AI Code Reviewon: [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 在终端中进行调查:
# 列出最近的工作流运行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 自动分析:
# 获取最近失败的运行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 审查状态和评论:
# 获取 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].mdname: 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# 1. 启动 Claude Codeclaude
# 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)## What's New in v2.0.0
This release brings performance improvements, bug fixes,and a new avatar feature.
### New Features- **Avatar Upload**: Users can now upload custom profile pictures
### Bug Fixes- Fixed login timeout issue that affected some mobile users
### Performance- Database queries are now 40% faster
### Breaking Changes- **API Endpoint Migration**: All endpoints moved from `/api/v1` to `/v2` - **Action Required**: Update your API client code - **Timeline**: Old endpoints stop working February 1, 2025 - **Migration Guide**: See docs/migration-v2.md
**Full Changelog**: v1.9.0...v2.0.0Version 2.0 is here!
We've made your experience faster and more personal:
**Customize Your Profile** - Upload your own avatar**Lightning Fast** - Pages load 40% faster**More Reliable** - Fixed the login timeout issue
**For Developers**: This is a breaking release.See our migration guide for API changes.| 问题 | 解决方案 |
|---|---|
| 发布说明太技术化 | 在提示中指定受众:“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 密钥,永远不要在代码中硬编码。