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