github

package
v1.44.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 29 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 provides owner-wide discovery and repository access through Service, using go-github for REST reads and merges, and GraphQL rebase and auto-merge requests and automation history. Client loads the App private key at startup. Rebases, auto-merge enablement, and immediate merges are guarded by the expected PR head SHA. Signing and installation token renewal are delegated to ghinstallation. Webhook verifies raw GitHub deliveries; worker and comment requests share Service. Snapshot completeness, label membership, and timeline timestamp extraction belong here; callers decide whether those facts authorize automation. Service composes accepted-action logging and caching decorators. Only validated source trees and blobs at pinned revisions use go-service's in-memory ttlcache backend. Other backends are bypassed for source reads; mutable GitHub state is always read fresh and cache errors fall back to GitHub.

Index

Constants

View Source
const CheckCompleted = "completed"

CheckCompleted identifies a finished check run, independently of its conclusion.

View Source
const FileRemoved = "removed"

FileRemoved identifies a changed file whose source must be read at the base revision.

View Source
const MergeableClean = "clean"

MergeableClean indicates that GitHub reports no mergeability blockers.

View Source
const MergeableUnstable = "unstable"

MergeableUnstable indicates non-passing checks while the pull request remains mergeable.

View Source
const PullClosed = "closed"

PullClosed includes merged pull requests in REST responses.

View Source
const PullOpen = "open"

PullOpen identifies an open pull request in REST responses and filters.

View Source
const StatusError = "error"

StatusError identifies a completed commit status reporting an error.

View Source
const StatusFailure = "failure"

StatusFailure identifies a completed failing commit status.

View Source
const StatusSuccess = "success"

StatusSuccess identifies a completed successful commit status.

View Source
const TreeBlob = "blob"

TreeBlob identifies a blob entry; its mode still determines whether it is a regular file.

View Source
const TreeDirectory = "tree"

TreeDirectory identifies a directory entry in a repository tree.

View Source
const UserBot = "Bot"

UserBot identifies a bot account in GitHub author metadata.

View Source
const UserHuman = "User"

UserHuman identifies a human account in GitHub author metadata.

Variables

View Source
var ErrIgnoredDelivery = errors.New("github: delivery does not require processing")

ErrIgnoredDelivery identifies a verified event or action with no worker handler.

View Source
var ErrRateLimited = errors.New("github: rate limit reached")

ErrRateLimited identifies a rate-limit error in a GraphQL HTTP-success payload.

Module provides shared API access and owner-wide discovery.

Functions

func HasCommentMetadata added in v0.13.0

func HasCommentMetadata(comment *IssueComment) bool

HasCommentMetadata checks for an author login and edit timestamp on a comment whose PR, author ID, and creation timestamp were already validated by GetComment or GetCommentWithHistory.

func HasLabel added in v0.13.0

func HasLabel(labels []*Label, name string) bool

HasLabel reports exact, case-sensitive membership. Nil or empty label lists contain no matching label.

func HasPullRequestNodeID added in v0.13.0

func HasPullRequestNodeID(pull *PullRequest) bool

HasPullRequestNodeID checks the identity required by GraphQL operations. A numeric pull request ID does not substitute for its node ID.

func IsRateLimited added in v0.8.0

func IsRateLimited(err error) bool

IsRateLimited recognizes throttling so reconciliation stops the current sweep instead of making more requests for other repositories against the same limit.

func IsRegularSourceFile added in v0.59.0

func IsRegularSourceFile(entry *TreeEntry) bool

IsRegularSourceFile reports whether an entry identifies a regular-file blob. Directories, symlinks, and submodules are not regular-file blobs.

func IsSubmodule added in v0.79.0

func IsSubmodule(entry *TreeEntry) bool

IsSubmodule identifies a gitlink; its SHA pins a commit in another repository.

func LatestAutomationEventTimes added in v0.13.0

func LatestAutomationEventTimes(events []*IssueEvent, label string) (time.Time, time.Time, time.Time)

LatestAutomationEventTimes returns the latest label application, removal, and auto-merge disable timestamps, in that order. Missing events return zero times. History must be validated, and label matching is exact. Disabling auto-merge is independent of the label; callers decide whether these facts revoke access.

func ValidatePullRequestMetadata added in v0.13.0

func ValidatePullRequestMetadata(pull *PullRequest) error

ValidatePullRequestMetadata requires a node ID, head SHA, branch references, and repository names before guarded automation. Callers decide which PRs need this validation, so incomplete snapshots of ineligible PRs can be ignored.

Types

type AppConfig added in v0.13.0

type AppConfig struct {
	// PrivateKey is the required go-service RSA key source read once at startup.
	PrivateKey string `yaml:"private_key,omitempty" json:"private_key,omitempty" toml:"private_key,omitempty" validate:"required"`

	// ID identifies the GitHub App used for JWT authentication and installation validation.
	ID int64 `yaml:"id,omitempty" json:"id,omitempty" toml:"id,omitempty" validate:"gt=0"`

	// InstallationID selects the installation used for repository access and webhook identity checks.
	InstallationID int64 `yaml:"installation_id,omitempty" json:"installation_id,omitempty" toml:"installation_id,omitempty" validate:"gt=0"`
}

