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