forge

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: 6 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 forge is the interface the core uses to talk to a code forge (GitHub, GitLab, Forgejo/Gitea). Every forge call, and every push, is made by the core with short-lived tokens: nothing in a sandbox holds one.

Pushes go through the forge's API (CommitFiles), not a git binary, so the core never runs repository hooks or any other repository code.

Index

Constants

View Source
const (
	PROpen   = "open"
	PRClosed = "closed" // closed without being merged
	PRMerged = "merged"
	PRAll    = "all" // a filter only
)

Pull request states, in PullRequest.State and ListPullRequestsOptions.

View Source
const (
	ReviewApproved         = "approved"
	ReviewChangesRequested = "changes_requested"
	ReviewCommented        = "commented"
)

Review verdicts, in Event.ReviewState.

View Source
const MaxCheckOutput = 16 << 10

MaxCheckOutput bounds CheckRun.Output, in bytes.

View Source
const MaxReviewComments = 300

MaxReviewComments bounds what ListReviewComments returns: the oldest ones of a longer review are left out.

Variables

View Source
var (
	ErrNotFound = errors.New("forge: not found")
	// ErrHeadMoved: a pull request's head is no longer the commit the
	// caller decided on.
	ErrHeadMoved    = errors.New("forge: the pull request's head moved")
	ErrUnauthorized = errors.New("forge: unauthorized")
	// ErrBadSignature is returned by ParseWebhook for a request whose
	// signature or token does not verify.
	ErrBadSignature = errors.New("forge: webhook signature does not verify")
	// ErrIgnored is returned by ParseWebhook for a delivery kōjō has no use
	// for (a ping, an event type it does not handle, its own comment).
	ErrIgnored = errors.New("forge: event ignored")
)

Errors a forge returns for the cases the core handles.

Functions

func ExpectedHead

func ExpectedHead(ctx context.Context) (sha string, ok bool)

ExpectedHead reads the mark WithExpectedHead left. ok is false when the context carries none.

func IsPullRequest

func IsPullRequest(ctx context.Context) (isPR, known bool)

IsPullRequest reads the mark WithPullRequest left. known is false when the context carries none.

func Keep

func Keep(s string, n int) string

Keep keeps the last n bytes of s at a character boundary: the end of a log is where it says what failed.

func WithExpectedHead

func WithExpectedHead(ctx context.Context, sha string) context.Context

WithExpectedHead marks ctx for CommitFiles with the commit the caller built its change on: the commit is written only while the branch still points there, and on top of it. When the branch moved, CommitFiles writes nothing and returns ErrHeadMoved. The core sets it when it adds a commit to a branch that people can push to as well (a follow-up on one of its pull requests), so that nothing they pushed is overwritten.

func WithPullRequest

func WithPullRequest(ctx context.Context, isPR bool) context.Context

WithPullRequest marks ctx with what a number passed to GetIssue, ListComments or Comment refers to: a pull request or an issue. GitHub and Forgejo number both in one sequence and ignore it; GitLab numbers merge requests and issues separately and needs it. The core sets it from the request it is working on.

Types

type CheckRun

type CheckRun struct {
	Name string `json:"name"`
	// State is success, failure or pending. A check that was skipped or
	// gave a neutral result counts as success, as it does for
	// ChecksStatus.
	State ChecksState `json:"state"`
	// Output is what the forge says about the result, where it says
	// anything: a check run's title, summary and text, or a commit
	// status's description (GitHub); the end of a failed job's log, after
	// its failure reason (GitLab); a commit status's description (Forgejo,
	// Gitea). It is cut to MaxCheckOutput bytes, keeping the end, where a
	// log says what failed.
	Output string `json:"output,omitempty"`
	URL    string `json:"url,omitempty"`
}

CheckRun is one check of a commit: a check run or a commit status on GitHub, a job of a pipeline on GitLab, a commit status on Forgejo and Gitea.

type ChecksState

type ChecksState string

ChecksState is the combined state of a commit's checks.

const (
	ChecksPending ChecksState = "pending"
	ChecksSuccess ChecksState = "success"
	ChecksFailure ChecksState = "failure"
	ChecksNone    ChecksState = "none"
)

