Documentation
¶
Overview ¶
Package github is a minimal, dependency-free client for the slice of the GitHub REST API gk needs (currently: listing an owner's repositories for `gk clone` with no arguments). It talks to api.github.com directly over net/http, so no `gh` binary is required at runtime — only reused, if present, as a source of an existing auth token.
Index ¶
- Variables
- func EventIDLess(a, b string) bool
- func ResolveToken() string
- type Client
- func (c *Client) CreatePullRequest(ctx context.Context, owner, repo string, in NewPullRequest) (PullRequest, error)
- func (c *Client) FindOpenPR(ctx context.Context, owner, repo, head, base string) (pr PullRequest, found bool, err error)
- func (c *Client) GetWorkflowRun(ctx context.Context, owner, repo string, runID int64) (WorkflowRun, error)
- func (c *Client) ListMyOrgs(ctx context.Context) ([]string, error)
- func (c *Client) ListRepoEvents(ctx context.Context, owner, repo, etag string) (events []RepoEvent, newETag string, notModified bool, pollIntervalSec int, ...)
- func (c *Client) ListRepos(ctx context.Context, owner string) ([]Repo, error)
- func (c *Client) ListWorkflowRuns(ctx context.Context, owner, repo, sha, workflow string) ([]WorkflowRun, error)
- func (c *Client) OwnerType(ctx context.Context, owner string) (string, error)
- func (c *Client) SearchCount(ctx context.Context, query string) (int, error)
- func (c *Client) SearchIssues(ctx context.Context, query, sort string, limit int) ([]Issue, error)
- func (c *Client) SearchIssuesWithTotal(ctx context.Context, query, sort string, limit int) ([]Issue, int, error)
- func (c *Client) ViewerLogin(ctx context.Context) string
- type HTTPDoer
- type Issue
- type NewPullRequest
- type PullRequest
- type Repo
- type RepoEvent
- type WorkflowRun
Constants ¶
This section is empty.
Variables ¶
var ErrNoCommitsBetween = errors.New("no commits between base and head")
ErrNoCommitsBetween reports the 422 for a head that is not ahead of base. Distinguished for the same reason: the fix (commit, or pick another base) is specific and worth naming.
var ErrOwnerNotFound = errors.New("github owner not found")
ErrOwnerNotFound reports that GET /users/{owner} answered 404 — the login does not exist on GitHub, or is invisible to the token in use. Callers surface this early instead of letting the later search 422 with a cryptic "cannot be searched" validation error.
var ErrPRAlreadyExists = errors.New("a pull request for this branch already exists")
ErrPRAlreadyExists reports the 422 GitHub returns when an open pull request already covers this head→base pair. It is separate from other validation failures because it is recoverable: the caller can look the existing PR up (FindOpenPR) and point at it instead of reporting a failure.
Functions ¶
func EventIDLess ¶
EventIDLess reports whether event id a is older than b. GitHub event ids are monotonically increasing numeric strings; it parses them as integers and falls back to length-then-lexical comparison for any non-numeric id.
func ResolveToken ¶
func ResolveToken() string
ResolveToken finds a GitHub API token without shelling out to `gh` or requiring one to be installed. SSH keys authenticate the git wire protocol (clone/push) but not this REST API, so they are not a source here — listing repositories needs a bearer token.
Resolution order:
- GH_TOKEN / GITHUB_TOKEN env vars — the same names `gh`, GitHub Actions, and most other GitHub tooling read.
- gh's own stored auth (~/.config/gh/hosts.yml, or $GH_CONFIG_DIR) — read as a plain file, not invoked as a binary, so a prior `gh auth login` is reused even where the CLI itself isn't on PATH.
Returns "" when none of the above yield a token; callers fall back to an unauthenticated request (public repos only, lower rate limit).
Types ¶
type Client ¶
type Client struct {
HTTP HTTPDoer // http.DefaultClient when nil
APIBase string // "https://api.github.com" when ""
Token string
// contains filtered or unexported fields
}
Client talks to api.github.com. The zero value works unauthenticated (public repos only, subject to the 60/hour anonymous rate limit); set Token (see ResolveToken) to see private repos too.
func (*Client) CreatePullRequest ¶
func (c *Client) CreatePullRequest(ctx context.Context, owner, repo string, in NewPullRequest) (PullRequest, error)
CreatePullRequest opens a pull request against owner/repo.
This is the one write path in this package, so it insists on a token up front: an anonymous POST comes back as a 401 whose message ("Requires authentication") reads like a gk bug rather than a missing credential.
func (*Client) FindOpenPR ¶
func (c *Client) FindOpenPR(ctx context.Context, owner, repo, head, base string) (pr PullRequest, found bool, err error)
FindOpenPR returns the open pull request for a head→base pair. head must be fully qualified as "owner:branch" (GitHub's head filter ignores a bare branch name on a repository that has forks). found is false when there is none — that is a normal answer, not an error.
base is part of the filter because a branch may have several open PRs, one per base; only the one against this base is the PR that a create attempt collided with. An empty base widens the search to any base.
func (*Client) GetWorkflowRun ¶ added in v0.143.0
func (c *Client) GetWorkflowRun(ctx context.Context, owner, repo string, runID int64) (WorkflowRun, error)
GetWorkflowRun returns the current state of one Actions run.
func (*Client) ListMyOrgs ¶
ListMyOrgs returns the organization logins the token's user belongs to (GET /user/orgs). It needs a token: unauthenticated callers get an empty list and no error, so a scope picker can simply offer fewer choices.
func (*Client) ListRepoEvents ¶
func (c *Client) ListRepoEvents(ctx context.Context, owner, repo, etag string) (events []RepoEvent, newETag string, notModified bool, pollIntervalSec int, err error)
ListRepoEvents fetches the repo's recent events with a conditional ETag.
On 304 Not Modified it returns notModified=true with no events (and does not count against the rate limit). Otherwise it returns the events newest-first (as GitHub sends them) and the new ETag to pass on the next call. pollIntervalSec echoes GitHub's X-Poll-Interval hint (0 when absent).
func (*Client) ListRepos ¶
ListRepos lists the repositories visible to this client under owner, whether owner is a GitHub org or a user.
It tries the org endpoint first — /orgs/{owner}/repos also returns private repos when the token belongs to an org member. A 404 there means owner isn't an org, so it falls through:
- if the token's own login matches owner, /user/repos (filtered to that owner) is used so the caller's own private repos show up — the public-only /users/{owner}/repos can't see them even for the token's own account.
- otherwise /users/{owner}/repos (public repos only; seeing someone else's private repos requires being added as a collaborator, which this endpoint does not surface).
func (*Client) ListWorkflowRuns ¶ added in v0.143.0
func (c *Client) ListWorkflowRuns(ctx context.Context, owner, repo, sha, workflow string) ([]WorkflowRun, error)
ListWorkflowRuns returns the newest Actions runs for a commit. If workflow is set, it filters by GitHub's workflow display name.
func (*Client) OwnerType ¶
OwnerType reports whether owner is an "Organization" or a "User" on GitHub, via GET /users/{owner} — the endpoint answers for both, and an org login resolves here too (with type "Organization"). Callers use it to pick the right search qualifier: `org:{owner}` vs `user:{owner}`.
func (*Client) SearchCount ¶
SearchCount returns just the total number of matches for a query, without paging the rows in — for callers (like `gk context`) that only need the count. It fetches a single minimal page and reads total_count.
func (*Client) SearchIssues ¶
SearchIssues runs a GitHub issue/PR search (GET /search/issues) and returns every matching row across pages. query is the raw `q=` value, e.g. "repo:owner/name is:open is:pr" — callers build the qualifiers.
A token is required for `@me` qualifiers and to see private repos; unauthenticated callers get public results only, under the stricter 10/min search bucket (vs 30/min authenticated).
sort is the API sort key ("updated" | "created" | "comments"); "" defaults to "updated". limit caps the number of rows returned (0 = no cap, up to the 1000-result API ceiling).
func (*Client) SearchIssuesWithTotal ¶
func (c *Client) SearchIssuesWithTotal(ctx context.Context, query, sort string, limit int) ([]Issue, int, error)
SearchIssuesWithTotal is SearchIssues plus the exact total_count reported by GitHub. Callers that cap the returned rows (for example an interactive picker) can still distinguish a complete result from a truncated one.
type HTTPDoer ¶
HTTPDoer is the subset of http.Client this package depends on. Lets tests substitute a recording transport without a network round-trip.
type Issue ¶
type Issue struct {
Number int
Title string
State string // "open" | "closed"
URL string // html_url — the browser link, not the API url
Owner string // parsed from repository_url
Repo string
Author string
UpdatedAt time.Time
IsPR bool
Draft bool
Labels []string
}
Issue is one row from the GitHub issue/PR search index. GitHub models pull requests as issues, so a single /search/issues query returns both; IsPR distinguishes them — the raw payload carries a `pull_request` object only for PRs.
type NewPullRequest ¶
NewPullRequest is the input for CreatePullRequest. Head names the source branch: a bare "branch" when it lives in the target repository, or "owner:branch" when it lives in a fork.
type PullRequest ¶
PullRequest is the slice of GitHub's pull-request JSON gk reports back. URL is html_url — the page a human opens, not the API resource.
type RepoEvent ¶
type RepoEvent struct {
ID string // monotonically increasing numeric id (as a string)
Type string // PullRequestEvent | IssuesEvent | PullRequestReviewEvent | IssueCommentEvent | PushEvent | ...
Action string // payload.action (opened | closed | labeled | submitted | created | ...)
Actor string // actor.login
CreatedAt time.Time
// Pull-request fields (PullRequestEvent, PullRequestReviewEvent).
PRNumber int
PRTitle string
PRMerged bool
PRBase string // base branch ref
PRHead string // head branch ref
// Issue fields (IssuesEvent, IssueCommentEvent).
IssueNumber int
IssueTitle string
Label string // payload.label.name (labeled action)
ReviewState string // payload.review.state (PullRequestReviewEvent)
}
RepoEvent is one flattened entry from a repository's event stream (GET /repos/{owner}/{repo}/events). GitHub returns a heterogeneous payload per Type; this struct hoists the fields the follow triggers care about, with the rest left zero.
type WorkflowRun ¶ added in v0.143.0
type WorkflowRun struct {
ID int64 `json:"id"`
Name string `json:"name"`
HeadSHA string `json:"head_sha"`
Status string `json:"status"`
Conclusion string `json:"conclusion"`
HTMLURL string `json:"html_url"`
}
WorkflowRun is the GitHub Actions run data needed to select and watch a workflow. The API supplies more fields, which gk deliberately does not own.