Open History to see the last commit
1import {
2 type PullRequestActor,
3 type PullRequestCheck,
4 type PullRequestChecksState,
5 type PullRequestComment,
6 type PullRequestReviewCommentDraft,
7 type PullRequestReviewThread,
8 type PullRequestState,
9} from "@t3tools/contracts";
10import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
11import type {
12 ProviderChangeRequest,
13 ProviderChangeRequestActivity,
14 ProviderChangeRequestStack,
15} from "@t3tools/source-control-core/server/PullRequestProvider";
16import * as DateTime from "effect/DateTime";
17import * as Schema from "effect/Schema";
18
19import { withoutOwnerMark } from "../shared/definition.ts";
20
21/** Source sends times as epoch milliseconds. */
22const EpochMillis = Schema.Finite;
23const Login = Schema.String;
24
25export const SourcePull = Schema.Struct({
26 number: Schema.Int,
27 title: Schema.String,
28 state: Schema.Literals(["open", "closed", "merged"]),
29 draft: Schema.Boolean,
30 author: Schema.NullOr(Login),
31 labels: Schema.optional(Schema.Array(Schema.String)),
32 head: Schema.String,
33 createdAt: EpochMillis,
34 visibility: Schema.optional(Schema.String),
35});
36export type SourcePull = typeof SourcePull.Type;
37
38export const SourcePulls = Schema.Struct({
39 items: Schema.Array(SourcePull),
40 next: Schema.NullOr(Schema.String),
41});
42
43const AutoMerge = Schema.Struct({ method: Schema.optional(Schema.String) });
44
45export const SourcePullDetail = Schema.Struct({
46 ...SourcePull.fields,
47 body: Schema.NullOr(Schema.String),
48 base: Schema.String,
49 headRepo: Schema.NullOr(Schema.String),
50 headSha: Schema.NullOr(Schema.String),
51 baseSha: Schema.NullOr(Schema.String),
52 mergeCommitSha: Schema.NullOr(Schema.String),
53 mergedAt: Schema.NullOr(EpochMillis),
54 mergedBy: Schema.NullOr(Login),
55 mergeable: Schema.NullOr(Schema.Boolean),
56 changedFiles: Schema.NullOr(Schema.Int),
57 changedLines: Schema.optional(Schema.NullOr(Schema.Unknown)),
58 reviewRequests: Schema.optional(Schema.Array(Login)),
59 autoMerge: Schema.optional(Schema.NullOr(AutoMerge)),
60 locked: Schema.optional(Schema.Boolean),
61 htmlUrl: Schema.optional(Schema.String),
62});
63export type SourcePullDetail = typeof SourcePullDetail.Type;
64
65/** `GET /pulls/{n}/checks`: the required checks of the base branch and whether it may merge. */
66export const SourceMergeChecks = Schema.Struct({
67 headSha: Schema.optional(Schema.NullOr(Schema.String)),
68 checks: Schema.Array(
69 Schema.Struct({
70 name: Schema.String,
71 state: Schema.String,
72 reason: Schema.optional(Schema.NullOr(Schema.String)),
73 }),
74 ),
75 upToDate: Schema.optional(Schema.NullOr(Schema.Boolean)),
76 mayMerge: Schema.Boolean,
77 refusal: Schema.optional(Schema.NullOr(Schema.String)),
78});
79export type SourceMergeChecks = typeof SourceMergeChecks.Type;
80
81/** `GET /check-runs?sha=`: Source CI jobs (with a job id) and checks synced from GitHub (url). */
82export const SourceCheckRun = Schema.Struct({
83 jobId: Schema.optional(Schema.String),
84 name: Schema.String,
85 view: Schema.optional(Schema.String),
86 status: Schema.String,
87 conclusion: Schema.NullOr(Schema.String),
88 startedAt: Schema.optional(Schema.NullOr(EpochMillis)),
89 completedAt: Schema.optional(Schema.NullOr(EpochMillis)),
90 summary: Schema.optional(Schema.NullOr(Schema.String)),
91 url: Schema.optional(Schema.NullOr(Schema.String)),
92 source: Schema.optional(Schema.NullOr(Schema.String)),
93});
94export type SourceCheckRun = typeof SourceCheckRun.Type;
95export const SourceCheckRuns = Schema.Array(SourceCheckRun);
96
97export const SourceCiRuns = Schema.Struct({
98 items: Schema.Array(
99 Schema.Struct({
100 id: Schema.String,
101 workflow: Schema.String,
102 headSha: Schema.String,
103 createdAt: EpochMillis,
104 htmlUrl: Schema.String,
105 }),
106 ),
107 next: Schema.NullOr(Schema.String),
108});
109export type SourceCiRun = (typeof SourceCiRuns.Type)["items"][number];
110
111export const SourceCiRunDetail = Schema.Struct({
112 id: Schema.String,
113 jobs: Schema.Array(
114 Schema.Struct({ key: Schema.String, name: Schema.String, jobId: Schema.NullOr(Schema.String) }),
115 ),
116});
117
118/** The job of a run a check came from, which its log and re-run are addressed by. */
119export interface SourceCiJob {
120 readonly runId: string;
121 readonly workflow: string;
122 readonly key: string;
123 readonly runUrl: string;
124}
125
126const TimelineEntry = Schema.Struct({
127 id: Schema.Int,
128 comment: Schema.NullOr(Schema.String),
129 author: Schema.NullOr(Login),
130 at: EpochMillis,
131 updatedAt: Schema.optional(Schema.NullOr(EpochMillis)),
132 moderation: Schema.optional(Schema.String),
133 review: Schema.optional(Schema.NullOr(Schema.String)),
134 path: Schema.optional(Schema.NullOr(Schema.String)),
135 replyTo: Schema.optional(Schema.NullOr(Schema.Int)),
136 reviewId: Schema.optional(Schema.NullOr(Schema.Int)),
137});
138type TimelineEntry = typeof TimelineEntry.Type;
139
140export const SourceTimeline = Schema.Struct({
141 // Events such as `head_updated` sit between the comments and carry no id.
142 timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])),
143 next: Schema.NullOr(Schema.String),
144});
145
146const ThreadComment = Schema.Struct({
147 id: Schema.Int,
148 comment: Schema.NullOr(Schema.String),
149 author: Schema.NullOr(Login),
150 at: EpochMillis,
151 updatedAt: Schema.optional(Schema.NullOr(EpochMillis)),
152});
153
154export const SourceThreads = Schema.Array(
155 Schema.Struct({
156 id: Schema.Int,
157 htmlUrl: Schema.optional(Schema.NullOr(Schema.String)),
158 path: Schema.String,
159 side: Schema.Literals(["old", "new"]),
160 line: Schema.NullOr(Schema.Int),
161 outdated: Schema.Boolean,
162 resolved: Schema.Boolean,
163 comments: Schema.Array(ThreadComment),
164 }),
165);
166
167const CommitDetails = {
168 baseSha: Schema.NullOr(Schema.String),
169 headSha: Schema.NullOr(Schema.String),
170 mergeBaseSha: Schema.NullOr(Schema.String),
171 available: Schema.Boolean,
172 unavailable: Schema.optional(Schema.NullOr(Schema.Unknown)),
173 tooLarge: Schema.optional(Schema.NullOr(Schema.Unknown)),
174};
175
176export const SourceCommits = Schema.Struct({
177 ...CommitDetails,
178 commitsTruncated: Schema.NullOr(Schema.Boolean),
179 commits: Schema.NullOr(
180 Schema.Array(
181 Schema.Struct({
182 sha: Schema.String,
183 title: Schema.String,
184 author: Schema.Struct({ name: Schema.String, timestamp: Schema.Finite }),
185 }),
186 ),
187 ),
188});
189
190export const SourceFiles = Schema.Struct({
191 ...CommitDetails,
192 truncated: Schema.NullOr(Schema.Boolean),
193 files: Schema.NullOr(
194 Schema.Array(
195 Schema.Struct({
196 path: Schema.String,
197 oldPath: Schema.optional(Schema.NullOr(Schema.String)),
198 status: Schema.String,
199 binary: Schema.optional(Schema.Boolean),
200 additions: Schema.optional(Schema.Int),
201 deletions: Schema.optional(Schema.Int),
202 }),
203 ),
204 ),
205});
206export type SourceFiles = typeof SourceFiles.Type;
207
208export const SourceDiff = Schema.Struct({
209 ...CommitDetails,
210 truncated: Schema.NullOr(Schema.Boolean),
211 patch: Schema.NullOr(Schema.String),
212});
213
214export const SourceContents = Schema.Struct({
215 binary: Schema.Boolean,
216 truncated: Schema.Boolean,
217 content: Schema.NullOr(Schema.String),
218});
219
220export const SourceStack = Schema.Struct({
221 members: Schema.Array(
222 Schema.Struct({
223 number: Schema.Int,
224 title: Schema.String,
225 headRef: Schema.String,
226 baseRef: Schema.String,
227 draft: Schema.Boolean,
228 }),
229 ),
230});
231export type SourceStack = typeof SourceStack.Type;
232
233export const SourceLabels = Schema.Array(
234 Schema.Struct({
235 name: Schema.String,
236 color: Schema.NullOr(Schema.String),
237 description: Schema.optional(Schema.NullOr(Schema.String)),
238 }),
239);
240
241export const SourceUser = Schema.Struct({ username: Schema.String });
242
243export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis));
244
245export const pullUrl = (host: string, repository: string, number: number) =>
246 `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`;
247
248/**
249 * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private
250 * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede.
251 */
252export const headBranchName = (head: string) =>
253 head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, "");
254
255/** Absent when Source names no visibility, so a reader tells unknown from public. */
256const visibilityOf = (pull: Pick<SourcePull, "visibility">) =>
257 pull.visibility === "private" || pull.visibility === "public"
258 ? { visibility: pull.visibility }
259 : {};
260
261export function toActor(login: string | null, host: string): PullRequestActor | null {
262 if (login === null || login.trim() === "") return null;
263 return {
264 login,
265 name: null,
266 avatarUrl: `https://${host}/avatars/${encodeURIComponent(login)}`,
267 ...(login.endsWith("[bot]") ? { isBot: true } : {}),
268 };
269}
270
271const toLabels = (labels: ReadonlyArray<string> | undefined) =>
272 (labels ?? []).map((name) => ({ name, color: null }));
273
274interface RepositoryOnHost {
275 readonly repository: string;
276 readonly host: string;
277}
278
279/** List rows name no base; the caller fills it from the detail read or the stack. */
280export function toChangeRequest(
281 pull: SourcePull & {
282 readonly base?: string | undefined;
283 readonly reviewRequests?: ReadonlyArray<string> | undefined;
284 },
285 target: RepositoryOnHost,
286): ProviderChangeRequest {
287 const createdAt = iso(pull.createdAt);
288 return {
289 number: pull.number,
290 title: pull.title,
291 url: pullUrl(target.host, target.repository, pull.number),
292 author: toActor(pull.author, target.host),
293 headBranch: headBranchName(pull.head),
294 baseBranch: pull.base ?? "",
295 state: pull.state,
296 isDraft: pull.draft,
297 ...visibilityOf(pull),
298 mergeability: "unknown",
299 additions: 0,
300 deletions: 0,
301 createdAt,
302 // Source reports no update time; creation is the latest it can vouch for.
303 updatedAt: createdAt,
304 reviewRequestLogins: pull.reviewRequests ?? [],
305 labels: toLabels(pull.labels),
306 };
307}
308
309const COMPLETED_STATUS: Readonly<Record<string, PullRequestCheck["status"]>> = {
310 success: "success",
311 neutral: "neutral",
312 skipped: "skipped",
313 cancelled: "cancelled",
314 action_required: "action-required",
315 stale: "neutral",
316};
317
318function checkStatus(run: SourceCheckRun): PullRequestCheck["status"] {
319 if (run.status !== "completed") return run.status === "waiting" ? "action-required" : "pending";
320 return COMPLETED_STATUS[run.conclusion ?? ""] ?? "failure";
321}
322
323/** A Source CI job's page: its run, scrolled to the job. Also how its log is found again. */
324const ciJobUrl = (job: SourceCiJob) => `${job.runUrl}?${new URLSearchParams({ job: job.key })}`;
325
326/** The run and job a Source CI check's URL names. */
327export function parseCiJobUrl(
328 url: string | null,
329 host: string,
330): { readonly runId: string; readonly job: string } | null {
331 const parsed = url === null ? null : URL.parse(url);
332 if (parsed === null || parsed.hostname !== host) return null;
333 const runId = /^\/@[^/]+\/[^/]+\/ci\/([0-9a-f-]{8,})\/?$/iu.exec(parsed.pathname)?.[1];
334 const job = parsed.searchParams.get("job");
335 return runId === undefined || job === null || job === "" ? null : { runId, job };
336}
337
338/**
339 * Source lists every run of a commit's checks, so a re-run arrives beside the run it replaced.
340 * The newest run of a name is the check's state; an older failure is history.
341 */
342export function toChecks(input: {
343 readonly runs: ReadonlyArray<SourceCheckRun>;
344 readonly jobs: ReadonlyMap<string, SourceCiJob>;
345 readonly required: ReadonlySet<string>;
346}): ReadonlyArray<PullRequestCheck> {
347 const newest = new Map<string, { readonly run: SourceCheckRun; readonly at: number }>();
348 for (const run of input.runs) {
349 if (run.view === "superseded") continue;
350 const job = run.jobId ? input.jobs.get(run.jobId) : undefined;
351 const name = job === undefined ? run.name : `${job.workflow}/${run.name}`;
352 const at = run.startedAt ?? run.completedAt ?? 0;
353 const held = newest.get(name);
354 if (held === undefined || at > held.at) newest.set(name, { run, at });
355 }
356 return sortChecks(
357 [...newest.entries()].map(([name, { run }]) => {
358 const job = run.jobId ? input.jobs.get(run.jobId) : undefined;
359 return {
360 name,
361 status: checkStatus(run),
362 description: run.summary?.split("\n", 1)[0]?.replace(/^#+\s*/u, "") || null,
363 url: job === undefined ? (run.url ?? null) : ciJobUrl(job),
364 ...(input.required.has(name) ? { required: true } : {}),
365 };
366 }),
367 );
368}
369
370export function checksStateOf(
371 checks: ReadonlyArray<PullRequestCheck>,
372): PullRequestChecksState | null {
373 const statuses = new Set(checks.map((check) => check.status));
374 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
375 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
376 return statuses.has("success") ? "passing" : null;
377}
378
379const REVIEW_STATES: Readonly<Record<string, string>> = {
380 approved: "approved",
381 changes_requested: "changes_requested",
382 commented: "commented",
383};
384
385const visible = (entry: { readonly moderation?: string | undefined }) =>
386 entry.moderation === undefined || entry.moderation === "visible";
387
388export function toActivity(input: {
389 readonly timeline: typeof SourceTimeline.Type;
390 readonly threads: typeof SourceThreads.Type;
391 readonly commits: typeof SourceCommits.Type;
392 readonly host: string;
393 readonly repository: string;
394 readonly number: number;
395}): ProviderChangeRequestActivity {
396 const { host } = input;
397 const page = pullUrl(host, input.repository, input.number);
398 const entries = input.timeline.timeline.filter(
399 (entry): entry is TimelineEntry => "id" in entry && visible(entry),
400 );
401 const comments: Array<PullRequestComment> = entries.map((entry: TimelineEntry) => ({
402 id: String(entry.id),
403 kind:
404 entry.review != null
405 ? ("review" as const)
406 : entry.path != null
407 ? ("review-comment" as const)
408 : ("issue-comment" as const),
409 author: toActor(entry.author, host),
410 body: entry.comment ?? "",
411 createdAt: iso(entry.at),
412 ...(entry.updatedAt != null && entry.updatedAt > entry.at
413 ? { editedAt: iso(entry.updatedAt) }
414 : {}),
415 url: `${page}#comment-${entry.id}`,
416 path: entry.path ?? null,
417 reviewState: entry.review == null ? null : (REVIEW_STATES[entry.review] ?? entry.review),
418 }));
419 const reviewThreads = input.threads.flatMap((thread): ReadonlyArray<PullRequestReviewThread> => {
420 if (thread.path.trim() === "" || thread.comments.length === 0) return [];
421 return [
422 {
423 id: String(thread.id),
424 path: thread.path,
425 line: thread.line !== null && thread.line > 0 ? thread.line : null,
426 side: thread.side === "old" ? "left" : "right",
427 isResolved: thread.resolved,
428 isOutdated: thread.outdated,
429 comments: thread.comments.map((comment) => ({
430 id: String(comment.id),
431 author: toActor(comment.author, host),
432 body: comment.comment ?? "",
433 createdAt: iso(comment.at),
434 ...(comment.updatedAt != null && comment.updatedAt > comment.at
435 ? { editedAt: iso(comment.updatedAt) }
436 : {}),
437 url: `${page}#comment-${comment.id}`,
438 })),
439 },
440 ];
441 });
442 return {
443 comments,
444 commentCount: comments.length,
445 commentsTruncated: input.timeline.next !== null,
446 reviewThreads,
447 commits: (input.commits.commits ?? []).map((commit) => ({
448 oid: commit.sha,
449 messageHeadline: commit.title,
450 committedDate: iso(commit.author.timestamp * 1_000),
451 })),
452 };
453}
454
455export function toStack(
456 stack: SourceStack,
457 target: RepositoryOnHost,
458 states: ReadonlyMap<number, PullRequestState>,
459): ProviderChangeRequestStack | null {
460 const bottom = stack.members[0];
461 if (bottom === undefined || stack.members.length < 2) return null;
462 return {
463 id: `${target.repository}#${bottom.number}`,
464 number: bottom.number,
465 url: pullUrl(target.host, target.repository, bottom.number),
466 base: bottom.baseRef,
467 layers: stack.members.map((member) => ({
468 number: member.number,
469 title: member.title,
470 headBranch: headBranchName(member.headRef),
471 state: states.get(member.number) ?? "open",
472 isDraft: member.draft,
473 })),
474 };
475}
476
477/** The line comment a review draft names, as Source's review takes it. */
478export function toReviewComment(draft: PullRequestReviewCommentDraft, commitId: string) {
479 const line = (position: PullRequestReviewCommentDraft["position"]) =>
480 position.kind === "added"
481 ? { side: "new" as const, line: position.newLine }
482 : position.kind === "deleted"
483 ? { side: "old" as const, line: position.oldLine }
484 : position.side === "left"
485 ? { side: "old" as const, line: position.oldLine }
486 : { side: "new" as const, line: position.newLine };
487 const end = line(draft.position);
488 const start = draft.startPosition === undefined ? undefined : line(draft.startPosition);
489 return {
490 path: draft.path,
491 side: end.side,
492 line: end.line,
493 ...(start !== undefined && start.side === end.side && start.line < end.line
494 ? { startLine: start.line }
495 : {}),
496 commitId,
497 body: draft.body,
498 };
499}
500
501/** The sections of a unified patch, by the path each one changes. */
502export function patchSections(patch: string): ReadonlyMap<string, string> {
503 const sections = new Map<string, string>();
504 const starts = [...patch.matchAll(/^diff --git a\/(.*) b\/(.*)$/gmu)];
505 for (const [index, match] of starts.entries()) {
506 const end = starts[index + 1]?.index ?? patch.length;
507 const section = patch.slice(match.index, end);
508 sections.set(match[2]!, section.endsWith("\n") ? section : `${section}\n`);
509 }
510 return sections;
511}