Open History to see the last commit
1import type {
2 PullRequestComment,
3 PullRequestDetail,
4 PullRequestReviewThread,
5} from "@t3tools/contracts";
6
7type EditingSubject = Pick<
8 PullRequestDetail,
9 "author" | "capabilities" | "viewer" | "viewerPermissions"
10>;
11
12function sameLogin(one: string | null | undefined, other: string | null | undefined): boolean {
13 if (one == null || other == null) return false;
14 return one.trim().toLowerCase() === other.trim().toLowerCase();
15}
16
17export function canEditPullRequestChangeRequest(detail: EditingSubject): boolean {
18 if (detail.capabilities.edit?.changeRequest !== true) return false;
19 if (detail.viewerPermissions.editChangeRequest !== undefined) {
20 return detail.viewerPermissions.editChangeRequest;
21 }
22 return (
23 sameLogin(detail.viewer, detail.author?.login) ||
24 detail.viewerPermissions.actions.includes("merge")
25 );
26}
27
28export function canEditPullRequestMaintainerEdits(
29 detail: Pick<
30 PullRequestDetail,
31 "state" | "capabilities" | "viewerPermissions" | "maintainerCanModify"
32 >,
33): boolean {
34 return (
35 detail.state === "open" &&
36 detail.capabilities.edit?.maintainerEdits === true &&
37 detail.viewerPermissions.maintainerEdits === true &&
38 detail.maintainerCanModify !== undefined
39 );
40}
41
42export interface MaintainerEditsChoice {
43 readonly key: string;
44 readonly observedAt: number | undefined;
45 readonly value: boolean;
46}
47
48/**
49 * A saved choice ends at the first host reading delivered after the save. Readers refresh once it
50 * succeeds, which drops reads still in flight, so that reading started after the write.
51 */
52export function maintainerEditsChoiceInForce(
53 choice: MaintainerEditsChoice | null,
54 key: string,
55 observedAt: number | undefined,
56 saving: boolean,
57): MaintainerEditsChoice | null {
58 if (choice === null || choice.key !== key) return null;
59 if (saving) return choice.observedAt === observedAt ? choice : { ...choice, observedAt };
60 return observedAt !== undefined && choice.observedAt === observedAt ? choice : null;
61}
62
63/** Hosts do not support rewriting review summaries through comment mutations. */
64export function canEditPullRequestComment(
65 detail: EditingSubject,
66 comment: Pick<PullRequestComment, "author" | "canEdit" | "kind">,
67): boolean {
68 if (detail.capabilities.edit?.comment !== true) return false;
69 if (comment.kind !== "issue-comment" && comment.kind !== "review-comment") return false;
70 if (comment.canEdit !== undefined) return comment.canEdit;
71 return sameLogin(detail.viewer, comment.author?.login);
72}
73
74export function canResolvePullRequestThread(
75 detail: Pick<PullRequestDetail, "viewerPermissions">,
76 thread: Pick<PullRequestReviewThread, "canResolve">,
77): boolean {
78 return detail.viewerPermissions.resolve && thread.canResolve !== false;
79}