Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import type { GitCommandError } from "@t3tools/contracts";
7
8import { assert, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
14import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15
16import * as GitLabCli from "./GitLabCli.ts";
17import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
18
19it.effect("lists a nested-group fork's merge requests by source branch and names its project", () =>
20 Effect.gen(function* () {
21 const branch = "feature/NestedGroups";
22 const output = JSON.stringify([
23 {
24 iid: 2,
25 title: "Another subgroup's fork",
26 web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/2",
27 target_branch: "main",
28 source_branch: branch,
29 state: "opened",
30 updated_at: "2026-04-08T15:00:00Z",
31 source_project_id: 102,
32 target_project_id: 100,
33 source_project: { path_with_namespace: "Group/Other/Fork" },
34 },
35 {
36 iid: 1,
37 title: "This subgroup's fork",
38 web_url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
39 target_branch: "main",
40 source_branch: branch,
41 state: "opened",
42 updated_at: "2026-04-07T15:00:00Z",
43 source_project_id: 101,
44 target_project_id: 100,
45 source_project: { path_with_namespace: "Group/Subgroup/Fork" },
46 },
47 ]);
48 const calls: SourceControlHost.SourceControlProcessInput[] = [];
49 const provider = yield* GitLabSourceControlProvider.make.pipe(
50 Effect.provide(
51 GitLabCli.layer.pipe(
52 Layer.provideMerge(
53 TestSourceControlHost.layer({
54 process: {
55 run: (input) =>
56 Effect.sync(() => {
57 calls.push(input);
58 return TestSourceControlHost.processOutput(output);
59 }),
60 },
61 }),
62 ),
63 Layer.provide(FileSystem.layerNoop({})),
64 ),
65 ),
66 );
67
68 for (const headSelector of [branch, `Group/Subgroup:${branch}`]) {
69 const changeRequests = yield* provider.listChangeRequests({
70 cwd: "/repo",
71 headSelector,
72 state: "all",
73 limit: 20,
74 });
75 expect(changeRequests).toMatchObject([
76 {
77 number: 2,
78 headRefName: branch,
79 isCrossRepository: true,
80 headRepositoryNameWithOwner: "Group/Other/Fork",
81 },
82 {
83 number: 1,
84 url: "https://gitlab.com/Group/Upstream/Repository/-/merge_requests/1",
85 headRefName: branch,
86 isCrossRepository: true,
87 headRepositoryNameWithOwner: "Group/Subgroup/Fork",
88 },
89 ]);
90 }
91 assert.lengthOf(calls, 2);
92 for (const call of calls) {
93 expect(call.command).toBe("glab");
94 expect(call.args).toEqual([
95 "mr",
96 "list",
97 "--source-branch",
98 branch,
99 "--all",
100 "--per-page",
101 "20",
102 "--output",
103 "json",
104 ]);
105 }
106 }),
107);
108
109// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its
110// source project only by `source_project_id`, never by a `source_project` path.
111it.effect("names a fork merge request's source project from real glab list output", () =>
112 Effect.gen(function* () {
113 const branch = "feature/fork-work";
114 const mergeRequest = (iid: number, sourceProjectId: number) => ({
115 id: 9000 + iid,
116 iid,
117 project_id: 100,
118 title: `Work ${iid}`,
119 state: "opened",
120 target_branch: "main",
121 source_branch: branch,
122 source_project_id: sourceProjectId,
123 target_project_id: 100,
124 draft: false,
125 sha: "0123456789abcdef0123456789abcdef01234567",
126 updated_at: "2026-04-07T15:00:00.000Z",
127 references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` },
128 web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`,
129 });
130 const output = JSON.stringify([
131 mergeRequest(1, 101),
132 mergeRequest(2, 101),
133 mergeRequest(3, 100),
134 mergeRequest(4, 102),
135 ]);
136 const apiCalls: ReadonlyArray<string>[] = [];
137 const provider = yield* GitLabSourceControlProvider.make.pipe(
138 Effect.provide(
139 GitLabCli.layer.pipe(
140 Layer.provideMerge(
141 TestSourceControlHost.layer({
142 process: {
143 run: (input) =>
144 Effect.sync(() => {
145 if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output);
146 apiCalls.push(input.args);
147 return TestSourceControlHost.processOutput(
148 input.args[1] === "projects/101"
149 ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" })
150 : "not json",
151 );
152 }),
153 },
154 }),
155 ),
156 Layer.provide(FileSystem.layerNoop({})),
157 ),
158 ),
159 );
160
161 const upstreamHead = yield* provider.listChangeRequests({
162 cwd: "/repo",
163 headSelector: branch,
164 state: "open",
165 limit: 20,
166 });
167 expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner");
168 expect(apiCalls).toEqual([]);
169
170 const changeRequests = yield* provider.listChangeRequests({
171 cwd: "/repo",
172 headSelector: `alice:${branch}`,
173 state: "open",
174 limit: 20,
175 });
176 // GitManager drops a cross-repository MR whose head project is unnamed.
177 expect(changeRequests).toMatchObject([
178 {
179 number: 1,
180 isCrossRepository: true,
181 headRepositoryNameWithOwner: "alice/upstream",
182 headRepositoryOwnerLogin: "alice",
183 },
184 { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" },
185 { number: 3, isCrossRepository: false },
186 { number: 4, isCrossRepository: true },
187 ]);
188 expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner");
189 expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner");
190 expect(apiCalls).toHaveLength(2);
191 expect(apiCalls).toEqual(
192 expect.arrayContaining([
193 ["api", "projects/101"],
194 ["api", "projects/102"],
195 ]),
196 );
197 }),
198);
199
200const withRepository = <A, E>(
201 test: (input: {
202 readonly git: (...args: string[]) => Effect.Effect<string, GitCommandError>;
203 readonly write: (path: string, contents: string) => Effect.Effect<void>;
204 readonly readTemplate: (treeish?: string) => Effect.Effect<Option.Option<string>>;
205 }) => Effect.Effect<A, E>,
206) =>
207 Effect.gen(function* () {
208 const host = yield* SourceControlHost.SourceControlHost;
209 const cwd = yield* Effect.acquireRelease(
210 Effect.sync(() => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-gitlab-template-"))),
211 (directory) => Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
212 );
213 const git = (...args: string[]) =>
214 host.git
215 .execute({ operation: "GitLabTemplate.test", cwd, args })
216 .pipe(Effect.map((result) => result.stdout.trim()));
217 const write = (path: string, contents: string) =>
218 Effect.sync(() => {
219 NodeFS.mkdirSync(NodePath.dirname(NodePath.join(cwd, path)), { recursive: true });
220 NodeFS.writeFileSync(NodePath.join(cwd, path), contents);
221 });
222 yield* git("init", "--initial-branch=main");
223 yield* git("config", "user.email", "test@example.com");
224 yield* git("config", "user.name", "Test User");
225 yield* write("README.md", "hello\n");
226 yield* git("add", "README.md");
227 yield* git("commit", "-m", "Initial commit");
228 const provider = yield* GitLabSourceControlProvider.make.pipe(
229 Effect.provide(Layer.mock(GitLabCli.GitLabCli)({})),
230 );
231 return yield* test({
232 git,
233 write,
234 readTemplate: (treeish = "HEAD") => provider.readChangeRequestTemplate!({ cwd, treeish }),
235 });
236 }).pipe(Effect.scoped, Effect.provide(TestSourceControlHost.layerWithRealGit()));
237
238const DEFAULT_TEMPLATE = ".gitlab/merge_request_templates/Default.md";
239
240it.effect("ignores unavailable or non-regular GitLab default templates", () =>
241 withRepository(({ git, write, readTemplate }) =>
242 Effect.gen(function* () {
243 expect(yield* readTemplate()).toEqual(Option.none());
244
245 yield* write(".gitlab/merge_request_templates/Bugfix.md", "Not the default");
246 yield* git("add", ".gitlab");
247 yield* git("commit", "-m", "Add a selectable template");
248 expect(yield* readTemplate()).toEqual(Option.none());
249
250 yield* write(DEFAULT_TEMPLATE, " \n\n");
251 yield* git("add", ".gitlab");
252 yield* git("commit", "-m", "Add a blank default");
253 expect(yield* readTemplate()).toEqual(Option.none());
254
255 // Index modes exercise committed symlinks and submodules even on hosts without symlinks.
256 const blob = yield* git("rev-parse", "HEAD:README.md");
257 yield* git("update-index", "--cacheinfo", "120000", blob, DEFAULT_TEMPLATE);
258 yield* git("commit", "-m", "Replace default with a symlink");
259 expect(yield* readTemplate()).toEqual(Option.none());
260
261 const commit = yield* git("rev-parse", "HEAD");
262 yield* git("update-index", "--cacheinfo", "160000", commit, DEFAULT_TEMPLATE);
263 yield* git("commit", "-m", "Replace default with a submodule");
264 expect(yield* readTemplate()).toEqual(Option.none());
265 expect(yield* readTemplate("missing-base")).toEqual(Option.none());
266 }),
267 ),
268);
269
270it.effect("bounds GitLab template content and marks truncation", () =>
271 withRepository(({ git, write, readTemplate }) =>
272 Effect.gen(function* () {
273 const prefix = "a".repeat(8_000);
274 yield* write(DEFAULT_TEMPLATE, prefix + "EXCLUDED_SUFFIX");
275 yield* git("add", ".gitlab");
276 yield* git("commit", "-m", "Add a large template");
277
278 expect(yield* readTemplate()).toEqual(Option.some(prefix + "\n\n[truncated]"));
279 }),
280 ),
281);