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

azureDevOpsPullRequestJson.ts

342 lines12.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 PullRequestMergeability,
9 PullRequestState,
10} from "@t3tools/contracts";
11import { TrimmedNonEmptyString } from "@t3tools/contracts";
12import { decodeJsonResult } from "@t3tools/shared/schemaJson";
13​
14import {
15 azureDevOpsOrganizationBaseFromRestApiUrl,
16 azureDevOpsPullRequestWebUrl,
17} from "../sourceControl/azureDevOpsPullRequests.ts";
18​
19/**
20 * Azure's enums are decoded as plain strings and normalized here, in the same tolerant style as
21 * the other hosts: a new merge status must not fail a whole payload. Every field beyond the
22 * identity is optional, because `az repos pr` returns rather more or less of the REST object
23 * depending on the command.
24 */
25const RawIdentitySchema = Schema.Struct({
26 displayName: Schema.optional(Schema.NullOr(Schema.String)),
27 /** An email or UPN, which is what `az account show` reports for the signed-in user. */
28 uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
29 imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
30});
31​
32const RawPullRequestSchema = Schema.Struct({
33 pullRequestId: Schema.Int,
34 title: Schema.String,
35 description: Schema.optional(Schema.NullOr(Schema.String)),
36 status: Schema.optional(Schema.NullOr(Schema.String)),
37 isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
38 /**
39 * Who armed auto-complete, which is the only thing Azure says about it: the field carries an
40 * identity while the pull request is set to complete on its own, and Azure leaves it out
41 * entirely once nobody has. So its presence is the answer, and there is no third state.
42 */
43 autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
44 mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
45 createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
46 reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
47 // Required, and required to be non-empty: the wire contract will not carry a change request
48 // without a branch or a created time, so a row missing one is skipped rather than breaking the
49 // response it travels in.
50 sourceRefName: TrimmedNonEmptyString,
51 targetRefName: TrimmedNonEmptyString,
52 creationDate: TrimmedNonEmptyString,
53 closedDate: Schema.optional(Schema.NullOr(Schema.String)),
54 url: Schema.optional(Schema.NullOr(Schema.String)),
55 repository: Schema.optional(
56 Schema.NullOr(
57 Schema.Struct({
58 name: Schema.optional(Schema.NullOr(Schema.String)),
59 webUrl: Schema.optional(Schema.NullOr(Schema.String)),
60 project: Schema.optional(
61 Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)) })),
62 ),
63 }),
64 ),
65 ),
66 _links: Schema.optional(
67 Schema.NullOr(
68 Schema.Struct({
69 web: Schema.optional(
70 Schema.NullOr(Schema.Struct({ href: Schema.optional(Schema.String) })),
71 ),
72 }),
73 ),
74 ),
75});
76​
77/** A pull request thread, which is how Azure keeps its conversation. */
78const RawThreadSchema = Schema.Struct({
79 id: Schema.Int,
80 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
81 threadContext: Schema.optional(
82 Schema.NullOr(Schema.Struct({ filePath: Schema.optional(Schema.NullOr(Schema.String)) })),
83 ),
84 comments: Schema.optional(
85 Schema.NullOr(
86 Schema.Array(
87 Schema.Struct({
88 id: Schema.optional(Schema.NullOr(Schema.Int)),
89 content: Schema.optional(Schema.NullOr(Schema.String)),
90 author: Schema.optional(Schema.NullOr(RawIdentitySchema)),
91 publishedDate: Schema.optional(Schema.NullOr(Schema.String)),
92 isDeleted: Schema.optional(Schema.NullOr(Schema.Boolean)),
93 /** `system` marks the notes Azure writes itself, which are events, not comments. */
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 AzureDevOpsPullRequest {
112 readonly number: number;
113 readonly title: string;
114 readonly url: string;
115 readonly author: PullRequestActor | null;
116 readonly headBranch: string;
117 readonly baseBranch: string;
118 readonly state: PullRequestState;
119 readonly isDraft: boolean;
120 readonly mergeability: PullRequestMergeability;
121 readonly createdAt: string;
122 /**
123 * Azure records no last-touched time on a pull request, so the closing time stands in where
124 * there is one and the creation time otherwise. The same fallback the rest of the app uses.
125 */
126 readonly updatedAt: string;
127 readonly closedAt: string | null;
128 readonly body: string;
129 readonly reviewRequestLogins: ReadonlyArray<string>;
130 readonly reviewers: ReadonlyArray<PullRequestActor>;
131 /** Where this pull request's threads live, when Azure said enough to work it out. */
132 readonly threadsUrl: string | null;
133 /** Whether Azure is set to complete this on its own once its policies pass. */
134 readonly autoMergeEnabled: boolean;
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 // `queued` and `notSet` mean Azure has not finished checking.
175 return "unknown";
176 }
178​
179/**
180 * The REST collection a pull request's threads hang from. Built from what Azure returned rather
181 * than from the local remote, whose shape differs between the modern, legacy and SSH forms.
182 */
183function toThreadsUrl(raw: Schema.Schema.Type<typeof RawPullRequestSchema>): string | null {
184 const base = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);
185 const project = trimmed(raw.repository?.project?.name);
186 const repository = trimmed(raw.repository?.name);
187 if (base === null || project === null || repository === null) return null;
188 return `${base}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repository)}/pullRequests/${raw.pullRequestId}/threads`;
190​
191/**
192 * Null when Azure said too little to place the pull request: a row with no browser url and no
193 * branch left after its prefix is dropped cannot be rendered or opened, and the wire contract
194 * refuses to carry it either.
195 */
196function toPullRequest(
197 raw: Schema.Schema.Type<typeof RawPullRequestSchema>,
198): AzureDevOpsPullRequest | null {
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 threadsUrl: toThreadsUrl(raw),
234 autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
235 };
237​
238const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
239const decodePullRequestEntry = Schema.decodeUnknownExit(RawPullRequestSchema);
240const decodePullRequest = decodeJsonResult(RawPullRequestSchema);
241const decodeThreadPage = decodeJsonResult(RawThreadPageSchema);
242const decodeThreadEntry = Schema.decodeUnknownExit(RawThreadSchema);
243const decodeViewer = decodeJsonResult(RawViewerSchema);
244​
245type DecodeFailure = Cause.Cause<Schema.SchemaError>;
246​
247export interface AzureDevOpsPullRequestBatch {
248 readonly items: ReadonlyArray<AzureDevOpsPullRequest>;
249 /** Zero-based positions of the decoded items in Azure's raw page. */
250 readonly rawIndexes: ReadonlyArray<number>;
251 /** Rows Azure returned, counted before decoding, so a skipped row cannot hide a next page. */
252 readonly rawCount: number;
254​
255/** Malformed entries are skipped rather than failing the batch, as on the other hosts. */
256export function decodePullRequestListJson(
257 raw: string,
258): Result.Result<AzureDevOpsPullRequestBatch, DecodeFailure> {
259 const decoded = decodeUnknownList(raw);
260 if (!Result.isSuccess(decoded)) {
261 return Result.fail(decoded.failure);
262 }
263 const items: AzureDevOpsPullRequest[] = [];
264 const rawIndexes: number[] = [];
265 for (const [rawIndex, entry] of decoded.success.entries()) {
266 const item = decodePullRequestEntry(entry);
267 if (Exit.isFailure(item)) continue;
268 const pullRequest = toPullRequest(item.value);
269 if (pullRequest !== null) {
270 items.push(pullRequest);
271 rawIndexes.push(rawIndex);
272 }
273 }
274 return Result.succeed({ items, rawIndexes, rawCount: decoded.success.length });
276​
277/** Null carries "Azure answered, but with too little to use", which the caller reports. */
278export function decodePullRequestJson(
279 raw: string,
280): Result.Result<AzureDevOpsPullRequest | null, DecodeFailure> {
281 const decoded = decodePullRequest(raw);
282 return Result.isSuccess(decoded)
283 ? Result.succeed(toPullRequest(decoded.success))
284 : Result.fail(decoded.failure);
286​
287/** `az account show --query user` reports the signed-in account, whose name is an email. */
288export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
289 const decoded = decodeViewer(raw);
290 return Result.isSuccess(decoded)
291 ? Result.succeed(trimmed(decoded.success.user?.name))
292 : Result.fail(decoded.failure);
294​
295/**
296 * Azure keeps its conversation as threads of comments, and every one of them is a remark
297 * somebody wrote: a reply under a thread is as much of the conversation as the line that opened
298 * it. A thread pinned to a file is a line-level review comment.
299 *
300 * Azure answers the whole thread collection in one response, with no cursor and no page to
301 * follow, so what this returns is everything the host has.
302 */
303export function decodeThreadsJson(
304 raw: string,
305): Result.Result<ReadonlyArray<PullRequestComment>, DecodeFailure> {
306 const decoded = decodeThreadPage(raw);
307 if (!Result.isSuccess(decoded)) {
308 return Result.fail(decoded.failure);
309 }
310 const comments: PullRequestComment[] = [];
311 for (const entry of decoded.success.value) {
312 const decodedThread = decodeThreadEntry(entry);
313 if (Exit.isFailure(decodedThread)) continue;
314 const thread = decodedThread.value;
315 if (thread.isDeleted === true) continue;
316 const path = trimmed(thread.threadContext?.filePath);
317 for (const comment of thread.comments ?? []) {
318 const publishedDate = trimmed(comment.publishedDate);
319 if (
320 comment.isDeleted === true ||
321 comment.commentType?.trim().toLowerCase() === "system" ||
322 (comment.content ?? "").trim().length === 0 ||
323 publishedDate === null
324 ) {
325 continue;
326 }
327 comments.push({
328 id: `${thread.id}:${comment.id ?? 0}`,
329 kind: path === null ? "issue-comment" : "review-comment",
330 author: toActor(comment.author),
331 body: comment.content ?? "",
332 createdAt: publishedDate,
333 url: null,
334 path,
335 reviewState: null,
336 });
337 }
338 }
339 return Result.succeed(
340 comments.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
341 );