跳到主要內容

GitHub PR 工作流

完整的拉取請求(Pull Request)生命週期——創建分支、提交更改、打開 PR、監控 CI 狀態、自動修復失敗以及合併。適用於 gh CLI,或在沒有 gh 時回退到通過 curl 使用 git + GitHub REST API。

技能元數據

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

參考:完整 SKILL.md

信息

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

GitHub Pull Request 工作流

管理 PR 生命週期的完整指南。每個部分首先展示 gh 的方式,然後展示在沒有 gh 的機器上使用 git + curl 的回退方案。

前提條件

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

快速身份驗證檢測

# Determine which method to use throughout this workflow
if command -v gh &>/dev/null && gh auth status &>/dev/null; then
AUTH="gh"
else
AUTH="git"
# Ensure we have a token for API calls
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
echo "Using: $AUTH"

從 Git 遠程倉庫提取 Owner/Repo

許多 curl 命令需要 owner/repo。從 git 遠程倉庫中提取它:

# Works for both HTTPS and SSH remote URLs
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)
echo "Owner: $OWNER, Repo: $REPO"

1. 分支創建

這部分純使用 git —— 兩種方式相同:

# Make sure you're up to date
git fetch origin
git checkout main && git pull origin main

# Create and switch to a new branch
git checkout -b feat/add-user-authentication

分支命名規範:

  • feat/description — 新功能
  • fix/description — 錯誤修復
  • refactor/description — 代碼重構
  • docs/description — 文檔
  • ci/description — CI/CD 更改

2. 進行提交

使用代理的文件工具(write_file, patch)進行更改,然後提交:

# Stage specific files
git add src/auth.py src/models/user.py tests/test_auth.py

# Commit with a conventional commit message
git commit -m "feat: add JWT-based user authentication

- Add login/register endpoints
- Add User model with password hashing
- Add auth middleware for protected routes
- Add unit tests for auth flow"

提交消息格式(約定式提交 Conventional Commits):

type(scope): short description

Longer explanation if needed. Wrap at 72 characters.

類型:feat, fix, refactor, docs, test, ci, chore, perf

3. 推送並創建 PR

推送分支(兩種方式相同)

git push -u origin HEAD

創建 PR

使用 gh:

gh pr create \
--title "feat: add JWT-based user authentication" \
--body "## Summary
- Adds login and register API endpoints
- JWT token generation and validation

## Test Plan
- [ ] Unit tests pass

Closes #42"

選項:--draft, --reviewer user1,user2, --label "enhancement", --base develop

使用 git + curl:

BRANCH=$(git branch --show-current)

curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/$OWNER/$REPO/pulls \
-d "{
\"title\": \"feat: add JWT-based user authentication\",
\"body\": \"## Summary\nAdds login and register API endpoints.\n\nCloses #42\",
\"head\": \"$BRANCH\",
\"base\": \"main\"
}"

響應 JSON 包含 PR number —— 保存它以供後續命令使用。

若要創建為草稿,請在 JSON 正文中添加 "draft": true

4. 監控 CI 狀態

檢查 CI 狀態

使用 gh:

# One-shot check
gh pr checks

# Watch until all checks finish (polls every 10s)
gh pr checks --watch

使用 git + curl:

# Get the latest commit SHA on the current branch
SHA=$(git rev-parse HEAD)

