prwait

package
v8.176.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 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 prwait is the wait engine behind `devctl pr wait` (and the merge that follows it): one bounded, blocking call that returns when a pull request's head is green, red, or cannot become green as it is.

Green is the merge box's view, not `gh pr checks`': every check run and commit status of the head (every run of a check name, the latest status per context), every CircleCI workflow of the head revision (the newest run per name, read from CircleCI because a job behind `requires:` has posted nothing yet), no GitHub Actions run of the head still queued, running or awaiting approval, and every required status context reported. A pending check of another app, or a pending status of another CI than CircleCI, the base does not require is not waited for, as the merge box does not wait for it: Result.Blocking names it, and a review the base requires that is missing. Closed, conflicting and behind-a-strict-base end the wait before it starts. Drafts wait for CI like other open pull requests.

Index

Constants

View Source
const (
	SourceActions  = "actions"
	SourceCircleCI = "circleci"
)

The sources of a failed job.

View Source
const (
	// MinInterval is the shortest a poll waits, however large the budget.
	MinInterval = 15 * time.Second
	// MaxInterval is the longest a poll waits, however small the budget.
	MaxInterval = 60 * time.Second
)

The bounds of the poll interval at scale 1.

View Source
const (
	SourceCheckRun         = "check_run"
	SourceStatus           = "status"
	SourceCircleCIWorkflow = "circleci_workflow"
)

The check sources of the document.

View Source
const ChecksViaGraphQL = "graphql"

ChecksViaGraphQL is Result.ChecksVia when the head's checks were read through GraphQL's statusCheckRollup.

View Source
const CircleCIConfigPath = ".circleci/config.yml"

CircleCIConfigPath is the file whose presence at the head makes CircleCI part of the verdict.

View Source
const Command = "pr wait"

Command is the command a wait's document names.

View Source
const CommitCommand = "commit wait"

CommitCommand is the command a commit's wait's document names.

View Source
const DefaultFailedLogLines = 50

DefaultFailedLogLines is how much of a failed job's log --failed-log keeps.

View Source
const DefaultTimeout = 60 * time.Minute

DefaultTimeout bounds a wait whose caller names none.

View Source
const FullFailedLogLines = -1

FullFailedLogLines keeps the full log, including Actions post-job cleanup. Zero remains the disabled value in wait configurations.

View Source
const NoChecksGrace = 2 * time.Minute

NoChecksGrace is how long a head may carry no check run, no status and no Actions run while the repository has workflows a pull_request event runs: the time GitHub takes to deliver the event and register their runs. It is measured from the pull request's last update, which a push to its head is.

View Source
const RegistrationGrace = time.Minute

RegistrationGrace is how long after the pull request's last update, which a push to its head and the merge commit --update-branch creates are, the head's workflows may still be registering their runs: GitHub delivers the event and creates the runs seconds after the push. Within it no verdict rests on what has not registered yet: a required context still absent is pending, not never reported, and a head without any GitHub Actions run or check run of its own is pending, not green.

View Source
const RunSettleGrace = 5 * time.Minute

RunSettleGrace is how long a GitHub Actions run may read in progress after its last listed job completed before the wait counts it finished. GitHub completes a run seconds after its last job, and starts a job behind needs: seconds after the jobs it needs; it has left a run in progress for an hour after its only job succeeded.

Variables

This section is empty.

Functions

func IsFork added in v8.82.0

func IsFork(pr *github.PullRequest) bool

IsFork says whether the head lives in another repository than the base.

func LatestWorkflowRuns added in v8.175.0

func LatestWorkflowRuns(runs []*github.WorkflowRun) []*github.WorkflowRun

LatestWorkflowRuns keeps one run per workflow, the one with the highest id: a run for the same head created later (a title check run again after the retitle) replaces the stale one. Two workflows that share a name are kept apart by their workflow id.

func LogHeadTail added in v8.164.0

func LogHeadTail(output string, n int) (head, tail string)

LogHeadTail returns the first and last n lines of output, without terminal control sequences or control characters except tab and line breaks. The excerpts overlap for short output. A nonpositive n returns empty excerpts.

func NotApplicable added in v8.82.0

func NotApplicable(pr *github.PullRequest) error

