gh

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 18 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 gh talks to GitHub: scale-set API, listener, and REST helpers.

Index

Constants

View Source
const DefaultRunnerGroupID = 1

DefaultRunnerGroupID is the id of the default runner group. Repo-level scale sets always use it.

View Source
const ResultCanceled = "canceled"

ResultCanceled is the result GitHub reports for a reassigned job.

View Source
const ScopesUnknown = "unknown"

ScopesUnknown is returned by TokenScopes for tokens that do not report OAuth scopes (fine-grained PATs, app tokens).

Variables

View Source
var (
	// ErrRunnerBusy: deleting a runner that is running a job (HTTP 422).
	ErrRunnerBusy = errors.New("runner is busy")
	// ErrNotFound wraps HTTP 404.
	ErrNotFound = errors.New("not found")
	// ErrJobNotFound: no job with that name in the run.
	ErrJobNotFound = errors.New("job not found in run")
)

Typed REST errors.

View Source
var (
	ErrTokenPerms = errors.New("token file is group or world accessible")
	ErrTokenEmpty = errors.New("token file is empty")
)

Token errors.

View Source
var ErrUnknownScaleSet = errors.New("scale set id unknown; call Ensure first")

ErrUnknownScaleSet is returned when a key has no known scale-set id yet (Ensure has not run).

Functions

func Token

func Token(file string) (string, error)

Token reads a token file, trimming whitespace. It refuses files readable by group or others so a leaked mode never silently exposes the credential.

Types

type Events

type Events interface {
	Assigned(key core.ScaleSetKey, j core.Job)
	// Reassigned: GitHub cancelled an assigned job that had no runner
	// (result canceled, empty runner name). The job is assigned again every
	// ~5 minutes; it is not a completion.
	Reassigned(key core.ScaleSetKey, j core.Job)
	Started(key core.ScaleSetKey, j core.Job)
	Completed(key core.ScaleSetKey, j core.Job)
	Stats(key core.ScaleSetKey, s Stats)
}

Events receives scale-set events. Calls come from a single goroutine, in the order documented on Listener. Redelivery after errors or reconnects means every method must be idempotent.

type FileChange

type FileChange struct {
	Path    string
	Content []byte
}

FileChange is one file written by CommitFiles.

type Listener

type Listener struct {

	// Backoff bounds; zero values use defaults.
	MinBackoff, MaxBackoff time.Duration
	// ConflictBackoff is the minimum wait after a session conflict.
	ConflictBackoff time.Duration
	// contains filtered or unexported fields
}

Listener runs the scale-set long poll for one scale set.