AppConfig identifies one installation. PrivateKey is a go-service source read once at startup; installation access tokens are renewed automatically.

type Branch added in v0.29.0

type Branch = github.Branch

Branch aliases github.Branch for branch cleanup snapshots.

type CheckRun added in v0.33.0

type CheckRun = github.CheckRun

CheckRun aliases github.CheckRun for current-head CI observations.

type Client

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

Client supplies installation access. The application client uses JWTs to validate installation ownership.

func NewClient

func NewClient(params ClientParams) (*Client, error)

NewClient reads the App key once at startup. Missing or empty sources and invalid RSA PEMs prevent startup; replacement requires a restart. Signing and installation token renewal are handled by ghinstallation. Construction makes no GitHub requests.

type ClientParams

type ClientParams struct {
	// In marks the injected dependencies.
	signal.In

	// Lifecycle closes the shared pool during shutdown.
	Lifecycle signal.Lifecycle

	// ID generates outbound request identifiers.
	ID id.Generator

	// Config supplies the endpoint and App identity.
	Config *Config

	// FS resolves the configured App private key and client TLS sources at startup.
	FS *os.FS

	// Logger records outbound HTTP outcomes.
	Logger *logger.Logger

	// UserAgent identifies the worker in outbound API requests.
	UserAgent env.UserAgent
}

ClientParams supplies startup credentials and the GitHub transport settings.

type CommitFile added in v0.27.0

type CommitFile = github.CommitFile

CommitFile aliases github.CommitFile for pull request file snapshots.

type CommitStatus added in v0.33.0

type CommitStatus = github.RepoStatus

CommitStatus aliases github.RepoStatus for commit-status contexts.

type CommitsComparison

type CommitsComparison = github.CommitsComparison

CommitsComparison aliases github.CommitsComparison so consumers use the project-owned package.

type Config

type Config struct {
	// Client configures the required REST and GraphQL endpoint, HTTP timeout, and safe-method retries.
	Client *client.Config `yaml:"client,omitempty" json:"client,omitempty" toml:"client,omitempty" validate:"required"`

	// App supplies required App and installation identity and the startup private-key source.
	App *AppConfig `yaml:"app,omitempty" json:"app,omitempty" toml:"app,omitempty" validate:"required"`

	// Webhook enables signed delivery processing when present; omission disables the endpoint.
	Webhook *WebhookConfig `yaml:"webhook,omitempty" json:"webhook,omitempty" toml:"webhook,omitempty" validate:"omitempty"`

	// Owner identifies the installation account whose owned repositories may be accessed.
	Owner string `yaml:"owner,omitempty" json:"owner,omitempty" toml:"owner,omitempty" validate:"required"`
}

Config identifies the owner whose installation repositories are reconciled. App credentials supply worker and comment access. The private key is loaded at startup; installation tokens renew automatically.

func (*Config) GetTimeout

func (c *Config) GetTimeout() time.Duration

GetTimeout returns the HTTP request timeout, defaulting to one minute when client settings are absent or their timeout is zero.

type Delivery added in v0.33.0

type Delivery struct {
	// Comment contains the verified comment event, or nil for a repository notification.
	Comment *IssueCommentEvent

	// Repository is a verified owner/repository discovery hint whose live state must be re-read.
	Repository string
}

Delivery routes a verified comment command or repository notification. Repository is only a discovery hint; current settings and PR state must be read from GitHub before automation. Comment is nil for repository notifications.

type DiffSide added in v0.77.0

type DiffSide string

DiffSide selects the base or head side of a pull request patch.

const DiffLeft DiffSide = "LEFT"

DiffLeft places a finding on the base side of a pull request patch.

const DiffRight DiffSide = "RIGHT"

DiffRight places a finding on the head side of a pull request patch.

func (DiffSide) IsDefined added in v0.77.0

func (s DiffSide) IsDefined() bool

IsDefined reports whether a diff side is present, without validating its value.

func (DiffSide) String added in v0.77.0

func (s DiffSide) String() string

String returns the side value used for inline review placement.

type DraftReviewComment added in v0.41.0

type DraftReviewComment = github.DraftReviewComment

DraftReviewComment aliases github.DraftReviewComment for inline findings.

type EnablePullRequestAutoMergeInput added in v0.9.0

type EnablePullRequestAutoMergeInput struct {
	// PullRequestID identifies the target PR by its GraphQL node ID, rather than its numeric ID.
	PullRequestID string `json:"pullRequestId"`

	// ExpectedHeadOID guards the mutation against concurrent changes to the PR head commit.
	ExpectedHeadOID string `json:"expectedHeadOid"`

	// MergeMethod selects the eventual merge strategy; the worker requests SQUASH.
	MergeMethod string `json:"mergeMethod"`
}

