Open History to see the last commit
1import { toIsoUtc } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Schema from "effect/Schema";
3import type {
4 PullRequestActor,
5 PullRequestCheck,
6 PullRequestCheckStatus,
7 PullRequestComment,
8 PullRequestCommit,
9 PullRequestReaction,
10 PullRequestReactionContent,
11 PullRequestReviewThread,
12} from "@t3tools/contracts";
13import type { ProviderChangeRequest } from "@t3tools/source-control-core/server/PullRequestProvider";
14import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
15import { forgejoHeadBranch } from "./forgejoPullRequests.ts";
16
17export const ForgejoUser = Schema.Struct({
18 login: Schema.String,
19 full_name: Schema.optional(Schema.NullOr(Schema.String)),
20 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
21});
22export const ForgejoLabel = Schema.Struct({
23 id: Schema.Int,
24 name: Schema.String,
25 color: Schema.optional(Schema.NullOr(Schema.String)),
26 description: Schema.optional(Schema.NullOr(Schema.String)),
27});
28export const ForgejoRepository = Schema.Struct({
29 full_name: Schema.String,
30 permissions: Schema.optional(Schema.Struct({ push: Schema.Boolean, admin: Schema.Boolean })),
31 archived: Schema.optional(Schema.Boolean),
32 allow_merge_commits: Schema.optional(Schema.Boolean),
33 allow_squash_merge: Schema.optional(Schema.Boolean),
34 allow_rebase: Schema.optional(Schema.Boolean),
35 allow_fast_forward_only_merge: Schema.optional(Schema.Boolean),
36 allow_rebase_update: Schema.optional(Schema.Boolean),
37 default_delete_branch_after_merge: Schema.optional(Schema.Boolean),
38});
39const Branch = Schema.Struct({
40 ref: Schema.String,
41 label: Schema.optional(Schema.String),
42 sha: Schema.String,
43 repo: Schema.NullOr(ForgejoRepository),
44});
45export const ForgejoPullRequest = Schema.Struct({
46 number: Schema.Int,
47 title: Schema.String,
48 body: Schema.NullOr(Schema.String),
49 html_url: Schema.String,
50 user: Schema.NullOr(ForgejoUser),
51 state: Schema.String,
52 draft: Schema.optional(Schema.Boolean),
53 flow: Schema.optional(Schema.Int),
54 merged: Schema.Boolean,
55 mergeable: Schema.optional(Schema.Boolean),
56 is_locked: Schema.optional(Schema.Boolean),
57 head: Branch,
58 base: Branch,
59 merge_base: Schema.optional(Schema.String),
60 created_at: Schema.String,
61 updated_at: Schema.String,
62 closed_at: Schema.NullOr(Schema.String),
63 merged_at: Schema.NullOr(Schema.String),
64 merge_commit_sha: Schema.optional(Schema.NullOr(Schema.String)),
65 merged_by: Schema.optional(Schema.NullOr(ForgejoUser)),
66 additions: Schema.optional(Schema.NullOr(Schema.Int)),
67 deletions: Schema.optional(Schema.NullOr(Schema.Int)),
68 changed_files: Schema.optional(Schema.NullOr(Schema.Int)),
69 comments: Schema.optional(Schema.Int),
70 labels: Schema.NullOr(Schema.Array(ForgejoLabel)),
71 requested_reviewers: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
72});
73export const ForgejoTimelineEvent = Schema.Struct({ type: Schema.String });
74
75/**
76 * Forgejo's pull request reply never says whether auto-merge is scheduled; only the timeline
77 * records each schedule and cancellation, so the latest of the two decides.
78 */
79export function forgejoAutoMergeScheduled(
80 events: ReadonlyArray<typeof ForgejoTimelineEvent.Type>,
81): boolean {
82 for (let index = events.length - 1; index >= 0; index--) {
83 const type = events[index]?.type;
84 if (type === "pull_scheduled_merge") return true;
85 if (type === "pull_cancel_scheduled_merge") return false;
86 }
87 return false;
88}
89export const ForgejoComment = Schema.Struct({
90 id: Schema.Int,
91 body: Schema.String,
92 user: Schema.NullOr(ForgejoUser),
93 created_at: Schema.String,
94 updated_at: Schema.optional(Schema.NullOr(Schema.String)),
95 html_url: Schema.optional(Schema.String),
96});
97export const ForgejoReview = Schema.Struct({
98 id: Schema.Int,
99 body: Schema.String,
100 user: Schema.NullOr(ForgejoUser),
101 state: Schema.String,
102 dismissed: Schema.optional(Schema.Boolean),
103 submitted_at: Schema.String,
104 html_url: Schema.optional(Schema.String),
105 comments_count: Schema.Int,
106});
107export const ForgejoReviewComment = Schema.Struct({
108 ...ForgejoComment.fields,
109 path: Schema.String,
110 position: Schema.Int,
111 original_position: Schema.Int,
112 commit_id: Schema.String,
113 original_commit_id: Schema.String,
114 resolver: Schema.NullOr(ForgejoUser),
115});
116export const ForgejoCommit = Schema.Struct({
117 sha: Schema.String,
118 author: Schema.NullOr(ForgejoUser),
119 commit: Schema.Struct({
120 message: Schema.String,
121 committer: Schema.Struct({ date: Schema.String }),
122 }),
123 parents: Schema.Array(Schema.Struct({ sha: Schema.String })),
124 stats: Schema.optional(
125 Schema.NullOr(Schema.Struct({ additions: Schema.Int, deletions: Schema.Int })),
126 ),
127});
128export const ForgejoStatus = Schema.Struct({
129 id: Schema.optional(Schema.Int),
130 context: Schema.String,
131 status: Schema.String,
132 description: Schema.NullOr(Schema.String),
133 target_url: Schema.NullOr(Schema.String),
134 updated_at: Schema.String,
135});
136export const ForgejoReaction = Schema.Struct({
137 content: Schema.String,
138 user: Schema.NullOr(ForgejoUser),
139});
140
141export function forgejoActor(
142 user: typeof ForgejoUser.Type | null | undefined,
143): PullRequestActor | null {
144 return user?.login
145 ? { login: user.login, name: user.full_name || null, avatarUrl: user.avatar_url || null }
146 : null;
147}
148
149export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) {
150 return {
151 number: pr.number,
152 title: pr.title,
153 url: pr.html_url,
154 author: forgejoActor(pr.user),
155 headBranch: forgejoHeadBranch(pr),
156 baseBranch: pr.base.ref,
157 headRepositoryNameWithOwner: pr.head.repo?.full_name ?? null,
158 state: pr.merged ? "merged" : pr.state === "closed" ? "closed" : "open",
159 isDraft: pr.draft ?? /^(?:\[WIP\]|WIP:)/i.test(pr.title),
160 // A false value also covers drafts and unfinished or failed conflict checks.
161 mergeability: pr.mergeable === true ? "mergeable" : "unknown",
162 additions: pr.additions ?? 0,
163 deletions: pr.deletions ?? 0,
164 createdAt: toIsoUtc(pr.created_at),
165 updatedAt: toIsoUtc(pr.updated_at),
166 closedAt: pr.closed_at === null ? null : toIsoUtc(pr.closed_at),
167 mergedAt: pr.merged_at === null ? null : toIsoUtc(pr.merged_at),
168 reviewRequestLogins: (pr.requested_reviewers ?? []).map((user) => user.login),
169 labels: (pr.labels ?? []).map((label) => ({
170 name: label.name,
171 color: label.color ?? null,
172 description: label.description || null,
173 })),
174 } satisfies ProviderChangeRequest;
175}
176
177export function forgejoComment(comment: typeof ForgejoComment.Type): PullRequestComment {
178 const createdAt = toIsoUtc(comment.created_at);
179 const editedAt = comment.updated_at == null ? undefined : toIsoUtc(comment.updated_at);
180 return {
181 id: String(comment.id),
182 kind: "issue-comment",
183 author: forgejoActor(comment.user),
184 body: comment.body,
185 createdAt,
186 ...(editedAt === undefined || editedAt === createdAt ? {} : { editedAt }),
187 url: comment.html_url || null,
188 path: null,
189 reviewState: null,
190 };
191}
192
193export function forgejoReview(review: typeof ForgejoReview.Type): PullRequestComment {
194 return {
195 id: `review:${review.id}`,
196 kind: "review",
197 author: forgejoActor(review.user),
198 body: review.body,
199 createdAt: toIsoUtc(review.submitted_at),
200 url: review.html_url || null,
201 path: null,
202 reviewState:
203 review.dismissed === true
204 ? "DISMISSED"
205 : review.state === "REQUEST_CHANGES"
206 ? "CHANGES_REQUESTED"
207 : review.state === "COMMENT"
208 ? "COMMENTED"
209 : review.state,
210 };
211}
212
213export function forgejoReviewThread(
214 comment: typeof ForgejoReviewComment.Type,
215): PullRequestReviewThread {
216 const oldSide = comment.position === 0 && comment.original_position > 0;
217 const line = oldSide ? comment.original_position : comment.position;
218 return {
219 id: String(comment.id),
220 path: comment.path,
221 line: line > 0 ? line : null,
222 side: oldSide ? "left" : "right",
223 isResolved: comment.resolver !== null,
224 isOutdated: false,
225 comments: [forgejoComment(comment)],
226 };
227}
228
229export function forgejoCommit(commit: typeof ForgejoCommit.Type): PullRequestCommit {
230 const author = forgejoActor(commit.author);
231 return {
232 oid: commit.sha,
233 messageHeadline: commit.commit.message.split("\n")[0] ?? "",
234 committedDate: toIsoUtc(commit.commit.committer.date),
235 authors: author ? [author] : [],
236 ...(commit.stats
237 ? { additions: commit.stats.additions, deletions: commit.stats.deletions }
238 : {}),
239 };
240}
241
242// Forgejo Actions reports a job that did not run as `skipped` and a cancelled one as `failure`,
243// and `warning` is finished without being a pass. Only `pending` and states we do not know may
244// hold a watch open.
245function forgejoCheckStatus(state: string): PullRequestCheckStatus {
246 switch (state) {
247 case "success":
248 return "success";
249 case "failure":
250 case "error":
251 return "failure";
252 case "skipped":
253 return "skipped";
254 case "warning":
255 return "neutral";
256 default:
257 return "pending";
258 }
259}
260
261export function forgejoChecks(
262 statuses: ReadonlyArray<typeof ForgejoStatus.Type>,
263 pullRequestUrl: string,
264): ReadonlyArray<PullRequestCheck> {
265 return dedupeChecks(
266 statuses.map((status) => ({
267 workflowName: null,
268 at: status.updated_at,
269 ...(status.id === undefined ? {} : { sequence: status.id }),
270 check: {
271 name: status.context || "check",
272 description: status.description || null,
273 url: status.target_url
274 ? (URL.parse(status.target_url, pullRequestUrl)?.href ?? null)
275 : null,
276 status: forgejoCheckStatus(status.status),
277 },
278 })),
279 );
280}
281
282export const FORGEJO_REACTIONS: Record<PullRequestReactionContent, string> = {
283 "thumbs-up": "+1",
284 "thumbs-down": "-1",
285 laugh: "laugh",
286 hooray: "hooray",
287 confused: "confused",
288 heart: "heart",
289 rocket: "rocket",
290 eyes: "eyes",
291};
292export function forgejoReactions(
293 reactions: ReadonlyArray<typeof ForgejoReaction.Type>,
294 viewer: string,
295): ReadonlyArray<PullRequestReaction> {
296 return Object.entries(FORGEJO_REACTIONS).flatMap(([content, emoji]) => {
297 const matching = reactions.filter((reaction) => reaction.content === emoji);
298 return matching.length === 0
299 ? []
300 : [
301 {
302 content: content as PullRequestReactionContent,
303 count: matching.length,
304 actors: matching.flatMap((reaction) =>
305 reaction.user?.login && reaction.user.login !== viewer ? [reaction.user.login] : [],
306 ),
307 viewerHasReacted: matching.some((reaction) => reaction.user?.login === viewer),
308 },
309 ];
310 });
311}