Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it, afterEach, describe, expect, 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";
16import { primaryRemoteUrl, scopeAzureCliArgs } from "./AzureDevOpsCli.ts";
17
18const processOutput = (stdout: string): SourceControlHost.SourceControlProcessOutput => ({
19 exitCode: ChildProcessSpawner.ExitCode(0),
20 stdout,
21 stderr: "",
22 stdoutTruncated: false,
23 stderrTruncated: false,
24});
25
26const mockRun = vi.fn<SourceControlHost.SourceControlHost["Service"]["process"]["run"]>();
27
28// The CLI layer is exercised on a host that spawns `az` itself, so the launcher upgrade stays out of these assertions.
29const layerSupport = Layer.mergeAll(
30 TestSourceControlHost.layer({
31 // No remotes: these cases leave `--detect true` to az.
32 process: {
33 run: (input) =>
34 input.command === "git" ? Effect.succeed(processOutput("")) : mockRun(input),
35 },
36 }),
37 NodeServices.layer,
38 Layer.succeed(HostProcess.Platform, "linux"),
39);
40const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(layerSupport)), layerSupport);
41
42afterEach(() => {
43 mockRun.mockReset();
44});
45
46describe("AzureDevOpsCli.layer", () => {
47 it.effect("parses pull request view output", () =>
48 Effect.gen(function* () {
49 mockRun.mockReturnValueOnce(
50 Effect.succeed(
51 processOutput(
52 JSON.stringify({
53 pullRequestId: 42,
54 title: "Add Azure provider",
55 sourceRefName: "refs/heads/feature/source-control",
56 targetRefName: "refs/heads/main",
57 lastMergeSourceCommit: { commitId: "a".repeat(40) },
58 status: "active",
59 creationDate: "2026-01-02T00:00:00.000Z",
60 closedDate: null,
61 _links: {
62 web: {
63 href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
64 },
65 },
66 }),
67 ),
68 ),
69 );
70
71 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
72 const result = yield* az.getPullRequest({
73 cwd: "/repo",
74 reference: "#42",
75 // The selected remote numbers the pull request, whatever the checkout's primary remote.
76 remoteUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
77 });
78
79 assert.strictEqual(result.number, 42);
80 assert.strictEqual(result.title, "Add Azure provider");
81 assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42");
82 assert.strictEqual(result.baseRefName, "main");
83 assert.strictEqual(result.headRefName, "feature/source-control");
84 assert.strictEqual(result.headSha, "a".repeat(40));
85 assert.strictEqual(result.state, "open");
86 assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
87 const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
88 assert.strictEqual(
89 classifyFailure?.("Please run az login to setup account."),
90 "authentication",
91 );
92 assert.strictEqual(
93 classifyFailure?.("Please run 'az login' to setup account."),
94 "authentication",
95 );
96 assert.strictEqual(
97 classifyFailure?.("TF401180: The requested pull request was not found."),
98 "not-found",
99 );
100 assert.strictEqual(
101 classifyFailure?.(
102 "ERROR: TF400733: The request has been canceled: Request was blocked due to exceeding usage of resource 'Global' in namespace 'User'.",
103 ),
104 "rate-limited",
105 );
106 assert.deepStrictEqual(call, {
107 operation: "AzureDevOpsCli.execute",
108 command: "az",
109 args: [
110 "repos",
111 "pr",
112 "show",
113 "--detect",
114 "false",
115 "--id",
116 "42",
117 "--only-show-errors",
118 "--output",
119 "json",
120 "--organization",
121 "https://dev.azure.com/acme",
122 ],
123 cwd: "/repo",
124 notFoundDetail: "Pull request not found.",
125 timeoutMs: 30_000,
126 });
127 assert.strictEqual(result.isCrossRepository, false);
128 }).pipe(Effect.provide(layer)),
129 );
130
131 it.effect("marks a pull request from a fork as cross-repository", () =>
132 Effect.gen(function* () {
133 mockRun.mockReturnValueOnce(
134 Effect.succeed(
135 processOutput(
136 JSON.stringify({
137 pullRequestId: 43,
138 title: "From a fork",
139 sourceRefName: "refs/heads/main",
140 targetRefName: "refs/heads/main",
141 status: "active",
142 forkSource: { name: "refs/heads/main", repository: { name: "repo-fork" } },
143 }),
144 ),
145 ),
146 );
147
148 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
149 const result = yield* az.getPullRequest({ cwd: "/repo", reference: "43" });
150
151 assert.strictEqual(result.isCrossRepository, true);
152 }).pipe(Effect.provide(layer)),
153 );
154
155 it.effect("builds a web URL when Azure returns only the pull request REST URL", () =>
156 Effect.gen(function* () {
157 mockRun.mockReturnValueOnce(
158 Effect.succeed(
159 processOutput(
160 JSON.stringify({
161 pullRequestId: 863,
162 title: "Fix Azure link",
163 url: "https://dev.azure.com/saplyai/a8fe4088-ad76-4eda-aaaa-e3329713a097/_apis/git/repositories/16108a25-93a3-4eff-b77d-85e894ee0fe4/pullRequests/863",
164 repository: {
165 name: "CV-engine",
166 project: {
167 name: "CV-engine",
168 },
169 },
170 sourceRefName: "refs/heads/feature/azure-pr-link",
171 targetRefName: "refs/heads/main",
172 status: "active",
173 }),
174 ),
175 ),
176 );
177
178 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
179 const result = yield* az.getPullRequest({
180 cwd: "/repo",
181 reference: "863",
182 });
183
184 assert.strictEqual(
185 result.url,
186 "https://dev.azure.com/saplyai/CV-engine/_git/CV-engine/pullrequest/863",
187 );
188 }).pipe(Effect.provide(layer)),
189 );
190
191 it.effect("reads repository clone URLs", () =>
192 Effect.gen(function* () {
193 mockRun.mockReturnValueOnce(
194 Effect.succeed(
195 processOutput(
196 JSON.stringify({
197 name: "repo",
198 webUrl: "https://dev.azure.com/acme/project/_git/repo",
199 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
200 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
201 project: {
202 name: "project",
203 },
204 }),
205 ),
206 ),
207 );
208
209 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
210 const result = yield* az.getRepositoryCloneUrls({
211 cwd: "/repo",
212 repository: "repo",
213 });
214
215 assert.deepStrictEqual(result, {
216 nameWithOwner: "project/repo",
217 url: "https://dev.azure.com/acme/project/_git/repo",
218 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
219 });
220 }).pipe(Effect.provide(layer)),
221 );
222
223 it.effect("looks up a project/repository path as that project's repository", () =>
224 Effect.gen(function* () {
225 mockRun.mockReturnValueOnce(
226 Effect.succeed(
227 processOutput(
228 JSON.stringify({
229 name: "repo",
230 webUrl: "https://dev.azure.com/acme/project/_git/repo",
231 remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
232 sshUrl: "git@ssh.dev.azure.com:v3/acme/project/repo",
233 project: { name: "project" },
234 }),
235 ),
236 ),
237 );
238
239 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
240 yield* az.getRepositoryCloneUrls({ cwd: "/somewhere", repository: "project/repo" });
241
242 assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0].args, [
243 "repos",
244 "show",
245 "--detect",
246 "true",
247 "--repository",
248 "repo",
249 "--project",
250 "project",
251 "--only-show-errors",
252 "--output",
253 "json",
254 ]);
255 }).pipe(Effect.provide(layer)),
256 );
257
258 it.effect("percent-encodes the source branch while preserving recognized ref prefixes", () =>
259 Effect.gen(function* () {
260 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
261
262 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
263 yield* az.listPullRequests({
264 cwd: "/somewhere",
265 headSelector: "user/feat/1-(#2)-slug",
266 state: "open",
267 });
268
269 const args = mockRun.mock.calls.at(-1)?.[0].args ?? [];
270 assert.strictEqual(args[args.indexOf("--source-branch") + 1], "user%2Ffeat%2F1-(%232)-slug");
271
272 for (const prefix of ["refs/heads/", "refs/pull/", "refs/tags/"]) {
273 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
274 yield* az.listPullRequests({
275 cwd: "/somewhere",
276 headSelector: "fallback",
277 source: { refName: `${prefix}user/feat/1-(#2)-slug` },
278 state: "open",
279 });
280
281 const refArgs = mockRun.mock.calls.at(-1)?.[0].args ?? [];
282 assert.strictEqual(
283 refArgs[refArgs.indexOf("--source-branch") + 1],
284 `${prefix}user%2Ffeat%2F1-(%232)-slug`,
285 );
286 }
287 }).pipe(Effect.provide(layer)),
288 );
289
290 it.effect("sends a title that looks like `@path` as text, not as a file for az to read", () =>
291 Effect.gen(function* () {
292 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
293 for (const title of ["@notes.txt", "a=@notes.txt"]) {
294 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
295 yield* az.createPullRequest({
296 cwd: "/somewhere",
297 baseBranch: "main",
298 headSelector: "feature",
299 title,
300 bodyFile: "/tmp/body.md",
301 });
302
303 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
304 const fileReads = (mockRun.mock.calls.at(-1)?.[0].args ?? []).flatMap((arg) => {
305 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
306 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
307 ? [value.slice(1)]
308 : [];
309 });
310 expect(fileReads).not.toContain("notes.txt");
311 expect(mockRun.mock.calls.at(-1)?.[0].stdin).toBe(
312 title.startsWith("@") ? title : undefined,
313 );
314 // az expands a separate `@file` value a second time, so a body of `@notes.txt` read notes.txt.
315 expect(mockRun.mock.calls.at(-1)?.[0].args).toContain("--description=@/tmp/body.md");
316 }
317 }).pipe(Effect.provide(layer)),
318 );
319
320 it.effect("preserves VCS causes without copying upstream details into messages", () =>
321 Effect.gen(function* () {
322 const cause = new VcsProcessExitError({
323 operation: "AzureDevOpsCli.execute",
324 command: "az repos list --organization sensitive-upstream-detail",
325 cwd: "/repo",
326 exitCode: 1,
327 detail: "sensitive-upstream-detail",
328 });
329 mockRun.mockReturnValueOnce(Effect.fail(cause));
330
331 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
332 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
333
334 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
335 assert.strictEqual(error.operation, "execute");
336 assert.strictEqual(error.command, "az");
337 assert.strictEqual(error.cwd, "/repo");
338 assert.strictEqual(error.argumentCount, 2);
339 assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
340 assert.strictEqual(error.cause, cause);
341 assert.equal(error.message.includes("sensitive-upstream-detail"), false);
342 }).pipe(Effect.provide(layer)),
343 );
344
345 it.effect("does not report a missing working directory as a missing Azure CLI", () =>
346 Effect.gen(function* () {
347 const cwd = "/missing/repo";
348 const platformCause = PlatformError.systemError({
349 _tag: "NotFound",
350 module: "ChildProcess",
351 method: "spawn",
352 syscall: "chdir",
353 pathOrDescriptor: cwd,
354 });
355 const cause = new VcsProcessSpawnError({
356 operation: "AzureDevOpsCli.execute",
357 command: "az",
358 cwd,
359 argumentCount: 2,
360 cause: platformCause,
361 });
362 mockRun.mockReturnValueOnce(Effect.fail(cause));
363
364 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
365 const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
366
367 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
368 assert.strictEqual(error.cwd, cwd);
369 assert.strictEqual(error.cause, cause);
370 }).pipe(Effect.provide(layer)),
371 );
372
373 it.effect("preserves rate-limit failures as a distinct error", () =>
374 Effect.gen(function* () {
375 const cause = new VcsProcessExitError({
376 operation: "AzureDevOpsCli.execute",
377 command: "az",
378 cwd: "/repo",
379 argumentCount: 2,
380 exitCode: 1,
381 detail: "API rate limit exceeded.",
382 failureKind: "rate-limited",
383 });
384 mockRun.mockReturnValueOnce(Effect.fail(cause));
385
386 const az = yield* AzureDevOpsCli.AzureDevOpsCli;
387 const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
388
389 assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCliRateLimitError);
390 assert.strictEqual(error.cause, cause);
391 }).pipe(Effect.provide(layer)),
392 );
393});
394
395describe("azureCliInvocation", () => {
396 const launcher = "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\wbin\\az.cmd";
397 const msi: AzureCliInstall = {
398 interpreter: "C:\\Program Files\\Microsoft SDKs\\Azure\\CLI2\\python.exe",
399 installer: "MSI",
400 };
401
402 const invocationFor = (install: AzureCliInstall | undefined) =>
403 AzureDevOpsCli.azureCliInvocation().pipe(
404 Effect.provideService(HostProcess.Platform, "win32"),
405 Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }),
406 Effect.provideService(SpawnExecutableResolution, () => launcher),
407 Effect.provideService(AzureCliInstallLocation, () => install),
408 );
409
410 it.effect("runs the install's interpreter in UTF-8 mode", () =>
411 Effect.gen(function* () {
412 assert.deepStrictEqual(yield* invocationFor(msi), {
413 command: msi.interpreter,
414 args: ["-X", "utf8", "-IBm", "azure.cli"],
415 env: { AZ_INSTALLER: "MSI" },
416 });
417 }),
418 );
419
420 it.effect("keeps the launcher when the install is not recognized", () =>
421 Effect.gen(function* () {
422 assert.deepStrictEqual(yield* invocationFor(undefined), {
423 command: "az",
424 args: [],
425 });
426 }),
427 );
428
429 it.effect("spawns az directly off Windows", () =>
430 Effect.gen(function* () {
431 const invocation = yield* AzureDevOpsCli.azureCliInvocation().pipe(
432 Effect.provideService(HostProcess.Platform, "linux"),
433 );
434
435 assert.deepStrictEqual(invocation, { command: "az", args: [] });
436 }),
437 );
438});
439
440describe("scopeAzureCliArgs", () => {
441 const origin = "https://dev.azure.com/acme/Project/_git/Repo";
442 const show = ["repos", "show", "--detect", "true"];
443
444 it.each([
445 [
446 ["repos", "show"],
447 ["--project=Project", "--repository=Repo"],
448 ],
449 [["repos", "create", "--name", "New"], ["--project=Project"]],
450 [
451 ["repos", "pr", "list"],
452 ["--project=Project", "--repository=Repo"],
453 ],
454 [
455 ["repos", "pr", "create"],
456 ["--project=Project", "--repository=Repo"],
457 ],
458 [["repos", "pr", "show", "--id", "42"], []],
459 [["devops", "invoke", "--area", "git"], []],
460 ])("scopes %j to the commands' supported arguments", (command, scope) => {
461 expect(scopeAzureCliArgs([...command, "--detect", "true"], origin)).toEqual([
462 ...command,
463 "--detect",
464 "false",
465 "--organization",
466 "https://dev.azure.com/acme",
467 ...scope,
468 ]);
469 });
470
471 it.each([
472 ["https://dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
473 ["https://user@dev.azure.com/acme/My%20Project/_git/My%20Repo", "https://dev.azure.com/acme"],
474 [
475 "https://acme.visualstudio.com/DefaultCollection/My%20Project/_git/My%20Repo",
476 "https://acme.visualstudio.com",
477 ],
478 ["https://acme.visualstudio.com/My%20Project/_git/My%20Repo", "https://acme.visualstudio.com"],
479 ["git@ssh.dev.azure.com:v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
480 ["ssh://git@ssh.dev.azure.com:22/v3/acme/My%20Project/My%20Repo", "https://dev.azure.com/acme"],
481 ["git@vs-ssh.visualstudio.com:v3/acme/My%20Project/My%20Repo", "https://acme.visualstudio.com"],
482 ])("reads the organization of %s", (url, organization) => {
483 expect(scopeAzureCliArgs(show, url)).toEqual([
484 "repos",
485 "show",
486 "--detect",
487 "false",
488 "--organization",
489 organization,
490 "--project=My Project",
491 "--repository=My Repo",
492 ]);
493 });
494
495 it("joins names starting with `-` to their options", () => {
496 expect(
497 scopeAzureCliArgs(
498 ["repos", "pr", "list", "--detect", "true"],
499 "https://dev.azure.com/acme/-Project/_git/-Repo",
500 ),
501 ).toEqual(expect.arrayContaining(["--project=-Project", "--repository=-Repo"]));
502 });
503
504 it("keeps the caller's project and repository", () => {
505 for (const selection of [
506 ["--project", "Chosen", "--repository", "Chosen"],
507 ["-p", "Chosen", "-r", "Chosen"],
508 ["--repository=Chosen", "--project", "Chosen"],
509 ]) {
510 expect(
511 scopeAzureCliArgs(["repos", "show", ...selection, "--detect", "true"], origin),
512 ).toEqual([
513 "repos",
514 "show",
515 ...selection,
516 "--detect",
517 "false",
518 "--organization",
519 "https://dev.azure.com/acme",
520 ]);
521 }
522 });
523
524 it.each([
525 [["account", "show", "--detect", "true"], origin],
526 [["repos", "show"], origin],
527 [["repos", "show", "--detect", "false"], origin],
528 [["repos", "show", "--detect", "true", "--org", "https://dev.azure.com/explicit"], origin],
529 [show, "https://github.com/acme/repo"],
530 [show, "https://dev.azure.com/acme"],
531 [show, "https://dev.azure.com/acme/%XX/_git/Repo"],
532 [show, "git@ssh.dev.azure.com:v4/acme/Project/Repo"],
533 [show, "git@vs-ssh.visualstudio.com:v3/acme.invalid/Project/Repo"],
534 // az would replace the value with the contents of a local file.
535 [show, "https://dev.azure.com/acme/Project/_git/%40.env"],
536 ])("leaves %j to az when %s gives no scope", (args, url) => {
537 expect(scopeAzureCliArgs(args, url)).toEqual(args);
538 });
539});
540
541describe("primaryRemoteUrl", () => {
542 const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
543 entries.map(([name, url]) => `${name}\t${url} (fetch)\n${name}\tpush-url (push)\n`).join("");
544 const azure = (name: string) => [name, `https://dev.azure.com/${name}/P/_git/R`] as const;
545
546 it.each([
547 // Where T3 publishes the branch and creates its pull requests.
548 [remotes(azure("upstream"), azure("origin")), azure("origin")[1]],
549 [
550 remotes(["github", "https://github.com/acme/repo"], azure("zebra"), azure("alpha")),
551 azure("zebra")[1],
552 ],
553 // A non-Azure origin leaves detection to az rather than scoping another repository.
554 [
555 remotes(azure("upstream"), ["origin", "https://github.com/acme/repo"]),
556 "https://github.com/acme/repo",
557 ],
558 [remotes(), null],
559 [`origin\t${azure("origin")[1]} (fetch)`, null],
560 ])("picks the scoping remote from %j", (output, url) => {
561 expect(primaryRemoteUrl(output)).toBe(url);
562 });
563});