EnablePullRequestAutoMergeInput selects a PR and merge method for auto-merge, guarded by ExpectedHeadOID against concurrent pushes.

type EnablePullRequestAutoMergeRequest added in v0.9.0

type EnablePullRequestAutoMergeRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// Input supplies the mutation arguments, including the target identity.
		Input EnablePullRequestAutoMergeInput `json:"input"`
	} `json:"variables"`
}

EnablePullRequestAutoMergeRequest encodes GitHub's auto-merge mutation.

type EnablePullRequestAutoMergeResponse added in v0.9.0

type EnablePullRequestAutoMergeResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Enable contains the enablePullRequestAutoMerge acceptance payload.
		Enable struct {
			// PullRequest identifies the PR accepted for auto-merge enablement.
			PullRequest struct {
				// ID must match the requested PR node ID to confirm acceptance.
				ID string `json:"id"`
			} `json:"pullRequest"`
		} `json:"enablePullRequestAutoMerge"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

EnablePullRequestAutoMergeResponse requires validation even on HTTP success.

func (*EnablePullRequestAutoMergeResponse) Validate added in v0.9.0

func (r *EnablePullRequestAutoMergeResponse) Validate(expectedID string) error

Validate rejects GraphQL errors and responses identifying a different PR.

type Errors added in v0.9.0

type Errors []struct {
	// Message contains the failure explanation included in the joined service error.
	Message string `json:"message"`

	// Type classifies the GraphQL failure, including RATE_LIMITED responses.
	Type string `json:"type"`
}

Errors contains GraphQL failures that may accompany data even on HTTP success.

func (Errors) Validate added in v0.9.0

func (e Errors) Validate() error

Validate joins reported failures and includes ErrRateLimited for rate limits. It returns nil when Errors is empty or nil.

type IssueComment added in v0.13.0

type IssueComment = github.IssueComment

IssueComment aliases github.IssueComment for signed command requests.

type IssueCommentEvent added in v0.13.0

type IssueCommentEvent = github.IssueCommentEvent

IssueCommentEvent aliases github.IssueCommentEvent for verified deliveries.

type IssueEvent added in v0.12.0

type IssueEvent = github.IssueEvent

IssueEvent aliases github.IssueEvent for pull request automation history.

type Label added in v0.13.0

type Label = github.Label

Label aliases github.Label for shared label membership checks.

type PullRequest

type PullRequest = github.PullRequest

PullRequest aliases github.PullRequest so consumers use the project-owned package.

type PullRequestAutomationEventsRequest added in v0.12.0

type PullRequestAutomationEventsRequest struct {
	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// ID identifies the PR node whose complete automation history is requested.
		ID string `json:"id"`

		// After selects the next page; nil starts pagination.
		After *string `json:"after"`
	} `json:"variables"`

	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`
}

PullRequestAutomationEventsRequest identifies a PR by node ID and supplies the cursor for the next page of its automation history.

type PullRequestAutomationEventsResponse added in v0.12.0

type PullRequestAutomationEventsResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Node contains the PR identity and requested automation timeline page.
		Node struct {
			// ID must match the requested PR node ID before its history is used.
			ID string `json:"id"`

			// TimelineItems contains label and auto-merge-disable history used to establish consent.
			TimelineItems struct {
				// Nodes contains the page's automation events; nil indicates an incomplete page.
				Nodes []*IssueEvent `json:"nodes"`

				// PageInfo reports whether discovery must continue before the results are complete.
				PageInfo struct {
					// EndCursor selects the following page when HasNextPage is true.
					EndCursor *string `json:"endCursor"`

					// HasNextPage reports whether more results remain; nil indicates an incomplete response.
					HasNextPage *bool `json:"hasNextPage"`
				} `json:"pageInfo"`
			} `json:"timelineItems"`
		} `json:"node"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

PullRequestAutomationEventsResponse decodes timeline history into SDK issue-event snapshots. Call Validate before using the history, even when the HTTP request succeeds.

func (*PullRequestAutomationEventsResponse) Validate added in v0.12.0

func (r *PullRequestAutomationEventsResponse) Validate(expectedID string) error

Validate rejects GraphQL errors, a PR node ID different from expectedID, incomplete pages, and events that cannot establish valid automation history.

type PullRequestReview added in v0.41.0

type PullRequestReview = github.PullRequestReview

PullRequestReview aliases github.PullRequestReview for native review history.

type PullRequestReviewAuthorsRequest added in v0.41.0

type PullRequestReviewAuthorsRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// IDs lists review node IDs whose authenticated authorship must be checked.
		IDs []string `json:"ids"`
	} `json:"variables"`
}

PullRequestReviewAuthorsRequest queries authenticated authorship for a batch of review node IDs.

type PullRequestReviewAuthorsResponse added in v0.41.0

type PullRequestReviewAuthorsResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Nodes returns one authorship result for each requested review identity.
		Nodes []*struct {
			// ViewerDidAuthor reports authenticated viewer authorship; nil cannot establish ownership.
			ViewerDidAuthor *bool `json:"viewer_did_author"`

			// ID identifies the review whose authorship was returned.
			ID string `json:"id"`
		} `json:"nodes"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

