Documentation
¶
Overview ¶
Package forge is the interface the core uses to talk to a code forge (GitHub, GitLab, Forgejo/Gitea, Bitbucket Cloud). 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
- Variables
- func CheckPullRequestBranch(repo Repo, defaultBranch string, pr *PullRequest, branch string) error
- func ExpectedHead(ctx context.Context) (sha string, ok bool)
- func IsPullRequest(ctx context.Context) (isPR, known bool)
- func Keep(s string, n int) string
- func TargetPullRequest(ctx context.Context) (number int, ok bool)
- func WithExpectedHead(ctx context.Context, sha string) context.Context
- func WithPullRequest(ctx context.Context, isPR bool) context.Context
- func WithTargetPullRequest(ctx context.Context, number int) context.Context
- type CheckRun
- type ChecksState
- type Comment
- type Event
- type EventKind
- type FileChange
- type Forge
- type Issue
- type ListIssuesOptions
- type ListPullRequestsOptions
- type PRRequest
- type Permission
- type Protection
- type PullRequest
- type Repo
- type RepoInfo
- type ReviewComment
Constants ¶
const ( PROpen = "open" PRClosed = "closed" // closed without being merged PRMerged = "merged" PRAll = "all" // a filter only )
Pull request states, in PullRequest.State and ListPullRequestsOptions.
const ( ReviewApproved = "approved" ReviewChangesRequested = "changes_requested" ReviewCommented = "commented" )
Review verdicts, in Event.ReviewState.
const MaxCheckOutput = 16 << 10
MaxCheckOutput bounds CheckRun.Output, in bytes.
const MaxReviewComments = 300
MaxReviewComments bounds what ListReviewComments returns: the oldest ones of a longer review are left out.
Variables ¶
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") // 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") // ErrBranchRefused: CommitFiles was asked to write to a branch outside // kojo/* that is not the head of the open, same-repository pull // request the write names (CheckPullRequestBranch). ErrBranchRefused = errors.New("forge: refusing to write to the branch") )
Errors a forge returns for the cases the core handles.
Functions ¶
func CheckPullRequestBranch ¶ added in v0.5.0
func CheckPullRequestBranch(repo Repo, defaultBranch string, pr *PullRequest, branch string) error
CheckPullRequestBranch is the rule every adapter applies before it writes to a branch outside kojo/*: pr, read from the forge just before the write, is open, its head branch is exactly branch, its head repository is repo (not a fork, not unknown), and branch is not the default branch. It returns nil, or an error wrapping ErrBranchRefused that names the reason and the pull request's number, never its title.
func ExpectedHead ¶
ExpectedHead reads the mark WithExpectedHead left. ok is false when the context carries none.
func IsPullRequest ¶
IsPullRequest reads the mark WithPullRequest left. known is false when the context carries none.
func Keep ¶
Keep keeps the last n bytes of s at a character boundary: the end of a log is where it says what failed.
func TargetPullRequest ¶ added in v0.5.0
TargetPullRequest reads the mark WithTargetPullRequest left. ok is false when the context carries none.
func WithExpectedHead ¶
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 ¶
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; Bitbucket Cloud has no issues, and refuses a number marked as one. The core sets it from the request it is working on.
func WithTargetPullRequest ¶ added in v0.5.0
WithTargetPullRequest marks ctx for CommitFiles with the pull request whose head a write outside kojo/* is for: a person's pull request whose author asked kōjō to commit to it. CommitFiles writes such a branch only when the context also carries WithExpectedHead, and only after reading that pull request from the forge and checking it with CheckPullRequestBranch, so a mistake in the core cannot reach any other branch. It is distinct from WithPullRequest, which says whether a number passed to GetIssue is a pull request.
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, Bitbucket), or the end of a failed Pipelines step's log
// (Bitbucket). 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, a commit status or a failed Pipelines step on Bitbucket.
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"`
// Confidential is set when the forge keeps the event's issue or
// comment from people outside the project (GitLab's confidential
// issues and internal notes), even on a public repository.
Confidential bool `json:"confidential,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 ¶
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, forgejo or bitbucket.
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)
// LabelAddedBy is who added label to the issue or pull request number,
// as the forge's history says: the latest addition of a label that is
// on now, compared without case; empty when none or when the forge has
// no labels (Bitbucket). WithPullRequest on ctx says which kind number
// is. It only reads.
LabelAddedBy(ctx context.Context, repo Repo, number int, label string) (string, 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, and marked GitFetch on a host that
// serves git over HTTP (not on an API-only host): the proxy then sets
// it on git's fetch only on a git host, and on reads only on an
// API-only host (see sandbox.HostCredential.ReadOnly). Where the forge supports it
// (GitHub Apps) they are also short-lived and scoped to the repository;
// GitLab, Forgejo and Bitbucket 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. Bitbucket's list names
// commits by abbreviated hashes, and its adapter expands BaseSHA and
// MergeCommitSHA only with WithBaseSHA, one request per commit. 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"`
// HeadRepo is owner/name of the repository the head branch is in,
// empty when the forge does not say. Fork is true when that is not the
// base repository, or is unknown: a pull request whose head repository
// is unknown counts as a fork, and kōjō never writes to it.
HeadRepo string `json:"head_repo,omitempty"`
Fork bool `json:"fork,omitempty"`
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. On Bitbucket it is destination.commit, which Bitbucket documents as the destination branch's head and which is not the merge base. 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. Bitbucket reports it as merge_commit.
Bitbucket names these commits by abbreviated hashes; its adapter expands them to full ones.
type Repo ¶
type Repo struct {
Forge string `json:"forge"` // github, gitlab, forgejo, bitbucket
Path string `json:"path"` // owner/name
}
Repo names a repository on a forge: "owner/name" (GitLab: the full path).
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.