Gh
Patterns for invoking the GitHub CLI (gh) from agents. Covers structured output, pagination, repo targeting, search vs list, gh api fallback.
- Скачивания
- 0
- В избранном
- 0
- Комментарии
- 0
- Просмотры
- 3
Установить скилл
Добавьте инструмент одной командой или скачайте проверенный архив версии.
npx skills add cli/cli --skill gh- Версия
- 1.0.0+fa92838bef95
- Автор
- Владимир Ломтев
- Репозиторий
- cli/cli
Как установить
- 1Скопируйте команду из блока установки.
- 2Запустите её в терминале из каталога проекта.
Документация
Reference
Interactivity policy
gh already does the right thing in non-TTY contexts: it skips the pager,
strips ANSI color, and errors out fast with a helpful message instead of
prompting (e.g. must provide --title and --body when not running interactively).
You don't need to defensively set GH_PAGER or pass --no-pager (no such
flag exists).
Parsing JSON
Human output from gh is column-formatted. If you want structured data:
- Add
--json field1,field2,...for structured output. - For
gh issue viewandgh pr view, use--json ...,commentsto include comments in structured data; use--commentsonly with the human-readable view. - Run a command with
--jsonand no field list to print the full set of available fields, then pick what you need. - Use
--jq '<expr>'for filtering without piping through a separatejq. - Use
--template '<go-template>'(alongside--json) when you want shaped text output. Note that--template/-Tcollides with a body-template flag on a few commands (e.g.gh pr create -T,gh issue create -T); always check--helpbefore assuming which one you're hitting.
Pagination and silent truncation
List commands cap results.
gh issue list,gh pr list,gh search ...: pass-L N(--limit N). The default is usually 30.gh issue list/gh pr listdo not expose aggregate totals liketotalCountvia--json. If you need a true total, usegh api graphqlto querytotalCount; otherwise, treat-Las the cap for the current call.- For raw API calls use
gh api --paginate <path>. Combine with--jqand (optionally)--slurpto assemble one array.
Repo targeting
gh infers the repo from the cwd's git remotes.
Pass --repo OWNER/REPO (-R) to override the resolved CWD repo.
Search vs list
gh search issues|prs|code|repos|commits|usersuses GitHub's search index and accepts the full search syntax (is:open,author:,label:,repo:owner/name,in:title, ...). Pass each qualifier as its own bare token, not as one quoted string:gh search issues repo:cli/cli is:open author:monalisaworks, butgh search issues "repo:cli/cli is:open"is treated as a single keyword (parsed asrepo:"cli/cli is:open") and fails withInvalid search query. Quote only multi-word free text (gh search issues "broken feature"). Most qualifiers also have a dedicated flag (--repo,--author,--label, ...). Prefer search for anything cross-repo or filtered by author/label.gh issue list --search "..."andgh pr list --search "..."take the query as one quoted string (it is a flag value) and are scoped to one repo.- Bots author as GitHub Apps, so
--author dependabotmatches nothing. Use--app dependabot(onpr/issue listandsearch prs|issues; expands toauthor:app/<slug>) or--author "dependabot[bot]". gh search issuesalso takes--search-type <lexical|semantic|hybrid>(github.com/GHEC only, issues only): usesemanticwhen the user describes a problem in natural language rather than exact terms, andhybridto blend keyword and semantic ranking;lexical(default) is exact matching.
Issue types, sub-issues, and relationships
Newer gh issue subcommands model issue types, sub-issue hierarchy, and
blocked-by/blocking relationships.
gh issue create:--type <name>,--parent <number|url>(creates the new issue as a sub-issue),--blocked-by <number|url,...>,--blocking <number|url,...>.gh issue edit(edits one or more issues in the same repo, e.g.gh issue edit 23 34):--type <name>/--remove-type,--parent <n|url>/--remove-parent,--add-sub-issue <n,n>/--remove-sub-issue <n,n>,--add-blocked-by <n,n>/--remove-blocked-by <n,n>,--add-blocking <n,n>/--remove-blocking <n,n>. Relationship and parent refs are issue numbers or URLs; a URL may point to another repo on the same host, but a different host is rejected.--add-sub-issuecannot be used when editing more than one issue.gh issue list --type <name>filters by issue type.gh issue viewandgh issue listaccept these as--jsonfields (prefer them over scraping the default text output):issueType,parent,subIssues,subIssuesSummary,blockedBy,blocking.subIssues,blockedBy, andblockingare objects shaped{"nodes": [...], "totalCount": N}(not flat arrays), andnodesis capped (subIssuesat 100,blockedBy/blockingat 50), so compare the node count againsttotalCountto detect truncation.- GHES: issue types and sub-issues need 3.17+; blocked-by/blocking relationships need 3.19+.
Attaching images and videos
--attach <path> is available on gh issue create, gh issue edit,
gh issue comment, gh pr create, gh pr edit, gh pr comment,
gh issue artifact create, and gh issue artifact edit.
- Repeat
--attachto upload multiple files:gh issue comment 12 --attach ./before.png --attach ./after.png. - Each command invocation accepts at most 50
--attachvalues total across images and videos. - Supported files are
png,jpg,jpeg,gif,webp,svg,mp4,mov, andwebm. - For an image, append alt text to the path after
#. Quote the value so the shell does not treat#as a comment:gh pr create --attach './login.png#The login error state'. Without alt text, the filename is used. --attachpaths and local Markdown destinations may be absolute or relative to the directory whereghruns. When the body comes from a file with--body-file, or from a file argument togh issue artifact create, relative destinations resolve against that file's directory first, then the directory whereghruns.- If the body references an attached path,
ghrewrites that Markdown reference to the uploaded URL. The reference keeps its existing alt text. Otherwise,ghappends the attachment to the body. For example:gh pr edit 23 --body '' --attach ./login.png. - Videos cannot take alt text. A standalone
becomes a bare player URL, while an inline video image becomes a link. A reference-style video image such as![recording][clip]with[clip]: ./repro.mp4is rejected; use a reference-style link instead. gh issue createandgh pr create:--attachcannot be used with--web.gh pr create --attachalso cannot be used with--dry-run.gh issue edit:--attachcan edit only one issue at a time.gh issue commentandgh pr comment:--attachcannot be used with--webor--delete-last. It works alone, with--edit-last, or with one of--body,--body-file, or--editor.gh issue artifact createandgh issue artifact edit:--attachworks only on Markdown documents, not links or HTML documents. With several Markdown documents,createuploads each file once and points every document that references it at the upload, and a file that no document references is an error before anything uploads.editwith only--attachappends the files to the artifact's current content.- Uploads require GitHub.com or a GHE.com tenant, an OAuth token, classic PAT,
or fine-grained PAT, and
WRITE,MAINTAIN, orADMINrepository permission. GitHub Enterprise Server and most GitHub App tokens are unsupported. - Uploads stop at the first failure. If earlier files uploaded,
ghstill writes those attachments and exits non-zero.gh issue create,gh issue edit,gh pr create, andgh pr editalso print the issue or pull request URL.gh issue artifact createandeditstill save an artifact that is missing some of its files if any of them uploaded, with the upload error as the reason on itscreatedorupdatedline. If none of them uploaded, the artifact isn't saved and gets afailedline.
Discussions (gh discussion)
Preview command set, subject to change. Subcommands:
gh discussion list [--state open|closed|all] [--category <name>] [--author <handle>] [--label <name>,...] [--answered] [--search <query>] [--sort created|updated] [--order asc|desc] [--limit N] [--after <cursor>] [--json <fields>] [--web]lists a repo's discussions.--statedefaults to open,--sortto updated,--orderto desc.--answeredis tri-state (--answered=falsefor unanswered) for Q&A categories.gh discussion view {<number>|<url>|<comment-id>|<comment-url>} [--comments] [--order oldest|newest] [--limit N] [--after <cursor>] [--json <fields>] [--web]shows a discussion's body; add--commentsfor its comments, or pass a comment ID/URL as the argument to list that comment's replies (no--repliesflag;--commentsis rejected with a comment argument).--order(default newest),--limit, and--afterapply only to comment and reply listings.gh discussion create [--title <t>] [--body <b> | --body-file <path>] [--category <name>] [--label <name>,...]creates a discussion.--title, a body (--bodyor--body-file), and--categoryare required non-interactively; omitting any will prompt on a terminal.gh discussion edit {<number>|<url>} [--title <t>] [--body <b>] [--body-file <path>] [--category <name>] [--add-label <name>,...] [--remove-label <name>,...]edits title, body, category, or labels.gh discussion comment {<number>|<discussion-url>|<comment-id>|<comment-url>} [--body <b>] [--body-file <path>] [--edit] [--delete] [--yes]adds a top-level comment (when given a discussion) or a reply (when given a comment);--editor--deleteupdates or removes a comment/reply and needs a comment ID or URL.--yesskips the--deleteconfirmation.--json/--jq/--templateare available onlistandviewonly;createandeditprint the discussion URL.commentprints the discussion comment (or reply) URL.
Issue artifacts (gh issue artifact)
Preview command set, subject to change. Issue artifacts are Markdown documents
(type generic or plan), HTML documents (type embedded_html), and links
(type link) attached to an issue. Each has a number on its issue, and
commands address artifacts by that number, since names aren't unique. They
are not GitHub Actions artifacts, which gh run download handles.
Subcommands:
gh issue artifact list {<issue-number>|<issue-url>} [--type generic|plan|link|embedded_html] [--limit N] [--json <fields>](aliasls) lists artifacts in number order. There is no default limit: every artifact is listed unless--limitis set.--type genericand--type planboth list every Markdown document, and each keeps its stored type. Piped output is tab-separated number, name, type, and RFC 3339 update time.--jsonfields includebody, so one call can return every artifact's content.gh issue artifact view {<issue> <artifact-number> | <artifact-url>} [--version N] [--json <fields>] [--web]shows one artifact and its edit history. In a terminal, it ends with the artifact's URL. Piped output isname:,number:,version:,type:,creator:,created:,updated-by:,updated:, andurl:lines, in that order, then--and the raw body.--version Nshows that version from the edit history.--version,--json, and--webare mutually exclusive.--json versionsreturns the edit history.--webopens a document's page on GitHub, or a link's URL.gh issue artifact create {<issue-number>|<issue-url>} [<file>[#<name>] | <url>]... [--body <text> | --body-file <path>] [--name <name>] [--type generic|plan|embedded_html] [--attach <path>]...(aliasnew) creates one artifact per file or URL, in argument order. A text file becomes a document named after the file, or after the text following#:gh issue artifact create 142 'docs/signin-plan.md#Sign-in plan'. A.htmlor.htmfile becomes an HTML document. Anhttp(s)URL becomes a link named after its host, and a.urlInternet Shortcut file becomes a link to its URL. Names can't contain some characters, such as parentheses.ghdrops them from names it takes from file names (plan (1).mdbecomesplan 1.md), but sends a name given with#or--nameas typed. Instead of file or URL arguments,--body <text>creates one document and--body-file <path>creates one artifact from a file. Neither can be combined with file or URL arguments.--namenames a single artifact. It's required with--bodyor--body-file -, and can't be combined with a#<name>suffix. Documents aregeneric, and HTML documentsembedded_html.--typesets the type of every document instead, whatever the file extension, so--type embedded_htmlmakes--bodyor--body-file -an HTML document. A plan currently behaves the same as a generic document.--typeis refused if any artifact is a link.gh issue artifact edit {<issue> <artifact-number> | <artifact-url>} [--name <name>] [--body <text> | --body-file <path>] [--attach <path>]... [--restore-version N]renames an artifact or replaces its content, saving a new version. At least one of--name,--body,--body-file,--attach, or--restore-versionis required, and a--body-filenever renames the artifact. The type never changes: a link's new content must be anhttp(s)URL or a.urlfile, and a document can't take a.urlfile.--restore-version Nsaves the name and content of version N from the edit history as a new version. It works for any versionviewlists, and can't be combined with--name,--body,--body-file, or--attach. If the artifact already matches that version, nothing is saved andghexits 0, with askippedline when piped.gh issue artifact delete {<issue> <artifact-number>... | <artifact-url>...} [--yes]deletes artifacts, which can't be restored. In a terminal,ghasks once for all of them.--yesskips the prompt and is required whenghcan't prompt. Without--yes, a failed lookup stops the command before the prompt, and nothing is deleted. With--yes, every number is attempted.gh issue artifact download {<issue> [<artifact-number>...] | <artifact-url>...} [--dir <dir> | --output <path>] [--clobber | --skip-existing] [--version N]writes the given artifacts, or every artifact on the issue, to files in--dir(default.). Each file is named<number>-<name>, with path separators, whitespace, control characters, and characters Windows forbids replaced by-. Markdown documents end in.md, HTML documents in.htmlor.htm, and links are saved as.urlInternet Shortcut files, whichcreateandeditread back as links. An existing file fails that artifact unless--clobberoverwrites it or--skip-existingskips it.--output <path>and--version N(an earlier version from the edit history) need exactly one artifact number, and--output -prints its stored body (a link's URL) with nothing else. Without numbers, an issue with no artifacts is an error.- The issue argument is a number or an issue URL, and a URL selects its own
repository. An artifact URL,
https://github.com/<owner>/<repo>/issues/<issue>/artifacts/<number>, can replace the issue and number, and selects its repository the same way. Artifact URLs in one command must be on the same issue. Pull requests are refused, and so is GitHub Enterprise Server. --json/--jq/--templateare available onlistandviewonly. Theidfield is a global ID that no command accepts; commands takenumber, orurl, the artifact's page on GitHub.create,edit, anddownload(except with--output -) report each artifact on its own line. When piped, every line goes to stdout with five tab-separated columns, empty ones included: status (created,updated,restored,written,skipped, orfailed), artifact number, name (the file path fordownload), source (the file, URL, or-given tocreate, or the--body-filevalue given toedit), and the reason for a skip, a failure, or--attachfiles that didn't upload. In a terminal, failures go to stderr. A failed artifact doesn't stop the others, and the command exits 1 after any failure or failed upload. Aftercreateexits 1, retry only thefailedlines, since the others were created.deletereports on stderr. In a terminal, each deleted or failed artifact gets a line. When piped, a deleted artifact prints nothing, and each failure prints<number>: <reason>. Any failure exits 1.createandeditread and check every file before any request, so a missing, empty, or binary file fails the whole command, and nothing is saved. Standard input is read only through--body-file -, andcreaterefuses a-argument.view,edit, anddownloadrefuse an artifact whose type this version ofghdoesn't know, with a message to upgradegh.listanddeletework with any type.
Reading files and directories (gh repo read-file / read-dir)
Preview commands, subject to change. They read a repo's contents over the API
without cloning, and honor --repo OWNER/REPO (-R) and --ref <branch|tag|commit>
(default branch when omitted).
gh repo read-file <path> [--ref <ref>] [--output <path> [--clobber]] [--allow-escape-sequences] [--json <fields>] [--jq <expr>]prints a file's contents. In non-TTY contexts the raw bytes go straight to stdout (pipe-friendly); binary files are written as-is when piped but are refused on a TTY. By default, a file containing terminal escape sequences is refused; pass--allow-escape-sequencesto read it anyway.--output <path>(-o) writes to disk instead of stdout (a trailing slash writes under a directory using the remote file name;--clobberallows overwrite); writing to disk always includes the raw bytes regardless of escape sequences.--outputand--jsonare mutually exclusive.--jsonfields includename,path,gitSHA,size,type,encoding, andcontent(base64 encoded).gh repo read-dir [<path>] [--ref <ref>] [--json <fields>] [--jq <expr>]lists a directory; with no path it lists the repo root. Non-TTY output is tab separated as type, name, octal mode, and byte size.--jsonfields includename,path,type,gitType,mode,modeOctal,gitSHA,size, andsubmodule. A path pointing at a file errors and points you atread-file(and vice versa).
Fall back to gh api for anything --json doesn't expose
Sometimes useful data isn't on the typed commands. Examples:
- Review-thread comments on a PR:
gh api repos/{owner}/{repo}/pulls/{n}/comments(the--commentsflag ongh pr viewshows issue-level comments only). - Arbitrary GraphQL:
gh api graphql -f query='...' -F var=value. - REST shortcuts:
gh api repos/{owner}/{repo}/...- note the{owner}/{repo}placeholder is filled in for you when run from a repo with detected remotes; pass them literally if you want determinism.
Authentication
gh auth statusprints the active host(s), user, and which env var (if any) is being honored.gh auth status --jsonis supported.
Other notes
gh pr checkout <n>switches branches. Usegh pr diff <n>orgh pr view <n>if you only need to read.gh pr checkout <n> --worktree <path>checks the PR out into a git worktree at<path>instead of switching the current branch.gh issue develop <n> --checkoutcreates a linked branch for the issue and checks it out. Add--worktree <path>to check that branch out into a git worktree at<path>instead of switching the current branch;--worktreerequires--checkout, cannot be blank, and cannot be combined with--list.NO_COLOR,CLICOLOR_FORCE, andGH_FORCE_TTYare honored. SetGH_FORCE_TTY=1if you want TTY-style output (colors, tables, the pager, interactivity) inside an agent harness; leave it unset unless needed.
Требования и возможности
Файлы версии
| Путь | Размер | SHA256 |
|---|---|---|
| SKILL.md | 20279 | 49e379899f0e89f7... |
Частые вопросы
- Как установить Gh?
- Используйте команду
npx skills add cli/cli --skill ghили скачайте ZIP-архив. - Можно ли скачать Gh бесплатно?
- Да, опубликованную версию можно скачать из маркетплейса бесплатно.
Похожие инструменты
Смотреть всеВойдите, чтобы оставить комментарий.
Комментариев пока нет.