Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

azureDevOpsPullRequestJson.ts

507 lines17.8 KB

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/**
18 * Azure's enums are decoded as plain strings and normalized here, in the same tolerant style as
19 * the other hosts: a new merge status must not fail a whole payload. Every field beyond the
20 * identity is optional, because `az repos pr` returns rather more or less of the REST object
21 * depending on the command.
22 */
23const RawIdentitySchema = Schema.Struct({
24 displayName: Schema.optional(Schema.NullOr(Schema.String)),
25 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
26 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
27});
28​
29const RawPullRequestSchema = Schema.Struct({
30 pullRequestId: Schema.Int,
31 title: Schema.String,
32 description: Schema.optional(Schema.NullOr(Schema.String)),
33 status: Schema.optional(Schema.NullOr(Schema.String)),
34 isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
35 /**
36 * Who armed auto-complete, which is the only thing Azure says about it: the field carries an
37 * identity while the pull request is set to complete on its own, and Azure leaves it out
38 * entirely once nobody has. So its presence is the answer, and there is no third state.
39 */
40 autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
41 completionOptions: Schema.optional(
42 Schema.NullOr(
43 Schema.Struct({
44 mergeStrategy: Schema.optional(Schema.NullOr(Schema.String)),
45 squashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
46 }),
47 ),
48 ),
49 mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
50 createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
51 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
52 sourceRefName: TrimmedNonEmptyString,
53 targetRefName: TrimmedNonEmptyString,
54 creationDate: TrimmedNonEmptyString,
55 closedDate: Schema.optional(Schema.NullOr(Schema.String)),
56 url: Schema.optional(Schema.NullOr(Schema.String)),
57 repository: Schema.optional(
58 Schema.NullOr(
59 Schema.Struct({
60 name: Schema.optional(Schema.NullOr(Schema.String)),
61 webUrl: Schema.optional(Schema.NullOr(Schema.String)),
62 project: Schema.optional(
63 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
64 ),
65 }),
66 ),
67 ),
68 _links: Schema.optional(
69 Schema.NullOr(
70 Schema.Struct({
71 web: Schema.optional(
72 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
73 ),
74 }),
75 ),
76 ),
77});
78​
79const RawThreadSchema = Schema.Struct({
80 id: Schema.Int,
81 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
82 threadContext: Schema.optional(
83 Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
84 ),
85 comments: Schema.optional(
86 Schema.NullOr(
87 Schema.Array(
88 Schema.Struct({
89 id: Schema.optional(Schema.NullOr(Schema.Int)),
90 content: Schema.optional(Schema.NullOr(Schema.String)),
91 author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
92 publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
93 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
94 commentType: Schema.optional(Schema.NullOr(Schema.String)),
95 }),
96 ),
97 ),
98 ),
99});
100​
101const RawThreadPageSchema = Schema.Struct({
102 value: Schema.Array(Schema.Unknown),
103});
104​
105const RawViewerSchema = Schema.Struct({
106 user: Schema.optional(
107 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
108 ),
109});
110​
111export interface AzureDevOpsRepositoryLocation {
112 readonly project: string;
113 readonly repository: string;
115​
116export interface AzureDevOpsPullRequest {
117 readonly number: number;
118 readonly title: string;
119 readonly url: string;
120 readonly author: PullRequestActor | null;
121 readonly headBranch: string;
122 readonly baseBranch: string;
123 readonly state: PullRequestState;
124 readonly isDraft: boolean;
125 readonly mergeability: PullRequestMergeability;
126 readonly createdAt: string;
127 readonly updatedAt: string;
128 readonly closedAt: string | null;
129 readonly body: string;
130 readonly reviewRequestLogins: ReadonlyArray<string>;
131 readonly reviewers: ReadonlyArray<PullRequestActor>;
132 readonly location: AzureDevOpsRepositoryLocation | null;
133 readonly autoMergeEnabled: boolean;
134 readonly autoMergeMethod?: PullRequestMergeMethod;
136​
137function trimmed(value: string | null | undefined): string | null {
138 const text = value?.trim() ?? "";
139 return text.length > 0 ? text : null;
141​
142function normalizeRefName(refName: string): string {
143 return refName.trim().replace(/^refs\/heads\//, "");
145​
146/** A login has to compare against `az account show`, which reports an email. */
147function toActor(raw: Schema.Schema.Type<typeof RawIdentitySchema> | null | undefined) {
148 const login = trimmed(raw?.uniqueName) ?? trimmed(raw?.displayName);
149 return login === null
150 ? null
151 : { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) };
153​
154function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
155 switch (raw.status?.trim().toLowerCase()) {
156 case "completed":
157 return "merged";
158 case "abandoned":
159 return "closed";
160 default:
161 return "open";
162 }
164​
165function toMergeability(value: string | null | undefined): PullRequestMergeability {
166 switch (value?.trim().toLowerCase()) {
167 case "succeeded":
168 return "mergeable";
169 case "conflicts":
170 case "failure":
171 case "rejectedbypolicy":
172 return "conflicting";
173 default:
174 return "unknown";
175 }
177​
178function toLocation(
179 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
180): AzureDevOpsRepositoryLocation | null {
181 const project = trimmed(raw.repository?.project?.name);
182 const repository = trimmed(raw.repository?.name);
183 if (project === null || repository === null) return null;
184 return { project, repository };
186​
187function toAutoMergeMethod(
188 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
189): PullRequestMergeMethod | undefined {
190 if (raw.autoCompleteSetBy == null) return undefined;
191 switch (raw.completionOptions?.mergeStrategy?.trim().toLowerCase()) {
192 case "squash":
193 return "squash";
194 case "rebase":
195 case "rebasemerge":
196 return "rebase";
197 case "nofastforward":
198 return "merge";
199 default:
200 return raw.completionOptions?.squashMerge === true ? "squash" : undefined;
201 }
203​
204function toPullRequest(
205 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
206): AzureDevOpsPullRequest | null {
207 const autoMergeMethod = toAutoMergeMethod(raw);
208 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
209 const actor = toActor(reviewer);
210 return actor === null ? [] : [actor];
211 });
212 const closedAt = trimmed(raw.closedDate);
213 const url = trimmed(
214 azureDevOpsPullRequestWebUrl({
215 pullRequestId: raw.pullRequestId,
216 webLink: raw._links?.web?.href,
217 repositoryWebUrl: raw.repository?.webUrl,
218 restApiUrl: raw.url,
219 projectName: raw.repository?.project?.name,
220 repositoryName: raw.repository?.name,
221 }),
222 );
223 const headBranch = trimmed(normalizeRefName(raw.sourceRefName));
224 const baseBranch = trimmed(normalizeRefName(raw.targetRefName));
225 if (url === null || headBranch === null || baseBranch === null) return null;
226 return {
227 number: raw.pullRequestId,
228 title: raw.title,
229 url,
230 author: toActor(raw.createdBy),
231 headBranch,
232 baseBranch,
233 state: toState(raw),
234 isDraft: raw.isDraft ?? false,
235 mergeability: toMergeability(raw.mergeStatus),
236 createdAt: raw.creationDate,
237 updatedAt: closedAt ?? raw.creationDate,
238 closedAt,
239 body: raw.description ?? "",
240 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
241 reviewers,
242 location: toLocation(raw),
243 autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
244 ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
245 };
247​
248const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
249const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
250const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
251const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
252const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
253const decodeViewer = decodeJsonResult(RawViewerSchema);
254​
255type DecodeFailure = Cause.Cause<Schema.SchemaError>;
256​
257export interface AzureDevOpsPullRequestBatch {
258 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
259 readonly rawIndexes: ReadonlyArray<number>;
260 /** Rows Azure returned, counted before decoding, so a skipped row cannot hide a next page. */
261 readonly rawCount: number;
263​
264export function decodePullRequestListJson(
265 raw: string,
266): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
267 const decoded = decodeUnknownList(raw);
268 if (!Result.isSuccess(decoded)) {
269 return Result.fail(decoded.failure);
270 }
271 const items: AzureDevOpsPullRequest[] = [];
272 const rawIndexes: number[] = [];
273 for (const [rawIndex, entry] of decoded.success.entries()) {
274 const item = decodePullRequestEntry(entry);
275 if (Exit.isFailure(item)) continue;
276 const pullRequest = toPullRequest(item.value);
277 if (pullRequest !== null) {
278 items.push(pullRequest);
279 rawIndexes.push(rawIndex);
280 }
281 }
282 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
284​
285/** Null carries "Azure answered, but with too little to use", which the caller reports. */
286export function decodePullRequestJson(
287 raw: string,
288): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
289 const decoded = decodePullRequest(raw);
290 return Result.isSuccess(decoded)
291 ? Result.succeed(toPullRequest(decoded.success))
292 : Result.fail(decoded.failure);
294​
295export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
296 const decoded = decodeViewer(raw);
297 return Result.isSuccess(decoded)
298 ? Result.succeed(trimmed(decoded.success.user?.name))
299 : Result.fail(decoded.failure);
301​
302export function decodeThreadsJson(
303 raw: string,
304): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
305 const decoded = decodeThreadPage(raw);
306 if (!Result.isSuccess(decoded)) {
307 return Result.fail(decoded.failure);
308 }
309 const comments: PullRequestComment[] = [];
310 for (const entry of decoded.success.value) {
311 const decodedThread = decodeThreadEntry(entry);
312 if (Exit.isFailure(decodedThread)) continue;
313 const thread = decodedThread.value;
314 if (thread.isDeleted === true) continue;
315 const path = trimmed(thread.threadContext?.filePath);
316 for (const comment of thread.comments ?? []) {
317 const publishedDate = trimmed(comment.publishedDate);
318 if (
319 comment.isDeleted === true ||
320 comment.commentType?.trim().toLowerCase() === "system" ||
321 (comment.content ?? "").trim().length === 0 ||
322 publishedDate === null
323 ) {
324 continue;
325 }
326 comments.push({
327 id: `${thread.id}:${comment.id ?? 0}`,
328 kind: path === null ? "issue-comment" : "review-comment",
329 author: toActor(comment.author),
330 body: comment.content ?? "",
331 createdAt: publishedDate,
332 url: null,
333 path,
334 reviewState: null,
335 });
336 }
337 }
338 return Result.succeed(
339 comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
340 );
342​
343const RawIterationSchema = Schema.Struct({
344 id: Schema.Int,
345 sourceRefCommit: Schema.optional(
346 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
347 ),
348 commonRefCommit: Schema.optional(
349 Schema.NullOr(Schema.Struct({ commitId: Schema.optional(Schema.NullOr(Schema.String)) })),
350 ),
351});
352​
353const RawIterationPageSchema = Schema.Struct({ value: Schema.Array(Schema.Unknown) });
354​
355const RawChangeEntrySchema = Schema.Struct({
356 changeType: Schema.optional(Schema.NullOr(Schema.String)),
357 sourceServerItem: Schema.optional(Schema.NullOr(Schema.String)),
358 originalPath: Schema.optional(Schema.NullOr(Schema.String)),
359 item: Schema.optional(
360 Schema.NullOr(
361 Schema.Struct({
362 path: Schema.optional(Schema.NullOr(Schema.String)),
363 objectId: Schema.optional(Schema.NullOr(Schema.String)),
364 originalObjectId: Schema.optional(Schema.NullOr(Schema.String)),
365 isFolder: Schema.optional(Schema.NullOr(Schema.Boolean)),
366 gitObjectType: Schema.optional(Schema.NullOr(Schema.String)),
367 }),
368 ),
369 ),
370});
371​
372const RawChangePageSchema = Schema.Struct({
373 changeEntries: Schema.Array(Schema.Unknown),
374 nextSkip: Schema.optional(Schema.NullOr(Schema.Number)),
375});
376​
377const RawItemContentSchema = Schema.Struct({
378 content: Schema.optional(Schema.NullOr(Schema.String)),
379 contentMetadata: Schema.optional(
380 Schema.NullOr(Schema.Struct({ isBinary: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
381 ),
382});
383​
384export interface AzureDevOpsIteration {
385 readonly id: number;
386 readonly headCommit: string;
387 readonly mergeBaseCommit: string;
389​
390export interface AzureDevOpsChangeEntry {
391 readonly path: string;
392 readonly oldPath: string;
393 readonly changeKind: "new" | "deleted" | "change" | "rename-pure" | "rename-changed";
394 readonly objectId: string | null;
395 readonly originalObjectId: string | null;
397​
398export interface AzureDevOpsChangePage {
399 readonly changes: ReadonlyArray<AzureDevOpsChangeEntry>;
400 readonly nextSkip: number | null;
402​
403export interface AzureDevOpsItemContent {
404 readonly contents: string;
405 readonly isBinary: boolean;
407​
408const decodeIterationPage = decodeJsonResult(RawIterationPageSchema);
409const decodeIterationEntry = Schema.decodeUnknownExit(RawIterationSchema);
410const decodeChangePage = decodeJsonResult(RawChangePageSchema);
411const decodeChangeEntry = Schema.decodeUnknownExit(RawChangeEntrySchema);
412const decodeItemContent = decodeJsonResult(RawItemContentSchema);
413​
414/**
415 * Azure leads a path with a slash that every other host and every patch omits. Not trimmed like
416 * the rest of this payload, since a leading/trailing space is a legal part of a file's name and
417 * the patch and viewed mark are keyed by the untrimmed path.
418 */
419function toRepositoryPath(value: string | null | undefined): string | null {
420 if (value === undefined || value === null) return null;
421 const path = value.replace(/^\/+/, "");
422 return path.length === 0 ? null : path;
424​
425function toChangeKind(
426 raw: string | null | undefined,
427 renamed: boolean,
428): AzureDevOpsChangeEntry["changeKind"] {
429 const parts = new Set(
430 (raw ?? "")
431 .toLowerCase()
432 .split(",")
433 .map((part) => part.trim())
434 .filter((part) => part.length > 0),
435 );
436 if (parts.has("delete")) return "deleted";
437 if (renamed || parts.has("rename")) return parts.has("edit") ? "rename-changed" : "rename-pure";
438 if (parts.has("add")) return "new";
439 return "change";
441​
442export function decodeIterationsJson(
443 raw: string,
444): Result.Result<ReadonlyArray<AzureDevOpsIteration>, DecodeFailure> {
445 const decoded = decodeIterationPage(raw);
446 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
447 const iterations: AzureDevOpsIteration[] = [];
448 for (const entry of decoded.success.value) {
449 const decodedIteration = decodeIterationEntry(entry);
450 if (Exit.isFailure(decodedIteration)) continue;
451 const iteration = decodedIteration.value;
452 const headCommit = trimmed(iteration.sourceRefCommit?.commitId);
453 const mergeBaseCommit = trimmed(iteration.commonRefCommit?.commitId);
454 if (headCommit === null || mergeBaseCommit === null) continue;
455 iterations.push({ id: iteration.id, headCommit, mergeBaseCommit });
456 }
457 return Result.succeed(iterations.toSorted((left, right) => left.id - right.id));
459​
460export function decodeIterationChangesJson(
461 raw: string,
462): Result.Result<AzureDevOpsChangePage, DecodeFailure> {
463 const decoded = decodeChangePage(raw);
464 if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
465 const changes: AzureDevOpsChangeEntry[] = [];
466 for (const entry of decoded.success.changeEntries) {
467 const decodedChange = decodeChangeEntry(entry);
468 if (Exit.isFailure(decodedChange)) continue;
469 const change = decodedChange.value;
470 const path = toRepositoryPath(change.item?.path);
471 if (path === null) continue;
472 if (change.item?.isFolder === true) continue;
473 if ((change.item?.gitObjectType ?? "blob").toLowerCase() !== "blob") continue;
474 // Azure names where a renamed file came from in either of two places depending on the route
475 // and the version, so both are read and the current path stands in when neither is there.
476 const oldPath =
477 toRepositoryPath(change.sourceServerItem) ?? toRepositoryPath(change.originalPath) ?? path;
478 changes.push({
479 path,
480 oldPath,
481 changeKind: toChangeKind(change.changeType, oldPath !== path),
482 objectId: trimmed(change.item?.objectId),
483 originalObjectId: trimmed(change.item?.originalObjectId),
484 });
485 }
486 const nextSkip = decoded.success.nextSkip ?? null;
487 return Result.succeed({
488 changes,
489 nextSkip: nextSkip !== null && Number.isSafeInteger(nextSkip) && nextSkip > 0 ? nextSkip : null,
490 });
492​
493/**
494 * Azure answers an absent file with an empty body rather than an error, which reads as empty.
495 * Whether the bytes are text is Azure's own call, not this decoder's to guess from content.
496 */
497export function decodeItemContentJson(
498 raw: string,
499): Result.Result<AzureDevOpsItemContent, DecodeFailure> {
500 const decoded = decodeItemContent(raw);
501 return Result.isSuccess(decoded)
502 ? Result.succeed({
503 contents: decoded.success.content ?? "",
504 isBinary: decoded.success.contentMetadata?.isBinary === true,
505 })
506 : Result.fail(decoded.failure);