Combined check states.

type Comment

type Comment struct {
	ID        string    `json:"id"`
	Author    string    `json:"author"`
	Body      string    `json:"body"`
	HTMLURL   string    `json:"html_url"`
	CreatedAt time.Time `json:"created_at"`
}

Comment is a comment on an issue or pull request.

type Event

type Event struct {
	Kind EventKind `json:"kind"`
	Repo Repo      `json:"repo"`
	// Actor is the login of the user who caused the event.
	Actor string `json:"actor"`
	// Number is the issue or pull request number, when there is one.
	Number int  `json:"number,omitempty"`
	IsPR   bool `json:"is_pr,omitempty"`
	// Title of the issue or pull request.
	Title string `json:"title,omitempty"`
	// Text is the comment or body that carries the request.
	Text string `json:"text,omitempty"`
	// CommentID is the comment that triggered a mention.
	CommentID string `json:"comment_id,omitempty"`
	// Ref and SHA name the branch and commit of a push or check.
	Ref string `json:"ref,omitempty"`
	SHA string `json:"sha,omitempty"`
	// ChangedPaths are the files a push touched, when the payload has them.
	// Nil means unknown (a truncated payload), not "none".
	ChangedPaths []string `json:"changed_paths,omitempty"`
	// DeliveryID is the forge's ID of the delivery, for de-duplication.
	DeliveryID string `json:"delivery_id,omitempty"`
	HTMLURL    string `json:"html_url,omitempty"`
	// ReviewState is the verdict of an EventPRReview: approved,
	// changes_requested or commented.
	ReviewState string `json:"review_state,omitempty"`
	// Path, Line and DiffHunk place an EventPRReviewComment: the file, the
	// line in it, and the part of the diff the comment is on. A forge that
	// does not send one of them leaves it empty.
	Path     string `json:"path,omitempty"`
	Line     int    `json:"line,omitempty"`
	DiffHunk string `json:"diff_hunk,omitempty"`
	// Merged says whether an EventPRClosed was a merge.
	Merged bool `json:"merged,omitempty"`
}

Event is one normalized webhook delivery.

type EventKind

type EventKind string

EventKind is what happened on the forge.

const (
	// EventMention is a comment (or a new issue/PR body) that mentions the
	// bot. Text holds the comment.
	EventMention EventKind = "mention"
	// EventIssueOpened is a new issue.
	EventIssueOpened EventKind = "issue_opened"
	// EventPROpened is a new or reopened pull request, or one marked ready.
	EventPROpened EventKind = "pr_opened"
	// EventPRUpdated is new commits on a pull request.
	EventPRUpdated EventKind = "pr_updated"
	// EventCheckFailed is a failed check run or pipeline on a branch.
	EventCheckFailed EventKind = "check_failed"
	// EventPush is a push to a branch. kōjō uses pushes to the default
	// branch to reload a repository's .factory/ files.
	EventPush EventKind = "push"
	// EventPRComment is a comment on a pull request's conversation that
	// does not mention the bot. One that does is an EventMention.
	EventPRComment EventKind = "pr_comment"
	// EventPRReview is a submitted review that has a body. ReviewState
	// holds its verdict. A review without text is not reported.
	EventPRReview EventKind = "pr_review"
	// EventPRReviewComment is a review comment on a line of a pull
	// request's diff. Path, Line and DiffHunk say where, as far as the
	// forge's payload does.
	EventPRReviewComment EventKind = "pr_review_comment"
	// EventPRClosed is a pull request that was merged (Merged) or closed
	// without merging. It is reported whoever closed it, the bot included.
	EventPRClosed EventKind = "pr_closed"
)

Event kinds kōjō acts on.

func (EventKind) IsFeedback

func (k EventKind) IsFeedback() bool

IsFeedback reports whether the event is something a person wrote about a pull request without addressing the bot: what kōjō learns from when the pull request is its own.

type FileChange

type FileChange struct {
	Path string
	// Content is the new content. Ignored when Delete is set.
	Content []byte
	// Mode is the git file mode: "100644" (default) or "100755".
	Mode   string
	Delete bool
}

