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) Dashboard(ctx context.Context, q DashQuery) (*DashResult, 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) GetWorkflowRunConditional(ctx context.Context, owner, repo string, runID int64, etag string) (run WorkflowRun, newETag string, notModified bool, err error)
- func (c *Client) ListMyOrgs(ctx context.Context) ([]string, error)
- func (c *Client) ListRecentWorkflowRuns(ctx context.Context, owner, repo, etag string) (runs []WorkflowRun, newETag string, notModified bool, err 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) ListWorkflowRunsForSHA(ctx context.Context, owner, repo, sha, etag string) (runs []WorkflowRun, newETag string, notModified bool, err error)
- func (c *Client) OwnerCommitActivity(ctx context.Context, scope string, days []DayRange) (*CommitActivity, error)
- func (c *Client) OwnerType(ctx context.Context, owner string) (string, error)
- func (c *Client) OwnerUnreleased(ctx context.Context, owner string) (*OwnerUnreleased, error)
- func (c *Client) PRActivity(ctx context.Context, scope string, days []DayRange) (opened, merged []int, err 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 CommitActivity
- type CompareCommit
- type DashCheck
- type DashIssue
- type DashIssueList
- type DashLinkedPR
- type DashPR
- type DashPRList
- type DashQuery
- type DashResult
- type DayRange
- type HTTPDoer
- type Issue
- type NewPullRequest
- type OwnerUnreleased
- type PullRequest
- type PushedRepoPoller
- type QueryTimeoutError
- type RateLimitError
- type Repo
- type RepoEvent
- type RepoUnreleased
- type TagComparison
- 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 ErrNoToken = errors.New("github token required")
ErrNoToken is returned before any request when the client has no token: GitHub rejects an anonymous GraphQL request with 403.
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) Dashboard ¶ added in v0.163.0
Dashboard reads the dashboard blocks with two GraphQL queries, one for PRs and one for issues, sent at the same time.
A rate-limit error on either query wins, so a poller waits for the reset. When both fail the errors are joined; when one fails its side is empty and PRErr or IssueErr says why.
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) GetWorkflowRunConditional ¶ added in v0.151.4
func (c *Client) GetWorkflowRunConditional(ctx context.Context, owner, repo string, runID int64, etag string) (run WorkflowRun, newETag string, notModified bool, err error)
GetWorkflowRunConditional is GetWorkflowRun made conditional on etag, for a poller that re-asks about one run until it finishes. notModified means GitHub answered 304, which does not count against the rate limit.
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) ListRecentWorkflowRuns ¶ added in v0.148.0
func (c *Client) ListRecentWorkflowRuns(ctx context.Context, owner, repo, etag string) (runs []WorkflowRun, newETag string, notModified bool, err error)
ListRecentWorkflowRuns returns a repository's newest Actions runs on any commit, conditionally on etag. notModified means GitHub answered 304 and runs is nil; the caller keeps its previous view. One call covers every run of the repo, so a watcher polls this instead of each run separately.
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) ListWorkflowRunsForSHA ¶ added in v0.148.0
func (c *Client) ListWorkflowRunsForSHA(ctx context.Context, owner, repo, sha, etag string) (runs []WorkflowRun, newETag string, notModified bool, err error)
ListWorkflowRunsForSHA is ListWorkflowRuns made conditional on etag, for a poller that re-asks about one pushed commit until its runs finish. notModified means GitHub answered 304 and runs is nil.
func (*Client) OwnerCommitActivity ¶ added in v0.165.0
func (c *Client) OwnerCommitActivity(ctx context.Context, scope string, days []DayRange) (*CommitActivity, error)
OwnerCommitActivity counts, for each day, the commits on the default branches of scope (org:o or user:o). It asks the commit search for one count a day, all at the same time: that took 0.5 to 0.75 s on accounts of 40 to 174 repositories and counts every repository, against 3.2 to 4.2 s for the newest activityRepos with historyCommitActivity.
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) OwnerUnreleased ¶ added in v0.165.0
OwnerUnreleased reads, with one GraphQL query, the latest tag of the owner's most recently pushed repositories and the commits each branch has after it. Forks and archived repositories are left out. A repository without unreleasedBranch answers that comparison with NOT_FOUND, which is expected and not a note.
func (*Client) PRActivity ¶ added in v0.165.0
func (c *Client) PRActivity(ctx context.Context, scope string, days []DayRange) (opened, merged []int, err error)
PRActivity counts, for each day, the pull requests of scope (repo:o/r, org:o, user:o) opened in it and merged in it. One query carries a search for each count, so it costs one point for any number of repositories.
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 CommitActivity ¶ added in v0.165.0
CommitActivity is the commits on the default branches of an owner's repositories for each day. Fallback says the commit search was rate limited and the counts come from the activityRepos most recently pushed repositories. Partial says the counts are a lower bound: a search timed out before it searched everything, or more repositories than those were pushed since the first day.
type CompareCommit ¶ added in v0.165.0
CompareCommit is one commit of a comparison. Parent is its first parent.
type DashCheck ¶ added in v0.163.0
type DashCheck struct {
Kind string // "check_run" | "status"
Name string
State string
Conclusion string
Description string
URL string
}
DashCheck is one CI check of a PR head: a check run or a commit status. State and Conclusion are GitHub's raw values: a check run has a status (QUEUED, IN_PROGRESS, COMPLETED) and a conclusion, a status context has only a state.
type DashIssue ¶ added in v0.163.0
type DashIssue struct {
Number int
Title string
URL string
Repo string
Author string
UpdatedAt time.Time
Assignees int
LinkedPRs []DashLinkedPR
}
DashIssue is one issue with the fields the dashboard needs.
type DashIssueList ¶ added in v0.163.0
DashIssueList is one issue block, as DashPRList.
type DashLinkedPR ¶ added in v0.163.0
DashLinkedPR is a pull request that references an issue.
type DashPR ¶ added in v0.163.0
type DashPR struct {
Number int
Title string
URL string
Repo string // owner/name
Author string
Draft bool
State string // OPEN | CLOSED | MERGED
HeadRef string
HeadOID string
BaseRef string
BaseOID string
MergeOID string // the merge, squash, or rebase commit; "" until the PR is merged
CrossRepo bool
ReviewDecision string // "" when the repository sets no review rule
UpdatedAt time.Time
Rollup string // statusCheckRollup.state, "" when the head has no checks
Checks []DashCheck
ChecksTotal int
ClosingIssues []int
ReviewStatus *DashCheck // the status named by DashQuery.ReviewContext; nil when unset or absent
}
DashPR is one pull request with the fields the dashboard needs.
type DashPRList ¶ added in v0.163.0
DashPRList is one PR block: Total is GitHub's count and Items holds at most one page of it.
type DashQuery ¶ added in v0.163.0
type DashQuery struct {
MyPRs string
ReviewPRs string
Assigned string
Mentioned string
Authored string
Owner string
Repo string
ReviewContext string
}
DashQuery holds the search strings of a dashboard read. Callers add the scope prefix (repo:, org:, user:). Owner and Repo, when set, add the repository block, which also lists the open issues with no assignee. ReviewContext, when set, reads that commit status of each PR head by name, so it is found even past the first page of checks.
type DashResult ¶ added in v0.163.0
type DashResult struct {
MyPRs DashPRList
ReviewPRs DashPRList
RepoOpen DashPRList
RepoMerged DashPRList
Assigned DashIssueList
Mentioned DashIssueList
Authored DashIssueList
Unassigned DashIssueList
RepoIssues int
HasRepo bool
PRErr error
IssueErr error
Notes []string
}
DashResult is one dashboard read. When only one of the two queries fails, PRErr or IssueErr holds why, and the other side's blocks are filled. Notes carry GraphQL errors that came with partial data.
type DayRange ¶ added in v0.165.0
DayRange is one day to count in: Start is its first instant and End its last. The caller picks the time zone.
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
Merged bool // a closed PR that was merged; State stays "closed"
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 OwnerUnreleased ¶ added in v0.165.0
type OwnerUnreleased struct {
Total int
Scanned int
Repos []RepoUnreleased
Notes []string
}
OwnerUnreleased is one read of an owner's repositories: Total is how many the owner has, Scanned how many were read (the newest push first), and Repos those of the read ones that have a tag.
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 PushedRepoPoller ¶ added in v0.148.0
type PushedRepoPoller struct {
Client *Client
Owner string
Limit int
// contains filtered or unexported fields
}
PushedRepoPoller lists one owner's repositories newest-push-first, one page per Poll. It remembers which endpoint answered and that endpoint's ETag, so a steady-state poll is a single conditional request.
type QueryTimeoutError ¶ added in v0.163.0
QueryTimeoutError reports a GraphQL query that GitHub did not finish in time (502/504) or that hit the caller's deadline. A large repository can push a heavy query past GitHub's limit, so it is reported apart from other failures instead of being retried with a smaller page.
func (*QueryTimeoutError) Error ¶ added in v0.163.0
func (e *QueryTimeoutError) Error() string
type RateLimitError ¶ added in v0.148.0
RateLimitError reports a primary or secondary rate-limit rejection. Reset is when GitHub says the caller may try again, so a long-running poller can sleep instead of failing.
func (*RateLimitError) Error ¶ added in v0.148.0
func (e *RateLimitError) Error() string
type Repo ¶
type Repo struct {
Owner string
Name string
Description string
UpdatedAt time.Time
PushedAt time.Time
Private bool
}
Repo is the subset of GitHub's repository JSON `gk clone`'s picker needs.
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 RepoUnreleased ¶ added in v0.165.0
type RepoUnreleased struct {
Repo string // owner/name
Tag string
Branches []TagComparison
}
RepoUnreleased is one repository with a tag: its latest tag by commit date, and the default branch and unreleasedBranch compared with it, the default branch first. A branch the repository does not have is left out.
type TagComparison ¶ added in v0.165.0
type TagComparison struct {
Branch string
Default bool // the repository's default branch
Ahead int
Behind int
Head string
Commits []CompareCommit
}
TagComparison is a branch compared with the latest tag: Ahead commits are on the branch and not in the tag, and Behind commits are in the tag and not on the branch. Behind is above 0 on unreleasedBranch after every release that leaves a commit on the default branch only, so it says that the tag is no release of this repository only when the default branch has it too. Commits holds the newest unreleasedWindow of the Ahead commits, the branch head last.
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"`
HeadBranch string `json:"head_branch"`
Event string `json:"event"`
CreatedAt time.Time `json:"created_at"`
}
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.