NotApplicable is the gate for pr merge before and after its wait: exit 3 for a draft, closed, merged, conflicting or behind pull request, nil otherwise. Wait applies the same gate but allows drafts to wait for CI.

func PrintFailedJobs added in v8.107.0

func PrintFailedJobs(w io.Writer, jobs []FailedJob)

PrintFailedJobs writes the requested log of each failed job to w.

Types

type AcceptedRed added in v8.131.0

type AcceptedRed struct {
	Name string `json:"name"`
	// Source is check_run, status or circleci_workflow.
	Source     string `json:"source"`
	Conclusion string `json:"conclusion"`
	// URL is the run, the status's target or the workflow.
	URL string `json:"url"`
}

AcceptedRed is a failed check, status or CircleCI workflow the caller named with --accept-red: recorded instead of making the verdict red.

type ActionRun

type ActionRun struct {
	Name       string `json:"name"`
	RunID      int64  `json:"runId"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion"`
	URL        string `json:"url"`
	// JobsCompleted: the run still reads in progress while every job of it
	// the head lists has completed, the last one RunSettleGrace ago or longer;
	// it no longer keeps the head waiting, its jobs are its verdict.
	JobsCompleted bool `json:"jobsCompleted,omitempty"`
}

ActionRun is the latest GitHub Actions run of one workflow for the head.

type Check

type Check struct {
	Name string `json:"name"`
	// ID is the check run's id, the job id of a GitHub Actions job; absent
	// for a status.
	ID int64 `json:"id,omitempty"`
	// Workflow is the GitHub Actions run the check run's job belongs to, when
	// the head's runs list it.
	Workflow string `json:"workflow,omitempty"`
	Source   string `json:"source"`
	// Status is queued, in_progress or completed for a check run; pending or
	// completed for a status.
	Status string `json:"status"`
	// Conclusion is the check run's conclusion or the status's state once it
	// is not pending; empty while unfinished.
	Conclusion string `json:"conclusion"`
	URL        string `json:"url"`
	// Required: branch protection or a ruleset of the base names this context.
	Required bool `json:"required"`
}

Check is one check of the head as the merge box lists it: a check run or a commit status (the latest of that context). Every run of a check name counts: the jobs of a matrix, or of several workflows calling one reusable workflow, report under one name, and each is listed with its own ID. Of one workflow run several times for the head (a title check after a retitle), the newest run's jobs count.

type CircleCI

type CircleCI struct {
	PipelineID     string     `json:"pipelineId"`
	PipelineNumber int64      `json:"pipelineNumber"`
	Workflows      []Workflow `json:"workflows"`
	// SetupHalted: setup succeeded without a continuation for
	// setupHaltGrace, and its jobs posted their own successful contexts.
	SetupHalted bool `json:"setupHalted,omitempty"`
}

CircleCI is the newest pipeline of the head revision and its workflows, the newest run per workflow name.

type CircleCIJobs added in v8.139.0

type CircleCIJobs interface {
	ListWorkflowJobs(ctx context.Context, workflowID string) ([]circleciclient.Job, error)
	FailedStepsOutput(ctx context.Context, org, repo string, number int64) (string, error)
}

CircleCIJobs lists the jobs of a CircleCI workflow and reads the output of a job's failed steps.

type CommitDocument added in v8.174.0

type CommitDocument struct {
	Document
	// Number and BaseRef hide the Result's fields of the same names:
	// encoding/json takes the shallower field of a name, and leaves these
	// empty ones out.
	Number  int    `json:"number,omitempty"`
	BaseRef string `json:"baseRef,omitempty"`
}

CommitDocument is the JSON of a commit's wait: a Document without the pull request's number and base, which a commit has none of.

func NewCommitDocument added in v8.174.0

func NewCommitDocument(now time.Time) CommitDocument

NewCommitDocument is the document of a commit's wait started at now.

type Commits added in v8.174.0

type Commits interface {
	// Repository is the repository: its default branch, and whether it is
	// a template.
	Repository(ctx context.Context, owner, repo string) (*github.Repository, error)
	// BranchHead is the commit at the head of branch and its committer
	// date.
	BranchHead(ctx context.Context, owner, repo, branch string) (string, time.Time, error)
	// CommitTime is the committer date of the commit sha.
	CommitTime(ctx context.Context, owner, repo, sha string) (time.Time, error)
}

