The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as FileSystem from "effect/FileSystem"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as Result from "effect/Result"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import type { |
| 8 | PullRequestAction, |
| 9 | PullRequestCheck, |
| 10 | PullRequestComment, |
| 11 | PullRequestInvolvement, |
| 12 | PullRequestLabel, |
| 13 | PullRequestListState, |
| 14 | PullRequestMergeMethod, |
| 15 | } from "@t3tools/contracts"; |
| 16 | |
| 17 | import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks"; |
| 18 | |
| 19 | import * as AzureDevOpsCli from "./AzureDevOpsCli.ts"; |
| 20 | import { blobContent, readBlobZip } from "./azureDevOpsBlobZip.ts"; |
| 21 | import { |
| 22 | decodeItemContentJson, |
| 23 | decodeIterationChangesJson, |
| 24 | decodeIterationsJson, |
| 25 | decodeLabelsJson, |
| 26 | decodePolicyChecksJson, |
| 27 | decodePullRequestJson, |
| 28 | decodePullRequestListJson, |
| 29 | decodeThreadsJson, |
| 30 | decodeViewerJson, |
| 31 | type AzureDevOpsChangeEntry, |
| 32 | type AzureDevOpsItemContent, |
| 33 | type AzureDevOpsIteration, |
| 34 | type AzureDevOpsPullRequest, |
| 35 | type AzureDevOpsRepositoryLocation, |
| 36 | } from "./azureDevOpsPullRequestJson.ts"; |
| 37 | import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 38 | |
| 39 | export class AzureDevOpsPullRequestReadError extends Schema.TaggedError<AzureDevOpsPullRequestReadError>()( |
| 40 | "AzureDevOpsPullRequestReadError", |
| 41 | { |
| 42 | command: Schema.Literal("az"), |
| 43 | cwd: Schema.String, |
| 44 | operation: Schema.String, |
| 45 | cause: Schema.Defect(), |
| 46 | }, |
| 47 | ) { |
| 48 | get detail(): string { |
| 49 | return `Azure CLI returned an unreadable ${this.operation} response.`; |
| 50 | } |
| 51 | |
| 52 | override get message(): string { |
| 53 | return `Azure CLI failed in ${this.operation}: ${this.detail}`; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | export class AzureDevOpsViewerUnavailableError extends Schema.TaggedError<AzureDevOpsViewerUnavailableError>()( |
| 58 | "AzureDevOpsViewerUnavailableError", |
| 59 | { |
| 60 | command: Schema.Literal("az"), |
| 61 | cwd: Schema.String, |
| 62 | }, |
| 63 | ) { |
| 64 | get detail(): string { |
| 65 | return "Azure CLI could not name the signed-in account. Run `az login` and retry."; |
| 66 | } |
| 67 | |
| 68 | override get message(): string { |
| 69 | return `Azure CLI failed in getViewer: ${this.detail}`; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedError<AzureDevOpsPullRequestIncompleteError>()( |
| 74 | "AzureDevOpsPullRequestIncompleteError", |
| 75 | { |
| 76 | command: Schema.Literal("az"), |
| 77 | cwd: Schema.String, |
| 78 | number: Schema.Int, |
| 79 | }, |
| 80 | ) { |
| 81 | get detail(): string { |
| 82 | return "Azure DevOps returned no branch or link for the pull request."; |
| 83 | } |
| 84 | |
| 85 | override get message(): string { |
| 86 | return `Azure CLI failed in getPullRequest: ${this.detail}`; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | export class AzureDevOpsReviewerNameError extends Schema.TaggedError<AzureDevOpsReviewerNameError>()( |
| 91 | "AzureDevOpsReviewerNameError", |
| 92 | { |
| 93 | command: Schema.Literal("az"), |
| 94 | cwd: Schema.String, |
| 95 | }, |
| 96 | ) { |
| 97 | get detail(): string { |
| 98 | return "A reviewer is named by an email address or an identity id."; |
| 99 | } |
| 100 | |
| 101 | override get message(): string { |
| 102 | return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`; |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | export type AzureDevOpsPullRequestCliError = |
| 107 | | AzureDevOpsCli.AzureDevOpsCliError |
| 108 | | AzureDevOpsPullRequestReadError |
| 109 | | AzureDevOpsPullRequestIncompleteError |
| 110 | | AzureDevOpsReviewerNameError |
| 111 | | AzureDevOpsViewerUnavailableError; |
| 112 | |
| 113 | const REST_API_VERSION = "7.1"; |
| 114 | const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; |
| 115 | /** A 2,000-file page exceeds the default 1 MiB output budget. */ |
| 116 | const CHANGE_ENTRIES_MAX_OUTPUT_BYTES = 8 * 1024 * 1024; |
| 117 | /** JSON escaping and base64 can exceed the decoded file's size. */ |
| 118 | const ITEM_CONTENT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; |
| 119 | /** A larger batch is left to per-file reads rather than held in memory at once. */ |
| 120 | const BLOB_ARCHIVE_MAX_BYTES = 64 * 1024 * 1024; |
| 121 | /** Matches what a per-file read could carry. */ |
| 122 | const BLOB_MAX_BYTES = ITEM_CONTENT_MAX_OUTPUT_BYTES; |
| 123 | /** Blobs past this, together, are left to per-file reads, which hold a few at a time. */ |
| 124 | const BLOB_BATCH_MAX_BYTES = 16 * 1024 * 1024; |
| 125 | const BLOB_ID = /^[0-9a-f]{40}$/i; |
| 126 | /** Review history is unpaged and independent of diff size. */ |
| 127 | const REVIEW_HISTORY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024; |
| 128 | |
| 129 | const POLICY_EVALUATIONS_PER_PAGE = 100; |
| 130 | const MAX_POLICY_EVALUATIONS = 1000; |
| 131 | |
| 132 | /** Azure's iteration-change page limit. */ |
| 133 | const CHANGE_ENTRIES_PER_PAGE = 2000; |
| 134 | |
| 135 | /** Count raw entries, including folders and malformed rows. */ |
| 136 | const MAX_CHANGE_ENTRIES = 10_000; |
| 137 | |
| 138 | export interface AzureDevOpsIterationChanges { |
| 139 | readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>; |
| 140 | readonly truncated: boolean; |
| 141 | } |
| 142 | |
| 143 | export class AzureDevOpsPullRequestCli extends Context.Service< |
| 144 | AzureDevOpsPullRequestCli, |
| 145 | { |
| 146 | readonly getViewer: (input: { |
| 147 | readonly cwd: string; |
| 148 | }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>; |
| 149 | |
| 150 | readonly listPullRequests: (input: { |
| 151 | readonly cwd: string; |
| 152 | readonly repository: string; |
| 153 | readonly state: PullRequestListState; |
| 154 | readonly involvement: PullRequestInvolvement; |
| 155 | readonly viewer: string; |
| 156 | readonly limit: number; |
| 157 | /** Matched by `--creator`, which takes the email a row shows as its login. */ |
| 158 | readonly author?: string | undefined; |
| 159 | /** |
| 160 | * Where to carry on from. Azure has no date filter for a pull request listing, so the only |
| 161 | * part of a cursor it can use is how many rows have already been handed over. |
| 162 | */ |
| 163 | readonly cursor?: ProviderListCursor | undefined; |
| 164 | }) => Effect.Effect< |
| 165 | { |
| 166 | readonly items: ReadonlyArray<AzureDevOpsPullRequest>; |
| 167 | readonly truncated: boolean; |
| 168 | readonly cursorAdvance: number; |
| 169 | }, |
| 170 | AzureDevOpsPullRequestCliError |
| 171 | >; |
| 172 | |
| 173 | readonly getPullRequest: (input: { |
| 174 | readonly cwd: string; |
| 175 | readonly number: number; |
| 176 | }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>; |
| 177 | |
| 178 | readonly listPolicyChecks: (input: { |
| 179 | readonly cwd: string; |
| 180 | readonly number: number; |
| 181 | /** Azure holds builds back on a draft, which reads the same as a build about to start. */ |
| 182 | readonly isDraft: boolean; |
| 183 | }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, AzureDevOpsPullRequestCliError>; |
| 184 | |
| 185 | readonly listThreads: (input: { |
| 186 | readonly cwd: string; |
| 187 | readonly location: AzureDevOpsRepositoryLocation; |
| 188 | readonly number: number; |
| 189 | }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>; |
| 190 | |
| 191 | /** `az repos pr show` returns null labels, so the detail reads them here. */ |
| 192 | readonly listLabels: (input: { |
| 193 | readonly cwd: string; |
| 194 | readonly location: AzureDevOpsRepositoryLocation; |
| 195 | readonly number: number; |
| 196 | }) => Effect.Effect<ReadonlyArray<PullRequestLabel>, AzureDevOpsPullRequestCliError>; |
| 197 | |
| 198 | readonly listIterations: (input: { |
| 199 | readonly cwd: string; |
| 200 | readonly location: AzureDevOpsRepositoryLocation; |
| 201 | readonly number: number; |
| 202 | }) => Effect.Effect<ReadonlyArray<AzureDevOpsIteration>, AzureDevOpsPullRequestCliError>; |
| 203 | |
| 204 | /** Changes cover the whole PR from its merge base. */ |
| 205 | readonly listIterationChanges: (input: { |
| 206 | readonly cwd: string; |
| 207 | readonly location: AzureDevOpsRepositoryLocation; |
| 208 | readonly number: number; |
| 209 | readonly iterationId: number; |
| 210 | }) => Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError>; |
| 211 | |
| 212 | readonly readItemContent: (input: { |
| 213 | readonly cwd: string; |
| 214 | readonly location: AzureDevOpsRepositoryLocation; |
| 215 | readonly path: string; |
| 216 | readonly commit: string; |
| 217 | }) => Effect.Effect<AzureDevOpsItemContent, AzureDevOpsPullRequestCliError>; |
| 218 | |
| 219 | /** |
| 220 | * Many files in one `az` run, by blob id, keyed by lowercase id. A blob only Azure's item read |
| 221 | * decodes faithfully, or one too large to carry, is left out. |
| 222 | */ |
| 223 | readonly readBlobs: (input: { |
| 224 | readonly cwd: string; |
| 225 | readonly location: AzureDevOpsRepositoryLocation; |
| 226 | readonly objectIds: ReadonlyArray<string>; |
| 227 | }) => Effect.Effect< |
| 228 | ReadonlyMap<string, AzureDevOpsItemContent>, |
| 229 | AzureDevOpsPullRequestCliError |
| 230 | >; |
| 231 | |
| 232 | readonly runPullRequestAction: (input: { |
| 233 | readonly cwd: string; |
| 234 | readonly number: number; |
| 235 | readonly action: PullRequestAction; |
| 236 | readonly mergeMethod?: PullRequestMergeMethod; |
| 237 | }) => Effect.Effect<AzureDevOpsPullRequest | void, AzureDevOpsPullRequestCliError>; |
| 238 | |
| 239 | readonly updatePullRequest: (input: { |
| 240 | readonly cwd: string; |
| 241 | readonly number: number; |
| 242 | readonly title?: string | undefined; |
| 243 | readonly body?: string | undefined; |
| 244 | }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>; |
| 245 | |
| 246 | readonly setPullRequestReviewers: (input: { |
| 247 | readonly cwd: string; |
| 248 | readonly number: number; |
| 249 | readonly reviewers: ReadonlyArray<string>; |
| 250 | readonly requested: boolean; |
| 251 | }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>; |
| 252 | } |
| 253 | >()("@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli") {} |
| 254 | |
| 255 | function statusArgs(state: PullRequestListState): ReadonlyArray<string> { |
| 256 | switch (state) { |
| 257 | case "open": |
| 258 | return ["--status", "active"]; |
| 259 | case "merged": |
| 260 | return ["--status", "completed"]; |
| 261 | case "closed": |
| 262 | return ["--status", "abandoned"]; |
| 263 | case "all": |
| 264 | return ["--status", "all"]; |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | function involvementArgs(input: { |
| 269 | readonly involvement: PullRequestInvolvement; |
| 270 | readonly viewer: string; |
| 271 | }): ReadonlyArray<string> { |
| 272 | switch (input.involvement) { |
| 273 | case "authored": |
| 274 | return ["--creator", input.viewer]; |
| 275 | case "reviewing": |
| 276 | return ["--reviewer", input.viewer]; |
| 277 | case "all": |
| 278 | return []; |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | function actionArgs( |
| 283 | action: PullRequestAction, |
| 284 | mergeMethod: PullRequestMergeMethod | undefined, |
| 285 | ): ReadonlyArray<string> { |
| 286 | switch (action) { |
| 287 | case "merge": |
| 288 | return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"]; |
| 289 | case "enable-auto-merge": |
| 290 | return [ |
| 291 | "--auto-complete", |
| 292 | "true", |
| 293 | ...(mergeMethod === undefined |
| 294 | ? [] |
| 295 | : ["--squash", mergeMethod === "squash" ? "true" : "false"]), |
| 296 | ]; |
| 297 | case "disable-auto-merge": |
| 298 | return ["--auto-complete", "false"]; |
| 299 | case "ready": |
| 300 | return ["--draft", "false"]; |
| 301 | case "draft": |
| 302 | return ["--draft", "true"]; |
| 303 | case "close": |
| 304 | return ["--status", "abandoned"]; |
| 305 | case "update-branch": |
| 306 | return []; |
| 307 | case "reopen": |
| 308 | return ["--status", "active"]; |
| 309 | case "revert": |
| 310 | case "approve-workflows": |
| 311 | case "delete-branch": |
| 312 | throw new Error(`Azure DevOps pull request action ${action} is unsupported`); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | function isReviewerName(value: string): boolean { |
| 317 | const name = value.trim(); |
| 318 | return name.length > 0 && !name.startsWith("-"); |
| 319 | } |
| 320 | |
| 321 | /** @public */ |
| 322 | export const make = Effect.gen(function* () { |
| 323 | const azure = yield* AzureDevOpsCli.AzureDevOpsCli; |
| 324 | const fileSystem = yield* FileSystem.FileSystem; |
| 325 | |
| 326 | const detectArgs = ["--detect", "true"] as const; |
| 327 | |
| 328 | const executeJson = (input: { |
| 329 | readonly cwd: string; |
| 330 | readonly args: ReadonlyArray<string>; |
| 331 | readonly maxOutputBytes?: number; |
| 332 | }) => |
| 333 | azure.execute({ |
| 334 | cwd: input.cwd, |
| 335 | args: [...input.args, "--only-show-errors", "--output", "json"], |
| 336 | ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }), |
| 337 | }); |
| 338 | |
| 339 | /** Use the extension's credentials; `az rest` uses the default tenant. */ |
| 340 | const invoke = <A>(input: { |
| 341 | readonly cwd: string; |
| 342 | readonly operation: string; |
| 343 | readonly resource: string; |
| 344 | readonly routeParameters: ReadonlyArray<string>; |
| 345 | readonly queryParameters?: ReadonlyArray<string>; |
| 346 | readonly maxOutputBytes?: number; |
| 347 | readonly decode: (raw: string) => Result.Result<A, unknown>; |
| 348 | }): Effect.Effect<A, AzureDevOpsPullRequestCliError> => |
| 349 | executeJson({ |
| 350 | cwd: input.cwd, |
| 351 | ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }), |
| 352 | args: [ |
| 353 | "devops", |
| 354 | "invoke", |
| 355 | ...detectArgs, |
| 356 | "--area", |
| 357 | "git", |
| 358 | "--resource", |
| 359 | input.resource, |
| 360 | "--api-version", |
| 361 | REST_API_VERSION, |
| 362 | "--route-parameters", |
| 363 | ...input.routeParameters, |
| 364 | ...(input.queryParameters === undefined |
| 365 | ? [] |
| 366 | : ["--query-parameters", ...input.queryParameters]), |
| 367 | ], |
| 368 | }).pipe( |
| 369 | Effect.flatMap((result) => { |
| 370 | const decoded = input.decode(result.stdout.trim()); |
| 371 | return Result.isSuccess(decoded) |
| 372 | ? Effect.succeed(decoded.success) |
| 373 | : Effect.fail( |
| 374 | new AzureDevOpsPullRequestReadError({ |
| 375 | command: "az", |
| 376 | cwd: input.cwd, |
| 377 | operation: input.operation, |
| 378 | cause: decoded.failure, |
| 379 | }), |
| 380 | ); |
| 381 | }), |
| 382 | ); |
| 383 | |
| 384 | /** Azure's items route requires a leading slash. */ |
| 385 | const toItemPath = (path: string) => (path.startsWith("/") ? path : `/${path}`); |
| 386 | |
| 387 | const repositoryRoute = (location: AzureDevOpsRepositoryLocation): ReadonlyArray<string> => [ |
| 388 | `project=${location.project}`, |
| 389 | `repositoryId=${location.repository}`, |
| 390 | ]; |
| 391 | |
| 392 | const pullRequestRoute = (input: { |
| 393 | readonly location: AzureDevOpsRepositoryLocation; |
| 394 | readonly number: number; |
| 395 | }): ReadonlyArray<string> => [ |
| 396 | ...repositoryRoute(input.location), |
| 397 | `pullRequestId=${input.number}`, |
| 398 | ]; |
| 399 | |
| 400 | /** Decoding can shorten a non-final page; advance by raw rows. */ |
| 401 | const listPullRequestPage = (input: { |
| 402 | readonly cwd: string; |
| 403 | readonly repository: string; |
| 404 | readonly state: PullRequestListState; |
| 405 | readonly involvement: PullRequestInvolvement; |
| 406 | readonly viewer: string; |
| 407 | readonly author?: string | undefined; |
| 408 | readonly limit: number; |
| 409 | readonly skip: number; |
| 410 | readonly cursorAdvance: number; |
| 411 | readonly items: ReadonlyArray<AzureDevOpsPullRequest>; |
| 412 | }): Effect.Effect< |
| 413 | { |
| 414 | readonly items: ReadonlyArray<AzureDevOpsPullRequest>; |
| 415 | readonly truncated: boolean; |
| 416 | readonly cursorAdvance: number; |
| 417 | }, |
| 418 | AzureDevOpsPullRequestCliError |
| 419 | > => { |
| 420 | const remaining = input.limit - input.items.length; |
| 421 | const top = remaining + 1; |
| 422 | return executeJson({ |
| 423 | cwd: input.cwd, |
| 424 | maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES, |
| 425 | args: [ |
| 426 | "repos", |
| 427 | "pr", |
| 428 | "list", |
| 429 | ...detectArgs, |
| 430 | "--repository", |
| 431 | input.repository, |
| 432 | ...statusArgs(input.state), |
| 433 | ...involvementArgs(input), |
| 434 | ...(input.author === undefined || input.involvement === "authored" |
| 435 | ? [] |
| 436 | : ["--creator", input.author]), |
| 437 | "--include-links", |
| 438 | ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]), |
| 439 | "--top", |
| 440 | String(top), |
| 441 | ], |
| 442 | }).pipe( |
| 443 | Effect.flatMap((result) => { |
| 444 | const raw = result.stdout.trim(); |
| 445 | if (raw.length === 0) { |
| 446 | return Effect.succeed({ |
| 447 | items: input.items, |
| 448 | truncated: false, |
| 449 | cursorAdvance: input.cursorAdvance, |
| 450 | }); |
| 451 | } |
| 452 | const decoded = decodePullRequestListJson(raw); |
| 453 | if (!Result.isSuccess(decoded)) { |
| 454 | return Effect.fail( |
| 455 | new AzureDevOpsPullRequestReadError({ |
| 456 | command: "az", |
| 457 | cwd: input.cwd, |
| 458 | operation: "listPullRequests", |
| 459 | cause: decoded.failure, |
| 460 | }), |
| 461 | ); |
| 462 | } |
| 463 | |
| 464 | const lastItemIndex = decoded.success.rawIndexes[remaining - 1]; |
| 465 | if (lastItemIndex !== undefined) { |
| 466 | const consumed = lastItemIndex + 1; |
| 467 | return Effect.succeed({ |
| 468 | items: [...input.items, ...decoded.success.items.slice(0, remaining)], |
| 469 | truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top, |
| 470 | cursorAdvance: input.cursorAdvance + consumed, |
| 471 | }); |
| 472 | } |
| 473 | |
| 474 | const items = [...input.items, ...decoded.success.items]; |
| 475 | if (decoded.success.rawCount < top) { |
| 476 | return Effect.succeed({ |
| 477 | items, |
| 478 | truncated: false, |
| 479 | cursorAdvance: input.cursorAdvance + decoded.success.rawCount, |
| 480 | }); |
| 481 | } |
| 482 | return listPullRequestPage({ |
| 483 | ...input, |
| 484 | skip: input.skip + decoded.success.rawCount, |
| 485 | cursorAdvance: input.cursorAdvance + decoded.success.rawCount, |
| 486 | items, |
| 487 | }); |
| 488 | }), |
| 489 | ); |
| 490 | }; |
| 491 | |
| 492 | return AzureDevOpsPullRequestCli.of({ |
| 493 | getViewer: Effect.fn("AzureDevOpsPullRequestCli.getViewer")(function (input) { |
| 494 | return executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe( |
| 495 | Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => { |
| 496 | const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`); |
| 497 | if (!Result.isSuccess(decoded)) { |
| 498 | return Effect.fail( |
| 499 | new AzureDevOpsPullRequestReadError({ |
| 500 | command: "az", |
| 501 | cwd: input.cwd, |
| 502 | operation: "getViewer", |
| 503 | cause: decoded.failure, |
| 504 | }), |
| 505 | ); |
| 506 | } |
| 507 | return decoded.success === null |
| 508 | ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd })) |
| 509 | : Effect.succeed(decoded.success); |
| 510 | }), |
| 511 | // `az account show` cannot identify PAT logins; the extension resolves `--creator me`. |
| 512 | Effect.catchIf( |
| 513 | (error) => error._tag !== "AzureDevOpsCliUnavailableError", |
| 514 | () => |
| 515 | executeJson({ |
| 516 | cwd: input.cwd, |
| 517 | args: [ |
| 518 | "repos", |
| 519 | "pr", |
| 520 | "list", |
| 521 | ...detectArgs, |
| 522 | "--creator", |
| 523 | "me", |
| 524 | "--status", |
| 525 | "all", |
| 526 | "--top", |
| 527 | "1", |
| 528 | ], |
| 529 | }).pipe( |
| 530 | Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => { |
| 531 | const decoded = decodePullRequestListJson(result.stdout.trim() || "[]"); |
| 532 | const login = Result.isSuccess(decoded) |
| 533 | ? decoded.success.items[0]?.author?.login |
| 534 | : undefined; |
| 535 | return login === undefined |
| 536 | ? Effect.fail( |
| 537 | new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }), |
| 538 | ) |
| 539 | : Effect.succeed(login); |
| 540 | }), |
| 541 | ), |
| 542 | ), |
| 543 | ); |
| 544 | }), |
| 545 | |
| 546 | listPullRequests: Effect.fn("AzureDevOpsPullRequestCli.listPullRequests")(function (input) { |
| 547 | return listPullRequestPage({ |
| 548 | cwd: input.cwd, |
| 549 | repository: input.repository, |
| 550 | state: input.state, |
| 551 | involvement: input.involvement, |
| 552 | viewer: input.viewer, |
| 553 | author: input.author, |
| 554 | limit: input.limit, |
| 555 | skip: input.cursor?.delivered ?? 0, |
| 556 | cursorAdvance: 0, |
| 557 | items: [], |
| 558 | }); |
| 559 | }), |
| 560 | |
| 561 | getPullRequest: Effect.fn("AzureDevOpsPullRequestCli.getPullRequest")(function (input) { |
| 562 | return executeJson({ |
| 563 | cwd: input.cwd, |
| 564 | args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)], |
| 565 | }).pipe( |
| 566 | Effect.flatMap( |
| 567 | (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => { |
| 568 | const decoded = decodePullRequestJson(result.stdout.trim()); |
| 569 | if (!Result.isSuccess(decoded)) { |
| 570 | return Effect.fail( |
| 571 | new AzureDevOpsPullRequestReadError({ |
| 572 | command: "az", |
| 573 | cwd: input.cwd, |
| 574 | operation: "getPullRequest", |
| 575 | cause: decoded.failure, |
| 576 | }), |
| 577 | ); |
| 578 | } |
| 579 | return decoded.success === null |
| 580 | ? Effect.fail( |
| 581 | new AzureDevOpsPullRequestIncompleteError({ |
| 582 | command: "az", |
| 583 | cwd: input.cwd, |
| 584 | number: input.number, |
| 585 | }), |
| 586 | ) |
| 587 | : Effect.succeed(decoded.success); |
| 588 | }, |
| 589 | ), |
| 590 | ); |
| 591 | }), |
| 592 | |
| 593 | listPolicyChecks: Effect.fn("AzureDevOpsPullRequestCli.listPolicyChecks")(function* (input) { |
| 594 | const unreadable = (cause: unknown) => |
| 595 | new AzureDevOpsPullRequestReadError({ |
| 596 | command: "az", |
| 597 | cwd: input.cwd, |
| 598 | operation: "listPolicyChecks", |
| 599 | cause, |
| 600 | }); |
| 601 | const checks: PullRequestCheck[] = []; |
| 602 | for (let skip = 0; skip < MAX_POLICY_EVALUATIONS; skip += POLICY_EVALUATIONS_PER_PAGE) { |
| 603 | const result = yield* executeJson({ |
| 604 | cwd: input.cwd, |
| 605 | args: [ |
| 606 | "repos", |
| 607 | "pr", |
| 608 | "policy", |
| 609 | "list", |
| 610 | ...detectArgs, |
| 611 | "--id", |
| 612 | String(input.number), |
| 613 | "--top", |
| 614 | String(POLICY_EVALUATIONS_PER_PAGE), |
| 615 | "--skip", |
| 616 | String(skip), |
| 617 | ], |
| 618 | }); |
| 619 | if (result.stdoutTruncated) return yield* unreadable("Policy output was truncated"); |
| 620 | const page = decodePolicyChecksJson(result.stdout.trim(), { isDraft: input.isDraft }); |
| 621 | if (!Result.isSuccess(page)) return yield* unreadable(page.failure); |
| 622 | checks.push(...page.success.checks); |
| 623 | if (page.success.rawCount < POLICY_EVALUATIONS_PER_PAGE) return sortChecks(checks); |
| 624 | } |
| 625 | return yield* unreadable("Policy evaluations exceeded the read limit"); |
| 626 | }), |
| 627 | |
| 628 | listThreads: Effect.fn("AzureDevOpsPullRequestCli.listThreads")(function (input) { |
| 629 | return invoke({ |
| 630 | cwd: input.cwd, |
| 631 | operation: "listThreads", |
| 632 | resource: "pullRequestThreads", |
| 633 | routeParameters: pullRequestRoute(input), |
| 634 | maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES, |
| 635 | decode: decodeThreadsJson, |
| 636 | }); |
| 637 | }), |
| 638 | |
| 639 | listLabels: Effect.fn("AzureDevOpsPullRequestCli.listLabels")(function (input) { |
| 640 | return invoke({ |
| 641 | cwd: input.cwd, |
| 642 | operation: "listLabels", |
| 643 | resource: "pullRequestLabels", |
| 644 | routeParameters: pullRequestRoute(input), |
| 645 | decode: decodeLabelsJson, |
| 646 | }); |
| 647 | }), |
| 648 | |
| 649 | listIterations: Effect.fn("AzureDevOpsPullRequestCli.listIterations")(function (input) { |
| 650 | return invoke({ |
| 651 | cwd: input.cwd, |
| 652 | operation: "listIterations", |
| 653 | resource: "pullRequestIterations", |
| 654 | routeParameters: pullRequestRoute(input), |
| 655 | maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES, |
| 656 | decode: decodeIterationsJson, |
| 657 | }); |
| 658 | }), |
| 659 | |
| 660 | listIterationChanges: Effect.fn("AzureDevOpsPullRequestCli.listIterationChanges")( |
| 661 | function (input) { |
| 662 | const page = (skip: number) => |
| 663 | invoke({ |
| 664 | cwd: input.cwd, |
| 665 | operation: "listIterationChanges", |
| 666 | resource: "pullRequestIterationChanges", |
| 667 | routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`], |
| 668 | queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`], |
| 669 | maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES, |
| 670 | decode: decodeIterationChangesJson, |
| 671 | }); |
| 672 | const from = ( |
| 673 | skip: number, |
| 674 | collected: ReadonlyArray<AzureDevOpsChangeEntry>, |
| 675 | ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> => |
| 676 | page(skip).pipe( |
| 677 | Effect.flatMap((answer) => { |
| 678 | const changes = [...collected, ...answer.changes]; |
| 679 | if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false }); |
| 680 | return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES |
| 681 | ? Effect.succeed({ changes, truncated: true }) |
| 682 | : from(answer.nextSkip, changes); |
| 683 | }), |
| 684 | ); |
| 685 | return from(0, []); |
| 686 | }, |
| 687 | ), |
| 688 | |
| 689 | readBlobs: Effect.fn("AzureDevOpsPullRequestCli.readBlobs")(function* (input) { |
| 690 | const requested = new Map<string, string>(); |
| 691 | // Azure states ids in uppercase and names entries in lowercase. |
| 692 | for (const id of input.objectIds) { |
| 693 | const key = id.toLowerCase(); |
| 694 | if (BLOB_ID.test(id) && !requested.has(key)) requested.set(key, id); |
| 695 | } |
| 696 | if (requested.size === 0) return new Map<string, AzureDevOpsItemContent>(); |
| 697 | const readFailure = (cause: unknown) => |
| 698 | new AzureDevOpsPullRequestReadError({ |
| 699 | command: "az", |
| 700 | cwd: input.cwd, |
| 701 | operation: "readBlobs", |
| 702 | cause, |
| 703 | }); |
| 704 | return yield* Effect.scoped( |
| 705 | Effect.gen(function* () { |
| 706 | const directory = yield* fileSystem |
| 707 | .makeTempDirectoryScoped({ prefix: "t3-azure-blobs-" }) |
| 708 | .pipe(Effect.mapError(readFailure)); |
| 709 | const request = `${directory}/ids.json`; |
| 710 | // invoke refuses to overwrite its output, so the archive gets a name nothing holds yet. |
| 711 | const archive = `${directory}/blobs.zip`; |
| 712 | yield* fileSystem |
| 713 | .writeFileString( |
| 714 | request, |
| 715 | `[${[...requested.values()].map((id) => `"${id}"`).join(",")}]`, |
| 716 | ) |
| 717 | .pipe(Effect.mapError(readFailure)); |
| 718 | yield* azure.execute({ |
| 719 | cwd: input.cwd, |
| 720 | args: [ |
| 721 | "devops", |
| 722 | "invoke", |
| 723 | ...detectArgs, |
| 724 | "--area", |
| 725 | "git", |
| 726 | "--resource", |
| 727 | "blobs", |
| 728 | "--api-version", |
| 729 | REST_API_VERSION, |
| 730 | "--route-parameters", |
| 731 | ...repositoryRoute(input.location), |
| 732 | "--http-method", |
| 733 | "POST", |
| 734 | "--in-file", |
| 735 | request, |
| 736 | "--accept-media-type", |
| 737 | "application/zip", |
| 738 | "--out-file", |
| 739 | archive, |
| 740 | "--only-show-errors", |
| 741 | ], |
| 742 | }); |
| 743 | const size = yield* fileSystem.stat(archive).pipe( |
| 744 | Effect.map((info) => Number(info.size)), |
| 745 | Effect.mapError(readFailure), |
| 746 | ); |
| 747 | const contents = new Map<string, AzureDevOpsItemContent>(); |
| 748 | if (size > BLOB_ARCHIVE_MAX_BYTES) return contents; |
| 749 | const zip = yield* fileSystem.readFile(archive).pipe(Effect.mapError(readFailure)); |
| 750 | const entries = readBlobZip(zip, BLOB_MAX_BYTES, BLOB_BATCH_MAX_BYTES); |
| 751 | if (entries === null) return yield* readFailure("Azure returned an unreadable archive."); |
| 752 | for (const [id, bytes] of entries) { |
| 753 | const content = requested.has(id) ? blobContent(bytes) : null; |
| 754 | if (content !== null) contents.set(id, content); |
| 755 | } |
| 756 | return contents; |
| 757 | }), |
| 758 | ); |
| 759 | }), |
| 760 | |
| 761 | readItemContent: Effect.fn("AzureDevOpsPullRequestCli.readItemContent")(function (input) { |
| 762 | return invoke({ |
| 763 | cwd: input.cwd, |
| 764 | operation: "readItemContent", |
| 765 | resource: "items", |
| 766 | routeParameters: repositoryRoute(input.location), |
| 767 | queryParameters: [ |
| 768 | // `az devops invoke` does not escape query values, so `#` or `&` in a path would truncate it. |
| 769 | `path=${encodeURIComponent(toItemPath(input.path))}`, |
| 770 | "versionDescriptor.versionType=commit", |
| 771 | `versionDescriptor.version=${input.commit}`, |
| 772 | "includeContent=true", |
| 773 | // Encoded content cannot identify binaries; request Azure's binary flag. |
| 774 | "includeContentMetadata=true", |
| 775 | // `az devops invoke` requires JSON; otherwise Azure returns raw file bytes. |
| 776 | "$format=json", |
| 777 | ], |
| 778 | maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES, |
| 779 | decode: decodeItemContentJson, |
| 780 | }); |
| 781 | }), |
| 782 | |
| 783 | setPullRequestReviewers: Effect.fn("AzureDevOpsPullRequestCli.setPullRequestReviewers")( |
| 784 | function* (input) { |
| 785 | if (input.reviewers.some((reviewer) => !isReviewerName(reviewer))) { |
| 786 | return yield* new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }); |
| 787 | } |
| 788 | return yield* azure |
| 789 | .execute({ |
| 790 | cwd: input.cwd, |
| 791 | args: [ |
| 792 | "repos", |
| 793 | "pr", |
| 794 | "reviewer", |
| 795 | input.requested ? "add" : "remove", |
| 796 | ...detectArgs, |
| 797 | "--id", |
| 798 | String(input.number), |
| 799 | // Repeating `--reviewers` replaces the earlier list. |
| 800 | "--reviewers", |
| 801 | ...input.reviewers, |
| 802 | "--only-show-errors", |
| 803 | "--output", |
| 804 | "json", |
| 805 | ], |
| 806 | }) |
| 807 | .pipe(Effect.asVoid); |
| 808 | }, |
| 809 | ), |
| 810 | |
| 811 | runPullRequestAction: Effect.fn("AzureDevOpsPullRequestCli.runPullRequestAction")( |
| 812 | function (input) { |
| 813 | return azure |
| 814 | .execute({ |
| 815 | cwd: input.cwd, |
| 816 | args: [ |
| 817 | "repos", |
| 818 | "pr", |
| 819 | "update", |
| 820 | ...detectArgs, |
| 821 | "--id", |
| 822 | String(input.number), |
| 823 | ...actionArgs(input.action, input.mergeMethod), |
| 824 | "--only-show-errors", |
| 825 | "--output", |
| 826 | "json", |
| 827 | ], |
| 828 | }) |
| 829 | .pipe( |
| 830 | // `pr update` prints the pull request it left, in the shape `pr show` prints. |
| 831 | Effect.map((result) => { |
| 832 | const decoded = decodePullRequestJson(result.stdout.trim()); |
| 833 | return Result.isSuccess(decoded) ? (decoded.success ?? undefined) : undefined; |
| 834 | }), |
| 835 | ); |
| 836 | }, |
| 837 | ), |
| 838 | |
| 839 | updatePullRequest: Effect.fn("AzureDevOpsPullRequestCli.updatePullRequest")(function (input) { |
| 840 | // One argv entry preserves leading dashes and multi-string descriptions. |
| 841 | const fields = [ |
| 842 | ...(input.title === undefined ? [] : [AzureDevOpsCli.textOption("--title", input.title)]), |
| 843 | ...(input.body === undefined |
| 844 | ? [] |
| 845 | : [AzureDevOpsCli.textOption("--description", input.body)]), |
| 846 | ]; |
| 847 | // az has one stdin, so each value read from it needs its own call. |
| 848 | const batches = |
| 849 | fields.filter((field) => field.stdin !== undefined).length > 1 |
| 850 | ? fields.map((field) => [field]) |
| 851 | : [fields]; |
| 852 | return Effect.forEach( |
| 853 | batches, |
| 854 | (batch) => { |
| 855 | const stdin = batch.find((field) => field.stdin !== undefined)?.stdin; |
| 856 | return azure.execute({ |
| 857 | cwd: input.cwd, |
| 858 | args: [ |
| 859 | "repos", |
| 860 | "pr", |
| 861 | "update", |
| 862 | ...detectArgs, |
| 863 | "--id", |
| 864 | String(input.number), |
| 865 | ...batch.map((field) => field.arg), |
| 866 | "--only-show-errors", |
| 867 | "--output", |
| 868 | "json", |
| 869 | ], |
| 870 | ...(stdin === undefined ? {} : { stdin }), |
| 871 | }); |
| 872 | }, |
| 873 | { discard: true }, |
| 874 | ); |
| 875 | }), |
| 876 | }); |
| 877 | }); |
| 878 | |
| 879 | export const layer = Layer.effect(AzureDevOpsPullRequestCli, make); |