github
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGitHub
GitHub
All GitHub operations use the CLI. Prefer with for structured,
parseable output. Use when not inside a git repository with a
configured remote. Use to open any resource in the browser.
gh--json--jq--repo owner/repo--web| Reference File | Purpose |
|---|---|
| GraphQL query patterns, cost model, mutations, rate limit inspection |
| Multi-step workflow recipes for CI triage, PR lifecycle, releases, batch ops |
所有GitHub操作都使用 CLI。推荐搭配和生成结构化、可解析的输出。如果当前不在已配置远程仓库的git目录下,请使用参数。使用参数可以在浏览器中打开对应资源。
gh--json--jq--repo owner/repo--web| 参考文件 | 用途 |
|---|---|
| GraphQL查询模式、成本模型、变更操作、速率限制检查 |
| CI排查、PR生命周期、版本发布、批量操作的多步骤工作流模板 |
Prerequisites and Auth
前置要求与身份认证
Installation
安装
| Platform | Command |
|---|---|
| macOS | |
| Debian/Ubuntu | |
| Windows | |
| 平台 | 命令 |
|---|---|
| macOS | |
| Debian/Ubuntu | |
| Windows | |
Authentication
身份认证
Log in interactively (opens browser for OAuth):
bash
gh auth loginCheck current auth status and active account:
bash
gh auth status交互式登录(会打开浏览器进行OAuth验证):
bash
gh auth login检查当前认证状态和活跃账号:
bash
gh auth statusRequired OAuth Scopes
所需OAuth权限范围
| Scope | Grants Access To |
|---|---|
| Private repos, issues, PRs, commits, status |
| Org membership, team listing |
| Trigger and manage GitHub Actions workflows |
| Create and manage gists |
| Delete repositories (not granted by default) |
| Manage org settings, teams, members |
| Read/write access to ProjectV2 boards |
Add missing scopes without re-authenticating from scratch:
bash
gh auth refresh --scopes repo,read:org,workflow| 权限范围 | 授权访问内容 |
|---|---|
| 私有仓库、issues、PR、提交、状态 |
| 组织成员身份、团队列表 |
| 触发和管理GitHub Actions工作流 |
| 创建和管理gists |
| 删除仓库(默认不授予该权限) |
| 管理组织设置、团队、成员 |
| ProjectV2看板的读写权限 |
无需完全重新认证即可补充缺失的权限:
bash
gh auth refresh --scopes repo,read:org,workflowIssues
Issues
Create
创建
bash
gh issue create --repo owner/repo --title "Login timeout on slow connections" --body "Users on 3G see a 504 after 8 seconds"Create with labels, assignees, and milestone:
bash
gh issue create --repo owner/repo \
--title "Add rate limiting to /api/upload" \
--body "Current endpoint has no throttle. Target: 100 req/min per user." \
--label "enhancement,backend" \
--assignee "username1,username2" \
--milestone "v2.1"| Flag | Purpose |
|---|---|
| Issue title (required unless |
| Issue body in markdown |
| Comma-separated label names |
| Comma-separated GitHub usernames |
| Milestone name |
| Project board name |
| Open the new issue in browser after creation |
bash
gh issue create --repo owner/repo --title "Login timeout on slow connections" --body "Users on 3G see a 504 after 8 seconds"创建时指定标签、处理人与里程碑:
bash
gh issue create --repo owner/repo \
--title "Add rate limiting to /api/upload" \
--body "Current endpoint has no throttle. Target: 100 req/min per user." \
--label "enhancement,backend" \
--assignee "username1,username2" \
--milestone "v2.1"| 参数 | 用途 |
|---|---|
| Issue标题(使用 |
| Markdown格式的Issue内容 |
| 逗号分隔的标签名称 |
| 逗号分隔的GitHub用户名 |
| 里程碑名称 |
| 项目看板名称 |
| 创建完成后在浏览器中打开新Issue |
List and Filter
列表与筛选
bash
gh issue list --repo owner/repo --state open --label "bug" --assignee "@me" --limit 20Structured output with JSON:
bash
gh issue list --repo owner/repo --json number,title,labels,assignees \
--jq '.[] | "\(.number) [\(.labels | map(.name) | join(","))] \(.title)"'bash
gh issue list --repo owner/repo --state open --label "bug" --assignee "@me" --limit 20结构化JSON输出:
bash
gh issue list --repo owner/repo --json number,title,labels,assignees \
--jq '.[] | "\(.number) [\(.labels | map(.name) | join(","))] \(.title)"'View, Edit, Close
查看、编辑、关闭
View issue details:
bash
gh issue view 42 --repo owner/repoView with comments:
bash
gh issue view 42 --repo owner/repo --commentsEdit an existing issue:
bash
gh issue edit 42 --repo owner/repo --add-label "priority:high" --add-assignee "username"Close an issue with a comment:
bash
gh issue close 42 --repo owner/repo --comment "Fixed in PR #87"查看Issue详情:
bash
gh issue view 42 --repo owner/repo查看包含评论的详情:
bash
gh issue view 42 --repo owner/repo --comments编辑现有Issue:
bash
gh issue edit 42 --repo owner/repo --add-label "priority:high" --add-assignee "username"带评论关闭Issue:
bash
gh issue close 42 --repo owner/repo --comment "Fixed in PR #87"Comments
评论
Add a comment to an issue:
bash
gh issue comment 42 --repo owner/repo --body "Reproduced on v2.0.3. Stack trace attached."为Issue添加评论:
bash
gh issue comment 42 --repo owner/repo --body "Reproduced on v2.0.3. Stack trace attached."Pull Requests
Pull Requests
Create
创建
Standard PR from current branch:
bash
gh pr create --repo owner/repo --title "Add rate limiter middleware" --body "Implements token bucket at 100 req/min"Draft PR with reviewers:
bash
gh pr create --repo owner/repo \
--title "Refactor auth module" \
--body "Splits monolithic auth into JWT and session submodules" \
--draft \
--reviewer "reviewer1,reviewer2" \
--label "refactor"Auto-fill title and body from commit messages:
bash
gh pr create --repo owner/repo --fillCreate PR targeting a specific base branch:
bash
gh pr create --repo owner/repo --base develop --head feature/rate-limiter --fill基于当前分支创建标准PR:
bash
gh pr create --repo owner/repo --title "Add rate limiter middleware" --body "Implements token bucket at 100 req/min"带评审人的草稿PR:
bash
gh pr create --repo owner/repo \
--title "Refactor auth module" \
--body "Splits monolithic auth into JWT and session submodules" \
--draft \
--reviewer "reviewer1,reviewer2" \
--label "refactor"从提交信息自动填充标题和内容:
bash
gh pr create --repo owner/repo --fill创建指向指定目标分支的PR:
bash
gh pr create --repo owner/repo --base develop --head feature/rate-limiter --fillList and Filter
列表与筛选
bash
gh pr list --repo owner/repo --state open --author "@me" --label "needs-review"JSON output with review status:
bash
gh pr list --repo owner/repo --json number,title,reviewDecision,statusCheckRollup \
--jq '.[] | "\(.number) \(.reviewDecision // "PENDING") \(.title)"'bash
gh pr list --repo owner/repo --state open --author "@me" --label "needs-review"带评审状态的JSON输出:
bash
gh pr list --repo owner/repo --json number,title,reviewDecision,statusCheckRollup \
--jq '.[] | "\(.number) \(.reviewDecision // "PENDING") \(.title)"'View and Review
查看与评审
View PR details including diff stats:
bash
gh pr view 55 --repo owner/repoView the diff:
bash
gh pr diff 55 --repo owner/repoApprove a PR:
bash
gh pr review 55 --repo owner/repo --approve --body "LGTM — tests pass, no security concerns"Request changes:
bash
gh pr review 55 --repo owner/repo --request-changes --body "Missing input validation on the upload handler"Add a review comment without approving or requesting changes:
bash
gh pr review 55 --repo owner/repo --comment --body "Consider caching the config lookup"查看PR详情(包含diff统计):
bash
gh pr view 55 --repo owner/repo查看diff:
bash
gh pr diff 55 --repo owner/repoapprove PR:
bash
gh pr review 55 --repo owner/repo --approve --body "LGTM — tests pass, no security concerns"请求修改:
bash
gh pr review 55 --repo owner/repo --request-changes --body "Missing input validation on the upload handler"添加评审评论(不approve也不请求修改):
bash
gh pr review 55 --repo owner/repo --comment --body "Consider caching the config lookup"Merge
合并
Merge with default strategy:
bash
gh pr merge 55 --repo owner/repoSquash merge and delete branch:
bash
gh pr merge 55 --repo owner/repo --squash --delete-branchRebase merge:
bash
gh pr merge 55 --repo owner/repo --rebaseAuto-merge when CI passes:
bash
gh pr merge 55 --repo owner/repo --auto --squash使用默认策略合并:
bash
gh pr merge 55 --repo owner/reposquash合并并删除分支:
bash
gh pr merge 55 --repo owner/repo --squash --delete-branchrebase合并:
bash
gh pr merge 55 --repo owner/repo --rebaseCI通过后自动合并:
bash
gh pr merge 55 --repo owner/repo --auto --squashCI Status
CI状态
Check CI status on a PR:
bash
gh pr checks 55 --repo owner/repoWatch CI and block until all checks complete:
bash
gh pr checks 55 --repo owner/repo --watch检查PR的CI状态:
bash
gh pr checks 55 --repo owner/repo监听CI状态直到所有检查完成:
bash
gh pr checks 55 --repo owner/repo --watchEdit, Ready, Close
编辑、标记就绪、关闭
Mark a draft PR as ready for review:
bash
gh pr ready 55 --repo owner/repoEdit PR metadata:
bash
gh pr edit 55 --repo owner/repo --add-reviewer "reviewer3" --add-label "urgent"Close a PR without merging:
bash
gh pr close 55 --repo owner/repo --comment "Superseded by #60"将草稿PR标记为就绪待评审:
bash
gh pr ready 55 --repo owner/repo编辑PR元数据:
bash
gh pr edit 55 --repo owner/repo --add-reviewer "reviewer3" --add-label "urgent"不合并直接关闭PR:
bash
gh pr close 55 --repo owner/repo --comment "Superseded by #60"CI / Actions
CI / Actions
List Workflow Runs
列出工作流运行记录
bash
gh run list --repo owner/repo --limit 10Filter by workflow name and branch:
bash
gh run list --repo owner/repo --workflow "CI" --branch main --status failure --limit 5JSON output:
bash
gh run list --repo owner/repo --json databaseId,status,conclusion,headBranch,name \
--jq '.[] | "\(.databaseId) \(.status) \(.conclusion // "running") \(.headBranch)"'bash
gh run list --repo owner/repo --limit 10按工作流名称和分支筛选:
bash
gh run list --repo owner/repo --workflow "CI" --branch main --status failure --limit 5JSON输出:
bash
gh run list --repo owner/repo --json databaseId,status,conclusion,headBranch,name \
--jq '.[] | "\(.databaseId) \(.status) \(.conclusion // "running") \(.headBranch)"'View Run Details
查看运行详情
bash
gh run view 123456789 --repo owner/repoView logs for failed steps only:
bash
gh run view 123456789 --repo owner/repo --log-failedView full logs:
bash
gh run view 123456789 --repo owner/repo --logbash
gh run view 123456789 --repo owner/repo仅查看失败步骤的日志:
bash
gh run view 123456789 --repo owner/repo --log-failed查看完整日志:
bash
gh run view 123456789 --repo owner/repo --logTrigger and Rerun
触发与重跑
Trigger a workflow manually:
bash
gh workflow run deploy.yml --repo owner/repo --ref main -f environment=stagingRerun only the failed jobs in a run:
bash
gh run rerun 123456789 --repo owner/repo --failedRerun the entire run:
bash
gh run rerun 123456789 --repo owner/repo手动触发工作流:
bash
gh workflow run deploy.yml --repo owner/repo --ref main -f environment=staging仅重跑运行中失败的任务:
bash
gh run rerun 123456789 --repo owner/repo --failed重跑整个工作流:
bash
gh run rerun 123456789 --repo owner/repoWatch a Run
监听运行状态
Stream live status updates until the run completes:
bash
gh run watch 123456789 --repo owner/repo流式输出实时状态更新直到运行完成:
bash
gh run watch 123456789 --repo owner/repoEnable and Disable Workflows
启用与禁用工作流
bash
gh workflow disable "Nightly Build" --repo owner/repo
gh workflow enable "Nightly Build" --repo owner/repobash
gh workflow disable "Nightly Build" --repo owner/repo
gh workflow enable "Nightly Build" --repo owner/repoDownload Artifacts
下载制品
bash
gh run download 123456789 --repo owner/repo --name "build-output"Download all artifacts from a run:
bash
gh run download 123456789 --repo owner/repobash
gh run download 123456789 --repo owner/repo --name "build-output"下载运行生成的所有制品:
bash
gh run download 123456789 --repo owner/repoRepositories
仓库
Create
创建
Create a new public repository:
bash
gh repo create owner/new-repo --public --description "Service for handling webhooks"Create from a template:
bash
gh repo create owner/new-service --template owner/service-template --public --clone创建新的公开仓库:
bash
gh repo create owner/new-repo --public --description "Service for handling webhooks"从模板创建:
bash
gh repo create owner/new-service --template owner/service-template --public --cloneFork and Clone
Fork与克隆
bash
gh repo fork owner/repo --clone
gh repo clone owner/repobash
gh repo fork owner/repo --clone
gh repo clone owner/repoView and List
查看与列表
bash
gh repo view owner/repo
gh repo view owner/repo --json name,description,defaultBranchRef --jq '.defaultBranchRef.name'List repos in an org:
bash
gh repo list some-org --limit 50 --json name,isArchived \
--jq '.[] | select(.isArchived == false) | .name'bash
gh repo view owner/repo
gh repo view owner/repo --json name,description,defaultBranchRef --jq '.defaultBranchRef.name'列出组织下的仓库:
bash
gh repo list some-org --limit 50 --json name,isArchived \
--jq '.[] | select(.isArchived == false) | .name'Edit Settings
编辑设置
bash
gh repo edit owner/repo --description "Updated description" --enable-issues --enable-wiki=falsebash
gh repo edit owner/repo --description "Updated description" --enable-issues --enable-wiki=falseArchive and Delete
归档与删除
bash
gh repo archive owner/repo --yes
gh repo delete owner/repo --yesbash
gh repo archive owner/repo --yes
gh repo delete owner/repo --yesReleases
版本发布
Create
创建
Create a release with auto-generated notes:
bash
gh release create v1.2.0 --repo owner/repo --generate-notesCreate with title, notes, and binary assets:
bash
gh release create v1.2.0 --repo owner/repo \
--title "v1.2.0 — Rate Limiter" \
--notes "Adds token bucket rate limiting to all API endpoints" \
./dist/app-linux-amd64 ./dist/app-darwin-arm64Create a prerelease:
bash
gh release create v2.0.0-rc1 --repo owner/repo --prerelease --generate-notes创建带自动生成说明的版本:
bash
gh release create v1.2.0 --repo owner/repo --generate-notes创建时指定标题、说明和二进制资源:
bash
gh release create v1.2.0 --repo owner/repo \
--title "v1.2.0 — Rate Limiter" \
--notes "Adds token bucket rate limiting to all API endpoints" \
./dist/app-linux-amd64 ./dist/app-darwin-arm64创建预发布版本:
bash
gh release create v2.0.0-rc1 --repo owner/repo --prerelease --generate-notesList and View
列表与查看
bash
gh release list --repo owner/repo --limit 5
gh release view v1.2.0 --repo owner/repobash
gh release list --repo owner/repo --limit 5
gh release view v1.2.0 --repo owner/repoEdit and Upload Assets
编辑与上传资源
bash
gh release edit v1.2.0 --repo owner/repo --draft=false --prerelease=falseUpload additional assets to an existing release:
bash
gh release upload v1.2.0 --repo owner/repo ./dist/app-windows-amd64.exebash
gh release edit v1.2.0 --repo owner/repo --draft=false --prerelease=false为已存在的版本上传额外资源:
bash
gh release upload v1.2.0 --repo owner/repo ./dist/app-windows-amd64.exeDelete
删除
bash
gh release delete v1.0.0-beta --repo owner/repo --yesbash
gh release delete v1.0.0-beta --repo owner/repo --yesSearch
搜索
Repositories
仓库
bash
gh search repos "rate limiter language:go" --limit 10 --json fullName,description,stargazersCount \
--jq '.[] | "\(.stargazersCount) \(.fullName): \(.description)"'bash
gh search repos "rate limiter language:go" --limit 10 --json fullName,description,stargazersCount \
--jq '.[] | "\(.stargazersCount) \(.fullName): \(.description)"'Issues
Issues
bash
gh search issues "memory leak is:open repo:owner/repo" --json number,title,url \
--jq '.[] | "#\(.number) \(.title)"'bash
gh search issues "memory leak is:open repo:owner/repo" --json number,title,url \
--jq '.[] | "#\(.number) \(.title)"'Pull Requests
Pull Requests
bash
gh search prs "review:approved is:merged repo:owner/repo" --json number,title,mergedAt \
--jq '.[] | "\(.number) \(.mergedAt) \(.title)"'bash
gh search prs "review:approved is:merged repo:owner/repo" --json number,title,mergedAt \
--jq '.[] | "\(.number) \(.mergedAt) \(.title)"'Code
代码
bash
gh search code "func RateLimit repo:owner/repo" --json path,repository \
--jq '.[] | "\(.repository.fullName) \(.path)"'bash
gh search code "func RateLimit repo:owner/repo" --json path,repository \
--jq '.[] | "\(.repository.fullName) \(.path)"'Commits
提交
bash
gh search commits "fix timeout repo:owner/repo" --json sha,commit \
--jq '.[] | "\(.sha[:8]) \(.commit.message | split("\n") | .[0])"'bash
gh search commits "fix timeout repo:owner/repo" --json sha,commit \
--jq '.[] | "\(.sha[:8]) \(.commit.message | split("\n") | .[0])"'API: REST and GraphQL
API: REST和GraphQL
REST: GET
REST: GET
bash
gh api repos/owner/repo/pulls/55 --jq '{title: .title, state: .state, author: .user.login}'bash
gh api repos/owner/repo/pulls/55 --jq '{title: .title, state: .state, author: .user.login}'REST: POST
REST: POST
bash
gh api repos/owner/repo/issues/42/comments -f body="Automated comment from CI triage"bash
gh api repos/owner/repo/issues/42/comments -f body="Automated comment from CI triage"REST: PATCH
REST: PATCH
bash
gh api repos/owner/repo/issues/42 -X PATCH -f state="closed"bash
gh api repos/owner/repo/issues/42 -X PATCH -f state="closed"Pagination
分页
Paginate through all results automatically:
bash
gh api repos/owner/repo/issues --paginate --jq '.[].number'自动分页获取所有结果:
bash
gh api repos/owner/repo/issues --paginate --jq '.[].number'Rate Limit Check
速率限制检查
bash
gh api rate_limit --jq '{core: .resources.core, graphql: .resources.graphql}'bash
gh api rate_limit --jq '{core: .resources.core, graphql: .resources.graphql}'GraphQL Queries
GraphQL查询
Inline GraphQL query:
bash
gh api graphql -f query='
query {
repository(owner: "owner", name: "repo") {
issues(first: 5, states: OPEN) {
nodes {
number
title
}
}
}
}
' --jq '.data.repository.issues.nodes[] | "\(.number) \(.title)"'See for cost model, bulk queries, mutations, and rate
limit management patterns.
references/graphql-queries.md内联GraphQL查询:
bash
gh api graphql -f query='
query {
repository(owner: "owner", name: "repo") {
issues(first: 5, states: OPEN) {
nodes {
number
title
}
}
}
}
' --jq '.data.repository.issues.nodes[] | "\(.number) \(.title)"'查看了解成本模型、批量查询、变更操作和速率限制管理模式。
references/graphql-queries.mdREST vs GraphQL Decision Table
REST与GraphQL选择对照表
| Scenario | Use | Reason |
|---|---|---|
| Fetch a single resource (one PR, one issue) | REST ( | Simple, predictable, low overhead |
| Fetch nested or related data in one round-trip | GraphQL | Avoids N+1 requests; select only needed fields |
| Bulk operations across many resources | GraphQL | Query complexity points are cheaper than REST calls |
| Creating or updating a resource (mutation) | Either | REST: |
| Rate-limit-sensitive pipeline or script | REST | REST has a simple 5000 req/hr counter; easier to budget |
| ProjectV2 board operations | GraphQL | ProjectV2 has no REST API; GraphQL only |
| 场景 | 选择 | 原因 |
|---|---|---|
| 获取单个资源(一个PR、一个issue) | REST ( | 简单、可预测、低开销 |
| 单次请求获取嵌套或关联数据 | GraphQL | 避免N+1请求;仅选择需要的字段 |
| 跨多个资源的批量操作 | GraphQL | 查询复杂度点数成本低于REST调用 |
| 创建或更新资源(变更操作) | 二者均可 | REST: |
| 对速率限制敏感的流水线或脚本 | REST | REST有简单的5000次/小时计数;更容易做预算 |
| ProjectV2看板操作 | GraphQL | ProjectV2无REST API;仅支持GraphQL |
Inline Workflow Examples
内联工作流示例
PR Lifecycle
PR生命周期
bash
undefinedbash
undefined1. Create a draft PR from the current branch
1. 基于当前分支创建草稿PR
gh pr create --repo owner/repo --title "Add rate limiter" --body "Token bucket at 100 req/min" --draft
gh pr create --repo owner/repo --title "Add rate limiter" --body "Token bucket at 100 req/min" --draft
2. Check CI status on the PR
2. 检查PR的CI状态
gh pr checks 55 --repo owner/repo --watch
gh pr checks 55 --repo owner/repo --watch
3. Mark ready once CI passes
3. CI通过后标记为就绪
gh pr ready 55 --repo owner/repo
gh pr ready 55 --repo owner/repo
4. Approve the PR
4. 评审通过PR
gh pr review 55 --repo owner/repo --approve --body "LGTM"
gh pr review 55 --repo owner/repo --approve --body "LGTM"
5. Squash-merge and delete branch
5. Squash合并并删除分支
gh pr merge 55 --repo owner/repo --squash --delete-branch
See `references/automation-workflows.md` for the full lifecycle with label management and reviewer rotation.gh pr merge 55 --repo owner/repo --squash --delete-branch
查看`references/automation-workflows.md`了解包含标签管理和评审人轮换的完整生命周期流程。CI Triage
CI排查
bash
undefinedbash
undefined1. Find the latest failed run on main
1. 查找main分支上最新的失败运行
gh run list --repo owner/repo --branch main --status failure --limit 1 --json databaseId --jq '.[0].databaseId'
gh run list --repo owner/repo --branch main --status failure --limit 1 --json databaseId --jq '.[0].databaseId'
2. View failed step logs (substitute run ID from step 1)
2. 查看失败步骤的日志(替换为步骤1获取的运行ID)
gh run view 123456789 --repo owner/repo --log-failed
gh run view 123456789 --repo owner/repo --log-failed
3. Rerun only failed jobs
3. 仅重跑失败的任务
gh run rerun 123456789 --repo owner/repo --failed
gh run rerun 123456789 --repo owner/repo --failed
4. Watch until complete
4. 监听直到运行完成
gh run watch 123456789 --repo owner/repo
See `references/automation-workflows.md` for batch triage across multiple branches and failure pattern analysis.
---gh run watch 123456789 --repo owner/repo
查看`references/automation-workflows.md`了解跨多分支的批量排查和失败模式分析。
---Error Handling
错误处理
| Error | Cause | Resolution |
|---|---|---|
| HTTP 401 Unauthorized | Token expired or revoked | Run |
| HTTP 403 Forbidden | Insufficient permissions or rate limited | Check |
| HTTP 404 Not Found | Repo does not exist, is private without | Verify repo name; run |
| HTTP 422 Unprocessable Entity | Invalid payload — missing required field, validation error | Check request body fields match API schema |
| HTTP 429 Too Many Requests | REST rate limit exceeded (5000 req/hr authenticated) | Wait for |
| GraphQL rate limit exceeded | Used more than 5000 points/hr | Reduce query complexity or wait; see |
| "no git remotes found" | Running | Add |
| Insufficient OAuth scopes | Token lacks required scope for the operation | Run |
| Duplicate issue/PR title | Not a real error — GitHub allows duplicates, but check before creating | Search with |
| Archived repo blocks writes | Repo is archived; all write operations fail | Unarchive with |
Enable debug logging to see raw HTTP requests and responses:
bash
GH_DEBUG=api gh pr list --repo owner/repo| 错误 | 原因 | 解决方法 |
|---|---|---|
| HTTP 401 Unauthorized | 令牌过期或被吊销 | 运行 |
| HTTP 403 Forbidden | 权限不足或触发速率限制 | 运行 |
| HTTP 404 Not Found | 仓库不存在、是私有仓库但没有 | 验证仓库名称;运行 |
| HTTP 422 Unprocessable Entity | 无效 payload — 缺失必填字段、验证失败 | 检查请求体字段是否符合API schema |
| HTTP 429 Too Many Requests | 超出REST速率限制(认证用户为5000次/小时) | 等待 |
| GraphQL速率限制超出 | 每小时使用超过5000点额度 | 降低查询复杂度或等待;查看 |
| "no git remotes found" | 在git仓库外运行 | 为命令添加 |
| OAuth权限不足 | 令牌缺少操作所需的权限范围 | 运行 |
| Issue/PR标题重复 | 不是实际错误 — GitHub允许重复,但创建前建议检查 | 先通过 |
| 归档仓库禁止写入 | 仓库已归档;所有写入操作失败 | 运行 |
启用debug日志查看原始HTTP请求和响应:
bash
GH_DEBUG=api gh pr list --repo owner/repoGists
Gists
Create
创建
Create a public gist from a file:
bash
gh gist create --public --desc "Rate limiter implementation" rate_limiter.pyCreate from stdin:
bash
echo '{"key": "value"}' | gh gist create --filename config.json从文件创建公开gist:
bash
gh gist create --public --desc "Rate limiter implementation" rate_limiter.py从标准输入创建:
bash
echo '{"key": "value"}' | gh gist create --filename config.jsonList, View, Edit, Delete
列表、查看、编辑、删除
bash
gh gist list --limit 10
gh gist view abc123def456
gh gist edit abc123def456 --add new_file.py
gh gist delete abc123def456bash
gh gist list --limit 10
gh gist view abc123def456
gh gist edit abc123def456 --add new_file.py
gh gist delete abc123def456Organizations and Teams
组织与团队
List orgs for the authenticated user:
bash
gh org listList org members with pagination:
bash
gh api orgs/some-org/members --paginate --jq '.[].login'List teams in an org:
bash
gh api orgs/some-org/teams --paginate --jq '.[] | "\(.slug): \(.description)"'List members of a specific team:
bash
gh api orgs/some-org/teams/backend-team/members --paginate --jq '.[].login'列出当前认证用户所属的组织:
bash
gh org list分页列出组织成员:
bash
gh api orgs/some-org/members --paginate --jq '.[].login'列出组织下的团队:
bash
gh api orgs/some-org/teams --paginate --jq '.[] | "\(.slug): \(.description)"'列出指定团队的成员:
bash
gh api orgs/some-org/teams/backend-team/members --paginate --jq '.[].login'Limitations
限制
- Network required — all commands require internet access; no offline mode.
gh - GraphQL point budget — 5000 points/hr for authenticated users. Complex queries with
high /
firstvalues consume points faster. Seelast.references/graphql-queries.md - Secrets are write-only — works, but there is no
gh secret set. Secret values cannot be retrieved after creation.gh secret get - Org admin operations — managing org settings, teams, and SAML requires the scope, which is not granted by default.
admin:org - Artifact retention — workflow artifacts are retained for 90 days by default. Expired artifacts cannot be downloaded.
- 需要网络 — 所有命令都需要网络连接;无离线模式。
gh - GraphQL点数预算 — 认证用户每小时有5000点额度。/
first值较高的复杂查询会更快消耗点数,参考last。references/graphql-queries.md - 密钥仅写 — 支持,但没有
gh secret set命令,密钥创建后无法检索值。gh secret get - 组织管理员操作 — 管理组织设置、团队和SAML需要权限,默认不授予该权限。
admin:org - 制品保留期 — 工作流制品默认保留90天,过期制品无法下载。
Calibration Rules
使用规范
- Prefer over parsing text output. Text output formats are unstable across
--jsonversions. Always useghto get machine-readable output.--json field1,field2 - Use to minimize output before processing. Filter at the source rather than piping large JSON blobs to external tools.
--jqruns server-side and reduces data transferred.--jq - Prefer higher-level commands over raw API. Use instead of
gh issue create. High-level commands handle auth, pagination, and error formatting automatically.gh api repos/.../issues -X POST - Use consistently when outside a git directory. Never rely on implicit repo detection in scripts or CI environments. Always pass
--repoexplicitly.--repo owner/repo - Use GraphQL only for nested or bulk data. For single-resource fetches and mutations with simple payloads, REST is faster to write, easier to debug, and predictable under rate limits.
- 优先使用而非解析文本输出。
--json不同版本的文本输出格式不稳定,始终使用gh获取机器可读的输出。--json field1,field2 - 使用在处理前最小化输出。 在源端过滤结果,不要将大型JSON blob管道到外部工具处理。
--jq在服务端运行,可减少传输的数据量。--jq - 优先使用高级命令而非原始API。 用代替
gh issue create,高级命令会自动处理认证、分页和错误格式化。gh api repos/.../issues -X POST - 在git目录外运行时始终指定。 不要在脚本或CI环境中依赖隐式仓库检测,始终显式传递
--repo参数。--repo owner/repo - 仅在获取嵌套或批量数据时使用GraphQL。 对于单资源获取和简单payload的变更操作,REST编写更快、调试更容易,速率限制表现也更可预测。