sdk

package
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package sdk provides a framework for building GitHub bots that receive and handle GitHub webhook events delivered as CloudEvents.

Bots

A bot is created with NewBot and configured with handler functions for specific GitHub event types. Use BotWithHandler to register handlers, or call Bot.RegisterHandler directly.

Handlers

Each handler type corresponds to a GitHub event type:

Serving

Call Serve to start the bot's CloudEvents HTTP receiver. The port defaults to the PORT environment variable, or 8080 if unset. Use WithPort to override the port programmatically.

GitHub Clients

NewGitHubClient creates an authenticated GitHub API client using OctoSTS for token management. NewInstallationClient creates a client using a GitHub App installation transport.

Index

Examples

Constants

View Source
const (
	ContextKeyAttributes contextKey = "ce-attributes"
	ContextKeyType       contextKey = "ce-type"
	ContextKeySubject    contextKey = "ce-subject"
)

Define constants for the keys to use with context.WithValue.

View Source
const (
	HeaderRetryAfter = "Retry-After"
	// The time at which the current rate limit window resets, in UTC epoch seconds
	HeaderXRateLimitReset = "X-Ratelimit-Reset"
	// The number of requests remaining in the current rate limit window
	HeaderXRateLimitRemaining = "X-Ratelimit-Remaining"
)

https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28#checking-the-status-of-your-rate-limit NOTE: Use the go canonical form (capitals) for these headers, even though they are lowercase in the docs.

Variables

View Source
var OctoTokenFunc = octosts.Token

OctoTokenFunc is the function used to mint Octo STS tokens. It is exposed as a package-level variable so tests can override it without going through the network. Production code should not reassign this.

Functions

func AttributeFromContext added in v0.5.156

func AttributeFromContext(ctx context.Context, key string) interface{}

AttributeFromContext retrieves an attribute by key from the context. Returns nil if the attribute does not exist.

Example
package main

import (
	"context"
	"fmt"

	"github.com/chainguard-dev/terraform-infra-common/modules/github-bots/sdk"
)

func main() {
	ctx := context.Background()
	val := sdk.AttributeFromContext(ctx, "missing-key")
	fmt.Println(val)
}
Output:
<nil>

func NewClient added in v1.0.12

func NewClient(base http.RoundTripper) *github.Client

NewClient returns a *github.Client whose HTTP transport is instrumented with httpmetrics.WrapTransport. base provides authentication: typically the Transport from oauth2.NewClient(ctx, ts), or a *ghinstallation.Transport for the GitHub App installation flow.

This is the low-level primitive used by NewGitHubClient and NewInstallationClient; it's also the supported entry point for callers that want a bare *github.Client (for example, the DAF githubreconciler's ClientCache) without the lifecycle helpers attached to GitHubClient.

func NewClientWithToken added in v1.0.12

func NewClientWithToken(ctx context.Context, token string) *github.Client

NewClientWithToken returns a *github.Client authenticated with a static access token (typically a personal access token from $GITHUB_TOKEN or the gh CLI). The transport is instrumented via NewClient.

Use this for one-off CLI tools and local utilities where the caller already has a raw token in hand. Production bots should prefer NewGitHubClient (Octo STS) or NewInstallationClient (GitHub App) instead.

func NewOrgTokenSource added in v1.0.12

func NewOrgTokenSource(ctx context.Context, identity, org string) oauth2.TokenSource

NewOrgTokenSource returns an oauth2.TokenSource that mints org-scoped tokens from Octo STS for the given org using identity as the policy name. The returned source caches valid tokens via oauth2.ReuseTokenSource.

The supplied ctx is used as the parent of each token-refresh request, so it should be long-lived: passing a per-request context risks "context cancelled" errors on later refreshes.

func NewRepoTokenSource added in v1.0.12

func NewRepoTokenSource(ctx context.Context, identity, org, repo string) oauth2.TokenSource

NewRepoTokenSource returns an oauth2.TokenSource that mints repo-scoped tokens from Octo STS for the given (org, repo) using identity as the policy name. The returned source caches valid tokens via oauth2.ReuseTokenSource.

The supplied ctx is used as the parent of each token-refresh request, so it should be long-lived: passing a per-request context risks "context cancelled" errors on later refreshes.

func NewSecondaryRateLimitWaiterClient added in v0.5.156

func NewSecondaryRateLimitWaiterClient(base http.RoundTripper) *http.Client

func Serve

func Serve(b Bot, opts ...ServeOption)

Types

type Bot

type Bot struct {
	Name     string
	Handlers map[EventType]EventHandlerFunc
}

func NewBot added in v0.5.156

func NewBot(name string, opts ...BotOptions) Bot
Example
package main

import (
	"context"
	"fmt"

	"github.com/chainguard-dev/terraform-infra-common/modules/github-bots/sdk"
	"github.com/google/go-github/v84/github"
)