PullRequestReviewAuthorsResponse requires each requested review identity and explicit authorship. Call Validate even when the HTTP request succeeds.

func (*PullRequestReviewAuthorsResponse) Validate added in v0.41.0

func (r *PullRequestReviewAuthorsResponse) Validate(expectedIDs []string) error

Validate requires exactly one explicit authorship result for every requested ID, regardless of response order. False is a valid authorship result.

type PullRequestReviewRequest added in v0.41.0

type PullRequestReviewRequest = github.PullRequestReviewRequest

PullRequestReviewRequest aliases github.PullRequestReviewRequest for review publication.

type Reaction added in v0.77.0

type Reaction string

Reaction selects GitHub reaction content for command feedback.

const ReactionConfused Reaction = "confused"

ReactionConfused reports a declined command.

const ReactionEyes Reaction = "eyes"

ReactionEyes acknowledges receipt of a command.

const ReactionThumbsUp Reaction = "+1"

ReactionThumbsUp acknowledges an accepted command.

func (Reaction) String added in v0.77.0

func (r Reaction) String() string

String returns the reaction content accepted by GitHub.

type RefUpdate added in v0.29.0

type RefUpdate struct {
	// Name is the fully qualified reference name, such as refs/heads/feature.
	Name string `json:"name"`

	// BeforeOID requires the reference to still point at this commit before it can change.
	BeforeOID string `json:"beforeOid"`

	// AfterOID sets the replacement commit; the all-zero OID deletes the reference.
	AfterOID string `json:"afterOid"`
}

RefUpdate carries the expected and replacement OIDs for an atomic ref update.

type Repository

type Repository = github.Repository

Repository aliases github.Repository to keep SDK imports in this package.

type RepositoryCommit added in v0.29.0

type RepositoryCommit = github.RepositoryCommit

RepositoryCommit aliases github.RepositoryCommit for commit age checks.

type RepositoryContent added in v0.49.0

type RepositoryContent = github.RepositoryContent

RepositoryContent aliases github.RepositoryContent for source blob metadata.

type ResolveReviewThreadRequest added in v0.42.0

type ResolveReviewThreadRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// Input supplies the mutation arguments, including the target identity.
		Input struct {
			// ThreadID identifies the thread to resolve after final eligibility rechecks.
			ThreadID string `json:"threadId"`
		} `json:"input"`
	} `json:"variables"`
}

ResolveReviewThreadRequest resolves a thread by node ID without an expected-state guard; callers must refresh eligibility before submission.

type ResolveReviewThreadResponse added in v0.42.0

type ResolveReviewThreadResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Resolve contains the resolveReviewThread acceptance payload.
		Resolve struct {
			// Thread confirms the target thread and its resolved state; nil cannot confirm acceptance.
			Thread *struct {
				// ID must match the requested thread node ID to confirm acceptance.
				ID string `json:"id"`

				// IsResolved must be present and true to confirm that the mutation resolved the thread.
				IsResolved *bool `json:"isResolved"`
			} `json:"thread"`
		} `json:"resolveReviewThread"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

ResolveReviewThreadResponse confirms a matching thread's resolved state. GraphQL errors or missing confirmation must not be treated as acceptance.

type ReviewEvent added in v0.77.0

type ReviewEvent string

ReviewEvent selects the verdict requested when publishing a native review.

const ReviewApprove ReviewEvent = "APPROVE"

ReviewApprove submits an approving review.

const ReviewComment ReviewEvent = "COMMENT"

ReviewComment submits feedback without approving or requesting changes.

const ReviewRequestChanges ReviewEvent = "REQUEST_CHANGES"

ReviewRequestChanges submits findings that request changes.

func (ReviewEvent) String added in v0.77.0

func (e ReviewEvent) String() string

String returns the event value sent when publishing a review.

type ReviewState added in v0.77.0

type ReviewState string

ReviewState identifies the recorded outcome of a submitted or dismissed review.

const ReviewApproved ReviewState = "APPROVED"

ReviewApproved identifies a submitted approval.

const ReviewChangesRequested ReviewState = "CHANGES_REQUESTED"

ReviewChangesRequested identifies a submitted request for changes.

const ReviewCommented ReviewState = "COMMENTED"

ReviewCommented identifies submitted feedback without a verdict.

const ReviewDismissed ReviewState = "DISMISSED"

ReviewDismissed identifies a review dismissed after submission.

func (ReviewState) String added in v0.77.0

func (s ReviewState) String() string

String returns the state value recorded by GitHub.

type ReviewThread added in v0.42.0

type ReviewThread struct {
	// ID is the GraphQL node identity used for final rechecks and resolution.
	ID string

	// ReviewBody contains the parent review's result marker for feature ownership checks.
	ReviewBody string

	// IsOutdated reports stale placement from GitHub, without establishing that a finding was fixed.
	IsOutdated bool

	// IsResolved reports whether the conversation is already closed.
	IsResolved bool

	// ViewerCanResolve reports whether the authenticated installation may resolve the thread.
	ViewerCanResolve bool

	// IsAppAuthor requires API-authenticated Bot authorship of both the root comment and parent review.
	IsAppAuthor bool
}

ReviewThread contains the state and authenticated ownership needed to maintain an existing conversation. IsAppAuthor requires both its root and parent review.

type ReviewThreadRequest added in v0.42.0

type ReviewThreadRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// ID identifies the thread node to refresh immediately before maintenance.
		ID string `json:"id"`
	} `json:"variables"`
}

ReviewThreadRequest queries one review thread by its node ID.

type ReviewThreadResponse added in v0.42.0

type ReviewThreadResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Node contains the thread's current state and ownership evidence; nil fails validation.
		Node *reviewThreadNode `json:"node"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