Commits are what a commit's wait reads besides GitHub: *githubclient.Client is one.

type Config

type Config struct {
	// GitHub is required. From [githubclient.NewConditional] its polls are
	// conditional requests and Rate is the [githubclient.Conditional].
	GitHub GitHub
	// Rate is where the poll interval comes from; nil polls at the floor.
	Rate RateSource
	// CircleCI returns the client once the head is known to carry a CircleCI
	// configuration; it is the place the CircleCI token is required, so an
	// [agentcli.ExitCoder] it returns ends the wait with that code, and
	// [circleciclient.ErrFromStatuses] judges the head's CircleCI jobs from
	// their commit statuses, as CircleCIFromStatuses does, with a warning.
	// nil means CircleCI is never consulted.
	CircleCI func(ctx context.Context) (*circleciclient.Client, error)
	// CircleCIFromStatuses, without CircleCI, reads CircleCI through the
	// commit statuses it posts to GitHub alone: the jobs the head's
	// CircleCIConfigPath runs on its branch are listed from the
	// configuration, and one that has posted no status yet, a job behind
	// requires: whose required jobs still run, keeps the head pending.
	CircleCIFromStatuses bool
	// Entries is read only for a template repository whose head carries
	// CircleCIConfigPath: GitHub alone judges it while its entry declares
	// gen.ci.templateContent. nil means no repository declares it.
	Entries EntryFinder
	// Commits are required by WaitCommit alone.
	Commits Commits
	// Clock defaults to the wall clock at scale 1.
	Clock agentcli.Clock
	// Progress may be nil.
	Progress *agentcli.Progress
	// Timeout defaults to DefaultTimeout. With SinglePoll it bounds the one
	// evaluation's reads instead, and zero leaves that to the caller's
	// context.
	Timeout time.Duration
	// SinglePoll answers after one evaluation of the head: its verdict, or
	// [agentcli.VerdictPending] (exit 2) while it is undecided or could not
	// be read this time, instead of polling until the timeout. It is the
	// observation a caller polls itself (devctl serve's waits with timeout
	// 0s).
	SinglePoll bool
	// FailedLogLines, when positive, makes a red verdict read the log of
	// each failed job once and keep that many of its last lines in
	// Result.FailedJobs. A green or pending head reads no log.
	// FullFailedLogLines keeps the full log; zero reads no log.
	FailedLogLines int
	// AcceptRed are check names whose failure does not make the verdict
	// red: a failed check run, status or CircleCI workflow of one of these
	// names is recorded in Result.AcceptedRed with a warning instead. A
	// name the base requires is never accepted, and a green head that
	// carries no check of a name is exit 3. Refusing a required name or a
	// security scan before the wait is the caller's (pkg/prmerge).
	AcceptRed []string
}

Config configures a Waiter.

type Document added in v8.150.0

type Document struct {
	agentcli.Envelope
	*Result
	// Identity is who acted on GitHub: "app", a GitHub App's user token (the
	// devctl App login on a laptop, the person's token on the server), or
	// "gh", the person's own gh login for an owner the App is not installed
	// on; empty when the run ended before choosing.
	Identity string `json:"identity"`
}

Document is the JSON of a wait: the envelope and the wait's result.

func NewDocument added in v8.150.0

func NewDocument(now time.Time) Document

NewDocument is the document of a wait started at now.

func (*Document) Take added in v8.150.0

func (d *Document) Take(result *Result)

Take puts a wait's result into the document, its warnings into the envelope.

type EntryFinder added in v8.127.1

type EntryFinder interface {
	FindEntry(ctx context.Context, owner, repo string) (*reposetup.Fields, bool, error)
}

EntryFinder finds a repository's declaration in the team files; found false when no team file declares it.

type FailedJob added in v8.107.0

type FailedJob struct {
	Name string `json:"name"`
	// Source is actions or circleci.
	Source string `json:"source"`
	URL    string `json:"url"`
	// LogTail is the requested tail or full log; on CircleCI, the output of
	// failed steps only. A tail starts with the lines from the log's first
	// failure when that failure lies before it.
	LogTail string `json:"logTail,omitempty"`
	// LogError says why the log could not be read; the verdict stands.
	LogError string `json:"logError,omitempty"`
}

