Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, afterEach, describe, vi } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as PlatformError from "effect/PlatformError";
7import { ChildProcessSpawner } from "effect/process";
8import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
9
10import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { SpawnExecutableResolution } from "@t3tools/shared/shell";
14import { AzureCliInstallLocation, type AzureCliInstall } from "./azureCliLauncher.ts";
15import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
16
17const processOutput = (stdout: string): SourceControlHost.SourceControlProcessOutput => ({
18 exitCode: ChildProcessSpawner.ExitCode(0),
19 stdout,
20 stderr: "",
21 stdoutTruncated: false,
22 stderrTruncated: false,
23});
24
25const mockRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
26
27// The CLI layer is exercised on a host that spawns `az` itself, so the launcher upgrade stays out of these assertions.
28const layerSupport = Layer.mergeAll(
29 TestSourceControlHost.layer({ process: { run: mockRun } }),
30 NodeServices.layer,
31 Layer.succeed(HostProcess.Platform, "linux"),
32);
33const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(layerSupport)), layerSupport);
34
35afterEach(() => {
36 mockRun.mockReset();
37});
38
39describe("AzureDevOpsCli.layer", () => {
40 it.effect("parses pull request view output", () =>
41 Effect.gen(function* () {
42 mockRun.mockReturnValueOnce(
43 Effect.succeed(
44 processOutput(
45 JSON.stringify({
46 pullRequestId: 42,
47 title: "Add Azure provider",
48 sourceRefName: "refs/heads/feature/source-control",
49 targetRefName: "refs/heads/main",
50 lastMergeSourceCommit: { commitId: "a".repeat(40) },
51 status: "active",
52 creationDate: "2026-01-02T00:00:00.000Z",
53 closedDate: null,
54 _links: {
55 web: {
56 href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
57 },
58 },
59 }),
60 ),
61 ),
62 );
63
64 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
65 const result = yield* az.getPullRequest({
66 cwd: "/repo",
67 reference: "#42",
68 });
69
70 assert.strictEqual(result.number, 42);
71 assert.strictEqual(result.title, "Add Azure provider");
72 assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42");
73 assert.strictEqual(result.baseRefName, "main");
74 assert.strictEqual(result.headRefName, "feature/source-control");
75 assert.strictEqual(result.headSha, "a".repeat(40));
76 assert.strictEqual(result.state, "open");
77 assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
78 const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
79 assert.strictEqual(
80 classifyFailure?.("Please run az login to setup account."),
81 "authentication",
82 );
83 assert.strictEqual(
84 classifyFailure?.("Please run 'az login' to setup account."),
85 "authentication",
86 );
87 assert.strictEqual(
88 classifyFailure?.("TF401180: The requested pull request was not found."),
89 "not-found",
90 );
91 assert.strictEqual(
92 classifyFailure?.(
93 "ERROR: TF400733: The request has been canceled: Request was blocked due to exceeding usage of resource 'Global' in namespace 'User'.",
94 ),
95 "rate-limited",
96 );
97 assert.deepStrictEqual(call, {
98 operation: "AzureDevOpsCli.execute",
99 command: "az",
100 args: [
101 "repos",
102 "pr",
103 "show",
104 "--detect",
105 "true",
106 "--id",
107 "42",
108 "--only-show-errors",
109 "--output",
110 "json",
111 ],
112 cwd: "/repo",
113 notFoundDetail: "Pull request not found.",
114 timeoutMs: 30_000,
115 });
116 assert.strictEqual(result.isCrossRepository, false);
117 }).pipe(Effect.provide(layer)),
118 );
119
120 it.effect("marks a pull request from a fork as cross-repository", () =>
121 Effect.gen(function* () {
122 mockRun.mockReturnValueOnce(
123 Effect.succeed(
124 processOutput(
125 JSON.stringify({
126 pullRequestId: 43,
127 title: "From a fork",
128 sourceRefName: "refs/heads/main",
129 targetRefName: "refs/heads/main",
130 status: "active",
131 forkSource: { name: "refs/heads/main", repository: { name: "repo-fork" } },
132 }),
133 ),
134 ),
135 );
136
137 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
138 const result = yield* az.getPullRequest({ cwd: "/repo", reference: "43" });
139
140 assert.strictEqual(result.isCrossRepository, true);
141 }).pipe(Effect.provide(layer)),
142 );
143
144 it.effect("builds a web URL when Azure returns only the pull request REST URL", () =>
145 Effect.gen(function* () {
146 mockRun.mockReturnValueOnce(
147 Effect.succeed(
148 processOutput(
149 JSON.stringify({
150 pullRequestId: 863,
151 title: "Fix Azure link",
152 url: "https://dev.azure.com/saplyai/a8fe4088-ad76-4eda-aaaa-e3329713a097/_apis/git/repositories/16108a25-93a3-4eff-b77d-85e894ee0fe4/pullRequests/863",
153 repository: {
154 name: "CV-engine",
155 project: {
156 name: "CV-engine",
157 },
158 },
159 sourceRefName: "refs/heads/feature/azure-pr-link",
160 targetRefName: "refs/heads/main",
161 status: "active",
162 }),
163 ),
164 ),
165 );
166
167 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
168 const result = yield* az.getPullRequest({
169 cwd: "/repo",
170 reference: "863",
171 });
172
173 assert.strictEqual(
174 result.url,
175 "https://dev.azure.com/saplyai/CV-engine/_git/CV-engine/pullrequest/863",
176 );
177 }).pipe(Effect.provide(layer)),
178 );
179
180 it.effect("reads repository clone URLs", () =>
181 Effect.gen(function* () {
182 mockRun.mockReturnValueOnce(
183 Effect.succeed(
184 processOutput(
185 JSON.stringify({
186 name: "repo",
187 webUrl: "https://dev.azure.com/acme/project/_git/repo",
188 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
189 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
190 project: {
191 name: "project",
192 },
193 }),
194 ),
195 ),
196 );
197
198 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
199 const result = yield* az.getRepositoryCloneUrls({
200 cwd: "/repo",
201 repository: "repo",
202 });
203
204 assert.deepStrictEqual(result, {
205 nameWithOwner: "project/repo",
206 url: "https://dev.azure.com/acme/project/_git/repo",
207 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
208 });
209 }).pipe(Effect.provide(layer)),
210 );
211
212 it.effect("looks up a project/repository path as that project's repository", () =>
213 Effect.gen(function* () {
214 mockRun.mockReturnValueOnce(
215 Effect.succeed(
216 processOutput(
217 JSON.stringify({
218 name: "repo",
219 webUrl: "https://dev.azure.com/acme/project/_git/repo",
220 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
221 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
222 project: { name: "project" },
223 }),
224 ),
225 ),
226 );
227
228 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
229 yield* az.getRepositoryCloneUrls({ cwd: "/somewhere", repository: "project/repo" });
230
231 assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0].args, [
232 "repos",
233 "show",
234 "--detect",
235 "true",
236 "--repository",
237 "repo",
238 "--project",
239 "project",
240 "--only-show-errors",
241 "--output",
242 "json",
243 ]);
244 }).pipe(Effect.provide(layer)),
245 );
246
247 it.effect("percent-encodes the source branch while preserving recognized ref prefixes", () =>
248 Effect.gen(function* () {
249 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
250
251 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
252 yield* az.listPullRequests({
253 cwd: "/somewhere",
254 headSelector: "user/feat/1-(#2)-slug",
255 state: "open",
256 });
257
258 const args = mockRun.mock.calls.at(-1)?.[0].args ?? [];
259 assert.strictEqual(args[args.indexOf("--source-branch") + 1], "user%2Ffeat%2F1-(%232)-slug");
260
261 for (const prefix of ["refs/heads/", "refs/pull/", "refs/tags/"]) {
262 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
263 yield* az.listPullRequests({
264 cwd: "/somewhere",
265 headSelector: "fallback",
266 source: { refName: `${prefix}user/feat/1-(#2)-slug` },
267 state: "open",
268 });
269
270 const refArgs = mockRun.mock.calls.at(-1)?.[0].args ?? [];
271 assert.strictEqual(
272 refArgs[refArgs.indexOf("--source-branch") + 1],
273 `${prefix}user%2Ffeat%2F1-(%232)-slug`,
274 );
275 }
276 }).pipe(Effect.provide(layer)),
277 );
278
279 it.effect("preserves VCS causes without copying upstream details into messages", () =>
280 Effect.gen(function* () {
281 const cause = new VcsProcessExitError({
282 operation: "AzureDevOpsCli.execute",
283 command: "az repos list --organization sensitive-upstream-detail",
284 cwd: "/repo",
285 exitCode: 1,
286 detail: "sensitive-upstream-detail",
287 });
288 mockRun.mockReturnValueOnce(Effect.fail(cause));
289
290 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
291 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
292
293 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
294 assert.strictEqual(error.operation, "execute");
295 assert.strictEqual(error.command, "az");
296 assert.strictEqual(error.cwd, "/repo");
297 assert.strictEqual(error.argumentCount, 2);
298 assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
299 assert.strictEqual(error.cause, cause);
300 assert.equal(error.message.includes("sensitive-upstream-detail"), false);
301 }).pipe(Effect.provide(layer)),
302 );
303
304 it.effect("does not report a missing working directory as a missing Azure CLI", () =>
305 Effect.gen(function* () {
306 const cwd = "/missing/repo";
307 const platformCause = PlatformError.systemError({
308 _tag: "NotFound",
309 module: "ChildProcess",
310 method: "spawn",
311 syscall: "chdir",
312 pathOrDescriptor: cwd,
313 });
314 const cause = new VcsProcessSpawnError({
315 operation: "AzureDevOpsCli.execute",
316 command: "az",
317 cwd,
318 argumentCount: 2,
319 cause: platformCause,
320 });
321 mockRun.mockReturnValueOnce(Effect.fail(cause));
322
323 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
324 const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
325
326 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
327 assert.strictEqual(error.cwd, cwd);
328 assert.strictEqual(error.cause, cause);
329 }).pipe(Effect.provide(layer)),
330 );
331
332 it.effect("preserves rate-limit failures as a distinct error", () =>
333 Effect.gen(function* () {
334 const cause = new VcsProcessExitError({
335 operation: "AzureDevOpsCli.execute",
336 command: "az",
337 cwd: "/repo",
338 argumentCount: 2,
339 exitCode: 1,
340 detail: "API rate limit exceeded.",
341 failureKind: "rate-limited",
342 });
343 mockRun.mockReturnValueOnce(Effect.fail(cause));
344
345 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
346 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
347
348 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCliRateLimitError);
349 assert.strictEqual(error.cause, cause);
350 }).pipe(Effect.provide(layer)),
351 );
352});
353
354describe("azureCliInvocation", () => {
355 const launcher = "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd";
356 const msi: AzureCliInstall = {
357 interpreter: "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\python.exe",
358 installer: "MSI",
359 };
360
361 const invocationFor = (install: AzureCliInstall | undefined) =>
362 AzureDevOpsCli.azureCliInvocation().pipe(
363 Effect.provideService(HostProcess.Platform, "win32"),
364 Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }),
365 Effect.provideService(SpawnExecutableResolution, () => launcher),
366 Effect.provideService(AzureCliInstallLocation, () => install),
367 );
368
369 it.effect("runs the install's interpreter in UTF-8 mode", () =>
370 Effect.gen(function* () {
371 assert.deepStrictEqual(yield* invocationFor(msi), {
372 command: msi.interpreter,
373 args: ["-X", "utf8", "-IBm", "azure.cli"],
374 env: { AZ_INSTALLER: "MSI" },
375 });
376 }),
377 );
378
379 it.effect("keeps the launcher when the install is not recognized", () =>
380 Effect.gen(function* () {
381 assert.deepStrictEqual(yield* invocationFor(undefined), {
382 command: "az",
383 args: [],
384 });
385 }),
386 );
387
388 it.effect("spawns az directly off Windows", () =>
389 Effect.gen(function* () {
390 const invocation = yield* AzureDevOpsCli.azureCliInvocation().pipe(
391 Effect.provideService(HostProcess.Platform, "linux"),
392 );
393
394 assert.deepStrictEqual(invocation, { command: "az", args: [] });
395 }),
396 );
397});