Skip to content
GitHub

DevelopForge

@holtkeeper/forge

The provider-neutral interface to Git hosting. Plugins use GitForge and never a GitLab or GitHub client directly; adapters such as @holtkeeper/forge-gitlab implement it.

What the config holds under forges:

interface ForgeDefinition {
kind: string // 'gitlab', 'github', ...
url: string
create(): GitForge
gitCredentials?(): { username: string; password: string }
withFetch?(wrap: (fetch: ForgeFetch) => ForgeFetch): ForgeDefinition
fetch?: ForgeFetch
}

withFetch returns the same forge with its HTTP fetch wrapped, e.g. by shared rate limits; adapters that do not use fetch leave it out. fetch is the wrapped fetch itself, for tools that call the forge API on their own and must share those limits (Renovate through @holtkeeper/renovate).

create is called lazily, when a task needs the forge, which is also when secrets are resolved. gitCredentials() returns HTTPS basic-auth credentials for git clone/git fetch of the forge’s repositories (GitLab: username oauth2, the token as password); it resolves secrets on each call, and forges that cannot provide credentials leave it out.

Repositories are addressed by their full path (games/app-x), merge requests by their per-repository number (GitLab iid, GitHub PR number). The terms follow GitLab — merge request, pipeline, job — and adapters map them to their provider.

Area Methods
Repositories listRepositories, getRepository, readFile, listFiles (optional), listMemberRepositories (optional: unarchived repositories the credentials are a member of, newest activity first, by search and limit)
Branches and commits createBranch, deleteBranch, commit (several file changes in one commit, through the API)
Merge requests findMergeRequest, createMergeRequest, updateMergeRequest, mergeMergeRequest, commentOnMergeRequest
Pipelines listPipelines (ref, sha, updatedAfter), listJobs, playJob, retryJob
Tags createTag
History (optional) listCommits(repo, { ref, since?, after?, limit? }): commits reachable from ref and not from since (git log since..ref), committed at or after the ISO time after (git log --since), newest first, as CommitRecord; listMergeRequestCommits(repo, id): the shas of a merge request’s commits, newest first
Push rules (optional) getPushRules(repo): the regular expressions the forge enforces on commit messages and new branch names (PushRules), undefined when there are none or they cannot be read
Releases (optional) getRelease(repo, tag), createRelease(repo, { tag, name, description }), updateRelease(repo, { tag, name?, description? }) → ForgeRelease { tag, name, description, webUrl }
Account (optional) getCurrentUser: the token’s user with the email commits should use, avatar, profile and settings page (ForgeUser); setCurrentUserAvatar(file): replaces that user’s avatar (see below)
Insights (optional) listMergeRequests, listPipelineRuns, listJobRuns, listProjectJobRuns, listPipelineJobs, listDeployments, listEnvironments, listTags, listBranches, listCiVariables, listImageTags, npmRegistry

setCurrentUserAvatar?(file: AccountAvatarFile) (optional) replaces the avatar of the account behind the token; AccountAvatarFile is { bytes, filename, contentType }. Callers pass only files checkAccountAvatar({ filename, size, head }) accepts: at most ACCOUNT_AVATAR_MAX_BYTES (200 KB, GitLab’s limit), an extension from ACCOUNT_AVATAR_EXTENSIONS (.png .jpg .jpeg .gif .webp .bmp .ico .tiff, case-insensitive) and contents whose signature matches that extension (no SVG). It answers { contentType } or { problem }, a sentence for the person who picked the file; @holtkeeper/forge/avatar exports the check alone for the web app. Forges whose API cannot change avatars (GitHub) leave the method out. Changing the bot account’s own avatar is an admin action, not a repository write, so readOnlyForge and commentsOffForge let it through.

listNoteReactions?(repo, mergeRequest, noteId): Promise<NoteReaction[]> (optional) reads the emoji reactions on one merge request note as { name, user }, names as the forge has them (thumbsup on GitLab, +1 on GitHub). reactionCounts(reactions) counts 👍 and 👎 under every known name and ignores other emoji. Forges without reactions leave the method out; the server then counts nothing. Review learnings use it to count reactions on Holtkeeper’s review comments.

