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