TypeScript
fix(server): self-hosted GitLab projects resolve bare pull request numbers (#15395)
Antony221831ff8ff4
diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.tsindex 7ff050fbb84..e5ec7b623b5 100644--- a/packages/shared/src/git.test.ts+++ b/packages/shared/src/git.test.ts@@ -54,6 +54,14 @@ describe("normalizeGitRemoteUrl", () => {expect(normalizeGitRemoteUrl("[email protected]:workspace/repo.git")).toBe("bitbucket.org/workspace/repo",);+ expect(normalizeGitRemoteUrl("code.example.test:team/repo.git")).toBe(+ "code.example.test/team/repo",+ );+ expect(normalizeGitRemoteUrl("[email protected]:/team/repo.git")).toBe(+ "code.example.test/team/repo",+ );+ expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project");+ expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project");});it("gives an Azure DevOps repository the same key over SSH as over HTTPS", () => {diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.tsindex 14af818f4c2..9ee615bf2ef 100644--- a/packages/shared/src/git.ts+++ b/packages/shared/src/git.ts@@ -163,9 +163,10 @@ export function normalizeGitRemoteUrl(value: string): string {}}- const scpStyleHostAndPath = /^[a-zA-Z0-9._-]+@([^:/\s]+):([^/\s]+(?:\/[^/\s]+)+)$/i.exec(- normalized,- );+ // A userless one-letter prefix is a Windows drive, not an SCP host.+ const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)+ ? null+ : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);const scpHost = scpStyleHostAndPath?.[1];const scpPath = scpStyleHostAndPath?.[2];if (scpHost && scpPath) {diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.tsindex 1c4268ba400..3227a13d3f8 100644--- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts@@ -1,4 +1,11 @@import { SourceControlProviderKind } from "@t3tools/contracts";+import { changeRequestUrlFor } from "@t3tools/shared/changeRequestUrl";+import {+ detectSourceControlProviderFromGitRemoteUrl,+ normalizeGitRemoteUrl,+} from "@t3tools/shared/git";+import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";+import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -241,6 +248,79 @@ it("tells a host glab has no login for apart from output that cannot say", () =>assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);});+it.effect.each([+ [+ "https://code.example.test:[email protected]:8443/Team/Repo.git",+ true,+ "gitlab",+ "Code.Example.Test:8443",+ ],+ ["[email protected]:team/repo.git", true, "gitlab"],+ ["code.example.test:team/repo.git", true, "gitlab"],+ ["[email protected]:/team/repo.git", true, "gitlab"],+ ["https://code.example.test/team/repo.git", false, "unknown"],+ ["https://github.com/team/repo.git", true, "github"],+] as const)(+ "resolves MR numbers for %s with authenticated=%s as %s",+ ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>+ Effect.gen(function* () {+ const provider = yield* makeProvider({});+ const identity = {+ canonicalKey: normalizeGitRemoteUrl(remoteUrl),+ locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },+ rootPath: "/repo",+ provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",+ };+ let authCalls = 0;+ const refined = yield* (+ provider.refineRepositoryIdentity?.({+ identity,+ resolveContext: (input) =>+ refineUnknownRemoteProvider({+ ...input,+ specs: [GitLabSourceControlProvider.discovery],+ process: {+ run: ({ command, args, cwd }) => {+ authCalls++;+ assert.deepStrictEqual(+ { command, args, cwd },+ {+ command: "glab",+ args: ["auth", "status", "--hostname", expectedAuthHost],+ cwd: "/repo",+ },+ );+ return Effect.succeed(+ processOutput(+ authenticated+ ? `${expectedAuthHost}\n ✓ Logged in to ${expectedAuthHost} as gitlab-user\n`+ : "x code.example.test has not been authenticated with glab.",+ { exitCode: ChildProcessSpawner.ExitCode(authenticated ? 0 : 1) },+ ),+ );+ },+ },+ }).pipe(+ Effect.map(({ provider }) =>+ provider ? { ...input.context, provider } : input.context,+ ),+ ),+ }) ?? Effect.succeed(identity)+ );+ const [host, ...repository] = refined.canonicalKey.split("/");+ assert.strictEqual(+ changeRequestUrlFor(refined.provider, host!, repository.join("/"), 42),+ expectedProvider === "gitlab"+ ? "https://code.example.test/team/repo/-/merge_requests/42"+ : expectedProvider === "github"+ ? "https://github.com/team/repo/pull/42"+ : null,+ );+ assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });+ if (expectedProvider === "github") assert.strictEqual(authCalls, 0);+ }),+);+it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {assert.deepStrictEqual(parseGitLabAuthStatusHosts(`localhost:8080diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.tsindex c8cd955b3f7..8d84beb7a83 100644--- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";+import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";import * as GitLabCli from "./GitLabCli.ts";import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";@@ -101,6 +102,39 @@ function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementIn} as const;}+function unknownRemoteProvider(remoteUrl: string) {+ // The shared detector does not recognize userless SCP remotes.+ const scpHost = /^([^@:/\\\s]{2,}):\/?[^/\s]+(?:\/[^/\s]+)+$/u.exec(remoteUrl.trim())?.[1];+ const provider = detectSourceControlProviderFromRemoteUrl(+ scpHost ? `ssh://${scpHost}` : remoteUrl,+ );+ return provider?.kind === "unknown" ? provider : null;+}++// A glab login confirms a self-hosted GitLab whose hostname does not identify its provider.+const refineRepositoryIdentity: NonNullable<+ SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]+> = Effect.fn("GitLabSourceControlProvider.refineRepositoryIdentity")(function* ({+ identity,+ resolveContext,+}) {+ if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown"))+ return identity;+ const provider = unknownRemoteProvider(identity.locator.remoteUrl);+ if (!provider) return identity;+ const context = yield* resolveContext({+ cwd: identity.rootPath,+ context: {+ provider,+ remoteName: identity.locator.remoteName,+ remoteUrl: identity.locator.remoteUrl,+ },+ });+ return context?.provider.kind === "gitlab"+ ? { ...identity, provider: SourceControlProviderKind.make("gitlab") }+ : identity;+});+export const discovery = {type: "cli",kind: SourceControlProviderKind.make("gitlab"),@@ -110,8 +144,13 @@ export const discovery = {authArgs: ["auth", "status"],// glab matches its configured hosts by exact name, so ask with the remote's own spelling.remoteRefinementArgs: ({ provider, remoteUrl }) => {- const at = remoteUrl.toLowerCase().indexOf(provider.name.toLowerCase());- const host = at < 0 ? provider.name : remoteUrl.slice(at, at + provider.name.length);+ const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)/iu.exec(remoteUrl.trim())?.[1];+ const remoteHost = authority+ ? authority.slice(authority.lastIndexOf("@") + 1)+ : remoteUrl.trim().replace(/^[^@:/]+@/u, "");+ const host = remoteHost.toLowerCase().startsWith(provider.name.toLowerCase())+ ? remoteHost.slice(0, provider.name.length)+ : provider.name;return ["auth", "status", "--hostname", host];},parseAuth: parseGitLabAuth,@@ -163,6 +202,7 @@ export const make = Effect.gen(function* () {return SourceControlProvider.SourceControlProvider.of({kind: SourceControlProviderKind.make("gitlab"),+ refineRepositoryIdentity,resolveLink: (input) => {// Automatic enrichment must not send ambient CLI credentials to a host from message text.if (input.url.host !== "gitlab.com") return undefined;