Expand description
vcs-github — automate GitHub from Rust by driving the gh CLI.
You call typed async methods; vcs-github runs the real gh, parses its
output, and hands you structured values — so you get gh’s own behaviour, auth,
and host resolution, not a reimplementation of the GitHub REST/GraphQL API.
Async, structured errors, mockable. Every command runs inside an OS job (an
OS-level container that kills the whole process tree if your program exits, via
processkit) so a gh subprocess is never orphaned, with an optional
per-client timeout. Read-style methods ask gh for
--json and deserialize it; nothing scrapes human-readable output.
§What you can do
Check auth · view the repo · the full pull-request lifecycle (list / view / create / merge / mark-ready / close, review / comment, CI checks, feedback) · issues · releases · GitHub Actions runs (list / view / watch). One tiny call to start:
use std::path::Path;
use vcs_github::{GitHub, GitHubApi};
let gh = GitHub::new();
let prs = gh.pr_list(Path::new(".")).await?; // up to 100 open PRs§The surface (engineering reference)
GitHubApi— the object-safe trait every operation lives on. Depend on&dyn GitHubApi(or generically onimpl GitHubApi) so a test can swap the real client for a double. Repo-scoped methods take the working directory as the first argument and return typed results (PullRequest,Issue,Repo,CheckRun,WorkflowRun,Release,PrFeedback, …) or a structuredError.GitHub— the real client.GitHub::newuses the job-backed runner;GitHub::with_runnerinjects a fake one for tests. It is generic over theProcessRunnerseam, defaulting to the production runner.with_credentialsattaches aCredentialProviderto supply a token per operation (injected asGH_TOKEN, never inargv) — opt-in, off by default (ambientghauth).GitHubAt— a cwd-bound view (GitHub::at) whose methods drop the leadingdir, sogh.at(dir).pr_list()reads asgh.pr_list(dir)— handy when one client drives one checkout.- Method groups on the trait: PRs (
pr_list,pr_view,pr_create,pr_merge,pr_ready,pr_close,pr_review,pr_comment,pr_edit,pr_checks,pr_feedback, …); Actions runs (run_list,run_view,run_watch— blocking, bounded by the client timeout); issues & releases (issue_create,release_view, …); plus the escape hatchesrun/apifor anything unmodelled. - Builder specs for the multi-option commands —
PrCreate(title/body with optionalhead/base),PrEdit(optionaltitleand/orbodyforpr edit),PrMerge(strategyMergeStrategy,--auto,--delete-branch), andReviewAction(whose private fields make an empty-body request-changes unrepresentable) — each#[non_exhaustive], built with a constructor and chained setters, named after the flags they emit.
§Recipes
Read state — depend on the trait so the same code takes a real client or a mock:
use std::path::Path;
use vcs_github::{GitHub, GitHubApi};
let gh = GitHub::new();
let dir = Path::new(".");
let authed = gh.auth_status().await?; // is `gh` logged in?
let open = gh.pr_list(dir).await?; // up to 100 open PRsMutate through the builder specs — open a PR, approve it, then squash-merge:
use std::path::Path;
use vcs_github::{GitHub, GitHubApi, PrCreate, PrMerge, ReviewAction};
let dir = Path::new(".");
let url = gh.pr_create(dir, PrCreate::new("Add X", "…").base("main")).await?;
gh.pr_review(dir, 7, ReviewAction::approve().with_body("LGTM")).await?;
gh.pr_merge(dir, 7, PrMerge::squash().delete_branch()).await?;§Testing
Two seams: enable the mock feature for a mockall-generated
MockGitHubApi (stub whole methods), or inject a
ScriptedRunner with GitHub::with_runner
to exercise the real argv-building and parsing against canned output — no
gh binary or network needed, so it runs on CI. The cross-cutting testing
patterns live in
vcs-testkit’s guide.
§Safety
Caller values placed in a bare positional argv slot (an api endpoint, a
release tag) are refused before spawning if empty or starting with - —
gh would parse them as flags. Flag-value slots (--body <b>,
--branch <b>) are consumed verbatim and need no guard.
§In-depth guide
Beyond this page, this crate ships a full how-to guide — rendered on docs.rs
from docs/. See the guide module.
Modules§
- __
mock_ Mock GitHub Api - __
mock_ Mock GitHub Api_ GitHub Api - guide
- vcs-github — GitHub CLI guide
Structs§
- Cancellation
Token - A token which can be used to signal a cancellation request to one or more tasks.
- Check
Run - One check on a PR (
gh pr checks --json …). - Comment
- A PR conversation comment (from
gh pr view --json comments). - Credential
- A resolved credential: a
Secretplus an optional username. For a forge token only the secret is used; for git HTTPS the username pairs with the secret as the password (a personal-access token). - Credential
Request - The context of a credential request: which service, and the remote host if
the backend knows it (forge calls often defer host resolution to the CLI, so
hostis frequentlyNone).#[non_exhaustive]: more context may be added. - EnvToken
- A provider that reads a bare token from a named environment variable, at
request time. If the variable is unset/empty it yields
None(fall back to ambient auth) rather than erroring — handy for “use$MY_TOKENif present”. - FnProvider
- A
CredentialProviderbacked by a synchronous closure (seeprovider_fn). - GitHub
- The real GitHub client. Generic over the
ProcessRunnerso tests can inject a fake process executor;GitHub::newuses the real job-backed runner. - GitHub
At - A
GitHubclient with a working directory bound, so its repo-scoped methods drop the leadingdirargument (gh.at(dir).pr_list()). Construct one withGitHub::at. - Issue
- An issue (
gh issue list --json number,title,state;gh issue viewadditionally fillsbody/url). - Mock
GitHub Api - The GitHub operations this crate exposes — the interface consumers code against and mock in tests.
- PrCreate
- Options for
GitHubApi::pr_create(gh pr create). - PrEdit
- Options for
GitHubApi::pr_edit(gh pr edit). - PrFeedback
- The review/comment feedback on a PR (
gh pr view --json reviews,comments). - PrMerge
- Options for
GitHubApi::pr_merge(gh pr merge). - Process
Result - The captured result of running a process to completion.
- Pull
Request - A pull request (
gh pr list/view --json number,title,state,headRefName,baseRefName,url). - Release
- A release (
gh release list/view --json …). - Repo
- A repository (
gh repo view --json name,owner,description,url,isPrivate,defaultBranchRef). - Review
- A submitted PR review (from
gh pr view --json reviews). - Review
Action - What
GitHubApi::pr_reviewsubmits (gh pr review). - Secret
- A secret value — an API token, a password — that redacts itself whenever
it is formatted, so it can’t leak into a log line or an error message. Read
the underlying value only at the point of use, via
expose. - Static
Credential - A provider that always yields the same
Credentialfor every request — the common “use this one token” case. - Workflow
Run - A GitHub Actions workflow run (
gh run list/view --json …).
Enums§
- Check
Bucket - gh’s coarse categorisation of a
CheckRun’s state — the field to branch on when deciding whether CI passed.ghderives it from the rawstate; this is the typed form of itspass/fail/pending/skipping/cancelstrings. - Credential
Service - Which backend/tool is asking for a credential — lets a provider return
different secrets per service.
#[non_exhaustive]: new backends may be added. - Error
- Errors produced when launching or running a child process.
- Merge
Strategy - How
GitHubApi::pr_mergemerges the PR — exactly one of gh’s mutually exclusive strategy flags. - Review
Kind - Which kind of review
GitHubApi::pr_reviewsubmits — match onReviewAction::kindto read it back.
Constants§
- BINARY
- Name of the underlying CLI binary this crate drives.
Traits§
- Credential
Provider - Supplies a
Credentialfor aCredentialRequest, just-in-time. ReturningOk(None)means “I have nothing for this request” — the backend then falls back to its ambient CLI auth, exactly as if no provider were configured. - GitHub
Api - The GitHub operations this crate exposes — the interface consumers code against and mock in tests.
Functions§
- provider_
fn - Adapt a synchronous closure into a
CredentialProvider. The closure runs at request time and returns the credential (orNoneto defer to ambient auth). For async sources (a network vault), implementCredentialProviderdirectly.
Type Aliases§
- Result
- Crate result alias.