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

originPullRequests.ts

411 lines13.9 KB

1/**
2 * Origin's REST shapes, read leniently: the API is in beta and int64 fields arrive as strings.
3 *
4 * @module source-control-cursor-origin/server/originPullRequests
5 */
6import * as DateTime from "effect/DateTime";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import type {
10 ChangeRequest,
11 PullRequestActor,
12 PullRequestCheck,
13 PullRequestCheckStatus,
14 PullRequestChecksState,
15 PullRequestMergeability,
16 PullRequestState,
17} from "@t3tools/contracts";
18import { SourceControlProviderKind } from "@t3tools/contracts";
19import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
20import { parseChangeRequestUrl } from "../shared/definition.ts";
21​
22const Int64 = Schema.Union([Schema.Number, Schema.NumberFromString]);
23const OptionalString = Schema.optional(Schema.NullOr(Schema.String));
24​
25const OriginActorSchema = Schema.Struct({
26 user: Schema.optional(
27 Schema.NullOr(
28 Schema.Struct({
29 id: OptionalString,
30 email: OptionalString,
31 displayName: OptionalString,
32 handle: OptionalString,
33 }),
34 ),
35 ),
36 app: Schema.optional(
37 Schema.NullOr(Schema.Struct({ id: OptionalString, displayName: OptionalString })),
38 ),
39 serviceAccount: Schema.optional(
40 Schema.NullOr(Schema.Struct({ id: OptionalString, displayName: OptionalString })),
41 ),
42});
43type OriginActor = typeof OriginActorSchema.Type;
44​
45/** Cursor profile pictures by actor id. The REST API omits them; the CLI's JSON carries them. */
46export type OriginAvatars = ReadonlyMap<string, string>;
47​
48/** The id an actor's avatar is keyed by, which the REST API and the CLI share. */
49export function originActorId(actor: OriginActor | null | undefined): string | null {
50 return (
51 actor?.user?.id?.trim() || actor?.app?.id?.trim() || actor?.serviceAccount?.id?.trim() || null
52 );
54​
55/** Every `{ id, avatarUrl }` pair anywhere in `origin pr list/view --json` output. */
56export function originAvatars(json: unknown): Map<string, string> {
57 const avatars = new Map<string, string>();
58 const visit = (value: unknown): void => {
59 if (Array.isArray(value)) {
60 for (const item of value) visit(item);
61 return;
62 }
63 if (value === null || typeof value !== "object") return;
64 const record = value as Record<string, unknown>;
65 if (typeof record.id === "string" && typeof record.avatarUrl === "string")
66 avatars.set(record.id, record.avatarUrl.trim());
67 for (const child of Object.values(record)) visit(child);
68 };
69 visit(json);
70 return avatars;
72​
73const RefSchema = Schema.Struct({ ref: Schema.String, sha: OptionalString });
74​
75export const OriginPullRequestSchema = Schema.Struct({
76 number: Int64,
77 state: OptionalString,
78 draft: Schema.optional(Schema.NullOr(Schema.Boolean)),
79 merged: Schema.optional(Schema.NullOr(Schema.Boolean)),
80 title: Schema.String,
81 body: OptionalString,
82 head: RefSchema,
83 base: RefSchema,
84 author: Schema.optional(Schema.NullOr(OriginActorSchema)),
85 createdAt: OptionalString,
86 updatedAt: OptionalString,
87 closedAt: OptionalString,
88 mergedAt: OptionalString,
89 additions: Schema.optional(Schema.NullOr(Int64)),
90 deletions: Schema.optional(Schema.NullOr(Int64)),
91 changedFiles: Schema.optional(Schema.NullOr(Int64)),
92 labels: Schema.optional(
93 Schema.NullOr(
94 Schema.Array(
95 Schema.Struct({ name: Schema.String, color: OptionalString, description: OptionalString }),
96 ),
97 ),
98 ),
99 webUrl: Schema.String,
100 stack: Schema.optional(
101 Schema.NullOr(
102 Schema.Struct({
103 parentPullRequest: Schema.optional(Schema.NullOr(Schema.Struct({ number: Int64 }))),
104 }),
105 ),
106 ),
107 version: Schema.optional(
108 Schema.NullOr(
109 Schema.Struct({
110 headSha: OptionalString,
111 baseSha: OptionalString,
112 potentialMergeCommit: Schema.optional(
113 Schema.NullOr(Schema.Struct({ state: OptionalString, baseSha: OptionalString })),
114 ),
115 }),
116 ),
117 ),
118});
119export type OriginPullRequest = typeof OriginPullRequestSchema.Type;
120​
121export const OriginPullRequestListSchema = Schema.Struct({
122 pullRequests: Schema.optional(Schema.NullOr(Schema.Array(OriginPullRequestSchema))),
123 nextPageToken: OptionalString,
124});
125​
126export const OriginRepositorySchema = Schema.Struct({
127 name: Schema.String,
128 fullName: OptionalString,
129 owner: Schema.optional(Schema.NullOr(Schema.Struct({ slug: Schema.String }))),
130 defaultBranch: OptionalString,
131 cloneUrl: OptionalString,
132 allowMergeCommit: Schema.optional(Schema.NullOr(Schema.Boolean)),
133 allowSquashMerge: Schema.optional(Schema.NullOr(Schema.Boolean)),
134});
135export type OriginRepository = typeof OriginRepositorySchema.Type;
136​
137const ThreadSchema = Schema.Struct({
138 id: Schema.String,
139 version: Schema.optional(Schema.NullOr(Schema.Struct({ headSha: OptionalString }))),
140 path: OptionalString,
141 side: OptionalString,
142 startLine: Schema.optional(Schema.NullOr(Int64)),
143 endLine: Schema.optional(Schema.NullOr(Int64)),
144 resolvedAt: OptionalString,
145});
146​
147const OriginCommentSchema = Schema.Struct({
148 id: Schema.String,
149 thread: Schema.optional(Schema.NullOr(ThreadSchema)),
150 body: OptionalString,
151 author: Schema.optional(Schema.NullOr(OriginActorSchema)),
152 createdAt: Schema.String,
153 updatedAt: OptionalString,
154});
155export type OriginComment = typeof OriginCommentSchema.Type;
156​
157export const OriginCommentListSchema = Schema.Struct({
158 comments: Schema.optional(Schema.NullOr(Schema.Array(OriginCommentSchema))),
159 nextPageToken: OptionalString,
160});
161​
162export const OriginReviewListSchema = Schema.Struct({
163 reviews: Schema.optional(
164 Schema.NullOr(
165 Schema.Array(
166 Schema.Struct({
167 id: Schema.String,
168 author: Schema.optional(Schema.NullOr(OriginActorSchema)),
169 verdict: OptionalString,
170 body: OptionalString,
171 submittedAt: Schema.String,
172 dismissal: Schema.optional(Schema.NullOr(Schema.Struct({ dismissedAt: OptionalString }))),
173 }),
174 ),
175 ),
176 ),
177 nextPageToken: OptionalString,
178});
179​
180const CommitPersonSchema = Schema.Struct({ date: OptionalString });
181​
182export const OriginCommitListSchema = Schema.Struct({
183 commits: Schema.optional(
184 Schema.NullOr(
185 Schema.Array(
186 Schema.Struct({
187 sha: Schema.String,
188 commit: Schema.Struct({
189 author: Schema.optional(Schema.NullOr(CommitPersonSchema)),
190 committer: Schema.optional(Schema.NullOr(CommitPersonSchema)),
191 message: Schema.String,
192 }),
193 stats: Schema.optional(
194 Schema.NullOr(
195 Schema.Struct({
196 additions: Schema.optional(Schema.NullOr(Int64)),
197 deletions: Schema.optional(Schema.NullOr(Int64)),
198 }),
199 ),
200 ),
201 }),
202 ),
203 ),
204 ),
205 nextPageToken: OptionalString,
206});
207​
208export const OriginFileListSchema = Schema.Struct({
209 files: Schema.optional(
210 Schema.NullOr(
211 Schema.Array(
212 Schema.Struct({
213 filename: Schema.String,
214 status: OptionalString,
215 patch: OptionalString,
216 previousFilename: OptionalString,
217 changes: Schema.optional(Schema.NullOr(Int64)),
218 }),
219 ),
220 ),
221 ),
222 nextPageToken: OptionalString,
223});
224​
225export const OriginCheckRunListSchema = Schema.Struct({
226 checkRuns: Schema.optional(
227 Schema.NullOr(
228 Schema.Array(
229 Schema.Struct({
230 name: Schema.String,
231 status: OptionalString,
232 conclusion: OptionalString,
233 detailsUrl: OptionalString,
234 output: Schema.optional(Schema.NullOr(Schema.Struct({ title: OptionalString }))),
235 }),
236 ),
237 ),
238 ),
239 nextPageToken: OptionalString,
240});
241​
242export function originActor(
243 actor: OriginActor | null | undefined,
244 avatars?: OriginAvatars,
245): PullRequestActor | null {
246 if (!actor) return null;
247 const id = originActorId(actor);
248 const avatarUrl = (id && avatars?.get(id)) || null;
249 const user = actor.user;
250 const login = user?.handle?.trim() || user?.email?.trim() || user?.displayName?.trim();
251 if (login) return { login, name: user?.displayName ?? null, avatarUrl };
252 const bot = actor.app ?? actor.serviceAccount;
253 const name = bot?.displayName?.trim() || bot?.id?.trim();
254 return name ? { login: name, name, avatarUrl, isBot: true } : null;
256​
257/**
258 * Whether the head merges cleanly into the base, from the merge commit Origin prepared for the
259 * pull request's latest version. That merge was made against the base as it stood then, so it
260 * only answers for the base's current tip when the version was built on it.
261 */
262export function preparedMergeability(pullRequest: OriginPullRequest): PullRequestMergeability {
263 // A version still being built for a new head answers for the old one.
264 if (!pullRequest.head.sha || pullRequest.version?.headSha !== pullRequest.head.sha)
265 return "unknown";
266 const state = pullRequest.version?.potentialMergeCommit?.state;
267 return state === "prepared"
268 ? "mergeable"
269 : state === "merge_conflict"
270 ? "conflicting"
271 : "unknown";
273​
274export const OriginMergeabilitySchema = Schema.Struct({
275 verdict: OptionalString,
276 headSha: OptionalString,
277 blockers: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ kind: OptionalString })))),
278});
279​
280export const OriginGitRefSchema = Schema.Struct({
281 object: Schema.optional(Schema.NullOr(Schema.Struct({ sha: OptionalString }))),
282});
283​
284export function originState(pullRequest: OriginPullRequest): PullRequestState {
285 if (pullRequest.merged || pullRequest.mergedAt || pullRequest.state === "merged") return "merged";
286 return pullRequest.state === "closed" ? "closed" : "open";
288​
289/** Stands in for a time Origin left out, so a row still sorts and renders. */
290export const UNKNOWN_TIME = "1970-01-01T00:00:00.000Z";
291​
292const timestamp = (value: string | null | undefined) => value?.trim() || null;
293​
294export function originUpdatedAt(pullRequest: OriginPullRequest): string {
295 return timestamp(pullRequest.updatedAt) ?? timestamp(pullRequest.createdAt) ?? UNKNOWN_TIME;
297​
298export function toOriginChangeRequest(pullRequest: OriginPullRequest): ChangeRequest {
299 const updatedAt = timestamp(pullRequest.updatedAt);
300 return {
301 provider: SourceControlProviderKind.make("cursor-origin"),
302 number: pullRequest.number,
303 title: pullRequest.title,
304 url: pullRequest.webUrl,
305 baseRefName: pullRequest.base.ref,
306 headRefName: pullRequest.head.ref,
307 ...(pullRequest.head.sha ? { headSha: pullRequest.head.sha } : {}),
308 state: originState(pullRequest),
309 ...(pullRequest.draft ? { isDraft: true } : {}),
310 closedAt: timestamp(pullRequest.closedAt),
311 mergedAt: timestamp(pullRequest.mergedAt),
312 updatedAt:
313 updatedAt === null ? Option.none() : Option.map(DateTime.make(updatedAt), DateTime.toUtc),
314 };
316​
317export function originCheck(
318 run: NonNullable<(typeof OriginCheckRunListSchema.Type)["checkRuns"]>[number],
319): PullRequestCheck {
320 const status: PullRequestCheckStatus =
321 run.status !== "completed"
322 ? run.status === "failing"
323 ? "failure"
324 : "pending"
325 : run.conclusion === "success"
326 ? "success"
327 : run.conclusion === "skipped"
328 ? "skipped"
329 : run.conclusion === "neutral" || run.conclusion === "stale"
330 ? "neutral"
331 : run.conclusion === "cancelled"
332 ? "cancelled"
333 : run.conclusion === "action_required"
334 ? "action-required"
335 : "failure";
336 return {
337 name: run.name,
338 status,
339 description: run.output?.title ?? null,
340 url: run.detailsUrl ?? null,
341 };
343​
344export function checksState(
345 checks: ReadonlyArray<PullRequestCheck>,
346): PullRequestChecksState | null {
347 if (checks.length === 0) return null;
348 if (
349 checks.some(
350 (check) =>
351 check.status === "failure" ||
352 check.status === "cancelled" ||
353 check.status === "action-required",
354 )
355 )
356 return "failing";
357 if (checks.some((check) => check.status === "pending")) return "pending";
358 return "passing";
360​
361/** A unified patch for the files a pull request or commit touches, from GitHub-style hunks. */
362export function originFilesPatch(
363 files: NonNullable<(typeof OriginFileListSchema.Type)["files"]>,
364): string {
365 return files
366 .map((file) => {
367 const oldPath = file.previousFilename || file.filename;
368 const added = file.status === "added";
369 const removed = file.status === "removed" || file.status === "deleted";
370 const action = file.status === "copied" ? "copy" : "rename";
371 const before = quoteGitPatchPath(`a/${oldPath}`);
372 const after = quoteGitPatchPath(`b/${file.filename}`);
373 const header = [
374 `diff --git ${before} ${after}`,
375 ...(added ? ["new file mode 100644"] : removed ? ["deleted file mode 100644"] : []),
376 ...(oldPath !== file.filename
377 ? [
378 `similarity index ${file.patch || Number(file.changes ?? 0) > 0 ? 0 : 100}%`,
379 `${action} from ${quoteGitPatchPath(oldPath)}`,
380 `${action} to ${quoteGitPatchPath(file.filename)}`,
381 ]
382 : []),
383 ];
384 if (!file.patch) return `${header.join("\n")}\n`;
385 return [
386 ...header,
387 `--- ${added ? "/dev/null" : before}`,
388 `+++ ${removed ? "/dev/null" : after}`,
389 file.patch.endsWith("\n") ? file.patch.slice(0, -1) : file.patch,
390 ]
391 .join("\n")
392 .concat("\n");
393 })
394 .join("");
396​
397/** `42` or `#42`; anything else, such as `123/fix`, is a branch. */
398function originPullNumber(reference: string): number | null {
399 const match = /^#?(\d+)$/u.exec(reference.trim());
400 const number = Number(match?.[1]);
401 return Number.isSafeInteger(number) && number > 0 ? number : null;
403​
404/** A cursor.com pull request URL names its own repository, which need not be the checkout's. */
405export function pullReference(reference: string) {
406 const trimmed = reference.trim();
407 if (!URL.canParse(trimmed)) return { repository: null, number: originPullNumber(trimmed) };
408 // Another host's pull request URL must not resolve to the same number here.
409 const link = parseChangeRequestUrl(new URL(trimmed));
410 return { repository: link?.repository ?? null, number: link?.number ?? null };