FileChange is one file of a commit.

type Forge

type Forge interface {
	// Name is github, gitlab or forgejo.
	Name() string
	// BotLogin is the account kōjō acts as; mentions of it trigger work and
	// its own comments are ignored.
	BotLogin(ctx context.Context) (string, error)

	// ParseWebhook verifies and decodes one webhook delivery.
	ParseWebhook(r *http.Request, body []byte) (*Event, error)

	GetRepo(ctx context.Context, repo Repo) (*RepoInfo, error)
	// ListRepos lists the repositories kōjō was installed on or can reach.
	// HeadSHA is left empty: filling it would cost a request per repository.
	ListRepos(ctx context.Context) ([]RepoInfo, error)
	GetIssue(ctx context.Context, repo Repo, number int) (*Issue, error)
	// ListIssues lists issues. Pull requests are never part of the list.
	ListIssues(ctx context.Context, repo Repo, opts ListIssuesOptions) ([]Issue, error)
	// ListPullRequests lists pull requests, the most recently updated
	// first, following pages up to opts.Limit.
	ListPullRequests(ctx context.Context, repo Repo, opts ListPullRequestsOptions) ([]PullRequest, error)
	ListComments(ctx context.Context, repo Repo, number int) ([]Comment, error)
	GetPR(ctx context.Context, repo Repo, number int) (*PullRequest, error)
	// GetPRDiff returns the unified diff of a pull request.
	GetPRDiff(ctx context.Context, repo Repo, number int) (string, error)
	// GetFile reads one file at ref. It returns ErrNotFound when missing.
	GetFile(ctx context.Context, repo Repo, ref, path string) ([]byte, error)
	// ListFiles lists the files under dir at ref, recursively, as paths
	// relative to the repository root. A missing dir is an empty list.
	ListFiles(ctx context.Context, repo Repo, ref, dir string) ([]string, error)
	// Permission returns the access level of a user on a repo.
	Permission(ctx context.Context, repo Repo, user string) (Permission, error)
	// BranchProtection describes the protection of a branch. Protected is
	// false when there is none.
	BranchProtection(ctx context.Context, repo Repo, branch string) (*Protection, error)
	// ChecksStatus summarizes the checks of a commit.
	ChecksStatus(ctx context.Context, repo Repo, sha string) (ChecksState, error)
	// CheckRuns lists the checks of a commit, each with its state and,
	// where the forge keeps it, its output. It only reads.
	CheckRuns(ctx context.Context, repo Repo, sha string) ([]CheckRun, error)
	// ListReviewComments lists the review of a pull request, oldest first:
	// the comments on lines of its diff and the text of each submitted
	// review, at most MaxReviewComments of them, the newest. The comments
	// on its conversation are ListComments'. It only reads.
	ListReviewComments(ctx context.Context, repo Repo, number int) ([]ReviewComment, error)

	// Comment posts a comment on an issue or pull request.
	Comment(ctx context.Context, repo Repo, number int, body string) (*Comment, error)
	// CreateBranch creates a branch at fromSHA. It fails if it exists.
	CreateBranch(ctx context.Context, repo Repo, name, fromSHA string) error
	// CommitFiles writes one commit on top of branch and returns its SHA.
	// With WithExpectedHead on ctx it writes only while the branch points
	// at that commit, and returns ErrHeadMoved otherwise.
	CommitFiles(ctx context.Context, repo Repo, branch, message string, changes []FileChange) (string, error)
	OpenPR(ctx context.Context, repo Repo, req PRRequest) (*PullRequest, error)
	// UpdatePR changes the title and the description of a pull request. An
	// empty title or body leaves that one as it is, so a description cannot
	// be emptied; with both empty nothing is sent. The draft state stays as
	// it is: where a forge reads it from the title (GitLab, Forgejo), the
	// adapter keeps or drops the title's prefix to match.
	UpdatePR(ctx context.Context, repo Repo, number int, title, body string) error
	// MergePR merges a pull request. Only the merge policy calls it. A draft
	// is marked ready first, since no forge merges a draft. headSHA is the
	// commit the caller decided on (the one whose checks it read): when the
	// pull request's head is another commit, nothing is changed and
	// ErrHeadMoved is returned, and the forge is asked to refuse a push that
	// lands between that comparison and the merge. An empty headSHA pins the
	// merge to the head found.
	MergePR(ctx context.Context, repo Repo, number int, method, headSHA string) error

	// CloneCredentials returns credentials for cloning repo over HTTPS: one
	// HostCredential per host the sandbox needs (the git host, the API
	// host), each marked ReadOnly so the proxy sets it only on requests
	// that cannot write. Where the forge supports it (GitHub Apps) they are
	// also short-lived and scoped to the repository; GitLab and Forgejo
	// return the configured token. They are handed to the proxy, never to
	// the sandbox.
	CloneCredentials(ctx context.Context, repo Repo) ([]sandbox.HostCredential, error)
	// Check verifies the forge is reachable and the app or token has the
	// permissions kōjō needs. It is what kojo doctor runs.
	Check(ctx context.Context) error
}

