跳到主要內容

Github 代碼審查

通過分析 git diff、在 PR 上留下內聯評論以及執行徹底的推送前審查來審查代碼變更。支持 gh CLI,或回退使用 git + 通過 curl 調用的 GitHub REST API。

技能元數據

來源捆綁(默認安裝)
路徑skills/github/github-code-review
版本1.1.0
作者Hermes Agent
許可證MIT
標籤GitHub, Code-Review, Pull-Requests, Git, Quality
相關技能github-auth, github-pr-workflow

參考:完整 SKILL.md

信息

以下是 Hermes 在觸發此技能時加載的完整技能定義。這是技能激活時代理看到的指令。

GitHub 代碼審查

在推送之前對本地變更進行代碼審查,或審查 GitHub 上的開放 PR。此技能的大部分功能使用原生 gitgh/curl 的區別僅在於 PR 級別的交互。

前提條件

  • 已通過 GitHub 身份驗證(參見 github-auth 技能)
  • 位於 git 倉庫中

設置(用於 PR 交互)

if command -v gh &>/dev/null && gh auth status &>/dev/null; then
AUTH="gh"
else
AUTH="git"
if [ -z "$GITHUB_TOKEN" ]; then
if [ -f ~/.hermes/.env ] && grep -q "^GITHUB_TOKEN=" ~/.hermes/.env; then
GITHUB_TOKEN=$(grep "^GITHUB_TOKEN=" ~/.hermes/.env | head -1 | cut -d= -f2 | tr -d '\n\r')
elif grep -q "github.com" ~/.git-credentials 2>/dev/null; then
GITHUB_TOKEN=$(grep "github.com" ~/.git-credentials 2>/dev/null | head -1 | sed 's|https://[^:]*:\([^@]*\)@.*|\1|')
fi
fi
fi

REMOTE_URL=$(git remote get-url origin)
OWNER_REPO=$(echo "$REMOTE_URL" | sed -E 's|.*github\.com[:/]||; s|\.git$||')
OWNER=$(echo "$OWNER_REPO" | cut -d/ -f1)
REPO=$(echo "$OWNER_REPO" | cut -d/ -f2)

1. 審查本地變更(推送前)

這是純 git 操作 — 在任何地方都有效,無需 API。

獲取 Diff

# Staged changes (what would be committed)
git diff --staged

# All changes vs main (what a PR would contain)
git diff main...HEAD

# File names only
git diff main...HEAD --name-only

# Stat summary (insertions/deletions per file)
git diff main...HEAD --stat

審查策略

  1. 首先了解整體情況:
git diff main...HEAD --stat
git log main..HEAD --oneline
  1. 逐個文件審查 — 對變更的文件使用 read_file 以獲取完整上下文,並使用 diff 查看具體變更內容:
git diff main...HEAD -- src/auth/login.py
  1. 檢查常見問題:
# Debug statements, TODOs, console.logs left behind
git diff main...HEAD | grep -n "print(\|console\.log\|TODO\|FIXME\|HACK\|XXX\|debugger"

# Large files accidentally staged
git diff main...HEAD --stat | sort -t'|' -k2 -rn | head -10

# Secrets or credential patterns
git diff main...HEAD | grep -in "password\|secret\|api_key\|token.*=\|private_key"

# Merge conflict markers
git diff main...HEAD | grep -n "<<<<<<\|>>>>>>\|======="
  1. 向用戶呈現結構化的反饋。

審查輸出格式

在審查本地變更時,請按以下結構呈現發現結果:

## Code Review Summary

### Critical
- **src/auth.py:45** — SQL injection: user input passed directly to query.
Suggestion: Use parameterized queries.

### Warnings
- **src/models/user.py:23** — Password stored in plaintext. Use bcrypt or argon2.
- **src/api/routes.py:112** — No rate limiting on login endpoint.

### Suggestions
- **src/utils/helpers.py:8** — Duplicates logic in `src/core/utils.py:34`. Consolidate.
- **tests/test_auth.py** — Missing edge case: expired token test.

### Looks Good
- Clean separation of concerns in the middleware layer
- Good test coverage for the happy path

2. 審查 GitHub 上的 Pull Request

查看 PR 詳情

使用 gh:

gh pr view 123
gh pr diff 123
gh pr diff 123 --name-only

使用 git + curl:

PR_NUMBER=123

