github

package module
v0.0.0-...-d9e739a Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 9 Imported by: 2 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.

README

Shared GitHub library

This Go module gives existing tools one implementation of verified PR publication, comments and guarded Prow maintenance. It is a library, not another CLI.

The root github package handles GitHub identity, complete evidence reads, publication and comment receipts. The prow package handles bot-hold release, retest commands and observing whether Prow acted on them.

Using the library

Existing Go commands import github.com/Azure/ARO-HCP/tooling/github and github.com/Azure/ARO-HCP/tooling/github/prow. For example, a caller with an already pushed branch can publish its complete PublicationRequest:

import (
    "context"

    automation "github.com/Azure/ARO-HCP/tooling/github"
    gh "github.com/google/go-github/v69/github"
)

func publish(ctx context.Context, repository, bot, token string, request automation.PublicationRequest) (automation.Receipt, error) {
    api := gh.NewClient(nil).WithAuthToken(token)
    client, err := automation.NewClient(repository, api)
    if err != nil {
        return automation.Receipt{}, err
    }
    client, err = client.WithActor(bot)
    if err != nil {
        return automation.Receipt{}, err
    }
    return client.Publish(ctx, request)
}

WithActor takes a trusted bot login from caller configuration. This supports installation tokens without asking GitHub's user-token-only /user endpoint to identify an App. Use WithWriter before WithActor when read and write clients have separate credentials.

Use WithCIReader when checks and commit statuses require a separate read token. PR metadata and hold history continue to use the ordinary read client, and WithWriter controls only mutation credentials.

PublicationRequest contains the source repository and branch, expected source and base SHAs, target branch, trusted actor, exact ownership marker, title, body and complete expected changed-file set. The marker must be a standalone line in the body. A returned receipt identifies the verified PR and observed head.

For a numbered update, supply ExpectedNumber, ExpectedTitle and ExpectedBody from the authorized PR. If the PR is missing, closed, replaced or its text has changed, publication stops without creating or editing a PR. GitHub does not provide an atomic conditional edit, so the final check is a read before the write. Publication requests must contain fewer than MaxPublicationFiles (3,000) changed paths.

When a caller has separately verified an existing PR's old ownership metadata, PreviousMarker permits replacing that exact marker. The write and its read-back must contain the new Marker, not the previous one.

Caller responsibilities

Callers supply an authenticated go-github/v69 client. The library does not read tokens from environment variables, mint App tokens or expand permissions.

Callers also own candidate validation, local commits, branch preparation, schedules and domain-specific eligibility decisions. Publication uses an already prepared remote branch at an expected commit; it never stages a dirty checkout or force pushes. New PRs default to drafts. Set PublicationRequest.ReadyForReview only when the caller's publication policy permits a ready PR; ARO-HCP's aro-hcp-robot[bot] policy requires that setting. Other automation needs explicit human authorization. Updating a PR always preserves its existing readiness.

Prow callers supply trusted actors, required checks and a budget namespace. A new library must not give dependency maintenance, security remediation or workflow recovery a shared or larger retry allowance. Artifact diagnosis and the decision that a failure is safe to retry remain with the calling tool.

Safety boundaries

  • Match PRs by ownership, repository, branches and a stable marker, never title alone.
  • Reject ambiguous ownership, incomplete evidence and unexpected heads.
  • Verify a write by reading its result and return an explicit receipt.
  • Do not blindly repeat a mutation after a timeout or uncertain response.
  • Treat a posted Prow comment as a request, not proof that a hold was removed or a new build started.
  • GitHub comments have no atomic expected-head precondition. Head checks reduce races but cannot provide compare-and-swap or exactly-once execution.
  • Do not cancel human or unexplained holds or provide approval and merge bypasses.

depctl dependabot native publish uses this library for replacement PR publication. Other consumers can adopt it through their existing Go commands without introducing a helper executable.

Prow maintenance

Construct prow.New(client, config) with the target repository, trusted writer, retry bots, hold controllers, required checks and a distinct budget namespace. ReleaseHold accepts only proven bot retry-exhaustion holds whose revision belongs to the PR's commits and whose current required CI is positive. Optional check conclusions do not gate maintenance; missing, pending, neutral or skipped required checks still block. Retest requires a current required-check failure, a distinct same-job comparison URL and a plain-text reason. The caller verifies comparison artifacts and diagnosis; the library validates URL syntax and association, not the comparison run's existence or outcome.

Named requests identify the canonical job from Prow evidence. Trusted caller configuration supplies Config.JobTriggers, a canonical-job-to-alias map with unique aliases, for example pull-ci-Azure-ARO-HCP-main-api-validation to api-validation. Named requests without a mapping are rejected. The library never guesses aliases by stripping prefixes, falls back to canonical names or accepts arbitrary command text. Required-set requests use /retest-required.