Forge is one configured forge.

type Issue

type Issue struct {
	Number    int       `json:"number"`
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	State     string    `json:"state"` // open, closed
	Author    string    `json:"author"`
	Labels    []string  `json:"labels,omitempty"`
	HTMLURL   string    `json:"html_url"`
	IsPR      bool      `json:"is_pr,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Issue is an issue (or the issue side of a pull request).

type ListIssuesOptions

type ListIssuesOptions struct {
	State  string // open (default), closed, all
	Labels []string
	Since  time.Time
	Limit  int // default 50
}

ListIssuesOptions filters ListIssues.

type ListPullRequestsOptions

type ListPullRequestsOptions struct {
	// State is open (default), closed (closed without being merged),
	// merged, or all.
	State string
	// Since keeps the pull requests updated at or after it. A merge updates
	// a pull request, so every pull request merged in a time range is among
	// the merged ones listed with Since at the range's start; keep those
	// whose MergedAt falls in the range, since one merged earlier and
	// commented on later is listed too.
	Since time.Time
	// Limit is the most pull requests returned. Default 50; the adapters
	// follow pages until they have that many.
	Limit int
	// WithBaseSHA fills BaseSHA where the forge's list leaves it out:
	// GitLab's list of merge requests has no diff_refs, so the adapter
	// reads each merge request, one request each. GitHub and Forgejo fill
	// BaseSHA either way.
	WithBaseSHA bool
}

ListPullRequestsOptions filters ListPullRequests.

type PRRequest

type PRRequest struct {
	Head  string
	Base  string
	Title string
	Body  string
	// Draft opens the pull request as a draft. The adapters honour it as
	// given: the merge policy decides, and draft is what it defaults to.
	Draft bool
}

PRRequest opens a pull request.

type Permission

type Permission string

Permission is a user's access level on a repository.

const (
	PermissionNone     Permission = "none"
	PermissionRead     Permission = "read"
	PermissionTriage   Permission = "triage"
	PermissionWrite    Permission = "write"
	PermissionMaintain Permission = "maintain"
	PermissionAdmin    Permission = "admin"
)

Access levels, weakest first.

func (Permission) AtLeast

func (p Permission) AtLeast(min Permission) bool

AtLeast reports whether p grants at least min.

type Protection

type Protection struct {
	Protected bool `json:"protected"`
	// RequiredChecks lists the status checks that must pass.
	RequiredChecks []string `json:"required_checks,omitempty"`
	// RequiredReviews is the number of approving reviews required.
	RequiredReviews int `json:"required_reviews,omitempty"`
}

Protection describes a branch's protection.

type PullRequest

type PullRequest struct {
	Number int    `json:"number"`
	Title  string `json:"title"`
	Body   string `json:"body"`
	State  string `json:"state"` // open, closed, merged
	Draft  bool   `json:"draft"`
	// Merged is true when State is merged.
	Merged  bool   `json:"merged,omitempty"`
	Author  string `json:"author"`
	Head    string `json:"head"` // branch
	HeadSHA string `json:"head_sha"`
	Base    string `json:"base"`
	BaseSHA string `json:"base_sha,omitempty"`
	// MergeCommitSHA is empty unless Merged.
	MergeCommitSHA string    `json:"merge_commit_sha,omitempty"`
	HTMLURL        string    `json:"html_url"`
	CreatedAt      time.Time `json:"created_at,omitzero"`
	UpdatedAt      time.Time `json:"updated_at,omitzero"`
	// MergedAt is zero unless Merged.
	MergedAt time.Time `json:"merged_at,omitzero"`
}

PullRequest is a pull (merge) request.

The three commits it names mean the same on every forge as far as the forges allow:

  • HeadSHA is the last commit of the head branch the forge knows of for the pull request.
  • BaseSHA is a commit of the base branch the pull request's changes apply to. On GitLab it is diff_refs.base_sha, the merge base of the latest diff version; on Forgejo and Gitea merge_base, the merge base the forge last computed. On GitHub it is base.sha, the base branch's commit as GitHub last recorded it for the pull request, which GitHub does not define further and need not be the merge base. Forgejo's own base.sha is the base branch's head at the time of the call, which says nothing about a pull request merged earlier, so it is not used. Empty when the forge does not say.
  • MergeCommitSHA is set only for a merged pull request: the commit the merge moved the base branch to. For a merge commit or a squash commit its first parent is the base branch right before the merge, the state of the code before the change. For a rebase or a fast-forward it is the pull request's last commit as it landed, so its first parent is the state before the change only when the pull request added one commit; otherwise BaseSHA is the commit the change was made against. GitHub reports it as merge_commit_sha (the merge commit, the squash commit, or the commit the base branch was rebased to); Forgejo as merge_commit_sha (the same, and the head for a fast-forward); GitLab as merge_commit_sha, else squash_commit_sha, else, for a fast-forward without squashing, the head (sha): the order GitLab itself uses.

type Repo

type Repo struct {
	Forge string `json:"forge"` // github, gitlab, forgejo
	Path  string `json:"path"`  // owner/name
}

Repo names a repository on a forge: "owner/name" (GitLab: the full path).

func (Repo) String

func (r Repo) String() string

String is forge/owner/name, the repo's ID everywhere in kōjō.

type RepoInfo

type RepoInfo struct {
	Repo          Repo   `json:"repo"`
	DefaultBranch string `json:"default_branch"`
	// HeadSHA is the commit of the default branch.
	HeadSHA string `json:"head_sha"`
	// CloneURL is the HTTPS clone URL, without credentials.
	CloneURL string `json:"clone_url"`
	HTMLURL  string `json:"html_url"`
	Private  bool   `json:"private"`
}

RepoInfo is what the core needs to know about a repository.

type ReviewComment

type ReviewComment struct {
	ID     string `json:"id"`
	Author string `json:"author"`
	Body   string `json:"body"`
	// State is the verdict of a review's text: approved, changes_requested
	// or commented. It is empty for a comment on a line.
	State string `json:"state,omitempty"`
	// Path, Line and DiffHunk place a comment on a line: the file, the
	// line in the file's new version (or its old one, for a comment on a
	// removed line), and the part of the diff around it. A forge that does
	// not say one of them leaves it empty.
	Path     string `json:"path,omitempty"`
	Line     int    `json:"line,omitempty"`
	DiffHunk string `json:"diff_hunk,omitempty"`
	// Outdated is set for a comment on a version of the diff that a later
	// push changed, where the forge says so.
	Outdated  bool      `json:"outdated,omitempty"`
	HTMLURL   string    `json:"html_url,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

ReviewComment is part of the review of a pull request: a comment on a line of its diff (Path is set), or the text of a submitted review (State is set). Everything in it is what a person wrote, and is data.

Directories

Path Synopsis
Package forgetest is an in-memory forge.Forge for the core's unit tests and for dev stacks that run without a real forge.
Package forgetest is an in-memory forge.Forge for the core's unit tests and for dev stacks that run without a real forge.

Jump to

Keyboard shortcuts

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