func main() {
	bot := sdk.NewBot("my-bot",
		sdk.BotWithHandler(
			sdk.PullRequestHandler(func(_ context.Context, pre github.PullRequestEvent) error {
				fmt.Printf("handling PR #%d\n", pre.GetNumber())
				return nil
			}),
		),
	)
	fmt.Println(bot.Name)
}
Output:
my-bot

func (*Bot) RegisterHandler added in v0.5.156

func (b *Bot) RegisterHandler(handler EventHandlerFunc)
Example
package main

import (
	"context"
	"fmt"

	"github.com/chainguard-dev/terraform-infra-common/modules/github-bots/sdk"
	"github.com/google/go-github/v84/github"
)

func main() {
	bot := sdk.NewBot("my-bot")
	bot.RegisterHandler(
		sdk.PushHandler(func(_ context.Context, _ github.PushEvent) error {
			return nil
		}),
	)
	fmt.Println(len(bot.Handlers))
}
Output:
1

type BotOptions added in v0.5.156

type BotOptions func(*Bot)

func BotWithHandler added in v0.5.156

func BotWithHandler(handler EventHandlerFunc) BotOptions

type CheckRunHandler added in v0.5.156

type CheckRunHandler func(ctx context.Context, pre github.CheckRunEvent) error

func (CheckRunHandler) EventType added in v0.5.156

func (r CheckRunHandler) EventType() EventType

type CheckSuiteHandler added in v0.5.156

type CheckSuiteHandler func(ctx context.Context, pre github.CheckSuiteEvent) error

func (CheckSuiteHandler) EventType added in v0.5.156

func (r CheckSuiteHandler) EventType() EventType

type CloneOpts added in v0.5.156

type CloneOpts struct {
	// Shallow indicates whether to perform a shallow clone (depth 1).
	Shallow bool
}

CloneOpts contains options for cloning a repository.

type EventHandlerFunc added in v0.5.156

type EventHandlerFunc interface {
	EventType() EventType
}

type EventType added in v0.5.156

type EventType string
const (
	// GitHub events (https://github.com/chainguard-dev/terraform-infra-common/tree/main/modules/github-events)
	PullRequestEvent        EventType = "dev.chainguard.github.pull_request"
	WorkflowRunEvent        EventType = "dev.chainguard.github.workflow_run"
	IssuesEvent             EventType = "dev.chainguard.github.issues"
	IssueCommentEvent       EventType = "dev.chainguard.github.issue_comment"
	PushEvent               EventType = "dev.chainguard.github.push"
	CheckRunEvent           EventType = "dev.chainguard.github.check_run"
	CheckSuiteEvent         EventType = "dev.chainguard.github.check_suite"
	ProjectsV2ItemEventType EventType = "dev.chainguard.github.projects_v2_item"

	// LoFo events
	WorkflowRunArtifactEvent EventType = "dev.chainguard.lofo.workflow_run_artifacts"
	WorkflowRunLogsEvent     EventType = "dev.chainguard.lofo.workflow_run_logs"
)

type GitHubClient

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

func NewGitHubClient

func NewGitHubClient(ctx context.Context, org, repo, policyName string, opts ...GitHubClientOption) GitHubClient

NewGitHubClient creates a new GitHub client, using a new token from OctoSTS, for the given org, repo and policy name.

A new token is created for each client, and is not refreshed. It can be revoked with Close.

func NewInstallationClient added in v0.5.156

func NewInstallationClient(ctx context.Context, org, repo string, tr *ghinstallation.Transport, opts ...GitHubClientOption) GitHubClient

func (GitHubClient) AddComment added in v0.5.156

func (c GitHubClient) AddComment(ctx context.Context, pr *github.PullRequest, botName, content string) error

AddComment adds a new comment to the given pull request.

func (GitHubClient) AddLabel

func (c GitHubClient) AddLabel(ctx context.Context, pr *github.PullRequest, label string) error

func (GitHubClient) Client

func (c GitHubClient) Client() *github.Client

func (GitHubClient) CloneRepo added in v0.5.156

func (c GitHubClient) CloneRepo(ctx context.Context, ref, destDir string, opts *CloneOpts) (*git.Repository, error)

CloneRepo clones the repository into a destination directory, and checks out a ref.

ref should be "refs/heads/<branch>" or "refs/tags/<tag>" or "refs/pull/<pr>/merge" or a commit SHA. destDir is the directory to clone the repository into. It will be created if it doesn't exist. if opts is nil, a full clone will be performed.

It returns the git.Repository object for the cloned repository.

func (GitHubClient) Close

func (c GitHubClient) Close(ctx context.Context) error

func (GitHubClient) CompareCommits added in v0.7.9