noteMarks?, addNoteMark? and removeNoteMark?(repo, mergeRequest, noteId, mark) (optional) read, leave and take back the marks of the token’s own account on a note: NoteMark is seen (the note is queued for an answer) or done (it was handled and needs none), each an emoji reaction the forge picks. Adding a mark that is there and removing one that is not are not errors. Webhook and polled note events carry the note’s id as NoteAddedEvent.noteId.

listFiles?(repo, { path?, ref?, recursive?, limit? }): Promise<TreeEntry[]> lists { path, type: 'file' | 'dir' } entries below path (root by default) at ref (default branch by default), direct children unless recursive, at most limit entries (default 10 000). Paths are relative to the repository root. A missing path or ref gives an empty list; submodules are left out. Used to expand workspace globs without a clone.

Optional, read-only history for analyses of CI jobs, branches and releases. Adapters may lag behind, so callers check that a method exists before calling it. Lists are newest first, times are ISO 8601, durations are seconds and absent while unknown, and limit caps the result (all matching items when omitted).

Method Returns
listMergeRequests(repo, { state?, updatedAfter?, targetBranch?, limit? }) MergeRequestRecord: a MergeRequest plus createdAt, updatedAt, mergedAt?, closedAt?, firstCommitAt?, changesCount? and headSha? (the last three only when cheap for the provider), mergeCommitSha? (the merge commit merging created) and squashCommitSha? (the commit its changes were squashed into); state defaults to all
listPipelineRuns(repo, { ref?, after?, limit? }) PipelineRun: a Pipeline plus createdAt, updatedAt?, startedAt?, finishedAt?, durationSeconds?, queuedSeconds?, source?; after filters by creation time
listJobRuns(repo, pipelineId) JobRun: a Job plus pipelineId, timing, retried (a later attempt replaced it) and allowFailure; retried attempts are included
listProjectJobRuns(repo, { after?, limit? }) JobRuns of every pipeline, newest first, retried attempts included, with ref, sha and tag (the pipeline ran for a tag) of their pipeline; much cheaper than listJobRuns per pipeline for long histories
getRepositoryAvatar(repo) ForgeImage { data, contentType }: the project’s avatar, else the nearest parent group’s; undefined when none has one. imageType(bytes) tells PNG, JPEG, GIF, WebP and SVG apart by signature
listPipelineJobs(repo, { ref?, limit? }) PipelineJob: the jobs of the latest pipeline of ref (default branch when omitted), latest attempts only, in pipeline order; a Job plus pipelineId, manual (waits for or was started by a person, as far as the forge tells), environment? (when the forge reports it), createdAt?, finishedAt?. Empty when the ref has no pipeline. Release flow detection reads deploy jobs with it
listDeployments(repo, { environment?, after?, limit?, status? }) Deployment: id, environment, status (pending, running, success, failed, canceled, skipped, blocked), sha, ref, createdAt, finishedAt?; after filters by update time, status keeps one status
listEnvironments(repo, { limit? }) ForgeEnvironment: name, state (available, stopping, stopped); environments that are not stopped, at most limit (default 100)
listTags(repo, { limit? }) TagRecord: a Tag plus committedAt (date of the tagged commit) and createdAt? (annotated tags)
headCommit(repo) The sha the default branch points at, in one request; undefined for an empty repository. Freshness reads heads with it
listBranches(repo) BranchRecord: every branch with name, head sha, committedAt, authorName?, authorEmail?, merged (head reachable from the default branch; squash merges do not count), protected, default, webUrl?
listCiVariables({ kind, path }) CiVariable { key, value, environmentScope } defined directly on a repository or group (no inherited ones); masked, hidden and file variables are left out. undefined when the token may not read them or the scope does not exist
listImageTags(image) Tags of an image (registry/path, no tag) in the forge’s own container registry; undefined when the forge does not serve it or the token may not read it
npmRegistry(repo) Base URL of the npm registry the forge runs for the repository (packages it publishes are read there with the forge token); undefined when there is none

This covers the first milestones (browserslist, audit, releases). Diffs, line threads with suggestions and webhook events are added with code review.

