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

AzureDevOpsPullRequestCli.test.ts

1,162 lines39.0 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Builds the zip Azure returns and stands in for az writing it.
2import * as NodeFS from "node:fs";
3import * as NodeZlib from "node:zlib";
4​
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { afterEach, assert, expect, it, vi } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import { ChildProcessSpawner } from "effect/process";
10​
11import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
12import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
13import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
14​
15const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
16​
17const layer = it.layer(
18 AzureDevOpsPullRequestCli.layer.pipe(
19 Layer.provide(
20 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
21 execute: mockedExecute,
22 }),
23 ),
24 Layer.provide(NodeServices.layer),
25 ),
26);
27​
28function output(stdout: string) {
29 return {
30 exitCode: ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35 };
37​
38const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
39​
40function outputWithin(maxOutputBytes: number | undefined, response: string) {
41 const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;
42 return ceiling >= Buffer.byteLength(response)
43 ? output(response)
44 : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };
46​
47const json = (value: Record<string, unknown>) => JSON.stringify(value);
48​
49const pullRequestRow = {
50 pullRequestId: 42,
51 title: "Add the page",
52 status: "active",
53 sourceRefName: "refs/heads/feat/page",
54 targetRefName: "refs/heads/main",
55 creationDate: "2026-07-01T00:00:00Z",
56 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
57 repository: { name: "web", project: { name: "platform" } },
58};
59​
60const oneIteration = {
61 value: [
62 {
63 id: 1,
64 sourceRefCommit: { commitId: "a".repeat(40) },
65 commonRefCommit: { commitId: "b".repeat(40) },
66 },
67 ],
68};
69​
70function pullRequestRows(
71 count: number,
72 firstNumber: number,
73): ReadonlyArray<Record<string, unknown>> {
74 return Array.from({ length: count }, (_, index) => ({
75 pullRequestId: firstNumber + index,
76 title: `Pull request ${firstNumber + index}`,
77 status: "active",
78 sourceRefName: "refs/heads/feat/page",
79 targetRefName: "refs/heads/main",
80 creationDate: "2026-07-01T00:00:00Z",
81 repository: { name: "web", project: { name: "platform" } },
82 url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
83 }));
85​
86function pullRequests(count: number, firstNumber: number): string {
87 return JSON.stringify(pullRequestRows(count, firstNumber));
89​
90/** Entries as Azure streams them: data descriptors, with sizes only in the central directory. */
91function streamedZip(
92 entries: ReadonlyArray<{
93 readonly name: string;
94 readonly data: Uint8Array;
95 readonly stored?: true;
96 }>,
97): Buffer {
98 const parts: Buffer[] = [];
99 const directory: Buffer[] = [];
100 let offset = 0;
101 for (const entry of entries) {
102 const name = Buffer.from(entry.name);
103 const method = entry.stored ? 0 : 8;
104 const body = entry.stored ? Buffer.from(entry.data) : NodeZlib.deflateRawSync(entry.data);
105 const local = Buffer.alloc(30);
106 local.writeUInt32LE(0x04034b50, 0);
107 local.writeUInt16LE(0x0008, 6);
108 local.writeUInt16LE(method, 8);
109 local.writeUInt16LE(name.length, 26);
110 const descriptor = Buffer.alloc(16);
111 descriptor.writeUInt32LE(0x08074b50, 0);
112 descriptor.writeUInt32LE(body.length, 8);
113 descriptor.writeUInt32LE(entry.data.length, 12);
114 const central = Buffer.alloc(46);
115 central.writeUInt32LE(0x02014b50, 0);
116 central.writeUInt16LE(0x0008, 8);
117 central.writeUInt16LE(method, 10);
118 central.writeUInt32LE(body.length, 20);
119 central.writeUInt32LE(entry.data.length, 24);
120 central.writeUInt16LE(name.length, 28);
121 central.writeUInt32LE(offset, 42);
122 parts.push(local, name, body, descriptor);
123 directory.push(central, name);
124 offset += local.length + name.length + body.length + descriptor.length;
125 }
126 const centralDirectory = Buffer.concat(directory);
127 const end = Buffer.alloc(22);
128 end.writeUInt32LE(0x06054b50, 0);
129 end.writeUInt16LE(entries.length, 8);
130 end.writeUInt16LE(entries.length, 10);
131 end.writeUInt32LE(centralDirectory.length, 12);
132 end.writeUInt32LE(offset, 16);
133 return Buffer.concat([...parts, centralDirectory, end]);
135​
136function argsOfCall(index: number): ReadonlyArray<string> {
137 const call = mockedExecute.mock.calls[index];
138 assert.isDefined(call);
139 return call[0].args;
141​
142function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {
143 const commit = "c".repeat(40);
144 return Array.from({ length: count }, (_, index) => {
145 const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;
146 return {
147 changeType: "edit",
148 item: {
149 path,
150 objectId: "a".repeat(40),
151 originalObjectId: "b".repeat(40),
152 commitId: commit,
153 gitObjectType: "blob",
154 url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,
155 },
156 };
157 });
159​
160afterEach(() => {
161 mockedExecute.mockReset();
162});
163​
164layer("AzureDevOpsPullRequestCli.layer", (it) => {
165 it.effect("reports the latest pushed source commit even while the trial merge is stale", () =>
166 Effect.gen(function* () {
167 const previousHead = "a".repeat(40);
168 const latestHead = "c".repeat(40);
169 mockedExecute
170 .mockReturnValueOnce(
171 Effect.succeed(
172 output(json({ ...pullRequestRow, lastMergeSourceCommit: { commitId: previousHead } })),
173 ),
174 )
175 .mockReturnValueOnce(
176 Effect.succeed(
177 output(
178 json({
179 value: [
180 {
181 id: 2,
182 sourceRefCommit: { commitId: latestHead },
183 commonRefCommit: { commitId: "b".repeat(40) },
184 },
185 ...oneIteration.value,
186 ],
187 }),
188 ),
189 ),
190 )
191 .mockReturnValueOnce(Effect.succeed(output(json({ changeEntries: [] }))))
192 .mockReturnValueOnce(Effect.succeed(output("[]")))
193 .mockReturnValueOnce(
194 Effect.succeed(output(json({ count: 1, value: [{ id: "4f1c", name: "release-1.0" }] }))),
195 );
196 const provider = yield* AzureDevOpsPullRequestProvider.make;
197 const detail = yield* provider.getChangeRequest({
198 cwd: "/w",
199 repository: "platform/web",
200 host: "dev.azure.com",
201 number: 42,
202 });
203​
204 expect(detail.headSha).toBe(latestHead);
205 expect(argsOfCall(2)).toContain("iterationId=2");
206 expect(argsOfCall(4)).toContain("pullRequestLabels");
207 expect(detail.labels).toEqual([{ name: "release-1.0", color: null }]);
208 expect(mockedExecute).toHaveBeenCalledTimes(5);
209 }),
210 );
211​
212 it.effect("reads an Azure pull request page larger than the VCS default output limit", () =>
213 Effect.gen(function* () {
214 const rows = pullRequestRows(100, 1).map((row) => ({
215 ...row,
216 description: "x".repeat(10_000),
217 }));
218 const response = JSON.stringify(rows);
219 expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);
220​
221 mockedExecute.mockImplementationOnce((input) =>
222 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
223 );
224 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
225​
226 const batch = yield* cli.listPullRequests({
227 cwd: "/w",
228 repository: "web",
229 state: "merged",
230 involvement: "all",
231 viewer: "bilal@acme.dev",
232 limit: 99,
233 });
234​
235 assert.strictEqual(batch.items.length, 99);
236 assert.isTrue(batch.truncated);
237 }),
238 );
239​
240 it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
241 Effect.gen(function* () {
242 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
243 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
244​
245 yield* cli.listPullRequests({
246 cwd: "/w",
247 repository: "web",
248 state: "open",
249 involvement: "all",
250 viewer: "bilal@acme.dev",
251 limit: 10,
252 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
253 });
254​
255 const args = argsOfCall(0);
256 expect(args).toContain("--skip");
257 assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
258 expect(args).not.toContain("2026-07-02T00:00:00Z");
259 }),
260 );
261​
262 it.effect("asks Azure for the author's pull requests by creator", () =>
263 Effect.gen(function* () {
264 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
265 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
266​
267 yield* cli.listPullRequests({
268 cwd: "/w",
269 repository: "web",
270 state: "open",
271 involvement: "reviewing",
272 viewer: "bilal@acme.dev",
273 limit: 10,
274 author: "ana@acme.dev",
275 });
276​
277 expect(argsOfCall(0)).toContain("--creator=ana@acme.dev");
278 expect(argsOfCall(0)).toContain("--reviewer=bilal@acme.dev");
279 }),
280 );
281​
282 it.effect("sends a repository, viewer and author that look like `@path` as text", () =>
283 Effect.gen(function* () {
284 // az has one stdin; it reads each further value from a file that holds the text.
285 const filed = new Map<string, string>();
286 mockedExecute.mockImplementationOnce((input) =>
287 Effect.sync(() => {
288 for (const arg of input.args) {
289 const match = /^(--\w+)=@(.+)$/u.exec(arg);
290 if (match?.[1] === undefined || match[2] === undefined || match[2] === "-") continue;
291 filed.set(match[1], NodeFS.readFileSync(match[2], "utf8"));
292 }
293 return output(pullRequests(1, 1));
294 }),
295 );
296 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
297​
298 yield* cli.listPullRequests({
299 cwd: "/w",
300 repository: "@web",
301 state: "open",
302 involvement: "reviewing",
303 viewer: "@bilal",
304 limit: 10,
305 author: "@ana",
306 });
307​
308 expect(argsOfCall(0)).toContain("--repository=@-");
309 assert.strictEqual(mockedExecute.mock.calls[0]?.[0].stdin, "@web");
310 assert.deepStrictEqual(
311 [...filed],
312 [
313 ["--reviewer", "@bilal"],
314 ["--creator", "@ana"],
315 ],
316 );
317 expect(argsOfCall(0).filter((arg) => arg.startsWith("@"))).toEqual([]);
318 }),
319 );
320​
321 it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
322 Effect.gen(function* () {
323 mockedExecute
324 .mockReturnValueOnce(
325 Effect.succeed(
326 output(
327 JSON.stringify([
328 { pullRequestId: "malformed" },
329 pullRequestRows(1, 1)[0],
330 { pullRequestId: "also malformed" },
331 ]),
332 ),
333 ),
334 )
335 .mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
336 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
337​
338 const batch = yield* cli.listPullRequests({
339 cwd: "/w",
340 repository: "web",
341 state: "open",
342 involvement: "all",
343 viewer: "bilal@acme.dev",
344 limit: 2,
345 });
346​
347 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
348 assert.isTrue(batch.truncated);
349 assert.strictEqual(batch.cursorAdvance, 4);
350 const secondArgs = argsOfCall(1);
351 assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
352 assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
353 }),
354 );
355​
356 it.effect("reads the signed-in account, which az reports as a bare value", () =>
357 Effect.gen(function* () {
358 mockedExecute.mockReturnValueOnce(
359 Effect.succeed(output(JSON.stringify({ name: "bilal@acme.dev", type: "user" }))),
360 );
361 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
362​
363 const viewer = yield* cli.getViewer({ cwd: "/w" });
364​
365 assert.strictEqual(viewer, "bilal@acme.dev");
366 expect(argsOfCall(0)).toEqual([
367 "account",
368 "show",
369 "--query",
370 "user",
371 "--only-show-errors",
372 "--output",
373 "json",
374 ]);
375 }),
376 );
377​
378 it.effect("names a token sign-in by the viewer's own pull request", () =>
379 Effect.gen(function* () {
380 const notLoggedIn = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
381 operation: "execute",
382 command: "az",
383 cwd: "/w",
384 argumentCount: 7,
385 cause: new Error("Please run 'az login' to setup account."),
386 });
387 mockedExecute
388 .mockReturnValueOnce(Effect.fail(notLoggedIn))
389 .mockReturnValueOnce(
390 Effect.succeed(
391 output(
392 JSON.stringify([{ ...pullRequestRow, createdBy: { uniqueName: "bilal@acme.dev" } }]),
393 ),
394 ),
395 )
396 .mockReturnValueOnce(Effect.succeed(output("")))
397 .mockReturnValueOnce(Effect.succeed(output("[]")));
398 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
399​
400 assert.strictEqual(yield* cli.getViewer({ cwd: "/w" }), "bilal@acme.dev");
401 expect(argsOfCall(1)).toEqual(expect.arrayContaining(["--creator", "me", "--top", "1"]));
402 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
403 assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
404 }),
405 );
406​
407 it.effect("fails when no sign-in can read pull requests", () =>
408 Effect.gen(function* () {
409 const signedOut = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
410 operation: "execute",
411 command: "az",
412 cwd: "/w",
413 argumentCount: 7,
414 cause: new Error("signed out"),
415 });
416 mockedExecute.mockReturnValue(Effect.fail(signedOut));
417 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
418​
419 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
420​
421 assert.strictEqual(error._tag, "AzureDevOpsCliAuthenticationError");
422 }),
423 );
424​
425 const policyRow = (name: string, status: string) => ({
426 status,
427 configuration: {
428 url: "https://dev.azure.com/acme/platform/_apis/policy/configurations/54",
429 isBlocking: true,
430 type: { id: "0609b952-1397-4640-95ec-e00a01b2c241" },
431 settings: { displayName: name },
432 },
433 });
434​
435 it.effect("follows every page of policies and puts failures first", () =>
436 Effect.gen(function* () {
437 const fullPage = Array.from({ length: 100 }, () => policyRow("Lint", "approved"));
438 mockedExecute
439 .mockReturnValueOnce(Effect.succeed(output(JSON.stringify(fullPage))))
440 .mockReturnValueOnce(
441 Effect.succeed(output(JSON.stringify([policyRow("Tests", "rejected")]))),
442 );
443 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
444 const checks = yield* cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false });
445 assert.deepStrictEqual(argsOfCall(1).slice(0, 12), [
446 "repos",
447 "pr",
448 "policy",
449 "list",
450 "--detect",
451 "true",
452 "--id",
453 "42",
454 "--top",
455 "100",
456 "--skip",
457 "100",
458 ]);
459 assert.strictEqual(checks.length, 101);
460 assert.strictEqual(checks[0]?.name, "Tests");
461 }),
462 );
463​
464 it.effect.each([
465 { name: "cut off", result: { ...output("[]"), stdoutTruncated: true } },
466 { name: "unreadable", result: output(JSON.stringify([{ status: 7 }])) },
467 ])("fails rather than report a $name policy page as complete", ({ result }) =>
468 Effect.gen(function* () {
469 mockedExecute.mockReturnValueOnce(Effect.succeed(result));
470 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
471 const error = yield* Effect.flip(
472 cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false }),
473 );
474 assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
475 }),
476 );
477​
478 it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
479 Effect.gen(function* () {
480 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
481 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
482​
483 yield* cli.updatePullRequest({
484 cwd: "/w",
485 number: 42,
486 body: "- rewrote the page\n- kept the rest",
487 });
488​
489 expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
490 }),
491 );
492​
493 it.effect(
494 "sends a title or description that looks like `@path` as text, not as a file for az to read",
495 () =>
496 Effect.gen(function* () {
497 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
498 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
499​
500 yield* cli.updatePullRequest({
501 cwd: "/w",
502 number: 42,
503 title: "@notes.txt",
504 body: "@notes.txt",
505 });
506​
507 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
508 const fileReads = argsOfCall(0).flatMap((arg) => {
509 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
510 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
511 ? [value.slice(1)]
512 : [];
513 });
514 expect(fileReads).not.toContain("notes.txt");
515 // Each `@` value goes over stdin, which reaches az wherever it runs; one per call.
516 expect(mockedExecute.mock.calls.map(([call]) => call.stdin)).toEqual([
517 "@notes.txt",
518 "@notes.txt",
519 ]);
520 }),
521 );
522​
523 it.effect("names the head's blob as what a cleared file was cleared at", () =>
524 Effect.gen(function* () {
525 mockedExecute
526 .mockReturnValueOnce(
527 Effect.succeed(
528 output(
529 JSON.stringify({
530 pullRequestId: 42,
531 title: "Add the page",
532 status: "active",
533 sourceRefName: "refs/heads/feat/page",
534 targetRefName: "refs/heads/main",
535 creationDate: "2026-07-01T00:00:00Z",
536 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
537 repository: { name: "web", project: { name: "platform" } },
538 }),
539 ),
540 ),
541 )
542 .mockReturnValueOnce(
543 Effect.succeed(
544 output(
545 JSON.stringify({
546 value: [
547 {
548 id: 1,
549 sourceRefCommit: { commitId: "a".repeat(40) },
550 commonRefCommit: { commitId: "b".repeat(40) },
551 },
552 {
553 id: 2,
554 sourceRefCommit: { commitId: "c".repeat(40) },
555 commonRefCommit: { commitId: "b".repeat(40) },
556 },
557 ],
558 }),
559 ),
560 ),
561 )
562 .mockReturnValueOnce(
563 Effect.succeed(
564 output(
565 JSON.stringify({
566 changeEntries: [
567 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
568 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
569 ],
570 }),
571 ),
572 ),
573 );
574 const provider = yield* AzureDevOpsPullRequestProvider.make;
575​
576 assert.strictEqual(provider.capabilities.viewedFiles, "environment");
577 assert.isDefined(provider.getFileRevisions);
578 const answer = yield* provider.getFileRevisions({
579 cwd: "/w",
580 repository: "web",
581 host: "dev.azure.com",
582 number: 42,
583 paths: ["README.md"],
584 });
585​
586 expect(argsOfCall(2)).toContain("iterationId=2");
587 expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);
588 }),
589 );
590​
591 it.effect(
592 "answers for a marked file the pull request no longer changes as the empty version",
593 () =>
594 Effect.gen(function* () {
595 mockedExecute
596 .mockReturnValueOnce(
597 Effect.succeed(
598 output(
599 json({
600 pullRequestId: 42,
601 title: "Add the page",
602 status: "active",
603 sourceRefName: "refs/heads/feat/page",
604 targetRefName: "refs/heads/main",
605 creationDate: "2026-07-01T00:00:00Z",
606 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
607 repository: { name: "web", project: { name: "platform" } },
608 }),
609 ),
610 ),
611 )
612 .mockReturnValueOnce(
613 Effect.succeed(
614 output(
615 json({
616 value: [
617 {
618 id: 1,
619 sourceRefCommit: { commitId: "a".repeat(40) },
620 commonRefCommit: { commitId: "b".repeat(40) },
621 },
622 ],
623 }),
624 ),
625 ),
626 )
627 .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));
628 const provider = yield* AzureDevOpsPullRequestProvider.make;
629 assert.isDefined(provider.getFileRevisions);
630​
631 const answer = yield* provider.getFileRevisions({
632 cwd: "/w",
633 repository: "web",
634 host: "dev.azure.com",
635 number: 42,
636 paths: ["GONE.md"],
637 });
638​
639 expect([...answer.revisions]).toEqual([["GONE.md", ""]]);
640 }),
641 );
642​
643 it.effect("says nothing about the files past the end of a change it gave up following", () =>
644 Effect.gen(function* () {
645 const entries = (from: number, count: number) =>
646 Array.from({ length: count }, (_, index) => ({
647 changeType: "edit",
648 item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },
649 }));
650 mockedExecute
651 .mockReturnValueOnce(
652 Effect.succeed(
653 output(
654 json({
655 pullRequestId: 42,
656 title: "Add the page",
657 status: "active",
658 sourceRefName: "refs/heads/feat/page",
659 targetRefName: "refs/heads/main",
660 creationDate: "2026-07-01T00:00:00Z",
661 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
662 repository: { name: "web", project: { name: "platform" } },
663 }),
664 ),
665 ),
666 )
667 .mockReturnValueOnce(
668 Effect.succeed(
669 output(
670 json({
671 value: [
672 {
673 id: 1,
674 sourceRefCommit: { commitId: "a".repeat(40) },
675 commonRefCommit: { commitId: "b".repeat(40) },
676 },
677 ],
678 }),
679 ),
680 ),
681 )
682 .mockReturnValueOnce(
683 Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),
684 )
685 .mockReturnValueOnce(
686 Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),
687 );
688 const provider = yield* AzureDevOpsPullRequestProvider.make;
689 assert.isDefined(provider.getFileRevisions);
690​
691 const answer = yield* provider.getFileRevisions({
692 cwd: "/w",
693 repository: "web",
694 host: "dev.azure.com",
695 number: 42,
696 paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],
697 });
698​
699 expect(argsOfCall(3)).toContain("$skip=5000");
700 expect([...answer.revisions]).toEqual([
701 ["src/f1.ts", "blob-1"],
702 ["src/f5001.ts", "blob-5001"],
703 ]);
704 }),
705 );
706​
707 it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>
708 Effect.gen(function* () {
709 mockedExecute
710 .mockReturnValueOnce(
711 Effect.succeed(
712 output(
713 json({
714 pullRequestId: 42,
715 title: "Add the page",
716 status: "active",
717 sourceRefName: "refs/heads/feat/page",
718 targetRefName: "refs/heads/main",
719 creationDate: "2026-07-01T00:00:00Z",
720 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
721 repository: { name: "web", project: { name: "platform" } },
722 }),
723 ),
724 ),
725 )
726 .mockReturnValueOnce(
727 Effect.succeed(
728 output(
729 json({
730 value: [
731 {
732 id: 1,
733 sourceRefCommit: { commitId: "a".repeat(40) },
734 commonRefCommit: { commitId: "b".repeat(40) },
735 },
736 ],
737 }),
738 ),
739 ),
740 )
741 .mockImplementation((command) => {
742 const skip = command.args.find((arg) => arg.startsWith("$skip="));
743 const from = Number(skip?.slice("$skip=".length) ?? 0);
744 return Effect.succeed(
745 output(
746 json({
747 changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],
748 nextSkip: from + 2_000,
749 }),
750 ),
751 );
752 });
753 const provider = yield* AzureDevOpsPullRequestProvider.make;
754 assert.isDefined(provider.getFileRevisions);
755​
756 const answer = yield* provider.getFileRevisions({
757 cwd: "/w",
758 repository: "web",
759 host: "dev.azure.com",
760 number: 42,
761 paths: ["src/page.ts"],
762 });
763​
764 assert.strictEqual(mockedExecute.mock.calls.length, 7);
765 assert.strictEqual(answer.revisions.size, 0);
766 }),
767 );
768​
769 it.effect("leaves one file the host would not hand over listed without its hunks", () =>
770 Effect.gen(function* () {
771 mockedExecute
772 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
773 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
774 .mockReturnValueOnce(
775 Effect.succeed(
776 output(
777 json({
778 changeEntries: [
779 { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },
780 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
781 ],
782 }),
783 ),
784 ),
785 )
786 .mockReturnValueOnce(
787 Effect.fail(
788 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
789 operation: "execute",
790 command: "az",
791 cwd: "/w",
792 argumentCount: 1,
793 cause: "the blob is past what the route will carry",
794 }),
795 ),
796 )
797 .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));
798 const provider = yield* AzureDevOpsPullRequestProvider.make;
799​
800 const slice = yield* provider.getDiff({
801 cwd: "/w",
802 repository: "web",
803 host: "dev.azure.com",
804 number: 42,
805 });
806​
807 assert.isTrue(slice.truncated);
808 expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");
809 expect(slice.patch).toContain("+hello");
810 }),
811 );
812​
813 it.effect("fails the whole read when it is the connection that would not answer", () =>
814 Effect.gen(function* () {
815 mockedExecute
816 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
817 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
818 .mockReturnValueOnce(
819 Effect.succeed(
820 output(
821 json({
822 changeEntries: [
823 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
824 ],
825 }),
826 ),
827 ),
828 )
829 .mockReturnValueOnce(
830 Effect.fail(
831 new AzureDevOpsCli.AzureDevOpsCliRateLimitError({
832 operation: "execute",
833 command: "az",
834 cwd: "/w",
835 argumentCount: 1,
836 cause: "429",
837 }),
838 ),
839 );
840 const provider = yield* AzureDevOpsPullRequestProvider.make;
841​
842 const error = yield* Effect.flip(
843 provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),
844 );
845​
846 assert.strictEqual(error.reason, "rate-limited");
847 }),
848 );
849​
850 it.effect("takes Azure's own word on a file it will not spell out", () =>
851 Effect.gen(function* () {
852 mockedExecute
853 .mockReturnValueOnce(
854 Effect.succeed(
855 output(
856 json({
857 pullRequestId: 42,
858 title: "Add the page",
859 status: "active",
860 sourceRefName: "refs/heads/feat/page",
861 targetRefName: "refs/heads/main",
862 creationDate: "2026-07-01T00:00:00Z",
863 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
864 repository: { name: "web", project: { name: "platform" } },
865 }),
866 ),
867 ),
868 )
869 .mockReturnValueOnce(
870 Effect.succeed(
871 output(
872 json({
873 value: [
874 {
875 id: 1,
876 sourceRefCommit: { commitId: "a".repeat(40) },
877 commonRefCommit: { commitId: "b".repeat(40) },
878 },
879 ],
880 }),
881 ),
882 ),
883 )
884 .mockReturnValueOnce(
885 Effect.succeed(
886 output(
887 json({
888 changeEntries: [
889 { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },
890 ],
891 }),
892 ),
893 ),
894 )
895 .mockReturnValueOnce(
896 Effect.succeed(
897 output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),
898 ),
899 );
900 const provider = yield* AzureDevOpsPullRequestProvider.make;
901​
902 const slice = yield* provider.getDiff({
903 cwd: "/w",
904 repository: "web",
905 host: "dev.azure.com",
906 number: 42,
907 });
908​
909 expect(argsOfCall(3)).toContain("includeContentMetadata=true");
910 expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");
911 assert.isTrue(slice.truncated);
912 }),
913 );
914​
915 it.effect("stops following pages when one of them does not move the cursor on", () =>
916 Effect.gen(function* () {
917 mockedExecute
918 .mockReturnValueOnce(
919 Effect.succeed(
920 output(
921 json({
922 pullRequestId: 42,
923 title: "Add the page",
924 status: "active",
925 sourceRefName: "refs/heads/feat/page",
926 targetRefName: "refs/heads/main",
927 creationDate: "2026-07-01T00:00:00Z",
928 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
929 repository: { name: "web", project: { name: "platform" } },
930 }),
931 ),
932 ),
933 )
934 .mockReturnValueOnce(
935 Effect.succeed(
936 output(
937 json({
938 value: [
939 {
940 id: 1,
941 sourceRefCommit: { commitId: "a".repeat(40) },
942 commonRefCommit: { commitId: "b".repeat(40) },
943 },
944 ],
945 }),
946 ),
947 ),
948 )
949 .mockReturnValueOnce(
950 Effect.succeed(
951 output(
952 json({
953 changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],
954 nextSkip: 2_000,
955 }),
956 ),
957 ),
958 )
959 .mockReturnValueOnce(
960 Effect.succeed(
961 output(
962 json({
963 changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],
964 nextSkip: 2_000,
965 }),
966 ),
967 ),
968 );
969 const provider = yield* AzureDevOpsPullRequestProvider.make;
970 assert.isDefined(provider.getFileRevisions);
971​
972 const answer = yield* provider.getFileRevisions({
973 cwd: "/w",
974 repository: "web",
975 host: "dev.azure.com",
976 number: 42,
977 paths: ["a.ts", "b.ts", "unlisted.ts"],
978 });
979​
980 assert.strictEqual(mockedExecute.mock.calls.length, 4);
981 expect([...answer.revisions]).toEqual([
982 ["a.ts", "8f80"],
983 ["b.ts", "0ca4"],
984 ]);
985 }),
986 );
987​
988 it.effect("reads a full page of change entries, which is past the default output limit", () =>
989 Effect.gen(function* () {
990 const response = json({ changeEntries: changeEntries(2_000) });
991 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
992 mockedExecute.mockImplementationOnce((input) =>
993 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
994 );
995 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
996​
997 const page = yield* cli.listIterationChanges({
998 cwd: "/w",
999 location: { project: "platform", repository: "web" },
1000 number: 42,
1001 iterationId: 1,
1002 });
1003​
1004 assert.strictEqual(page.changes.length, 2_000);
1005 assert.isFalse(page.truncated);
1006 }),
1007 );
1008​
1009 it.effect("reads a file whose JSON envelope is past the default output limit", () =>
1010 Effect.gen(function* () {
1011 const file = "const value = 1;\n".repeat(57_000);
1012 const response = json({ content: file });
1013 expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1014 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1015 mockedExecute.mockImplementationOnce((input) =>
1016 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
1017 );
1018 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1019​
1020 const item = yield* cli.readItemContent({
1021 cwd: "/w",
1022 location: { project: "platform", repository: "web" },
1023 path: "src/generated/schema.ts",
1024 commit: "a".repeat(40),
1025 });
1026​
1027 assert.strictEqual(item.contents, file);
1028 assert.isFalse(item.isBinary);
1029 }),
1030 );
1031​
1032 it.effect(
1033 "reads a batch of files from one blobs zip, keeping only what Azure's read would say",
1034 () =>
1035 Effect.gen(function* () {
1036 const id = (digit: string) => digit.repeat(40);
1037 const utf8 = (text: string) => new TextEncoder().encode(text);
1038 let sent = "";
1039 mockedExecute.mockImplementationOnce((input) =>
1040 Effect.sync(() => {
1041 const flag = (name: string) => input.args[input.args.indexOf(name) + 1] ?? "";
1042 sent = NodeFS.readFileSync(flag("--in-file"), "utf8");
1043 NodeFS.writeFileSync(
1044 flag("--out-file"),
1045 streamedZip([
1046 { name: id("a"), data: utf8("plain text\n") },
1047 { name: id("b"), data: utf8("\uFEFFcafé ✓\n") },
1048 { name: id("c"), data: Uint8Array.of(0x89, 0x50, 0x00, 0x01) },
1049 // Windows-1252 "café" and UTF-16: Azure decodes these itself.
1050 { name: id("d"), data: Uint8Array.of(0x63, 0x61, 0x66, 0xe9) },
1051 { name: id("e"), data: Uint8Array.of(0xff, 0xfe, 0x68, 0x00) },
1052 { name: id("f"), data: utf8("stored\n"), stored: true },
1053 { name: id("9"), data: utf8("never asked for\n") },
1054 ]),
1055 );
1056 return output("");
1057 }),
1058 );
1059 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1060​
1061 const blobs = yield* cli.readBlobs({
1062 cwd: "/w",
1063 location: { project: "platform", repository: "web" },
1064 objectIds: [id("A"), id("b"), id("C"), id("d"), id("e"), id("f"), id("a"), "../etc"],
1065 });
1066​
1067 expect(JSON.parse(sent)).toEqual([id("A"), id("b"), id("C"), id("d"), id("e"), id("f")]);
1068 expect(argsOfCall(0)).toEqual(
1069 expect.arrayContaining(["blobs", "POST", "application/zip", "project=platform"]),
1070 );
1071 expect(Object.fromEntries(blobs)).toEqual({
1072 [id("a")]: { contents: "plain text\n", isBinary: false },
1073 [id("b")]: { contents: "café ✓\n", isBinary: false },
1074 [id("c")]: { contents: "", isBinary: true },
1075 [id("f")]: { contents: "stored\n", isBinary: false },
1076 });
1077 }),
1078 );
1079​
1080 it.effect("leaves blobs past the batch's total size to per-file reads", () =>
1081 Effect.gen(function* () {
1082 const ids = ["1", "2", "3", "4", "5", "6"].map((digit) => digit.repeat(40));
1083 // Compresses to a few KiB each, so only the inflated total can bound memory.
1084 const blob = new Uint8Array(3 * 1024 * 1024).fill(0x61);
1085 mockedExecute.mockImplementationOnce((input) =>
1086 Effect.sync(() => {
1087 NodeFS.writeFileSync(
1088 input.args[input.args.indexOf("--out-file") + 1] ?? "",
1089 streamedZip(ids.map((name) => ({ name, data: blob }))),
1090 );
1091 return output("");
1092 }),
1093 );
1094 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1095​
1096 const blobs = yield* cli.readBlobs({
1097 cwd: "/w",
1098 location: { project: "platform", repository: "web" },
1099 objectIds: ids,
1100 });
1101​
1102 expect([...blobs.keys()]).toEqual(ids.slice(0, 5));
1103 }),
1104 );
1105​
1106 it.effect("escapes characters in a file path that would cut the query string", () =>
1107 Effect.gen(function* () {
1108 mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "x" }))));
1109 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1110​
1111 yield* cli.readItemContent({
1112 cwd: "/w",
1113 location: { project: "platform", repository: "web" },
1114 path: "docs/C#/a&b.md",
1115 commit: "a".repeat(40),
1116 });
1117​
1118 expect(mockedExecute.mock.calls.at(-1)?.[0].args).toContain("path=%2Fdocs%2FC%23%2Fa%26b.md");
1119 }),
1120 );
1121​
1122 it.effect("reports a pull request it cannot place as its own outcome", () =>
1123 Effect.gen(function* () {
1124 mockedExecute.mockReturnValueOnce(
1125 Effect.succeed(
1126 output(
1127 JSON.stringify({
1128 pullRequestId: 42,
1129 title: "Add the page",
1130 sourceRefName: "refs/heads/feat/page",
1131 targetRefName: "refs/heads/main",
1132 creationDate: "2026-07-01T00:00:00Z",
1133 }),
1134 ),
1135 ),
1136 );
1137 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1138​
1139 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1140​
1141 assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
1142 }),
1143 );
1144​
1145 it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
1146 Effect.gen(function* () {
1147 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1148​
1149 const error = yield* Effect.flip(
1150 cli.setPullRequestReviewers({
1151 cwd: "/w",
1152 number: 42,
1153 reviewers: ["--query"],
1154 requested: true,
1155 }),
1156 );
1157​
1158 assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
1159 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1160 }),
1161 );
1162});