Publication supports forks and defaults to draft creation, but Prow maintenance deliberately accepts only open, non-draft PRs whose head repository is the target repository. Publishing a PR does not automatically make it eligible for Prow maintenance; draft and fork consumers must retain that boundary.

A root PostComment receipt with observed means only that the comment was read back successfully. Prow converts that acknowledgement to requested. Pass the intact result to Observe with a context deadline to verify label removal or a new current-head run of a currently eligible job. Historical runs form the already-seen baseline, not additional observation targets. Observation does not prove that this comment caused the run or that the run passed. indeterminate requires reconciliation, not blind retries.

Each action collects one complete eligibility snapshot. Observation reads only PR state for hold release, or head-bound statuses/checks with PR identity bookends for retests; it does not repeatedly fetch comments, commits and label history.

Retest comments retain a bounded, versioned record of their original targets and already-seen runs. Calling Retest again reconciles the existing request without posting another comment and restores that observation baseline, so a targeted run that started before a process restart can still be observed. Edited or malformed records fail closed. Older comments without baseline metadata retain their consumed budget but cannot prove that a run already started before resumption.

When adopting this API, a consumer must reconcile its existing recovery markers and cooldown rules before enabling writes. A new namespace is not permission to reset an existing retry budget.

Tests

GOWORK=off go test -race ./...

Tests use local HTTP fixtures and injected evidence. They do not need GitHub credentials or send mutations to a real repository.

Documentation

Overview

Package github provides verified GitHub publication and comment operations for existing Go tools. Clients and credentials are supplied by the caller; the package does not run candidate code or grant publication authority. Prow-specific maintenance operations live in the prow subpackage.

Index

Constants

View Source
const MaxPublicationFiles = 3000

MaxPublicationFiles is the exclusive changed-file limit for publications whose complete file inventory must be verifiable.

Variables

View Source
var ErrConflict = errors.New("remote state conflicts with expectation")

ErrConflict reports a failed remote precondition.

View Source
var ErrEvidenceIncomplete = errors.New("remote evidence is incomplete")

ErrEvidenceIncomplete reports missing or ambiguous remote evidence.

View Source
var ErrIndeterminate = errors.New("remote write result is indeterminate")

ErrIndeterminate reports a write whose result could not be verified; callers must reconcile, not blindly retry.

Functions

func CommentMarker

func CommentMarker(key, head string) string

CommentMarker identifies an idempotency key on exactly one commit; invalid inputs return an empty marker.

Types

type Check

type Check struct {
	ID         int    `json:"id"`
	Name       string `json:"name"`
	HeadSHA    string `json:"headSHA"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion"`
	DetailsURL string `json:"detailsURL"`
}

Check is one check run.

type Client

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

Client accesses one repository through caller-authenticated clients.

func NewClient

func NewClient(repository string, api *gh.Client) (*Client, error)

NewClient constructs a client without reading credentials or changing authentication.

func (*Client) Actor

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

Actor returns the explicitly trusted writer identity, or discovers a user-token identity. App installation tokens should use WithActor because GitHub does not support /user for them.

func (*Client) BaseContains

func (c *Client) BaseContains(ctx context.Context, base, commit string) error

BaseContains fails when commit is not part of base, so a stale or foreign checkout can never publish a diff computed against an unrelated branch.

func (*Client) CI

func (c *Client) CI(ctx context.Context, head string) (CommitCI, error)

CI reads every status and latest-check page for a full commit SHA without collecting PR history.

func (*Client) OpenProposals

func (c *Client) OpenProposals(ctx context.Context, actor, marker, branchPrefix string) ([]int, error)

OpenProposals reports the numbers of open pull requests authored by actor that carry marker or whose head branch starts with branchPrefix. A run uses it to stop before doing expensive work while its own proposal is still pending.

func (*Client) OpenPullRequests

func (c *Client) OpenPullRequests(ctx context.Context) ([]PullRequest, error)

OpenPullRequests reads the complete open pull request inventory, rejecting pages that could hide an entry or describe a foreign target.

func (*Client) PostComment

func (c *Client) PostComment(ctx context.Context, number int, expectedHead, key, body string) (Receipt, error)

PostComment posts once after a complete trusted-author deduplication read and verifies the returned comment by ID. Fresh reads require the pull to remain open, unmerged, and bound to its original author, repositories, refs, and head. A failed write or readback is indeterminate: callers must reconcile before attempting another write. GitHub provides no atomic state- or head-conditioned comment write; a change first observed after writing is indeterminate.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, r PublicationRequest) (Receipt, error)

Publish finds, creates or updates exactly one owned proposal and verifies all remote evidence. Write failures are indeterminate, never automatically retried. Concurrent publishers require external serialization. GitHub cannot atomically condition PR metadata writes on the head or current text.

func (*Client) PullRequest

func (c *Client) PullRequest(ctx context.Context, number int) (PullRequest, error)

