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