Files
deepseek-harness/packages/experimental/forge-gitlab/src/urls.ts
T
LegGasai cb44a3c2ee feat(forge): read, review, and bind GitLab merge requests (#8317)
* feat(forge): let providers declare their hosts, names, sign-in, and review decisions

Prepare the forge contract for a second provider:

- ForgeProvider lists the hosts it serves and names itself (label,
  changeRequestNoun); registering a provider that lists a host another
  registered provider lists throws, so each URL has at most one provider.
  ctx.forge.describe(forge) returns the family's ForgeDescription.
- ForgeReadiness carries the sign-in command, which the panel's sign-in
  banner shows instead of building `gh auth login` for the github family.
- ForgeReviewData lists the review decisions the host lets the reader
  record; the review dialog offers only those instead of hardcoding the
  GitHub rule that a pull request's author may only comment.
- ForgeReviewThread.original may name a later commit the host carried the
  thread to while its lines stayed unchanged.
- The changes view names the code host and its word for a change request
  from the entry's ForgeDescription instead of hardcoding GitHub and PR.

The GitHub provider declares its configured hosts, GitHub, pull requests,
`gh auth login --hostname <host>`, and reads viewerDidAuthor for the
review decisions. Upgrade guide: forge-provider-hosts.

* feat(forge-gitlab): read GitLab merge requests through the GitLab CLI

Add the experimental forge-gitlab provider. It serves the configured
GitLab hosts through glab: status batches over GraphQL, head-pinned
patches from merge request diff versions, commit listings, merge bases,
pipeline jobs, closing issues, and review threads mapped from REST
discussions, including outdated threads' hunks.

The forge bundle composes the provider, disabled by default.

* feat(forge-gitlab): write GitLab reviews, retry pipelines, request reviews, and rebase

The GitLab provider now writes through glab as well as reading:
comments start discussions at positions derived from the head's diff
version, pending replies and comments are draft notes that a review
publishes with its summary and review state, and approving checks the
head through GitLab's sha parameter. Review reads carry the signed-in
user's rights from GraphQL, their draft notes as the pending review,
and the decisions GitLab lets them record.

Snapshots name the head pipeline as every job's rerun, offer rebase as
the branch update, and follow GitLab's permissions for reruns and
review requests. updateBranch's contract now states how a provider
whose host takes no expected head checks it.

* feat(forge): let forge providers register the commands that bind change requests

forge-session no longer recognizes gh commands by itself. A provider now
registers a declarative ForgeCommandRule through
ctx.forgeSession.registerCommands: its executable, creation and reference
subcommands, change request page path, JSON URL members, declared
options, and a pure select that maps one parsed reference command to a
URL or a read-only lookup. forge-github registers gh and forge-gitlab
registers glab, which adds glab mr create, view, update, and checkout,
including numbers with -R: a full project URL binds directly, and other
repository forms resolve through glab mr view in the call's shell.

forge-session keeps the shared parts: the literal shell tokenizer,
option parsing, output reading, lookups, and the projection. The
forgeChangeRequests state version derives from the recognized rules, so
a changed rule set refolds every Session, including commands that ran
before the provider loaded. Ending a registration keeps its rule
recognized until restart, so unloading providers at shutdown does not
rewrite every checkpoint.

* refactor(forge-gitlab): publish the GitLab provider as @deepseek-ai/dsh-forge-gitlab

New experimental packages omit the experimental prefix so that promotion
keeps their npm name. Register the directory in
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS instead of growing the legacy
prefixed list, and rename every dependency, configuration row, path
mapping, and document that names the package.

* fix(forge-gitlab): keep review writes, comment positions, and reads within GitLab's facts and the limits

- After GitLab refuses a publication, read the drafts again: delete
  them only when all remain, since GitLab can publish them before it
  refuses the summary, and report the outcome as unknown otherwise.
  A rollback that leaves drafts reports how many may remain.
- Place comments on files GitLab collapsed through the diff compared
  from their texts, and let a file's new path name it over another
  file's old path after chained renames.
- Keep the final newline of raw file reads.
- Apply maxOutputBytes to the complete review result, and report a
  read whose rights stop early or skip a discussion's later notes as
  truncated.
- Serve a version over maxCachedVersionBytes without keeping it.
- Resolve uploaded avatars GitLab names by their path on the host.
- Schedule bounded reads through p-limit.

* fix(forge-session): run lookups only for live command rules and keep the projection registered

- Reference lookups use the rules of live registrations, so a disposed
  provider's rule still folds but starts no gh or glab process.
- A failed re-registration registers the projection again with the
  earlier rules, so clients keep its view; an error is logged only when
  that fails too.
- Document the startup re-registration, test that the checkpointed
  state version survives a real Loader start, shutdown, and restart,
  and record that starting without a provider removes the bindings only
  its commands made.
- Describe the changes view's pending review and single comment
  without naming GitHub, which keeps its own rule in forge-github, and
  render registerCommands as code in the generated service reference.

* fix(forge-bundle): name GitLab merge requests in the bundle description

The bundle now follows GitLab merge requests as well as GitHub pull
requests, so the description's first sentence in every locale names
both kinds of change request.

* feat(forge): bind the change requests that gh api and glab api requests name

Models often read a merge request through `glab api` or a pull request
through `gh api` instead of `glab mr view` or `gh pr view`, which left
the change request unbound. A command rule now declares raw API request
subcommands beside its reference subcommands, each group with its own
options, since `-f` is a value of `gh api` and a flag of
`gh pr checkout`.

An API request binds, as referenced, only the change request its REST
path names, such as `projects/group%2Fapp/merge_requests/7/changes` or
`repos/octo/demo/pulls/7/files`; its output is not read, since one
request can list many change requests. A path whose host the command
names binds directly, and one without a host, or with the current
repository's placeholders, resolves through the CLI's view command in
the call's shell. The gh and glab rules move to version 2.

* docs(forge): add forge-gitlab and the forge-session peers to the module graph

Regenerate docs/module-graph for the renamed GitLab provider and the
optional forge-session peer of both providers.

* test(web): refresh the forge bundle description in the recommended plugin catalog

The creation recommendation recording carries every recommended
plugin's description; refresh it for the forge bundle description that
now names GitLab merge requests and the glab sign-in.

* chore(forge-gitlab): carry the 0.2.2-rc.3 release version and move upgrade guides to v0.2.2-rc.3
2026-11-13 07:56:57 +00:00

140 lines
6.1 KiB
TypeScript

/** GitLab remote URL and merge request URL parsing, and validation of the project paths inlined into requests. */
import type { ChangeRequestRef, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge'
/** Characters GitLab permits in one group or project path segment. */
const SEGMENT = /^[A-Za-z0-9_.-]+$/
/** Host, namespace, and project addressed by a URL. */
export interface GitLabLocation {
/** Lowercase host name. */
readonly host: string
/** Group or user namespace, with nested groups joined by `/`. */
readonly owner: string
/** Project path without a `.git` suffix. */
readonly name: string
}
/**
* Check one group or project path segment.
* @param value - candidate segment.
* @returns whether GitLab permits the segment and it is not a dot path.
*/
export function isSegment(value: string): boolean {
return SEGMENT.test(value) && value !== '.' && value !== '..'
}
/**
* Split a namespace and project path, rejecting an empty or invalid segment.
* @param host - host the path is on.
* @param parts - path segments, the project last.
* @returns the namespace and project, or undefined.
*/
function location(host: string, parts: readonly string[]): GitLabLocation | undefined {
if (parts.length < 2 || !parts.every(isSegment)) return undefined
return { host: host.toLowerCase(), owner: parts.slice(0, -1).join('/'), name: parts.slice(-1).join('') }
}
/**
* Validate a merge request before its project path and number are inlined into an API path or a GraphQL variable.
* @param ref - merge request on a GitLab host.
* @returns the project's full path, `namespace/project`.
* @throws when a path segment is not permitted or the number is not a positive integer.
*/
export function checkedProject(ref: ChangeRequestRef): string {
const { owner, name } = ref.repository
if (!owner.split('/').every(isSegment) || !isSegment(name)) throw new Error(`forge-gitlab: invalid project ${JSON.stringify(`${owner}/${name}`)}`)
if (!Number.isSafeInteger(ref.number) || ref.number <= 0) throw new Error(`forge-gitlab: invalid merge request number ${ref.number}`)
return `${owner}/${name}`
}
/**
* The REST path prefix of a merge request, with the project path percent-encoded as GitLab requires.
* @param ref - merge request on a GitLab host.
* @returns `projects/<encoded path>/merge_requests/<iid>`.
* @throws as {@link checkedProject} does.
*/
export function mergeRequestPath(ref: ChangeRequestRef): string {
return `projects/${encodeURIComponent(checkedProject(ref))}/merge_requests/${ref.number}`
}
/**
* Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/namespace/project`, `ssh://[user@]host[:port]/…`,
* `git://host/…`, and the scp-like `[user@]host:namespace/project`, each with an optional `.git` suffix or trailing
* slash and with nested groups in the namespace. HTTP(S) ports belong to the host identity; SSH and Git transport
* ports do not.
* @param url - fetch or push URL as Git reports it.
* @returns the location, or undefined for other URL shapes.
*/
export function parseRemoteUrl(url: string): GitLabLocation | undefined {
// The GitHub provider parses the same remote URL forms; the providers share no runtime module but the forge entry,
// which exports only what the Loader loads, so each keeps its copy.
/* jscpd:ignore-start */
const trimmed = url.trim()
const scheme = /^https?:\/\/(?:[^@/]+@)?([^/:]+(?::\d+)?)\/(.+)$/i.exec(trimmed)
?? /^(?:ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed)
const scp = scheme === null ? /^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(trimmed) : null
const match = scheme ?? scp
if (match === null) return undefined
const [, host = '', path = ''] = match
/* jscpd:ignore-end */
return location(host, path.replace(/\/+$/, '').replace(/\.git$/i, '').split('/'))
}
/**
* Parse a merge request web URL such as `https://gitlab.com/group/project/-/merge_requests/12/diffs`.
* @param url - web URL of a merge request.
* @returns the location and number, or undefined for other URLs.
*/
export function parseMergeRequestUrl(url: string): (GitLabLocation & { readonly number: number }) | undefined {
const match = /^https?:\/\/([^/]+)\/(.+?)\/-\/merge_requests\/(\d+)(?:[/?#].*)?$/i.exec(url.trim())
if (match === null) return undefined
const [, host = '', path = '', digits = ''] = match
const number = Number(digits)
const parsed = location(host, path.split('/'))
if (parsed === undefined || !Number.isSafeInteger(number) || number <= 0) return undefined
return { ...parsed, number }
}
/**
* Parse an issue web URL such as `https://gitlab.com/group/project/-/issues/12`.
* @param url - web URL of an issue.
* @returns the location and number, or undefined for other URLs.
*/
export function parseIssueUrl(url: string): (GitLabLocation & { readonly number: number }) | undefined {
const match = /^https?:\/\/([^/]+)\/(.+?)\/-\/(?:issues|work_items)\/(\d+)(?:[/?#].*)?$/i.exec(url.trim())
if (match === null) return undefined
const [, host = '', path = '', digits = ''] = match
const parsed = location(host, path.split('/'))
return parsed === undefined ? undefined : { ...parsed, number: Number(digits) }
}
/**
* Percent-encode each segment of a repository-relative path for a web or API URL.
* @param path - repository-relative path.
* @returns the encoded path with `/` kept between segments.
*/
export function encodedPath(path: string): string {
return path.split('/').map(encodeURIComponent).join('/')
}
/**
* Build the repository of a location.
* @param location - parsed host, namespace, and project.
* @returns the repository of the `gitlab` family.
*/
export function repositoryOf(location: GitLabLocation): ForgeRepository {
return { forge: 'gitlab', host: location.host, owner: location.owner, name: location.name }
}
/**
* Resolve an avatar URL GitLab names by its path on the host, as it does for an uploaded avatar without a separate
* asset host.
* @param host - GitLab host.
* @param url - avatar URL as GitLab reports it.
* @returns the absolute URL, or null when GitLab names none.
*/
export function avatarUrlOf(host: string, url: string | null): string | null {
return url?.startsWith('/') === true ? `https://${host}${url}` : url
}