🐾LuoLuo Wiki
Claude Code

Headless 与 CI/CD

在自动化流水线中使用 Claude Code

Headless 模式让 Claude Code 在没有人类交互的情况下运行,专为 CI/CD 和自动化场景设计。

基本用法

单次执行

claude -p "检查代码中的安全漏洞"

-p(或 --print)传入指令,执行完毕后输出结果并退出。

JSON 输出

claude -p "分析项目依赖的安全性" --output-format json

返回结构化 JSON,方便程序解析。

流式 JSON

claude -p "修复所有 lint 错误" --output-format stream-json

实时输出每个步骤的 JSON,适合长时间任务的进度监控。

权限控制

指定允许的工具

claude -p "跑测试看看结果" \
  --allowedTools "Read,Glob,Grep,Bash(npm test)"

只允许读取文件和运行 npm test,其他操作一律禁止。

跳过权限检查(仅限沙盒环境)

claude -p "修复并提交" --dangerously-skip-permissions

仅在隔离的 CI 容器中使用,不要在本地运行。

GitHub Actions 集成

自动代码审查

name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Claude Code
        run: npm i -g @anthropic-ai/claude-code

      - name: Review PR
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "审查这个 PR 的代码变更,关注安全性、性能和代码质量。输出 Markdown 格式的审查报告。" \
            --output-format json > review.json

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const review = require('./review.json');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: review.result
            });

自动修复 Lint

name: Auto Fix Lint
on: [push]

jobs:
  fix:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm i -g @anthropic-ai/claude-code
      - name: Fix lint errors
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "运行 lint 检查,修复所有错误,然后提交修复" \
            --allowedTools "Read,Edit,Write,Bash(npx biome*),Bash(git*)" \
            --dangerously-skip-permissions

生成 Changelog

- name: Generate Changelog
  run: |
    claude -p "基于最近 10 个 commit 生成 CHANGELOG 条目" \
      --output-format json \
      --allowedTools "Read,Bash(git log*)"

批量处理

处理多个文件

for file in src/components/*.tsx; do
  claude -p "给 $file 添加 JSDoc 注释" \
    --allowedTools "Read,Edit"
done

多项目分析

for dir in packages/*/; do
  echo "=== $dir ==="
  claude -p "分析 $dir 的代码质量,评分 1-10" \
    --output-format json
done

与其他工具组合

管道输入

git diff HEAD~5 | claude -p "总结这些代码变更"

作为预提交检查

# .husky/pre-commit
claude -p "检查暂存区的代码是否有安全问题" \
  --allowedTools "Bash(git diff --cached)" \
  --output-format json

注意事项

  • Headless 模式每次调用都是独立会话,不共享上下文
  • 控制好 --allowedTools 范围,避免意外操作
  • 在 CI 中使用 --dangerously-skip-permissions 时确保环境隔离
  • 注意 API 消耗,大规模使用时监控费用

On this page