ReviewThreadResponse carries one thread's state and authenticated ownership. The service validates its identity and parent PR before returning a snapshot.

type ReviewThreadsRequest added in v0.42.0

type ReviewThreadsRequest struct {
	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// ID identifies the PR node whose inline conversations are requested.
		ID string `json:"id"`

		// After selects the next page; nil starts pagination.
		After *string `json:"after"`
	} `json:"variables"`

	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`
}

ReviewThreadsRequest queries one page of threads by pull request node ID. A nil After cursor starts pagination.

type ReviewThreadsResponse added in v0.42.0

type ReviewThreadsResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Node contains the requested PR and thread page; nil cannot establish identity.
		Node *struct {

			// ReviewThreads contains one page of thread state and ownership evidence.
			ReviewThreads struct {
				// Nodes contains thread candidates; nil indicates an incomplete discovery page.
				Nodes []*reviewThreadNode `json:"nodes"`

				// PageInfo reports whether discovery must continue before the results are complete.
				PageInfo struct {
					// EndCursor selects the following page when HasNextPage is true.
					EndCursor *string `json:"endCursor"`

					// HasNextPage reports whether more results remain; nil indicates an incomplete response.
					HasNextPage *bool `json:"hasNextPage"`
				} `json:"pageInfo"`
			} `json:"reviewThreads"`
			// contains filtered or unexported fields
		} `json:"node"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

ReviewThreadsResponse carries thread ownership, state, and pagination. HTTP success still requires GraphQL, identity, and completeness validation.

type Service added in v0.8.0