func (c GitHubClient) CompareCommits(ctx context.Context, owner, repo, base, head string, opts *github.ListOptions) (*github.CommitsComparison, error)

CompareCommits fetches the differences between two commits

func (GitHubClient) FetchWorkflowRunArtifact added in v0.5.156

func (c GitHubClient) FetchWorkflowRunArtifact(ctx context.Context, wr *github.WorkflowRun, name string) (*zip.Reader, error)

FetchWorkflowRunArtifact returns a zip reader for the artifact with `name` from the given WorkflowRun.

func (GitHubClient) FetchWorkflowRunLogs added in v0.5.156

func (c GitHubClient) FetchWorkflowRunLogs(ctx context.Context, wr *github.WorkflowRun, store httpreaderat.Store) (*zip.Reader, error)

FetchWorkflowRunLogs returns a Reader for the logs of the given WorkflowRun

func (GitHubClient) GetCommitDetails added in v0.7.9

func (c GitHubClient) GetCommitDetails(ctx context.Context, owner, repo, sha string, opts *github.ListOptions) (*github.RepositoryCommit, error)

GetCommitDetails fetches the details of a single commit

func (GitHubClient) GetFileContent added in v0.5.156

func (c GitHubClient) GetFileContent(ctx context.Context, owner, repo, path, ref string) (string, error)

GetFileContent fetches the content of a file at a given ref

func (GitHubClient) GetRelease added in v0.5.156

func (c GitHubClient) GetRelease(ctx context.Context, owner, repo, tag string) (*github.RepositoryRelease, error)

GetRelease fetches the release by tag

func (GitHubClient) GetWorkflowRunArtifact deprecated added in v0.5.156

func (c GitHubClient) GetWorkflowRunArtifact(ctx context.Context, wr *github.WorkflowRun, name string) (*zip.Reader, error)

Deprecated: Use FetchWorkflowRunArtifact instead.

func (GitHubClient) GetWorkflowRunLogs deprecated added in v0.5.156

func (c GitHubClient) GetWorkflowRunLogs(ctx context.Context, wre github.WorkflowRunEvent) ([]byte, error)

Deprecated: use FetchWorkflowRunLogs instead.

func (GitHubClient) GetWorkloadRunPullRequestNumber added in v0.5.156

func (c GitHubClient) GetWorkloadRunPullRequestNumber(ctx context.Context, wre github.WorkflowRunEvent) (int, error)

func (GitHubClient) GitAuth added in v0.5.156

func (c GitHubClient) GitAuth() (transport.AuthMethod, error)

GitAuth returns a go-git transport.AuthMethod using the GitHubClient's credentials. This is useful for authentication in go-git operations like cloning and fetching repositories.

func (GitHubClient) ListArtifactsFunc added in v0.5.156

func (c GitHubClient) ListArtifactsFunc(ctx context.Context, wr *github.WorkflowRun, opt *github.ListOptions, f func(artifact *github.Artifact) (bool, error)) error

ListArtifactsFunc executes a paginated list of all artifacts for a given workflow run and executes the provided function on each of the artifacts. The provided function should return a boolean to indicate whether the list operation can stop making API calls.

func (GitHubClient) ListFiles added in v0.5.156

func (c GitHubClient) ListFiles(ctx context.Context, owner, repo, path, ref string) ([]*github.RepositoryContent, error)

ListFiles lists the files in a directory at a given ref

func (GitHubClient) RemoveLabel

func (c GitHubClient) RemoveLabel(ctx context.Context, pr *github.PullRequest, label string) error

func (GitHubClient) RepoURL added in v0.5.156

func (c GitHubClient) RepoURL() (string, error)

RepoURL returns the HTTPS git URL of the GitHubClient's configured repository.

func (GitHubClient) SearchContentInFilename added in v0.5.156

func (c GitHubClient) SearchContentInFilename(ctx context.Context, owner, repo, path, content string, opt *github.ListOptions) (*github.CodeSearchResult, error)

SearchContentInFilename searches for a text in a filename in a specific repository

func (GitHubClient) SearchFilenameInRepository added in v0.5.156

func (c GitHubClient) SearchFilenameInRepository(ctx context.Context, owner, repo, path string, opt *github.ListOptions) (*github.CodeSearchResult, error)

SearchFilenameInRepository searches for a filename in a specific repository

func (GitHubClient) SetComment

func (c GitHubClient) SetComment(ctx context.Context, pr *github.PullRequest, botName, content string) error

SetComment adds or replaces a bot comment on the given pull request.

type GitHubClientOption added in v0.5.156

type GitHubClientOption func(*GitHubClient)

GitHubClientOption configures the client, these are ran after the default setup.

func WithBufferSize added in v0.5.156

func WithBufferSize(bufSize int) GitHubClientOption

func WithClient added in v0.5.156

func WithClient(client *github.Client) GitHubClientOption

WithClient sets the inner GitHub client to the given client useful for testing

func WithSecondaryRateLimitWaiter added in v0.5.156

func WithSecondaryRateLimitWaiter() GitHubClientOption

WithSecondaryRateLimitWaiter is intended to change the underlying transport to respect GitHub's rate-limiting requests. As of today, it is a no-op. Using this option will not change the behavior of `GitHubClient`.

type IssueCommentHandler added in v0.5.156

type IssueCommentHandler func(ctx context.Context, ice github.IssueCommentEvent) error

func (IssueCommentHandler) EventType added in v0.5.156

func (r IssueCommentHandler) EventType() EventType

type IssuesHandler added in v0.5.156

type IssuesHandler func(ctx context.Context, ice github.IssueEvent) error

func (IssuesHandler) EventType added in v0.5.156

func (r IssuesHandler) EventType() EventType

type ProjectV2Item added in v0.5.156

type ProjectV2Item struct {
	ID            int64             `json:"id,omitempty"`
	NodeID        string            `json:"node_id,omitempty"`
	ProjectNodeID string            `json:"project_node_id,omitempty"`
	ContentNodeID string            `json:"content_node_id,omitempty"`
	ContentType   string            `json:"content_type,omitempty"`
	CreatedAt     *github.Timestamp `json:"created_at,omitempty"`
	UpdatedAt     *github.Timestamp `json:"updated_at,omitempty"`
	ArchivedAt    *github.Timestamp `json:"archived_at,omitempty"`
}

https://github.com/google/go-github/blob/v60.0.0/github/event_types.go#L1085

type ProjectsV2ItemEvent added in v0.5.156

type ProjectsV2ItemEvent struct {
	Action        string               `json:"action,omitempty"`
	Changes       json.RawMessage      `json:"changes,omitempty"`
	ProjectV2Item *ProjectV2Item       `json:"projects_v2_item,omitempty"`
	Organization  *github.Organization `json:"organization,omitempty"`
	Sender        *github.User         `json:"sender,omitempty"`
}

https://github.com/google/go-github/blob/v60.0.0/github/event_types.go#L1062

ProjectsV2ItemEvent represents a project_v2_item event. It's copied from go-github since their version only supports the `archived` action.

type ProjectsV2ItemHandler added in v0.5.156

type ProjectsV2ItemHandler func(ctx context.Context, pie ProjectsV2ItemEvent) error

func (ProjectsV2ItemHandler) EventType added in v0.5.156

func (r ProjectsV2ItemHandler) EventType() EventType

type PullRequestHandler added in v0.5.156

type PullRequestHandler func(ctx context.Context, pre github.PullRequestEvent) error

func (PullRequestHandler) EventType added in v0.5.156

func (r PullRequestHandler) EventType() EventType

type PushHandler added in v0.5.156

type PushHandler func(ctx context.Context, pre github.PushEvent) error

func (PushHandler) EventType added in v0.5.156

func (r PushHandler) EventType() EventType

type SecondaryRateLimitWaiter added in v0.5.156

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

SecondaryRateLimitWaiter

func (*SecondaryRateLimitWaiter) RoundTrip added in v0.5.156

func (w *SecondaryRateLimitWaiter) RoundTrip(req *http.Request) (*http.Response, error)

type ServeOption added in v1.0.5

type ServeOption func(*serveConfig)

ServeOption configures the Serve function.

func WithPort added in v1.0.5

func WithPort(port int) ServeOption

WithPort sets the port for the bot's HTTP server. If not provided, the PORT environment variable is used, defaulting to 8080.

type WorkflowRunArtifactHandler added in v0.5.156

type WorkflowRunArtifactHandler func(ctx context.Context, wre github.WorkflowRunEvent) error

func (WorkflowRunArtifactHandler) EventType added in v0.5.156

func (r WorkflowRunArtifactHandler) EventType() EventType

type WorkflowRunHandler added in v0.5.156

type WorkflowRunHandler func(ctx context.Context, wre github.WorkflowRunEvent) error

func (WorkflowRunHandler) EventType added in v0.5.156

func (r WorkflowRunHandler) EventType() EventType

type WorkflowRunLogsHandler added in v0.5.156

type WorkflowRunLogsHandler func(ctx context.Context, wre github.WorkflowRunEvent) error

func (WorkflowRunLogsHandler) EventType added in v0.5.156

func (r WorkflowRunLogsHandler) EventType() EventType

Directories

Path Synopsis
Package check provides utilities for creating and updating GitHub Check Runs.
Package check provides utilities for creating and updating GitHub Check Runs.
Package octosts provides utilities for working with OctoSTS bot users.
Package octosts provides utilities for working with OctoSTS bot users.

Jump to

Keyboard shortcuts

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