FailedJob is one failed job of a red head and the end of its log.

func (FailedJob) MarshalJSON added in v8.139.0

func (j FailedJob) MarshalJSON() ([]byte, error)

MarshalJSON writes the job with its name, URL and log error without control sequences, as its log tail already is: CI sets them.

type FailedLog added in v8.107.0

type FailedLog struct {
	Enabled bool
	Lines   int
}

FailedLog is the --failed-log flag pair of the commands that wait.

func (*FailedLog) Init added in v8.107.0

func (f *FailedLog) Init(cmd *cobra.Command)

Init registers --failed-log and --failed-log-lines on cmd.

func (FailedLog) TailLines added in v8.107.0

func (f FailedLog) TailLines() (int, error)

TailLines is the Config.FailedLogLines the flags ask for: 0 without --failed-log, FullFailedLogLines for --failed-log-lines 0.

type GitHub added in v8.150.0

type GitHub interface {
	JobLogs
	PullRequest(ctx context.Context, owner, repo string, number int) (*github.PullRequest, error)
	ReviewDecision(ctx context.Context, owner, repo string, number int) (string, error)
	RequiredStatusContexts(ctx context.Context, owner, repo, branch string) ([]string, error)
	WorkflowRunsForSHA(ctx context.Context, owner, repo, sha string) ([]*github.WorkflowRun, error)
	CheckRollup(ctx context.Context, owner, repo, sha string) ([]*github.CheckRun, []*github.RepoStatus, error)
	CheckRunsForRef(ctx context.Context, owner, repo, ref string) ([]*github.CheckRun, error)
	CommitStatuses(ctx context.Context, owner, repo, ref string) ([]*github.RepoStatus, error)
	FileExists(ctx context.Context, owner, repo, path, ref string) (bool, error)
	CommitMessage(ctx context.Context, owner, repo, sha string) (string, error)
	ListDirectory(ctx context.Context, owner, repo, path, ref string) ([]string, error)
	InactiveWorkflowPaths(ctx context.Context, owner, repo string) (map[string]bool, error)
	ReadFile(ctx context.Context, owner, repo, path, ref string) ([]byte, bool, error)
}

GitHub is what the wait reads from GitHub; *githubclient.Client is one.

type JobLogs added in v8.139.0

type JobLogs interface {
	JobLog(ctx context.Context, owner, repo string, jobID int64) (io.ReadCloser, error)
}

JobLogs reads the log of a GitHub Actions job.

type LogReader added in v8.139.0

type LogReader struct {
	GitHub JobLogs
	// Lines is how many of a log's last lines a job keeps, or
	// FullFailedLogLines to keep the full log.
	Lines int
}

LogReader reads the requested lines of failed jobs' logs for the commands that wait with --failed-log: GitHub Actions job logs and the output of CircleCI's failed steps, without terminal control sequences or control characters but tab. A log that cannot be read is named in the job's LogError.

func (LogReader) ActionsJob added in v8.139.0

func (r LogReader) ActionsJob(ctx context.Context, owner, repo string, id int64, name, url string) FailedJob

ActionsJob is the failed GitHub Actions job id with the requested log; a tail ends at the last failed step's error; a full log includes cleanup.

func (LogReader) CircleCIJob added in v8.139.0

func (r LogReader) CircleCIJob(ctx context.Context, owner, repo string, client CircleCIJobs, number int64, name, url string) FailedJob

CircleCIJob is the failed CircleCI job number with the tail of its failed steps' output.

func (LogReader) CircleCIWorkflow added in v8.139.0

func (r LogReader) CircleCIWorkflow(ctx context.Context, owner, repo string, client CircleCIJobs, id, name, url string) []FailedJob

CircleCIWorkflow is every failed job of the failed CircleCI workflow id, named workflow/job, with the tail of its failed steps' output; the workflow itself when its jobs cannot be listed.

type RateSource

type RateSource interface {
	Rate() githubclient.RateLimit
}

RateSource reports the GitHub rate limit the newest response carried.

type Result

