github

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 30 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 is the forge adapter for GitHub: github.com, GitHub Enterprise Cloud with data residency (api.<tenant>.ghe.com) and GitHub Enterprise Server (config.GitHub.BaseURL, https://ghe.example.com/api/v3).

Auth model

kōjō is a GitHub App. The adapter signs a short RS256 JWT with the App's private key, finds the installation that covers a repository and trades the JWT for an installation token. Installation tokens last about an hour; they are cached per installation and renewed five minutes before they expire. Every repository call uses the token of that repository's installation, so the App's permissions are the upper bound of what the core can do.

CloneCredentials asks for a separate token for each call, limited to the one repository with contents:read and metadata:read. That token goes to the egress proxy and can never push.

Webhooks are verified with the HMAC-SHA256 of the body in X-Hub-Signature-256, in constant time, before anything is decoded. A Forge without a webhook secret rejects every delivery.

Writes

CreateBranch and CommitFiles refuse any branch that is not kojo/*. CommitFiles uses the Git Data API (blobs, a tree on top of the branch's tree, a commit, a non-forced ref update), so no git binary and no repository hook runs in the core. It accepts regular files only: modes 100644 and 100755, and no path inside .git. With forge.WithExpectedHead it writes only while the branch is at that commit; the non-forced ref update refuses a push that lands in between.

Limitations

  • ListRepos does not fill RepoInfo.HeadSHA (it would cost one request per repository). GetRepo does.
  • ListIssues leaves pull requests out, although GitHub's issue list includes them.
  • ListPullRequests reads GET /pulls sorted by update, newest first. That list has no since filter, so the pages stop at the first pull request updated before it, and no merged state, so closed and merged are GitHub's "closed" told apart by merged_at. BaseSHA is base.sha; MergeCommitSHA is merge_commit_sha of a merged pull request (GitHub sets it to a test merge commit while one is open, which is dropped).
  • A push payload carries at most 2048 commits. Event.ChangedPaths is nil for a push at that limit, which means "unknown", not "nothing changed".
  • A failed check produces both a check_run and a check_suite delivery; both are reported as EventCheckFailed.
  • Mentions inside quoted text or code blocks count as mentions.
  • MergePR marks a draft pull request ready for review before it merges it, through the GraphQL API (the REST API cannot do it).
  • A 403 that GitHub sends for a rate limit is not reported as forge.ErrUnauthorized.
  • The App has no workflows permission, so GitHub rejects a commit that changes a file under .github/workflows.

Index

Constants

View Source
const Name = "github"

Name is the forge name of this adapter.

View Source
const WebhookPath = "/webhooks/github"

WebhookPath is where the core receives GitHub deliveries, below the public URL.

Variables

This section is empty.

Functions

func Manifest

func Manifest(publicURL string, opts ManifestOptions) ([]byte, error)

Manifest returns the GitHub App manifest, as JSON, for a kōjō reachable at publicURL. The setup command posts it to ManifestFormURL in a form field named "manifest"; GitHub answers with a code for ExchangeManifestCode.

The App receives webhooks at publicURL + WebhookPath, has the minimal permissions (contents and pull requests and issues: write; checks, statuses, metadata and administration: read) and subscribes to the events ParseWebhook handles.

func ManifestFormURL

func ManifestFormURL(baseURL, org, state string) (string, error)

ManifestFormURL is the page the manifest is posted to: the App settings of the signed-in user, or of org when org is set. baseURL is config.GitHub.BaseURL (empty for github.com). state comes back with the code, to tie the redirect to the request.

Types

type AppCredentials

type AppCredentials struct {
	// AppID goes into config.GitHub.AppID.
	AppID string
	// Slug is the App's URL name; its bot account is "<slug>[bot]".
	Slug string
	Name string
	// Owner is the user or organization that owns the App.
	Owner string
	// HTMLURL is the App's public page, where it is installed from.
	HTMLURL string
	// PrivateKey is the PEM private key (config.GitHub.PrivateKey).
	PrivateKey string
	// WebhookSecret goes into config.GitHub.WebhookSecret.
	WebhookSecret string
	// ClientID and ClientSecret are the App's OAuth credentials. kōjō does
	// not use them.
	ClientID     string
	ClientSecret string
}

AppCredentials is what GitHub returns once for a new App. Everything but the ID, slug and URLs is a secret.

func ExchangeManifestCode

func ExchangeManifestCode(ctx context.Context, baseURL, code string, opts ...Option) (*AppCredentials, error)

ExchangeManifestCode trades the temporary code of the manifest flow for the new App's credentials. The code is valid for one hour and one use. baseURL is config.GitHub.BaseURL (empty for github.com). Of the options, WithHTTPClient and WithLogger apply.

type Forge

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

Forge is a GitHub App on github.com or on a GitHub Enterprise instance. It is safe for concurrent use.

func New

func New(cfg config.GitHub, opts ...Option) (*Forge, error)

New builds the adapter from the deployment config. It reads and parses the App's private key but makes no request.

func (*Forge) BotLogin

func (f *Forge) BotLogin(ctx context.Context) (string, error)

BotLogin is the App's bot account, "<slug>[bot]".

func (*Forge) BranchProtection

func (f *Forge) BranchProtection(ctx context.Context, repo forge.Repo, branch string) (*forge.Protection, error)

BranchProtection merges the two ways GitHub protects a branch: rulesets and classic branch protection. Protected is true when either applies. Reading classic protection needs the administration:read permission.

func (*Forge) Check

func (f *Forge) Check(ctx context.Context) error

Check verifies that GitHub is reachable with the App's key and that the App can do what kōjō needs. It returns one joined error naming every problem: a missing webhook secret, each permission the App lacks, each event it is not subscribed to, and each installation that has not accepted the App's current permissions.

func (*Forge) CheckRuns

func (f *Forge) CheckRuns(ctx context.Context, repo forge.Repo, sha string) ([]forge.CheckRun, error)

CheckRuns lists the check runs of a commit, then its commit statuses, each with the output GitHub keeps for it: a check run's title, summary and text, a status's description. The states are read as ChecksStatus reads them.

func (*Forge) ChecksStatus

func (f *Forge) ChecksStatus(ctx context.Context, repo forge.Repo, sha string) (forge.ChecksState, error)

ChecksStatus combines the check runs of a commit with its commit statuses: failure if anything failed, else pending if anything is still running, else success, and none when the commit has neither.

func (*Forge) CloneCredentials

func (f *Forge) CloneCredentials(ctx context.Context, repo forge.Repo) ([]sandbox.HostCredential, error)

CloneCredentials returns a fresh installation token that can only read the contents of repo, as one credential for the git host (Basic) and one for the API host (Bearer). On Enterprise Server both are the same host, so it returns the Basic credential alone: the API accepts it too.

func (*Forge) Comment

func (f *Forge) Comment(ctx context.Context, repo forge.Repo, number int, body string) (*forge.Comment, error)

Comment posts a comment on an issue or pull request.

func (*Forge) CommitFiles

func (f *Forge) CommitFiles(ctx context.Context, repo forge.Repo, branch, message string, changes []forge.FileChange) (string, error)

CommitFiles writes one commit on top of branch, which must be kojo/* and exist, and returns the commit's SHA. It uploads a blob per file, builds a tree on the branch's tree, commits it and moves the branch without force: when the branch moved in the meantime the update fails and nothing is lost. With forge.WithExpectedHead it starts only when the branch is at that commit, and a branch that moved after it was read is forge.ErrHeadMoved too. The commit is authored by the App's bot and signed by GitHub.

func (*Forge) CreateBranch

func (f *Forge) CreateBranch(ctx context.Context, repo forge.Repo, name, fromSHA string) error

CreateBranch creates the branch name at fromSHA. name must be kojo/*. It fails if the branch exists.

func (*Forge) GetFile

func (f *Forge) GetFile(ctx context.Context, repo forge.Repo, ref, filePath string) ([]byte, error)

GetFile reads one file at ref (a branch, tag or commit; empty means the default branch). A directory, a submodule or a missing path is forge.ErrNotFound.

func (*Forge) GetIssue

func (f *Forge) GetIssue(ctx context.Context, repo forge.Repo, number int) (*forge.Issue, error)

GetIssue reads an issue. A pull request number returns its issue side, with IsPR set.

func (*Forge) GetPR

func (f *Forge) GetPR(ctx context.Context, repo forge.Repo, number int) (*forge.PullRequest, error)

GetPR reads a pull request.

func (*Forge) GetPRDiff

func (f *Forge) GetPRDiff(ctx context.Context, repo forge.Repo, number int) (string, error)

GetPRDiff returns the unified diff of a pull request.

func (*Forge) GetRepo

func (f *Forge) GetRepo(ctx context.Context, repo forge.Repo) (*forge.RepoInfo, error)

GetRepo describes a repository and the head of its default branch. HeadSHA is empty for a repository without commits.

func (*Forge) ListComments

func (f *Forge) ListComments(ctx context.Context, repo forge.Repo, number int) ([]forge.Comment, error)

ListComments lists the comments of an issue or pull request, oldest first. Review comments on a diff are not included.

func (*Forge) ListFiles

func (f *Forge) ListFiles(ctx context.Context, repo forge.Repo, ref, dir string) ([]string, error)

ListFiles lists the files under dir at ref, recursively and sorted, as paths relative to the repository root. Submodules are left out. A ref that does not exist is forge.ErrNotFound; a dir that does not exist is an empty list.

func (*Forge) ListIssues

func (f *Forge) ListIssues(ctx context.Context, repo forge.Repo, opts forge.ListIssuesOptions) ([]forge.Issue, error)

ListIssues lists issues, newest first, without pull requests.

func (*Forge) ListPullRequests

func (f *Forge) ListPullRequests(ctx context.Context, repo forge.Repo, opts forge.ListPullRequestsOptions) ([]forge.PullRequest, error)

ListPullRequests lists pull requests, the most recently updated first. GitHub's list knows neither a merged state nor a since filter: closed and merged are both its "closed", told apart by merged_at, and the pages stop at the first pull request updated before opts.Since.

func (*Forge) ListRepos

func (f *Forge) ListRepos(ctx context.Context) ([]forge.RepoInfo, error)

ListRepos lists the repositories of every installation of the App that is not suspended. HeadSHA is not filled.

func (*Forge) ListReviewComments

func (f *Forge) ListReviewComments(ctx context.Context, repo forge.Repo, number int) ([]forge.ReviewComment, error)

ListReviewComments lists the review of a pull request, oldest first: the comments on lines of its diff (GET /pulls/{n}/comments) and the text of each submitted review (GET /pulls/{n}/reviews). A review without text is left out; its comments on lines are listed on their own.

func (*Forge) MergePR

func (f *Forge) MergePR(ctx context.Context, repo forge.Repo, number int, method, headSHA string) error

MergePR merges a pull request. method is merge (the default), squash or rebase. A draft is marked ready for review first, because GitHub does not merge drafts.

func (*Forge) Name

func (f *Forge) Name() string

Name is "github".

func (*Forge) OpenPR

func (f *Forge) OpenPR(ctx context.Context, repo forge.Repo, req forge.PRRequest) (*forge.PullRequest, error)

OpenPR opens a pull request from req.Head into req.Base, as a draft when req.Draft is set.

func (*Forge) ParseWebhook

func (f *Forge) ParseWebhook(r *http.Request, body []byte) (*forge.Event, error)

ParseWebhook verifies the HMAC of a delivery and normalizes it.

It returns forge.ErrBadSignature when the signature is missing or wrong, and forge.ErrIgnored for a ping, an event or action kōjō does not handle, a comment on an issue that does not mention the bot and anything the bot did itself. A failed check, a closed pull request and a push are reported whoever caused them, except a push by the bot to one of its own kojo/* branches.

func (*Forge) Permission

func (f *Forge) Permission(ctx context.Context, repo forge.Repo, user string) (forge.Permission, error)

Permission returns a user's role on a repository. A user GitHub does not know, or one without access, has PermissionNone. On a public repository everyone has at least PermissionRead.

func (*Forge) UpdatePR

func (f *Forge) UpdatePR(ctx context.Context, repo forge.Repo, number int, title, body string) error

UpdatePR changes a pull request's title and description with one PATCH. An empty title or body is left out, so that one stays as it is; with both empty nothing is sent. GitHub keeps the draft state in a flag of its own, so a new title does not change it.

type ManifestOptions

type ManifestOptions struct {
	// Name is the App's name, which also becomes its slug and the login
	// people mention. App names are unique on a GitHub instance. Default
	// "kojo".
	Name string
	// RedirectURL is where GitHub sends the browser, with ?code=..., once
	// the App is created. The setup command listens there.
	RedirectURL string
	// Public lets other accounts install the App. Default false: only the
	// owner can.
	Public bool
}

ManifestOptions are the parts of an App manifest that do not follow from the public URL.

type Option

type Option func(*options)

Option configures New and ExchangeManifestCode.

func WithAppSlug

func WithAppSlug(slug string) Option

WithAppSlug sets the App's slug (the "kojo" of "kojo[bot]"), which saves the request that looks it up. The setup command knows it from the manifest exchange.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock used for JWTs and token expiry. The default is time.Now.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client. The default has a 30 second timeout.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger. The default is slog.Default.

Jump to

Keyboard shortcuts

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