github

package
v0.164.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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.

View Source
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.

View Source
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.

View Source
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

func EventIDLess(a, b string) bool

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:

  1. GH_TOKEN / GITHUB_TOKEN env vars — the same names `gh`, GitHub Actions, and most other GitHub tooling read.
  2. 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

func (c *Client) Dashboard(ctx context.Context, q DashQuery) (*DashResult, error)

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

func (c *Client) ListMyOrgs(ctx context.Context) ([]string, error)

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

func (c *Client) ListRepos(ctx context.Context, owner string) ([]Repo, error)

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) OwnerType

func (c *Client) OwnerType(ctx context.Context, owner string) (string, error)

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

func (c *Client) SearchCount(ctx context.Context, query string) (int, error)

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

func (c *Client) SearchIssues(ctx context.Context, query, sort string, limit int) ([]Issue, error)

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.

func (*Client) ViewerLogin

func (c *Client) ViewerLogin(ctx context.Context) string

ViewerLogin returns the login of the token's owner, or "" when unauthenticated (or the lookup failed). Memoized for the client's lifetime.

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

type DashIssueList struct {
	Total int
	Items []DashIssue
}

DashIssueList is one issue block, as DashPRList.

type DashLinkedPR added in v0.163.0

type DashLinkedPR struct {
	Number int
	State  string
	Merged bool
}

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
	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

type DashPRList struct {
	Total int
	Items []DashPR
}

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
	Unassigned    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 and the Unassigned search. 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 HTTPDoer

type HTTPDoer interface {
	Do(*http.Request) (*http.Response, error)
}

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

type NewPullRequest struct {
	Title string
	Body  string
	Head  string
	Base  string
	Draft bool
}

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

type PullRequest struct {
	Number int
	Title  string
	URL    string
	State  string
	Draft  bool
}

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.

func (*PushedRepoPoller) Poll added in v0.148.0

func (p *PushedRepoPoller) Poll(ctx context.Context) (repos []Repo, changed bool, err error)

Poll returns the newest-pushed repositories. changed is false when GitHub answered 304 and repos is the previous result.

type QueryTimeoutError added in v0.163.0

type QueryTimeoutError struct {
	Query  string
	Status string
}

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

type RateLimitError struct {
	Status string
	Reset  time.Time
}

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 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL