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

azureDevOpsPullRequestJson.ts

372 lines13.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 {
16 azureDevOpsOrganizationBaseFromRestApiUrl,
17 azureDevOpsPullRequestWebUrl,
18} from "../sourceControl/azureDevOpsPullRequests.ts";
19​
20/**
21 * Azure's enums are decoded as plain strings and normalized here, in the same tolerant style as
22 * the other hosts: a new merge status must not fail a whole payload. Every field beyond the
23 * identity is optional, because `az repos pr` returns rather more or less of the REST object
24 * depending on the command.
25 */
26const RawIdentitySchema = Schema.Struct({
27 displayName: Schema.optional(Schema.NullOr(Schema.String)),
28 /** An email or UPN, which is what `az account show` reports for the signed-in user. */
29 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
30 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
31});
32​
33const RawPullRequestSchema = Schema.Struct({
34 pullRequestId: Schema.Int,
35 title: Schema.String,
36 description: Schema.optional(Schema.NullOr(Schema.String)),
37 status: Schema.optional(Schema.NullOr(Schema.String)),
38 isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
39 /**
40 * Who armed auto-complete, which is the only thing Azure says about it: the field carries an
41 * identity while the pull request is set to complete on its own, and Azure leaves it out
42 * entirely once nobody has. So its presence is the answer, and there is no third state.
43 */
44 autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
45 completionOptions: Schema.optional(
46 Schema.NullOr(
47 Schema.Struct({
48 mergeStrategy: Schema.optional(Schema.NullOr(Schema.String)),
49 squashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
50 }),
51 ),
52 ),
53 mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
54 createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
55 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
56 // Required, and required to be non-empty: the wire contract will not carry a change request
57 // without a branch or a created time, so a row missing one is skipped rather than breaking the
58 // response it travels in.
59 sourceRefName: TrimmedNonEmptyString,
60 targetRefName: TrimmedNonEmptyString,
61 creationDate: TrimmedNonEmptyString,
62 closedDate: Schema.optional(Schema.NullOr(Schema.String)),
63 url: Schema.optional(Schema.NullOr(Schema.String)),
64 repository: Schema.optional(
65 Schema.NullOr(
66 Schema.Struct({
67 name: Schema.optional(Schema.NullOr(Schema.String)),
68 webUrl: Schema.optional(Schema.NullOr(Schema.String)),
69 project: Schema.optional(
70 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
71 ),
72 }),
73 ),
74 ),
75 _links: Schema.optional(
76 Schema.NullOr(
77 Schema.Struct({
78 web: Schema.optional(
79 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
80 ),
81 }),
82 ),
83 ),
84});
85​
86/** A pull request thread, which is how Azure keeps its conversation. */
87const RawThreadSchema = Schema.Struct({
88 id: Schema.Int,
89 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
90 threadContext: Schema.optional(
91 Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
92 ),
93 comments: Schema.optional(
94 Schema.NullOr(
95 Schema.Array(
96 Schema.Struct({
97 id: Schema.optional(Schema.NullOr(Schema.Int)),
98 content: Schema.optional(Schema.NullOr(Schema.String)),
99 author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
100 publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
101 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
102 /** `system` marks the notes Azure writes itself, which are events, not comments. */
103 commentType: Schema.optional(Schema.NullOr(Schema.String)),
104 }),
105 ),
106 ),
107 ),
108});
109​
110const RawThreadPageSchema = Schema.Struct({
111 value: Schema.Array(Schema.Unknown),
112});
113​
114const RawViewerSchema = Schema.Struct({
115 user: Schema.optional(
116 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
117 ),
118});
119​
120export interface AzureDevOpsPullRequest {
121 readonly number: number;
122 readonly title: string;
123 readonly url: string;
124 readonly author: PullRequestActor | null;
125 readonly headBranch: string;
126 readonly baseBranch: string;
127 readonly state: PullRequestState;
128 readonly isDraft: boolean;
129 readonly mergeability: PullRequestMergeability;
130 readonly createdAt: string;
131 /**
132 * Azure records no last-touched time on a pull request, so the closing time stands in where
133 * there is one and the creation time otherwise. The same fallback the rest of the app uses.
134 */
135 readonly updatedAt: string;
136 readonly closedAt: string | null;
137 readonly body: string;
138 readonly reviewRequestLogins: ReadonlyArray<string>;
139 readonly reviewers: ReadonlyArray<PullRequestActor>;
140 /** Where this pull request's threads live, when Azure said enough to work it out. */
141 readonly threadsUrl: string | null;
142 /** Whether Azure is set to complete this on its own once its policies pass. */
143 readonly autoMergeEnabled: boolean;
144 /** The completion strategy Azure stored with auto-complete, where it reported one. */
145 readonly autoMergeMethod?: PullRequestMergeMethod;
147​
148function trimmed(value: string | null | undefined): string | null {
149 const text = value?.trim() ?? "";
150 return text.length > 0 ? text : null;
152​
153function normalizeRefName(refName: string): string {
154 return refName.trim().replace(/^refs\/heads\//, "");
156​
157/** A login has to compare against `az account show`, which reports an email. */
158function toActor(raw: Schema.Schema.Type<typeof RawIdentitySchema> | null | undefined) {
159 const login = trimmed(raw?.uniqueName) ?? trimmed(raw?.displayName);
160 return login === null
161 ? null
162 : { login, name: trimmed(raw?.displayName), avatarUrl: trimmed(raw?.imageUrl) };
164​
165function toState(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): PullRequestState {
166 switch (raw.status?.trim().toLowerCase()) {
167 case "completed":
168 return "merged";
169 case "abandoned":
170 return "closed";
171 default:
172 return "open";
173 }
175​
176function toMergeability(value: string | null | undefined): PullRequestMergeability {
177 switch (value?.trim().toLowerCase()) {
178 case "succeeded":
179 return "mergeable";
180 case "conflicts":
181 case "failure":
182 case "rejectedbypolicy":
183 return "conflicting";
184 default:
185 // `queued` and `notSet` mean Azure has not finished checking.
186 return "unknown";
187 }
189​
190/**
191 * The REST collection a pull request's threads hang from. Built from what Azure returned rather
192 * than from the local remote, whose shape differs between the modern, legacy and SSH forms.
193 */
194function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): string | null {
195 const base = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);
196 const project = trimmed(raw.repository?.project?.name);
197 const repository = trimmed(raw.repository?.name);
198 if (base === null || project === null || repository === null) return null;
199 return `${base}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repository)}/pullRequests/${raw.pullRequestId}/threads`;
201​
202function toAutoMergeMethod(
203 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
204): PullRequestMergeMethod | undefined {
205 if (raw.autoCompleteSetBy == null) return undefined;
206 switch (raw.completionOptions?.mergeStrategy?.trim().toLowerCase()) {
207 case "squash":
208 return "squash";
209 case "rebase":
210 case "rebasemerge":
211 return "rebase";
212 case "nofastforward":
213 return "merge";
214 default:
215 return raw.completionOptions?.squashMerge === true ? "squash" : undefined;
216 }
218​
219/**
220 * Null when Azure said too little to place the pull request: a row with no browser url and no
221 * branch left after its prefix is dropped cannot be rendered or opened, and the wire contract
222 * refuses to carry it either.
223 */
224function toPullRequest(
225 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
226): AzureDevOpsPullRequest | null {
227 const autoMergeMethod = toAutoMergeMethod(raw);
228 const reviewers = (raw.reviewers ?? []).flatMap((reviewer) => {
229 const actor = toActor(reviewer);
230 return actor === null ? [] : [actor];
231 });
232 const closedAt = trimmed(raw.closedDate);
233 const url = trimmed(
234 azureDevOpsPullRequestWebUrl({
235 pullRequestId: raw.pullRequestId,
236 webLink: raw._links?.web?.href,
237 repositoryWebUrl: raw.repository?.webUrl,
238 restApiUrl: raw.url,
239 projectName: raw.repository?.project?.name,
240 repositoryName: raw.repository?.name,
241 }),
242 );
243 const headBranch = trimmed(normalizeRefName(raw.sourceRefName));
244 const baseBranch = trimmed(normalizeRefName(raw.targetRefName));
245 if (url === null || headBranch === null || baseBranch === null) return null;
246 return {
247 number: raw.pullRequestId,
248 title: raw.title,
249 url,
250 author: toActor(raw.createdBy),
251 headBranch,
252 baseBranch,
253 state: toState(raw),
254 isDraft: raw.isDraft ?? false,
255 mergeability: toMergeability(raw.mergeStatus),
256 createdAt: raw.creationDate,
257 updatedAt: closedAt ?? raw.creationDate,
258 closedAt,
259 body: raw.description ?? "",
260 reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
261 reviewers,
262 threadsUrl: toThreadsUrl(raw),
263 autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
264 ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
265 };
267​
268const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
269const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
270const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
271const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
272const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
273const decodeViewer = decodeJsonResult(RawViewerSchema);
274​
275type DecodeFailure = Cause.Cause<Schema.SchemaError>;
276​
277export interface AzureDevOpsPullRequestBatch {
278 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
279 /** Zero-based positions of the decoded items in Azure's raw page. */
280 readonly rawIndexes: ReadonlyArray<number>;
281 /** Rows Azure returned, counted before decoding, so a skipped row cannot hide a next page. */
282 readonly rawCount: number;
284​
285/** Malformed entries are skipped rather than failing the batch, as on the other hosts. */
286export function decodePullRequestListJson(
287 raw: string,
288): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
289 const decoded = decodeUnknownList(raw);
290 if (!Result.isSuccess(decoded)) {
291 return Result.fail(decoded.failure);
292 }
293 const items: AzureDevOpsPullRequest[] = [];
294 const rawIndexes: number[] = [];
295 for (const [rawIndex, entry] of decoded.success.entries()) {
296 const item = decodePullRequestEntry(entry);
297 if (Exit.isFailure(item)) continue;
298 const pullRequest = toPullRequest(item.value);
299 if (pullRequest !== null) {
300 items.push(pullRequest);
301 rawIndexes.push(rawIndex);
302 }
303 }
304 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
306​
307/** Null carries "Azure answered, but with too little to use", which the caller reports. */
308export function decodePullRequestJson(
309 raw: string,
310): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
311 const decoded = decodePullRequest(raw);
312 return Result.isSuccess(decoded)
313 ? Result.succeed(toPullRequest(decoded.success))
314 : Result.fail(decoded.failure);
316​
317/** `az account show --query user` reports the signed-in account, whose name is an email. */
318export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
319 const decoded = decodeViewer(raw);
320 return Result.isSuccess(decoded)
321 ? Result.succeed(trimmed(decoded.success.user?.name))
322 : Result.fail(decoded.failure);
324​
325/**
326 * Azure keeps its conversation as threads of comments, and every one of them is a remark
327 * somebody wrote: a reply under a thread is as much of the conversation as the line that opened
328 * it. A thread pinned to a file is a line-level review comment.
329 *
330 * Azure answers the whole thread collection in one response, with no cursor and no page to
331 * follow, so what this returns is everything the host has.
332 */
333export function decodeThreadsJson(
334 raw: string,
335): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
336 const decoded = decodeThreadPage(raw);
337 if (!Result.isSuccess(decoded)) {
338 return Result.fail(decoded.failure);
339 }
340 const comments: PullRequestComment[] = [];
341 for (const entry of decoded.success.value) {
342 const decodedThread = decodeThreadEntry(entry);
343 if (Exit.isFailure(decodedThread)) continue;
344 const thread = decodedThread.value;
345 if (thread.isDeleted === true) continue;
346 const path = trimmed(thread.threadContext?.filePath);
347 for (const comment of thread.comments ?? []) {
348 const publishedDate = trimmed(comment.publishedDate);
349 if (
350 comment.isDeleted === true ||
351 comment.commentType?.trim().toLowerCase() === "system" ||
352 (comment.content ?? "").trim().length === 0 ||
353 publishedDate === null
354 ) {
355 continue;
356 }
357 comments.push({
358 id: `${thread.id}:${comment.id ?? 0}`,
359 kind: path === null ? "issue-comment" : "review-comment",
360 author: toActor(comment.author),
361 body: comment.content ?? "",
362 createdAt: publishedDate,
363 url: null,
364 path,
365 reviewState: null,
366 });
367 }
368 }
369 return Result.succeed(
370 comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
371 );