type Service interface {
	// ReadSourceFiles batches uncached regular entries from ListSourceFiles at a fixed
	// revision. Only complete UTF-8 blobs matching the repository, tree SHA and
	// byte size are returned, keyed by path. Binary entries are omitted; failed,
	// missing, or inconsistent responses reject the group. Validated blobs are
	// cached by repository identity and blob SHA when ttlcache is configured.
	// Reads do not retry.
	ReadSourceFiles(ctx context.Context, repo *Repository, revision string, files []*TreeEntry) (map[string]string, error)

	// ListSourceFiles returns all entries from a complete recursive tree at an
	// immutable commit SHA, retaining directories, symlinks, and submodules as
	// metadata without following them. ReadSourceFiles accepts only entries passing
	// IsRegularSourceFile. Truncated trees, invalid or duplicate paths, and missing
	// regular-file blob identities are errors. Validated trees are cached by
	// repository identity and revision when ttlcache is configured.
	ListSourceFiles(ctx context.Context, repo *Repository, revision string) ([]*TreeEntry, error)

	// GetSubmoduleRepository validates submodule metadata against its tree entry
	// at revision and resolves only active public same-owner GitHub repositories
	// accessible to the installation. Unsupported URLs, mismatched metadata, nonpublic
	// targets, missing visibility metadata, and missing access return an error. The URL is never fetched directly.
	GetSubmoduleRepository(ctx context.Context, repo *Repository, revision string, entry *TreeEntry) (*Repository, error)

	// ListBranches collects complete, validated branch pagination before cleanup.
	ListBranches(ctx context.Context, repo *Repository) ([]*Branch, error)

	// GetBranch rechecks branch identity, protection, and head without redirects.
	GetBranch(ctx context.Context, repo *Repository, name string) (*Branch, error)

	// GetCommit reads an immutable commit and requires a matching SHA and date.
	GetCommit(ctx context.Context, repo *Repository, sha string) (*RepositoryCommit, error)

	// ListBranchPullRequests collects complete head-branch history, including open PRs.
	ListBranchPullRequests(ctx context.Context, repo *Repository, branch string) ([]*PullRequest, error)

	// DeleteBranch deletes a branch only while its expected SHA still matches.
	// GraphQL failures and unconfirmed responses fail without mutation retries.
	DeleteBranch(ctx context.Context, repo *Repository, branch *Branch) error

	// ValidateInstallation checks the configured App, owner, and suspension state
	// without caching. Comment commands must call it before accessing repositories.
	ValidateInstallation(ctx context.Context) error

	// GetComment reads the current comment and verifies its PR and author identity.
	GetComment(ctx context.Context, repo *Repository, number int, expected *IssueComment) (*IssueComment, error)

	// GetCommentWithHistory reads the complete discussion and validates the
	// expected command's PR, author, and creation identity. A missing command
	// returns nil with the current history; no snapshot is cached.
	GetCommentWithHistory(ctx context.Context, repo *Repository, number int, expected *IssueComment) (*IssueComment, []*IssueComment, error)

	// HasWritePermission checks the author's current repository permissions.
	HasWritePermission(ctx context.Context, repo *Repository, author *User) (bool, error)

	// AddLabel adds one label without replacing others or retrying mutations.
	AddLabel(ctx context.Context, repo *Repository, number int, label string) error

	// AddCommentReaction adds a reaction as the App. Repeated reactions are
	// idempotent in GitHub; mutation requests are not retried.
	AddCommentReaction(ctx context.Context, repo *Repository, comment *IssueComment, content Reaction) error

	// AddComment publishes feedback once and validates the response. An ambiguous
	// failure may have published the comment; callers must not retry automatically.
	AddComment(ctx context.Context, repo *Repository, number int, body string) error

	// ListComments collects complete comment history and validates each comment's PR identity.
	ListComments(ctx context.Context, repo *Repository, number int) ([]*IssueComment, error)

	// IsAppComment requires a bot author and the configured GitHub App identity.
	IsAppComment(comment *IssueComment) bool

	// AddReview submits a COMMENT, APPROVE, or REQUEST_CHANGES review at the reviewed head and validates
	// publication and authenticated authorship. Ambiguous failures are not retried.
	AddReview(ctx context.Context, repo *Repository, pull *PullRequest, review *PullRequestReviewRequest) error

	// ListReviews returns complete native review history with validated PR identities.
	ListReviews(ctx context.Context, repo *Repository, pull *PullRequest) ([]*PullRequestReview, error)

	// ListReviewCommentBodies returns root comments matching the author and identity of an authenticated review.
	ListReviewCommentBodies(ctx context.Context, repo *Repository, pull *PullRequest, review *PullRequestReview) ([]string, error)

	// HasAppReview checks whether any candidate belongs to the authenticated
	// installation viewer. Human authors are skipped; bot checks are batched.
	HasAppReview(ctx context.Context, reviews []*PullRequestReview) (bool, error)

	// AppReviews returns authenticated installation-viewer reviews in input order.
	// Human authors are skipped; bot checks are batched and fail on incomplete results.
	AppReviews(ctx context.Context, reviews []*PullRequestReview) ([]*PullRequestReview, error)

	// ListReviewThreads completes thread pagination with authenticated root and review ownership.
	ListReviewThreads(ctx context.Context, repo *Repository, pull *PullRequest) ([]*ReviewThread, error)

	// GetReviewThread refreshes one thread and returns nil for a closed parent PR.
	GetReviewThread(ctx context.Context, repo *Repository, pull *PullRequest, id string) (*ReviewThread, error)

	// ResolveReviewThread resolves once; callers refresh eligibility immediately before it.
	ResolveReviewThread(ctx context.Context, repo *Repository, pull *PullRequest, thread *ReviewThread) error

	// ListPullRequestFiles rejects incomplete pagination and mismatched file counts.
	ListPullRequestFiles(ctx context.Context, repo *Repository, pull *PullRequest) ([]*CommitFile, error)

	// ListRepositories validates the authenticated owner and collects all pages
	// before returning active owned repositories accessible to the installation.
	ListRepositories(ctx context.Context) ([]*Repository, error)

	// FindRepository completes installation discovery and returns the active
	// owned repository with this full name, ignoring case, or nil when absent.
	FindRepository(ctx context.Context, name string) (*Repository, error)

	// GetRepository reads full settings omitted by discovery and validates that
	// the response identifies the discovered repository.
	GetRepository(ctx context.Context, repo *Repository) (*Repository, error)

	// IsSameRepository checks that both PR branches belong to the discovered
	// repository, comparing names case-insensitively.
	IsSameRepository(repo *Repository, pull *PullRequest) bool

	// IsRepository compares a repository's full owner/name with name, ignoring
	// case. It performs no remote access or partial-name matching.
	IsRepository(repo *Repository, name string) bool

	// IsBaseRepository checks that the PR targets the discovered repository,
	// comparing names case-insensitively. Its head may belong to a fork.
	IsBaseRepository(repo *Repository, pull *PullRequest) bool

	// IsSamePullRequestIdentity matches PR number and node ID across snapshots
	// and requires current to target repo, comparing repository names ignoring
	// case. Branch refs and commit SHAs may differ.
	IsSamePullRequestIdentity(repo *Repository, current, expected *PullRequest) bool

	// IsSamePullRequest compares identity, branch repositories, refs, and head
	// SHA across snapshots. Repository names are compared case-insensitively.
	IsSamePullRequest(current, expected *PullRequest) bool

	// ListOpenPullRequests collects all pages in ascending creation order before
	// returning so mutations cannot change ordering partway through pagination.
	ListOpenPullRequests(ctx context.Context, repo *Repository) ([]*PullRequest, error)

	// GetPullRequest reads fresh auto-merge, branch, and identity state.
	GetPullRequest(ctx context.Context, repo *Repository, number int) (*PullRequest, error)

	// ListPullRequestAutomationEvents collects all label and auto-merge-disable
	// events through GraphQL. Event names are GraphQL type names. Errors,
	// incomplete pages, and mismatched PR identities reject the whole history.
	ListPullRequestAutomationEvents(ctx context.Context, pull *PullRequest) ([]*IssueEvent, error)

	// Compare reports commits missing from head relative to base. A missing
	// behind_by is an error rather than evidence that the branch is current.
	Compare(ctx context.Context, repo *Repository, base, head string) (*CommitsComparison, error)

	// ListCheckRuns collects all latest check runs and validates their head SHA.
	ListCheckRuns(ctx context.Context, repo *Repository, sha string) ([]*CheckRun, error)

	// ListCommitStatuses collects the latest status for each context, validating
	// the commit SHA and complete pagination of the combined-status response.
	ListCommitStatuses(ctx context.Context, repo *Repository, sha string) ([]*CommitStatus, error)

	// Rebase requests a server-side rebase guarded by the expected head SHA.
	// HTTP failures, GraphQL errors, and mismatched responses fail without
	// retrying the mutation. Success confirms acceptance, not completion.
	Rebase(ctx context.Context, pull *PullRequest) error

	// EnableAutoMerge requests squash merging once GitHub's requirements pass,
	// guarded by the expected head SHA. Failures are not retried.
	EnableAutoMerge(ctx context.Context, pull *PullRequest) error

	// Merge squash-merges a ready pull request, guarded by its head SHA.
	// A rejected or unconfirmed merge fails without retrying.
	Merge(ctx context.Context, repo *Repository, pull *PullRequest) error
}

