Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestComment,
9 PullRequestInvolvement,
10 PullRequestListState,
11 PullRequestMergeMethod,
12} from "@t3tools/contracts";
13
14import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
15import {
16 decodeItemContentJson,
17 decodeIterationChangesJson,
18 decodeIterationsJson,
19 decodePullRequestJson,
20 decodePullRequestListJson,
21 decodeThreadsJson,
22 decodeViewerJson,
23 type AzureDevOpsChangeEntry,
24 type AzureDevOpsItemContent,
25 type AzureDevOpsIteration,
26 type AzureDevOpsPullRequest,
27 type AzureDevOpsRepositoryLocation,
28} from "./azureDevOpsPullRequestJson.ts";
29import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
30
31export class AzureDevOpsPullRequestReadError extends Schema.TaggedError<AzureDevOpsPullRequestReadError>()(
32 "AzureDevOpsPullRequestReadError",
33 {
34 command: Schema.Literal("az"),
35 cwd: Schema.String,
36 operation: Schema.String,
37 cause: Schema.Defect(),
38 },
39) {
40 get detail(): string {
41 return `Azure CLI returned an unreadable ${this.operation} response.`;
42 }
43
44 override get message(): string {
45 return `Azure CLI failed in ${this.operation}: ${this.detail}`;
46 }
47}
48
49export class AzureDevOpsViewerUnavailableError extends Schema.TaggedError<AzureDevOpsViewerUnavailableError>()(
50 "AzureDevOpsViewerUnavailableError",
51 {
52 command: Schema.Literal("az"),
53 cwd: Schema.String,
54 },
55) {
56 get detail(): string {
57 return "Azure CLI could not name the signed-in account. Run `az login` and retry.";
58 }
59
60 override get message(): string {
61 return `Azure CLI failed in getViewer: ${this.detail}`;
62 }
63}
64
65export class AzureDevOpsPullRequestIncompleteError extends Schema.TaggedError<AzureDevOpsPullRequestIncompleteError>()(
66 "AzureDevOpsPullRequestIncompleteError",
67 {
68 command: Schema.Literal("az"),
69 cwd: Schema.String,
70 number: Schema.Int,
71 },
72) {
73 get detail(): string {
74 return "Azure DevOps returned no branch or link for the pull request.";
75 }
76
77 override get message(): string {
78 return `Azure CLI failed in getPullRequest: ${this.detail}`;
79 }
80}
81
82export class AzureDevOpsReviewerNameError extends Schema.TaggedError<AzureDevOpsReviewerNameError>()(
83 "AzureDevOpsReviewerNameError",
84 {
85 command: Schema.Literal("az"),
86 cwd: Schema.String,
87 },
88) {
89 get detail(): string {
90 return "A reviewer is named by an email address or an identity id.";
91 }
92
93 override get message(): string {
94 return `Azure CLI failed in setPullRequestReviewers: ${this.detail}`;
95 }
96}
97
98export type AzureDevOpsPullRequestCliError =
99 | AzureDevOpsCli.AzureDevOpsCliError
100 | AzureDevOpsPullRequestReadError
101 | AzureDevOpsPullRequestIncompleteError
102 | AzureDevOpsReviewerNameError
103 | AzureDevOpsViewerUnavailableError;
104
105const REST_API_VERSION = "7.1";
106const PULL_REQUEST_LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
107/** A 2,000-file page exceeds the default 1 MiB output budget. */
108const CHANGE_ENTRIES_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
109/** JSON escaping and base64 can exceed the decoded file's size. */
110const ITEM_CONTENT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
111/** Review history is unpaged and independent of diff size. */
112const REVIEW_HISTORY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
113
114/** Azure's iteration-change page limit. */
115const CHANGE_ENTRIES_PER_PAGE = 2000;
116
117/** Count raw entries, including folders and malformed rows. */
118const MAX_CHANGE_ENTRIES = 10_000;
119
120export interface AzureDevOpsIterationChanges {
121 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
122 readonly truncated: boolean;
123}
124
125export class AzureDevOpsPullRequestCli extends Context.Service<
126 AzureDevOpsPullRequestCli,
127 {
128 readonly getViewer: (input: {
129 readonly cwd: string;
130 }) => Effect.Effect<string, AzureDevOpsPullRequestCliError>;
131
132 readonly listPullRequests: (input: {
133 readonly cwd: string;
134 readonly repository: string;
135 readonly state: PullRequestListState;
136 readonly involvement: PullRequestInvolvement;
137 readonly viewer: string;
138 readonly limit: number;
139 /** Matched by `--creator`, which takes the email a row shows as its login. */
140 readonly author?: string | undefined;
141 /**
142 * Where to carry on from. Azure has no date filter for a pull request listing, so the only
143 * part of a cursor it can use is how many rows have already been handed over.
144 */
145 readonly cursor?: ProviderListCursor | undefined;
146 }) => Effect.Effect<
147 {
148 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
149 readonly truncated: boolean;
150 readonly cursorAdvance: number;
151 },
152 AzureDevOpsPullRequestCliError
153 >;
154
155 readonly getPullRequest: (input: {
156 readonly cwd: string;
157 readonly number: number;
158 }) => Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError>;
159
160 readonly listThreads: (input: {
161 readonly cwd: string;
162 readonly location: AzureDevOpsRepositoryLocation;
163 readonly number: number;
164 }) => Effect.Effect<ReadonlyArray<PullRequestComment>, AzureDevOpsPullRequestCliError>;
165
166 readonly listIterations: (input: {
167 readonly cwd: string;
168 readonly location: AzureDevOpsRepositoryLocation;
169 readonly number: number;
170 }) => Effect.Effect<ReadonlyArray<AzureDevOpsIteration>, AzureDevOpsPullRequestCliError>;
171
172 /** Changes cover the whole PR from its merge base. */
173 readonly listIterationChanges: (input: {
174 readonly cwd: string;
175 readonly location: AzureDevOpsRepositoryLocation;
176 readonly number: number;
177 readonly iterationId: number;
178 }) => Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError>;
179
180 readonly readItemContent: (input: {
181 readonly cwd: string;
182 readonly location: AzureDevOpsRepositoryLocation;
183 readonly path: string;
184 readonly commit: string;
185 }) => Effect.Effect<AzureDevOpsItemContent, AzureDevOpsPullRequestCliError>;
186
187 readonly runPullRequestAction: (input: {
188 readonly cwd: string;
189 readonly number: number;
190 readonly action: PullRequestAction;
191 readonly mergeMethod?: PullRequestMergeMethod;
192 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
193
194 readonly updatePullRequest: (input: {
195 readonly cwd: string;
196 readonly number: number;
197 readonly title?: string | undefined;
198 readonly body?: string | undefined;
199 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
200
201 readonly setPullRequestReviewers: (input: {
202 readonly cwd: string;
203 readonly number: number;
204 readonly reviewers: ReadonlyArray<string>;
205 readonly requested: boolean;
206 }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
207 }
208>()("@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli") {}
209
210function statusArgs(state: PullRequestListState): ReadonlyArray<string> {
211 switch (state) {
212 case "open":
213 return ["--status", "active"];
214 case "merged":
215 return ["--status", "completed"];
216 case "closed":
217 return ["--status", "abandoned"];
218 case "all":
219 return ["--status", "all"];
220 }
221}
222
223function involvementArgs(input: {
224 readonly involvement: PullRequestInvolvement;
225 readonly viewer: string;
226}): ReadonlyArray<string> {
227 switch (input.involvement) {
228 case "authored":
229 return ["--creator", input.viewer];
230 case "reviewing":
231 return ["--reviewer", input.viewer];
232 case "all":
233 return [];
234 }
235}
236
237function actionArgs(
238 action: PullRequestAction,
239 mergeMethod: PullRequestMergeMethod | undefined,
240): ReadonlyArray<string> {
241 switch (action) {
242 case "merge":
243 return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
244 case "enable-auto-merge":
245 return [
246 "--auto-complete",
247 "true",
248 ...(mergeMethod === undefined
249 ? []
250 : ["--squash", mergeMethod === "squash" ? "true" : "false"]),
251 ];
252 case "disable-auto-merge":
253 return ["--auto-complete", "false"];
254 case "ready":
255 return ["--draft", "false"];
256 case "draft":
257 return ["--draft", "true"];
258 case "close":
259 return ["--status", "abandoned"];
260 case "update-branch":
261 return [];
262 case "reopen":
263 return ["--status", "active"];
264 case "revert":
265 case "approve-workflows":
266 case "delete-branch":
267 throw new Error(`Azure DevOps pull request action ${action} is unsupported`);
268 }
269}
270
271function isReviewerName(value: string): boolean {
272 const name = value.trim();
273 return name.length > 0 && !name.startsWith("-");
274}
275
276/** @public */
277export const make = Effect.gen(function* () {
278 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
279
280 // Let `az` parse all three remote formats.
281 const detectArgs = ["--detect", "true"] as const;
282
283 const executeJson = (input: {
284 readonly cwd: string;
285 readonly args: ReadonlyArray<string>;
286 readonly maxOutputBytes?: number;
287 }) =>
288 azure.execute({
289 cwd: input.cwd,
290 args: [...input.args, "--only-show-errors", "--output", "json"],
291 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
292 });
293
294 /** Use the extension's credentials; `az rest` uses the default tenant. */
295 const invoke = <A>(input: {
296 readonly cwd: string;
297 readonly operation: string;
298 readonly resource: string;
299 readonly routeParameters: ReadonlyArray<string>;
300 readonly queryParameters?: ReadonlyArray<string>;
301 readonly maxOutputBytes?: number;
302 readonly decode: (raw: string) => Result.Result<A, unknown>;
303 }): Effect.Effect<A, AzureDevOpsPullRequestCliError> =>
304 executeJson({
305 cwd: input.cwd,
306 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
307 args: [
308 "devops",
309 "invoke",
310 ...detectArgs,
311 "--area",
312 "git",
313 "--resource",
314 input.resource,
315 "--api-version",
316 REST_API_VERSION,
317 "--route-parameters",
318 ...input.routeParameters,
319 ...(input.queryParameters === undefined
320 ? []
321 : ["--query-parameters", ...input.queryParameters]),
322 ],
323 }).pipe(
324 Effect.flatMap((result) => {
325 const decoded = input.decode(result.stdout.trim());
326 return Result.isSuccess(decoded)
327 ? Effect.succeed(decoded.success)
328 : Effect.fail(
329 new AzureDevOpsPullRequestReadError({
330 command: "az",
331 cwd: input.cwd,
332 operation: input.operation,
333 cause: decoded.failure,
334 }),
335 );
336 }),
337 );
338
339 /** Azure's items route requires a leading slash. */
340 const toItemPath = (path: string) => (path.startsWith("/") ? path : `/${path}`);
341
342 const repositoryRoute = (location: AzureDevOpsRepositoryLocation): ReadonlyArray<string> => [
343 `project=${location.project}`,
344 `repositoryId=${location.repository}`,
345 ];
346
347 const pullRequestRoute = (input: {
348 readonly location: AzureDevOpsRepositoryLocation;
349 readonly number: number;
350 }): ReadonlyArray<string> => [
351 ...repositoryRoute(input.location),
352 `pullRequestId=${input.number}`,
353 ];
354
355 /** Decoding can shorten a non-final page; advance by raw rows. */
356 const listPullRequestPage = (input: {
357 readonly cwd: string;
358 readonly repository: string;
359 readonly state: PullRequestListState;
360 readonly involvement: PullRequestInvolvement;
361 readonly viewer: string;
362 readonly author?: string | undefined;
363 readonly limit: number;
364 readonly skip: number;
365 readonly cursorAdvance: number;
366 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
367 }): Effect.Effect<
368 {
369 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
370 readonly truncated: boolean;
371 readonly cursorAdvance: number;
372 },
373 AzureDevOpsPullRequestCliError
374 > => {
375 const remaining = input.limit - input.items.length;
376 const top = remaining + 1;
377 return executeJson({
378 cwd: input.cwd,
379 maxOutputBytes: PULL_REQUEST_LIST_MAX_OUTPUT_BYTES,
380 args: [
381 "repos",
382 "pr",
383 "list",
384 ...detectArgs,
385 "--repository",
386 input.repository,
387 ...statusArgs(input.state),
388 ...involvementArgs(input),
389 ...(input.author === undefined || input.involvement === "authored"
390 ? []
391 : ["--creator", input.author]),
392 "--include-links",
393 ...(input.skip === 0 ? [] : ["--skip", String(input.skip)]),
394 "--top",
395 String(top),
396 ],
397 }).pipe(
398 Effect.flatMap((result) => {
399 const raw = result.stdout.trim();
400 if (raw.length === 0) {
401 return Effect.succeed({
402 items: input.items,
403 truncated: false,
404 cursorAdvance: input.cursorAdvance,
405 });
406 }
407 const decoded = decodePullRequestListJson(raw);
408 if (!Result.isSuccess(decoded)) {
409 return Effect.fail(
410 new AzureDevOpsPullRequestReadError({
411 command: "az",
412 cwd: input.cwd,
413 operation: "listPullRequests",
414 cause: decoded.failure,
415 }),
416 );
417 }
418
419 const lastItemIndex = decoded.success.rawIndexes[remaining - 1];
420 if (lastItemIndex !== undefined) {
421 const consumed = lastItemIndex + 1;
422 return Effect.succeed({
423 items: [...input.items, ...decoded.success.items.slice(0, remaining)],
424 truncated: consumed < decoded.success.rawCount || decoded.success.rawCount === top,
425 cursorAdvance: input.cursorAdvance + consumed,
426 });
427 }
428
429 const items = [...input.items, ...decoded.success.items];
430 if (decoded.success.rawCount < top) {
431 return Effect.succeed({
432 items,
433 truncated: false,
434 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
435 });
436 }
437 return listPullRequestPage({
438 ...input,
439 skip: input.skip + decoded.success.rawCount,
440 cursorAdvance: input.cursorAdvance + decoded.success.rawCount,
441 items,
442 });
443 }),
444 );
445 };
446
447 return AzureDevOpsPullRequestCli.of({
448 getViewer: (input) =>
449 executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
450 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
451 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
452 if (!Result.isSuccess(decoded)) {
453 return Effect.fail(
454 new AzureDevOpsPullRequestReadError({
455 command: "az",
456 cwd: input.cwd,
457 operation: "getViewer",
458 cause: decoded.failure,
459 }),
460 );
461 }
462 return decoded.success === null
463 ? Effect.fail(new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }))
464 : Effect.succeed(decoded.success);
465 }),
466 // `az account show` cannot identify PAT logins; the extension resolves `--creator me`.
467 Effect.catchIf(
468 (error) => error._tag !== "AzureDevOpsCliUnavailableError",
469 () =>
470 executeJson({
471 cwd: input.cwd,
472 args: [
473 "repos",
474 "pr",
475 "list",
476 ...detectArgs,
477 "--creator",
478 "me",
479 "--status",
480 "all",
481 "--top",
482 "1",
483 ],
484 }).pipe(
485 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
486 const decoded = decodePullRequestListJson(result.stdout.trim() || "[]");
487 const login = Result.isSuccess(decoded)
488 ? decoded.success.items[0]?.author?.login
489 : undefined;
490 return login === undefined
491 ? Effect.fail(
492 new AzureDevOpsViewerUnavailableError({ command: "az", cwd: input.cwd }),
493 )
494 : Effect.succeed(login);
495 }),
496 ),
497 ),
498 ),
499
500 listPullRequests: (input) =>
501 listPullRequestPage({
502 cwd: input.cwd,
503 repository: input.repository,
504 state: input.state,
505 involvement: input.involvement,
506 viewer: input.viewer,
507 author: input.author,
508 limit: input.limit,
509 skip: input.cursor?.delivered ?? 0,
510 cursorAdvance: 0,
511 items: [],
512 }),
513
514 getPullRequest: (input) =>
515 executeJson({
516 cwd: input.cwd,
517 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
518 }).pipe(
519 Effect.flatMap(
520 (result): Effect.Effect<AzureDevOpsPullRequest, AzureDevOpsPullRequestCliError> => {
521 const decoded = decodePullRequestJson(result.stdout.trim());
522 if (!Result.isSuccess(decoded)) {
523 return Effect.fail(
524 new AzureDevOpsPullRequestReadError({
525 command: "az",
526 cwd: input.cwd,
527 operation: "getPullRequest",
528 cause: decoded.failure,
529 }),
530 );
531 }
532 return decoded.success === null
533 ? Effect.fail(
534 new AzureDevOpsPullRequestIncompleteError({
535 command: "az",
536 cwd: input.cwd,
537 number: input.number,
538 }),
539 )
540 : Effect.succeed(decoded.success);
541 },
542 ),
543 ),
544
545 listThreads: (input) =>
546 invoke({
547 cwd: input.cwd,
548 operation: "listThreads",
549 resource: "pullRequestThreads",
550 routeParameters: pullRequestRoute(input),
551 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
552 decode: decodeThreadsJson,
553 }),
554
555 listIterations: (input) =>
556 invoke({
557 cwd: input.cwd,
558 operation: "listIterations",
559 resource: "pullRequestIterations",
560 routeParameters: pullRequestRoute(input),
561 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
562 decode: decodeIterationsJson,
563 }),
564
565 listIterationChanges: (input) => {
566 const page = (skip: number) =>
567 invoke({
568 cwd: input.cwd,
569 operation: "listIterationChanges",
570 resource: "pullRequestIterationChanges",
571 routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
572 queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
573 maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
574 decode: decodeIterationChangesJson,
575 });
576 const from = (
577 skip: number,
578 collected: ReadonlyArray<AzureDevOpsChangeEntry>,
579 ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
580 page(skip).pipe(
581 Effect.flatMap((answer) => {
582 const changes = [...collected, ...answer.changes];
583 if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
584 return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
585 ? Effect.succeed({ changes, truncated: true })
586 : from(answer.nextSkip, changes);
587 }),
588 );
589 return from(0, []);
590 },
591
592 readItemContent: (input) =>
593 invoke({
594 cwd: input.cwd,
595 operation: "readItemContent",
596 resource: "items",
597 routeParameters: repositoryRoute(input.location),
598 queryParameters: [
599 `path=${toItemPath(input.path)}`,
600 "versionDescriptor.versionType=commit",
601 `versionDescriptor.version=${input.commit}`,
602 "includeContent=true",
603 // Encoded content cannot identify binaries; request Azure's binary flag.
604 "includeContentMetadata=true",
605 // `az devops invoke` requires JSON; otherwise Azure returns raw file bytes.
606 "$format=json",
607 ],
608 maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,
609 decode: decodeItemContentJson,
610 }),
611
612 setPullRequestReviewers: (input) =>
613 input.reviewers.some((reviewer) => !isReviewerName(reviewer))
614 ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
615 : azure
616 .execute({
617 cwd: input.cwd,
618 args: [
619 "repos",
620 "pr",
621 "reviewer",
622 input.requested ? "add" : "remove",
623 ...detectArgs,
624 "--id",
625 String(input.number),
626 // Repeating `--reviewers` replaces the earlier list.
627 "--reviewers",
628 ...input.reviewers,
629 "--only-show-errors",
630 "--output",
631 "json",
632 ],
633 })
634 .pipe(Effect.asVoid),
635
636 runPullRequestAction: (input) =>
637 azure
638 .execute({
639 cwd: input.cwd,
640 args: [
641 "repos",
642 "pr",
643 "update",
644 ...detectArgs,
645 "--id",
646 String(input.number),
647 ...actionArgs(input.action, input.mergeMethod),
648 "--only-show-errors",
649 "--output",
650 "json",
651 ],
652 })
653 .pipe(Effect.asVoid),
654
655 updatePullRequest: (input) =>
656 azure
657 .execute({
658 cwd: input.cwd,
659 args: [
660 "repos",
661 "pr",
662 "update",
663 ...detectArgs,
664 "--id",
665 String(input.number),
666 // One argv entry preserves leading dashes and multi-string descriptions.
667 ...(input.title === undefined ? [] : [`--title=${input.title}`]),
668 ...(input.body === undefined ? [] : [`--description=${input.body}`]),
669 "--only-show-errors",
670 "--output",
671 "json",
672 ],
673 })
674 .pipe(Effect.asVoid),
675 });
676});
677
678export const layer = Layer.effect(AzureDevOpsPullRequestCli, make);