type Result struct {
	Repository string `json:"repository"`
	// Number and BaseRef are the pull request's; a [CommitDocument] leaves
	// them out.
	Number  int    `json:"number"`
	HeadSHA string `json:"headSha"`
	BaseRef string `json:"baseRef"`
	// Ref is the branch a commit's wait judges the commit on; absent for a
	// pull request's.
	Ref string `json:"ref,omitempty"`
	// Draft is true when the pull request was a draft at the latest poll. A green
	// draft has passed CI but still cannot be merged by pr merge.
	Draft bool `json:"draft,omitempty"`
	// Checks are the head's check runs, every run of a name that counts, and
	// its statuses, the latest per context.
	Checks []Check `json:"checks"`
	// ChecksVia is ChecksViaGraphQL when the last poll read Checks through
	// GraphQL because REST's check endpoints went unanswered; absent when REST
	// answered.
	ChecksVia string `json:"checksVia,omitempty"`
	// CircleCI is absent when the head carries no CircleCI configuration, the
	// repository is a template whose entry declares that configuration as
	// template content, or CircleCI has no project or listed pipeline for it.
	CircleCI *CircleCI `json:"circleci,omitempty"`
	// Actions are the head's GitHub Actions runs, the latest per workflow.
	Actions []ActionRun `json:"actions"`
	// Unfinished names what the head was still waiting for when the wait
	// ended without a verdict.
	Unfinished []string `json:"unfinished,omitempty"`
	// FailedJobs are the failed jobs of a red head with the tails of their
	// logs, read with Config.FailedLogLines.
	FailedJobs []FailedJob `json:"failedJobs,omitempty"`
	// AcceptedRed are the failed checks the caller accepted with
	// Config.AcceptRed, each with its run's URL.
	AcceptedRed []AcceptedRed `json:"acceptedRed,omitempty"`
	// Blocking names what keeps GitHub's merge box from merging a green
	// head: a check or status the base does not require that is still
	// pending, which the wait does not wait for, and a review the base
	// requires that is missing or asks for changes.
	Blocking []string `json:"blocking,omitempty"`
	// Warnings are for the envelope: a head that changed under the wait, a
	// template repository, a CircleCI project that does not exist or lists no pipeline.
	Warnings []string `json:"-"`
}

Result is the command's part of the document.

type Waiter

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

Waiter runs waits.

func New

func New(config Config) (*Waiter, error)

New returns a Waiter for config.

func (*Waiter) Wait

func (w *Waiter) Wait(ctx context.Context, owner, repo string, number int) (*Result, error)

Wait blocks until owner/repo#number is green (nil), red or otherwise decided (an *agentcli.ExitError with the code of the table), or the timeout passes (exit 2). A required context absent from a head whose checks, runs and workflows have all finished is exit 4 at that poll, before the timeout, once the pull request's last update is RegistrationGrace old, and so is a head that waits only for Actions runs awaiting a member's approval; while anything else is still pending, the timeout is 2 whatever is absent. A failure the base does not require is red once the required contexts have finished. The Result is always returned, as far as it was filled; a tooling failure is any other error. With Config.SinglePoll it answers after one evaluation: its verdict, or agentcli.VerdictPending.

func (*Waiter) WaitCommit added in v8.174.0

func (w *Waiter) WaitCommit(ctx context.Context, owner, repo, ref, sha string) (*Result, error)

WaitCommit is Wait for a commit without a pull request: the head of branch ref, or the commit sha when it is set, judged on ref (the repository's default branch when ref is empty). It applies Wait's rules with no required context, as nothing guards a commit that is already on its branch: every check run, status, Actions run and CircleCI job of the commit finishes without failing. The registration grace counts from the commit's committer date. A head of ref that moves under the wait is followed, as Wait follows a pull request's head; a commit named by sha never moves. Config.Commits is required.

type Workflow

type Workflow struct {
	Name   string `json:"name"`
	Status string `json:"status"`
	URL    string `json:"url"`
}

Workflow is one CircleCI workflow of the pipeline.

Directories

Path Synopsis
Package prwaittest is an in-process test double of what a pull request wait reads from GitHub: a prwait.GitHub answering from state a test sets, one head state per poll.
Package prwaittest is an in-process test double of what a pull request wait reads from GitHub: a prwait.GitHub answering from state a test sets, one head state per poll.

Jump to

Keyboard shortcuts

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