# Get PR details
curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER \
| python3 -c "
import sys, json
pr = json.load(sys.stdin)
print(f\"Title: {pr['title']}\")
print(f\"Author: {pr['user']['login']}\")
print(f\"Branch: {pr['head']['ref']} -> {pr['base']['ref']}\")
print(f\"State: {pr['state']}\")
print(f\"Body:\n{pr['body']}\")"

# List changed files
curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER/files \
| python3 -c "
import sys, json
for f in json.load(sys.stdin):
print(f\"{f['status']:10} +{f['additions']:-4} -{f['deletions']:-4} {f['filename']}\")"

將 PR 檢出到本地以進行完整審查

這適用於原生 git — 無需 gh

# Fetch the PR branch and check it out
git fetch origin pull/123/head:pr-123
git checkout pr-123

# Now you can use read_file, search_files, run tests, etc.

# View diff against the base branch
git diff main...pr-123

使用 gh(快捷方式):

gh pr checkout 123

在 PR 上留下評論

通用 PR 評論 — 使用 gh:

gh pr comment 123 --body "Overall looks good, a few suggestions below."

通用 PR 評論 — 使用 curl:

curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/issues/$PR_NUMBER/comments \
-d '{"body": "Overall looks good, a few suggestions below."}'

留下內聯審查評論

單條內聯評論 — 使用 gh(通過 API):

HEAD_SHA=$(gh pr view 123 --json headRefOid --jq '.headRefOid')

gh api repos/$OWNER/$REPO/pulls/123/comments \
--method POST \
-f body="This could be simplified with a list comprehension." \
-f path="src/auth/login.py" \
-f commit_id="$HEAD_SHA" \
-f line=45 \
-f side="RIGHT"

單條內聯評論 — 使用 curl:

# Get the head commit SHA
HEAD_SHA=$(curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER \
| python3 -c "import sys,json; print(json.load(sys.stdin)['head']['sha'])")

curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER/comments \
-d "{
\"body\": \"This could be simplified with a list comprehension.\",
\"path\": \"src/auth/login.py\",
\"commit_id\": \"$HEAD_SHA\",
\"line\": 45,
\"side\": \"RIGHT\"
}"

提交正式審查(批准 / 請求變更)

使用 gh:

gh pr review 123 --approve --body "LGTM!"
gh pr review 123 --request-changes --body "See inline comments."
gh pr review 123 --comment --body "Some suggestions, nothing blocking."

使用 curl — 原子化提交多條評論審查:

HEAD_SHA=$(curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER \
| python3 -c "import sys,json; print(json.load(sys.stdin)['head']['sha'])")

curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER/reviews \
-d "{
\"commit_id\": \"$HEAD_SHA\",
\"event\": \"COMMENT\",
\"body\": \"Code review from Hermes Agent\",
\"comments\": [
{\"path\": \"src/auth.py\", \"line\": 45, \"body\": \"Use parameterized queries to prevent SQL injection.\"},
{\"path\": \"src/models/user.py\", \"line\": 23, \"body\": \"Hash passwords with bcrypt before storing.\"},
{\"path\": \"tests/test_auth.py\", \"line\": 1, \"body\": \"Add test for expired token edge case.\"}
]
}"

事件值:"APPROVE""REQUEST_CHANGES""COMMENT"

line 字段指的是文件版本中的行號。對於已刪除的行,請使用 "side": "LEFT"


3. 審查清單

在執行代碼審查(本地或 PR)時,系統地檢查以下內容:

正確性

  • 代碼是否實現了其聲稱的功能?
  • 是否處理了邊界情況(空輸入、null、大數據量、併發訪問)?
  • 是否優雅地處理了錯誤路徑?

安全性

  • 無硬編碼的秘密、憑證或 API 密鑰
  • 對用戶-facing 輸入進行輸入驗證
  • 無 SQL 注入、XSS 或路徑遍歷漏洞
  • 在需要的地方進行身份驗證/授權檢查

代碼質量

  • 命名清晰(變量、函數、類)
  • 無不必要的複雜性或過早抽象
  • DRY 原則 — 無應提取的重複邏輯
  • 函數職責單一(專注)

測試

  • 新的代碼路徑是否經過測試?
  • 是否覆蓋了正常路徑和錯誤情況?
  • 測試是否可讀且易於維護?

性能

  • 無 N+1 查詢或不必要的循環
  • 在有益的地方使用適當的緩存
  • 異步代碼路徑中無阻塞操作

文檔

  • 公共 API 是否有文檔
  • 非顯而易見的邏輯是否有註釋解釋“為什麼”
  • 如果行為發生變更,README 是否已更新

4. 推送前審查工作流

當用戶要求你“審查代碼”或“在推送前檢查”時:

  1. git diff main...HEAD --stat — 查看變更範圍
  2. git diff main...HEAD — 閱讀完整 diff
  3. 對於每個變更的文件,如果需要更多上下文,請使用 read_file
  4. 應用上述清單
  5. 以結構化格式呈現發現結果(關鍵問題 / 警告 / 建議 / 看起來不錯)
  6. 如果發現關鍵問題,在用戶推送之前提供修復建議

5. PR 審查工作流(端到端)

當用戶要求你“審查 PR #N”、“查看此 PR”或提供 PR URL 時,請遵循以下步驟:

步驟 1:設置環境

source "${HERMES_HOME:-$HOME/.hermes}/skills/github/github-auth/scripts/gh-env.sh"
# Or run the inline setup block from the top of this skill

步驟 2:收集 PR 上下文

獲取 PR 元數據、描述和變更文件列表,以便在深入代碼之前瞭解範圍。

使用 gh:

gh pr view 123
gh pr diff 123 --name-only
gh pr checks 123

使用 curl:

PR_NUMBER=123

# PR details (title, author, description, branch)
curl -s -H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GH_OWNER/$GH_REPO/pulls/$PR_NUMBER

# Changed files with line counts
curl -s -H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GH_OWNER/$GH_REPO/pulls/$PR_NUMBER/files

步驟 3:將 PR 檢出到本地

這使你可以完全訪問 read_filesearch_files 並能夠運行測試。

git fetch origin pull/$PR_NUMBER/head:pr-$PR_NUMBER
git checkout pr-$PR_NUMBER

步驟 4:閱讀差異並理解變更

# Full diff against the base branch
git diff main...HEAD

# Or file-by-file for large PRs
git diff main...HEAD --name-only
# Then for each file:
git diff main...HEAD -- path/to/file.py

對於每個已更改的文件,使用 read_file 查看變更周圍的完整上下文——僅憑差異可能會遺漏只有在周圍代碼中才能可見的問題。

步驟 5:在本地運行自動化檢查(如適用)

# Run tests if there's a test suite
python -m pytest 2>&1 | tail -20
# or: npm test, cargo test, go test ./..., etc.

# Run linter if configured
ruff check . 2>&1 | head -30
# or: eslint, clippy, etc.

步驟 6:應用審查清單(第 3 節)

逐一檢查每個類別:正確性、安全性、代碼質量、測試、性能、文檔。

步驟 7:將審查發佈到 GitHub

收集你的發現,並將其作為帶有行內評論的正式審查提交。

使用 gh:

# If no issues — approve
gh pr review $PR_NUMBER --approve --body "Reviewed by Hermes Agent. Code looks clean — good test coverage, no security concerns."

# If issues found — request changes with inline comments
gh pr review $PR_NUMBER --request-changes --body "Found a few issues — see inline comments."

使用 curl — 原子化審查,包含多個行內評論:

HEAD_SHA=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GH_OWNER/$GH_REPO/pulls/$PR_NUMBER \
| python3 -c "import sys,json; print(json.load(sys.stdin)['head']['sha'])")

# Build the review JSON — event is APPROVE, REQUEST_CHANGES, or COMMENT
curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$GH_OWNER/$GH_REPO/pulls/$PR_NUMBER/reviews \
-d "{
\"commit_id\": \"$HEAD_SHA\",
\"event\": \"REQUEST_CHANGES\",
\"body\": \"## Hermes Agent Review\n\nFound 2 issues, 1 suggestion. See inline comments.\",
\"comments\": [
{\"path\": \"src/auth.py\", \"line\": 45, \"body\": \"🔴 **Critical:** User input passed directly to SQL query — use parameterized queries.\"},
{\"path\": \"src/models.py\", \"line\": 23, \"body\": \"⚠️ **Warning:** Password stored without hashing.\"},
{\"path\": \"src/utils.py\", \"line\": 8, \"body\": \"💡 **Suggestion:** This duplicates logic in core/utils.py:34.\"}
]
}"

步驟 8:同時發佈總結評論

除了行內評論外,還要留下一個頂層總結,以便 PR 作者一目瞭然地瞭解全貌。使用 references/review-output-template.md 中的審查輸出格式。

使用 gh:

gh pr comment $PR_NUMBER --body "$(cat <<'EOF'
## Code Review Summary

**Verdict: Changes Requested** (2 issues, 1 suggestion)

### 🔴 Critical
- **src/auth.py:45** — SQL injection vulnerability

### ⚠️ Warnings
- **src/models.py:23** — Plaintext password storage

### 💡 Suggestions
- **src/utils.py:8** — Duplicated logic, consider consolidating

### ✅ Looks Good
- Clean API design
- Good error handling in the middleware layer

---
*Reviewed by Hermes Agent*
EOF
)"

步驟 9:清理

git checkout main
git branch -D pr-$PR_NUMBER

決策:批准 vs 請求變更 vs 評論

  • 批准 — 沒有關鍵或警告級別的問題,只有輕微建議或完全通過
  • 請求變更 — 存在任何需要在合併前修復的關鍵或警告級別問題
  • 評論 — 觀察和建議,但沒有阻礙性問題(當你不確定或 PR 處於草稿狀態時使用)