Service owns repository discovery, identity checks, REST reads, and guarded mutations. Callers own pull request eligibility, rebase, and merge policy.

func NewService added in v0.8.0

func NewService(params ServiceParams) Service

NewService constructs shared worker and webhook access through the App client. Construction does not contact GitHub; each sweep discovers fresh remote state. Shared source retention uses the supplied cache when configured for ttlcache. A nil cache or any other backend leaves source retention disabled.

type ServiceParams added in v1.41.0

type ServiceParams struct {
	// In marks the injected dependencies.
	signal.In

	// Config supplies the GitHub owner and App identity.
	Config *Config

	// Client provides GitHub App and installation access.
	Client *Client

	// CacheConfig selects the configured cache backend. Only ttlcache is used.
	CacheConfig *config.Config

	// SourceCache stores validated source trees and blobs when ttlcache is enabled.
	SourceCache *cache.Cache

	// Logger records outcomes of GitHub actions.
	Logger *logger.Logger
}

ServiceParams supplies GitHub access, source caching, and action logging.

type TreeEntry added in v0.49.0

type TreeEntry = github.TreeEntry

TreeEntry aliases github.TreeEntry to retain path and blob identity from a source tree.

type UpdatePullRequestBranchInput

type UpdatePullRequestBranchInput struct {
	// PullRequestID identifies the target PR by its GraphQL node ID, rather than its numeric ID.
	PullRequestID string `json:"pullRequestId"`

	// ExpectedHeadOID guards the mutation against concurrent changes to the PR head commit.
	ExpectedHeadOID string `json:"expectedHeadOid"`

	// UpdateMethod selects the GitHub update strategy; the worker requests REBASE.
	UpdateMethod string `json:"updateMethod"`
}

UpdatePullRequestBranchInput supplies GitHub's branch-update arguments. ExpectedHeadOID rejects concurrent head changes; UpdateMethod selects REBASE or MERGE.

type UpdatePullRequestBranchRequest

type UpdatePullRequestBranchRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// Input supplies the mutation arguments, including the target identity.
		Input UpdatePullRequestBranchInput `json:"input"`
	} `json:"variables"`
}

UpdatePullRequestBranchRequest encodes a branch-update mutation. Query must declare $input with the GraphQL type UpdatePullRequestBranchInput.