# Query the combined status
curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/status \
| python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"Overall: {data['state']}\")
for s in data.get('statuses', []):
print(f\" {s['context']}: {s['state']} - {s.get('description', '')}\")"

# Also check GitHub Actions check runs (separate endpoint)
curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/check-runs \
| python3 -c "
import sys, json
data = json.load(sys.stdin)
for cr in data.get('check_runs', []):
print(f\" {cr['name']}: {cr['status']} / {cr['conclusion'] or 'pending'}\")"

輪詢直到完成(git + curl)

# Simple polling loop — check every 30 seconds, up to 10 minutes
SHA=$(git rev-parse HEAD)
for i in $(seq 1 20); do
STATUS=$(curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/commits/$SHA/status \
| python3 -c "import sys,json; print(json.load(sys.stdin)['state'])")
echo "Check $i: $STATUS"
if [ "$STATUS" = "success" ] || [ "$STATUS" = "failure" ] || [ "$STATUS" = "error" ]; then
break
fi
sleep 30
done

5. 自動修復 CI 失敗

當 CI 失敗時,診斷並修復。此循環適用於任何一種身份驗證方法。

步驟 1:獲取失敗詳情

使用 gh:

# List recent workflow runs on this branch
gh run list --branch $(git branch --show-current) --limit 5

# View failed logs
gh run view <RUN_ID> --log-failed

使用 git + curl:

BRANCH=$(git branch --show-current)

# List workflow runs on this branch
curl -s \
-H "Authorization: token $GITHUB_TOKEN" \
"https://api.github.com/repos/$OWNER/$REPO/actions/runs?branch=$BRANCH&per_page=5" \
| python3 -c "
import sys, json
runs = json.load(sys.stdin)['workflow_runs']
for r in runs:
print(f\"Run {r['id']}: {r['name']} - {r['conclusion'] or r['status']}\")"

# Get failed job logs (download as zip, extract, read)
RUN_ID=<run_id>
curl -s -L \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/logs \
-o /tmp/ci-logs.zip
cd /tmp && unzip -o ci-logs.zip -d ci-logs && cat ci-logs/*.txt

步驟 2:修復並推送

識別問題後,使用文件工具(patch, write_file)進行修復:

git add <fixed_files>
git commit -m "fix: resolve CI failure in <check_name>"
git push

步驟 3:驗證

使用上述第 4 節中的命令重新檢查 CI 狀態。

自動修復循環模式

當被要求自動修復 CI 時,遵循此循環:

  1. 檢查 CI 狀態 → 識別失敗
  2. 讀取失敗日誌 → 理解錯誤
  3. 使用 read_file + patch/write_file → 修復代碼
  4. git add . && git commit -m "fix: ..." && git push
  5. 等待 CI → 重新檢查狀態
  6. 如果仍然失敗則重複(最多 3 次嘗試,然後詢問用戶)

6. 合併

使用 gh:

# Squash merge + delete branch (cleanest for feature branches)
gh pr merge --squash --delete-branch

# Enable auto-merge (merges when all checks pass)
gh pr merge --auto --squash --delete-branch

使用 git + curl:

PR_NUMBER=<number>

# Merge the PR via API (squash)
curl -s -X PUT \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/repos/$OWNER/$REPO/pulls/$PR_NUMBER/merge \
-d "{
\"merge_method\": \"squash\",
\"commit_title\": \"feat: add user authentication (#$PR_NUMBER)\"
}"

# Delete the remote branch after merge
BRANCH=$(git branch --show-current)
git push origin --delete $BRANCH

# Switch back to main locally
git checkout main && git pull origin main
git branch -d $BRANCH

合併方法:"merge"(合併提交), "squash", "rebase"

啟用自動合併(curl)

# Auto-merge requires the repo to have it enabled in settings.
# This uses the GraphQL API since REST doesn't support auto-merge.
PR_NODE_ID=$(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)['node_id'])")

curl -s -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
https://api.github.com/graphql \
-d "{\"query\": \"mutation { enablePullRequestAutoMerge(input: {pullRequestId: \\\"$PR_NODE_ID\\\", mergeMethod: SQUASH}) { clientMutationId } }\"}"

7. 完整工作流示例

# 1. Start from clean main
git checkout main && git pull origin main

# 2. Branch
git checkout -b fix/login-redirect-bug

# 3. (Agent makes code changes with file tools)

# 4. Commit
git add src/auth/login.py tests/test_login.py
git commit -m "fix: correct redirect URL after login

Preserves the ?next= parameter instead of always redirecting to /dashboard."

# 5. Push
git push -u origin HEAD

# 6. Create PR (picks gh or curl based on what's available)
# ... (see Section 3)

# 7. Monitor CI (see Section 4)

# 8. Merge when green (see Section 6)

實用 PR 命令參考

操作ghgit + curl
列出我的 PRgh pr list --author @mecurl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/repos/$OWNER/$REPO/pulls?state=open"
查看 PR 差異gh pr diffgit diff main...HEAD(本地)或 curl -H "Accept: application/vnd.github.diff" ...
添加評論gh pr comment N --body "..."curl -X POST .../issues/N/comments -d '{"body":"..."}'
請求審查gh pr edit N --add-reviewer usercurl -X POST .../pulls/N/requested_reviewers -d '{"reviewers":["user"]}'
關閉 PRgh pr close Ncurl -X PATCH .../pulls/N -d '{"state":"closed"}'
檢出他人的 PRgh pr checkout Ngit fetch origin pull/N/head:pr-N && git checkout pr-N