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

AzureDevOpsPullRequestProvider.ts

767 lines28.3 KB

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