跳到正文
DEV Community· Vildanden·· 2 小時前AI 評分51

如何用一行 claude -p 在 CI 執行 Claude Code 程式碼審查

Run a Claude Code review in CI with one claude -p line

AI 導讀

Claude Code 的 `claude -p` 無頭模式可在 CI 或 git hook 中執行一次提示詞、輸出答案後結束,讓程式碼差異審查成為腳本步驟。範例將 `git diff origin/main...HEAD` 傳入審查提示詞,並以 `--allowedTools "Read,Grep"` 限制為唯讀;只有輸出 `LGTM` 才令建置通過。

正文

Vildanden

Most people only use Claude Code interactively. But the same CLI has a headless mode: claude -p "<prompt>" runs one prompt, prints the answer, and exits. That makes it a normal script step you can drop into CI or a git hook.

The one line

git diff origin/main...HEAD | claude -p "Review this diff. List real bugs only. If there are none, print exactly: LGTM" --output-format text

Piped stdin becomes context, -p runs non-interactively, and the output is plain text you can grep.

Make it fail the build

#!/usr/bin/env bash
set -euo pipefail
out=$(git diff origin/main...HEAD | claude -p \
  "Review this diff for bugs, missing error handling and leaked secrets. If nothing is wrong, reply with exactly LGTM." \
  --allowedTools "Read,Grep" --max-turns 3)
echo "$out"
[[ "$out" == "LGTM" ]] || exit 1
  • --allowedTools "Read,Grep" keeps the CI run read-only: it can look at files but not edit or run shell commands.
  • --max-turns 3 caps how long it can wander.
  • Need structured results? Use --output-format json and parse .result with jq.

GitHub Actions step

- name: Claude review
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: |
    npm i -g @anthropic-ai/claude-code
    ./scripts/claude-review.sh

Keep the key in repository secrets, never in the script.

Tips

  • Keep the prompt strict ("bugs only", "exactly LGTM") so the output is easy to check.
  • Your project CLAUDE.md and .claude/settings.json still load in headless mode, so your house rules apply in CI too.
  • Start as a non-blocking job (continue-on-error: true) for a week before you let it fail builds.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

來源:DEV Community · dev.to