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

GitLabSourceControlProvider.test.ts

276 lines9.6 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("accepts authenticated GitLab hosts when another configured host fails", () => {
29 const auth = GitLabSourceControlProvider.discovery.parseAuth({
30 exitCode: ChildProcessSpawner.ExitCode(1),
31 stdout: `gitlab.com
32 x gitlab.com: API call failed: 401 Unauthorized
33 ! No token found
34self-hosted.example.test
35 ✓ Logged in to self-hosted.example.test as gitlab-user
36 ✓ Token found: ******
37`,
38 stderr: "",
39 });
40​
41 assert.deepStrictEqual(
42 {
43 status: auth.status,
44 account: auth.account,
45 host: auth.host,
46 },
47 {
48 status: "authenticated",
49 account: Option.some("gitlab-user"),
50 host: Option.some("self-hosted.example.test"),
51 },
52 );
53});
54​
55it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
56 const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
57 cwd: "/repo",
58 context: {
59 provider: {
60 kind: SourceControlProviderKind.make("unknown"),
61 name: "Self-Hosted.Example.Test",
62 baseUrl: "https://Self-Hosted.Example.Test",
63 },
64 remoteName: "origin",
65 remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
66 },
67 auth: {
68 exitCode: ChildProcessSpawner.ExitCode(0),
69 stdout: `self-hosted.example.test
70 ✓ Logged in to self-hosted.example.test as gitlab-user
71 ✓ Token found: ******
72`,
73 stderr: "",
74 },
75 });
76​
77 assert.deepStrictEqual(provider, {
78 kind: "gitlab",
79 name: "GitLab Self-Hosted",
80 baseUrl: "https://Self-Hosted.Example.Test",
81 });
82});
83​
84it("tells a host glab has no login for apart from output that cannot say", () => {
85 const refine = (stderr: string) =>
86 GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
87 cwd: "/repo",
88 context: {
89 provider: {
90 kind: SourceControlProviderKind.make("unknown"),
91 name: "git.example.test",
92 baseUrl: "https://git.example.test",
93 },
94 remoteName: "origin",
95 remoteUrl: "https://git.example.test/group/project.git",
96 },
97 auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
98 });
99​
100 assert.strictEqual(
101 refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
102 null,
103 );
104 assert.strictEqual(
105 refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
106 null,
107 );
108 assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
109});
110​
111// regression: #15395 self-hosted GitLab remotes resolve bare MR numbers once glab is signed in
112it.effect.each([
113 [
114 "https://code.example.test:8443@Code.Example.Test:8443/Team/Repo.git",
115 true,
116 "gitlab",
117 "Code.Example.Test:8443",
118 ],
119 ["git@code.example.test:team/repo.git", true, "gitlab"],
120 ["https://code.example.test/team/repo.git", false, "unknown"],
121 ["https://github.com/team/repo.git", true, "github"],
122] as const)(
123 "resolves MR numbers for %s with authenticated=%s as %s",
124 ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>
125 Effect.gen(function* () {
126 const provider = yield* makeProvider({});
127 const identity = {
128 canonicalKey: normalizeGitRemoteUrl(remoteUrl),
129 locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
130 rootPath: "/repo",
131 provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",
132 };
133 let authCalls = 0;
134 const refined = yield* (
135 provider.refineRepositoryIdentity?.({
136 identity,
137 resolveContext: (input) =>
138 refineUnknownRemoteProvider({
139 ...input,
140 specs: [GitLabSourceControlProvider.discovery],
141 process: {
142 run: ({ command, args, cwd }) => {
143 authCalls++;
144 assert.deepStrictEqual(
145 { command, args, cwd },
146 {
147 command: "glab",
148 args: ["auth", "status", "--hostname", expectedAuthHost],
149 cwd: "/repo",
150 },
151 );
152 return Effect.succeed(
153 processOutput(
154 authenticated
155 ? `${expectedAuthHost}\n ✓ Logged in to ${expectedAuthHost} as gitlab-user\n`
156 : "x code.example.test has not been authenticated with glab.",
157 { exitCode: ChildProcessSpawner.ExitCode(authenticated ? 0 : 1) },
158 ),
159 );
160 },
161 },
162 }).pipe(
163 Effect.map(({ provider }) =>
164 provider ? { ...input.context, provider } : input.context,
165 ),
166 ),
167 }) ?? Effect.succeed(identity)
168 );
169 const [host, ...repository] = refined.canonicalKey.split("/");
170 assert.strictEqual(
171 changeRequestUrlFor(refined.provider, host!, repository.join("/"), 42),
172 expectedProvider === "gitlab"
173 ? "https://code.example.test/team/repo/-/merge_requests/42"
174 : expectedProvider === "github"
175 ? "https://github.com/team/repo/pull/42"
176 : null,
177 );
178 assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });
179 if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
180 }),
181);
182​
183it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
184 assert.deepStrictEqual(
185 parseGitLabAuthStatusHosts(`localhost:8080
186 ✓ Logged in to localhost:8080 as local-user
187selfhosted
188 ✓ Logged in to selfhosted as single-label-user
189`),
190 [
191 { host: "localhost:8080", account: "local-user" },
192 { host: "selfhosted", account: "single-label-user" },
193 ],
194 );
195});
196​
197it.effect.each(["merge_requests", "issues"])(
198 "resolves %s subjects on the linked host without using the checkout",
199 (kind) =>
200 Effect.gen(function* () {
201 const provider = yield* makeProvider({
202 execute: (input) => {
203 assert.deepStrictEqual(input.args, [
204 "api",
205 "--hostname",
206 "gitlab.com",
207 `projects/group%2Fsubgroup%2Fproject/${kind}/42`,
208 ]);
209 assert.strictEqual(input.maxOutputBytes, 32_000);
210 assert.strictEqual(input.timeoutMs, 3_000);
211 return Effect.succeed({
212 exitCode: ChildProcessSpawner.ExitCode(0),
213 stdout: JSON.stringify({
214 title: "Pairing expiry",
215 description: "Preserve remote access",
216 }),
217 stderr: "",
218 stdoutTruncated: false,
219 stderrTruncated: false,
220 });
221 },
222 });
223 const lookup = provider.resolveLink?.({
224 cwd: "/unrelated",
225 url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
226 });
227 assert.ok(lookup);
228 assert.deepStrictEqual(yield* lookup, {
229 title: "Pairing expiry",
230 body: "Preserve remote access",
231 });
232 assert.strictEqual(
233 provider.resolveLink?.({
234 cwd: "/unrelated",
235 url: new URL("https://gitlab.com/owner/repo"),
236 }),
237 undefined,
238 );
239 }),
240);
241​
242it.effect.each(["read", "decode"] as const)(
243 "retains the %s failure without exposing its raw contents",
244 (stage) =>
245 Effect.gen(function* () {
246 const cause = new GitLabCli.GitLabCliCommandError({
247 command: "glab",
248 cwd: "/repo",
249 operation: "execute",
250 cause: new Error("private response text"),
251 });
252 const provider = yield* makeProvider({
253 execute: () =>
254 stage === "read"
255 ? Effect.fail(cause)
256 : Effect.succeed({
257 exitCode: ChildProcessSpawner.ExitCode(0),
258 stdout: "private response text",
259 stderr: "",
260 stdoutTruncated: false,
261 stderrTruncated: false,
262 }),
263 });
264 const lookup = provider.resolveLink?.({
265 cwd: "/repo",
266 url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
267 });
268 assert.ok(lookup);
269 const error = yield* Effect.flip(lookup);
270 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
271 assert.strictEqual(error.detail, "The linked subject could not be read.");
272 assert.notInclude(error.message, "private response text");
273 if (stage === "read") assert.strictEqual(error.cause, cause);
274 else assert.propertyVal(error.cause, "_tag", "SchemaError");
275 }),
276);