Optional: ensureWebhook(target, { url, secret, events }) makes sure a hook with that URL exists on a group ({ group }) or project ({ project }) and carries this secret and these events (WebhookEvent, every one listed in webhookEvents: pushes, tags, merge requests, comments, issues, pipelines, jobs, deployments, releases, wiki pages, milestones, members, emoji, feature flags, access tokens); an existing hook with the same URL is updated, never duplicated. It returns { id, hooks, fallback? }: hooks are the hooks set up ({ id, scope, target }), and fallback explains when a group target got one hook per project instead. removeWebhook(hooks) removes them, ignoring hooks that are already gone.

webhookStatus(hook, url) says whether the forge still delivers to a hook: WebhookStatus { state, id?, disabledUntil? } with state enabled, temporarily_disabled (comes back on its own at disabledUntil), disabled (stays off until re-enabled) or missing. The hook is found by its id, else by url on the same target; a hook with another URL is never reported, so a caller only ever sees its own hooks. enableWebhook(hook) makes the forge deliver again to a hook it disabled after failed deliveries (pass the hook webhookStatus matched, with its id); it rejects when the forge still cannot deliver. Implementations prefer a test delivery Holtkeeper’s receiver ignores, so re-enabling never looks like real activity.

ForgeEvent is something that happened on a forge, whichever way Holtkeeper learned it (a webhook delivery or polling with @holtkeeper/updates):

kind Fields
tag repo, tag, sha
push repo, branch, sha (the new head), actor (empty when unknown), before? (the head before; absent for a new branch), files? (every path the pushed commits touched, only when the source lists all of them), defaultBranch?
mergeRequest repo, action (open, reopen, update, merge, close, approved), actor (empty when unknown), newCommits, leftDraft, labelsAdded, mr (with headSha when known)
note repo, mergeRequest, mergeRequestState, headSha?, author, body, discussionId?, inThread (a diff or discussion note rather than a standalone comment)
pipeline repo, mergeRequest, pipelineId, status, sha, actor; only finished merge request pipelines

Adapters throw errors that carry the forge’s HTTP status as a numeric status (GitLabApiError of forge-gitlab). forgeErrorStatus(error) reads it, undefined for anything else, so callers tell a missing repository (404) from a rejected token (401) or a missing scope (403) without knowing the adapter.

readOnlyForge(forge, isReadOnly) returns forge with every change to a repository for which isReadOnly(path) (sync or async) is true rejected with ReadOnlyRepositoryError (repo, operation) before anything reaches the forge: createBranch, deleteBranch, commit, createTag, createRelease, updateRelease, the merge request writes (createMergeRequest, updateMergeRequest, mergeMergeRequest, commentOnMergeRequest), submitReview, replyToDiscussion, postMergeRequestNote, updateMergeRequestNote, deleteMergeRequestNote, resolveDiscussion, note marks (addNoteMark, removeNoteMark), playJob, retryJob, deploy keys (registerSshKey with a deploy scope, enableDeployKey) and project webhooks (ensureWebhook with { project }). Reads, user keys, group webhooks, removing keys and hooks, re-enabling hooks (webhookStatus, enableWebhook) and the token account’s avatar (setCurrentUserAvatar, an admin change to the bot account rather than a repository write) pass through; optional methods stay absent when the forge lacks them. readOnlyDefinition(definition, isReadOnly) does the same for every client a ForgeDefinition creates, including those of its withFetch copies.

commentsOffForge(forge, isOff) returns forge with every note on a merge request of a repository for which isOff(path) (sync or async) is true rejected with MergeRequestCommentsOffError (repo, operation) before anything reaches the forge: commentOnMergeRequest, submitReview (except a bare approval: event: 'approve' with no comments and no summary), replyToDiscussion, postMergeRequestNote, updateMergeRequestNote, deleteMergeRequestNote, resolveDiscussion and note marks (addNoteMark, removeNoteMark). Creating, updating (labels included) and merging merge requests, account changes such as setCurrentUserAvatar and everything else pass through, so merge requests Holtkeeper opens keep their description; labels on other people’s merge requests are left to the callers that set them (merge request policies). commentsOffDefinition(definition, isOff) does the same for every client a ForgeDefinition creates, including those of its withFetch copies. The server wraps every panel forge with it for the mergeRequests.comments setting, as it does with readOnlyDefinition for repo.freeze; forges from the config file are not wrapped, so there only the server’s own event and job checks apply.

type Secret = string | { env: string }

env(name) creates an environment reference; resolveSecret(secret) returns the value and throws if the variable is not set. Adapters accept Secret for tokens.