type UpdatePullRequestBranchResponse

type UpdatePullRequestBranchResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Update contains the branch-update mutation's acceptance payload.
		Update struct {
			// PullRequest identifies the PR accepted for a branch update.
			PullRequest struct {
				// ID must match the requested PR node ID to confirm acceptance.
				ID string `json:"id"`
			} `json:"pullRequest"`
		} `json:"updatePullRequestBranch"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

UpdatePullRequestBranchResponse decodes GitHub's branch-update mutation. HTTP success can include GraphQL errors or incomplete data; call Validate before treating an update as accepted.

func (*UpdatePullRequestBranchResponse) Validate

func (r *UpdatePullRequestBranchResponse) Validate(expectedID string) error

Validate returns joined GraphQL errors or an error when the payload does not identify expectedID. A matching payload confirms acceptance, not completion.

type UpdateRefsRequest added in v0.29.0

type UpdateRefsRequest struct {
	// Query contains the GraphQL operation submitted with these variables.
	Query string `json:"query"`

	// Variables binds the operation's GraphQL arguments.
	Variables struct {
		// Input supplies the mutation arguments, including the target identity.
		Input struct {
			// RepositoryID identifies the repository by its GraphQL node ID.
			RepositoryID string `json:"repositoryId"`

			// ClientMutationID correlates the mutation request with its acceptance response.
			ClientMutationID string `json:"clientMutationId"`

			// RefUpdates contains the guarded reference changes; cleanup submits one deletion at a time.
			RefUpdates []RefUpdate `json:"refUpdates"`
		} `json:"input"`
	} `json:"variables"`
}

UpdateRefsRequest deletes one branch with an atomic expected-commit guard. The zero AfterOID deletes the reference; ClientMutationID must be echoed.

type UpdateRefsResponse added in v0.29.0

type UpdateRefsResponse struct {
	// Data contains returned operation data, which still requires error and identity validation.
	Data struct {
		// Update confirms an accepted updateRefs mutation; nil cannot confirm success.
		Update *struct {
			// ClientMutationID correlates the mutation request with its acceptance response.
			ClientMutationID string `json:"clientMutationId"`
		} `json:"updateRefs"`
	} `json:"data"`

	// Errors retains GraphQL failures even when the HTTP response succeeds.
	Errors Errors `json:"errors"`
}

UpdateRefsResponse requires a matching mutation ID and no GraphQL errors.

func (*UpdateRefsResponse) Validate added in v0.29.0

func (r *UpdateRefsResponse) Validate(expectedID string) error

Validate rejects absent, unconfirmed, or failed reference updates.

type User added in v0.13.0

type User = github.User

User aliases github.User for current command-author permission checks.

type Webhook added in v0.13.0

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

Webhook verifies raw GitHub deliveries before exposing SDK events to policies. It holds no delivery history; policy must re-read current remote state.

func NewWebhook added in v0.13.0

func NewWebhook(cfg *Config, filesystem *os.FS) (*Webhook, error)

NewWebhook resolves optional delivery credentials at startup, returning nil when webhook configuration is disabled. A configured webhook requires App credentials, a nonempty secret, and a timeout below ten seconds.

func (*Webhook) GetTimeout added in v0.13.0

func (w *Webhook) GetTimeout() time.Duration

GetTimeout returns the independent synchronous processing budget.

func (*Webhook) Read added in v0.13.0

func (w *Webhook) Read(req *http.Request) (*Delivery, error)

Read verifies SHA-256 signatures and installation/repository identity before routing supported events. Unknown event types and actions are ignored.

type WebhookConfig added in v0.13.0

type WebhookConfig struct {
	// Secret is the required go-service signature-secret source read once at startup.
	Secret string `yaml:"secret,omitempty" json:"secret,omitempty" toml:"secret,omitempty" validate:"required"`

	// Timeout bounds synchronous delivery processing; zero uses five seconds and values must stay below ten seconds.
	Timeout time.Duration `yaml:"timeout,omitempty" json:"timeout,omitempty" toml:"timeout,omitempty"`
}

WebhookConfig enables signed GitHub comment deliveries with App credentials. Secret is a go-service source read at startup. Timeout bounds synchronous processing and defaults to five seconds, below GitHub's ten-second deadline.

func (*WebhookConfig) GetTimeout added in v0.13.0

func (c *WebhookConfig) GetTimeout() time.Duration

GetTimeout returns the delivery processing budget, defaulting to five seconds.

func (*WebhookConfig) IsEnabled added in v0.21.0

func (c *WebhookConfig) IsEnabled() bool

IsEnabled reports whether webhook configuration is present.

func (*WebhookConfig) IsValid added in v0.21.0

func (c *WebhookConfig) IsValid() bool

IsValid reports whether the configured processing budget is positive and below GitHub's ten-second deadline. A zero timeout uses the default budget.

Jump to

Keyboard shortcuts

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