Open History to see the last commit
1import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Semaphore from "effect/Semaphore";
4import { rollupCheckStatuses } from "@t3tools/source-control-core/server/pullRequestChecks";
5import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
6
7import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
8import {
9 azureDevOpsFilePatch,
10 azureDevOpsUnreadableFilePatch,
11 formatAzureDevOpsDiffCursor,
12 parseAzureDevOpsDiffCursor,
13 MAX_DIFF_SLICE_BYTES,
14 MAX_DIFF_SLICE_EDITS,
15 MAX_DIFF_SLICE_FILES,
16 byteLength,
17 MAX_FILE_DIFF_EDITS,
18 type AzureDevOpsFileTexts,
19} from "./azureDevOpsDiff.ts";
20import {
21 PullRequestProviderError,
22 type PullRequestProviderFailure,
23 type ProviderChangeRequest,
24 type ProviderChangeRequestActivity,
25 type ProviderChangeRequestDetail,
26 type ProviderChangeRequestSummary,
27 type ProviderDiffSlice,
28 type PullRequestProviderApi,
29} from "@t3tools/source-control-core/server/PullRequestProvider";
30import type {
31 AzureDevOpsChangeEntry,
32 AzureDevOpsItemContent,
33 AzureDevOpsIteration,
34 AzureDevOpsPullRequest,
35 AzureDevOpsRepositoryLocation,
36} from "./azureDevOpsPullRequestJson.ts";
37import { definition } from "../shared/definition.ts";
38
39/** A file the blob batch missed pays for two Python startups. */
40const DIFF_FILE_CONCURRENCY = 4;
41
42/** Readers share a spawn budget across requests. */
43export const MAX_DIFF_SPAWNS = 2 * DIFF_FILE_CONCURRENCY;
44
45export const LOCATION_CACHE_CAPACITY = 128;
46
47/** A version's change list can run to thousands of paths. */
48const CHANGES_CACHE_CAPACITY = 32;
49
50/**
51 * Files whose contents one `az` run fetches. The run costs about the same for 10 blobs as for
52 * 100, and a slice rarely spends this many before its budgets close it.
53 */
54export const BLOB_BATCH_FILES = 100;
55
56/** Least recently used goes first. */
57function remember<V>(cache: Map<string, V>, capacity: number, key: string, value: V): V {
58 cache.delete(key);
59 if (cache.size >= capacity) {
60 const oldest = cache.keys().next().value;
61 if (oldest !== undefined) cache.delete(oldest);
62 }
63 cache.set(key, value);
64 return value;
65}
66
67function recall<V>(cache: Map<string, V>, key: string): V | undefined {
68 const held = cache.get(key);
69 if (held !== undefined) remember(cache, Number.POSITIVE_INFINITY, key, held);
70 return held;
71}
72
73/** The blobs a file's two sides need, as the change list names them. */
74function blobIdsOf(change: AzureDevOpsChangeEntry): ReadonlyArray<string> {
75 const ids: string[] = [];
76 if (change.changeKind !== "new" && change.originalObjectId !== null) {
77 ids.push(change.originalObjectId);
78 }
79 if (change.changeKind !== "deleted" && change.objectId !== null) ids.push(change.objectId);
80 return ids;
81}
82
83const CAPABILITIES: PullRequestCapabilities = {
84 diff: true,
85 comment: false,
86 actions: [...definition.changeRequestActions],
87 // Azure has no rebase strategy.
88 mergeMethods: ["merge", "squash"],
89 // `az repos pr list` has no text filter.
90 search: false,
91 reactions: false,
92 mentions: false,
93 referenceSigils: [],
94 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
95 // Reviewer candidates require separate identity/graph APIs and permissions.
96 reviewers: { request: true, listCandidates: false, searchCandidates: false },
97 edit: { changeRequest: true, comment: false },
98 // Azure's viewed marks use an undocumented endpoint and are invalidated by each push.
99 viewedFiles: "environment",
100};
101
102const UNAVAILABLE_REQUIREMENT = {
103 missing:
104 "Azure CLI (`az`) with the Azure DevOps extension is required. Install `az`, then run `az extension add --name azure-devops`.",
105 unauthenticated: "Azure CLI is not signed in. Run `az login` and retry.",
106};
107
108/**
109 * Azure DevOps states no permission anywhere `az repos pr show` or `az repos pr list` reach: the
110 * answer lives in the security namespaces, behind identity descriptors and token paths that would
111 * be several calls per pull request to resolve.
112 */
113const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
114 actions: CAPABILITIES.actions,
115 comment: CAPABILITIES.comment,
116 resolve: CAPABILITIES.review.resolve,
117 verdicts: CAPABILITIES.review.verdicts,
118 requestReviewers: CAPABILITIES.reviewers.request,
119};
120
121function azureDevOpsProviderFailure(
122 error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,
123): PullRequestProviderFailure {
124 if (error._tag === "AzureDevOpsCliUnavailableError") return { reason: "missing-tool" };
125 if (error._tag === "AzureDevOpsCliAuthenticationError") return { reason: "unauthenticated" };
126 if (error._tag === "AzureDevOpsCliRateLimitError") return { reason: "rate-limited" };
127 if (error._tag === "AzureDevOpsPullRequestNotFoundError") return { reason: "not-found" };
128 return { reason: "failed" };
129}
130
131function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {
132 return {
133 number: pullRequest.number,
134 title: pullRequest.title,
135 url: pullRequest.url,
136 author: pullRequest.author,
137 headBranch: pullRequest.headBranch,
138 baseBranch: pullRequest.baseBranch,
139 state: pullRequest.state,
140 isDraft: pullRequest.isDraft,
141 mergeability: pullRequest.mergeability,
142 // Azure omits line counts; computing them requires both sides of every file.
143 additions: 0,
144 deletions: 0,
145 createdAt: pullRequest.createdAt,
146 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
147 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
148 updatedAt: pullRequest.updatedAt,
149 reviewRequestLogins: pullRequest.reviewRequestLogins,
150 // Azure keeps labels on work items rather than on the pull request.
151 labels: [],
152 };
153}
154
155function toSummary(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequestSummary {
156 return {
157 number: pullRequest.number,
158 title: pullRequest.title,
159 url: pullRequest.url,
160 author: pullRequest.author,
161 headBranch: pullRequest.headBranch,
162 baseBranch: pullRequest.baseBranch,
163 state: pullRequest.state,
164 isDraft: pullRequest.isDraft,
165 mergeability: pullRequest.mergeability,
166 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
167 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
168 updatedAt: pullRequest.updatedAt,
169 };
170}
171
172export const make = Effect.gen(function* () {
173 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
174 const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);
175 const readItemContent = (input: Parameters<typeof cli.readItemContent>[0]) =>
176 diffSpawns.withPermits(1)(cli.readItemContent(input));
177 const readBlobs = (input: Parameters<typeof cli.readBlobs>[0]) =>
178 diffSpawns.withPermits(1)(cli.readBlobs(input));
179
180 const fail =
181 (operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>
182 new PullRequestProviderError({
183 provider: SourceControlProviderKind.make("azure-devops"),
184 operation,
185 ...azureDevOpsProviderFailure(error),
186 detail: error.detail,
187 cause: error,
188 });
189
190 const unsupported = (operation: string) =>
191 Effect.fail(
192 new PullRequestProviderError({
193 provider: SourceControlProviderKind.make("azure-devops"),
194 operation,
195 reason: "failed",
196 detail: "Azure DevOps reviews cannot be written from here yet.",
197 }),
198 );
199
200 const EMPTY_DIFF_SLICE: ProviderDiffSlice = { patch: "", truncated: false, nextCursor: null };
201
202 // PR locations are immutable; caching avoids full PR reads for viewed-file checks.
203 const locations = new Map<string, AzureDevOpsRepositoryLocation>();
204 // A pushed iteration never changes, so neither do its commits nor its change list.
205 const knownIterations = new Map<string, ReadonlyArray<AzureDevOpsIteration>>();
206 const iterationChanges = new Map<string, AzureDevOpsPullRequestCli.AzureDevOpsIterationChanges>();
207
208 const locationOf = (input: { readonly cwd: string; readonly number: number }) => {
209 const key = `${input.cwd} ${input.number}`;
210 const held = recall(locations, key);
211 if (held !== undefined) return Effect.succeed(held);
212 return cli
213 .getPullRequest({ cwd: input.cwd, number: input.number })
214 .pipe(
215 Effect.map((pullRequest) =>
216 pullRequest.location === null
217 ? null
218 : remember(locations, LOCATION_CACHE_CAPACITY, key, pullRequest.location),
219 ),
220 );
221 };
222
223 const readChecks = (input: { readonly cwd: string }, pullRequest: AzureDevOpsPullRequest) =>
224 cli.listPolicyChecks({
225 cwd: input.cwd,
226 number: pullRequest.number,
227 isDraft: pullRequest.isDraft,
228 });
229
230 /** A later slice names its iteration, which the list it was cut from already holds. */
231 const diffScope = Effect.fn("AzureDevOpsPullRequestProvider.diffScope")(function* (input: {
232 readonly cwd: string;
233 readonly number: number;
234 readonly iterationId?: number;
235 }) {
236 const location = yield* locationOf(input);
237 if (location === null) return null;
238 const key = `${input.cwd} ${input.number}`;
239 const held = recall(knownIterations, key);
240 if (
241 input.iterationId !== undefined &&
242 held?.some((iteration) => iteration.id === input.iterationId)
243 ) {
244 return { location, iterations: held };
245 }
246 const iterations = yield* cli.listIterations({
247 cwd: input.cwd,
248 location,
249 number: input.number,
250 });
251 remember(knownIterations, LOCATION_CACHE_CAPACITY, key, iterations);
252 return { location, iterations };
253 });
254
255 const changesOf = (input: {
256 readonly cwd: string;
257 readonly location: AzureDevOpsRepositoryLocation;
258 readonly number: number;
259 readonly iterationId: number;
260 }) => {
261 const key = `${input.cwd} ${input.number} ${input.iterationId}`;
262 const held = recall(iterationChanges, key);
263 return held !== undefined
264 ? Effect.succeed(held)
265 : cli
266 .listIterationChanges(input)
267 .pipe(
268 Effect.map((listed) => remember(iterationChanges, CHANGES_CACHE_CAPACITY, key, listed)),
269 );
270 };
271
272 const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };
273
274 /** Azure fails reads of absent files. */
275 const readTexts = (input: {
276 readonly cwd: string;
277 readonly location: AzureDevOpsRepositoryLocation;
278 readonly iteration: AzureDevOpsIteration;
279 readonly change: Pick<AzureDevOpsChangeEntry, "changeKind" | "path" | "oldPath">;
280 }) =>
281 Effect.all(
282 [
283 input.change.changeKind === "new"
284 ? Effect.succeed(EMPTY_ITEM)
285 : readItemContent({
286 cwd: input.cwd,
287 location: input.location,
288 path: input.change.oldPath,
289 commit: input.iteration.mergeBaseCommit,
290 }),
291 input.change.changeKind === "deleted"
292 ? Effect.succeed(EMPTY_ITEM)
293 : readItemContent({
294 cwd: input.cwd,
295 location: input.location,
296 path: input.change.path,
297 commit: input.iteration.headCommit,
298 }),
299 ],
300 { concurrency: 2 },
301 ).pipe(
302 Effect.map(([oldItem, newItem]): AzureDevOpsFileTexts => ({
303 oldContents: oldItem.contents,
304 newContents: newItem.contents,
305 // Encoded bytes cannot identify binaries; trust Azure's metadata.
306 binary: oldItem.isBinary || newItem.isBinary,
307 })),
308 );
309
310 const listLatestChanges = (input: {
311 readonly cwd: string;
312 readonly location: AzureDevOpsRepositoryLocation;
313 readonly number: number;
314 readonly iterations: ReadonlyArray<AzureDevOpsIteration>;
315 }) => {
316 const latest = input.iterations.at(-1);
317 return latest === undefined
318 ? Effect.succeed({
319 changes: [],
320 truncated: false,
321 } as AzureDevOpsPullRequestCli.AzureDevOpsIterationChanges)
322 : changesOf({
323 cwd: input.cwd,
324 location: input.location,
325 number: input.number,
326 iterationId: latest.id,
327 });
328 };
329
330 const provider: PullRequestProviderApi = {
331 kind: SourceControlProviderKind.make("azure-devops"),
332 capabilities: CAPABILITIES,
333 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
334 // The bare repository name repeats across an organization; the project path does not.
335 repositoryKey: ({ canonicalKey }) => canonicalKey,
336
337 getViewer: (input) =>
338 cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
339
340 listChangeRequests: (input) =>
341 cli
342 .listPullRequests({
343 cwd: input.cwd,
344 repository: input.repository,
345 state: input.state,
346 involvement: input.involvement,
347 viewer: input.viewer,
348 limit: input.limit,
349 cursor: input.cursor,
350 author:
351 input.filters?.author === undefined
352 ? undefined
353 : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
354 })
355 .pipe(
356 Effect.mapError(fail("listChangeRequests")),
357 Effect.map((batch) => ({
358 items: batch.items.map(toChangeRequest),
359 truncated: batch.truncated,
360 cursorAdvance: batch.cursorAdvance,
361 // Azure's ordering is stable across offset-based pages.
362 continues: true,
363 })),
364 ),
365
366 getChangeRequestPreview: (input) =>
367 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
368 Effect.mapError(fail("getChangeRequestPreview")),
369 Effect.map((pullRequest) => ({
370 number: pullRequest.number,
371 title: pullRequest.title,
372 url: pullRequest.url,
373 author: pullRequest.author,
374 state: pullRequest.state,
375 isDraft: pullRequest.isDraft,
376 createdAt: pullRequest.createdAt,
377 })),
378 ),
379
380 getChangeRequestChecks: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequestChecks")(
381 function* (input) {
382 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
383 const checks = yield* readChecks(input, pullRequest);
384 return { state: pullRequest.state, checks };
385 },
386 Effect.mapError(fail("getChangeRequestChecks")),
387 ),
388
389 getChangeRequestSummary: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequestSummary")(
390 function* (input) {
391 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
392 // Undefined keeps the last known state; null would claim no checks exist.
393 const checksState = yield* readChecks(input, pullRequest).pipe(
394 Effect.map((checks) => rollupCheckStatuses(checks.map((check) => check.status))),
395 Effect.orElseSucceed(() => undefined),
396 );
397 return {
398 ...toSummary(pullRequest),
399 ...(checksState === undefined ? {} : { checksState }),
400 };
401 },
402 Effect.mapError(fail("getChangeRequestSummary")),
403 ),
404
405 getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
406 function* (input) {
407 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
408 const location = pullRequest.location;
409 const iterations =
410 location === null
411 ? []
412 : yield* cli
413 .listIterations({ cwd: input.cwd, location, number: input.number })
414 .pipe(Effect.orElseSucceed(() => []));
415 // The trial merge's lastMergeSourceCommit can lag behind a new source push.
416 const headSha = iterations.at(-1)?.headCommit;
417 const changedFiles =
418 location === null
419 ? 0
420 : yield* listLatestChanges({
421 cwd: input.cwd,
422 location,
423 number: input.number,
424 iterations,
425 }).pipe(
426 Effect.map((listed) => listed.changes.length),
427 Effect.orElseSucceed(() => 0),
428 );
429 const checks = yield* readChecks(input, pullRequest).pipe(Effect.orElseSucceed(() => []));
430 const detail: ProviderChangeRequestDetail = {
431 ...toChangeRequest(pullRequest),
432 body: pullRequest.body,
433 ...(headSha === undefined ? {} : { headSha }),
434 changedFiles,
435 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
436 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
437 reviewers: pullRequest.reviewers,
438 checks,
439 mergeCapabilities: { merge: true, squash: true, rebase: false },
440 viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
441 autoMergeEnabled: pullRequest.autoMergeEnabled,
442 ...(pullRequest.autoMergeMethod === undefined
443 ? {}
444 : { autoMergeMethod: pullRequest.autoMergeMethod }),
445 };
446 return detail;
447 },
448 Effect.mapError(fail("getChangeRequest")),
449 ),
450
451 getChangeRequestActivity: (input) =>
452 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
453 Effect.mapError(fail("getChangeRequestActivity")),
454 Effect.flatMap((pullRequest) =>
455 (pullRequest.location === null
456 ? Effect.succeed({ comments: [], truncated: true })
457 : cli
458 .listThreads({
459 cwd: input.cwd,
460 location: pullRequest.location,
461 number: input.number,
462 })
463 .pipe(
464 Effect.map((comments) => ({ comments, truncated: false })),
465 Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
466 )
467 ).pipe(
468 Effect.map((conversation): ProviderChangeRequestActivity => ({
469 comments: conversation.comments,
470 commentCount: conversation.comments.length,
471 commentsTruncated: conversation.truncated,
472 reviewThreads: [],
473 commits: [],
474 })),
475 ),
476 ),
477 ),
478
479 getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
480
481 // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so
482 // the Code tab has nothing to scope itself to and always asks for the whole change.
483 getDiff: Effect.fn("AzureDevOpsPullRequestProvider.getDiff")(
484 function* (input) {
485 const cursor = parseAzureDevOpsDiffCursor(input.cursor);
486 const scope = yield* diffScope({
487 cwd: input.cwd,
488 number: input.number,
489 ...(cursor === null ? {} : { iterationId: cursor.iterationId }),
490 });
491 if (scope === null) return EMPTY_DIFF_SLICE;
492 const iteration =
493 cursor === null
494 ? scope.iterations.at(-1)
495 : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);
496 if (iteration === undefined) return EMPTY_DIFF_SLICE;
497 const listed = yield* changesOf({
498 cwd: input.cwd,
499 location: scope.location,
500 number: input.number,
501 iterationId: iteration.id,
502 });
503 const changes = listed.changes;
504
505 const sections: string[] = [];
506 let truncated = listed.truncated;
507 let bytes = 0;
508 let edits = 0;
509 let index = cursor?.fileIndex ?? 0;
510 let full = false;
511 // Prefetched files beyond the slice must be read again.
512 const batchWidth = () => {
513 if (sections.length === 0) return DIFF_FILE_CONCURRENCY;
514 const admits = (left: number, spent: number) =>
515 Math.ceil(left / Math.max(1, spent / sections.length));
516 return Math.max(
517 1,
518 Math.min(
519 DIFF_FILE_CONCURRENCY,
520 MAX_DIFF_SLICE_FILES - sections.length,
521 admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),
522 admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),
523 ),
524 );
525 };
526 let blobs: ReadonlyMap<string, AzureDevOpsItemContent> = new Map();
527 let blobsUntil = index;
528 const fromBlobs = (change: AzureDevOpsChangeEntry): AzureDevOpsFileTexts | null => {
529 const side = (id: string | null) =>
530 id === null ? undefined : blobs.get(id.toLowerCase());
531 const oldItem = change.changeKind === "new" ? EMPTY_ITEM : side(change.originalObjectId);
532 const newItem = change.changeKind === "deleted" ? EMPTY_ITEM : side(change.objectId);
533 return oldItem === undefined || newItem === undefined
534 ? null
535 : {
536 oldContents: oldItem.contents,
537 newContents: newItem.contents,
538 binary: oldItem.isBinary || newItem.isBinary,
539 };
540 };
541 while (!full && index < changes.length) {
542 if (index >= blobsUntil) {
543 blobsUntil = index + BLOB_BATCH_FILES;
544 blobs = yield* readBlobs({
545 cwd: input.cwd,
546 location: scope.location,
547 objectIds: changes.slice(index, blobsUntil).flatMap(blobIdsOf),
548 }).pipe(
549 // Per-file reads then answer, or fail, for each file.
550 Effect.catchTags({
551 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(new Map()),
552 AzureDevOpsCommandFailedError: () => Effect.succeed(new Map()),
553 AzureDevOpsPullRequestReadError: () => Effect.succeed(new Map()),
554 }),
555 );
556 }
557 const batch = changes.slice(index, Math.min(index + batchWidth(), blobsUntil));
558 const read = yield* Effect.forEach(
559 batch,
560 (change) =>
561 Effect.suspend(() => {
562 const held = fromBlobs(change);
563 return held === null
564 ? readTexts({ cwd: input.cwd, location: scope.location, iteration, change })
565 : Effect.succeed(held);
566 }).pipe(
567 // Auth, rate-limit and CLI failures must reach the caller.
568 Effect.catchTags({
569 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),
570 AzureDevOpsCommandFailedError: () => Effect.succeed(null),
571 AzureDevOpsPullRequestReadError: () => Effect.succeed(null),
572 }),
573 Effect.map((texts) => ({ change, texts })),
574 ),
575 { concurrency: DIFF_FILE_CONCURRENCY },
576 );
577 for (const { change, texts } of read) {
578 // Synchronous diffs need yields to let other server work run.
579 yield* Effect.yieldNow;
580 const file =
581 texts === null
582 ? azureDevOpsUnreadableFilePatch(change)
583 : azureDevOpsFilePatch({ change, texts });
584 sections.push(file.section);
585 bytes += byteLength(file.section);
586 edits += file.edits;
587 truncated = truncated || file.truncated;
588 index += 1;
589 // Add a file before checking budgets so oversized files cannot stall the cursor.
590 if (
591 bytes >= MAX_DIFF_SLICE_BYTES ||
592 edits + MAX_FILE_DIFF_EDITS > MAX_DIFF_SLICE_EDITS ||
593 sections.length >= MAX_DIFF_SLICE_FILES ||
594 file.abandoned
595 ) {
596 full = true;
597 break;
598 }
599 }
600 }
601
602 const slice: ProviderDiffSlice = {
603 patch: sections.join(""),
604 truncated,
605 nextCursor:
606 index >= changes.length
607 ? null
608 : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),
609 };
610 return slice;
611 },
612 Effect.mapError(fail("getDiff")),
613 ),
614
615 getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(
616 function* (input) {
617 const scope = yield* diffScope(input);
618 const iteration = scope?.iterations.at(-1);
619 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
620 return yield* readTexts({
621 cwd: input.cwd,
622 location: scope.location,
623 iteration,
624 change: {
625 changeKind: input.changeType,
626 path: input.newPath,
627 oldPath: input.oldPath,
628 },
629 });
630 },
631 Effect.mapError(fail("getDiffFileContents")),
632 ),
633
634 /**
635 * A path the change does not carry is at the empty revision, which is where a file the pull
636 * request deletes sits. When the change was too long to follow to its end, those paths are left
637 * out instead: reporting them as deleted would clear a file nobody has read.
638 */
639 getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(
640 function* (input) {
641 const revisions = new Map<string, string>();
642 if (input.paths.length === 0) return { revisions };
643 const scope = yield* diffScope(input);
644 if (scope === null) return { revisions };
645 const listed = yield* listLatestChanges({
646 ...scope,
647 cwd: input.cwd,
648 number: input.number,
649 });
650 const marked = new Set(input.paths);
651 for (const change of listed.changes) {
652 if (!marked.has(change.path) || change.objectId === null) continue;
653 revisions.set(change.path, change.objectId);
654 }
655 if (!listed.truncated) {
656 for (const path of input.paths) {
657 if (!revisions.has(path)) revisions.set(path, "");
658 }
659 }
660 return { revisions };
661 },
662 Effect.mapError(fail("getFileRevisions")),
663 ),
664
665 runAction: (input) =>
666 cli
667 .runPullRequestAction({
668 cwd: input.cwd,
669 number: input.number,
670 action: input.action,
671 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
672 })
673 .pipe(
674 Effect.mapError(fail("runAction")),
675 Effect.map(
676 (pullRequest) =>
677 pullRequest && {
678 ...toSummary(pullRequest),
679 autoMergeEnabled: pullRequest.autoMergeEnabled,
680 ...(pullRequest.autoMergeMethod === undefined
681 ? {}
682 : { autoMergeMethod: pullRequest.autoMergeMethod }),
683 },
684 ),
685 ),
686
687 updateChangeRequest: (input) =>
688 cli
689 .updatePullRequest({
690 cwd: input.cwd,
691 number: input.number,
692 title: input.title,
693 body: input.body,
694 })
695 .pipe(Effect.mapError(fail("updateChangeRequest"))),
696
697 listReviewerCandidates: () =>
698 Effect.fail(
699 new PullRequestProviderError({
700 provider: SourceControlProviderKind.make("azure-devops"),
701 operation: "listReviewerCandidates",
702 reason: "failed",
703 detail: "Azure DevOps cannot say who may review a pull request.",
704 }),
705 ),
706
707 setReviewerRequest: (input) =>
708 cli
709 .setPullRequestReviewers({
710 cwd: input.cwd,
711 number: input.number,
712 reviewers: input.reviewers.map((reviewer) => reviewer.id),
713 requested: input.requested,
714 })
715 .pipe(Effect.mapError(fail("setReviewerRequest"))),
716
717 comment: () => unsupported("comment"),
718
719 submitReview: () => unsupported("submitReview"),
720
721 replyToThread: () => unsupported("replyToThread"),
722
723 setThreadResolution: () => unsupported("setThreadResolution"),
724
725 setReaction: () => unsupported("setReaction"),
726 };
727
728 return provider;
729});