PullRequest reads complete identity metadata for one positive pull-request number.

func (*Client) Snapshot

func (c *Client) Snapshot(ctx context.Context, number int, expectedHead string) (Snapshot, error)

Snapshot collects every evidence page, retains commit attribution and rechecks identity after collection.

func (*Client) WithActor

func (c *Client) WithActor(actor string) (*Client, error)

WithActor returns an independent client bound to a trusted expected writer login, including App bot logins. The caller must obtain this identity from trusted configuration, not untrusted proposal metadata.

func (*Client) WithCIReader

func (c *Client) WithCIReader(reader *gh.Client) (*Client, error)

WithCIReader returns an independent client with a separate credential for CI evidence.

func (*Client) WithWriter

func (c *Client) WithWriter(writer *gh.Client) (*Client, error)

WithWriter returns an independent client using an explicit write credential and clears any configured actor.

type Comment

type Comment struct {
	ID        int    `json:"id"`
	Author    string `json:"author"`
	Body      string `json:"body"`
	CreatedAt string `json:"createdAt"`
	UpdatedAt string `json:"updatedAt"`
}

Comment is one issue comment.

type CommitCI

type CommitCI struct {
	Statuses []Status `json:"statuses"`
	Checks   []Check  `json:"checks"`
}

CommitCI is the complete status history and latest check runs for one commit.

type HoldEvent

type HoldEvent struct {
	ID        int    `json:"id"`
	Event     string `json:"event"`
	Actor     string `json:"actor"`
	CreatedAt string `json:"createdAt"`
}

HoldEvent is one hold-label transition.

type PublicationRequest

type PublicationRequest struct {
	// ExpectedNumber restricts publication to this exact open owned proposal; zero permits creation.
	ExpectedNumber int
	// ExpectedTitle and ExpectedBody bind a numbered update to the authorized PR text.
	ExpectedTitle  string
	ExpectedBody   string
	HeadRepository string
	HeadRef        string
	ExpectedHead   string
	BaseRef        string
	ExpectedBase   string
	Actor          string
	Marker         string
	// PreviousMarker authorizes the exact prior marker during an ownership-preserving update only.
	// Post-write verification always requires Marker and the new exact body.
	PreviousMarker string
	Title          string
	Body           string
	ExpectedFiles  []string
	// ReadyForReview explicitly opts new PRs into the caller's ready-publication policy.
	// It never changes an existing proposal's readiness.
	ReadyForReview bool
}

PublicationRequest describes a caller-prepared, already-pushed branch. Publish never changes Git refs. HeadRepository is the exact source repository, including a fork when publishing across repositories. ExpectedBase is the required base branch tip, checked read-only before and after publication. Marker must be an exact standalone HTML comment owned by the caller, not a substring of another marker. Existing proposals retain their readiness; new proposals default to drafts.

type PullRequest

type PullRequest struct {
	Number   int      `json:"number"`
	Author   string   `json:"author"`
	State    string   `json:"state"`
	Draft    bool     `json:"draft"`
	Merged   bool     `json:"merged"`
	Title    string   `json:"title"`
	Body     string   `json:"body"`
	Labels   []string `json:"labels"`
	HeadRef  string   `json:"headRef"`
	HeadSHA  string   `json:"headSHA"`
	HeadRepo string   `json:"headRepo"`
	BaseRef  string   `json:"baseRef"`
	BaseRepo string   `json:"baseRepo"`
}

PullRequest is the identity and review state of one proposal.

func (PullRequest) URL

func (p PullRequest) URL(repository string) string

URL returns the canonical proposal URL.

type Receipt

type Receipt struct {
	Number        int
	URL           string
	Author        string
	HeadRepo      string
	Base          string
	HeadSHA       string
	CommentID     int
	RequestedHead string
	ObservedHead  string
	Outcome       string
}

Receipt describes verified observations, not authorization to act.

type Snapshot

type Snapshot struct {
	Pull       PullRequest `json:"pull"`
	Commits    []string    `json:"commits"`
	Comments   []Comment   `json:"comments"`
	HoldEvents []HoldEvent `json:"holdEvents"`
	Statuses   []Status    `json:"statuses"`
	Checks     []Check     `json:"checks"`
	// CommitDetails is the complete ordered SDK evidence underlying Commits.
	CommitDetails []*gh.RepositoryCommit `json:"-"`
}

Snapshot is a complete, head-bound evidence set.

type Status

type Status struct {
	ID        int    `json:"id"`
	Context   string `json:"context"`
	State     string `json:"state"`
	CreatedAt string `json:"createdAt"`
	TargetURL string `json:"targetURL"`
}

Status is one commit status.

Directories

Path Synopsis
Package prow requests bounded Prow maintenance actions from explicit evidence.
Package prow requests bounded Prow maintenance actions from explicit evidence.

Jump to

Keyboard shortcuts

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