Order of event delivery within one message (deterministic):

  1. Reassigned (canceled with no runner), in message order
  2. Assigned
  3. Started
  4. Completed (after Started: a short job's Started and Completed can share a message)
  5. Stats (initial session statistics arrive as a synthetic first message)

JobAvailable messages are ignored (the service never sends them for scale sets; jobs arrive as JobAssigned).

func (*Listener) Run

func (l *Listener) Run(ctx context.Context) error

Run polls until ctx is done, reconnecting with jittered exponential backoff after any error. A session conflict (another active session for the scale set) is logged and retried, never fatal. It returns ctx.Err() on shutdown.

func (*Listener) SetCapacity

func (l *Listener) SetCapacity(n int)

SetCapacity sets maxCapacity sent to the service on each poll (effective on the next poll, up to ~50s later). Safe for concurrent use.

type PR

type PR struct {
	Number  int
	URL     string
	Created bool
}

PR is an opened or reused pull request.

type PRState

type PRState struct {
	Number   int
	Merged   bool
	Closed   bool
	ClosedAt time.Time // merge or close time; zero while open
}

PRState is the lifecycle state of a pull request.

type REST

type REST struct {
	// contains filtered or unexported fields
}

REST is a thin, typed wrapper over the GitHub REST API.

func NewREST

func NewREST(token string, opts ...github.ClientOptionsFunc) (*REST, error)

NewREST builds a REST client. Extra options (for example github.WithURLs in tests) are applied after the token.

func (*REST) BranchExists

func (r *REST) BranchExists(ctx context.Context, owner, repo, branch string) (bool, error)

BranchExists reports whether a branch exists.

func (*REST) CancelRun

func (r *REST) CancelRun(ctx context.Context, owner, repo string, runID int64) error

CancelRun asks GitHub to cancel a run.

func (*REST) CommitFiles

func (r *REST) CommitFiles(ctx context.Context, owner, repo, branch, message string, files []FileChange) (sha string, changed bool, err error)

CommitFiles writes files to branch as ONE commit (git data API) and returns the commit SHA. If every file already matches the branch tip, nothing is committed and the tip SHA is returned with changed=false.

func (*REST) CreateBranch

func (r *REST) CreateBranch(ctx context.Context, owner, repo, branch, base string) (sha string, created bool, err error)

CreateBranch creates branch from the tip of base and returns the new tip SHA. If the branch already exists it is left alone and its tip is returned with created=false.

func (*REST) CreateRegistrationToken

func (r *REST) CreateRegistrationToken(ctx context.Context, t core.Target) (string, error)

CreateRegistrationToken returns a runner registration token for config.sh.

func (*REST) DefaultBranch

func (r *REST) DefaultBranch(ctx context.Context, owner, repo string) (string, error)

DefaultBranch returns a repository's default branch.

func (*REST) DeleteRunner

func (r *REST) DeleteRunner(ctx context.Context, t core.Target, id int64) error

DeleteRunner deregisters a runner. A busy runner yields ErrRunnerBusy; a runner that is already gone is not an error.

func (*REST) DispatchWorkflow

func (r *REST) DispatchWorkflow(ctx context.Context, owner, repo, file, ref string, inputs map[string]any) error

DispatchWorkflow triggers a workflow_dispatch run (smoke test).

func (*REST) FindVariable

func (r *REST) FindVariable(ctx context.Context, owner, repo, name string) (Variable, bool, error)

FindVariable looks a variable up the way a workflow does: repo first, then the owner's org. found=false when neither has it.

func (*REST) ForceCancelRun

func (r *REST) ForceCancelRun(ctx context.Context, owner, repo string, runID int64) error

ForceCancelRun force-cancels a run (use after CancelRun did not take).

func (*REST) GetFile

func (r *REST) GetFile(ctx context.Context, owner, repo, p, ref string) ([]byte, string, error)

GetFile returns a file's content and blob SHA at ref.

func (*REST) GetPRState

func (r *REST) GetPRState(ctx context.Context, owner, repo string, number int) (PRState, error)

GetPRState reports whether a PR is merged or closed.

func (*REST) GetRepo

func (r *REST) GetRepo(ctx context.Context, owner, repo string) (Repo, error)

GetRepo returns repository metadata (visibility, default branch).

func (*REST) GetRun

func (r *REST) GetRun(ctx context.Context, owner, repo string, runID int64) (Run, error)

GetRun fetches a workflow run.

func (*REST) ListOrgRepos

func (r *REST) ListOrgRepos(ctx context.Context, org string) ([]Repo, error)

ListOrgRepos lists every repository of an org (including archived).

func (*REST) ListOrgRunnerGroups

func (r *REST) ListOrgRunnerGroups(ctx context.Context, org string) ([]RunnerGroup, error)

ListOrgRunnerGroups lists an org's runner groups.

func (*REST) ListRunners

func (r *REST) ListRunners(ctx context.Context, t core.Target) ([]Runner, error)

ListRunners lists runners registered at a target (repo or org).

func (*REST) ListWorkflowFiles

func (r *REST) ListWorkflowFiles(ctx context.Context, owner, repo, ref string) ([]WorkflowFile, error)

ListWorkflowFiles lists .yml/.yaml files in .github/workflows at ref. A missing directory yields no files.

func (*REST) OpenPR

func (r *REST) OpenPR(ctx context.Context, owner, repo, head, base, title, body string) (PR, error)

OpenPR opens a PR from head into base, or returns the open one for head.

func (*REST) PRsForCommit

func (r *REST) PRsForCommit(ctx context.Context, owner, repo, sha, branch string) ([]PRState, error)

PRsForCommit lists PRs (open, closed or merged) whose head is sha and whose head branch is branch. A run's own pull_requests list is emptied once its PR merges, so stale-run checks use this instead.

func (*REST) RerunJob

func (r *REST) RerunJob(ctx context.Context, owner, repo string, runID int64, jobName string) error

RerunJob re-runs the job named jobName of run runID. The scale-set JobID is a GUID, so the numeric REST id is found by listing the run's jobs.

func (*REST) TagExists

func (r *REST) TagExists(ctx context.Context, owner, repo, tag string) (bool, error)

TagExists reports whether a tag exists.

func (*REST) TokenScopes

func (r *REST) TokenScopes(ctx context.Context) ([]string, error)

TokenScopes returns the OAuth scopes of the token (X-OAuth-Scopes). Tokens that do not report scopes (fine-grained PATs) yield []string{ScopesUnknown}.

func (*REST) UpdateVariable

func (r *REST) UpdateVariable(ctx context.Context, scope core.Target, name, value string) error

UpdateVariable sets a variable's value at its scope (repo or org).

type Repo

type Repo struct {
	Owner         string
	Name          string
	DefaultBranch string
	Archived      bool
	Private       bool
	Fork          bool
}

Repo is the subset of repository metadata needed for scanning.

type Run

type Run struct {
	ID         int64
	Event      string
	HeadBranch string
	HeadSHA    string
	PRs        []int
	Status     string
	Conclusion string
	CreatedAt  time.Time
}

Run is the subset of a workflow run the manager needs.

type Runner

type Runner struct {
	ID     int64
	Name   string
	OS     string
	Status string // online | offline
	Busy   bool
	Labels []string
}

Runner is a registered self-hosted runner.

type RunnerGroup

type RunnerGroup struct {
	ID      int64
	Name    string
	Default bool
}

RunnerGroup is an org runner group.

type ScaleSets

type ScaleSets struct {
	// contains filtered or unexported fields
}

ScaleSets manages the scale sets an instance owns. It keeps one scaleset client per target and remembers the id of every scale set it ensured.

func NewScaleSets

func NewScaleSets(token, version string) *ScaleSets

NewScaleSets returns a ScaleSets authenticating with a token (PAT or gh OAuth token).

func (*ScaleSets) Delete

func (s *ScaleSets) Delete(ctx context.Context, key core.ScaleSetKey) error

Delete removes the scale set Ensure returned for key.

func (*ScaleSets) DeleteByID

func (s *ScaleSets) DeleteByID(ctx context.Context, t core.Target, id int) error

DeleteByID removes a scale set by id (reconciler use; id from a state DB).

func (*ScaleSets) Ensure

func (s *ScaleSets) Ensure(ctx context.Context, key core.ScaleSetKey, name string, labels []string, runnerGroup string) (int, error)

Ensure gets or creates the scale set `name` for key, aligns its labels with labels (name is always included) and returns its id. Created scale sets set DisableUpdate so GitHub never self-updates our runners.

func (*ScaleSets) GenerateJIT

func (s *ScaleSets) GenerateJIT(ctx context.Context, key core.ScaleSetKey, runnerName string, workFolder ...string) (string, int, error)

GenerateJIT registers an ephemeral runner named runnerName and returns the encoded JIT config and the runner id. workFolder is optional (Windows VMs pass an absolute per-job folder); empty keeps the runner default `_work`.

func (*ScaleSets) ID

func (s *ScaleSets) ID(key core.ScaleSetKey) (int, bool)

ID returns the scale-set id remembered for key.

func (*ScaleSets) NewListener

func (s *ScaleSets) NewListener(key core.ScaleSetKey, events Events, log *slog.Logger, capacity int) (*Listener, error)

NewListener builds a Listener for key. Ensure must have run for key.

func (*ScaleSets) OpenSession

func (s *ScaleSets) OpenSession(ctx context.Context, key core.ScaleSetKey, owner string) (Session, error)

OpenSession opens a message session for key's scale set.

func (*ScaleSets) RemoveRunner

func (s *ScaleSets) RemoveRunner(ctx context.Context, key core.ScaleSetKey, runnerID int) error

RemoveRunner deregisters a runner by id. A missing runner is not an error.

type Session

type Session interface {
	listener.Client
	Close(ctx context.Context) error
}

Session is a scale-set message session.

type Stats

type Stats struct {
	Assigned   int // jobs assigned (running + assigned-unstarted)
	Running    int
	Registered int // registered runners
	Busy       int
	Idle       int
}

Stats is the scale-set service's view of a scale set.

type Variable

type Variable struct {
	Name  string
	Value string
	Scope core.Target
}

Variable is an Actions variable and where it was found.

type WorkflowFile

type WorkflowFile struct {
	Path string
	SHA  string
}

WorkflowFile is a workflow file on a ref.

Jump to

Keyboard shortcuts

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