Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import type {
6 PullRequestActor,
7 PullRequestComment,
8 PullRequestMergeMethod,
9 PullRequestMergeability,
10 PullRequestState,
11} from "@t3tools/contracts";
12import { TrimmedNonEmptyString } from "@t3tools/contracts";
13import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14
15import { azureDevOpsPullRequestWebUrl } from "./azureDevOpsPullRequests.ts";
16
17// CLI fields vary by command; unknown enum values must not fail the payload.
18const RawIdentitySchema = Schema.Struct({
19 displayName: Schema.optional(Schema.NullOr(Schema.String)),
20 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
21 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
22});
23
24const RawPullRequestSchema = Schema.Struct({
25 pullRequestId: Schema.Int,
26 title: Schema.String,
27 description: Schema.optional(Schema.NullOr(Schema.String)),
28 status: Schema.optional(Schema.NullOr(Schema.String)),
29 isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
30 /** This identity's presence indicates auto-complete. */
31 autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
32 completionOptions: Schema.optional(
33 Schema.NullOr(
34 Schema.Struct({
35 mergeStrategy: Schema.optional(Schema.NullOr(Schema.String)),
36 squashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
37 }),
38 ),
39 ),
40 mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
41 createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
42 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
43 sourceRefName: TrimmedNonEmptyString,
44 targetRefName: TrimmedNonEmptyString,
45 creationDate: TrimmedNonEmptyString,
46 closedDate: Schema.optional(Schema.NullOr(Schema.String)),
47 url: Schema.optional(Schema.NullOr(Schema.String)),
48 repository: Schema.optional(
49 Schema.NullOr(
50 Schema.Struct({
51 name: Schema.optional(Schema.NullOr(Schema.String)),
52 webUrl: Schema.optional(Schema.NullOr(Schema.String)),
53 project: Schema.optional(
54 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
55 ),
56 }),
57 ),
58 ),
59 _links: Schema.optional(
60 Schema.NullOr(
61 Schema.Struct({
62 web: Schema.optional(
63 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
64 ),
65 }),
66 ),
67 ),
68});
69
70const RawThreadSchema = Schema.Struct({
71 id: Schema.Int,
72 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
73 threadContext: Schema.optional(
74 Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
75 ),
76 comments: Schema.optional(
77 Schema.NullOr(
78 Schema.Array(
79 Schema.Struct({
80 id: Schema.optional(Schema.NullOr(Schema.Int)),
81 content: Schema.optional(Schema.NullOr(Schema.String)),
82 author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
83 publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
84 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
85 commentType: Schema.optional(Schema.NullOr(Schema.String)),
86 }),
87 ),
88 ),
89 ),
90});
91
92const RawThreadPageSchema = Schema.Struct({
93 value: Schema.Array(Schema.Unknown),
94});
95
96const RawViewerSchema = Schema.Struct({
97 user: Schema.optional(
98 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
99 ),
100});
101
102export interface AzureDevOpsRepositoryLocation {
103 readonly project: string;
104 readonly repository: string;
105}
106
107export interface AzureDevOpsPullRequest {
108 readonly number: number;
109 readonly title: string;
110 readonly url: string;
111 readonly author: PullRequestActor | null;
112 readonly headBranch: string;
113 readonly baseBranch: string;
114 readonly state: PullRequestState;
115 readonly isDraft: boolean;
116 readonly mergeability: PullRequestMergeability;
117 readonly createdAt: string;
118 readonly updatedAt: string;
119 readonly closedAt: string | null;
120 readonly body: string;
121 readonly reviewRequestLogins: ReadonlyArray<string>;
122 readonly reviewers: ReadonlyArray<PullRequestActor>;
123 readonly location: AzureDevOpsRepositoryLocation | null;
124 readonly autoMergeEnabled: boolean;
125 readonly autoMergeMethod?: PullRequestMergeMethod;
126}
127
128function trimmed(value: string | null | undefined): string | null {
129 const text = value?.trim() ?? "";
130 return text.length > 0 ? text : null;
131}
132
133function normalizeRefName(refName: string): string {
134 return refName.trim().replace(/^refs\/heads\//, "");
135}
136
137/** Logins must match the email from `az account show`. */
138function toActor(raw: Schema.Schema.Type<typeof RawIdentitySchema> | null | undefined) {
139 const login = trimmed(raw?.uniqueName) ?? trimmed(raw?.displayName);
140 return login === null
141 ? null
142 : { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) };
143}
144
145function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
146 switch (raw.status?.trim().toLowerCase()) {
147 case "completed":
148 return "merged";
149 case "abandoned":
150 return "closed";
151 default:
152 return "open";
153 }
154}
155
156function toMergeability(value: string | null | undefined): PullRequestMergeability {
157 switch (value?.trim().toLowerCase()) {
158 case "succeeded":
159 return "mergeable";
160 case "conflicts":
161 case "failure":
162 case "rejectedbypolicy":
163 return "conflicting";
164 default:
165 return "unknown";
166 }
167}
168
169function toLocation(
170 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
171): AzureDevOpsRepositoryLocation | null {
172 const project = trimmed(raw.repository?.project?.name);
173 const repository = trimmed(raw.repository?.name);
174 if (project === null || repository === null) return null;
175 return { project, repository };
176}
177
178function toAutoMergeMethod(
179 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
180): PullRequestMergeMethod | undefined {
181 if (raw.autoCompleteSetBy == null) return undefined;
182 switch (raw.completionOptions?.mergeStrategy?.trim().toLowerCase()) {
183 case "squash":
184 return "squash";
185 case "rebase":
186 case "rebasemerge":
187 return "rebase";
188 case "nofastforward":
189 return "merge";
190 default:
191 return raw.completionOptions?.squashMerge === true ? "squash" : undefined;
192 }
193}
194
195function toPullRequest(
196 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
197): AzureDevOpsPullRequest | null {
198 const autoMergeMethod = toAutoMergeMethod(raw);
199 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
200 const actor = toActor(reviewer);
201 return actor === null ? [] : [actor];
202 });
203 const closedAt = trimmed(raw.closedDate);
204 const url = trimmed(
205 azureDevOpsPullRequestWebUrl({
206 pullRequestId: raw.pullRequestId,
207 webLink: raw._links?.web?.href,
208 repositoryWebUrl: raw.repository?.webUrl,
209 restApiUrl: raw.url,
210 projectName: raw.repository?.project?.name,
211 repositoryName: raw.repository?.name,
212 }),
213 );
214 const headBranch = trimmed(normalizeRefName(raw.sourceRefName));
215 const baseBranch = trimmed(normalizeRefName(raw.targetRefName));
216 if (url === null || headBranch === null || baseBranch === null) return null;
217 return {
218 number: raw.pullRequestId,
219 title: raw.title,
220 url,
221 author: toActor(raw.createdBy),
222 headBranch,
223 baseBranch,
224 state: toState(raw),
225 isDraft: raw.isDraft ?? false,
226 mergeability: toMergeability(raw.mergeStatus),
227 createdAt: raw.creationDate,
228 updatedAt: closedAt ?? raw.creationDate,
229 closedAt,
230 body: raw.description ?? "",
231 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
232 reviewers,
233 location: toLocation(raw),
234 autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
235 ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
236 };
237}
238
239const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
240const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
241const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
242const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
243const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
244const decodeViewer = decodeJsonResult(RawViewerSchema);
245
246type DecodeFailure = Cause.Cause<Schema.SchemaError>;
247
248export interface AzureDevOpsPullRequestBatch {
249 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
250 readonly rawIndexes: ReadonlyArray<number>;
251 /** Count before decoding to avoid ending pagination on skipped rows. */
252 readonly rawCount: number;
253}
254
255export function decodePullRequestListJson(
256 raw: string,
257): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
258 const decoded = decodeUnknownList(raw);
259 if (!Result.isSuccess(decoded)) {
260 return Result.fail(decoded.failure);
261 }
262 const items: AzureDevOpsPullRequest[] = [];
263 const rawIndexes: number[] = [];
264 for (const [rawIndex, entry] of decoded.success.entries()) {
265 const item = decodePullRequestEntry(entry);
266 if (Exit.isFailure(item)) continue;
267 const pullRequest = toPullRequest(item.value);
268 if (pullRequest !== null) {
269 items.push(pullRequest);
270 rawIndexes.push(rawIndex);
271 }
272 }
273 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
274}
275
276/** Null means Azure returned insufficient data. */
277export function decodePullRequestJson(
278 raw: string,
279): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
280 const decoded = decodePullRequest(raw);
281 return Result.isSuccess(decoded)
282 ? Result.succeed(toPullRequest(decoded.success))
283 : Result.fail(decoded.failure);
284}
285
286export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
287 const decoded = decodeViewer(raw);
288 return Result.isSuccess(decoded)
289 ? Result.succeed(trimmed(decoded.success.user?.name))
290 : Result.fail(decoded.failure);
291}
292
293export function decodeThreadsJson(
294 raw: string,
295): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
296 const decoded = decodeThreadPage(raw);
297 if (!Result.isSuccess(decoded)) {
298 return Result.fail(decoded.failure);
299 }
300 const comments: PullRequestComment[] = [];
301 for (const entry of decoded.success.value) {
302 const decodedThread = decodeThreadEntry(entry);
303 if (Exit.isFailure(decodedThread)) continue;
304 const thread = decodedThread.value;
305 if (thread.isDeleted === true) continue;
306 const path = trimmed(thread.threadContext?.filePath);
307 for (const comment of thread.comments ?? []) {
308 const publishedDate = trimmed(comment.publishedDate);
309 if (
310 comment.isDeleted === true ||
311 comment.commentType?.trim().toLowerCase() === "system" ||
312 (comment.content ?? "").trim().length === 0 ||
313 publishedDate === null
314 ) {
315 continue;
316 }
317 comments.push({
318 id: `${thread.id}:${comment.id ?? 0}`,
319 kind: path === null ? "issue-comment" : "review-comment",
320 author: toActor(comment.author),
321 body: comment.content ?? "",
322 createdAt: publishedDate,
323 url: null,
324 path,
325 reviewState: null,
326 });
327 }
328 }
329 return Result.succeed(
330 comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
331 );
332}
333
334const RawIterationSchema = Schema.Struct({
335 id: Schema.Int,
336 sourceRefCommit: Schema.optional(
337 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
338 ),
339 commonRefCommit: Schema.optional(
340 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
341 ),
342});
343
344const RawIterationPageSchema = Schema.Struct({ value: Schema.Array(Schema.Unknown) });
345
346const RawChangeEntrySchema = Schema.Struct({
347 changeType: Schema.optional(Schema.NullOr(Schema.String)),
348 sourceServerItem: Schema.optional(Schema.NullOr(Schema.String)),
349 originalPath: Schema.optional(Schema.NullOr(Schema.String)),
350 item: Schema.optional(
351 Schema.NullOr(
352 Schema.Struct({
353 path: Schema.optional(Schema.NullOr(Schema.String)),
354 objectId: Schema.optional(Schema.NullOr(Schema.String)),
355 originalObjectId: Schema.optional(Schema.NullOr(Schema.String)),
356 isFolder: Schema.optional(Schema.NullOr(Schema.Boolean)),
357 gitObjectType: Schema.optional(Schema.NullOr(Schema.String)),
358 }),
359 ),
360 ),
361});
362
363const RawChangePageSchema = Schema.Struct({
364 changeEntries: Schema.Array(Schema.Unknown),
365 nextSkip: Schema.optional(Schema.NullOr(Schema.Number)),
366});
367
368const RawItemContentSchema = Schema.Struct({
369 content: Schema.optional(Schema.NullOr(Schema.String)),
370 contentMetadata: Schema.optional(
371 Schema.NullOr(Schema.Struct({ isBinary: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
372 ),
373});
374
375export interface AzureDevOpsIteration {
376 readonly id: number;
377 readonly headCommit: string;
378 readonly mergeBaseCommit: string;
379}
380
381export interface AzureDevOpsChangeEntry {
382 readonly path: string;
383 readonly oldPath: string;
384 readonly changeKind: "new" | "deleted" | "change" | "rename-pure" | "rename-changed";
385 readonly objectId: string | null;
386 readonly originalObjectId: string | null;
387}
388
389export interface AzureDevOpsChangePage {
390 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
391 readonly nextSkip: number | null;
392}
393
394export interface AzureDevOpsItemContent {
395 readonly contents: string;
396 readonly isBinary: boolean;
397}
398
399const decodeIterationPage = decodeJsonResult(RawIterationPageSchema);
400const decodeIterationEntry = Schema.decodeUnknownExit(RawIterationSchema);
401const decodeChangePage = decodeJsonResult(RawChangePageSchema);
402const decodeChangeEntry = Schema.decodeUnknownExit(RawChangeEntrySchema);
403const decodeItemContent = decodeJsonResult(RawItemContentSchema);
404
405/** Preserve whitespace to match patch paths and viewed marks. */
406function toRepositoryPath(value: string | null | undefined): string | null {
407 if (value === undefined || value === null) return null;
408 const path = value.replace(/^\/+/, "");
409 return path.length === 0 ? null : path;
410}
411
412function toChangeKind(
413 raw: string | null | undefined,
414 renamed: boolean,
415): AzureDevOpsChangeEntry["changeKind"] {
416 const parts = new Set(
417 (raw ?? "")
418 .toLowerCase()
419 .split(",")
420 .map((part) => part.trim())
421 .filter((part) => part.length > 0),
422 );
423 if (parts.has("delete")) return "deleted";
424 if (renamed || parts.has("rename")) return parts.has("edit") ? "rename-changed" : "rename-pure";
425 if (parts.has("add")) return "new";
426 return "change";
427}
428
429export function decodeIterationsJson(
430 raw: string,
431): Result.Result<ReadonlyArray<AzureDevOpsIteration>, DecodeFailure> {
432 const decoded = decodeIterationPage(raw);
433 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
434 const iterations: AzureDevOpsIteration[] = [];
435 for (const entry of decoded.success.value) {
436 const decodedIteration = decodeIterationEntry(entry);
437 if (Exit.isFailure(decodedIteration)) continue;
438 const iteration = decodedIteration.value;
439 const headCommit = trimmed(iteration.sourceRefCommit?.commitId);
440 const mergeBaseCommit = trimmed(iteration.commonRefCommit?.commitId);
441 if (headCommit === null || mergeBaseCommit === null) continue;
442 iterations.push({ id: iteration.id, headCommit, mergeBaseCommit });
443 }
444 return Result.succeed(iterations.toSorted((left, right) => left.id - right.id));
445}
446
447export function decodeIterationChangesJson(
448 raw: string,
449): Result.Result<AzureDevOpsChangePage, DecodeFailure> {
450 const decoded = decodeChangePage(raw);
451 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
452 const changes: AzureDevOpsChangeEntry[] = [];
453 for (const entry of decoded.success.changeEntries) {
454 const decodedChange = decodeChangeEntry(entry);
455 if (Exit.isFailure(decodedChange)) continue;
456 const change = decodedChange.value;
457 const path = toRepositoryPath(change.item?.path);
458 if (path === null) continue;
459 if (change.item?.isFolder === true) continue;
460 if ((change.item?.gitObjectType ?? "blob").toLowerCase() !== "blob") continue;
461 // Azure uses either field for renames, depending on route/version.
462 const oldPath =
463 toRepositoryPath(change.sourceServerItem) ?? toRepositoryPath(change.originalPath) ?? path;
464 changes.push({
465 path,
466 oldPath,
467 changeKind: toChangeKind(change.changeType, oldPath !== path),
468 objectId: trimmed(change.item?.objectId),
469 originalObjectId: trimmed(change.item?.originalObjectId),
470 });
471 }
472 const nextSkip = decoded.success.nextSkip ?? null;
473 return Result.succeed({
474 changes,
475 nextSkip: nextSkip !== null && Number.isSafeInteger(nextSkip) && nextSkip > 0 ? nextSkip : null,
476 });
477}
478
479/** Azure returns an empty body for absent files. Binary status comes from its metadata. */
480export function decodeItemContentJson(
481 raw: string,
482): Result.Result<AzureDevOpsItemContent, DecodeFailure> {
483 const decoded = decodeItemContent(raw);
484 return Result.isSuccess(decoded)
485 ? Result.succeed({
486 contents: decoded.success.content ?? "",
487 isBinary: decoded.success.contentMetadata?.isBinary === true,
488 })
489 : Result.fail(decoded.failure);
490}