Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
3import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
4import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
5import { assert, it } from "@effect/vitest";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import { ChildProcessSpawner } from "effect/process";
10
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12import * as GitLabCli from "./GitLabCli.ts";
13import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
14import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
15import { definition } from "../shared/definition.ts";
16
17function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
18 return GitLabSourceControlProvider.make.pipe(
19 Effect.provide(
20 Layer.mergeAll(Layer.mock(GitLabCli.GitLabCli)(gitlab), TestSourceControlHost.layer()),
21 ),
22 );
23}
24
25it("accepts authenticated GitLab hosts when another configured host fails", () => {
26 const auth = GitLabSourceControlProvider.discovery.parseAuth({
27 exitCode: ChildProcessSpawner.ExitCode(1),
28 stdout: `gitlab.com
29 x gitlab.com: API call failed: 401 Unauthorized
30 ! No token found
31self-hosted.example.test
32 ✓ Logged in to self-hosted.example.test as gitlab-user
33 ✓ Token found: ******
34`,
35 stderr: "",
36 });
37
38 assert.deepStrictEqual(
39 {
40 status: auth.status,
41 account: auth.account,
42 host: auth.host,
43 },
44 {
45 status: "authenticated",
46 account: Option.some("gitlab-user"),
47 host: Option.some("self-hosted.example.test"),
48 },
49 );
50});
51
52it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
53 const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
54 cwd: "/repo",
55 context: {
56 provider: {
57 kind: SourceControlProviderKind.make("unknown"),
58 name: "Self-Hosted.Example.Test",
59 baseUrl: "https://Self-Hosted.Example.Test",
60 },
61 remoteName: "origin",
62 remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
63 },
64 auth: {
65 exitCode: ChildProcessSpawner.ExitCode(0),
66 stdout: `self-hosted.example.test
67 ✓ Logged in to self-hosted.example.test as gitlab-user
68 ✓ Token found: ******
69`,
70 stderr: "",
71 },
72 });
73
74 assert.deepStrictEqual(provider, {
75 kind: "gitlab",
76 name: "GitLab Self-Hosted",
77 baseUrl: "https://Self-Hosted.Example.Test",
78 });
79});
80
81it("tells a host glab has no login for apart from output that cannot say", () => {
82 const refine = (stderr: string) =>
83 GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
84 cwd: "/repo",
85 context: {
86 provider: {
87 kind: SourceControlProviderKind.make("unknown"),
88 name: "git.example.test",
89 baseUrl: "https://git.example.test",
90 },
91 remoteName: "origin",
92 remoteUrl: "https://git.example.test/group/project.git",
93 },
94 auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
95 });
96
97 assert.strictEqual(
98 refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
99 null,
100 );
101 assert.strictEqual(
102 refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
103 null,
104 );
105 assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
106});
107
108// regression: #15395 self-hosted GitLab remotes resolve bare MR numbers once glab is signed in
109it.effect.each([
110 [
111 "https://code.example.test:8443@Code.Example.Test:8443/Team/Repo.git",
112 true,
113 "gitlab",
114 "Code.Example.Test:8443",
115 ],
116 ["git@code.example.test:team/repo.git", true, "gitlab"],
117 ["https://code.example.test/team/repo.git", false, "unknown"],
118 ["https://github.com/team/repo.git", true, "github"],
119] as const)(
120 "resolves MR numbers for %s with authenticated=%s as %s",
121 ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>
122 Effect.gen(function* () {
123 const provider = yield* makeProvider({});
124 const identity = {
125 canonicalKey: normalizeGitRemoteUrl(remoteUrl),
126 locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
127 rootPath: "/repo",
128 // Only a remote no host recognised is left for glab to refine.
129 provider: SourceControlProviderKind.make(
130 expectedProvider === "github" ? "github" : "unknown",
131 ),
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 if (expectedProvider === "gitlab") {
170 const [host, ...repository] = refined.canonicalKey.split("/");
171 assert.strictEqual(
172 definition.changeRequestUrl({
173 host: host!,
174 repository: repository.join("/"),
175 number: 42,
176 }),
177 "https://code.example.test/team/repo/-/merge_requests/42",
178 );
179 }
180 assert.deepStrictEqual(refined, {
181 ...identity,
182 provider: SourceControlProviderKind.make(expectedProvider),
183 });
184 if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
185 }),
186);
187
188it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
189 assert.deepStrictEqual(
190 parseGitLabAuthStatusHosts(`localhost:8080
191 ✓ Logged in to localhost:8080 as local-user
192selfhosted
193 ✓ Logged in to selfhosted as single-label-user
194`),
195 [
196 { host: "localhost:8080", account: "local-user" },
197 { host: "selfhosted", account: "single-label-user" },
198 ],
199 );
200});
201
202it.effect(
203 "looks up a branch's merge requests a full page at a time, past forks' same-named branches",
204 () =>
205 Effect.gen(function* () {
206 const provider = yield* makeProvider({});
207 assert.deepStrictEqual(
208 provider.headBranchProbe?.({
209 headSelectors: ["octocat:feature", "feature"],
210 state: "open",
211 }),
212 { headSelectors: ["feature"], limit: 100 },
213 );
214 }),
215);
216
217it.effect.each(["merge_requests", "issues"])(
218 "resolves %s subjects on the linked host without using the checkout",
219 (kind) =>
220 Effect.gen(function* () {
221 const provider = yield* makeProvider({
222 execute: (input) => {
223 assert.deepStrictEqual(input.args, [
224 "api",
225 "--hostname",
226 "gitlab.com",
227 `projects/group%2Fsubgroup%2Fproject/${kind}/42`,
228 ]);
229 assert.strictEqual(input.maxOutputBytes, 32_000);
230 assert.strictEqual(input.timeoutMs, 3_000);
231 return Effect.succeed({
232 exitCode: ChildProcessSpawner.ExitCode(0),
233 stdout: JSON.stringify({
234 title: "Pairing expiry",
235 description: "Preserve remote access",
236 }),
237 stderr: "",
238 stdoutTruncated: false,
239 stderrTruncated: false,
240 });
241 },
242 });
243 const lookup = provider.resolveLink?.({
244 cwd: "/unrelated",
245 url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
246 });
247 assert.ok(lookup);
248 assert.deepStrictEqual(yield* lookup, {
249 title: "Pairing expiry",
250 body: "Preserve remote access",
251 });
252 for (const url of [
253 "https://gitlab.com/owner/repo",
254 "https://gitlab.attacker.test/team/project/-/issues/1",
255 ]) {
256 assert.strictEqual(
257 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
258 undefined,
259 );
260 }
261 }),
262);
263
264it.effect.each(["read", "decode"] as const)(
265 "retains the %s failure without exposing its raw contents",
266 (stage) =>
267 Effect.gen(function* () {
268 const cause = new GitLabCli.GitLabCliCommandError({
269 command: "glab",
270 cwd: "/repo",
271 operation: "execute",
272 cause: new Error("private response text"),
273 });
274 const provider = yield* makeProvider({
275 execute: () =>
276 stage === "read"
277 ? Effect.fail(cause)
278 : Effect.succeed({
279 exitCode: ChildProcessSpawner.ExitCode(0),
280 stdout: "private response text",
281 stderr: "",
282 stdoutTruncated: false,
283 stderrTruncated: false,
284 }),
285 });
286 const lookup = provider.resolveLink?.({
287 cwd: "/repo",
288 url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
289 });
290 assert.ok(lookup);
291 const error = yield* Effect.flip(lookup);
292 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
293 assert.strictEqual(error.detail, "The linked subject could not be read.");
294 assert.notInclude(error.message, "private response text");
295 if (stage === "read") assert.strictEqual(error.cause, cause);
296 else assert.propertyVal(error.cause, "_tag", "SchemaError");
297 }),
298);
299
300it.effect.each([
301 { headSelector: "octocat:feature/fix", source: undefined, sourceProject: "octocat/t3code" },
302 {
303 headSelector: "feature/fix",
304 source: { owner: "team/subgroup", refName: "feature/fix" },
305 sourceProject: "team/subgroup/t3code",
306 },
307 {
308 headSelector: "feature/fix",
309 source: { repository: "octocat/renamed-fork", refName: "feature/fix" },
310 sourceProject: "octocat/renamed-fork",
311 },
312])("creates a fork MR from $sourceProject into the current project", (testCase) =>
313 Effect.gen(function* () {
314 const requests: ReadonlyArray<string>[] = [];
315 const host = TestSourceControlHost.layer({
316 process: {
317 run: (input) => {
318 requests.push(input.args);
319 if (input.args[1] === "projects/:fullpath") {
320 return Effect.succeed(processOutput(JSON.stringify({ id: 100, path: "t3code" })));
321 }
322 assert.deepStrictEqual(input.args, [
323 "api",
324 "--method",
325 "POST",
326 `projects/${encodeURIComponent(testCase.sourceProject)}/merge_requests`,
327 "--raw-field",
328 "source_branch=feature/fix",
329 "--raw-field",
330 "target_branch=main",
331 "--raw-field",
332 "target_project_id=100",
333 "--raw-field",
334 "title=Fix remote flow",
335 "--field",
336 "description=@/tmp/body.md",
337 ]);
338 return Effect.succeed(processOutput("{}"));
339 },
340 },
341 });
342 const provider = yield* GitLabSourceControlProvider.make.pipe(
343 Effect.provide(Layer.merge(host, GitLabCli.layer.pipe(Layer.provide(host)))),
344 );
345 yield* provider.createChangeRequest({
346 cwd: "/repo",
347 baseRefName: "main",
348 headSelector: testCase.headSelector,
349 ...(testCase.source ? { source: testCase.source } : {}),
350 title: "Fix remote flow",
351 bodyFile: "/tmp/body.md",
352 });
353 assert.strictEqual(requests.length, 2);
354 assert.deepStrictEqual(requests[0], ["api", "projects/:fullpath"]);
355 }),
356);