Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitLabSourceControlProvider.test.ts

320 lines10.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { changeRequestUrlFor } from "@t3tools/shared/changeRequestUrl";
3import {
4 detectSourceControlProviderFromGitRemoteUrl,
5 normalizeGitRemoteUrl,
6} from "@t3tools/shared/git";
7import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
8import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
9import { assert, it } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import { ChildProcessSpawner } from "effect/process";
14​
15import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
16import * as GitLabCli from "./GitLabCli.ts";
17import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
18import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
19​
20function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
21 return GitLabSourceControlProvider.make.pipe(
22 Effect.provide(
23 Layer.mergeAll(Layer.mock(GitLabCli.GitLabCli)(gitlab), TestSourceControlHost.layer()),
24 ),
25 );
27​
28it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
29 Effect.gen(function* () {
30 const provider = yield* makeProvider({
31 getMergeRequest: () =>
32 Effect.succeed({
33 number: 42,
34 title: "Add GitLab provider",
35 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
36 baseRefName: "main",
37 headRefName: "feature/source-control",
38 headSha: "a".repeat(40),
39 state: "closed",
40 closedAt: "2026-08-23T10:00:00Z",
41 isCrossRepository: true,
42 headRepositoryNameWithOwner: "fork/t3code",
43 headRepositoryOwnerLogin: "fork",
44 }),
45 });
46​
47 const changeRequest = yield* provider.getChangeRequest({
48 cwd: "/repo",
49 reference: "42",
50 });
51​
52 assert.deepStrictEqual(changeRequest, {
53 provider: SourceControlProviderKind.make("gitlab"),
54 number: 42,
55 title: "Add GitLab provider",
56 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
57 baseRefName: "main",
58 headRefName: "feature/source-control",
59 headSha: "a".repeat(40),
60 state: "closed",
61 closedAt: "2026-08-23T10:00:00Z",
62 mergedAt: null,
63 updatedAt: Option.none(),
64 isCrossRepository: true,
65 headRepositoryNameWithOwner: "fork/t3code",
66 headRepositoryOwnerLogin: "fork",
67 });
68 }),
69);
70​
71it("accepts authenticated GitLab hosts when another configured host fails", () => {
72 const auth = GitLabSourceControlProvider.discovery.parseAuth({
73 exitCode: ChildProcessSpawner.ExitCode(1),
74 stdout: `gitlab.com
75 x gitlab.com: API call failed: 401 Unauthorized
76 ! No token found
77self-hosted.example.test
78 ✓ Logged in to self-hosted.example.test as gitlab-user
79 ✓ Token found: ******
80`,
81 stderr: "",
82 });
83​
84 assert.deepStrictEqual(
85 {
86 status: auth.status,
87 account: auth.account,
88 host: auth.host,
89 },
90 {
91 status: "authenticated",
92 account: Option.some("gitlab-user"),
93 host: Option.some("self-hosted.example.test"),
94 },
95 );
96});
97​
98it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
99 const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
100 cwd: "/repo",
101 context: {
102 provider: {
103 kind: SourceControlProviderKind.make("unknown"),
104 name: "Self-Hosted.Example.Test",
105 baseUrl: "https://Self-Hosted.Example.Test",
106 },
107 remoteName: "origin",
108 remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
109 },
110 auth: {
111 exitCode: ChildProcessSpawner.ExitCode(0),
112 stdout: `self-hosted.example.test
113 ✓ Logged in to self-hosted.example.test as gitlab-user
114 ✓ Token found: ******
115`,
116 stderr: "",
117 },
118 });
119​
120 assert.deepStrictEqual(provider, {
121 kind: "gitlab",
122 name: "GitLab Self-Hosted",
123 baseUrl: "https://Self-Hosted.Example.Test",
124 });
125});
126​
127it("tells a host glab has no login for apart from output that cannot say", () => {
128 const refine = (stderr: string) =>
129 GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
130 cwd: "/repo",
131 context: {
132 provider: {
133 kind: SourceControlProviderKind.make("unknown"),
134 name: "git.example.test",
135 baseUrl: "https://git.example.test",
136 },
137 remoteName: "origin",
138 remoteUrl: "https://git.example.test/group/project.git",
139 },
140 auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
141 });
142​
143 assert.strictEqual(
144 refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
145 null,
146 );
147 assert.strictEqual(
148 refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
149 null,
150 );
151 assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
152});
153​
154it.effect.each([
155 [
156 "https://code.example.test:8443@Code.Example.Test:8443/Team/Repo.git",
157 true,
158 "gitlab",
159 "Code.Example.Test:8443",
160 ],
161 ["git@code.example.test:team/repo.git", true, "gitlab"],
162 ["code.example.test:team/repo.git", true, "gitlab"],
163 ["git@code.example.test:/team/repo.git", true, "gitlab"],
164 ["https://code.example.test/team/repo.git", false, "unknown"],
165 ["https://github.com/team/repo.git", true, "github"],
166] as const)(
167 "resolves MR numbers for %s with authenticated=%s as %s",
168 ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>
169 Effect.gen(function* () {
170 const provider = yield* makeProvider({});
171 const identity = {
172 canonicalKey: normalizeGitRemoteUrl(remoteUrl),
173 locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
174 rootPath: "/repo",
175 provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",
176 };
177 let authCalls = 0;
178 const refined = yield* (
179 provider.refineRepositoryIdentity?.({
180 identity,
181 resolveContext: (input) =>
182 refineUnknownRemoteProvider({
183 ...input,
184 specs: [GitLabSourceControlProvider.discovery],
185 process: {
186 run: ({ command, args, cwd }) => {
187 authCalls++;
188 assert.deepStrictEqual(
189 { command, args, cwd },
190 {
191 command: "glab",
192 args: ["auth", "status", "--hostname", expectedAuthHost],
193 cwd: "/repo",
194 },
195 );
196 return Effect.succeed(
197 processOutput(
198 authenticated
199 ? `${expectedAuthHost}\n ✓ Logged in to ${expectedAuthHost} as gitlab-user\n`
200 : "x code.example.test has not been authenticated with glab.",
201 { exitCode: ChildProcessSpawner.ExitCode(authenticated ? 0 : 1) },
202 ),
203 );
204 },
205 },
206 }).pipe(
207 Effect.map(({ provider }) =>
208 provider ? { ...input.context, provider } : input.context,
209 ),
210 ),
211 }) ?? Effect.succeed(identity)
212 );
213 const [host, ...repository] = refined.canonicalKey.split("/");
214 assert.strictEqual(
215 changeRequestUrlFor(refined.provider, host!, repository.join("/"), 42),
216 expectedProvider === "gitlab"
217 ? "https://code.example.test/team/repo/-/merge_requests/42"
218 : expectedProvider === "github"
219 ? "https://github.com/team/repo/pull/42"
220 : null,
221 );
222 assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });
223 if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
224 }),
225);
226​
227it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
228 assert.deepStrictEqual(
229 parseGitLabAuthStatusHosts(`localhost:8080
230 ✓ Logged in to localhost:8080 as local-user
231selfhosted
232 ✓ Logged in to selfhosted as single-label-user
233`),
234 [
235 { host: "localhost:8080", account: "local-user" },
236 { host: "selfhosted", account: "single-label-user" },
237 ],
238 );
239});
240​
241it.effect.each(["merge_requests", "issues"])(
242 "resolves %s subjects on the linked host without using the checkout",
243 (kind) =>
244 Effect.gen(function* () {
245 const provider = yield* makeProvider({
246 execute: (input) => {
247 assert.deepStrictEqual(input.args, [
248 "api",
249 "--hostname",
250 "gitlab.com",
251 `projects/group%2Fsubgroup%2Fproject/${kind}/42`,
252 ]);
253 assert.strictEqual(input.maxOutputBytes, 32_000);
254 assert.strictEqual(input.timeoutMs, 3_000);
255 return Effect.succeed({
256 exitCode: ChildProcessSpawner.ExitCode(0),
257 stdout: JSON.stringify({
258 title: "Pairing expiry",
259 description: "Preserve remote access",
260 }),
261 stderr: "",
262 stdoutTruncated: false,
263 stderrTruncated: false,
264 });
265 },
266 });
267 const lookup = provider.resolveLink?.({
268 cwd: "/unrelated",
269 url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
270 });
271 assert.ok(lookup);
272 assert.deepStrictEqual(yield* lookup, {
273 title: "Pairing expiry",
274 body: "Preserve remote access",
275 });
276 assert.strictEqual(
277 provider.resolveLink?.({
278 cwd: "/unrelated",
279 url: new URL("https://gitlab.com/owner/repo"),
280 }),
281 undefined,
282 );
283 }),
284);
285​
286it.effect.each(["read", "decode"] as const)(
287 "retains the %s failure without exposing its raw contents",
288 (stage) =>
289 Effect.gen(function* () {
290 const cause = new GitLabCli.GitLabCliCommandError({
291 command: "glab",
292 cwd: "/repo",
293 operation: "execute",
294 cause: new Error("private response text"),
295 });
296 const provider = yield* makeProvider({
297 execute: () =>
298 stage === "read"
299 ? Effect.fail(cause)
300 : Effect.succeed({
301 exitCode: ChildProcessSpawner.ExitCode(0),
302 stdout: "private response text",
303 stderr: "",
304 stdoutTruncated: false,
305 stderrTruncated: false,
306 }),
307 });
308 const lookup = provider.resolveLink?.({
309 cwd: "/repo",
310 url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
311 });
312 assert.ok(lookup);
313 const error = yield* Effect.flip(lookup);
314 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
315 assert.strictEqual(error.detail, "The linked subject could not be read.");
316 assert.notInclude(error.message, "private response text");
317 if (stage === "read") assert.strictEqual(error.cause, cause);
318 else assert.propertyVal(error.cause, "_tag", "SchemaError");
319 }),
320);